// Global Tweaks state + panel. Controls theme, density, accent, plan tier.
// Each variation reads from window.TWEAKS and re-renders on 'tweaks:change'.

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "dark",
  "density": "cozy",
  "accent": "#4ecdc4",
  "tier": "Growth",
  "demo": "filler"
}/*EDITMODE-END*/;

window.TWEAKS = { ...TWEAK_DEFAULTS };

function applyTweaks(next) {
  window.TWEAKS = { ...window.TWEAKS, ...next };
  // Mark which tweaks the user has hand-touched so per-client branding
  // doesn't stomp them on next load.
  if ('accent' in next) localStorage.setItem('somAccentTouched', '1');
  if ('tier' in next) localStorage.setItem('somTierTouched', '1');
  window.dispatchEvent(new CustomEvent('tweaks:change', { detail: window.TWEAKS }));
  if (window.parent && window.parent !== window) {
    try {
      window.parent.postMessage({ type: '__edit_mode_set_keys', edits: next }, '*');
    } catch (e) {}
  }
}
window.applyTweaks = applyTweaks;

// Hook: subscribe to tweaks and re-render.
function useTweaks() {
  const [, force] = React.useReducer(x => x + 1, 0);
  React.useEffect(() => {
    const h = () => force();
    window.addEventListener('tweaks:change', h);
    return () => window.removeEventListener('tweaks:change', h);
  }, []);
  return window.TWEAKS;
}
window.useTweaks = useTweaks;

const ACCENT_SWATCHES = [
  { name: "Teal", val: "#4ecdc4" },
  { name: "Sky", val: "#5aa9e6" },
  { name: "Gold", val: "#e7b56b" },
  { name: "Lime", val: "#a8d66a" },
  { name: "Coral", val: "#ff8b6b" },
  { name: "Violet", val: "#a78bfa" },
];

function TweaksPanel() {
  const t = useTweaks();
  const [open, setOpen] = React.useState(true);
  const [visible, setVisible] = React.useState(false);

  React.useEffect(() => {
    const onMsg = (e) => {
      if (!e.data || typeof e.data !== 'object') return;
      if (e.data.type === '__activate_edit_mode') setVisible(true);
      if (e.data.type === '__deactivate_edit_mode') setVisible(false);
    };
    window.addEventListener('message', onMsg);
    try { window.parent.postMessage({ type: '__edit_mode_available' }, '*'); } catch (e) {}
    // default to visible on load so user sees it (dev)
    setVisible(true);
    return () => window.removeEventListener('message', onMsg);
  }, []);

  if (!visible) return null;

  const panelStyle = {
    position: 'fixed', bottom: 16, right: 16, zIndex: 9999,
    width: open ? 272 : 44, maxHeight: '80vh', overflow: 'auto',
    background: 'rgba(255,255,255,0.98)',
    backdropFilter: 'blur(10px)',
    border: '1px solid rgba(18,37,61,0.12)',
    borderRadius: 14,
    boxShadow: '0 20px 60px rgba(18,37,61,0.18)',
    fontFamily: '-apple-system, BlinkMacSystemFont, "Plus Jakarta Sans", system-ui, sans-serif',
    color: '#12253d',
    transition: 'width .2s ease',
  };

  if (!open) {
    return (
      <div style={panelStyle}>
        <button onClick={() => setOpen(true)} title="Tweaks" style={{
          width: 44, height: 44, border: 'none', background: 'transparent',
          cursor: 'pointer', fontSize: 18, color: '#12253d',
        }}>⚙</button>
      </div>
    );
  }

  return (
    <div style={panelStyle}>
      <div style={{ padding: '12px 16px', borderBottom: '1px solid rgba(18,37,61,0.08)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: '#12253d' }}>Tweaks</div>
        <button onClick={() => setOpen(false)} style={{ border: 'none', background: 'transparent', cursor: 'pointer', fontSize: 16, color: '#6b7c8a' }}>–</button>
      </div>

      <div style={{ padding: '14px 16px' }}>
        <Group label="Theme">
          <Seg options={[['light','Light'],['dark','Dark']]} value={t.theme} onChange={v => applyTweaks({ theme: v })} />
        </Group>

        <Group label="Density">
          <Seg options={[['cozy','Cozy'],['compact','Compact']]} value={t.density} onChange={v => applyTweaks({ density: v })} />
        </Group>

        <Group label="Client plan tier">
          <Seg options={[['Essentials','Essentials'],['Growth','Growth'],['Stewardship','Stewardship']]} value={t.tier} onChange={v => applyTweaks({ tier: v })} />
        </Group>

        <Group label="Demo data">
          <Seg options={[['filler','Active client'],['clean','Brand new']]} value={t.demo} onChange={v => applyTweaks({ demo: v })} />
        </Group>

        <Group label="Accent color">
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {ACCENT_SWATCHES.map(s => (
              <button key={s.val}
                onClick={() => applyTweaks({ accent: s.val })}
                title={s.name}
                style={{
                  width: 28, height: 28, borderRadius: '50%', cursor: 'pointer',
                  background: s.val,
                  border: t.accent === s.val ? '2px solid #12253d' : '2px solid rgba(0,0,0,0)',
                  outline: '1px solid rgba(18,37,61,0.12)',
                  padding: 0,
                }} />
            ))}
          </div>
        </Group>
      </div>
    </div>
  );
}

function Group({ label, children }) {
  return (
    <div style={{ marginBottom: 14 }}>
      <div style={{ fontSize: 11, fontWeight: 600, color: '#6b7c8a', marginBottom: 6, letterSpacing: '0.04em', textTransform: 'uppercase' }}>{label}</div>
      {children}
    </div>
  );
}

function Seg({ options, value, onChange }) {
  return (
    <div style={{ display: 'flex', background: 'rgba(18,37,61,0.06)', borderRadius: 8, padding: 3, gap: 2 }}>
      {options.map(([v, label]) => (
        <button key={v}
          onClick={() => onChange(v)}
          style={{
            flex: 1,
            padding: '6px 8px',
            border: 'none',
            background: value === v ? '#fff' : 'transparent',
            color: value === v ? '#12253d' : '#6b7c8a',
            boxShadow: value === v ? '0 1px 3px rgba(18,37,61,0.1)' : 'none',
            borderRadius: 6,
            fontSize: 11,
            fontWeight: 600,
            cursor: 'pointer',
            letterSpacing: '0.02em',
          }}>{label}</button>
      ))}
    </div>
  );
}

window.TweaksPanel = TweaksPanel;
