// =============================================================================
// HISTORY — Week-by-week timeline graph
// =============================================================================

function History({ activeWeek }) {
  const { teams, scoresByWeek, loading } = useLiveSeasonData();

  const data = teams.map(team => {
    const weekTotals = RVL_WEEKS.map(w => rvlTeamWeekTotalLive(team, scoresByWeek[w.id] || {}));
    const cumulative = []; let acc = 0;
    for (const wt of weekTotals) { acc += wt; cumulative.push(acc); }
    return { team, weekTotals, cumulative };
  });

  const [highlight, setHighlight] = useState(null);
  const [hover, setHover] = useState(null); // { teamId, name, value, week, x, y, color }

  if (loading || teams.length === 0) return <PageLoader label="Loading season history…"/>;

  const maxCum = Math.max(...data.flatMap(d => d.cumulative), 1);
  const W = 1000, H = 420, PAD_L = 60, PAD_R = 40, PAD_T = 24, PAD_B = 44;

  const xScale = (i) => PAD_L + (i / (RVL_WEEKS.length - 1)) * (W - PAD_L - PAD_R);
  const yScale = (v) => PAD_T + (1 - v / maxCum) * (H - PAD_T - PAD_B);

  // Sort for legend by final cum
  const sorted = [...data].sort((a,b) => b.cumulative[b.cumulative.length - 1] - a.cumulative[a.cumulative.length - 1]);

  return (
    <div className="rise">
      <div style={{ marginBottom: 24 }}>
        <div className="kicker">Timeline</div>
        <h1 style={{ fontSize: 32, marginBottom: 4 }}>Season Trajectory</h1>
        <p style={{ color: "var(--ink-mute)", fontSize: 14 }}>Cumulative points across all six weeks. Hover a team in the legend to highlight.</p>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1fr) 320px", gap: 16 }} className="history-grid">
      <div className="card" style={{ padding: 20 }}>
        <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ display: "block" }}>
          {/* Y grid */}
          {[0, 0.25, 0.5, 0.75, 1].map(p => (
            <g key={p}>
              <line x1={PAD_L} y1={yScale(maxCum * p)} x2={W - PAD_R} y2={yScale(maxCum * p)} stroke="var(--line)" strokeDasharray={p === 0 ? "0" : "2 4"}/>
              <text x={PAD_L - 8} y={yScale(maxCum * p) + 4} fontSize="11" fill="var(--ink-mute)" textAnchor="end" fontFamily="var(--font-mono)">{Math.round(maxCum * p).toLocaleString()}</text>
            </g>
          ))}
          {/* X labels */}
          {RVL_WEEKS.map((w, i) => (
            <g key={w.id}>
              <text x={xScale(i)} y={H - 18} fontSize="11" fill="var(--ink-mute)" textAnchor="middle">{w.label}</text>
              <text x={xScale(i)} y={H - 4}  fontSize="9"  fill="var(--ink-mute)" textAnchor="middle">{w.short}</text>
              {w.id === activeWeek && (
                <line x1={xScale(i)} y1={PAD_T} x2={xScale(i)} y2={H - PAD_B} stroke="var(--gold)" strokeDasharray="3 5" opacity="0.4"/>
              )}
            </g>
          ))}
          {/* Lines */}
          {data.map(d => {
            const isHighlighted = highlight === d.team.id || hover?.teamId === d.team.id;
            const someActive = highlight || hover;
            const dimmed = someActive && !isHighlighted;
            const path = d.cumulative.map((v, i) => `${i === 0 ? "M" : "L"} ${xScale(i)} ${yScale(v)}`).join(" ");
            const lastX = xScale(d.cumulative.length - 1);
            const lastY = yScale(d.cumulative[d.cumulative.length - 1]);
            return (
              <g key={d.team.id} opacity={dimmed ? 0.15 : 1} style={{ transition: "opacity .15s ease" }}>
                <path d={path} fill="none" stroke={d.team.crest.primary} strokeWidth={isHighlighted ? 3.5 : 2} strokeLinecap="round" strokeLinejoin="round"/>
                {d.cumulative.map((v, i) => (
                  <g key={i}>
                    <circle cx={xScale(i)} cy={yScale(v)} r={isHighlighted ? 5 : 3} fill={d.team.crest.primary} stroke="#0f0a0b" strokeWidth="1.5"/>
                    <circle cx={xScale(i)} cy={yScale(v)} r={14} fill="transparent" style={{ cursor: "pointer" }}
                      onMouseEnter={() => setHover({ teamId: d.team.id, name: d.team.name, value: v, week: RVL_WEEKS[i].label, x: xScale(i), y: yScale(v), color: d.team.crest.primary })}
                      onMouseLeave={() => setHover(null)}/>
                  </g>
                ))}
                {isHighlighted && (() => {
                  const label = d.team.name;
                  const lw = label.length * 7.2 + 18;
                  const lh = 22;
                  let lx = lastX - lw - 10;
                  let ly = lastY - lh / 2;
                  if (lx < PAD_L + 4) lx = lastX + 10;
                  if (ly < PAD_T + 2) ly = PAD_T + 2;
                  if (ly + lh > H - PAD_B - 2) ly = H - PAD_B - lh - 2;
                  return (
                    <g style={{ pointerEvents: "none" }}>
                      <rect x={lx} y={ly} width={lw} height={lh} rx="5" fill={d.team.crest.primary}/>
                      <text x={lx + lw / 2} y={ly + 15} fontSize="12" fontWeight="800" fill="#fff" textAnchor="middle">{label}</text>
                    </g>
                  );
                })()}
              </g>
            );
          })}

          {/* Tooltip */}
          {hover && (() => {
            const lines = [hover.name, `${hover.week} · ${hover.value.toLocaleString()} pts`];
            const padX = 12, padY = 12;
            const tw = Math.max(140, hover.name.length * 7 + 24);
            const th = 56;
            let tx = hover.x + 14;
            let ty = hover.y - th - 10;
            if (tx + tw > W - 8) tx = hover.x - tw - 14;
            if (ty < PAD_T) ty = hover.y + 14;
            return (
              <g style={{ pointerEvents: "none" }}>
                <line x1={hover.x} y1={PAD_T} x2={hover.x} y2={H - PAD_B} stroke={hover.color} strokeDasharray="3 3" opacity="0.55"/>
                <rect x={tx} y={ty} width={tw} height={th} rx="8"
                  fill="#0f0a0b" stroke={hover.color} strokeWidth="1.5"/>
                <text x={tx + padX} y={ty + padY + 12} fontSize="13" fontWeight="800" fill={hover.color}>{lines[0]}</text>
                <text x={tx + padX} y={ty + padY + 32} fontSize="11" fill="#fff" opacity="0.85">{lines[1]}</text>
              </g>
            );
          })()}
        </svg>
      </div>

      {/* Right-side legend */}
      <div className="card" style={{ padding: 0, overflow: "hidden", display: "flex", flexDirection: "column" }}>
        <div style={{ padding: "12px 16px", borderBottom: "1px solid var(--line)" }}>
          <div className="kicker" style={{ marginBottom: 2 }}>Teams</div>
          <div style={{ fontSize: 11, color: "var(--ink-mute)" }}>Hover to highlight on chart</div>
        </div>
        <div style={{ overflowY: "auto", flex: 1, maxHeight: 460 }}>
          {sorted.map((d, idx) => (
            <div key={d.team.id}
                 onMouseEnter={() => setHighlight(d.team.id)}
                 onMouseLeave={() => setHighlight(null)}
                 style={{
                   display: "grid", gridTemplateColumns: "24px 32px 1fr auto",
                   gap: 10, alignItems: "center",
                   padding: "10px 14px",
                   background: highlight === d.team.id ? "var(--bg-card-2)" : "transparent",
                   borderLeft: `3px solid ${highlight === d.team.id ? d.team.crest.primary : "transparent"}`,
                   borderBottom: idx < sorted.length - 1 ? "1px solid var(--line)" : 0,
                   cursor: "pointer",
                   transition: "background .12s ease, border-color .12s ease",
                 }}>
              <div style={{ fontWeight: 700, color: "var(--ink-mute)", fontFamily: "var(--font-mono)", fontSize: 12 }}>#{idx + 1}</div>
              <TeamCrest team={d.team} size={28}/>
              <div style={{ minWidth: 0 }}>
                <div style={{ fontWeight: 600, fontSize: 12, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{d.team.name}</div>
                <div style={{ fontSize: 10, color: "var(--ink-mute)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{d.team.captain?.name || "—"}</div>
              </div>
              <div className="display" style={{ fontSize: 15, color: "var(--gold-light)", fontFamily: "var(--font-mono)" }}>{d.cumulative[d.cumulative.length - 1].toLocaleString()}</div>
            </div>
          ))}
        </div>
      </div>
      </div>

      <style>{`
        @media (max-width: 980px) {
          .history-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </div>
  );
}

// =============================================================================
// WEEKLY RECAP — shareable WhatsApp card
// =============================================================================

function WeeklyRecap({ activeWeek }) {
  const week = RVL_WEEKS.find(w => w.id === activeWeek);
  const fallbackFocus = RVL_WEEKLY_FOCUS[activeWeek] || {};
  const { teams, scoresByWeek, loading } = useLiveSeasonData();
  const [cms, setCms] = useState({});
  useEffect(() => {
    RvlApi.publicSiteSettings().then(d => d && setCms(d)).catch(() => {});
  }, []);
  const focus = {
    emoji:    cms[`focus_${activeWeek}_emoji`]    || "",
    activity: cms[`focus_${activeWeek}_activity`] || "",
    note:     cms[`focus_${activeWeek}_note`]     || "",
  };

  const weekData = scoresByWeek[activeWeek] || {};

  const rankedAll = teams.map(t => ({
    team: t,
    weekPts: rvlTeamWeekTotalLive(t, weekData) + rvlTeamWeekBonusTotal(t, activeWeek),
  })).filter(r => r.weekPts > 0).sort((a, b) => b.weekPts - a.weekPts);

  // Assign dense ranks
  let lastPts = null, lastRank = 0;
  const ranked = rankedAll.map(r => {
    if (r.weekPts !== lastPts) { lastRank++; lastPts = r.weekPts; }
    return { ...r, rank: lastRank };
  });

  // Show all teams within top 3 ranks
  const top3Ranked = ranked.filter(r => r.rank <= 3);

  const allMembers = [];
  for (const t of teams) {
    for (const m of t.members) {
      const pts = rvlComputeWeekPoints(weekData[m.id]);
      allMembers.push({ team: t, member: m, pts });
    }
  }
  allMembers.sort((a, b) => b.pts - a.pts);
  const topMember = allMembers[0]?.pts > 0 ? allMembers[0] : null;

  const visitorsRanked = [];
  for (const t of teams) {
    for (const m of t.members) {
      const s = weekData[m.id] || {};
      const v = (s.visitors || []).length;
      if (v > 0) visitorsRanked.push({ team: t, member: m, v });
    }
  }
  visitorsRanked.sort((a, b) => b.v - a.v);
  const visitorHero = visitorsRanked[0];

  // Inductors (members who brought inducted visitors) and inductees (new member names)
  const inductors = [];
  const inductees = [];
  for (const t of teams) {
    for (const m of t.members) {
      const s = weekData[m.id] || {};
      const inducted = (s.visitors || []).filter(v => v.category === "induction");
      if (inducted.length > 0) {
        inductors.push({ member: m, team: t, count: inducted.length });
        inducted.forEach(v => { if (v.name) inductees.push(v.name); });
      }
    }
  }

  const [copied, setCopied] = useState(false);
  const cardRef = useRef(null);

  if (!rvlIsWeekUnlocked(activeWeek)) return <WeekLocked weekId={activeWeek} title={`Recap for ${(RVL_WEEKS.find(w => w.id === activeWeek) || {}).label || "this week"} is locked`}/>;
  if (loading) return <PageLoader label="Building recap…"/>;

  return (
    <div className="rise">
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 18, flexWrap: "wrap", gap: 12 }}>
        <div>
          <div className="kicker">Share</div>
          <h1 style={{ fontSize: 32 }}>Weekly Recap Card</h1>
          <p style={{ color: "var(--ink-mute)", fontSize: 14, maxWidth: 560 }}>
            Auto-generated shareable card for the captains&apos; WhatsApp group. Right-click → Save image, or click Copy.
          </p>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <button className="btn btn-ghost btn-sm" onClick={async () => {
            if (!cardRef.current) return;
            try {
              const node = cardRef.current;
              const rect = node.getBoundingClientRect();
              const w = Math.ceil(rect.width);
              const h = Math.ceil(rect.height);
              const dataUrl = await window.htmlToImage.toPng(node, {
                pixelRatio: 2,
                backgroundColor: "#0f0a0b",
                cacheBust: true,
                skipFonts: true,
                width: w,
                height: h,
                canvasWidth: w * 2,
                canvasHeight: h * 2,
                style: { transform: "none", margin: "0" },
              });
              const link = document.createElement("a");
              link.download = `recap-${activeWeek}.png`;
              link.href = dataUrl;
              link.click();
            } catch (e) {
              rvlToast?.error?.(e.message || "Image export failed");
            }
          }}>🖼 Download image</button>
          <button className="btn btn-primary btn-sm" onClick={() => window.print()}>⬇ Download PDF</button>
        </div>
      </div>

      {/* The shareable card itself */}
      <div ref={cardRef} className="recap-card-print" style={{
        maxWidth: 720, margin: "0 auto", padding: 32,
        borderRadius: 22, position: "relative", overflow: "hidden",
        background: "linear-gradient(160deg, #4a0d12 0%, #1a0608 60%, #0f0a0b 100%)",
        border: "2px solid var(--gold)",
        color: "#fff",
        boxShadow: "0 30px 80px -20px rgba(0,0,0,.7), inset 0 0 0 1px rgba(212,168,71,.2)",
      }}>
        <div style={{
          position: "absolute", inset: 0,
          backgroundImage: "repeating-linear-gradient(115deg, rgba(255,255,255,.025) 0 18px, transparent 18px 80px)",
          pointerEvents: "none",
        }}/>
        <div style={{
          position: "absolute", top: -160, right: -100, width: 380, height: 380,
          borderRadius: "50%",
          background: "radial-gradient(circle, rgba(212,168,71,.30), transparent 65%)",
          filter: "blur(10px)",
        }}/>

        {/* Header */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 24, position: "relative", zIndex: 1 }}>
          <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
            <div style={{
              width: 60, height: 60, borderRadius: 12,
              background: "#fff",
              display: "grid", placeItems: "center",
              boxShadow: "0 0 0 2px rgba(255,255,255,.15)",
              overflow: "hidden",
            }}>
              <img src="/bni-logo.jpeg" alt="BNI" style={{ width: "100%", height: "100%", objectFit: "contain"}}/>
            </div>
            <div>
              <div style={{ fontSize: 14, color: "rgba(255,255,255,.78)", letterSpacing: "0.18em", textTransform: "uppercase", fontWeight: 700 }}>Rachhit Visitor League</div>
              <div className="display" style={{ fontSize: 26, marginTop: 2 }}>{week.label} RECAP</div>
            </div>
          </div>
          <div style={{ textAlign: "right" }}>
            <div style={{ fontSize: 11, color: "rgba(255,255,255,.6)" }}>Week of</div>
            <div className="display" style={{ fontSize: 20, color: "var(--gold-light)" }}>{week.range}</div>
          </div>
        </div>

        {/* Top 3 teams */}
        <div style={{ marginBottom: 20, position: "relative", zIndex: 1 }}>
          <div className="kicker" style={{ color: "var(--gold-light)", marginBottom: 10 }}>★ Team Standings · this week</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {ranked.length === 0 && (
              <div style={{ padding: "28px 14px", background: "rgba(0,0,0,.25)", border: "1px dashed rgba(212,168,71,.3)", borderRadius: 12, textAlign: "center", display: "flex", flexDirection: "column", alignItems: "center", gap: 8 }}>
                <div style={{ fontSize: 28, opacity: 0.4 }}>🏆</div>
                <div style={{ fontSize: 14, fontWeight: 700, color: "rgba(255,255,255,.75)" }}>No scores yet this week</div>
                <div style={{ fontSize: 11, color: "rgba(255,255,255,.4)" }}>Standings will appear once entries are submitted</div>
              </div>
            )}
            {top3Ranked.map((r) => (
              <div key={r.team.id} style={{
                display: "grid", gridTemplateColumns: "44px 56px 1fr 110px",
                gap: 14, alignItems: "center",
                background: "rgba(0,0,0,.32)",
                border: r.rank === 1 ? "1px solid var(--gold)" : "1px solid rgba(255,255,255,.08)",
                borderRadius: 12, padding: "10px 14px",
              }}>
                <RankBadge rank={r.rank} size={36}/>
                <TeamCrest team={r.team} size={48}/>
                <div>
                  <div className="display" style={{ fontSize: 22, lineHeight: 1 }}>{r.team.name}</div>
                  <div style={{ fontSize: 11, color: "rgba(255,255,255,.6)" }}>Captain · {r.team.captain?.name || "—"}</div>
                </div>
                <div style={{ textAlign: "right" }}>
                  <div className="display" style={{ fontSize: 34, color: r.rank === 1 ? "var(--gold-light)" : "#fff", lineHeight: 1 }}>{r.weekPts}</div>
                  <div style={{ fontSize: 10, color: "rgba(255,255,255,.6)", letterSpacing: "0.1em", textTransform: "uppercase" }}>points</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Stars */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 20, position: "relative", zIndex: 1 }}>
          {topMember && (
            <div style={{
              background: "rgba(0,0,0,.32)", border: "1px solid rgba(255,255,255,.08)",
              borderRadius: 12, padding: 14,
            }}>
              <div className="kicker" style={{ color: "var(--gold-light)", marginBottom: 6 }}>⭐ Star of the week</div>
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <Avatar name={topMember.member.name} size={44} color={topMember.team.crest.primary}/>
                <div>
                  <div style={{ fontWeight: 700, fontSize: 15, whiteSpace: "nowrap" }}>{topMember.member.name}</div>
                  <div style={{ fontSize: 11, color: "rgba(255,255,255,.6)", whiteSpace: "nowrap" }}>{topMember.team.name} · {topMember.pts} pts</div>
                </div>
              </div>
            </div>
          )}
          {visitorHero && (
            <div style={{
              background: "rgba(0,0,0,.32)", border: "1px solid rgba(255,255,255,.08)",
              borderRadius: 12, padding: 14,
            }}>
              <div className="kicker" style={{ color: "var(--gold-light)", marginBottom: 6 }}>🎯 Visitor magnet</div>
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <Avatar name={visitorHero.member.name} size={44} color={visitorHero.team.crest.primary}/>
                <div>
                  <div style={{ fontWeight: 700, fontSize: 15, whiteSpace: "nowrap" }}>{visitorHero.member.name}</div>
                  <div style={{ fontSize: 11, color: "rgba(255,255,255,.6)", whiteSpace: "nowrap" }}>{visitorHero.team.name} · {visitorHero.v} visitors</div>
                </div>
              </div>
            </div>
          )}
        </div>

        {/* Thank You + Welcome */}
        {(inductors.length > 0 || inductees.length > 0) && (
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 20, position: "relative", zIndex: 1 }}>
            {inductors.length > 0 && (
              <div style={{ background: "rgba(212,168,71,.12)", border: "1px solid rgba(212,168,71,.35)", borderRadius: 12, padding: 14 }}>
                <div className="kicker" style={{ color: "var(--gold-light)", marginBottom: 8 }}>🙏 Thank You</div>
                <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                  {inductors.map((ind, i) => (
                    <div key={i} style={{ display: "flex", alignItems: "center", gap: 10 }}>
                      <Avatar name={ind.member.name} size={36} color={ind.team.crest.primary}/>
                      <div style={{ minWidth: 0 }}>
                        <div style={{ fontWeight: 700, fontSize: 14, color: "#fff", whiteSpace: "nowrap" }}>{ind.member.name}</div>
                        <div style={{ fontSize: 11, color: "rgba(255,255,255,.6)", whiteSpace: "nowrap" }}>{ind.team.name} · inducted {ind.count}</div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}
            {inductees.length > 0 && (
              <div style={{ background: "rgba(31,138,74,.12)", border: "1px solid rgba(31,138,74,.35)", borderRadius: 12, padding: 14 }}>
                <div className="kicker" style={{ color: "#86efac", marginBottom: 8 }}>🎉 Welcome</div>
                <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                  {inductees.map((name, i) => (
                    <div key={i} style={{ display: "flex", alignItems: "center", gap: 8 }}>
                      <div style={{ width: 8, height: 8, borderRadius: "50%", background: "#4ade80", flexShrink: 0 }}/>
                      <div style={{ fontWeight: 700, fontSize: 14, color: "#fff", whiteSpace: "nowrap" }}>{name}</div>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>
        )}

        {/* Focus */}
        <div style={{
          background: "rgba(212,168,71,.10)", border: "1px solid rgba(212,168,71,.3)",
          borderRadius: 12, padding: "12px 14px", position: "relative", zIndex: 1,
          display: "flex", alignItems: "center", gap: 12,
        }}>
          <div style={{ fontSize: 28 }}>{focus.emoji}</div>
          <div style={{ minWidth: 0 }}>
            <div className="kicker" style={{ color: "var(--gold-light)" }}>Next focus · {focus.activity}</div>
            <div style={{ fontSize: 13, color: "rgba(255,255,255,.85)", whiteSpace: "nowrap" }}>{focus.note}</div>
          </div>
        </div>

        <div style={{ marginTop: 20, paddingTop: 14, borderTop: "1px solid rgba(255,255,255,.08)", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, position: "relative", zIndex: 1 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <div style={{ background: "#fff", borderRadius: 10, padding: 4, display: "flex", alignItems: "center", justifyContent: "center" }}>
              <img src="/applex-group.png" alt="Applex Group" style={{ height: 44, width: 44, objectFit: "contain", borderRadius: 6 }}/>
            </div>
            <div style={{ fontSize: 12, color: "rgba(255,255,255,.6)", lineHeight: 1.5 }}>
              Powered by <a href="https://applexgroup.com/" target="_blank" rel="noreferrer" style={{ color: "#d4a847", fontWeight: 800, textDecoration: "none" }}>Applex Group</a><br/>
              Member of BNI Racchit Pune East Region
            </div>
          </div>
          <div style={{ fontSize: 12, color: "rgba(255,255,255,.4)", textAlign: "right" }}>
            Rachhit Visitor League · BNI Pune East
          </div>
        </div>
      </div>
    </div>
  );
}

// =============================================================================
// HEAD-TO-HEAD — pick two teams, compare side-by-side
// =============================================================================

function HeadToHead({ activeWeek }) {
  const { teams, scoresByWeek, loading } = useLiveSeasonData();
  const [a, setA] = useState(null);
  const [b, setB] = useState(null);

  useEffect(() => {
    if (teams.length >= 2) {
      if (a === null) setA(teams[0].id);
      if (b === null) setB(teams[1].id);
    }
  }, [teams, a, b]);

  if (loading || teams.length === 0 || a === null || b === null) return <PageLoader label="Loading teams…"/>;

  const teamA = teams.find(t => t.id === a) || teams[0];
  const teamB = teams.find(t => t.id === b) || teams[1];

  function side(team) {
    const stats = { attendance: 0, visitors: 0, inductions: 0, one_to_ones: 0, referrals: 0, testimonials: 0, dance_card_on_time: 0, m2c: 0, training: 0, tyfcb: 0 };
    let total = 0;
    for (const w of RVL_WEEKS) {
      const wkData = scoresByWeek[w.id] || {};
      const wt = rvlTeamWeekTotalLive(team, wkData);
      total += wt;
      total += rvlTeamWeekBonusTotal(team, w.id);
      for (const m of team.members) {
        const s = wkData[m.id] || {};
        if (s.present) stats.attendance++;
        const vs = s.visitors || [];
        stats.visitors    += vs.filter(v => v.category !== "induction").length;
        stats.inductions  += vs.filter(v => v.category === "induction").length;
        stats.one_to_ones += Math.min((s.one_to_ones || []).length, 2);
        stats.referrals   += (s.referrals || []).length;
        stats.testimonials += s.testimonial || 0;
        if (s.dance_card === "dc_14") stats.dance_card_on_time++;
        stats.m2c      += s.m2c_photo || 0;
        stats.training += s.training || 0;
        stats.tyfcb    += s.tyfcb || 0;
      }
      if (w.id === activeWeek) break;
    }
    return { ...stats, total };
  }
  const A = side(teamA);
  const B = side(teamB);

  const rows = [
    { label: "Total points",         a: A.total,         b: B.total,         fmt: v => v.toLocaleString() },
    { label: "Attendance (member-weeks)", a: A.attendance, b: B.attendance, fmt: v => v },
    { label: "Visitors invited",     a: A.visitors,      b: B.visitors,      fmt: v => v },
    { label: "Inductions",           a: A.inductions,    b: B.inductions,    fmt: v => v },
    { label: "One-to-Ones",          a: A.one_to_ones,   b: B.one_to_ones,   fmt: v => v },
    { label: "Referrals",            a: A.referrals,     b: B.referrals,     fmt: v => v },
    { label: "Testimonials",         a: A.testimonials,  b: B.testimonials,  fmt: v => v },
    { label: "Dance Card on time",   a: A.dance_card_on_time, b: B.dance_card_on_time, fmt: v => v },
    { label: "M2C photos posted",    a: A.m2c,           b: B.m2c,           fmt: v => v },
    { label: "Trainings attended",   a: A.training,      b: B.training,      fmt: v => v },
    { label: "TYFCB",                a: A.tyfcb,         b: B.tyfcb,         fmt: v => `₹${(v/100000).toFixed(1)}L` },
  ];

  return (
    <div className="rise">
      <div style={{ marginBottom: 18 }}>
        <div className="kicker">Versus</div>
        <h1 style={{ fontSize: 32, marginBottom: 4 }}>Head to Head</h1>
        <p style={{ color: "var(--ink-mute)", fontSize: 14 }}>Pick any two teams. Compare season-cumulative through the current week.</p>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 80px 1fr", gap: 14, marginBottom: 18, alignItems: "stretch" }} className="h2h-grid">
        <TeamPicker team={teamA} all={teams} onChange={setA} side="a"/>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "center" }}>
          <div className="display" style={{
            fontSize: 38, color: "var(--gold-light)",
            width: 64, height: 64, borderRadius: "50%",
            background: "linear-gradient(135deg, var(--crimson), var(--crimson-deep))",
            display: "grid", placeItems: "center",
            border: "2px solid var(--gold)",
            boxShadow: "0 8px 20px rgba(178,30,46,.5)",
          }}>VS</div>
        </div>
        <TeamPicker team={teamB} all={teams} onChange={setB} side="b"/>
      </div>

      <div className="card" style={{ padding: 0, overflow: "hidden" }}>
        {rows.map((r, i) => {
          const aWins = r.a > r.b;
          const bWins = r.b > r.a;
          const max = Math.max(r.a, r.b, 1);
          return (
            <div key={r.label} style={{
              display: "grid", gridTemplateColumns: "1fr 220px 1fr",
              gap: 14, padding: "14px 22px",
              borderBottom: i < rows.length - 1 ? "1px solid var(--line)" : 0,
              alignItems: "center",
            }} className="h2h-row">
              <div style={{ textAlign: "right" }}>
                <div className="display" style={{ fontSize: 22, color: aWins ? "var(--gold-light)" : "var(--ink)" }}>{r.fmt(r.a)}</div>
                <div style={{ height: 6, background: "var(--bg-card-2)", borderRadius: 999, marginTop: 4, overflow: "hidden" }}>
                  <div style={{ height: "100%", width: `${(r.a / max) * 100}%`, marginLeft: `${100 - (r.a / max) * 100}%`, background: teamA.crest.primary }}/>
                </div>
              </div>
              <div style={{ fontSize: 11, fontWeight: 700, color: "var(--ink-mute)", letterSpacing: "0.14em", textTransform: "uppercase", textAlign: "center" }}>{r.label}</div>
              <div>
                <div className="display" style={{ fontSize: 22, color: bWins ? "var(--gold-light)" : "var(--ink)" }}>{r.fmt(r.b)}</div>
                <div style={{ height: 6, background: "var(--bg-card-2)", borderRadius: 999, marginTop: 4, overflow: "hidden" }}>
                  <div style={{ height: "100%", width: `${(r.b / max) * 100}%`, background: teamB.crest.primary }}/>
                </div>
              </div>
            </div>
          );
        })}
      </div>

      <style>{`
        @media (max-width: 700px) {
          .h2h-grid { grid-template-columns: 1fr !important; }
          .h2h-row { grid-template-columns: 1fr !important; }
          .h2h-row > :nth-child(2) { order: -1; }
        }
      `}</style>
    </div>
  );
}

function TeamPicker({ team, all, onChange, side }) {
  return (
    <div style={{
      background: `linear-gradient(135deg, ${team.crest.primary} 0%, color-mix(in oklab, ${team.crest.primary} 20%, #0a0606) 100%)`,
      borderRadius: 16, padding: 20,
      border: "1px solid var(--line-bright)",
      color: "#fff",
    }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 12 }}>
        <TeamCrest team={team} size={56} glow/>
        <div style={{ minWidth: 0, flex: 1 }}>
          <div className="display" style={{ fontSize: 22, lineHeight: 1 }}>{team.name}</div>
          <div style={{ fontSize: 12, color: "rgba(255,255,255,.7)" }}>Captain · {team.captain?.name || "—"}</div>
        </div>
      </div>
      <CustomSelect
        value={team.id}
        onChange={onChange}
        width="100%"
        options={all.map(t => ({
          value: t.id,
          label: t.name,
          icon: <TeamCrest team={t} size={20}/>,
        }))}
      />
    </div>
  );
}

// Print styles for the weekly recap: only the card prints, full-color, centered.
(function injectRecapPrintStyles() {
  if (document.getElementById("recap-card-print-styles")) return;
  const style = document.createElement("style");
  style.id = "recap-card-print-styles";
  style.textContent = `
    @media print {
      @page { size: A4; margin: 0; }
      html, body { background: #fff !important; margin: 0 !important; padding: 0 !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
      body * { visibility: hidden !important; }
      .recap-card-print, .recap-card-print * { visibility: visible !important; }
      .recap-card-print {
        position: absolute !important; left: 50% !important; top: 12mm !important;
        transform: translateX(-50%) !important;
        margin: 0 !important; box-shadow: none !important;
      }
    }
  `;
  document.head.appendChild(style);
})();

Object.assign(window, { History, WeeklyRecap, HeadToHead });
