function Tweaks() {
  const [open, setOpen] = React.useState(false);
  const [active, setActive] = React.useState(false);
  const [state, setState] = React.useState(window.__TWEAKS__ || {});

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

  React.useEffect(() => {
    applyAll(state);
  }, [state]);

  function applyAll(s) {
    document.documentElement.setAttribute('data-palette', s.palette || 'terracota');
    document.documentElement.setAttribute('data-title-font', s.titleFont || 'dm-serif');
    document.documentElement.setAttribute('data-grain', String(s.showGrain !== false));
  }

  function set(k, v) {
    const next = { ...state, [k]: v };
    setState(next);
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { [k]: v } }, '*');
  }

  if (!active) return null;

  const panel = {
    position: 'fixed', bottom: 20, right: 20, zIndex: 200,
    background: 'var(--cream)', border: '1px solid var(--ink)',
    fontFamily: "'Inter', sans-serif", fontSize: 13,
    width: open ? 320 : 'auto',
    boxShadow: '0 20px 40px -10px rgba(0,0,0,.25)',
  };
  const head = {
    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
    padding: '12px 16px', borderBottom: open ? '1px solid var(--line)' : 'none',
    cursor: 'pointer',
  };
  const row = { padding: '14px 16px', borderBottom: '1px solid var(--line)' };
  const label = {
    fontFamily: "'JetBrains Mono', monospace", fontSize: 10,
    letterSpacing: '0.14em', textTransform: 'uppercase',
    color: 'var(--ink-soft)', marginBottom: 8, display: 'block',
  };
  const chipRow = { display: 'flex', gap: 6, flexWrap: 'wrap' };
  const chip = (active) => ({
    padding: '6px 12px', border: '1px solid var(--ink)',
    background: active ? 'var(--ink)' : 'transparent',
    color: active ? 'var(--cream)' : 'var(--ink)',
    fontFamily: "'Inter', sans-serif", fontSize: 12,
    cursor: 'pointer', borderRadius: 0,
  });

  const palettes = [
    { id: 'terracota', label: 'Terracota', c1: '#F2EADB', c2: '#B4532A' },
    { id: 'verde',     label: 'Verde musgo', c1: '#EDEBDD', c2: '#546B3A' },
    { id: 'cafe',      label: 'Café', c1: '#E9DFCA', c2: '#4E2A15' },
  ];

  return (
    <div style={panel}>
      <div style={head} onClick={() => setOpen(!open)}>
        <span className="mono" style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase' }}>
          Tweaks
        </span>
        <span style={{ fontSize: 14 }}>{open ? '−' : '+'}</span>
      </div>
      {open && (
        <>
          <div style={row}>
            <span style={label}>Paleta</span>
            <div style={chipRow}>
              {palettes.map(p => (
                <button key={p.id} onClick={() => set('palette', p.id)} style={{
                  ...chip(state.palette === p.id),
                  display: 'flex', alignItems: 'center', gap: 8,
                }}>
                  <span style={{
                    display: 'inline-block', width: 10, height: 10,
                    background: `linear-gradient(135deg, ${p.c1} 50%, ${p.c2} 50%)`,
                    border: '1px solid rgba(0,0,0,0.2)',
                  }}/>
                  {p.label}
                </button>
              ))}
            </div>
          </div>

          <div style={row}>
            <span style={label}>Tipografia de títulos</span>
            <div style={chipRow}>
              {[
                { id: 'dm-serif', label: 'DM Serif' },
                { id: 'instrument', label: 'Instrument' },
              ].map(f => (
                <button key={f.id} onClick={() => set('titleFont', f.id)}
                  style={chip(state.titleFont === f.id)}>
                  {f.label}
                </button>
              ))}
            </div>
          </div>

          <div style={{ ...row, borderBottom: 'none' }}>
            <label style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer' }}>
              <input type="checkbox" checked={state.showGrain !== false}
                onChange={e => set('showGrain', e.target.checked)} />
              <span>Textura granulada no fundo</span>
            </label>
          </div>
        </>
      )}
    </div>
  );
}

window.Tweaks = Tweaks;
