// =========================================================
// ANALYTICS — productivity tracker view.
// Computes weekly/rolling stats from the task list, sessions log,
// and habit history. Pure-derivation: the source of truth stays in
// shell-v2.jsx's state, this view just reads and renders.
// =========================================================

function Analytics({ T, D, state, isMobile }) {
  const nowD = new Date();
  const thisMon = mondayOf(nowD);
  const lastMon = addDays(thisMon, -7);
  const nextMon = addDays(thisMon, 7);

  const tasks   = state.tasks || [];
  const habits  = state.habits || [];
  const hist    = state.habitHistory || {};
  const sess    = state.sessions || [];

  // ---- Week buckets for completed + added ----
  const inRange = (ts, a, b) => ts >= a.getTime() && ts < b.getTime();

  const completedThisWeek = tasks.filter(t => t.completedAt && inRange(t.completedAt, thisMon, nextMon)).length;
  const addedThisWeek     = tasks.filter(t => t.created && inRange(t.created, thisMon, nextMon)).length;
  const completedLastWeek = tasks.filter(t => t.completedAt && inRange(t.completedAt, lastMon, thisMon)).length;
  const addedLastWeek     = tasks.filter(t => t.created && inRange(t.created, lastMon, thisMon)).length;

  // ---- 8-week rolling bars ----
  const weeks = [];
  for (let i = 7; i >= 0; i--) {
    const a = addDays(thisMon, -7 * i);
    const b = addDays(a, 7);
    const completed = tasks.filter(t => t.completedAt && inRange(t.completedAt, a, b)).length;
    const added     = tasks.filter(t => t.created && inRange(t.created, a, b)).length;
    const label = `${a.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}`;
    weeks.push({ a, b, completed, added, label });
  }
  const maxBar = Math.max(1, ...weeks.flatMap(w => [w.completed, w.added]));

  // ---- Contexts breakdown over the last 4 weeks of completions ----
  const fourWeeksAgo = addDays(thisMon, -21);
  const recentCompleted = tasks.filter(t => t.completedAt && t.completedAt >= fourWeeksAgo.getTime());
  const ctxCounts = {};
  recentCompleted.forEach(t => {
    const k = t.context || '(no context)';
    ctxCounts[k] = (ctxCounts[k] || 0) + 1;
  });
  const ctxRows = Object.entries(ctxCounts).sort((a, b) => b[1] - a[1]);
  const ctxMax = Math.max(1, ...ctxRows.map(r => r[1]));

  // ---- Sessions (days opened) this week ----
  const sessionsThisWeek = sess.filter(ts => inRange(ts, thisMon, nextMon));
  const daysOpenedThisWeek = new Set(sessionsThisWeek.map(ts => isoDate(new Date(ts)))).size;

  // ---- Streak: consecutive days with at least one session, ending today ----
  const sessionDaySet = new Set(sess.map(ts => isoDate(new Date(ts))));
  let streak = 0;
  for (let i = 0; i < 365; i++) {
    const d = addDays(nowD, -i);
    if (sessionDaySet.has(isoDate(d))) streak++; else if (i > 0) break;
  }

  // ---- Habit weekly rates over last 8 weeks ----
  const habitWeeks = [];
  for (let i = 7; i >= 0; i--) {
    const wA = addDays(thisMon, -7 * i);
    const row = { label: wA.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }), habits: {} };
    habits.forEach(h => {
      let hits = 0;
      for (let j = 0; j < 7; j++) {
        if ((hist[h.id] || {})[isoDate(addDays(wA, j))]) hits++;
      }
      row.habits[h.id] = hits;
    });
    habitWeeks.push(row);
  }

  // ---------- styles ----------
  const pad = isMobile ? 16 : 28;
  const CardS = {
    border: `1px solid ${T.line}`, padding: isMobile ? 14 : 18,
    background: T.panel, marginBottom: 14,
  };
  const Label = ({ children, style }) => (
    <div style={{
      fontFamily: 'var(--mono)', fontSize: 10, color: T.fg3,
      letterSpacing: '0.14em', textTransform: 'uppercase',
      ...style,
    }}>{children}</div>
  );
  const Big = ({ value, sub }) => (
    <div>
      <div style={{
        fontFamily: 'var(--sans)', fontSize: isMobile ? 32 : 40, color: T.fg,
        letterSpacing: 'var(--display-tight)', fontWeight: 'var(--hw)',
        lineHeight: 1,
      }}>{value}</div>
      {sub && <div style={{ fontFamily: 'var(--mono)', fontSize: 10, color: T.fg3, letterSpacing: '0.1em', marginTop: 6 }}>{sub}</div>}
    </div>
  );

  return (
    <div style={{
      flex: 1, minHeight: 0, overflowY: 'auto',
      background: T.panel, color: T.fg, fontFamily: 'var(--sans)',
      padding: `${pad}px ${pad}px ${pad * 2}px`,
    }}>
      <div style={{ maxWidth: 960, margin: '0 auto' }}>
        <Label>ANALYTICS · {nowD.toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' }).toUpperCase()}</Label>
        <div style={{
          fontSize: isMobile ? 26 : 34, fontWeight: 'var(--hw)', letterSpacing: 'var(--display-tight)',
          marginTop: 6, marginBottom: 20,
        }}>This week, in numbers.</div>

        {/* ── this week headline ── */}
        <div style={{
          display: 'grid', gridTemplateColumns: isMobile ? '1fr 1fr' : 'repeat(4, 1fr)',
          gap: 12, marginBottom: 20,
        }}>
          <div style={CardS}>
            <Label>COMPLETED</Label>
            <div style={{ marginTop: 8 }}>
              <Big value={completedThisWeek}
                sub={`${completedLastWeek} last wk · ${signedDelta(completedThisWeek - completedLastWeek)}`} />
            </div>
          </div>
          <div style={CardS}>
            <Label>ADDED</Label>
            <div style={{ marginTop: 8 }}>
              <Big value={addedThisWeek}
                sub={`${addedLastWeek} last wk · ${signedDelta(addedThisWeek - addedLastWeek)}`} />
            </div>
          </div>
          <div style={CardS}>
            <Label>COMPLETION</Label>
            <div style={{ marginTop: 8 }}>
              <Big value={addedThisWeek === 0 ? '—' : `${Math.round((completedThisWeek / addedThisWeek) * 100)}%`}
                sub="of this week's additions" />
            </div>
          </div>
          <div style={CardS}>
            <Label>SESSIONS</Label>
            <div style={{ marginTop: 8 }}>
              <Big value={daysOpenedThisWeek}
                sub={`days opened · ${streak} day streak`} />
            </div>
          </div>
        </div>

        {/* ── 8-week bars ── */}
        <div style={CardS}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 14 }}>
            <Label>COMPLETION · LAST 8 WEEKS</Label>
            <span style={{ fontFamily: 'var(--mono)', fontSize: 10, color: T.fg3, letterSpacing: '0.1em' }}>
              <span style={{ color: T.accent }}>■</span> COMPLETED &nbsp;
              <span style={{ color: T.fg2 }}>■</span> ADDED
            </span>
          </div>
          <div style={{ display: 'flex', gap: 6, alignItems: 'flex-end', height: 120 }}>
            {weeks.map((w, i) => {
              const ch = (w.completed / maxBar) * 100;
              const ah = (w.added / maxBar) * 100;
              return (
                <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
                  <div style={{ width: '100%', height: 100, display: 'flex', alignItems: 'flex-end', gap: 2 }}>
                    <div title={`Completed: ${w.completed}`} style={{
                      flex: 1, height: `${ch}%`, background: T.accent, minHeight: w.completed ? 2 : 0,
                    }} />
                    <div title={`Added: ${w.added}`} style={{
                      flex: 1, height: `${ah}%`, background: T.fg3, minHeight: w.added ? 2 : 0,
                    }} />
                  </div>
                  <div style={{ fontFamily: 'var(--mono)', fontSize: 9, color: T.fg3, letterSpacing: '0.05em' }}>
                    {w.label}
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* ── contexts breakdown ── */}
        <div style={CardS}>
          <Label>CONTEXTS · LAST 4 WEEKS</Label>
          {ctxRows.length === 0 ? (
            <div style={{ padding: '14px 0', color: T.fg3, fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.12em' }}>
              ─── NO COMPLETIONS YET ───
            </div>
          ) : (
            <div style={{ marginTop: 10 }}>
              {ctxRows.map(([k, n]) => (
                <div key={k} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '7px 0' }}>
                  <div style={{
                    fontFamily: 'var(--mono)', fontSize: 12, color: T.fg2,
                    minWidth: isMobile ? 90 : 120,
                  }}>{k}</div>
                  <div style={{ flex: 1, height: 6, background: T.line }}>
                    <div style={{ width: `${(n / ctxMax) * 100}%`, height: '100%', background: T.accent }} />
                  </div>
                  <div style={{ fontFamily: 'var(--mono)', fontSize: 11, color: T.fg, minWidth: 28, textAlign: 'right' }}>{n}</div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* ── habit scoreboard ── */}
        <div style={CardS}>
          <Label>HABITS · LAST 8 WEEKS</Label>
          {habits.length === 0 ? (
            <div style={{ padding: '14px 0', color: T.fg3, fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.12em' }}>
              ─── NO HABITS YET ───
            </div>
          ) : (
            <div style={{ marginTop: 12 }}>
              {habits.map(h => {
                const series = habitWeeks.map(w => w.habits[h.id] || 0);
                const thisWeekHits = series[series.length - 1];
                const total = series.reduce((a, b) => a + b, 0);
                const rate = series.length ? Math.round((total / (series.length * 7)) * 100) : 0;
                return (
                  <div key={h.id} style={{ padding: '10px 0', borderTop: `1px solid ${T.line}` }}>
                    <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 8 }}>
                      <div style={{ fontSize: 14, fontWeight: 'var(--hw)', color: T.fg }}>{h.name}</div>
                      <div style={{ flex: 1 }} />
                      <div style={{ fontFamily: 'var(--mono)', fontSize: 10, color: T.fg3 }}>THIS WEEK {thisWeekHits}/{h.target}</div>
                      <div style={{ fontFamily: 'var(--mono)', fontSize: 10, color: T.fg3 }}>8W RATE {rate}%</div>
                    </div>
                    <div style={{ display: 'flex', gap: 3, alignItems: 'flex-end', height: 38 }}>
                      {series.map((n, i) => (
                        <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 2 }}>
                          <div title={`${habitWeeks[i].label}: ${n}/7`} style={{
                            width: '100%', height: `${(n / 7) * 32}px`, background: T.accent,
                            minHeight: n ? 2 : 0,
                          }} />
                          <div style={{ fontFamily: 'var(--mono)', fontSize: 8, color: T.fg3, textAlign: 'center' }}>{n}</div>
                        </div>
                      ))}
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>

        <div style={{ fontFamily: 'var(--mono)', fontSize: 9, color: T.fg3, letterSpacing: '0.12em', textAlign: 'center', marginTop: 18 }}>
          ─── STATS UPDATE AS YOU USE THE APP ───
        </div>
      </div>
    </div>
  );
}

function signedDelta(n) {
  if (n === 0) return '—';
  return n > 0 ? `+${n}` : `${n}`;
}

Object.assign(window, { Analytics });
