// Cursor + reveal observer + Tweaks + App root
const { useEffect, useRef, useState } = React;

function useCursor() {
  useEffect(() => {
    if (!window.matchMedia('(hover: hover) and (pointer: fine)').matches) return;
    const dot = document.createElement('div');
    const ring = document.createElement('div');
    dot.className = 'cursor-dot'; ring.className = 'cursor-ring';
    document.body.appendChild(dot); document.body.appendChild(ring);
    let mx = -100, my = -100, rx = -100, ry = -100;
    const onMove = (e) => { mx = e.clientX; my = e.clientY; dot.style.transform = `translate(${mx}px, ${my}px)`; };
    const onOver = (e) => {
      const t = e.target.closest('[data-cursor], a, button, input, textarea');
      if (t) ring.classList.add('hover'); else ring.classList.remove('hover');
    };
    const loop = () => {
      rx += (mx - rx) * 0.18;
      ry += (my - ry) * 0.18;
      ring.style.transform = `translate(${rx}px, ${ry}px)`;
      requestAnimationFrame(loop);
    };
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseover', onOver);
    loop();
    return () => {
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('mouseover', onOver);
      dot.remove(); ring.remove();
    };
  }, []);
}

function useReveal() { /* CSS-only now; kept as no-op for compatibility */ }

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "default",
  "lang": "pt"
}/*EDITMODE-END*/;

function TweaksPanel({ visible, theme, setTheme, lang, setLang }) {
  if (!visible) return null;
  return (
    <div className="tweaks-panel">
      <div className="tweaks-head mono">TWEAKS</div>
      <div className="tweaks-body">
        <div className="tweaks-group">
          <div className="tweaks-label mono">Theme</div>
          <div className="tweaks-row">
            {[
              { id: 'default', swatch: ['#0a0b0a', 'oklch(0.88 0.22 130)'] },
              { id: 'midnight', swatch: ['#06070d', 'oklch(0.78 0.18 280)'] },
              { id: 'ivory', swatch: ['#f1ede4', 'oklch(0.55 0.18 28)'] }
            ].map(o => (
              <button key={o.id} className={`swatch ${theme === o.id ? 'on' : ''}`} onClick={() => setTheme(o.id)}>
                <span style={{background: o.swatch[0]}} /><span style={{background: o.swatch[1]}} />
                <span className="swatch-name mono">{o.id}</span>
              </button>
            ))}
          </div>
        </div>
        <div className="tweaks-group">
          <div className="tweaks-label mono">Language</div>
          <div className="tweaks-row">
            <button className={`pill ${lang === 'pt' ? 'on' : ''}`} onClick={() => setLang('pt')}>Português</button>
            <button className={`pill ${lang === 'en' ? 'on' : ''}`} onClick={() => setLang('en')}>English</button>
          </div>
        </div>
      </div>
    </div>
  );
}

function App() {
  const [lang, setLang] = useState(() => localStorage.getItem('cerne_lang') || TWEAK_DEFAULTS.lang);
  const [theme, setTheme] = useState(() => localStorage.getItem('cerne_theme') || TWEAK_DEFAULTS.theme);
  const [editMode, setEditMode] = useState(false);

  useEffect(() => { localStorage.setItem('cerne_lang', lang); }, [lang]);
  useEffect(() => {
    localStorage.setItem('cerne_theme', theme);
    document.body.classList.remove('theme-default', 'theme-midnight', 'theme-ivory');
    document.body.classList.add(`theme-${theme}`);
  }, [theme]);

  useCursor();
  useReveal();

  // Tweaks host bridge
  useEffect(() => {
    const onMsg = (e) => {
      const d = e.data || {};
      if (d.type === '__activate_edit_mode') setEditMode(true);
      if (d.type === '__deactivate_edit_mode') setEditMode(false);
    };
    window.addEventListener('message', onMsg);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', onMsg);
  }, []);

  const persist = (key, val) => {
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { [key]: val } }, '*');
  };

  const t = window.CERNE_I18N[lang];

  return (
    <>
      <div className="noise" />
      <Nav t={t} lang={lang} setLang={(l) => { setLang(l); persist('lang', l); }} />
      <Hero t={t} lang={lang} />
      <StatsStrip t={t} />
      <Services t={t} />
      <Work t={t} lang={lang} />
      <Process t={t} />
      <Lab t={t} lang={lang} />
      <Stack t={t} />
      <Faq t={t} />
      <Contact t={t} lang={lang} />
      <Footer t={t} />
      <TweaksPanel
        visible={editMode}
        theme={theme}
        setTheme={(v) => { setTheme(v); persist('theme', v); }}
        lang={lang}
        setLang={(v) => { setLang(v); persist('lang', v); }}
      />
    </>
  );
}

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