// app/screens-progress.jsx — progress, streaks, pace, per-book completion.
const { useMemo: useMemoPr } = React;

// circular progress ring
function Ring({ pct, size = 150, stroke = 12, color, track, font, accent, label, sub }) {
  const r = (size - stroke) / 2;
  const c = 2 * Math.PI * r;
  const off = c * (1 - Math.max(0, Math.min(100, pct)) / 100);
  return (
    <div style={{ position: 'relative', width: size, height: size }}>
      <svg width={size} height={size} style={{ transform: 'rotate(-90deg)' }}>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke={track} strokeWidth={stroke} />
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke={color} strokeWidth={stroke}
          strokeLinecap="round" strokeDasharray={c} strokeDashoffset={off} style={{ transition: 'stroke-dashoffset 0.6s cubic-bezier(.3,.7,.4,1)' }} />
      </svg>
      <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
        <div style={{ fontFamily: font, fontSize: 40, color: color, fontWeight: 700, lineHeight: 1 }}>{label}</div>
        <div style={{ fontSize: 12, color: sub.color, fontWeight: 600, marginTop: 4 }}>{sub.text}</div>
      </div>
    </div>
  );
}

function StatCell({ t, accent, font, value, label, icon }) {
  return (
    <div style={{ flex: 1, background: t.surface, borderRadius: 16, border: `1px solid ${t.line}`, padding: '14px 12px' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, color: accent.base, marginBottom: 8 }}>
        <Icon name={icon} size={17} stroke={1.9} />
      </div>
      <div style={{ fontFamily: font, fontSize: 26, color: t.ink, fontWeight: 700, lineHeight: 1 }}>{value}</div>
      <div style={{ fontSize: 11.5, color: t.ink3, fontWeight: 600, marginTop: 4 }}>{label}</div>
    </div>
  );
}

function ProgressScreen({ t, accent, font, plan, completed, stats }) {
  const todayDate = window.ymd(window.today());

  const extra = useMemoPr(() => {
    // longest streak across all plan days
    let longest = 0, run = 0;
    plan.days.forEach(d => {
      if (completed[d.date]) { run++; longest = Math.max(longest, run); } else run = 0;
    });
    // pace: how many days should be done by today vs actually done
    const dueByToday = plan.days.filter(d => d.date <= todayDate).length;
    const aheadBy = stats.done - dueByToday; // + ahead, - behind
    // per-book completion from verses read (sequential mapping)
    let read = stats.versesRead;
    const books = window.BOOKS.map(b => {
      const took = Math.max(0, Math.min(b.verses, read));
      read -= b.verses;
      return { name: b.name, abbr: b.abbr, pct: Math.round((took / b.verses) * 100), verses: b.verses };
    });
    const booksDone = books.filter(b => b.pct >= 100).length;
    return { longest, aheadBy, dueByToday, books, booksDone };
  }, [plan, completed, stats]);

  const onPace = extra.aheadBy >= 0;

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      <div style={{ padding: '52px 20px 6px' }}>
        <div style={{ fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase', color: accent.base, fontWeight: 700 }}>Your journey</div>
        <div style={{ fontFamily: font, fontSize: 26, color: t.ink, fontWeight: 600, marginTop: 2 }}>Progress</div>
      </div>

      <div className="bom-scroll" style={{ flex: 1, overflowY: 'auto', padding: '12px 18px 120px' }}>
        {/* ring + streak */}
        <div style={{ background: t.hero, borderRadius: 22, padding: '22px', display: 'flex', alignItems: 'center', gap: 20, position: 'relative', overflow: 'hidden' }}>
          <div style={{ position: 'absolute', inset: 9, border: `1px solid ${accent.base}`, opacity: 0.18, borderRadius: 15, pointerEvents: 'none' }} />
          <Ring pct={stats.pct} size={132} stroke={11} color={accent.base} track="rgba(255,255,255,0.12)" font={font} accent={accent}
            label={`${stats.pct}%`} sub={{ text: `${stats.done} of ${stats.total} days`, color: t.heroSub }} />
          <div style={{ flex: 1 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ color: accent.base }}><Icon name="flame" size={26} stroke={1.9} /></span>
              <span style={{ fontFamily: font, fontSize: 38, color: t.heroInk, fontWeight: 700, lineHeight: 1 }}>{stats.streak}</span>
            </div>
            <div style={{ fontSize: 13, color: t.heroSub, fontWeight: 600, marginTop: 4 }}>day streak</div>
            <div style={{ marginTop: 14, fontSize: 13.5, color: t.heroInk, fontWeight: 500, lineHeight: 1.4 }}>
              {stats.versesRead.toLocaleString()} verses read
            </div>
          </div>
        </div>

        {/* pace banner */}
        <div style={{ marginTop: 14, display: 'flex', alignItems: 'center', gap: 12, background: onPace ? accent.soft : t.surface, border: `1px solid ${onPace ? accent.base : t.line}`, borderRadius: 16, padding: '14px 16px' }}>
          <div style={{ width: 40, height: 40, borderRadius: 11, background: onPace ? accent.base : t.sunken, color: onPace ? accent.ink : t.ink3, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <Icon name={onPace ? 'check' : 'flame'} size={22} stroke={2.1} />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: font, fontSize: 16, color: t.ink, fontWeight: 600 }}>
              {extra.aheadBy === 0 ? 'Right on pace' : onPace ? `${extra.aheadBy} day${extra.aheadBy > 1 ? 's' : ''} ahead` : `${-extra.aheadBy} day${extra.aheadBy < -1 ? 's' : ''} behind`}
            </div>
            <div style={{ fontSize: 12.5, color: t.ink3, fontWeight: 500, marginTop: 1 }}>
              {onPace ? 'Keep the steady rhythm going.' : 'A short reading or two will catch you up.'}
            </div>
          </div>
        </div>

        {/* stat grid */}
        <div style={{ display: 'flex', gap: 10, marginTop: 14 }}>
          <StatCell t={t} accent={accent} font={font} value={extra.longest} label="Longest streak" icon="flame" />
          <StatCell t={t} accent={accent} font={font} value={extra.booksDone} label="Books finished" icon="book" />
          <StatCell t={t} accent={accent} font={font} value={Math.max(0, stats.total - stats.done)} label="Days to go" icon="plan" />
        </div>

        {/* per-book completion */}
        <div style={{ marginTop: 22, marginBottom: 10, padding: '0 4px', display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
          <span style={{ fontFamily: font, fontSize: 19, color: t.ink, fontWeight: 600 }}>The fifteen books</span>
          <span style={{ fontSize: 11.5, color: t.ink3, fontWeight: 600 }}>{extra.booksDone}/15 complete</span>
        </div>
        <div style={{ background: t.surface, borderRadius: 18, border: `1px solid ${t.line}`, padding: '6px 16px' }}>
          {extra.books.map((b, i) => (
            <div key={b.abbr} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '11px 0', borderTop: i ? `1px solid ${t.hairline}` : 'none' }}>
              <div style={{ width: 92, flexShrink: 0, fontFamily: font, fontSize: 15, color: t.ink, fontWeight: 600, whiteSpace: 'nowrap' }}>{b.name}</div>
              <div style={{ flex: 1 }}><Bar pct={b.pct} color={b.pct >= 100 ? accent.base : accent.base} track={t.sunken} height={6} /></div>
              <div style={{ width: 34, textAlign: 'right', fontSize: 11.5, color: b.pct >= 100 ? accent.base : t.ink3, fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>
                {b.pct >= 100 ? '✓' : `${b.pct}%`}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ProgressScreen });
