/* global React */
const { useState: tUseState, useEffect: tUseEffect } = React;

function Tweaks() {
  const [open, setOpen] = tUseState(false);
  const [vals, setVals] = tUseState(() => ({ ...(window.TWEAKS || {}) }));

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

  tUseEffect(() => {
    document.documentElement.style.setProperty('--accent', vals.accent);
    document.documentElement.setAttribute('data-theme', vals.theme);
    document.documentElement.setAttribute('data-density', vals.density);
  }, [vals]);

  const set = (patch) => {
    const next = { ...vals, ...patch };
    setVals(next);
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: patch }, '*');
  };

  if (!open) return null;

  const swatches = [
    { c: '#EC4E3C', name: 'Coral (logo)' },
    { c: '#E5A23C', name: 'Ámbar' },
    { c: '#5BAE74', name: 'Verde' },
    { c: '#6B6FE8', name: 'Lavanda' },
    { c: '#0B1540', name: 'Navy' },
  ];

  return (
    <div className="tweaks-panel">
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
        <div style={{ fontWeight: 600, fontSize: 14, letterSpacing: '-0.01em' }}>Tweaks</div>
        <div className="mono" style={{ fontSize: 10, color: 'var(--ink-low)', letterSpacing: '0.08em' }}>LIVE</div>
      </div>
      <div className="tweaks-row">
        <span>Acento</span>
        <div className="swatch-row">
          {swatches.map(s => (
            <button key={s.c} title={s.name} className={`swatch ${vals.accent === s.c ? 'active' : ''}`} style={{ background: s.c }} onClick={() => set({ accent: s.c })} />
          ))}
        </div>
      </div>
      <div className="tweaks-row">
        <span>Tema</span>
        <div className="seg">
          <button className={vals.theme === 'light' ? 'active' : ''} onClick={() => set({ theme: 'light' })}>LIGHT</button>
          <button className={vals.theme === 'dark' ? 'active' : ''} onClick={() => set({ theme: 'dark' })}>DARK</button>
        </div>
      </div>
      <div className="tweaks-row">
        <span>Densidad</span>
        <div className="seg">
          <button className={vals.density === 'comfortable' ? 'active' : ''} onClick={() => set({ density: 'comfortable' })}>CÓMODA</button>
          <button className={vals.density === 'compact' ? 'active' : ''} onClick={() => set({ density: 'compact' })}>COMPACTA</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Tweaks });
