/* GCCReady — Chrome (Navbar, Footer, FAB, page shell) */

function Navbar() {
  const [open, setOpen] = React.useState(false);
  const [scrolled, setScrolled] = React.useState(false);
  const [megaOpen, setMegaOpen] = React.useState(null);
  const hash = useHash();

  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 10);
    onScroll();
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const nav = [
    { label: 'Programs', hash: '#/programs', mega: 'programs' },
    { label: 'Certifications', hash: '#/certifications', mega: 'certs' },
    { label: 'Skills & Tools', hash: '#/skill-readiness', mega: 'skills' },
    { label: 'GCCs & Roles', hash: '#/gcc-employers', mega: 'gccs' },
    { label: 'For', hash: '#/for-students', mega: 'for' },
    { label: 'Library', hash: '#/resources/library' },
  ];

  const megas = {
    programs: {
      title: 'Programs',
      cols: [
        { head: 'Core Offerings', items: [
          ['Skill Badge', '#/skill-badge', 'qr'],
          ['Crash Course — GCC Fundamentals', '#/programs#crash', 'zap'],
          ['GCC Sprint (Cohort)', '#/sprint', 'rocket'],
          ['Domain Deep Dives', '#/domains', 'layers'],
        ]},
        { head: 'Certifications', items: [
          ['US CMA', '#/certifications/us-cma', 'calculator'],
          ['US CPA', '#/certifications/us-cpa', 'file-check'],
          ['CFA', '#/certifications/cfa', 'chart-pie'],
          ['All certifications →', '#/certifications', 'arrow-right'],
        ]},
      ],
    },
    certs: {
      title: 'Certifications',
      cols: [
        { head: 'Live now', items: [
          ['US CPA', '#/certifications/us-cpa', 'file-check'],
          ['US CMA', '#/certifications/us-cma', 'calculator'],
          ['EA (Enrolled Agent)', '#/certifications/ea', 'file-text'],
          ['CFA', '#/certifications/cfa', 'chart-pie'],
        ]},
        { head: 'Upcoming + add-ons', items: [
          ['ACCA (Upcoming)', '#/certifications/acca', 'globe'],
          ['Power BI / PL-300', '#/certifications/power-bi', 'bar-chart'],
          ['ESG Certificate', '#/certifications/esg', 'leaf'],
          ['Compare all', '#/compare-certifications', 'layers'],
        ]},
        { head: 'Why GCCReady', items: [
          ['Skill Badge', '#/skill-badge', 'qr'],
          ['Mentor network', '#/mentors', 'award'],
          ['ROI calculator', '#/tools', 'trending-up'],
        ]},
      ],
    },
    skills: {
      title: 'Skills & Tools',
      cols: [
        { head: 'Skill Readiness', items: [
          ['All 30 programmes', '#/skill-readiness', 'zap'],
          ['India accounting (Tally / Zoho)', '#/skill-readiness#india-accounting', 'landmark'],
          ['US accounting (QuickBooks / Xero)', '#/skill-readiness#us-accounting', 'globe'],
          ['Enterprise ERP (SAP / Oracle)', '#/skill-readiness#enterprise-erp', 'building-2'],
          ['Analytics (Power BI / Python)', '#/skill-readiness#analytics', 'bar-chart'],
        ]},
        { head: 'Free tools', items: [
          ['All 13 calculators', '#/tools', 'sparkles'],
          ['CPA ROI', '/tools-static/cpa-roi-calculator.html', 'trending-up'],
          ['Eligibility Checker', '/tools-static/cpa-eligibility-checker.html', 'shield-check'],
          ['Salary Benchmark', '/tools-static/cpa-salary-benchmark.html', 'coins'],
          ['Skill Badge Assessment', '#/skill-badge', 'qr'],
        ]},
      ],
    },
    gccs: {
      title: 'GCCs & Roles',
      cols: [
        { head: 'GCC employers', items: [
          ['80+ Named GCCs', '#/gcc-employers', 'building-2'],
          ['BFSI', '#/gcc-employers/bfsi', 'landmark'],
          ['Big Tech & SaaS', '#/gcc-employers/big-tech', 'cpu'],
          ['Pharma & Health', '#/gcc-employers/pharma-health', 'heart-pulse'],
          ['Big 4 / Consulting', '#/gcc-employers/consulting', 'scale'],
        ]},
        { head: 'Roles', items: [
          ['22 Role Pods', '#/roles', 'briefcase'],
          ['AI Product Mgmt', '#/role/ai-pm', 'rocket'],
          ['AI Data Analytics', '#/role/data-analytics', 'bar-chart'],
          ['Finance Ops', '#/role/fa-ops', 'calculator'],
          ['US Tax', '#/role/tax', 'file-text'],
        ]},
      ],
    },
    domains: {
      title: 'Domain Deep Dives',
      cols: [
        { head: 'Finance & Operations', items: [
          ['Finance & Accounting Ops', '#/domains/finance-accounting', 'landmark'],
          ['Risk, Audit & Compliance', '#/domains/risk-compliance', 'shield-check'],
          ['Procurement & Supply Chain', '#/domains/procurement', 'package'],
        ]},
        { head: 'Tech & Digital', items: [
          ['Software Engineering', '#/domains/software-engineering', 'cpu'],
          ['Data & Analytics', '#/domains/data-analytics', 'bar-chart'],
          ['Cybersecurity', '#/domains/cybersecurity', 'shield-check'],
        ]},
        { head: 'Business Functions', items: [
          ['Customer & Partner Ops', '#/domains/customer-ops', 'users'],
          ['HR Shared Services', '#/domains/hr-shared-services', 'user-check'],
          ['All domains →', '#/domains', 'arrow-right'],
        ]},
      ],
    },
    for: {
      title: 'Who is it for?',
      cols: [
        { head: 'Learners', items: [
          ['For Students', '#/for-students', 'graduation-cap'],
          ['Student Resources', '#/student-resources', 'book-open'],
          ['Skill Badge Assessment', '#/skill-badge', 'qr'],
        ]},
        { head: 'Institutions', items: [
          ['For Colleges & TPOs', '#/tpo', 'building'],
          ['Placement Cell Demo', '#/contact?intent=college', 'briefcase'],
          ['Train-the-Trainer', '#/hub/train-the-trainer-tpo', 'graduation-cap'],
        ]},
        { head: 'Employers', items: [
          ['Hire from GCCReady', '#/hire', 'briefcase'],
          ['Wall of Placements', '#/placements', 'award'],
          ['Mentor Network', '#/mentors', 'star'],
          ['Employer Toolkit', '#/employer-toolkit', 'package'],
          ['Mini-GCC (US founders)', '#/mini-gcc', 'rocket'],
        ]},
      ],
    },
  };

  const isActive = (h) => hash === h || (h !== '#/' && hash.startsWith(h));

  return (
    <>
      <header style={{
        position:'sticky', top:0, zIndex:50,
        background: scrolled ? 'rgba(255,255,255,0.9)' : '#fff',
        backdropFilter: scrolled ? 'saturate(180%) blur(14px)' : 'none',
        borderBottom: `1px solid ${scrolled ? 'var(--gr-border)' : 'transparent'}`,
        transition:'all .2s ease',
      }}>
        <div className="gr-container" style={{display:'flex', alignItems:'center', justifyContent:'space-between', height:72}}>
          <Logo size="md" />
          <nav style={{display:'flex', alignItems:'center', gap:4}} className="gr-desktop-nav">
            {nav.map(n => (
              <div key={n.label}
                onMouseEnter={()=> {
                  if (window.__gr_megaTimer) { clearTimeout(window.__gr_megaTimer); window.__gr_megaTimer = null; }
                  if (n.mega) setMegaOpen(n.mega);
                  else setMegaOpen(null);
                }}
                onMouseLeave={()=> {
                  if (window.__gr_megaTimer) clearTimeout(window.__gr_megaTimer);
                  window.__gr_megaTimer = setTimeout(()=> setMegaOpen(null), 220);
                }}
                style={{position:'relative'}}>
                <a href={n.hash}
                   style={{
                     display:'inline-flex', alignItems:'center', gap:4,
                     padding:'10px 14px', borderRadius:10, textDecoration:'none',
                     color: isActive(n.hash) ? 'var(--gr-navy)' : 'var(--gr-fg-2)',
                     font:'600 14.5px/1 Inter',
                     background: isActive(n.hash) ? 'var(--gr-bg-tint)' : 'transparent',
                   }}>
                  {n.label}
                  {n.mega && <Icon name="chevron-down" size={14} style={{opacity:.6}}/>}
                </a>
                {n.mega && megaOpen === n.mega && (
                  <MegaMenu data={megas[n.mega]} onClose={()=>setMegaOpen(null)}
                    align={nav.indexOf(n) >= nav.length - 2 ? 'right' : 'center'}/>
                )}
              </div>
            ))}
          </nav>
          <div style={{display:'flex', alignItems:'center', gap:10}}>
            <a href="#/contact" className="gr-btn gr-btn-ghost" style={{padding:'10px 16px', fontSize:14}}>
              Talk to us
            </a>
            <a href="#/skill-badge" className="gr-btn gr-btn-primary" style={{padding:'10px 18px', fontSize:14}}>
              Get Skill Badge <Icon name="arrow-right" size={15}/>
            </a>
            <button onClick={()=>setOpen(!open)} className="gr-mobile-only" style={{
              background:'none', border:'none', padding:8, cursor:'pointer', display:'none',
            }}>
              <Icon name={open?'x':'menu'} size={22}/>
            </button>
          </div>
        </div>
      </header>
      <style>{`
        @media (max-width: 1060px) {
          .gr-desktop-nav { display: none !important; }
          .gr-mobile-only { display: block !important; }
        }
      `}</style>
    </>
  );
}

function MegaMenu({ data, align = 'center' }) {
  // Hover bridge: 12-px transparent strip between trigger and menu so cursor
  // never crosses a "dead zone" that would close the menu mid-traverse.
  // align="right" puts the menu against the right edge of its trigger so
  // last-position triggers don't overflow the viewport.
  const positionStyle = align === 'right'
    ? { right: 0, left: 'auto' }
    : { left: '50%', transform: 'translateX(-50%)' };
  return (
    <div style={{
      position:'absolute', top:'100%', ...positionStyle,
      paddingTop:12,  // bridge — part of the same hover region
      animation:'grFade .18s ease-out both',
      maxWidth: 'calc(100vw - 48px)',
    }}
    onMouseEnter={()=> { if (window.__gr_megaTimer) { clearTimeout(window.__gr_megaTimer); window.__gr_megaTimer = null; } }}
    >
    <div style={{
      background:'#fff', border:'1px solid var(--gr-border)',
      borderRadius:20, boxShadow:'var(--gr-shadow-xl)',
      padding:24, minWidth: 560, maxWidth: 'min(900px, calc(100vw - 48px))',
      display:'grid', gap:24,
      gridTemplateColumns: `repeat(${data.cols.length}, minmax(180px, 1fr))`,
    }}>
      {data.cols.map((col, i) => (
        <div key={i}>
          <div className="gr-eyebrow" style={{marginBottom:12}}>{col.head}</div>
          <div style={{display:'flex', flexDirection:'column', gap:2}}>
            {col.items.map(([label, href, icon]) => (
              <a key={label} href={href} style={{
                display:'flex', alignItems:'center', gap:10,
                padding:'10px 10px', borderRadius:10,
                color:'var(--gr-fg-1)', textDecoration:'none',
                font:'600 14px/1.2 Inter',
              }}
              onMouseEnter={e=>e.currentTarget.style.background='var(--gr-bg-tint)'}
              onMouseLeave={e=>e.currentTarget.style.background='transparent'}>
                <div style={{
                  width:30, height:30, borderRadius:8,
                  background:'var(--gr-navy-50)', color:'var(--gr-navy)',
                  display:'flex', alignItems:'center', justifyContent:'center',
                }}>
                  <Icon name={icon} size={15}/>
                </div>
                {label}
              </a>
            ))}
          </div>
        </div>
      ))}
    </div>
    </div>
  );
}

function Footer() {
  return (
    <footer style={{background:'var(--gr-navy-deep)', color:'#fff', paddingTop:72}}>
      <div className="gr-container">
        <div style={{
          display:'grid', gridTemplateColumns:'1.6fr repeat(6, 1fr)',
          gap:48, paddingBottom:56, borderBottom:'1px solid rgba(255,255,255,.08)',
        }}>
          <div>
            <Logo size="md" inverted/>
            <p style={{
              margin:'20px 0 0', color:'rgba(255,255,255,.6)',
              font:'400 14px/1.6 Inter', maxWidth:320,
            }}>
              Making every Indian student GCC-ready. Built in India by CorpReady AI.
            </p>
            <div style={{display:'flex', gap:10, marginTop:20}}>
              {['linkedin','youtube','instagram'].map(s => (
                <a key={s} href="#" style={{
                  width:38, height:38, borderRadius:10,
                  display:'flex', alignItems:'center', justifyContent:'center',
                  background:'rgba(255,255,255,.06)', color:'#fff',
                }}>
                  <Icon name={s} size={16}/>
                </a>
              ))}
            </div>
          </div>
          {[
            { h:'Programs',       items:[['Skill Badge','#/skill-badge'],['Crash Course','#/programs#crash'],['GCC Sprint','#/sprint'],['All Programs','#/programs'],['Pricing','#/pricing']]},
            { h:'Certifications', items:[['US CPA','#/certifications/us-cpa'],['US CMA','#/certifications/us-cma'],['EA','#/certifications/ea'],['CFA','#/certifications/cfa'],['ACCA (Upcoming)','#/certifications/acca']]},
            { h:'GCCs & Roles',   items:[['80+ Named GCCs','#/gcc-employers'],['22 Role Pods','#/roles'],['BFSI Sector','#/gcc-employers/bfsi'],['Big Tech Sector','#/gcc-employers/big-tech'],['All Domains','#/domains']]},
            { h:'Tools & Library',items:[['All 13 Tools','#/tools'],['ROI Calculator','/tools-static/cpa-roi-calculator.html'],['Eligibility Checker','/tools-static/cpa-eligibility-checker.html'],['Library (301 articles)','#/resources/library'],['Compare Certs','#/compare-certifications']]},
            { h:'For You',        items:[['Students','#/for-students'],['Student Resources','#/student-resources'],['Colleges & TPOs','#/tpo'],['Hire from GCCReady','#/hire'],['Wall of Placements','#/placements'],['Mentor Network','#/mentors'],['Mini-GCC (US founders)','#/mini-gcc']]},
            { h:'Company',        items:[['About','#/about'],['Contact','#/contact'],['Careers','#/about#careers'],['Terms','#/legal/terms'],['Privacy','#/legal/privacy']]},
          ].map(col => (
            <div key={col.h}>
              <div style={{
                font:'700 12px/1 Inter', color:'#F59E0B',
                textTransform:'uppercase', letterSpacing:'.14em', marginBottom:18,
              }}>{col.h}</div>
              <ul style={{listStyle:'none', padding:0, margin:0, display:'flex', flexDirection:'column', gap:12}}>
                {col.items.map(([l, href]) => (
                  <li key={l}><a href={href} style={{
                    color:'rgba(255,255,255,.72)', textDecoration:'none',
                    font:'500 14px/1 Inter',
                  }}>{l}</a></li>
                ))}
              </ul>
            </div>
          ))}
        </div>
        <div style={{
          padding:'28px 0', display:'flex', justifyContent:'space-between',
          color:'rgba(255,255,255,.45)', font:'500 13px/1 Inter', flexWrap:'wrap', gap:12,
        }}>
          <div>© 2025 CorpReady AI Technologies Pvt Ltd · GCCReady is a product of CorpReady AI · Bengaluru, India</div>
          <div style={{display:'flex', gap:20}}>
            <span>GST: 29AAICC1234F1Z5</span>
            <span>CIN: U80900KA2024PTC000000</span>
          </div>
        </div>
      </div>
    </footer>
  );
}

function WhatsAppFAB() {
  const [expanded, setExpanded] = React.useState(false);
  return (
    <div style={{position:'fixed', bottom:24, right:24, zIndex:40}}>
      {expanded && (
        <div style={{
          position:'absolute', bottom: 70, right: 0, width: 320,
          background:'#fff', borderRadius:20, border:'1px solid var(--gr-border)',
          boxShadow:'var(--gr-shadow-xl)', padding:20, animation:'grFade .2s ease-out both',
        }}>
          <div style={{display:'flex', alignItems:'center', gap:10, marginBottom:12}}>
            <div style={{
              width:42, height:42, borderRadius:'50%',
              background:'#25D366', color:'#fff',
              display:'flex', alignItems:'center', justifyContent:'center',
            }}>
              <Icon name="whatsapp" size={22}/>
            </div>
            <div>
              <div style={{font:'700 15px/1.2 DM Sans', color:'var(--gr-navy)'}}>GCCReady Concierge</div>
              <div style={{font:'500 12px/1.2 Inter', color:'var(--gr-green)', marginTop:2}}>● Usually replies in 8 mins</div>
            </div>
          </div>
          <div style={{
            background:'var(--gr-bg-tint)', borderRadius:12, padding:'10px 12px',
            font:'500 13.5px/1.5 Inter', color:'var(--gr-fg-2)', marginBottom:12,
          }}>
            Hi! 👋 Tell us your graduation year, stream, and city — we'll share the right pathway in 2 minutes.
          </div>
          <a href={`https://wa.me/${(window.GR_CONFIG && window.GR_CONFIG.WHATSAPP_NUM) || '919999999999'}`} target="_blank" rel="noopener" className="gr-btn" style={{
            background:'#25D366', color:'#fff', width:'100%',
          }}>
            <Icon name="whatsapp" size={16}/> Chat on WhatsApp
          </a>
          <div style={{textAlign:'center', marginTop:12, font:'500 11px/1 Inter', color:'var(--gr-fg-4)'}}>
            You'll get a link to book a 15-min call with an advisor.
          </div>
        </div>
      )}
      <button onClick={()=>setExpanded(!expanded)} style={{
        width:60, height:60, borderRadius:'50%',
        background:'#25D366', border:'none', cursor:'pointer',
        color:'#fff', display:'flex', alignItems:'center', justifyContent:'center',
        boxShadow:'0 12px 28px -6px rgba(37, 211, 102, .55), 0 0 0 8px rgba(37, 211, 102, .12)',
      }}>
        <Icon name={expanded ? 'x' : 'whatsapp'} size={28}/>
      </button>
    </div>
  );
}

// Hash router helper
function useHash() {
  const [h, setH] = React.useState(window.location.hash || '#/');
  React.useEffect(() => {
    const on = () => { setH(window.location.hash || '#/'); window.scrollTo(0, 0); };
    window.addEventListener('hashchange', on);
    return () => window.removeEventListener('hashchange', on);
  }, []);
  return h;
}

function PageShell({ children, noFab }) {
  return (
    <div>
      <Navbar/>
      <main>{children}</main>
      <Footer/>
      {!noFab && <WhatsAppFAB/>}
    </div>
  );
}

Object.assign(window, { Navbar, Footer, WhatsAppFAB, PageShell, useHash });
