// Tweaks panel — activates via toolbar toggle

function Tweaks() {
  const { theme, updateTheme, t } = useTheme();
  const [open, setOpen] = React.useState(false);

  React.useEffect(() => {
    const onMsg = (e) => {
      if (e.data?.type === '__activate_edit_mode') setOpen(true);
      if (e.data?.type === '__deactivate_edit_mode') setOpen(false);
    };
    window.addEventListener('message', onMsg);
    // announce availability AFTER listener is live
    try { window.parent.postMessage({ type: '__edit_mode_available' }, '*'); } catch {}
    return () => window.removeEventListener('message', onMsg);
  }, []);

  const set = (patch) => {
    updateTheme(patch);
    try { window.parent.postMessage({ type: '__edit_mode_set_keys', edits: patch }, '*'); } catch {}
  };

  if (!open) return null;

  const primaries = [
    { label: 'Medical Navy', v: '#0A3A5C' },
    { label: 'Clinical Blue', v: '#1A5FB4' },
    { label: 'Forest', v: '#1F5F4A' },
    { label: 'Plum', v: '#4A2B5C' },
    { label: 'Graphite', v: '#1F2933' },
  ];
  const accents = [
    { label: 'Coral', v: '#E85D4A' },
    { label: 'Amber', v: '#E5A23D' },
    { label: 'Teal', v: '#13A7A7' },
    { label: 'Rose', v: '#D94E7A' },
  ];

  return (
    <div className="tweaks-panel" style={{
      position: 'fixed', right: 20, bottom: 20, zIndex: 100, width: 300,
      background: '#fff', borderRadius: 14, border: '1px solid rgba(0,0,0,.08)',
      boxShadow: '0 10px 40px rgba(10,30,60,.18), 0 2px 6px rgba(10,30,60,.08)',
      fontFamily: "'Be Vietnam Pro', system-ui, sans-serif", color: '#0A1E2C',
      overflow: 'hidden',
    }}>
      <div style={{ padding: '12px 14px', borderBottom: '1px solid #EEF2F6', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ fontSize: 13, fontWeight: 700 }}>Tweaks</div>
        <div style={{ fontSize: 11, color: '#7C8A97' }}>Option A</div>
      </div>
      <div style={{ padding: 14, maxHeight: '70vh', overflowY: 'auto' }}>
        <Group label="Màu chính">
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {primaries.map(p => (
              <button key={p.v} onClick={() => set({ primary: p.v })} title={p.label} style={swatchStyle(p.v, theme.primary === p.v)}/>
            ))}
          </div>
        </Group>
        <Group label="Màu nhấn">
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {accents.map(p => (
              <button key={p.v} onClick={() => set({ accent: p.v })} title={p.label} style={swatchStyle(p.v, theme.accent === p.v)}/>
            ))}
          </div>
        </Group>
        <Group label={`Bo góc · ${theme.radius}px`}>
          <input type="range" min={4} max={20} step={2} value={theme.radius} onChange={e => set({ radius: +e.target.value })} style={{ width: '100%', accentColor: t.primary }}/>
        </Group>
        <Group label="Phong cách hero">
          {[['split','Split hero'],['center','Centered']].map(([v, l]) => (
            <label key={v} style={rowStyle}>
              <input type="radio" checked={theme.heroStyle === v} onChange={() => set({ heroStyle: v })} style={{ accentColor: t.primary }}/>
              <span style={{ fontSize: 12.5 }}>{l}</span>
            </label>
          ))}
        </Group>
        <Group label="Mật độ">
          {[['cozy','Thoáng'],['comfy','Chuẩn'],['compact','Chặt']].map(([v, l]) => (
            <label key={v} style={rowStyle}>
              <input type="radio" checked={theme.density === v} onChange={() => set({ density: v })} style={{ accentColor: t.primary }}/>
              <span style={{ fontSize: 12.5 }}>{l}</span>
            </label>
          ))}
        </Group>
        <button onClick={() => { updateTheme(THEME_DEFAULTS); set(THEME_DEFAULTS); }} style={{
          width: '100%', padding: '9px 12px', border: `1px solid ${t.border}`, borderRadius: 8,
          background: '#fff', fontSize: 12, cursor: 'pointer', color: t.textMuted, marginTop: 8,
        }}>Khôi phục mặc định</button>
      </div>
    </div>
  );
}

function Group({ label, children }) {
  return (
    <div style={{ marginBottom: 16 }}>
      <div style={{ fontSize: 10.5, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.8, color: '#7C8A97', marginBottom: 8 }}>{label}</div>
      {children}
    </div>
  );
}

const rowStyle = { display: 'flex', alignItems: 'center', gap: 8, padding: '3px 0', cursor: 'pointer' };

function swatchStyle(color, active) {
  return {
    width: 32, height: 32, borderRadius: 8, border: active ? '2px solid #0A1E2C' : '1px solid rgba(0,0,0,.12)',
    background: color, cursor: 'pointer', padding: 0, transition: 'transform .1s',
    outline: active ? '2px solid #fff' : 'none', outlineOffset: active ? -4 : 0,
  };
}

Object.assign(window, { Tweaks });
