// ─────────────────────────────────────────────────────────────
// tweaks.jsx — Tweaks panel for The Ledger
// Reads/writes settings via setSettings callback (which persists to localStorage).
// ─────────────────────────────────────────────────────────────
const { TweaksPanel, TweakSection, TweakRadio, TweakToggle, TweakButton } = window;

function LedgerTweaks({ settings, setSettings, onClearData, onSignOut }) {
  const cats = window.LedgerStore.CATEGORIES;

  const swatchOptions = {
    basic:       ['var(--slate-700)', '#0F172A', '#475569', '#7B6450', '#a855f7'],
    education:   ['var(--info-500)',  '#1E3A8A', '#0EA5E9', '#10B981', '#9333ea'],
    wishes:      ['var(--brand-magenta)', '#BE123C', '#E11D48', '#7C3AED', '#EA580C'],
    investments: ['var(--positive-500)', '#047857', '#16A34A', '#0891B2', '#D97706'],
  };

  // Resolve a CSS var to a swatch we can show as a colored circle
  function resolveSwatch(token) {
    if (!token || !token.startsWith('var(')) return token;
    const name = token.slice(4, -1).trim();
    return getComputedStyle(document.documentElement).getPropertyValue(name).trim() || '#999';
  }

  function setCategoryColor(catId, value) {
    setSettings({ ...settings, categoryColors: { ...settings.categoryColors, [catId]: value } });
  }

  return (
    <TweaksPanel title="Ajustes">
      <TweakSection label="Visual" />
      <TweakRadio
        label="Estilo do gráfico"
        value={settings.chartStyle}
        options={[
          { value: 'bars',  label: 'Barras' },
          { value: 'lines', label: 'Linha' },
          { value: 'area',  label: 'Área' },
        ]}
        onChange={(v) => setSettings({ ...settings, chartStyle: v })}
      />
      <TweakToggle
        label="Modo escuro"
        value={settings.theme === 'dark'}
        onChange={(on) => setSettings({ ...settings, theme: on ? 'dark' : 'light' })}
      />

      <TweakSection label="Cores das categorias" />
      {cats.map(c => (
        <ColorSwatchRow
          key={c.id}
          label={c.name}
          value={settings.categoryColors[c.id]}
          options={swatchOptions[c.id]}
          resolveSwatch={resolveSwatch}
          onChange={(v) => setCategoryColor(c.id, v)}
        />
      ))}

      <TweakSection label="Dados" />
      <TweakButton label="Limpar todos os dados" onClick={onClearData} secondary />
      <TweakButton label="Sair" onClick={onSignOut} secondary />
    </TweaksPanel>
  );
}

// A swatch row that resolves CSS-var tokens to actual hex colors so the picker shows colors,
// but still stores the original token string so light/dark mode keeps working.
function ColorSwatchRow({ label, value, options, resolveSwatch, onChange }) {
  return (
    <div className="twk-row">
      <div className="twk-lbl"><span>{label}</span></div>
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
        {options.map(opt => {
          const hex = resolveSwatch(opt);
          const on = opt === value;
          return (
            <button
              key={opt}
              type="button"
              onClick={() => onChange(opt)}
              title={opt}
              style={{
                width: 22, height: 22, borderRadius: 6,
                background: hex,
                border: on ? '2px solid #000' : '1.5px solid rgba(0,0,0,0.18)',
                boxShadow: on ? '0 0 0 2px rgba(255,255,255,0.6)' : 'none',
                cursor: 'pointer',
                outline: 'none',
                padding: 0,
              }}
            />
          );
        })}
      </div>
    </div>
  );
}

window.LedgerTweaks = LedgerTweaks;
