const { useState: useTweaksState, useEffect: useTweaksEffect } = React;

const THEMES = [
  { id: 'warm',  name: 'Warm',  swatches: ['#F4EFE6', '#F23827', '#00B8D4', '#F5C518'] },
  { id: 'neon',  name: 'Neon',  swatches: ['#0a0a0f', '#FF2D6F', '#00F0FF', '#E8FF3A'] },
  { id: 'lofi',  name: 'Lo-fi', swatches: ['#E8DFCB', '#C94F3A', '#6B8E9B', '#C8A94A'] },
  { id: 'y2k',   name: 'Y2K',   swatches: ['#F7F1FB', '#FF3DB1', '#2DD4FF', '#9B3DFF'] },
];

function Tweaks() {
  const [theme, setTheme]     = useTweaksState(localStorage.getItem('umbmp.theme') || 'warm');
  const [scan,  setScan]      = useTweaksState(+(localStorage.getItem('umbmp.scan') ?? 0.5));
  const [open,  setOpen]      = useTweaksState(true);

  useTweaksEffect(() => {
    document.documentElement.setAttribute('data-theme', theme);
    localStorage.setItem('umbmp.theme', theme);
  }, [theme]);

  useTweaksEffect(() => {
    document.documentElement.style.setProperty('--scanline-opacity', String(scan));
    localStorage.setItem('umbmp.scan', String(scan));
  }, [scan]);

  if (!open) return (
    <button
      className="btn"
      style={{ position: 'fixed', bottom: 24, right: 24, zIndex: 1000 }}
      onClick={() => setOpen(true)}
    >⚙ Tweaks</button>
  );

  return (
    <div className="tweaks-panel">
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
        <h5>Tweaks</h5>
        <button
          onClick={() => setOpen(false)}
          style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 18, lineHeight: 1 }}
        >×</button>
      </div>

      <div className="row">
        <label>Vibe / palette</label>
        <div className="swatches">
          {THEMES.map(t => (
            <button
              key={t.id}
              className={theme === t.id ? 'active' : ''}
              onClick={() => setTheme(t.id)}
              style={{
                background: `linear-gradient(135deg, ${t.swatches[0]} 0%, ${t.swatches[0]} 50%, ${t.swatches[1]} 50%, ${t.swatches[1]} 75%, ${t.swatches[2]} 75%, ${t.swatches[2]} 90%, ${t.swatches[3]} 90%)`,
                color: t.id === 'neon' ? '#fff' : '#111',
              }}
            >
              <span style={{ background: 'rgba(255,255,255,0.85)', color: '#111', padding: '2px 6px', borderRadius: 4 }}>{t.name}</span>
            </button>
          ))}
        </div>
      </div>

      <div className="row">
        <label>Scanline grain ({Math.round(scan * 100)}%)</label>
        <input type="range" min="0" max="1" step="0.05" value={scan} onChange={e => setScan(+e.target.value)} />
      </div>

      <div className="row" style={{ marginBottom: 0, fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--muted)', letterSpacing: '0.1em', textTransform: 'uppercase' }}>
        Tip: drag the knobs in Studio →
      </div>
    </div>
  );
}

window.Tweaks = Tweaks;
