/* global React */
// Tweaks panel — vary aesthetic, accent direction, density

const { useState } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "signalHue": "lime",
  "trustHue": "indigo",
  "density": "comfortable",
  "displayFont": "instrument"
}/*EDITMODE-END*/;

const SIGNAL_PALETTES = {
  lime:    { '--signal': '#C4F25E', '--signal-deep': '#91C92F' },
  amber:   { '--signal': '#F5C04A', '--signal-deep': '#C99A1F' },
  electric:{ '--signal': '#3DD9FF', '--signal-deep': '#0EA8D9' },
  coral:   { '--signal': '#FF9572', '--signal-deep': '#E8704A' },
};
const TRUST_PALETTES = {
  indigo:  { '--trust': '#1F3A5F', '--trust-2': '#2C4E78' },
  forest:  { '--trust': '#1F4231', '--trust-2': '#2D5942' },
  plum:    { '--trust': '#3F1F4A', '--trust-2': '#582B68' },
  graphite:{ '--trust': '#2A2823', '--trust-2': '#3D3A33' },
};
const DENSITY = {
  comfortable: { '--container': '1240px' },
  compact:     { '--container': '1080px' },
  wide:        { '--container': '1380px' },
};
const FONTS = {
  instrument: '"Instrument Serif", serif',
  newsreader: '"Newsreader", "Instrument Serif", serif',
  fraunces:   '"Fraunces", "Instrument Serif", serif',
};

function applyTweaks(t) {
  const root = document.documentElement.style;
  const sig = SIGNAL_PALETTES[t.signalHue] || SIGNAL_PALETTES.lime;
  const tr  = TRUST_PALETTES[t.trustHue]   || TRUST_PALETTES.indigo;
  const d   = DENSITY[t.density]           || DENSITY.comfortable;
  Object.entries(sig).forEach(([k, v]) => root.setProperty(k, v));
  Object.entries(tr).forEach(([k, v])  => root.setProperty(k, v));
  Object.entries(d).forEach(([k, v])   => root.setProperty(k, v));
  root.setProperty('--serif', FONTS[t.displayFont] || FONTS.instrument);
}

function MeceTweaks() {
  const [t, set] = useTweaks(TWEAK_DEFAULTS);
  const [visible, setVisible] = useState(false);

  React.useEffect(() => { applyTweaks(t); }, [t]);

  // Custom listener for visibility
  React.useEffect(() => {
    function onMsg(e) {
      if (e.data?.type === '__activate_edit_mode') setVisible(true);
      if (e.data?.type === '__deactivate_edit_mode') setVisible(false);
    }
    window.addEventListener('message', onMsg);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', onMsg);
  }, []);

  if (!visible) return null;

  function close() {
    setVisible(false);
    window.parent.postMessage({ type: '__edit_mode_dismissed' }, '*');
  }

  const setT = (k, v) => set({ [k]: v });

  return (
    <div style={{
      position: 'fixed', right: 24, bottom: 24, zIndex: 1000,
      width: 320,
      background: 'var(--paper)',
      border: '1px solid var(--line)',
      borderRadius: 16,
      padding: 18,
      boxShadow: '0 20px 60px -20px rgba(17,16,14,0.3)',
      fontFamily: 'var(--sans)',
    }}>
      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        marginBottom: 16,
      }}>
        <div style={{
          fontFamily: 'var(--serif)', fontStyle: 'italic',
          fontSize: 20, letterSpacing: '-0.01em',
        }}>Tweaks</div>
        <button onClick={close} style={{
          background: 'var(--bg)', border: '1px solid var(--line)',
          width: 24, height: 24, borderRadius: '50%',
          fontSize: 12, cursor: 'pointer', color: 'var(--ink-2)',
        }}>×</button>
      </div>

      <TweakSwatchRow label="signal hue · innovation"
        options={Object.entries(SIGNAL_PALETTES).map(([k, v]) => ({ k, color: v['--signal'] }))}
        value={t.signalHue} onChange={(v) => setT('signalHue', v)} />

      <TweakSwatchRow label="trust hue"
        options={Object.entries(TRUST_PALETTES).map(([k, v]) => ({ k, color: v['--trust'] }))}
        value={t.trustHue} onChange={(v) => setT('trustHue', v)} />

      <TweakOptRow label="density"
        options={['compact', 'comfortable', 'wide']}
        value={t.density} onChange={(v) => setT('density', v)} />

      <TweakOptRow label="display serif"
        options={['instrument', 'newsreader', 'fraunces']}
        value={t.displayFont} onChange={(v) => setT('displayFont', v)} />

      <div style={{
        fontFamily: 'var(--mono)', fontSize: 10,
        color: 'var(--ink-3)', letterSpacing: '0.04em',
        marginTop: 14, paddingTop: 14, borderTop: '1px solid var(--line)',
      }}>
        innovation × trust · live preview
      </div>
    </div>
  );
}

function useTweaks(defaults) {
  const [t, setT] = React.useState(defaults);
  function set(patchOrKey, maybeVal) {
    const patch = typeof patchOrKey === 'string' ? { [patchOrKey]: maybeVal } : patchOrKey;
    setT(prev => {
      const next = { ...prev, ...patch };
      try { window.parent.postMessage({ type: '__edit_mode_set_keys', edits: patch }, '*'); } catch {}
      return next;
    });
  }
  return [t, set];
}

function TweakSwatchRow({ label, options, value, onChange }) {
  return (
    <div style={{ marginBottom: 14 }}>
      <div style={{
        fontFamily: 'var(--mono)', fontSize: 10,
        textTransform: 'uppercase', letterSpacing: '0.08em',
        color: 'var(--ink-3)', marginBottom: 8,
      }}>{label}</div>
      <div style={{ display: 'flex', gap: 8 }}>
        {options.map(o => (
          <button key={o.k}
            onClick={() => onChange(o.k)}
            title={o.k}
            style={{
              width: 34, height: 34, borderRadius: 10,
              background: o.color,
              border: value === o.k ? '2px solid var(--ink)' : '2px solid var(--line)',
              cursor: 'pointer', padding: 0,
              outline: value === o.k ? '2px solid var(--paper)' : 'none',
              outlineOffset: -4,
            }}/>
        ))}
      </div>
    </div>
  );
}

function TweakOptRow({ label, options, value, onChange }) {
  return (
    <div style={{ marginBottom: 14 }}>
      <div style={{
        fontFamily: 'var(--mono)', fontSize: 10,
        textTransform: 'uppercase', letterSpacing: '0.08em',
        color: 'var(--ink-3)', marginBottom: 8,
      }}>{label}</div>
      <div style={{
        display: 'flex', gap: 0,
        background: 'var(--bg)', borderRadius: 999,
        padding: 3,
      }}>
        {options.map(o => (
          <button key={o}
            onClick={() => onChange(o)}
            style={{
              flex: 1, padding: '7px 10px',
              border: 'none',
              borderRadius: 999,
              background: value === o ? 'var(--ink)' : 'transparent',
              color: value === o ? 'var(--signal)' : 'var(--ink-2)',
              fontFamily: 'var(--mono)', fontSize: 11,
              cursor: 'pointer',
              transition: 'all .15s',
              letterSpacing: '0.02em',
            }}>
            {o}
          </button>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { MeceTweaks, applyTweaksDefaults: () => applyTweaks(TWEAK_DEFAULTS) });
