// tweaks.jsx — Collapsible Tweaks panel

const { useState, useEffect } = React;

const TWEAK_DEFAULTS_BLOB = window.__TWEAK_DEFAULTS;

function TweakRow({ label, children }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '10px 14px', borderTop: '1px solid var(--tw-border)' }}>
      <span style={{ fontSize: 11, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--tw-dim)' }}>{label}</span>
      <div style={{ display: 'flex', gap: 4 }}>{children}</div>
    </div>
  );
}

function SegButton({ active, onClick, children, title }) {
  return (
    <button
      onClick={onClick}
      title={title}
      style={{
        fontFamily: 'inherit', fontSize: 11, letterSpacing: '0.02em',
        padding: '5px 9px', borderRadius: 4, cursor: 'pointer',
        border: '1px solid ' + (active ? 'var(--tw-fg)' : 'var(--tw-border)'),
        background: active ? 'var(--tw-fg)' : 'transparent',
        color: active ? 'var(--tw-bg)' : 'var(--tw-fg)',
        transition: 'all 120ms ease',
      }}
    >{children}</button>
  );
}

function Swatch({ color, active, onClick, label }) {
  return (
    <button onClick={onClick} title={label} style={{
      width: 22, height: 22, borderRadius: '50%', cursor: 'pointer',
      background: color,
      border: active ? '2px solid var(--tw-fg)' : '1px solid var(--tw-border)',
      outline: active ? '2px solid var(--tw-bg)' : 'none',
      outlineOffset: -4,
    }} />
  );
}

function TweaksPanel({ state, setState }) {
  const [open, setOpen] = useState(() => {
    try { return localStorage.getItem('yl_tweaks_open') !== 'false'; } catch { return true; }
  });

  useEffect(() => {
    try { localStorage.setItem('yl_tweaks_open', String(open)); } catch {}
  }, [open]);

  const [enabled, setEnabled] = useState(false);
  useEffect(() => {
    const handler = (e) => {
      if (e.data?.type === '__activate_edit_mode') setEnabled(true);
      if (e.data?.type === '__deactivate_edit_mode') setEnabled(false);
    };
    window.addEventListener('message', handler);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', handler);
  }, []);

  const update = (key, value) => {
    setState(prev => ({ ...prev, [key]: value }));
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { [key]: value } }, '*');
  };

  if (!enabled) return null;

  const ACCENTS = [
    { k: 'crimson', c: '#d83434', label: 'Crimson' },
    { k: 'marigold', c: '#e8a33d', label: 'Marigold' },
    { k: 'forest', c: '#2f5d3a', label: 'Forest' },
    { k: 'cobalt', c: '#2e52c7', label: 'Cobalt' },
    { k: 'ink', c: '#111111', label: 'Ink' },
  ];

  return (
    <div style={{
      position: 'fixed', right: 20, bottom: 20, zIndex: 9999,
      width: open ? 280 : 'auto',
      background: 'var(--tw-bg)', color: 'var(--tw-fg)',
      border: '1px solid var(--tw-border)',
      borderRadius: 8,
      fontFamily: 'var(--font-ui)',
      fontSize: 12,
      boxShadow: '0 12px 40px rgba(0,0,0,0.12)',
      overflow: 'hidden',
    }}>
      <button onClick={() => setOpen(!open)} style={{
        width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '10px 14px', background: 'transparent', border: 'none', cursor: 'pointer',
        color: 'var(--tw-fg)', fontFamily: 'inherit', fontSize: 11,
        letterSpacing: '0.08em', textTransform: 'uppercase',
      }}>
        <span>◐ Tweaks</span>
        <span style={{ color: 'var(--tw-dim)' }}>{open ? '−' : '+'}</span>
      </button>

      {open && (
        <div>
          <TweakRow label="Theme">
            <SegButton active={state.theme==='editorial'} onClick={() => update('theme','editorial')}>Editorial</SegButton>
            <SegButton active={state.theme==='magazine'} onClick={() => update('theme','magazine')}>Magazine</SegButton>
            <SegButton active={state.theme==='experimental'} onClick={() => update('theme','experimental')}>Dark</SegButton>
          </TweakRow>

          <TweakRow label="Font">
            <SegButton active={state.font==='grotesk'} onClick={() => update('font','grotesk')}>Grotesk</SegButton>
            <SegButton active={state.font==='serif'} onClick={() => update('font','serif')}>Serif</SegButton>
            <SegButton active={state.font==='mono'} onClick={() => update('font','mono')}>Mono</SegButton>
          </TweakRow>

          <TweakRow label="Accent">
            {ACCENTS.map(a => (
              <Swatch key={a.k} color={a.c} active={state.accent===a.k} onClick={() => update('accent',a.k)} label={a.label} />
            ))}
          </TweakRow>

          <TweakRow label="Density">
            <SegButton active={state.density==='tight'} onClick={() => update('density','tight')}>Tight</SegButton>
            <SegButton active={state.density==='normal'} onClick={() => update('density','normal')}>Normal</SegButton>
            <SegButton active={state.density==='airy'} onClick={() => update('density','airy')}>Airy</SegButton>
          </TweakRow>

          <TweakRow label="Grid">
            <SegButton active={state.grid==='uniform'} onClick={() => update('grid','uniform')}>Uniform</SegButton>
            <SegButton active={state.grid==='masonry'} onClick={() => update('grid','masonry')}>Masonry</SegButton>
            <SegButton active={state.grid==='mixed'} onClick={() => update('grid','mixed')}>Mixed</SegButton>
          </TweakRow>

          <TweakRow label="Mobile cols">
            <SegButton active={state.mobileCols===1} onClick={() => update('mobileCols', 1)}>1</SegButton>
            <SegButton active={state.mobileCols===2} onClick={() => update('mobileCols', 2)}>2</SegButton>
          </TweakRow>

          <TweakRow label="Aspect">
            <SegButton active={state.aspect==='4-3'} onClick={() => update('aspect','4-3')}>4:3</SegButton>
            <SegButton active={state.aspect==='3-2'} onClick={() => update('aspect','3-2')}>3:2</SegButton>
            <SegButton active={state.aspect==='1-1'} onClick={() => update('aspect','1-1')}>1:1</SegButton>
            <SegButton active={state.aspect==='native'} onClick={() => update('aspect','native')}>Native</SegButton>
          </TweakRow>

          <TweakRow label="Captions">
            <SegButton active={state.captions==='hidden'} onClick={() => update('captions','hidden')}>Off</SegButton>
            <SegButton active={state.captions==='hover'} onClick={() => update('captions','hover')}>Hover</SegButton>
            <SegButton active={state.captions==='always'} onClick={() => update('captions','always')}>On</SegButton>
          </TweakRow>
        </div>
      )}
    </div>
  );
}

window.TweaksPanel = TweaksPanel;
