// Root app — composes the full homepage and the Tweaks panel.

const TWEAK_DEFAULTS = {
  "theme": "light",
  "accent": "#1F3A5F",
  "grain": true,
  "paperTone": "ivory",
  "subhead": "A personal lab for better homes, healthier routines, useful AI agents, and thoughtful work."
};

const ACCENT_OPTIONS = ['#1F3A5F', '#9C6B1F', '#8E3A1F', '#2F4A37'];

const PAPER_TONES = {
  ivory: { paper: '#FBF9F2', paper2: '#F4F1E7', paper3: '#E8E4D6', rule: '#DDD7C6', ruleStrong: '#BBB6A5' },
  bone:  { paper: '#F2EFE7', paper2: '#E8E4D7', paper3: '#D7D2C2', rule: '#C7C2B2', ruleStrong: '#A8A395' },
  cream: { paper: '#EDE9DD', paper2: '#E0DCCC', paper3: '#CFC9B5', rule: '#CFCBBC', ruleStrong: '#B3AE9D' },
  dove:  { paper: '#E7E9E4', paper2: '#D5D8D2', paper3: '#BFC3BC', rule: '#B0B3AA', ruleStrong: '#91948C' },
};

const App = () => {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [active, setActive] = React.useState('top');

  React.useEffect(() => {
    document.documentElement.dataset.theme = t.theme === 'dark' ? 'dark' : '';
  }, [t.theme]);

  React.useEffect(() => {
    document.body.dataset.grain = t.grain ? 'on' : 'off';
  }, [t.grain]);

  React.useEffect(() => {
    const root = document.documentElement;
    if (t.accent && t.accent !== '#1F3A5F') {
      root.style.setProperty('--accent', t.accent);
      const deep = darken(t.accent, 0.25);
      root.style.setProperty('--accent-press', deep);
      root.style.setProperty('--prussian', t.accent);
      root.style.setProperty('--prussian-deep', deep);
      root.style.setProperty('--accent-bg', tint(t.accent, 0.85));
      root.style.setProperty('--prussian-tint', tint(t.accent, 0.85));
    } else {
      root.style.removeProperty('--accent');
      root.style.removeProperty('--accent-press');
      root.style.removeProperty('--prussian');
      root.style.removeProperty('--prussian-deep');
      root.style.removeProperty('--accent-bg');
      root.style.removeProperty('--prussian-tint');
    }
  }, [t.accent]);

  React.useEffect(() => {
    const root = document.documentElement;
    const palette = PAPER_TONES[t.paperTone] || PAPER_TONES.dove;
    if (t.theme === 'dark') {
      root.style.removeProperty('--paper');
      root.style.removeProperty('--paper-2');
      root.style.removeProperty('--paper-3');
      root.style.removeProperty('--rule');
      root.style.removeProperty('--rule-strong');
      return;
    }
    root.style.setProperty('--paper', palette.paper);
    root.style.setProperty('--paper-2', palette.paper2);
    root.style.setProperty('--paper-3', palette.paper3);
    root.style.setProperty('--rule', palette.rule);
    root.style.setProperty('--rule-strong', palette.ruleStrong);
  }, [t.paperTone, t.theme]);

  const onNavigate = (id) => {
    setActive(id);
    if (id === 'top') {
      window.scrollTo({ top: 0, behavior: 'smooth' });
      return;
    }
    document.getElementById(id)?.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };

  const toggleTheme = () => setTweak('theme', t.theme === 'light' ? 'dark' : 'light');

  React.useEffect(() => {
    const sections = ['lab', 'systems', 'projects', 'notes', 'about', 'contact'];
    const onScroll = () => {
      let cur = 'top';
      for (const id of sections) {
        const el = document.getElementById(id);
        if (!el) continue;
        const r = el.getBoundingClientRect();
        if (r.top < 200) cur = id;
      }
      const navMap = { lab: 'top', systems: 'systems', projects: 'projects', notes: 'notes', about: 'about', contact: 'about' };
      setActive(navMap[cur] || 'top');
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  return (
    <React.Fragment>
      <SiteHeader active={active} onNavigate={onNavigate} theme={t.theme} onToggleTheme={toggleTheme} />
      <main>
        <Hero subhead={t.subhead} />
        <WhatIsLab />
        <AreasOfWork />
        <FeaturedProjects />
        <FieldNotes />
        <AboutLab />
        <ContactFollow />
      </main>
      <SiteFooter />

      <TweaksPanel title="Tweaks">
        <TweakSection label="Theme">
          <TweakRadio
            label="Mode"
            value={t.theme}
            onChange={(v) => setTweak('theme', v)}
            options={[{ value: 'light', label: 'Paper' }, { value: 'dark', label: 'Dark' }]}
          />
          <TweakColor
            label="Accent"
            value={t.accent}
            onChange={(v) => setTweak('accent', v)}
            options={ACCENT_OPTIONS}
          />
          <TweakSelect
            label="Paper tone"
            value={t.paperTone}
            onChange={(v) => setTweak('paperTone', v)}
            options={[
              { value: 'ivory', label: 'Ivory (lightest)' },
              { value: 'bone',  label: 'Bone' },
              { value: 'cream', label: 'Chalk cream' },
              { value: 'dove',  label: 'Dove gray' },
            ]}
          />
          <TweakToggle
            label="Paper grain"
            value={t.grain}
            onChange={(v) => setTweak('grain', v)}
          />
        </TweakSection>
        <TweakSection label="Copy">
          <TweakText
            label="Subheadline"
            value={t.subhead}
            onChange={(v) => setTweak('subhead', v)}
          />
        </TweakSection>
      </TweaksPanel>
    </React.Fragment>
  );
};

// Tiny color helpers
function hexToRgb(hex) {
  const h = hex.replace('#', '');
  return { r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16) };
}

function rgbToHex({r,g,b}) {
  const c = (n) => n.toString(16).padStart(2,'0');
  return `#${c(Math.round(r))}${c(Math.round(g))}${c(Math.round(b))}`;
}

function darken(hex, amt) {
  const {r,g,b} = hexToRgb(hex);
  return rgbToHex({ r: r*(1-amt), g: g*(1-amt), b: b*(1-amt) });
}

function tint(hex, amt) {
  const {r,g,b} = hexToRgb(hex);
  const m = { r: 231, g: 233, b: 228 };
  return rgbToHex({
    r: r + (m.r - r) * amt,
    g: g + (m.g - g) * amt,
    b: b + (m.b - b) * amt,
  });
}

window.App = App;
