/* screens/Final.jsx — post-tournament recap. window.FinalScreen */
/* actual: { actualResults, actualKO, actualBracket } from WCLogic.computeActual(realScores) */
function FinalScreen({ store, go, actual, realScores }) {
  const { results, ko, name } = store.state;
  const L = window.WCLogic;
  const userBracket = L.buildBracket(results, ko);

  const actualKO      = (actual && actual.actualKO)      || L.ACTUAL_KO;
  const actualBracket = (actual && actual.actualBracket) || L.ACTUAL_BRACKET;

  const full = L.fullAccuracyReal(results, ko, realScores);
  // R16+ and the champion call are derived from a simulated bracket until every
  // group fixture has a real result — showing them earlier would present a
  // fabricated "actual" champion/qualifier set as fact.
  const groupStageDone = full.group.played >= window.WC.fixtures.length;

  const actualChamp = actualKO['F-1'];
  const userChamp = userBracket.champ;
  const champRight = groupStageDone && userChamp && userChamp === actualChamp;

  const koRows = [
    ['Round of 16 qualifiers', L.reachAccuracy(userBracket.rounds, 'R16', actualBracket).hit, 16, 'teams in the last 16'],
    ['Quarter-finalists',      L.reachAccuracy(userBracket.rounds, 'QF',  actualBracket).hit, 8,  'teams in the last 8'],
    ['Semi-finalists',         L.reachAccuracy(userBracket.rounds, 'SF',  actualBracket).hit, 4,  'teams in the last 4'],
    ['Finalists',              L.reachAccuracy(userBracket.rounds, 'F',   actualBracket).hit, 2,  'teams in the final'],
  ];

  return (
    <div className="page">
      <header className="phead">
        <div>
          <div className="eyebrow">{groupStageDone ? 'Full time · Tournament recap' : 'Tournament in progress · Recap so far'}</div>
          <h1 className="section-h">{groupStageDone ? 'How you did' : "How you're doing so far"}</h1>
          <p className="muted phead__sub">
            {groupStageDone
              ? `The whole World Cup, scored. Here's your bracket against the way it actually played out${name ? ', ' + name : ''}.`
              : `The group stage is still underway — here's your accuracy on matches played so far${name ? ', ' + name : ''}. Your knockout bracket and champion pick are scored once the group stage wraps up.`}
          </p>
        </div>
      </header>

      <div className="recap">
        <div className={`recap__hero ${champRight ? 'is-champ' : ''}`}>
          <div className="recap__bigwrap">
            <div className="recap__big display tnum">{full.correct}<span className="recap__of">/{full.total}</span></div>
            <div className="recap__bigsub">matches predicted correctly</div>
            <div className="recap__badge"><AccuracyBadge pct={full.pct} size="lg" /> overall accuracy</div>
          </div>

          <div className="recap__champ">
            <div className={`trophy ${champRight ? 'trophy--win' : ''}`}><IconTrophy size={champRight ? 56 : 40} /></div>
            {!groupStageDone ? (
              <>
                <div className="recap__champlbl">Your champion pick</div>
                <div className="recap__champteam display">
                  {userChamp ? <><span style={{ fontSize: 26 }}>{window.WC.team(userChamp).flag}</span> {window.WC.team(userChamp).name}</> : '—'}
                </div>
                <div className="muted" style={{ fontSize: 12, marginTop: 4 }}>🔒 Revealed once the group stage completes</div>
              </>
            ) : champRight ? (
              <>
                <div className="recap__champlbl" style={{ color: 'var(--gold-bright)' }}>You called the champion</div>
                <div className="recap__champteam display"><span style={{ fontSize: 30 }}>{window.WC.team(actualChamp).flag}</span> {window.WC.team(actualChamp).name}</div>
                <Verdict ok={true} size={22} />
              </>
            ) : (
              <>
                <div className="recap__champlbl">Champion</div>
                <div className="recap__champteam display"><span style={{ fontSize: 26 }}>{window.WC.team(actualChamp).flag}</span> {window.WC.team(actualChamp).name}</div>
                <div className="muted" style={{ fontSize: 12, marginTop: 4 }}>You picked {userChamp ? window.WC.team(userChamp).name : '—'}</div>
              </>
            )}
          </div>
        </div>

        <div className="recap__break">
          <div className="recap__breakh">Breakdown by stage</div>
          <div className="brk">
            <div className="brk__top">
              <span className="brk__label">Group stage</span>
              <span className="brk__val tnum"><b>{full.group.correct}</b><span className="muted">/{full.group.played}</span></span>
            </div>
            <div className="brk__bar"><i data-level={L.accuracyClass(full.pct)} style={{ width: full.pct + '%' }} /></div>
            <div className="brk__note muted">match results so far</div>
          </div>

          {groupStageDone ? koRows.map(([label, hit, total, note]) => {
            const pct = Math.round(hit / total * 100);
            return (
              <div className="brk" key={label}>
                <div className="brk__top">
                  <span className="brk__label">{label}</span>
                  <span className="brk__val tnum"><b>{hit}</b><span className="muted">/{total}</span></span>
                </div>
                <div className="brk__bar"><i data-level={L.accuracyClass(pct)} style={{ width: pct + '%' }} /></div>
                <div className="brk__note muted">{note}</div>
              </div>
            );
          }) : (
            <div className="brk">
              <div className="brk__note muted">🔒 Knockout bracket + champion call unlock once the group stage finishes ({full.group.played}/{window.WC.fixtures.length} matches played so far).</div>
            </div>
          )}

          {groupStageDone && (
            <div className="brk brk--champ">
              <div className="brk__top">
                <span className="brk__label">Champion call</span>
                <Verdict ok={!!champRight} size={20} />
              </div>
            </div>
          )}
        </div>
      </div>

      <div className="recap__cta">
        <Btn size="lg" onClick={() => go('summary')}><IconShare size={16} /> Share my recap</Btn>
        <Btn variant="ghost" size="lg" onClick={() => go('knockout')}>Review my bracket</Btn>
      </div>
    </div>
  );
}
window.FinalScreen = FinalScreen;
