// Progress.jsx — "Compare progress": ONE person's learning growth over time
// (their past self vs their present self). Works for the signed-in learner
// (Today header) and for any individual friend (friend detail → Compare).

// Time windows to compare "now" against. `f` is the fraction of this person's
// current totals that already existed at the START of that window.
const PROGRESS_RANGES = [
  { id: '1m', f: 0.86, label: '1 month ago' },
  { id: '3m', f: 0.58, label: '3 months ago' },
  { id: 'all', f: 0.10, label: 'the start' },
];

// Deterministic 0..1 jitter from a string, so per-domain deltas vary but never
// change between renders.
function pHash(str) {
  let h = 2166136261;
  for (let i = 0; i < str.length; i++) { h ^= str.charCodeAt(i); h = Math.imul(h, 16777619); }
  return ((h >>> 0) % 1000) / 1000;
}

// Compute the user's own "subject" from the same TOPICS/DOMAINS data the rest of
// the app uses.
function meSubject(profile, accentId) {
  const ac = (typeof ACCENTS !== 'undefined' && ACCENTS.find((a) => a.id === accentId)) || null;
  const domains = DOMAINS.map((d) => {
    const ts = TOPICS.filter((t) => t.domain === d.id);
    if (!ts.length) return null;
    return { id: d.id, name: d.name, accent: d.accent,
      progress: Math.round(ts.reduce((s, t) => s + t.progress, 0) / ts.length) };
  }).filter(Boolean);
  const overall = Math.round(TOPICS.reduce((s, t) => s + t.progress, 0) / TOPICS.length);
  const notes = TOPICS.reduce((s, t) => s + (t.notes || 0), 0);
  return {
    name: (profile && profile.name) || 'You', you: true, seed: 'me',
    accent: ac ? ac.light : '#1E8FF0',
    now: { overall, topics: TOPICS.length, notes,
      materials: (typeof MATERIALS !== 'undefined') ? MATERIALS.length : 96, cards: 1240, hours: 86 },
    domains,
  };
}
window.meSubject = meSubject;

// Derive a believable "then" snapshot for `subject` at the chosen window.
function buildProgress(range, subject) {
  const f = range.f;
  const mF = 0.35 + 0.65 * f; // mastery grows slower than raw totals
  const now = subject.now;
  const seed = subject.seed || subject.name || 'x';
  const nowOverall = now.overall;

  const domains = subject.domains.map((d) => {
    const j = 0.9 + pHash(d.id + range.id + seed) * 0.25; // 0.9..1.15
    let then = Math.round(d.progress * mF * j);
    then = Math.max(0, Math.min(d.progress, then)); // progress only ever grows
    return { id: d.id, name: d.name, accent: d.accent, now: d.progress, then };
  });

  const metric = (icon, label, nowV, fac, fmt) => ({ icon, label, now: nowV, then: Math.round(nowV * fac), fmt });
  const metrics = [
    metric('trending', 'Overall mastery', nowOverall, mF, (v) => v + '%'),
    metric('layers', 'Topics tracked', now.topics, f),
    metric('book', 'Notes captured', now.notes, f),
    metric('sparkles', 'Materials generated', now.materials, f),
    metric('cards', 'Cards reviewed', now.cards, f),
    metric('clock', 'Study time logged', now.hours, f, (v) => v + 'h'),
  ];

  const N = 8;
  const series = Array.from({ length: N }, (_, i) => {
    const p = i / (N - 1);
    const base = nowOverall * mF + (nowOverall - nowOverall * mF) * p;
    const wobble = (pHash('s' + range.id + seed + i) - 0.5) * 3 * (p > 0 && p < 1 ? 1 : 0);
    return Math.max(0, Math.min(100, Math.round(base + wobble)));
  });
  series[0] = Math.round(nowOverall * mF);
  series[N - 1] = nowOverall;

  return { domains, metrics, series, nowOverall, thenOverall: Math.round(nowOverall * mF) };
}

// Small SVG area+line sparkline of overall mastery over the window.
function ProgressSpark({ series, color }) {
  const W = 520, H = 92, pad = 6;
  const xs = (i) => pad + i * (W - pad * 2) / (series.length - 1);
  const ys = (v) => H - pad - v / 100 * (H - pad * 2);
  const line = series.map((v, i) => (i ? 'L' : 'M') + xs(i).toFixed(1) + ' ' + ys(v).toFixed(1)).join(' ');
  const area = line + ' L' + xs(series.length - 1).toFixed(1) + ' ' + (H - pad) + ' L' + xs(0).toFixed(1) + ' ' + (H - pad) + ' Z';
  const gid = 'pgSpark' + Math.round(pHash(series.join(',')) * 1e6);
  return (
    <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" style={{ width: '100%', height: 92, display: 'block' }}>
      <defs>
        <linearGradient id={gid} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity="0.28" />
          <stop offset="100%" stopColor={color} stopOpacity="0" />
        </linearGradient>
      </defs>
      <path d={area} fill={`url(#${gid})`} />
      <path d={line} fill="none" stroke={color} strokeWidth="2.5" strokeLinejoin="round" strokeLinecap="round" vectorEffect="non-scaling-stroke" />
      <circle cx={xs(series.length - 1)} cy={ys(series[series.length - 1])} r="4" fill={color} />
    </svg>);
}

function ProgressMetricRow({ icon, label, then, now, fmt, nowColor }) {
  const f = fmt || ((v) => String(v));
  const max = Math.max(now, then, 1);
  const delta = now - then;
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 9 }}>
        <Icon name={icon} size={14} style={{ color: 'var(--ink-3)' }} />
        <span className="mono" style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '.04em', color: 'var(--ink-3)', fontWeight: 700 }}>{label}</span>
        {delta > 0 && <span className="pg-delta" style={{ marginLeft: 'auto' }}><Icon name="trending" size={12} /> +{f(delta)}</span>}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <span className="mono pg-tag" style={{ color: 'var(--ink-3)' }}>Then</span>
          <div className="cmp-track"><i style={{ width: Math.max(3, then / max * 100) + '%', background: 'var(--line-strong)' }} /></div>
          <span className="mono" style={{ fontSize: 12.5, fontWeight: 600, width: 52, textAlign: 'right', color: 'var(--ink-3)' }}>{f(then)}</span>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <span className="mono pg-tag" style={{ color: 'var(--ink)' }}>Now</span>
          <div className="cmp-track"><i style={{ width: Math.max(3, now / max * 100) + '%', background: nowColor }} /></div>
          <span className="mono" style={{ fontSize: 12.5, fontWeight: 600, width: 52, textAlign: 'right', color: 'var(--ink)' }}>{f(now)}</span>
        </div>
      </div>
    </div>);
}

// `subject` = { name, you, accent, seed, now:{overall,topics,notes,materials,cards,hours}, domains:[{id,name,accent,progress}] }
function ProgressCompareModal({ subject, onClose }) {
  const [rangeId, setRangeId] = React.useState('3m');
  const range = PROGRESS_RANGES.find((r) => r.id === rangeId) || PROGRESS_RANGES[1];
  const data = React.useMemo(() => buildProgress(range, subject), [rangeId, subject]);
  const overallDelta = data.nowOverall - data.thenOverall;
  const first = (subject.name || 'You').split(' ')[0];
  const nowColor = subject.accent || 'var(--blue)';
  const possessive = subject.you ? 'Your' : first + '\u2019s';
  // "When you/they started" reads better than the generic 'the start' label.
  const rangeLabel = (r) => r.id === 'all' ? (subject.you ? 'When you started' : 'When ' + first + ' started') : r.label;

  return ReactDOM.createPortal(
    <div className="scrim" onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal" style={{ maxWidth: 640, width: '92vw', maxHeight: '90vh', display: 'flex', flexDirection: 'column' }}>
        <div className="mhead">
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <Icon name="chart" size={18} style={{ color: 'var(--ink-3)' }} />
            <div style={{ fontWeight: 600, fontSize: 16 }}>{possessive} progress over time</div>
          </div>
          <button className="icon-btn" style={{ width: 32, height: 32, border: 'none' }} onClick={onClose}><Icon name="x" size={18} /></button>
        </div>

        <div className="mbody" style={{ overflowY: 'auto', padding: '20px 24px 26px' }}>
          {/* range picker */}
          <div className="segmented" style={{ marginBottom: 20 }}>
            {PROGRESS_RANGES.map((r) =>
            <button key={r.id} className={rangeId === r.id ? 'on' : ''} onClick={() => setRangeId(r.id)}>{r.label}</button>
            )}
          </div>

          {/* headline: then → now mastery + trend */}
          <div className="card pad" style={{ padding: '18px 20px', marginBottom: 20 }}>
            <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 14, flexWrap: 'wrap' }}>
              <div>
                <div className="mono" style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '.04em', color: 'var(--ink-3)', fontWeight: 700 }}>Overall mastery</div>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginTop: 6 }}>
                  <span style={{ fontSize: 22, fontWeight: 600, color: 'var(--ink-3)' }}>{data.thenOverall}%</span>
                  <Icon name="arrow-right" size={18} style={{ color: 'var(--ink-4)' }} />
                  <span style={{ fontSize: 34, fontWeight: 600, letterSpacing: '-0.02em', color: nowColor, lineHeight: 1 }}>{data.nowOverall}%</span>
                </div>
              </div>
              {overallDelta > 0 && <span className="pg-delta lg"><Icon name="trending" size={15} /> +{overallDelta} points</span>}
            </div>
            <div style={{ marginTop: 14 }}><ProgressSpark series={data.series} color={nowColor} /></div>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 4 }}>
              <span className="mono" style={{ fontSize: 10.5, color: 'var(--ink-4)' }}>{rangeLabel(range)}</span>
              <span className="mono" style={{ fontSize: 10.5, color: 'var(--ink-4)' }}>Today</span>
            </div>
          </div>

          {/* legend */}
          <div style={{ display: 'flex', gap: 18, margin: '0 2px 16px' }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontSize: 12.5, color: 'var(--ink-2)' }}>
              <span style={{ width: 12, height: 12, borderRadius: 3, background: 'var(--line-strong)' }} /> Then</span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontSize: 12.5, color: 'var(--ink-2)' }}>
              <span style={{ width: 12, height: 12, borderRadius: 3, background: nowColor }} /> Now</span>
          </div>

          {/* metric rows */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 17 }}>
            {data.metrics.map((m, i) => <ProgressMetricRow key={i} {...m} nowColor={nowColor} />)}
          </div>

          {/* per-domain growth */}
          <div style={{ marginTop: 26, paddingTop: 20, borderTop: '1px solid var(--line)' }}>
            <div className="mono" style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '.04em', color: 'var(--ink-3)', fontWeight: 700, marginBottom: 14 }}>Mastery growth by domain</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              {data.domains.sort((a, b) => (b.now - b.then) - (a.now - a.then)).map((d) => {
                const delta = d.now - d.then;
                return (
                  <div key={d.id}>
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, marginBottom: 5 }}>
                      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontSize: 13, fontWeight: 500, minWidth: 0 }}>
                        <span style={{ width: 8, height: 8, borderRadius: 99, background: d.accent, flex: 'none' }} />
                        <span style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{d.name}</span>
                      </span>
                      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, flex: 'none' }}>
                        <span className="mono" style={{ fontSize: 12, color: 'var(--ink-3)' }}>{d.then}% → <strong style={{ color: 'var(--ink)' }}>{d.now}%</strong></span>
                        {delta > 0 && <span className="pg-delta sm">+{delta}</span>}
                      </span>
                    </div>
                    <div className="cmp-track sm" style={{ position: 'relative' }}>
                      <i style={{ width: Math.max(2, d.then) + '%', background: 'var(--line-strong)', position: 'absolute', inset: 0 }} />
                      <i style={{ width: Math.max(2, d.now) + '%', background: d.accent, position: 'absolute', inset: 0, opacity: 0.85 }} />
                    </div>
                  </div>);
              })}
            </div>
          </div>
        </div>
      </div>
    </div>,
    document.body
  );
}

window.ProgressCompareModal = ProgressCompareModal;
