/* global React, ReactDOM, Nav, Footer, HomePage, SolutionsPage, AboutPage, ContactPage, DefensiblePage,
   TweaksPanel, useTweaks, TweakSection, TweakRadio, TweakColor, TweakToggle, TweakSelect */
const { useState, useEffect } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#3b82f6",
  "density": "comfortable",
  "headlineFont": "Geist",
  "showHeroDashboard": true,
  "teamLayout": "founder",
  "defensibleFont": "EB Garamond"
}/*EDITMODE-END*/;

const PAGES = {
  home: HomePage,
  solutions: SolutionsPage,
  defensible: DefensiblePage,
  about: AboutPage,
  contact: ContactPage,
};

function App() {
  const [route, setRoute] = useState(() => {
    const h = (window.location.hash || '').replace('#', '');
    return PAGES[h] ? h : 'home';
  });

  const go = (id) => {
    setRoute(id);
    window.location.hash = id;
    window.scrollTo({ top: 0, behavior: 'instant' });
  };

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

  const [t, setT] = useTweaks(TWEAK_DEFAULTS);

  // Apply tweaks via CSS vars
  useEffect(() => {
    const r = document.documentElement;
    r.style.setProperty('--blue', t.accent);
    // derive accent variants
    const dim = shade(t.accent, -0.18);
    const lite = shade(t.accent, 0.25);
    r.style.setProperty('--blue-dim', dim);
    r.style.setProperty('--blue-2', lite);
    r.style.setProperty('--blue-soft', tint(t.accent, 0.85));

    // density
    if (t.density === 'compact') {
      r.style.setProperty('--section-pad', '56px');
    } else {
      r.style.setProperty('--section-pad', '120px');
    }
    document.body.dataset.density = t.density;

    // headline font
    const fontMap = {
      'Geist':     '"Geist", ui-sans-serif, system-ui, sans-serif',
      'Instrument Serif': '"Instrument Serif", Georgia, serif',
      'Space Grotesk':   '"Space Grotesk", "Geist", system-ui, sans-serif',
    };
    r.style.setProperty('--sans', fontMap[t.headlineFont] || fontMap.Geist);

    // dashboard overlay toggle
    document.body.dataset.heroDashboard = t.showHeroDashboard ? 'on' : 'off';

    // defensible headline font
    const defFontMap = {
      'Instrument Serif': '"Instrument Serif", Georgia, serif',
      'EB Garamond':      '"EB Garamond", Georgia, serif',
      'DM Serif Display': '"DM Serif Display", Georgia, serif',
      'Newsreader':       '"Newsreader", Georgia, serif',
      'Space Grotesk':    '"Space Grotesk", ui-sans-serif, system-ui, sans-serif',
      'JetBrains Mono':   '"JetBrains Mono", ui-monospace, monospace',
    };
    r.style.setProperty('--d-serif-active', defFontMap[t.defensibleFont] || defFontMap['Instrument Serif']);
    document.body.dataset.defensibleFont = t.defensibleFont;
  }, [t.accent, t.density, t.headlineFont, t.showHeroDashboard, t.defensibleFont]);

  const Page = PAGES[route] || HomePage;
  return (
    <div data-screen-label={`Page · ${route}`}>
      <Nav route={route} go={go} />
      <Page go={go} teamLayout={t.teamLayout} />
      <Footer go={go} />

      <TweaksPanel title="Tweaks">
        <TweakSection label="Brand accent" />
        <TweakColor
          label="Accent"
          value={t.accent}
          onChange={(v) => setT('accent', v)}
          options={['#3b82f6', '#22c55e', '#f97316', '#a855f7']}
        />

        <TweakSection label="Typography" />
        <TweakRadio
          label="Headline"
          value={t.headlineFont}
          onChange={(v) => setT('headlineFont', v)}
          options={[
            { value: 'Geist', label: 'Geist' },
            { value: 'Instrument Serif', label: 'Serif' },
            { value: 'Space Grotesk', label: 'Grotesk' },
          ]}
        />

        <TweakSection label="Layout" />
        <TweakRadio
          label="Density"
          value={t.density}
          onChange={(v) => setT('density', v)}
          options={[
            { value: 'compact', label: 'Compact' },
            { value: 'comfortable', label: 'Comfortable' },
          ]}
        />
        <TweakToggle
          label="Hero overlay"
          value={t.showHeroDashboard}
          onChange={(v) => setT('showHeroDashboard', v)}
        />

        <TweakSection label="About — Team layout" />
        <TweakSelect
          label="Layout"
          value={t.teamLayout}
          onChange={(v) => setT('teamLayout', v)}
          options={[
            { value: 'founder',  label: 'Founder spotlight' },
            { value: 'list',     label: 'Name list (no avatars)' },
            { value: 'monogram', label: 'Monogram grid' },
            { value: 'photos',   label: 'Photo grid (original)' },
          ]}
        />

        <TweakSection label="Defensible — headline font" />
        <TweakSelect
          label="Font"
          value={t.defensibleFont}
          onChange={(v) => setT('defensibleFont', v)}
          options={[
            { value: 'Instrument Serif', label: 'Instrument Serif — editorial' },
            { value: 'EB Garamond',      label: 'EB Garamond — old-style, dignified' },
            { value: 'DM Serif Display', label: 'DM Serif Display — high contrast' },
            { value: 'Newsreader',       label: 'Newsreader — modern editorial' },
            { value: 'Space Grotesk',    label: 'Space Grotesk — technical sans' },
            { value: 'JetBrains Mono',   label: 'JetBrains Mono — terminal' },
          ]}
        />
      </TweaksPanel>
    </div>
  );
}

// =========================================================
// Color utils — shift toward black/white
// =========================================================
function hexToRgb(hex) {
  const h = hex.replace('#', '');
  return [0,1,2].map(i => parseInt(h.substr(i*2, 2), 16));
}
function rgbToHex(r,g,b) {
  return '#' + [r,g,b].map(v => Math.max(0, Math.min(255, Math.round(v))).toString(16).padStart(2,'0')).join('');
}
function shade(hex, amt) {
  // negative = darker, positive = lighter
  const [r,g,b] = hexToRgb(hex);
  const f = amt < 0 ? 0 : 255;
  const p = Math.abs(amt);
  return rgbToHex(r + (f - r) * p, g + (f - g) * p, b + (f - b) * p);
}
function tint(hex, amt) {
  // mix toward white
  return shade(hex, amt);
}

// Load extra font stylesheets so they're ready when tweaks pick them
const extra = document.createElement('link');
extra.rel = 'stylesheet';
extra.href = 'https://fonts.googleapis.com/css2?family=Instrument+Serif:ital@0;1&family=Space+Grotesk:wght@400;500;600;700&family=EB+Garamond:ital,wght@0,400;0,500;1,400&family=DM+Serif+Display:ital@0;1&family=Newsreader:ital,opsz,wght@0,6..72,400;0,6..72,500;1,6..72,400&family=JetBrains+Mono:wght@400;500;700&display=swap';
document.head.appendChild(extra);

// Apply hero dashboard toggle via CSS hook
const hideStyle = document.createElement('style');
hideStyle.textContent = `body[data-hero-dashboard="off"] .hero-card { display: none; }`;
document.head.appendChild(hideStyle);

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