/* GCCReady — Router
 *
 * Supports BOTH path-style URLs (e.g. /skill-badge) and hash-style (#/skill-badge).
 * On initial load, if the pathname is anything other than '/' AND there's no hash,
 * we promote the path to a hash and rewrite history so the SPA can render.
 * This lets crawlers index direct paths (provided the host has SPA fallback —
 * see vercel.json / netlify.toml / _redirects) while keeping the in-app
 * hash-based nav fast and reload-free.
 */
(function bridgePathToHash() {
  if (typeof window === 'undefined') return;
  var p = window.location.pathname || '/';
  var h = window.location.hash || '';
  // Don't promote static asset paths or known asset routes
  if (/\.(js|jsx|css|png|jpg|jpeg|svg|webp|ico|json|xml|txt|html|map)$/i.test(p)) return;
  if (p.startsWith('/articles/') || p.startsWith('/hubs/') || p.startsWith('/tools-static/')) return;
  if (p !== '/' && !h) {
    // Promote: turn /skill-badge into #/skill-badge and reset path to /
    var newHash = '#' + p + (window.location.search || '');
    window.history.replaceState(null, '', '/' + newHash);
  }
})();

function App() {
  const hash = useHash();
  const [, path, sub, sub2] = (hash||'#/').split('/');
  // hash is like '#/domains/finance-accounting' → ['#','domains','finance-accounting']
  const route = (hash || '#/').replace(/^#\/?/, '').split('#')[0].split('?')[0];
  const [seg0, seg1] = route.split('/');

  let page;
  switch (seg0) {
    case '': case undefined: page = <HomePage/>; break;
    case 'for-students': page = <ForStudentsPage/>; break;
    case 'for-colleges': page = <ForCollegesPage/>; break;
    case 'for-employers': page = <ForEmployersPage/>; break;
    case 'programs': page = <ProgramsPage/>; break;
    case 'sprint': page = <SprintPage/>; break;
    case 'pricing': page = <PricingPage/>; break;
    case 'gcc-employers': page = seg1 ? <SectorPage slug={seg1}/> : <GCCUniversePage/>; break;
    case 'gcc': page = seg1 ? <EmployerPage slug={seg1}/> : <GCCUniversePage/>; break;
    case 'roles': page = <RolesPage/>; break;
    case 'role': page = seg1 ? <RoleDetailPage slug={seg1}/> : <RolesPage/>; break;
    case 'mini-gcc': page = seg1 === 'form' ? <MiniGCCFormPage/> : <MiniGCCPage/>; break;
    case 'resources':
      if (seg1 === 'library') page = <ResourcesLibraryPage/>;
      else page = <ResourcesPage/>;
      break;
    case 'article': page = seg1 ? <ArticlePage slug={seg1}/> : <ResourcesLibraryPage/>; break;
    case 'tpo': page = <TPOLandingPage/>; break;
    case 'employer-toolkit': page = <EmployerToolkitPage/>; break;
    case 'student-resources': page = <StudentResourcesPage/>; break;
    case 'hub': page = seg1 ? <HubPage slug={seg1}/> : <HomePage/>; break;
    case 'tools': page = <ToolsHubPage/>; break;
    case 'mentors': page = <MentorNetworkPage/>; break;
    case 'compare-with':
      if (seg1 && COMPETITORS[seg1]) page = <CompareWithPage slug={seg1}/>;
      else page = <CompareWithIndex/>;
      break;
    case 'skill-readiness': page = <SkillReadinessPage/>; break;
    case 'placements': page = <PlacementsPage/>; break;
    case 'hire': page = <EmployerConnectPage/>; break;
    case 'skill-badge':
      if (seg1 === 'take' || seg1 === 'assess') page = <SkillBadgeAssessPage/>;
      else page = <SkillBadgePage/>;
      break;
    case 'certifications':
      if (seg1 === 'us-cma') page = <CMAPage/>;
      else if (seg1 && CERT_PILLAR[seg1]) page = <PillarCertPage slug={seg1}/>;
      else page = <CertificationsPage/>;
      break;
    case 'domains':
      if (!seg1) page = <DomainsHub/>;
      else if (seg1 === 'finance-accounting') page = <FinanceDomainPage/>;
      else {
        const map = {
          'risk-compliance': ['Risk, Audit & Compliance','shield-check',[['SOX','Compliance'],['KYC','AML Ops'],['IA','Internal Audit'],['GRC','Risk Tech']]],
          'procurement': ['Procurement & Supply Chain','package',[['S2P','Source-to-Pay'],['S&OP','Planning'],['Log','Logistics'],['Vnd','Vendor Mgmt']]],
          'software-engineering': ['Software Engineering','cpu',[['FS','Full-stack'],['SRE','Reliability'],['Plat','Platform'],['QA','Quality']]],
          'data-analytics': ['Data & Analytics','bar-chart',[['SQL','Core'],['BI','Power BI'],['Py','Python'],['ML','ML Ops']]],
          'cybersecurity': ['Cybersecurity','shield-check',[['SOC','Operations'],['GRC','Compliance'],['IAM','Identity'],['AppSec','Product']]],
          'customer-ops': ['Customer & Partner Ops','users',[['CX','Support'],['T&S','Trust & Safety'],['PO','Partner Ops'],['Succ','Success']]],
          'hr-shared-services': ['HR Shared Services','user-check',[['WDY','Workday'],['Pay','Payroll'],['TA','Talent Acq'],['PA','People Analytics']]],
          'marketing-ops': ['Marketing & Revenue Ops','trending-up',[['Rev','RevOps'],['Cam','Campaign'],['Att','Attribution'],['MA','Marketing Auto']]],
          'legal-compliance-ops': ['Legal & Compliance Ops','scale',[['CLM','Contract Lifecycle'],['Para','Paralegal'],['Comp','Compliance'],['IP','IP Ops']]],
          'healthcare-ops': ['Healthcare Ops','heart-pulse',[['RCM','Revenue Cycle'],['PV','Pharmacovigilance'],['Cod','Medical Coding'],['Clin','Clinical Ops']]],
          'sustainability': ['ESG & Sustainability','leaf',[['Rep','ESG Reporting'],['Carb','Carbon Accounting'],['Reg','Regulatory'],['Imp','Impact Mgmt']]],
          'product-ops': ['Product Ops','package',[['Rel','Release'],['QA','QA Ops'],['UAT','UAT'],['Tel','Telemetry']]],
        };
        const d = map[seg1];
        page = d ? <GenericDomainPage name={d[0]} icon={d[1]} subs={d[2]}/> : <DomainsHub/>;
      }
      break;
    case 'contact':   page = <ContactPage/>; break;
    case 'about':     page = <AboutPage/>; break;
    case 'press':     page = <PressPage/>; break;
    case 'legal':
      if (seg1 === 'privacy') page = <LegalPage title="Privacy Policy" sections={[
        {h:'1. Who we are', p:['CorpReady AI Technologies Pvt Ltd ("GCCReady") is the data fiduciary for this policy. We\'re registered in Bengaluru, India and process data for users of gccready.com and the Skill Badge product.']},
        {h:'2. What we collect', p:['Account data (name, email, phone, college).','Assessment responses and scores for the Skill Badge.','Device and analytics data (cookies, IP, session events).','Payment information, processed by Razorpay — we never store card numbers.']},
        {h:'3. How we use it', p:['To deliver programs and produce your Skill Badge.','To share your card (with consent) with partner GCC recruiters.','To communicate program updates and send The GCC Brief (opt-in).','To improve the rubric and our products, using de-identified aggregate data only.']},
        {h:'4. Your rights', p:['Under India\'s DPDP Act 2023 you have the right to access, correct, and erase your data. Email privacy@gccready.com for any request; we respond in 30 days.']},
        {h:'5. Retention', p:['Skill Badge scores retained 24 months after last activity, then anonymised. Payment records 8 years (statutory). Video proctoring recordings deleted after 90 days.']},
        {h:'6. Data sharing', p:['We never sell personal data. We share with: (i) partner GCCs, only with your opt-in; (ii) your college, if partnered AND you chose to display; (iii) statutory authorities, on valid legal request.']},
        {h:'7. Security', p:['ISO 27001 certified. All data encrypted at rest (AES-256) and in transit (TLS 1.3). Access logs audited monthly.']},
      ]}/>;
      else if (seg1 === 'refunds') page = <LegalPage title="Refund & Cancellation Policy" sections={[
        {h:'1. Cooling-off window (7 days)', p:['Full refund for any paid program if you email refunds@gccready.com within 7 calendar days of program start and haven\'t accessed more than 20% of content.']},
        {h:'2. Crash Course refunds', p:['Week 1–2: 75% refund. Week 3–4: 50% refund. Week 5–6: No refund.']},
        {h:'3. Sprint refunds', p:['Week 1–2: 75% refund. Week 3–6: 40% refund. Week 7+: No cash refund, but transfer to next cohort permitted.','Placement guarantee: If you complete the Sprint and don\'t get a verified offer within 90 days, we refund 100% (₹34,999).','ISA students who exit voluntarily before completion: ISA cancelled, no liability.']},
        {h:'4. Certification refunds', p:['IMA/AICPA exam fees paid on your behalf are non-refundable once you register. The GCCReady tuition portion (~₹51,000 of CMA, similar for others) follows the Sprint refund schedule above.']},
        {h:'5. Skill Badge retakes', p:['Skill Badge is free; refunds not applicable. Paid proctored retakes (₹499) are non-refundable once scheduled.']},
        {h:'6. Processing time', p:['Approved refunds are credited to the original payment method within 7–10 working days.']},
      ]}/>;
      else if (seg1 === 'cookies') page = <LegalPage title="Cookie Policy" sections={[
        {h:'1. What cookies we use', p:['Essential: session, CSRF, preference (no consent required).','Analytics: PostHog product analytics (consent-gated).','Marketing: Meta & LinkedIn pixels on /for-colleges and /for-employers only, consent-gated.']},
        {h:'2. Managing cookies', p:['Click "Cookie Settings" in the footer. Browser-level controls also work. Disabling essential cookies breaks the Skill Badge flow.']},
        {h:'3. Third parties', p:['Razorpay (payments), Intercom (support chat), Google Workspace (forms) may set their own cookies. We only enable them post-consent where required.']},
      ]}/>;
      else page = <LegalPage title="Terms of Service" sections={[
        {h:'1. Acceptance', p:['By creating an account or purchasing a program, you agree to these Terms. If you do not agree, please don\'t use our services.']},
        {h:'2. Eligibility', p:['You must be 16+ to take the Skill Badge. You must be 18+ to enrol in paid programs. If you\'re under 18 we require consent from a parent or guardian.']},
        {h:'3. Your account', p:['You\'re responsible for keeping your credentials safe. We are not liable for unauthorised actions by third parties who acquired your password.']},
        {h:'4. Skill Badge usage', p:['Your Skill Badge is your personal record. You control visibility to recruiters. Misrepresentation (cheating in proctored assessments) voids the card and bans the account.']},
        {h:'5. Payments & refunds', p:['See our Refund Policy. All fees are in INR and inclusive of 18% GST.']},
        {h:'6. Intellectual property', p:['All course content, assessments, and the Skill Badge rubric are copyright CorpReady AI Technologies Pvt Ltd. You may not redistribute or resell without written permission.']},
        {h:'7. Placement guarantees', p:['The Sprint placement guarantee applies only if you: (a) completed 95% of program, (b) attended all mock interviews, (c) accepted at least 4 interview intros, and (d) didn\'t refuse a verified offer matching your stated preferences.']},
        {h:'8. Liability', p:['Our maximum liability is the amount you paid us in the preceding 12 months. We are not liable for indirect or consequential losses.']},
        {h:'9. Governing law', p:['These Terms are governed by the laws of India. Jurisdiction: courts of Bengaluru, Karnataka.']},
        {h:'10. Changes', p:['We\'ll notify you via email 30 days before material changes.']},
      ]}/>;
      break;
    default: page = <HomePage/>;
  }

  return <PageShell>{page}</PageShell>;
}

ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
