// Stats — "Your time". Reflective watch analytics: what you actually watch,
// where your attention goes, and which subscriptions are dead weight.
// Deliberately not a vanity dashboard — it's here to help you cull and decide.

function Stats({ state, dispatch }) {
  const { videos, channels, watched, hidden, notes, favorites, watchLog, settings } = state;
  const fmt = window.SoloUtils.formatDur;

  const visibleChannels = channels.filter(c => !hidden.has(c.id));
  const visibleVideos = videos.filter(v => !hidden.has(v.channelId));
  const watchedVideos = visibleVideos.filter(v => watched.has(v.id) || v.watched);
  const noteCount = Object.values(notes).reduce((a, l) => a + l.length, 0);

  // Last 14 days of logged playback (real player time only)
  const days = [];
  for (let i = 13; i >= 0; i--) {
    const d = new Date();
    d.setDate(d.getDate() - i);
    const key = window.SoloUtils.dayKey(d);
    days.push({ key, label: key.slice(5).replace('-', '/'), sec: watchLog[key] || 0 });
  }
  const maxDay = Math.max(60, ...days.map(d => d.sec));
  const totalLogged = Object.values(watchLog).reduce((a, b) => a + b, 0);
  const weekSec = days.slice(7).reduce((a, d) => a + d.sec, 0);

  const todaySec = watchLog[window.SoloUtils.dayKey()] || 0;
  const limitSec = (settings.dailyLimitMin || 0) * 60;

  // Per-channel: watched / total, sorted by attention
  const perChannel = visibleChannels.map(c => {
    const vids = visibleVideos.filter(v => v.channelId === c.id);
    const seen = vids.filter(v => watched.has(v.id) || v.watched);
    return { c, total: vids.length, seen: seen.length, ratio: vids.length ? seen.length / vids.length : 0 };
  }).sort((a, b) => b.seen - a.seen);
  const neverOpened = perChannel.filter(r => r.total > 0 && r.seen === 0);

  return (
    <main className="main">
      <div className="page-head">
        <div>
          <div className="page-eyebrow">REFLECTION, NOT VANITY</div>
          <h1 className="page-title">Your time</h1>
          <p className="page-subtitle">
            Only what the player actually measured. No streaks, no badges — just enough to decide what deserves to stay.
          </p>
        </div>
        <div className="page-head-right">
          <div className="page-stats">
            <div><span className="num">{fmt(weekSec)}</span>this week</div>
            <div><span className="num">{watchedVideos.length}</span>watched</div>
            <div><span className="num">{noteCount}</span>notes</div>
          </div>
        </div>
      </div>

      <div className="feed-scroll stats-scroll">
        {limitSec > 0 && (
          <section className="stats-block">
            <div className="stats-block-head">TODAY VS YOUR INTENTION</div>
            <div className="stats-budget">
              <div className="stats-budget-bar">
                <div
                  className={`stats-budget-fill ${todaySec >= limitSec ? 'over' : ''}`}
                  style={{ width: Math.min(100, (todaySec / limitSec) * 100) + '%' }}
                ></div>
              </div>
              <div className="stats-budget-row">
                <span>{fmt(todaySec)} watched</span>
                <span>{settings.dailyLimitMin}m intention</span>
              </div>
            </div>
          </section>
        )}

        <section className="stats-block">
          <div className="stats-block-head">LAST 14 DAYS · MEASURED PLAYBACK</div>
          <div className="stats-days">
            {days.map(d => (
              <div key={d.key} className="stats-day" title={`${d.label} · ${fmt(d.sec)}`}>
                <div className="stats-day-bar">
                  <div className="stats-day-fill" style={{ height: Math.max(d.sec > 0 ? 4 : 0, (d.sec / maxDay) * 100) + '%' }}></div>
                </div>
                <div className="stats-day-label">{d.label.slice(3)}</div>
              </div>
            ))}
          </div>
          <div className="stats-foot-line">
            total logged all-time: <b>{fmt(totalLogged)}</b> · counted only while a video is actually playing
          </div>
        </section>

        <section className="stats-block">
          <div className="stats-block-head">WHERE YOUR ATTENTION GOES</div>
          <div className="stats-channels">
            {perChannel.map(({ c, total, seen, ratio }) => (
              <button
                key={c.id}
                className="stats-ch-row"
                onClick={() => dispatch({ type: 'route', route: { type: 'channel', id: c.id } })}
              >
                <span className="stats-ch-mark" style={{ background: c.accent }}>{c.mark}</span>
                <span className="stats-ch-name">{c.name}</span>
                <span className="stats-ch-bar">
                  <span className="stats-ch-fill" style={{ width: (ratio * 100) + '%' }}></span>
                </span>
                <span className="stats-ch-nums">{seen}/{total}</span>
              </button>
            ))}
          </div>
        </section>

        {neverOpened.length > 0 && (
          <section className="stats-block">
            <div className="stats-block-head stats-block-head-warn">WORTH A SECOND LOOK</div>
            <div className="stats-cull-note">
              You haven't watched anything from {neverOpened.length === 1 ? 'this channel' : 'these channels'} —
              following is a choice, and so is unfollowing.
            </div>
            <div className="ch-tags">
              {neverOpened.map(({ c }) => (
                <button key={c.id} className="tag-chip tag-chip-channel"
                  onClick={() => dispatch({ type: 'route', route: { type: 'channel', id: c.id } })}>
                  <span className="tag-dot" style={{ background: c.accent }}></span>
                  {c.name}
                </button>
              ))}
            </div>
          </section>
        )}

        <section className="stats-block">
          <div className="stats-block-head">LIBRARY</div>
          <div className="stats-grid">
            <div className="stats-cell"><span className="num">{visibleChannels.length}</span><span className="lab">channels followed</span></div>
            <div className="stats-cell"><span className="num">{visibleVideos.length}</span><span className="lab">videos in feed</span></div>
            <div className="stats-cell"><span className="num">{watchedVideos.length}</span><span className="lab">watched</span></div>
            <div className="stats-cell"><span className="num">{favorites.size}</span><span className="lab">favorites</span></div>
            <div className="stats-cell"><span className="num">{noteCount}</span><span className="lab">notes taken</span></div>
            <div className="stats-cell"><span className="num">{Object.keys(notes).filter(k => notes[k].length).length}</span><span className="lab">videos with notes</span></div>
          </div>
        </section>
      </div>
    </main>
  );
}

window.Stats = Stats;
