/* Brand Lens — scoreboard: alignment, calibration, divergences */
function Scoreboard({ recs, goReview, goGuide }) {
  const reviewed = useMemo(() => recs.filter((r) => r.user && r.ai), [recs]);

  const m = useMemo(() => {
    let kk = 0, kr = 0, rk = 0, rr = 0;        // you-keep/AI-keep ... you-reject/AI-reject
    let likedScores = [], dislikedScores = [];
    for (const r of reviewed) {
      const aiKeep = r.ai.verdict === 'keep';
      const youKeep = !!r.user.like;
      if (youKeep && aiKeep) kk++;
      else if (youKeep && !aiKeep) kr++;
      else if (!youKeep && aiKeep) rk++;
      else rr++;
      (youKeep ? likedScores : dislikedScores).push(r.ai.score);
    }
    const aligned = kk + rr;
    const total = reviewed.length;
    const avg = (a) => (a.length ? Math.round(a.reduce((x, y) => x + y, 0) / a.length) : null);
    return { kk, kr, rk, rr, aligned, total,
      pct: total ? Math.round((aligned / total) * 100) : 0,
      avgLiked: avg(likedScores), avgDisliked: avg(dislikedScores) };
  }, [reviewed]);

  const divergences = useMemo(
    () => reviewed.filter((r) => (r.ai.verdict === 'keep') !== !!r.user.like)
      .sort((a, b) => Math.abs(b.ai.score - 50) - Math.abs(a.ai.score - 50)),
    [reviewed]
  );

  if (reviewed.length === 0) {
    return <Empty title="No reviews yet" body="React to a few of the AI's calls and your agreement scoreboard builds here." cta="Start calibrating" onCta={goReview} />;
  }

  const brief = window.Lens.getLearnedBrief();

  return (
    <div>
      <h2 style={{ fontSize: 'clamp(26px,2.8vw,34px)', margin: 0, fontWeight: 500, letterSpacing: '-.015em' }}>Scoreboard</h2>
      <p style={{ fontSize: 16, color: 'var(--fg-2)', margin: '10px 0 22px', maxWidth: '62ch', lineHeight: 1.6 }}>
        How often you agreed with the AI's call across {m.total} reviewed {m.total === 1 ? 'image' : 'images'} — and where you didn't. Refresh the style guide between rounds to re-teach the judge; this number should climb.
      </p>

      {brief && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '11px 16px', marginBottom: 22, fontSize: 13.5,
          background: 'var(--ps-aqua-100)', color: 'var(--ps-aqua-700)', borderRadius: 10 }}>
          <Icon name="sparkle" size={15} /> The judge is currently calibrated from {brief.basedOn} of your reviews. Agreement above reflects that calibration.
        </div>
      )}

      <div style={{ display: 'grid', gridTemplateColumns: 'auto 1fr', gap: 26, alignItems: 'center',
        background: 'var(--ps-cloud-gray)', border: '1px solid var(--ps-line)', borderRadius: 18, padding: '26px 30px', marginBottom: 26, flexWrap: 'wrap' }}>
        <ScoreRing score={m.pct} size={132} label="agreed" />
        <div>
          <div style={{ fontSize: 22, fontWeight: 500, color: 'var(--ps-navy)', lineHeight: 1.25, maxWidth: '40ch' }}>
            {m.pct >= 80 ? 'The AI reads your taste well.' : m.pct >= 55 ? 'The AI is roughly tracking your taste.' : 'The AI and your taste diverge a lot — refresh the guide to recalibrate it.'}
          </div>
          <div style={{ fontSize: 14, color: 'var(--fg-2)', marginTop: 8 }}>
            You agreed with {m.aligned} of {m.total} calls · {divergences.length} divergence{divergences.length === 1 ? '' : 's'} to learn from.
          </div>
        </div>
      </div>

      {/* confusion matrix */}
      <h2 style={{ fontSize: 20, fontWeight: 500, margin: '0 0 14px' }}>Where the calls landed</h2>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 14, marginBottom: 30 }}>
        <Cell n={m.kk} aligned label="You kept · AI kept" sub="Clear brand fit you both saw." />
        <Cell n={m.rr} aligned label="You passed · AI passed" sub="Clear miss you both caught." />
        <Cell n={m.rk} label="You passed · AI kept" sub="AI too lenient — it liked what you didn't." />
        <Cell n={m.kr} label="You kept · AI passed" sub="AI too harsh — it missed one you liked." />
      </div>

      {/* calibration */}
      <h2 style={{ fontSize: 20, fontWeight: 500, margin: '0 0 6px' }}>Score calibration</h2>
      <p style={{ fontSize: 14, color: 'var(--fg-2)', margin: '0 0 16px', maxWidth: '64ch', lineHeight: 1.6 }}>
        Average brand-fit score the AI gave the images you actually kept vs. the ones you passed. A big gap means the score is a reliable proxy for your taste.
      </p>
      <div style={{ background: 'var(--ps-white)', border: '1px solid var(--ps-line)', borderRadius: 16, padding: '22px 24px', marginBottom: 32 }}>
        <CalBar label="Images you kept" score={m.avgLiked} good />
        <CalBar label="Images you passed" score={m.avgDisliked} />
        {m.avgLiked != null && m.avgDisliked != null && (
          <div style={{ fontSize: 13.5, color: 'var(--fg-2)', marginTop: 14, paddingTop: 14, borderTop: '1px solid var(--ps-line)' }}>
            Separation of <b style={{ color: 'var(--ps-navy)' }}>{Math.abs(m.avgLiked - m.avgDisliked)} points</b>
            {Math.abs(m.avgLiked - m.avgDisliked) >= 25 ? ' — the score tracks your taste well.' : ' — modest; your taste has nuance the raw score misses.'}
          </div>
        )}
      </div>

      {/* divergences */}
      {divergences.length > 0 && (
        <>
          <h2 style={{ fontSize: 20, fontWeight: 500, margin: '0 0 6px' }}>Learn from the divergences</h2>
          <p style={{ fontSize: 14, color: 'var(--fg-2)', margin: '0 0 16px', maxWidth: '64ch', lineHeight: 1.6 }}>
            The images where you and the AI disagreed. These carry the most signal about what makes your taste yours.
          </p>
          <div style={{ display: 'grid', gap: 14, marginBottom: 30 }}>
            {divergences.map((r) => <DivergeRow key={r.id} rec={r} />)}
          </div>
        </>
      )}

      <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
        <Btn kind="primary" icon="sparkle" onClick={goGuide}>Build the style guide</Btn>
        {recs.some((r) => !r.user) && <Btn icon="arrow" onClick={goReview}>Keep reviewing</Btn>}
      </div>
    </div>
  );
}

function Cell({ n, label, sub, aligned }) {
  return (
    <div style={{ border: `1px solid ${aligned ? '#BFE6D4' : 'var(--ps-line)'}`, borderRadius: 14, padding: '18px 20px',
      background: aligned ? '#F2FAF6' : 'var(--ps-white)' }}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
        <span style={{ fontSize: 32, fontWeight: 700, color: aligned ? '#1F7A52' : 'var(--ps-navy)', lineHeight: 1 }}>{n}</span>
        <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--fg-1)' }}>{label}</span>
      </div>
      <div style={{ fontSize: 13, color: 'var(--fg-2)', marginTop: 7, lineHeight: 1.5 }}>{sub}</div>
    </div>
  );
}

function CalBar({ label, score, good }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '8px 0' }}>
      <div style={{ width: 130, fontSize: 13.5, fontWeight: 600, color: 'var(--fg-1)', flex: 'none' }}>{label}</div>
      <div style={{ flex: 1, height: 14, background: 'var(--ps-cloud-gray)', borderRadius: 8, overflow: 'hidden' }}>
        <div style={{ width: `${score || 0}%`, height: '100%', borderRadius: 8,
          background: good ? 'var(--st-success)' : 'var(--ps-flag)', transition: 'width .6s var(--ease-out)' }} />
      </div>
      <div style={{ width: 44, textAlign: 'right', fontSize: 15, fontWeight: 700, color: 'var(--ps-navy)', flex: 'none' }}>
        {score == null ? '—' : score}
      </div>
    </div>
  );
}

function DivergeRow({ rec }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '92px 1fr', gap: 16, alignItems: 'center',
      background: 'var(--ps-white)', border: '1px solid var(--ps-line)', borderRadius: 14, padding: 12, boxShadow: 'var(--sh-1)' }}>
      <img src={rec.dataURL} alt={rec.name} style={{ width: 92, height: 70, objectFit: 'cover', borderRadius: 9, display: 'block' }} />
      <div>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center', marginBottom: 7 }}>
          <span style={{ fontSize: 12, color: 'var(--fg-3)' }}>You</span><VerdictPill verdict={rec.user.like ? 'keep' : 'reject'} />
          <Icon name="arrow" size={13} style={{ color: 'var(--ps-line-strong)' }} />
          <span style={{ fontSize: 12, color: 'var(--fg-3)' }}>AI</span><VerdictPill verdict={rec.ai.verdict} />
          <span style={{ fontSize: 12, color: 'var(--fg-3)', marginLeft: 'auto' }}>fit {rec.ai.score}</span>
        </div>
        <div style={{ fontSize: 13, color: 'var(--fg-2)', lineHeight: 1.5 }}>
          {rec.user.comment ? <span style={{ fontStyle: 'italic' }}>“{rec.user.comment}”</span> : <span style={{ color: 'var(--fg-3)' }}>No note left.</span>}
          {' '}<span style={{ color: 'var(--fg-3)' }}>· AI: {rec.ai.headline}</span>
        </div>
      </div>
    </div>
  );
}

function Empty({ title, body, cta, onCta }) {
  return (
    <div style={{ maxWidth: 520, margin: '60px auto', textAlign: 'center' }}>
      <h2 style={{ fontSize: 30, fontWeight: 500, margin: 0 }}>{title}</h2>
      <p style={{ fontSize: 16, color: 'var(--fg-2)', lineHeight: 1.6, margin: '12px 0 22px' }}>{body}</p>
      <Btn kind="primary" icon="arrow" onClick={onCta}>{cta}</Btn>
    </div>
  );
}

window.Scoreboard = Scoreboard;
window.LensEmpty = Empty;
