/* Dump — settings.jsx: slide-in panel / bottom sheet */

function SettingsPanel() {
  const state = useDumpStore();
  const { settings, sessionTokens } = state;
  const [keyDraft, setKeyDraft] = useState('');
  const [clientDraft, setClientDraft] = useState(settings.googleClientId || '');
  const [newCat, setNewCat] = useState('');
  const [childName, setChildName] = useState('');
  const [childLabel, setChildLabel] = useState('');

  const children = settings.children || [];
  const addChild = () => {
    const n = childName.trim();
    if (!n) return;
    if (children.some((c) => c.name.toLowerCase() === n.toLowerCase())) { DumpAPI.toast('That name is already added.'); return; }
    DumpStore.set((s) => ({ settings: { ...s.settings, children: (s.settings.children || []).concat([{ id: DumpUtil.uid(), name: n, label: childLabel.trim() }]) } }));
    setChildName(''); setChildLabel('');
  };
  const removeChild = (id) => DumpStore.set((s) => ({ settings: { ...s.settings, children: (s.settings.children || []).filter((c) => c.id !== id) } }));

  const close = () => DumpStore.set({ settingsOpen: false });

  useEffect(() => {
    const onEsc = (e) => { if (e.key === 'Escape') close(); };
    document.addEventListener('keydown', onEsc);
    return () => document.removeEventListener('keydown', onEsc);
  }, []);

  const saveKey = () => {
    const k = keyDraft.trim();
    if (!k) { DumpAPI.toast('Paste a key first.'); return; }
    DumpStore.set((s) => ({ settings: { ...s.settings, anthropicKey: k, useAI: true } }));
    setKeyDraft('');
    DumpAPI.toast('API key saved — AI sorting on.');
  };
  const clearKey = () => {
    DumpStore.set((s) => ({ settings: { ...s.settings, anthropicKey: '' } }));
    DumpAPI.toast('API key removed — back to the built-in sorter.');
  };

  const saveClientId = () => {
    DumpStore.set((s) => ({ settings: { ...s.settings, googleClientId: clientDraft.trim() } }));
    DumpAPI.toast(clientDraft.trim() ? 'Google Client ID saved.' : 'Google Client ID cleared.');
  };

  const addCat = () => {
    const c = newCat.trim();
    if (!c) return;
    if (settings.categories.some((x) => x.toLowerCase() === c.toLowerCase())) {
      DumpAPI.toast('That category already exists.');
      return;
    }
    DumpStore.set((s) => ({ settings: { ...s.settings, categories: s.settings.categories.concat([c]) } }));
    setNewCat('');
  };
  const removeCat = (c) => {
    if (settings.categories.length <= 1) { DumpAPI.toast('Keep at least one category.'); return; }
    DumpStore.set((s) => ({ settings: { ...s.settings, categories: s.settings.categories.filter((x) => x !== c) } }));
  };

  const savedKey = settings.anthropicKey ? settings.anthropicKey.trim() : '';

  return (
    <React.Fragment>
      <div className="overlay" onClick={close}></div>
      <div className="settings-panel" role="dialog" aria-label="Settings" data-screen-label="Settings">
        <div className="settings-head">
          <h2>Settings</h2>
          <button className="icon-btn" onClick={close} aria-label="Close settings">{Icons.x(18)}</button>
        </div>
        <div className="settings-body">

          <div className="set-group">
            <label className="set-label">Appearance</label>
            <div className="seg">
              <button
                className={settings.theme !== 'dark' ? 'active' : ''}
                onClick={() => DumpStore.set((s) => ({ settings: { ...s.settings, theme: 'light' } }))}>
                {Icons.sun ? Icons.sun(13) : null} Light
              </button>
              <button
                className={settings.theme === 'dark' ? 'active' : ''}
                onClick={() => DumpStore.set((s) => ({ settings: { ...s.settings, theme: 'dark' } }))}>
                {Icons.moon ? Icons.moon(13) : null} Dark
              </button>
            </div>
            <p className="set-hint">Switch between light and dark. Your brand colours keep their meaning in both.</p>
          </div>

          <div className="set-group">
            <label className="set-label">Daily anchors</label>
            <div className="set-row">
              <button className="btn btn-sm" onClick={() => DumpStore.set({ settingsOpen: false, route: 'anchors' })}>{Icons.calendar(14)} Edit the shape of your day</button>
            </div>
            <p className="set-hint">The fixed blocks — school run, work, bedtime — the calendar uses to show how much time you actually have free.</p>
          </div>

          <div className="set-group">
            <label className="set-label">Look &amp; feel</label>
            <p className="set-hint">Visual options — accent, fonts, capacity gauge, calendar hours — now live in the <strong>Tweaks</strong> panel (toggle it from the toolbar), so there's one home for how Enstow looks.</p>
          </div>

          <div className="set-group">
            <label className="set-label" htmlFor="set-name">Your name</label>
            <div className="set-row">
              <input id="set-name" type="text" placeholder="What should we call you?"
                value={settings.userName || ''}
                onChange={(e) => DumpStore.set((s) => ({ settings: { ...s.settings, userName: e.target.value } }))} />
            </div>
            <p className="set-hint">Used to greet you on the Today screen. Leave blank for a neutral greeting.</p>
          </div>

          <div className="set-group">
            <label className="set-label">My children</label>
            {children.length ? (
              <div className="child-list">
                {children.map((c) => (
                  <div className="child-row" key={c.id}>
                    <span className="child-name">{c.name}</span>
                    {c.label ? <span className="child-class">{c.label}</span> : null}
                    <button className="x" onClick={() => removeChild(c.id)} aria-label={'Remove ' + c.name}>×</button>
                  </div>
                ))}
              </div>
            ) : null}
            <div className="set-row child-add">
              <input type="text" placeholder="Name or nickname" value={childName}
                onChange={(e) => setChildName(e.target.value)}
                onKeyDown={(e) => { if (e.key === 'Enter') addChild(); }} />
              <input type="text" placeholder="Class / year (optional)" value={childLabel} style={{ flex: '0 1 150px' }}
                onChange={(e) => setChildLabel(e.target.value)}
                onKeyDown={(e) => { if (e.key === 'Enter') addChild(); }} />
              <button className="btn btn-sm" onClick={addChild}>Add</button>
            </div>
            <p className="set-hint">Add each child by name or a private nickname. When a letter or task is about “the kids,” Enstow can ask which one — and a class or year helps it match automatically.</p>
          </div>

          <div className="set-group">
            <label className="set-label">AI sorting</label>
            <div className="edit-row" style={{ gap: 12 }}>
              <span className="mode-toggle" onClick={() => DumpStore.set((s) => ({ settings: { ...s.settings, useAI: !s.settings.useAI } }))}>
                <span className={'switch' + (settings.useAI ? ' on' : '')}></span>
                Use AI for sorting, clarify &amp; digests
              </span>
            </div>
            <div className="set-row" style={{ marginTop: 10 }}>
              <input id="set-key" type="password" aria-label="Anthropic API key" placeholder={savedKey ? 'Replace key…' : 'sk-ant-…'}
                value={keyDraft} onChange={(e) => setKeyDraft(e.target.value)} />
              <button className="btn btn-sm" onClick={saveKey}>Save</button>
            </div>
            <p className="set-hint">
              {settings.useAI && !savedKey
                ? <span style={{ color: 'var(--priority)' }}>Add an Anthropic key to switch on AI — until then, the built-in sorter runs.</span>
                : savedKey
                  ? <span>Key ending in <strong>…{savedKey.slice(-4)}</strong> · <button className="linklike" onClick={clearKey}>remove</button>. {settings.useAI ? 'AI is on (~$0.002 a dump).' : 'Toggle on to use it.'}</span>
                  : 'Off: instant built-in sorter — no key, no cost. On + a key: real AI sorting.'}
            </p>
            <p className="set-cost-note">Typical dump ≈ $0.002 with your own key · demo mode is free.</p>
          </div>

          <div className="set-group">
            <label className="set-label">Connections</label>
            <div className="edit-row" style={{ gap: 12 }}>
              <span className="mode-toggle" onClick={() => DumpStore.set((s) => ({ settings: { ...s.settings, simConnections: !s.settings.simConnections } }))}>
                <span className={'switch' + (settings.simConnections ? ' on' : '')}></span>
                Simulate connections (Calendar, Gmail, Slack)
              </span>
            </div>
            <p className="set-hint">{settings.simConnections
              ? 'Connections use built-in demo data — fake OAuth, no real accounts. Works alongside real AI, so you can demo Calendar while sorting for real.'
              : 'Connections use real OAuth (Google Client ID required for Calendar & Gmail).'}</p>
          </div>

          <div className="set-group">
            <label className="set-label">Demo data</label>
            <div className="set-row">
              <button className="btn btn-sm" onClick={() => { DumpDemo.load(); DumpStore.set({ settingsOpen: false, route: 'tasks' }); }}>Load demo data</button>
              <button className="btn btn-sm btn-ghost btn-danger-ghost" onClick={() => { if (window.confirm('Reset the demo? This clears all tasks, history and connections.')) DumpDemo.reset(); }}>Reset demo</button>
            </div>
            <div className="set-row" style={{ marginTop: 8 }}>
              <button className="btn btn-sm btn-ghost" onClick={() => { DumpStore.set({ settingsOpen: false }); setTimeout(() => window.__previewOnboarding && window.__previewOnboarding(), 120); }}>{Icons.capture(13)} Preview onboarding</button>
              <button className="btn btn-sm btn-ghost" onClick={() => { DumpStore.set({ settingsOpen: false }); setTimeout(() => window.__startTour && window.__startTour(), 150); }}>{Icons.sparkle(13)} Take the tour</button>
            </div>
            <p className="set-hint">Load fills the board with a lived-in week for Jess (the demo persona). Reset wipes everything back to a clean start. Preview onboarding overlays the first-run flow without touching any data. Take the tour walks you through the whole app.</p>
          </div>

          <div className="set-group">
            <label className="set-label">Clarify style</label>
            <div className="seg">
              <button
                className={settings.clarifyMode !== 'chat' ? 'active' : ''}
                onClick={() => DumpStore.set((s) => ({ settings: { ...s.settings, clarifyMode: 'cards' } }))}>
                {Icons.file(13)} Cards
              </button>
              <button
                className={settings.clarifyMode === 'chat' ? 'active' : ''}
                onClick={() => DumpStore.set((s) => ({ settings: { ...s.settings, clarifyMode: 'chat' } }))}>
                {Icons.chat(13)} Chat
              </button>
            </div>
            <p className="set-hint">
              How you're asked about vague items after a dump. Cards: one item at a time, form-style. Chat: a brief back-and-forth — max two exchanges per item.
            </p>
          </div>

          <div className="set-group">
            <label className="set-label">Keep done tasks for</label>
            <div className="seg">
              {[{ v: 14, l: '14 days' }, { v: 30, l: '30 days' }, { v: 90, l: '90 days' }, { v: 0, l: 'Forever' }].map((o) => (
                <button key={o.v}
                  className={(settings.doneRetention || 0) === o.v ? 'active' : ''}
                  onClick={() => DumpAPI.setDoneRetention(o.v)}>
                  {o.l}
                </button>
              ))}
            </div>
            <p className="set-hint">
              How long finished tasks stay on the Done page before clearing themselves. Your all-time finished count is always kept.
            </p>
          </div>

          <div className="set-group">
            <label className="set-label">Pomodoro timer</label>
            <div className="set-row">
              <label className="set-inline-label">Work session</label>
              <input type="number" min="5" max="90" className="set-num" value={settings.pomodoroWork}
                onChange={(e) => DumpStore.set((s) => ({ settings: { ...s.settings, pomodoroWork: Math.min(90, Math.max(5, parseInt(e.target.value, 10) || 25)) } }))} />
              <span className="set-hint-inline">min</span>
            </div>
            <div className="set-row">
              <label className="set-inline-label">Short break</label>
              <input type="number" min="1" max="30" className="set-num" value={settings.pomodoroBreak}
                onChange={(e) => DumpStore.set((s) => ({ settings: { ...s.settings, pomodoroBreak: Math.min(30, Math.max(1, parseInt(e.target.value, 10) || 5)) } }))} />
              <span className="set-hint-inline">min</span>
            </div>
            <div className="set-row">
              <label className="set-inline-label">Long break</label>
              <input type="number" min="5" max="60" className="set-num" value={settings.pomodoroLongBreak}
                onChange={(e) => DumpStore.set((s) => ({ settings: { ...s.settings, pomodoroLongBreak: Math.min(60, Math.max(5, parseInt(e.target.value, 10) || 15)) } }))} />
              <span className="set-hint-inline">min (after every {settings.pomodoroLongAfter})</span>
            </div>
            <p className="set-hint">Standard Pomodoro is 25 min work / 5 min break / 15 min long break after 4 sessions.</p>
          </div>

          <div className="set-group">
            <label className="set-label" htmlFor="set-gcid">Google Client ID</label>
            <div className="set-row">
              <input id="set-gcid" type="text" placeholder="1234…apps.googleusercontent.com"
                value={clientDraft} onChange={(e) => setClientDraft(e.target.value)} />
              <button className="btn btn-sm" onClick={saveClientId}>Save</button>
            </div>
            <p className="set-hint">Needed for Google Calendar and Gmail. From Google Cloud Console → OAuth credentials.</p>
          </div>

          <div className="set-group">
            <label className="set-label">Categories</label>
            <div className="cat-list">
              {settings.categories.map((c) => {
                const col = DumpUtil.catColor(c, settings.categories);
                return (
                  <div className="cat-row" key={c}>
                    <span className="cat-dot" style={{ background: col.text }}></span>
                    <span>{c}</span>
                    <button className="x" onClick={() => removeCat(c)} aria-label={'Remove ' + c}>×</button>
                  </div>
                );
              })}
            </div>
            <div className="set-row">
              <input type="text" placeholder="New category…" value={newCat}
                onChange={(e) => setNewCat(e.target.value)}
                onKeyDown={(e) => { if (e.key === 'Enter') addCat(); }} />
              <button className="btn btn-sm" onClick={addCat}>Add</button>
            </div>
          </div>

          <div className="set-group">
            <label className="set-label">Habit reminder</label>
            <div className="edit-row" style={{ gap: 12 }}>
              <span className="mode-toggle" onClick={() => DumpStore.set((s) => ({ settings: { ...s.settings, habitReminder: !s.settings.habitReminder } }))}>
                <span className={'switch' + (settings.habitReminder ? ' on' : '')}></span>
                Remind me if I haven't offloaded in
              </span>
              <input type="number" min="1" max="30" value={settings.habitDays}
                style={{ width: 62, fontFamily: 'var(--sans)', fontSize: 14, background: 'var(--paper)', border: '1px solid var(--line-strong)', borderRadius: 9, padding: '7px 10px' }}
                onChange={(e) => {
                  const v = Math.max(1, Math.min(30, parseInt(e.target.value || '2', 10)));
                  DumpStore.set((s) => ({ settings: { ...s.settings, habitDays: v } }));
                }} />
              <span style={{ fontSize: 13, color: 'var(--ink-soft)' }}>days</span>
            </div>
          </div>

          <div className="set-group">
            <label className="set-label">Session token usage</label>
            <div className="usage-box">
              <span>In <strong>{sessionTokens.in.toLocaleString()}</strong></span>
              <span>Out <strong>{sessionTokens.out.toLocaleString()}</strong></span>
            </div>
          </div>

        </div>
      </div>
    </React.Fragment>
  );
}

window.SettingsPanel = SettingsPanel;
