/* StatsTab — Stats screen: streak, week heatmap, totals, recent log */
(function () {
  const { useMemo } = React;

  function StatsTab({ today, todayKey, sessions, setSessions, streak }) {
    const PF = window.PulseFloor;

    const todaySessions = useMemo(
      () => sessions.filter((s) => s.day === todayKey),
      [sessions, todayKey]
    );

    const totalMinutes = useMemo(
      () => Math.round(sessions.reduce((a, b) => a + b.dur, 0) / 60),
      [sessions]
    );

    const weekStrip = useMemo(() => {
      const days = [];
      const todayIdx = PF.dayIndex(today);
      const dow = today.getDay(); // 0=Sun
      const monOffset = (dow + 6) % 7; // days back to monday
      for (let i = 0; i < 7; i++) {
        const di = todayIdx - monOffset + i;
        const d = new Date(today);
        d.setDate(today.getDate() - monOffset + i);
        days.push({
          di,
          label: ["M","T","W","T","F","S","S"][i],
          date: d.getDate(),
          isToday: di === todayIdx,
          isFuture: di > todayIdx,
          done: sessions.some((s) => s.day === String(di)),
        });
      }
      return days;
    }, [sessions, today]);

    return (
      <div className="fade-in">
        <div className="section-head">
          <h2>Progress</h2>
          <span className="meta">since you started</span>
        </div>

        <div className="stat-grid">
          <div className="stat-card accent">
            <div className="l">Streak</div>
            <div className="v">{streak}<small>days</small></div>
          </div>
          <div className="stat-card accent-2">
            <div className="l">Total</div>
            <div className="v">{sessions.length}<small>sessions</small></div>
          </div>
          <div className="stat-card">
            <div className="l">Minutes</div>
            <div className="v">{totalMinutes}<small>min</small></div>
          </div>
          <div className="stat-card">
            <div className="l">Today</div>
            <div className="v">{todaySessions.length}<small>done</small></div>
          </div>
        </div>

        <div style={{height: 16}}></div>

        <div className="card">
          <div className="row between">
            <div style={{fontWeight: 600, letterSpacing: "-0.01em"}}>This week</div>
            <div className="muted" style={{fontSize: 12}}>{weekStrip.filter(d=>d.done).length}/7 days</div>
          </div>
          <div className="week-grid">
            {weekStrip.map((d, i) => (
              <div key={i} className={`day ${d.isToday ? "today" : ""} ${d.done ? "done" : ""}`}>
                <div style={{fontSize: 11, fontWeight: 600}}>{d.date}</div>
                <div className="label">{d.label}</div>
              </div>
            ))}
          </div>
        </div>

        <div style={{height: 16}}></div>

        <div className="card">
          <div style={{fontWeight: 600, letterSpacing: "-0.01em", marginBottom: 10}}>Recent sessions</div>
          {sessions.length === 0 ? (
            <div className="muted" style={{fontSize: 13, padding: "8px 0"}}>No sessions yet. Hit start on the trainer to get going.</div>
          ) : (
            <div style={{display: "grid", gap: 6}}>
              {sessions.slice(-6).reverse().map((s, i) => {
                const p = [...PF.PRESETS, { id: "random", name: "Daily Random" }].find(x => x.id === s.patternId);
                const d = new Date(s.ts);
                return (
                  <div key={i} className="row between" style={{padding: "8px 0", borderTop: i === 0 ? "0" : "1px solid var(--border)"}}>
                    <div>
                      <div style={{fontWeight: 500, fontSize: 14}}>{p?.name || s.patternId}</div>
                      <div className="muted mono" style={{fontSize: 11}}>{d.toLocaleDateString("en-US", { month: "short", day: "numeric" })} · {d.toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit" })}</div>
                    </div>
                    <div className="mono" style={{color: "var(--accent)", fontSize: 13}}>{Math.round(s.dur)}s</div>
                  </div>
                );
              })}
            </div>
          )}
        </div>

        {sessions.length > 0 && (
          <button
            className="btn ghost"
            style={{marginTop: 16, fontSize: 12, color: "var(--text-mute)", padding: 10}}
            onClick={() => { if (confirm("Reset all progress?")) setSessions([]); }}
          >
            Reset progress
          </button>
        )}
      </div>
    );
  }

  window.StatsTab = StatsTab;
})();
