/* Track & Train — By-type review tab */

function ByTypeView({ data, onUpdateSession, onDeleteSession, onAddType }) {
  const [activeId, setActiveId] = useState(data.types[0]?.id || null);
  const [yearScope, setYearScope] = useState('all');
  const [editing, setEditing] = useState(null);
  const { ask, ui: confirmUI } = useConfirm();

  // keep a valid selection if types change
  useEffect(() => {
    if (!data.types.find(t => t.id === activeId)) setActiveId(data.types[0]?.id || null);
  }, [data.types, activeId]);

  const active = data.types.find(t => t.id === activeId) || null;

  // all sessions of the active type (sorted, newest first)
  const allOfType = useMemo(() => {
    return data.sessions
      .filter(s => s.typeId === activeId)
      .sort((a, b) => b.date.localeCompare(a.date) || b.createdAt - a.createdAt);
  }, [data.sessions, activeId]);

  // distinct years that have sessions, newest first
  const years = useMemo(() => {
    return [...new Set(allOfType.map(s => s.date.slice(0, 4)))].sort((a, b) => b.localeCompare(a));
  }, [allOfType]);

  // reset scope to all-time if the selected year no longer has data for this type
  useEffect(() => {
    if (yearScope !== 'all' && !years.includes(yearScope)) setYearScope('all');
  }, [years, yearScope]);

  // sessions in the current scope (year filter)
  const sessions = useMemo(() => {
    return yearScope === 'all' ? allOfType : allOfType.filter(s => s.date.slice(0, 4) === yearScope);
  }, [allOfType, yearScope]);

  const stats = useMemo(() => {
    const now = new Date();
    const mk = `${now.getFullYear()}-${pad(now.getMonth()+1)}`;
    const thisMonth = sessions.filter(s => s.date.startsWith(mk)).length;
    const months = new Set(sessions.map(s => s.date.slice(0, 7))).size;
    const perMonth = months ? (sessions.length / months) : 0;
    const rated = sessions.filter(s => s.feeling != null);
    const avg = rated.length ? rated.reduce((a, s) => a + s.feeling, 0) / rated.length : null;
    return { total: sessions.length, thisMonth, perMonth, avg };
  }, [sessions]);

  const avgEmoji = stats.avg != null ? feelingOf(Math.round(stats.avg))?.emoji : '—';

  const startEdit = (s) => setEditing({ draft: { ...s } });
  const saveSession = () => { if (editing.draft.typeId) { onUpdateSession(editing.draft); setEditing(null); } };
  const removeSession = async (s) => {
    const ok = await ask({ title: t('confirm_del_session_title'), message: t('confirm_del_session_msg'), confirmLabel: t('delete'), danger: true });
    if (ok) { onDeleteSession(s.id); setEditing(null); }
  };

  if (data.types.length === 0) {
    return <div className="empty fade-in"><div className="emoji-icon"><Icon.tag/></div><h3>{t('notype_title')}</h3><p>{t('notype_msg')}</p></div>;
  }

  return (
    <div className="fade-in">
      {/* type selector */}
      <div className="type-scroller">
        {data.types.map(t => (
          <button key={t.id} className={'type-pill ' + (t.id === activeId ? 'on' : '')} onClick={() => { setActiveId(t.id); setYearScope('all'); }}>
            <span className="type-dot" style={{ background: t.id === activeId ? '#fff' : t.color }}></span>
            {t.name}
          </button>
        ))}
      </div>

      {active && (
        <Fragment>
          {/* hero */}
          <div className="bt-hero" style={{ marginBottom: 18 }}>
            <div className="bt-eyebrow"><span className="type-dot" style={{ background: active.color }}></span> {t('bt_eyebrow')}</div>
            <div className="bt-name">{active.name}</div>
            <div className="bt-grid">
              <div className="bt-stat"><div className="k">{t('st_total')}</div><div className="v">{stats.total}</div></div>
              {yearScope === 'all'
                ? <div className="bt-stat"><div className="k">{t('st_month')}</div><div className="v">{stats.thisMonth}</div></div>
                : <div className="bt-stat"><div className="k">{t('st_permonth')}</div><div className="v">{stats.total ? stats.perMonth.toFixed(1) : '—'}</div></div>}
              <div className="bt-stat"><div className="k">{t('st_feeling')}</div><div className="v" style={{ fontSize: 22 }}>{avgEmoji}</div></div>
            </div>
          </div>

          {/* history */}
          <div className="section-label" style={{ paddingLeft: 2 }}>
            <span>{t('history')}</span>
            <span className="flex items-center gap-8">
              <span className="muted" style={{ textTransform: 'none', letterSpacing: 0, fontWeight: 500 }}>{nSessions(sessions.length)}</span>
              {years.length > 0 && (
                <select className="year-select" value={yearScope} onChange={e => setYearScope(e.target.value)}>
                  <option value="all">{t('all_time')}</option>
                  {years.map(y => <option key={y} value={y}>{y}</option>)}
                </select>
              )}
            </span>
          </div>

          {sessions.length === 0 ? (
            <div className="empty">
              <div className="emoji-icon"><Icon.calendar/></div>
              <h3>{t('bt_empty_title')}</h3>
              <p>{t('bt_empty_msg', { name: active.name })}</p>
            </div>
          ) : (
            sessions.map(s => {
              const d = parseKey(s.date);
              const f = feelingOf(s.feeling);
              const rel = relativeDay(s.date);
              return (
                <button key={s.id} className="bt-day-row" onClick={() => startEdit(s)}>
                  <span className="bt-datebox">
                    <span className="d" style={{ color: active.color }}>{d.getDate()}</span>
                    <span className="m">{monthShort(d.getMonth())}</span>
                  </span>
                  <span className="bt-day-main">
                    <span className="sc-top">
                      <span className="sc-type" style={{ fontSize: 14 }}>{capitalize(dowLong(d.getDay()))}</span>
                      {rel && <span className="chip" style={{ fontSize: 10 }}>{rel}</span>}
                      {f && <span className="sc-feel" style={{ marginLeft: 'auto', fontSize: 16 }}>{f.emoji}</span>}
                    </span>
                    {s.notes ? <span className="sc-notes" style={{ marginTop: 3 }}>{s.notes}</span> : <span className="sc-empty-notes" style={{ marginTop: 3 }}>{t('no_notes')}</span>}
                  </span>
                </button>
              );
            })
          )}
        </Fragment>
      )}

      {/* edit sheet */}
      <Sheet
        open={!!editing}
        onClose={() => setEditing(null)}
        title={t('edit_title')}
        action={editing
          ? <button className="icon-btn" style={{ color: 'var(--ink-3)' }} onClick={() => removeSession(editing.draft)} aria-label={t('delete')}><Icon.trash/></button>
          : null}
      >
        {editing && (
          <Fragment>
            <p className="day-date" style={{ margin: '-4px 0 16px' }}>{capitalize(formatLongDate(editing.draft.date))}</p>
            <SessionForm
              types={data.types}
              draft={editing.draft}
              onChange={(d) => setEditing(e => ({ ...e, draft: d }))}
              onAddType={onAddType}
            />
            <button className="btn accent block lg" style={{ marginTop: 22 }} disabled={!editing.draft.typeId} onClick={saveSession}>
              {t('save_changes')}
            </button>
          </Fragment>
        )}
      </Sheet>

      {confirmUI}
    </div>
  );
}

Object.assign(window, { ByTypeView });
