// SoloTube — settings popover

const { useEffect: useEffectS, useState: useStateS } = React;

function compileDigestStats(state) {
  const today = new Date();
  let weekSec = 0;
  for (let i = 0; i < 7; i++) {
    const d = new Date(today); d.setDate(today.getDate() - i);
    weekSec += (state.watchLog[d.toISOString().slice(0, 10)] || 0);
  }
  const h = Math.floor(weekSec / 3600), m = Math.floor((weekSec % 3600) / 60);
  const watchTime = weekSec === 0 ? '0m' : (h > 0 ? h + 'h ' : '') + (m > 0 ? m + 'm' : (h > 0 ? '' : '0m'));

  const watchedVids = state.videos.filter(v => state.watched.has(v.id));
  const watchedCount = watchedVids.length;
  const finishedCount = watchedVids.filter(v => v.progress == null || v.progress >= 0.8).length;

  const chMap = {};
  for (const c of state.channels) {
    if (c.id === 'c-singles') continue;
    chMap[c.id] = { name: c.name, mark: c.mark || c.name[0], accent: c.accent || '#888', count: 0 };
  }
  for (const v of watchedVids) { if (chMap[v.channelId]) chMap[v.channelId].count++; }
  const totalW = watchedCount || 1;
  const channels = Object.values(chMap).filter(c => c.count > 0)
    .sort((a, b) => b.count - a.count).slice(0, 4)
    .map(c => ({ ...c, pct: Math.round((c.count / totalW) * 100) }));

  const highlights = [...state.favorites]
    .map(id => { const v = state.videos.find(vv => vv.id === id); if (!v) return null;
      const ch = state.channels.find(c => c.id === v.channelId);
      return { title: v.title, channelName: ch?.name || '', videoId: v.id }; })
    .filter(Boolean).slice(0, 3);

  const allNotes = Object.entries(state.notes || {})
    .flatMap(([vid, notes]) => notes.map(n => ({ ...n, videoId: vid })))
    .sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0));
  let topNote = null, additionalNotes = 0;
  if (allNotes.length) {
    const best = [...allNotes].sort((a, b) => b.text.length - a.text.length)[0];
    const vid = state.videos.find(v => v.id === best.videoId);
    const ch = state.channels.find(c => c.id === vid?.channelId);
    topNote = { text: best.text, videoTitle: vid?.title || '', channelName: ch?.name || '' };
    additionalNotes = Math.max(0, allNotes.length - 1);
  }

  const uploadMap = {};
  for (const c of state.channels) {
    if (c.id === 'c-singles') continue;
    uploadMap[c.id] = { name: c.name, mark: c.mark || c.name[0], accent: c.accent || '#888', newCount: 0 };
  }
  for (const v of state.videos) { if (!state.watched.has(v.id) && uploadMap[v.channelId]) uploadMap[v.channelId].newCount++; }
  const uploads = Object.values(uploadMap).filter(c => c.newCount > 0)
    .sort((a, b) => b.newCount - a.newCount).slice(0, 4);

  const now = new Date();
  const wkStart = new Date(now); wkStart.setDate(now.getDate() - 6);
  const mos = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  const weekLabel = wkStart.getMonth() === now.getMonth()
    ? `${mos[now.getMonth()]} ${wkStart.getDate()}–${now.getDate()}, ${now.getFullYear()}`
    : `${mos[wkStart.getMonth()]} ${wkStart.getDate()} – ${mos[now.getMonth()]} ${now.getDate()}, ${now.getFullYear()}`;
  const weekNum = Math.ceil(((now - new Date(now.getFullYear(), 0, 1)) / 86400000 + new Date(now.getFullYear(), 0, 1).getDay() + 1) / 7);

  return { watchTime, watchedCount, finishedCount, channels, highlights, topNote, additionalNotes, uploads, weekLabel, weekNum };
}

const LIMIT_PRESETS = [0, 30, 60, 120];

function SettingsPopover({ state, dispatch }) {
  const { settings, sidebarRail, theme } = state;
  const close = () => dispatch({ type: 'close-settings' });
  const [advOpen, setAdvOpen] = useStateS(false);

  useEffectS(() => {
    function onKey(e) { if (e.key === 'Escape') close(); }
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  const set = (key) => (v) => dispatch({ type: 'set-setting', key, value: v });
  const [digestStatus, setDigestStatus] = useStateS('idle');
  const [resetConfirm, setResetConfirm] = useStateS(false);

  const sendDigest = async () => {
    const email = (settings.digestEmail || '').trim();
    if (!email) return;
    setDigestStatus('sending');
    try {
      const stats = compileDigestStats(state);
      const r = await fetch('/api/digest', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, stats }),
      });
      const body = await r.json().catch(() => ({}));
      if (!r.ok) throw new Error(body?.error || 'Failed');
      setDigestStatus('sent');
      setTimeout(() => setDigestStatus('idle'), 4000);
    } catch {
      setDigestStatus('error');
      setTimeout(() => setDigestStatus('idle'), 4000);
    }
  };

  const leftPx = sidebarRail ? 70 : 296;
  const limitMin = settings.dailyLimitMin || 0;
  const customActive = limitMin > 0 && !LIMIT_PRESETS.includes(limitMin);

  const thumbRaw = settings.thumbnails;
  const thumbCurrent = thumbRaw === false ? 'off' : (thumbRaw === 'generated' ? 'generated' : 'real');

  return (
    <div className="settings-back" onMouseDown={(e) => { if (e.target === e.currentTarget) close(); }}>
      <div
        className="settings-pop"
        style={{ left: leftPx + 'px' }}
        onMouseDown={(e) => e.stopPropagation()}
      >
        <div className="settings-head">
          <span className="settings-eyebrow">SETTINGS</span>
          <button className="settings-x" onClick={close}>✕</button>
        </div>

        {/* Appearance */}
        <SettingsGroup label="Appearance">
          <div className="settings-row">
            <span className="settings-row-label">Theme</span>
            <button
              className={`settings-theme-btn ${theme === 'dark' ? 'dark' : 'light'}`}
              onClick={() => dispatch({ type: 'theme', theme: theme === 'light' ? 'dark' : 'light' })}
            >
              {theme === 'light' ? '◐ Light' : '◑ Dark'}
            </button>
          </div>
          <div className="settings-row settings-row-inl">
            <span className="settings-row-label">Thumbnails</span>
            <span className="settings-budget-opts">
              {['real', 'generated', 'off'].map(opt => (
                <button
                  key={opt}
                  className={`settings-budget-btn ${thumbCurrent === opt ? 'on' : ''}`}
                  onClick={() => set('thumbnails')(opt === 'off' ? false : opt)}
                >
                  {opt === 'real' ? 'Real' : opt === 'generated' ? 'Art' : 'Off'}
                </button>
              ))}
            </span>
          </div>
        </SettingsGroup>

        {/* Feed */}
        <SettingsGroup label="Feed">
          <SettingsRow label="Video snippets"  value={settings.videoSnippets}  onChange={set('videoSnippets')} />
          <SettingsRow label="Filter tabs"     value={settings.filterBar}     onChange={set('filterBar')} />
          <SettingsRow label="Section headers" value={settings.sectionHeaders} onChange={set('sectionHeaders')} />
          <SettingsRow label="Row numbers"     value={settings.viewIndices}    onChange={set('viewIndices')} />
          <SettingsRow label="Progress bars"   value={settings.progressBars}  onChange={set('progressBars')} />
          <SettingsRow label="Auto-archive watched" sub="Move to archive after watching" value={settings.autoArchiveWatched} onChange={set('autoArchiveWatched')} />
        </SettingsGroup>

        {/* Intention */}
        <SettingsGroup label="Intention">
          <div className="settings-row settings-row-budget">
            <span className="settings-row-meta">
              <span className="settings-row-label">Daily limit</span>
              <span className="settings-row-sub">Soft nudge only — never a lock</span>
            </span>
            <span className="settings-budget-opts">
              {LIMIT_PRESETS.map(min => (
                <button
                  key={min}
                  className={`settings-budget-btn ${limitMin === min ? 'on' : ''}`}
                  onClick={() => set('dailyLimitMin')(min)}
                >{min === 0 ? 'off' : min + 'm'}</button>
              ))}
              <input
                type="number"
                className={`settings-budget-custom ${customActive ? 'on' : ''}`}
                placeholder="…"
                min="1"
                max="480"
                value={customActive ? limitMin : ''}
                onChange={(e) => {
                  const v = parseInt(e.target.value, 10);
                  set('dailyLimitMin')(!isNaN(v) && v > 0 ? v : 0);
                }}
              />
            </span>
          </div>
          <SettingsRow label="Deep zen in focus" sub="Strips stats, brief and description" value={settings.deepZen} onChange={set('deepZen')} />
        </SettingsGroup>

        {/* Digest */}
        <SettingsGroup label="Weekly digest">
          <div style={{ padding: '2px 22px 14px' }}>
            <input
              className="settings-digest-email"
              type="email"
              placeholder="your@email.com"
              style={{ width: '100%', marginBottom: 12 }}
              value={settings.digestEmail || ''}
              onChange={(e) => set('digestEmail')(e.target.value)}
            />
            <div className="settings-row settings-row-inl" style={{ marginBottom: 6 }}>
              <span className="settings-row-label">Schedule</span>
              <span className="settings-budget-opts">
                <button className={`settings-budget-btn ${!settings.digestScheduleEnabled ? 'on' : ''}`}
                  onClick={() => set('digestScheduleEnabled')(false)}>off</button>
                <button className={`settings-budget-btn ${settings.digestScheduleEnabled ? 'on' : ''}`}
                  onClick={() => set('digestScheduleEnabled')(true)}>weekly</button>
              </span>
            </div>
            {settings.digestScheduleEnabled && (
              <div style={{ marginTop: 10 }}>
                <div className="settings-adv-sub" style={{ marginBottom: 6 }}>DAY</div>
                <div className="settings-budget-opts" style={{ flexWrap: 'wrap', gap: 4, marginBottom: 10 }}>
                  {['Sun','Mon','Tue','Wed','Thu','Fri','Sat'].map((d, i) => (
                    <button key={d}
                      className={`settings-budget-btn ${settings.digestScheduleDay === i ? 'on' : ''}`}
                      onClick={() => set('digestScheduleDay')(i)}
                    >{d}</button>
                  ))}
                </div>
                <div className="settings-adv-sub" style={{ marginBottom: 6 }}>TIME · LOCAL</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
                  <input
                    type="number" min="0" max="23"
                    className="settings-budget-custom on"
                    style={{ width: 52 }}
                    value={settings.digestScheduleHour ?? 9}
                    onChange={e => {
                      const v = parseInt(e.target.value, 10);
                      if (!isNaN(v) && v >= 0 && v <= 23) set('digestScheduleHour')(v);
                    }}
                  />
                  <span style={{ fontFamily: 'var(--ff-mono)', fontSize: 11, color: 'var(--ink-3)' }}>:00</span>
                  <span style={{ fontFamily: 'var(--ff-mono)', fontSize: 10, color: 'var(--ink-3)', letterSpacing: '0.04em' }}>
                    {settings.digestTimezone || Intl.DateTimeFormat().resolvedOptions().timeZone}
                  </span>
                </div>
                {state.lastDigestSent && (
                  <div style={{ fontFamily: 'var(--ff-mono)', fontSize: 10, color: 'var(--ink-3)', letterSpacing: '0.04em', marginBottom: 6 }}>
                    last sent {new Date(state.lastDigestSent).toLocaleDateString()}
                  </div>
                )}
              </div>
            )}
            <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 8 }}>
              <button
                className={`settings-digest-btn${digestStatus !== 'idle' ? ' ' + digestStatus : ''}`}
                disabled={digestStatus === 'sending' || !(settings.digestEmail || '').trim()}
                onClick={sendDigest}
              >
                {digestStatus === 'idle'    ? 'Send now'  :
                 digestStatus === 'sending' ? 'Sending…'  :
                 digestStatus === 'sent'    ? '✓ Sent'    : 'Error'}
              </button>
            </div>
          </div>
        </SettingsGroup>

        {/* Advanced — collapsed by default */}
        <SettingsGroup label="">
          <button className="settings-adv-toggle" onClick={() => setAdvOpen(o => !o)}>
            <span className="settings-adv-chev">{advOpen ? '▾' : '▸'}</span>
            Advanced
          </button>
          {advOpen && (
            <>
              <div className="settings-adv-sub">PAGE CHROME</div>
              <SettingsRow label="Section eyebrow" value={settings.pageEyebrow} onChange={set('pageEyebrow')} />
              <SettingsRow label="Subtitle copy"   value={settings.pageSubtitle} onChange={set('pageSubtitle')} />
              <SettingsRow label="Stats counter"   value={settings.pageStats}    onChange={set('pageStats')} />
              <SettingsRow label="Inbox button"    value={settings.inbox}        onChange={set('inbox')} />
              <div className="settings-adv-sub">RAIL SIDEBAR</div>
              <SettingsRow label="Channels in rail"  value={settings.railChannels}      onChange={set('railChannels')} />
              <SettingsRow label="Unwatched dots"    value={settings.railUnwatchedDots} onChange={set('railUnwatchedDots')} />
            </>
          )}
        </SettingsGroup>

        {/* Account */}
        {window.__clerk && (
          <SettingsGroup label="Account">
            <div className="settings-row settings-row-account">
              <span className="settings-row-meta">
                <span className="settings-row-label">Signed in as</span>
                <span className="settings-row-sub">{window.__clerkUser?.primaryEmailAddress?.emailAddress || ''}</span>
              </span>
              <button
                className="settings-signout-btn"
                onClick={() => window.__clerk.signOut().then(() => { window.location.href = '/login'; })}
              >
                Sign out
              </button>
            </div>
          </SettingsGroup>
        )}

        <div className="settings-foot">
          <span>ESC to close</span>
          <button
            className={`settings-reset${resetConfirm ? ' confirm' : ''}`}
            onClick={() => {
              if (!resetConfirm) {
                setResetConfirm(true);
                setTimeout(() => setResetConfirm(false), 3000);
              } else {
                setResetConfirm(false);
                const zen = {
                  pageEyebrow: false, pageSubtitle: false, pageStats: false, inbox: true,
                  railChannels: false, railUnwatchedDots: false,
                  sectionHeaders: true, progressBars: true, viewIndices: true, filterBar: true,
                  thumbnails: 'real', dailyLimitMin: 0, deepZen: true,
                };
                Object.keys(zen).forEach(k => dispatch({ type: 'set-setting', key: k, value: zen[k] }));
              }
            }}
          >{resetConfirm ? 'sure?' : 'reset'}</button>
        </div>
      </div>
    </div>
  );
}

function SettingsGroup({ label, children }) {
  return (
    <div className="settings-group">
      {label && <div className="settings-group-label">{label}</div>}
      {children}
    </div>
  );
}

function SettingsRow({ label, sub, value, onChange }) {
  return (
    <label className="settings-row">
      <span className="settings-row-meta">
        <span className="settings-row-label">{label}</span>
        {sub && <span className="settings-row-sub">{sub}</span>}
      </span>
      <span className={`settings-check ${value ? 'on' : ''}`} onClick={(e) => { e.preventDefault(); onChange(!value); }}>
        <span className="settings-check-fill"></span>
      </span>
    </label>
  );
}

window.compileDigestStats = compileDigestStats;
window.SettingsPopover = SettingsPopover;
