/* Tweaks — runtime palette/theme/typography switcher (lightweight) */
const { useState: useTweakState, useEffect: useTweakEffect } = React;

function applyTweaks(t) {
  const palettes = window.__PALETTES || {};
  const types = window.__TYPOGRAPHY || {};
  if (palettes[t.palette]) {
    document.documentElement.style.setProperty('--accent', palettes[t.palette].accent);
    document.documentElement.style.setProperty('--accent-dim', palettes[t.palette].dim);
    document.documentElement.style.setProperty('--accent-soft', palettes[t.palette].soft);
  }
  if (types[t.typography]) {
    document.documentElement.style.setProperty('--font-display', types[t.typography].display);
    document.documentElement.style.setProperty('--font-ui', types[t.typography].ui);
    document.documentElement.style.setProperty('--font-body', types[t.typography].ui);
  }
  if (t.theme) document.documentElement.setAttribute('data-theme', t.theme);
  try { localStorage.setItem('zg-tweaks', JSON.stringify(t)); } catch (e) {}
}

function useTweaks() {
  const [t, setT] = useTweakState(() => {
    try {
      const stored = localStorage.getItem('zg-tweaks');
      if (stored) return { ...(window.__TWEAK_DEFAULTS || {}), ...JSON.parse(stored) };
    } catch (e) {}
    return window.__TWEAK_DEFAULTS || {};
  });
  useTweakEffect(() => { applyTweaks(t); }, [t]);
  const set = (k, v) => setT(prev => {
    const next = typeof k === 'object' ? { ...prev, ...k } : { ...prev, [k]: v };
    try { window.parent.postMessage({type:'__edit_mode_set_keys', edits: typeof k === 'object' ? k : {[k]:v}}, '*'); } catch(e){}
    return next;
  });
  return [t, set];
}

function TweaksPanel({ t, set, onClose }) {
  const palettes = ['inkgold', 'emerald', 'plum'];
  const themes = ['dark', 'light'];
  const typos = ['editorial', 'modern'];
  return (
    <div style={{
      position: 'fixed', bottom: 24, insetInlineEnd: 24, zIndex: 1000,
      background: 'var(--bg-surface-solid)', border: '1px solid var(--border)',
      borderRadius: 8, padding: 20, width: 280, fontFamily: 'var(--font-ui)',
      boxShadow: '0 12px 40px rgba(0,0,0,.4)'
    }}>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:16}}>
        <div style={{fontFamily:'var(--font-mono)', fontSize:10, letterSpacing:'.18em', color:'var(--accent)'}}>TWEAKS</div>
        <button onClick={onClose} style={{all:'unset', cursor:'pointer', color:'var(--text-muted)', fontSize:18}}>×</button>
      </div>
      {[
        { label: 'Palette', key: 'palette', opts: palettes },
        { label: 'Theme', key: 'theme', opts: themes },
        { label: 'Type', key: 'typography', opts: typos },
      ].map(group => (
        <div key={group.key} style={{marginBottom:14}}>
          <div style={{fontSize:10, fontFamily:'var(--font-mono)', letterSpacing:'.14em', color:'var(--text-muted)', marginBottom:6, textTransform:'uppercase'}}>{group.label}</div>
          <div style={{display:'flex', gap:6, flexWrap:'wrap'}}>
            {group.opts.map(o => (
              <button key={o} onClick={() => set(group.key, o)} style={{
                all:'unset', cursor:'pointer', padding:'6px 12px', fontSize:11,
                border: '1px solid ' + (t[group.key] === o ? 'var(--accent)' : 'var(--border)'),
                background: t[group.key] === o ? 'var(--accent)' : 'transparent',
                color: t[group.key] === o ? 'var(--bg-primary)' : 'var(--text-secondary)',
                borderRadius: 4
              }}>{o}</button>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

function TweaksMount() {
  const [t, set] = useTweaks();
  const [open, setOpen] = useTweakState(false);
  useTweakEffect(() => {
    const handler = (e) => {
      if (e.data?.type === '__activate_edit_mode') setOpen(true);
      if (e.data?.type === '__deactivate_edit_mode') setOpen(false);
    };
    window.addEventListener('message', handler);
    try { window.parent.postMessage({type:'__edit_mode_available'}, '*'); } catch(e){}
    return () => window.removeEventListener('message', handler);
  }, []);
  return open ? <TweaksPanel t={t} set={set} onClose={() => { setOpen(false); try{window.parent.postMessage({type:'__edit_mode_dismissed'},'*')}catch(e){} }} /> : null;
}

window.useTweaks = useTweaks;
window.TweaksMount = TweaksMount;
