// App shell + Tweaks

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "brass",
  "grain": 0.08,
  "palette": "ink",
  "fontPair": "fraunces-inter"
}/*EDITMODE-END*/;

const PALETTES = {
  ink:    { bg: '#0a0f1a', bgRaise: '#0e1422', ink: '#f0ece4', ink2: '#c9cdd6', mute: '#7a8599', mute2: '#4a5366' },
  forest: { bg: '#0a120f', bgRaise: '#0e1814', ink: '#ece8de', ink2: '#c3ccc0', mute: '#7a8a80', mute2: '#485248' },
  obsidian: { bg: '#0a0a0c', bgRaise: '#121214', ink: '#f2efe8', ink2: '#cacbd0', mute: '#7c7e85', mute2: '#484950' },
};
const ACCENTS = {
  brass:  'oklch(0.82 0.085 78)',
  sage:   'oklch(0.80 0.07 150)',
  amber:  'oklch(0.80 0.12 60)',
  slate:  'oklch(0.80 0.04 240)',
};
const FONT_PAIRS = {
  'fraunces-inter': { serif: "'Fraunces', 'Iowan Old Style', Georgia, serif", sans: "'Inter Tight', -apple-system, sans-serif" },
  'fraunces-mono':  { serif: "'Fraunces', Georgia, serif", sans: "'JetBrains Mono', ui-monospace, monospace" },
};

function applyTweaks(t) {
  const r = document.documentElement;
  const p = PALETTES[t.palette] || PALETTES.ink;
  r.style.setProperty('--bg', p.bg);
  r.style.setProperty('--bg-raise', p.bgRaise);
  r.style.setProperty('--ink', p.ink);
  r.style.setProperty('--ink-2', p.ink2);
  r.style.setProperty('--mute', p.mute);
  r.style.setProperty('--mute-2', p.mute2);
  r.style.setProperty('--accent', ACCENTS[t.accent] || ACCENTS.brass);
  const f = FONT_PAIRS[t.fontPair] || FONT_PAIRS['fraunces-inter'];
  r.style.setProperty('--serif', f.serif);
  r.style.setProperty('--sans', f.sans);
  r.style.setProperty('--grain-opacity', String(t.grain));
}

function TweaksPanel({ tweaks, setTweaks, onClose }) {
  const update = (k, v) => {
    const next = { ...tweaks, [k]: v };
    setTweaks(next);
    applyTweaks(next);
    try {
      window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { [k]: v } }, '*');
    } catch {}
  };
  const box = {
    position: 'fixed', bottom: 24, right: 24, zIndex: 10001,
    width: 320, background: 'rgba(14, 20, 34, 0.96)',
    backdropFilter: 'blur(16px)', border: '1px solid var(--rule-2)',
    padding: 20, fontFamily: 'var(--sans)', color: 'var(--ink)',
    boxShadow: '0 20px 60px rgba(0,0,0,0.5)',
  };
  const label = { fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.14em', color: 'var(--mute)', textTransform: 'uppercase', marginBottom: 10, display: 'block' };
  const chipRow = { display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 18 };
  const chip = (active) => ({
    padding: '6px 10px', fontSize: 11, fontFamily: 'var(--mono)',
    border: `1px solid ${active ? 'var(--accent)' : 'var(--rule-2)'}`,
    color: active ? 'var(--accent)' : 'var(--ink-2)',
    cursor: 'pointer', letterSpacing: '0.05em',
  });
  return (
    <div style={box}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18, paddingBottom: 14, borderBottom: '1px solid var(--rule)' }}>
        <span style={{ fontFamily: 'var(--serif)', fontSize: 16 }}>Tweaks</span>
        <button onClick={onClose} style={{ color: 'var(--mute)', fontSize: 18, lineHeight: 1 }}>×</button>
      </div>

      <span style={label}>Palette</span>
      <div style={chipRow}>
        {Object.keys(PALETTES).map(k => (
          <button key={k} style={chip(tweaks.palette === k)} onClick={() => update('palette', k)}>{k}</button>
        ))}
      </div>

      <span style={label}>Accent</span>
      <div style={chipRow}>
        {Object.keys(ACCENTS).map(k => (
          <button key={k} style={chip(tweaks.accent === k)} onClick={() => update('accent', k)}>
            <span style={{ display: 'inline-block', width: 8, height: 8, background: ACCENTS[k], marginRight: 6, verticalAlign: 'middle' }}></span>
            {k}
          </button>
        ))}
      </div>

      <span style={label}>Font pairing</span>
      <div style={chipRow}>
        {Object.keys(FONT_PAIRS).map(k => (
          <button key={k} style={chip(tweaks.fontPair === k)} onClick={() => update('fontPair', k)}>{k}</button>
        ))}
      </div>

      <span style={label}>Grain · {tweaks.grain.toFixed(2)}</span>
      <input type="range" min="0" max="0.25" step="0.01" value={tweaks.grain}
        onChange={e => update('grain', parseFloat(e.target.value))}
        style={{ width: '100%', accentColor: 'var(--accent)' }} />
    </div>
  );
}

function App() {
  const [tweaks, setTweaks] = React.useState(TWEAK_DEFAULTS);
  const [tweakOpen, setTweakOpen] = React.useState(false);

  React.useEffect(() => { applyTweaks(tweaks); }, []);

  // Handle initial load with hash (e.g. /#about) — React mounts after browser
  // tries to scroll, so do it manually once everything is rendered.
  React.useEffect(() => {
    const hash = window.location.hash.replace('#', '');
    if (!hash) return;
    const tryScroll = (attempt = 0) => {
      const el = document.getElementById(hash);
      if (el) {
        const top = el.getBoundingClientRect().top + window.pageYOffset - 64;
        window.scrollTo({ top, behavior: 'smooth' });
      } else if (attempt < 8) {
        setTimeout(() => tryScroll(attempt + 1), 100);
      }
    };
    setTimeout(() => tryScroll(), 120);
  }, []);

  React.useEffect(() => {
    const handler = (e) => {
      if (!e.data) return;
      if (e.data.type === '__activate_edit_mode') setTweakOpen(true);
      if (e.data.type === '__deactivate_edit_mode') setTweakOpen(false);
    };
    window.addEventListener('message', handler);
    try { window.parent.postMessage({ type: '__edit_mode_available' }, '*'); } catch {}
    return () => window.removeEventListener('message', handler);
  }, []);

  return (
    <>
      <Nav />
      <Hero />
      <Marquee />
      <WhenToBring />
      <Services />
      <Work />
      <Process />
      <About />
      <Contact />
      {tweakOpen && <TweaksPanel tweaks={tweaks} setTweaks={setTweaks} onClose={() => setTweakOpen(false)} />}
    </>
  );
}

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