/* IGI — App shell, router, tweaks */

const TWEAKS_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#2563eb",
  "navyTone": "navy",
  "fontPair": "manrope_newsreader",
  "showTrustBar": true,
  "showChat": true,
  "showStickyCTA": true,
  "heroVariant": "split"
}/*EDITMODE-END*/;

function App() {
  const [route, setRoute] = React.useState(() => {
    const h = window.location.hash.replace('#/', '') || 'home';
    return h;
  });
  const [tweaks, setTweak] = useTweaks(TWEAKS_DEFAULTS);

  React.useEffect(() => {
    const onHash = () => setRoute(window.location.hash.replace('#/', '') || 'home');
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  React.useEffect(() => {
    window.scrollTo({ top: 0, behavior: 'instant' });
  }, [route]);

  const navigate = (r) => {
    window.location.hash = `#/${r}`;
    setRoute(r);
  };

  // Apply tweak overrides
  React.useEffect(() => {
    document.documentElement.style.setProperty('--blue-600', tweaks.accent);
    document.documentElement.style.setProperty('--blue-700', shade(tweaks.accent, -0.12));
    document.documentElement.style.setProperty('--blue-500', shade(tweaks.accent, 0.1));
    document.documentElement.style.setProperty('--blue-50', shade(tweaks.accent, 0.92));

    const navyMap = {
      navy: ['#0a2540', '#061a30', '#0f2d52', '#f1f5fa'],
      slate: ['#1e293b', '#0f172a', '#334155', '#f1f5f9'],
      forest: ['#14532d', '#0a2e1a', '#166534', '#f0fdf4'],
      espresso: ['#3f2a1d', '#231510', '#5a3d2b', '#faf6f1'],
    };
    const [n8, n9, n7, n50] = navyMap[tweaks.navyTone] || navyMap.navy;
    document.documentElement.style.setProperty('--navy-800', n8);
    document.documentElement.style.setProperty('--navy-900', n9);
    document.documentElement.style.setProperty('--navy-700', n7);
    document.documentElement.style.setProperty('--navy-50', n50);

    const fontMap = {
      manrope_newsreader: ['"Manrope"', '"Newsreader"'],
      jakarta_serif: ['"Plus Jakarta Sans"', '"Crimson Pro"'],
      dm_dm: ['"DM Sans"', '"DM Serif Display"'],
      ibm: ['"IBM Plex Sans"', '"IBM Plex Serif"'],
    };
    const [sans, serif] = fontMap[tweaks.fontPair] || fontMap.manrope_newsreader;
    document.documentElement.style.setProperty('--font-sans', `${sans}, -apple-system, system-ui, sans-serif`);
    document.documentElement.style.setProperty('--font-serif', `${serif}, Georgia, serif`);
  }, [tweaks]);

  const showChrome = route !== 'quote-fullscreen';

  return (
    <>
      {showChrome && <Nav route={route} navigate={navigate} />}

      <main data-screen-label={routeLabel(route)}>
        {route === 'home' && <Home navigate={navigate} />}
        {route === 'motor' && <Motor navigate={navigate} />}
        {route === 'igi-drive' && <IGIDrive navigate={navigate} />}
        {route === 'igi-vitality-drive' && <IGIVitalityDrive navigate={navigate} />}
        {route === 'home-prop' && <HomeProp navigate={navigate} />}
        {route === 'travel' && <Travel navigate={navigate} />}
        {route === 'health' && <Health navigate={navigate} />}
        {route === 'marine' && <Marine navigate={navigate} />}
        {route === 'fire' && <Fire navigate={navigate} />}
        {route === 'engineering' && <Engineering navigate={navigate} />}
        {route === 'liability' && <Liability navigate={navigate} />}
        {route === 'crop' && <Crop navigate={navigate} />}
        {route === 'corporate' && <Corporate navigate={navigate} />}
        {route === 'quote' && <QuoteFlow navigate={navigate} />}
        {route === 'claims' && <Claims navigate={navigate} />}
        {route === 'dashboard' && <Dashboard navigate={navigate} />}
        {route === 'locator' && <Locator />}
        {route === 'about' && <About navigate={navigate} />}
        {route === 'contact' && <Contact />}
      </main>

      {showChrome && <Footer navigate={navigate} />}

      {tweaks.showStickyCTA && route !== 'dashboard' && route !== 'quote' && <StickyCTA navigate={navigate} route={route} />}
      {tweaks.showChat && <ChatWidget />}

      <TweaksPanel title="Tweaks">
          <TweakSection title="Brand colors">
            <TweakColor
              label="Accent color"
              value={tweaks.accent}
              onChange={v => setTweak('accent', v)}
              options={['#2563eb', '#0d9488', '#7c3aed', '#dc2626', '#d97706']}
            />
            <TweakRadio
              label="Dark tone"
              value={tweaks.navyTone}
              onChange={v => setTweak('navyTone', v)}
              options={[
                { value: 'navy', label: 'Navy' },
                { value: 'slate', label: 'Slate' },
                { value: 'forest', label: 'Forest' },
                { value: 'espresso', label: 'Espresso' },
              ]}
            />
          </TweakSection>
          <TweakSection title="Typography">
            <TweakSelect
              label="Font pairing"
              value={tweaks.fontPair}
              onChange={v => setTweak('fontPair', v)}
              options={[
                { value: 'manrope_newsreader', label: 'Manrope + Newsreader' },
                { value: 'jakarta_serif', label: 'Plus Jakarta + Crimson' },
                { value: 'dm_dm', label: 'DM Sans + DM Serif' },
                { value: 'ibm', label: 'IBM Plex Sans + Serif' },
              ]}
            />
          </TweakSection>
          <TweakSection title="Page elements">
            <TweakToggle label="Show trust bar" value={tweaks.showTrustBar} onChange={v => setTweak('showTrustBar', v)} />
            <TweakToggle label="Show chat widget" value={tweaks.showChat} onChange={v => setTweak('showChat', v)} />
            <TweakToggle label="Show sticky CTA" value={tweaks.showStickyCTA} onChange={v => setTweak('showStickyCTA', v)} />
          </TweakSection>
          <TweakSection title="Quick navigation">
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 6 }}>
              {['home', 'motor', 'quote', 'claims', 'dashboard', 'locator', 'about', 'contact'].map(r => (
                <button key={r} onClick={() => navigate(r)} style={{
                  padding: '8px 10px', fontSize: 12, fontWeight: 600,
                  border: '1px solid var(--ink-200)', borderRadius: 8,
                  background: route === r ? 'var(--navy-800)' : 'white',
                  color: route === r ? 'white' : 'var(--ink-700)',
                  textTransform: 'capitalize',
                }}>{r}</button>
              ))}
            </div>
          </TweakSection>
      </TweaksPanel>
    </>
  );
}

// Lighten/darken hex color
function shade(hex, percent) {
  const n = hex.replace('#', '');
  const num = parseInt(n, 16);
  let r = (num >> 16);
  let g = ((num >> 8) & 0x00FF);
  let b = (num & 0x0000FF);
  if (percent > 0) {
    r = Math.round(r + (255 - r) * percent);
    g = Math.round(g + (255 - g) * percent);
    b = Math.round(b + (255 - b) * percent);
  } else {
    r = Math.round(r * (1 + percent));
    g = Math.round(g * (1 + percent));
    b = Math.round(b * (1 + percent));
  }
  return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}

function routeLabel(r) {
  const map = {
    home: 'Homepage',
    motor: 'Motor product detail',
    quote: 'Quote builder',
    claims: 'Claims center',
    dashboard: 'Customer dashboard',
    locator: 'Hospital & workshop locator',
    about: 'About IGI',
    contact: 'Contact',
  };
  return map[r] || r;
}

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