// App mount + tweaks panel
const { useState: useStateApp, useEffect: useEffectApp } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#8A3B1C",
  "paper": "#F5F1EA",
  "displayFont": "Newsreader",
  "bodyFont": "Geist"
}/*EDITMODE-END*/;

function applyTweaks(t) {
  const root = document.documentElement;
  root.style.setProperty('--tw-accent', t.accent);
  // Rebuild tailwind color usage via CSS vars on the fly
  const style = document.getElementById('tweak-style') || (() => {
    const s = document.createElement('style'); s.id = 'tweak-style'; document.head.appendChild(s); return s;
  })();
  style.textContent = `
    html, body { background: ${t.paper} !important; }
    .bg-paper { background-color: ${t.paper} !important; }
    .text-sienna { color: ${t.accent} !important; }
    .bg-sienna { background-color: ${t.accent} !important; }
    .border-sienna { border-color: ${t.accent} !important; }
    .hover\\:bg-sienna:hover { background-color: ${t.accent} !important; }
    .hover\\:text-sienna:hover { color: ${t.accent} !important; }
    .ornament { color: ${t.accent} !important; }
    .dropcap::first-letter { color: ${t.accent} !important; }
    ::selection { background: ${t.accent} !important; }
    .font-display { font-family: '${t.displayFont}', Georgia, serif !important; }
    body, .font-sans { font-family: '${t.bodyFont}', system-ui, sans-serif !important; }
  `;
}

function TweaksPanel({ tweaks, setTweaks, onClose }) {
  const accents = [
    ['Deep sienna', '#8A3B1C'],
    ['Forest', '#2F4F2A'],
    ['Aubergine', '#4A1E3A'],
    ['Oxblood', '#5C1A1A'],
    ['Ink only', '#141413'],
  ];
  const papers = [
    ['Warm cream', '#F5F1EA'],
    ['Bone', '#F2EEE5'],
    ['Off-white', '#FAFAF6'],
    ['Cool paper', '#EEEFF0'],
  ];
  const displayFonts = ['Newsreader', 'Libre Caslon Text', 'Source Serif 4'];
  const bodyFonts = ['Geist', 'IBM Plex Sans', 'Söhne'];
  return (
    <div className="tweaks-panel fixed bottom-6 right-6 z-50 w-[320px] bg-paper/95 rule-top rule-bottom border hairline">
      <div className="rule-bottom px-4 py-3 flex items-center justify-between">
        <div className="smallcaps text-muted">Tweaks</div>
        <button onClick={onClose} className="smallcaps text-muted hover:text-ink">Close ×</button>
      </div>
      <div className="p-4 space-y-5">
        <div>
          <div className="smallcaps text-muted mb-2">Accent</div>
          <div className="flex gap-2 flex-wrap">
            {accents.map(([l, v]) => (
              <button key={l} title={l} onClick={() => setTweaks({ ...tweaks, accent: v })}
                      className={`w-8 h-8 rounded-full border hairline ${tweaks.accent === v ? 'ring-2 ring-ink ring-offset-2 ring-offset-paper' : ''}`}
                      style={{ background: v }} />
            ))}
          </div>
        </div>
        <div>
          <div className="smallcaps text-muted mb-2">Paper</div>
          <div className="flex gap-2 flex-wrap">
            {papers.map(([l, v]) => (
              <button key={l} title={l} onClick={() => setTweaks({ ...tweaks, paper: v })}
                      className={`w-8 h-8 rounded-full border hairline ${tweaks.paper === v ? 'ring-2 ring-ink ring-offset-2 ring-offset-paper' : ''}`}
                      style={{ background: v }} />
            ))}
          </div>
        </div>
        <div>
          <div className="smallcaps text-muted mb-2">Display font</div>
          <select value={tweaks.displayFont} onChange={e => setTweaks({ ...tweaks, displayFont: e.target.value })}
                  className="w-full bg-transparent border hairline px-2 py-1 font-display">
            {displayFonts.map(f => <option key={f} value={f}>{f}</option>)}
          </select>
        </div>
        <div>
          <div className="smallcaps text-muted mb-2">Body font</div>
          <select value={tweaks.bodyFont} onChange={e => setTweaks({ ...tweaks, bodyFont: e.target.value })}
                  className="w-full bg-transparent border hairline px-2 py-1">
            {bodyFonts.map(f => <option key={f} value={f}>{f}</option>)}
          </select>
        </div>
      </div>
    </div>
  );
}

function App() {
  const { route } = useRoute();
  const page = {
    home: <Home />,
    pov: <POV />,
    industries: <Industries />,
    cases: <Cases />,
    tools: <Tools />,
    writing: <Writing />,
    now: <Now />,
    about: <About />,
    resume: <Resume />,
    contact: <Contact />,
  }[route] || <Home />;

  return (
    <div>
      <TopBar />
      {page}
      <Footer />
    </div>
  );
}

function Root() {
  const [tweaks, setTweaksRaw] = useStateApp(TWEAK_DEFAULTS);
  const [showTweaks, setShowTweaks] = useStateApp(false);
  const [editModeOn, setEditModeOn] = useStateApp(false);

  const setTweaks = (next) => {
    setTweaksRaw(next);
    applyTweaks(next);
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: next }, '*');
  };

  useEffectApp(() => {
    applyTweaks(tweaks);
  }, []);

  useEffectApp(() => {
    // Load any extra fonts we offer in tweaks so switching actually changes something visible
    const extra = document.createElement('link');
    extra.rel = 'stylesheet';
    extra.href = 'https://fonts.googleapis.com/css2?family=Libre+Caslon+Text:ital,wght@0,400;0,700;1,400&family=Source+Serif+4:ital,opsz,wght@0,8..60,300..700;1,8..60,300..700&family=IBM+Plex+Sans:wght@300;400;500;600&display=swap';
    document.head.appendChild(extra);
  }, []);

  useEffectApp(() => {
    const onMessage = (ev) => {
      const d = ev?.data; if (!d || !d.type) return;
      if (d.type === '__activate_edit_mode') { setEditModeOn(true); setShowTweaks(true); }
      else if (d.type === '__deactivate_edit_mode') { setEditModeOn(false); setShowTweaks(false); }
    };
    window.addEventListener('message', onMessage);
    // announce availability only after listener is wired
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', onMessage);
  }, []);

  return (
    <RouteProvider>
      <App />
      {editModeOn && showTweaks && (
        <TweaksPanel tweaks={tweaks} setTweaks={setTweaks} onClose={() => setShowTweaks(false)} />
      )}
    </RouteProvider>
  );
}

// Because <App/> needs useRoute inside RouteProvider, we mount Root which wraps correctly.
ReactDOM.createRoot(document.getElementById('root')).render(<Root />);
