// history.jsx — Session History overlay (stats + search + filters + timeline + per-session
// share & delete + clear). Opened from Settings. Exported to window.

function SessionHistory({ stats, th, accent, onClose, onDeleteSession, onClearHistory, onShared, onToast }) {
  const { t, dir } = useI18n();
  const [typeF, setTypeF] = React.useState('all');   // all | standard | pomodoro | countup
  const [rangeF, setRangeF] = React.useState('all');  // all | today | week | month
  const [confirmClear, setConfirmClear] = React.useState(false);

  const history = Array.isArray(stats.history) ? stats.history : [];
  const pad = (n) => String(n).padStart(2, '0');
  const ymd = (d) => d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate());
  const fmtDur = (min) => { const h = Math.floor(min / 60), mm = min % 60; return h > 0 ? h + 'h ' + (mm ? mm + 'm' : '') : mm + 'm'; };
  const typeLabel = (m) => t(m === 'pomodoro' ? 'sess_pomodoro' : m === 'countup' ? 'sess_countup' : 'sess_focus');
  const typeIcon = (m, s) => m === 'pomodoro' ? <IconClock size={s} /> : m === 'countup' ? <IconWave size={s} /> : <IconFocus size={s} />;
  const soundLabel = (key) => { if (!key) return null; const snd = (window.SOUNDS || []).find((x) => x.key === key); return snd ? t(snd.t) : null; };

  // ── filtering ──
  const now = Date.now();
  const inRange = (ts) => rangeF === 'all' ? true
    : rangeF === 'today' ? ymd(new Date(ts)) === ymd(new Date(now))
    : rangeF === 'week' ? (now - ts) < 7 * 864e5
    : (now - ts) < 31 * 864e5;
  const filtered = history
    .filter((h) => inRange(h.ts) && (typeF === 'all' || h.type === typeF))
    .sort((a, b) => (b.ts || 0) - (a.ts || 0));

  // ── group by day ──
  const order = []; const gmap = {};
  filtered.forEach((h) => { if (!gmap[h.date]) { gmap[h.date] = []; order.push(h.date); } gmap[h.date].push(h); });
  const todayY = ymd(new Date()), yestY = ymd(new Date(now - 864e5));
  const dayLabel = (d) => d === todayY ? t('hist_today') : d === yestY ? t('hist_yesterday')
    : (() => { try { return new Date(d + 'T00:00:00').toLocaleDateString(undefined, { weekday: 'long', month: 'short', day: 'numeric' }); } catch (e) { return d; } })();

  const shareOne = (h) => {
    haptic(14, true);
    if (onShared) onShared();
    const dateLabel = (() => { try { return new Date(h.ts || Date.now()).toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' }); } catch (e) { return h.date; } })();
    window.shareSessionImage({ minutes: h.dur, dateLabel, typeLabel: typeLabel(h.type),
      headline: t('share_focused', { n: h.dur }), generated: t('share_generated'), onToast, toastReady: t('toast_share_ready') });
  };

  const Chip = ({ active, onClick, children }) => (
    <button onClick={onClick} data-haptic="light" style={{
      padding: '7px 13px', borderRadius: 12, cursor: 'pointer', fontFamily: 'inherit', fontSize: 12.5, whiteSpace: 'nowrap',
      border: '1px solid ' + (active ? accent[0] + 'aa' : th.border2),
      background: active ? `linear-gradient(135deg, ${accent[0]}26, ${accent[1]}12)` : th.surface,
      color: active ? th.text : th.dim,
    }}>{children}</button>
  );

  return (
    <div className="prem-overlay" dir={dir}>
      <div className="prem-backdrop" onClick={onClose} />
      <div className="prem-sheet" style={{ background: th.sheet, borderColor: th.border2 }}>
        {/* header */}
        <div style={{ flexShrink: 0, padding: '14px 18px 6px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
          <div style={{ fontSize: 19, fontWeight: 400, color: th.text }}>{t('session_history')}</div>
          <button onClick={onClose} aria-label={t('np_close')} style={{ width: 34, height: 34, borderRadius: '50%', background: th.surface2, border: '1px solid ' + th.border, color: th.text, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><IconClose size={16} /></button>
        </div>

        {/* filters */}
        <div style={{ flexShrink: 0, padding: '6px 18px 10px' }}>
          <div style={{ display: 'flex', gap: 7, overflowX: 'auto' }}>
            <Chip active={typeF === 'all'} onClick={() => setTypeF('all')}>{t('hist_all')}</Chip>
            <Chip active={typeF === 'standard'} onClick={() => setTypeF('standard')}>{t('sess_focus')}</Chip>
            <Chip active={typeF === 'pomodoro'} onClick={() => setTypeF('pomodoro')}>{t('sess_pomodoro')}</Chip>
            <Chip active={typeF === 'countup'} onClick={() => setTypeF('countup')}>{t('sess_countup')}</Chip>
          </div>
          <div style={{ display: 'flex', gap: 7, overflowX: 'auto', marginTop: 7 }}>
            <Chip active={rangeF === 'all'} onClick={() => setRangeF('all')}>{t('hist_range_all')}</Chip>
            <Chip active={rangeF === 'today'} onClick={() => setRangeF('today')}>{t('hist_today')}</Chip>
            <Chip active={rangeF === 'week'} onClick={() => setRangeF('week')}>{t('hist_range_week')}</Chip>
            <Chip active={rangeF === 'month'} onClick={() => setRangeF('month')}>{t('hist_range_month')}</Chip>
          </div>
        </div>

        {/* timeline */}
        <div className="scroll-area" style={{ flex: 1, padding: '4px 18px 28px' }}>
          {order.length === 0 ? (
            <div style={{ textAlign: 'center', color: th.faint, fontSize: 13.5, padding: '40px 10px', fontWeight: 300 }}>{t('hist_empty')}</div>
          ) : order.map((d) => (
            <div key={d} style={{ marginBottom: 14 }}>
              <div style={{ fontSize: 11, letterSpacing: 1.4, textTransform: 'uppercase', color: th.faint, fontWeight: 600, margin: '4px 2px 9px' }}>{dayLabel(d)}</div>
              {gmap[d].map((h) => {
                const snd = soundLabel(h.sound);
                return (
                  <div key={h.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px', borderRadius: 15, background: th.surface, border: '1px solid ' + th.border, marginBottom: 8 }}>
                    <span style={{ width: 34, height: 34, borderRadius: 10, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
                      background: `linear-gradient(140deg, ${accent[0]}33, ${accent[1]}1a)`, color: accent[0] }}>{typeIcon(h.type, 17)}</span>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 14, fontWeight: 400, color: th.text }}>{typeLabel(h.type)}</div>
                      <div style={{ fontSize: 12, color: th.faint, marginTop: 3, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                        {fmtDur(h.dur)} · {h.start} → {h.end}{snd ? ' · ' + snd : ''}
                      </div>
                    </div>
                    <button onClick={() => shareOne(h)} aria-label={t('share')} data-haptic="medium" style={{ width: 34, height: 34, borderRadius: 10, flexShrink: 0, cursor: 'pointer', background: th.surface2, border: '1px solid ' + th.border, color: th.dim, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><IconShare size={15} /></button>
                  </div>
                );
              })}
            </div>
          ))}

          {history.length > 0 && (
            <button onClick={() => { if (confirmClear) { haptic([0, 40, 30]); onClearHistory(); setConfirmClear(false); } else { setConfirmClear(true); setTimeout(() => setConfirmClear(false), 3000); } }}
              style={{ width: '100%', marginTop: 8, padding: '13px', borderRadius: 14, cursor: 'pointer', fontFamily: 'inherit', fontSize: 13.5,
                background: 'transparent', border: '1px solid ' + (confirmClear ? '#FF6B6B66' : th.border2), color: confirmClear ? '#FF6B6B' : th.dim }}>
              {confirmClear ? t('hist_clear_confirm') : t('hist_clear')}
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { SessionHistory });
