/* ============================================================================
   Operation Outbreak — Wrapped · PDF PAGES (static, print-ready)
   Three letter-portrait pages (816×1056). No animation — every value is in its
   final state so the printed PDF is deterministic. Driven by a single player
   record + the shared group stats.
   ============================================================================ */

/* ordinal suffix: 1→1st, 2→2nd, 3→3rd, 11→11th, 22→22nd, 41→41st, 97→97th */
function ordinal(n) {
  const s = ["th", "st", "nd", "rd"], v = n % 100;
  return n + (s[(v - 20) % 10] || s[v] || s[0]);
}

/* ── static epidemiological curve (fully drawn, no SMIL) ─────────────────── */function PdfCurve({ height = 250 }) {
  const D = window.OO_DATA.group, W = 1120, H = height, padX = 8, padTop = 34, padBottom = 26;
  const c = buildCurve(D.curve, W, H, padX, padTop, padBottom);
  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ display: "block", overflow: "visible" }}>
      <defs>
        <linearGradient id="pdfLine" x1="0" y1="0" x2="1" y2="0"><stop offset="0%" stopColor="#FF7171" /><stop offset="100%" stopColor="#DB3A3A" /></linearGradient>
        <linearGradient id="pdfArea" x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stopColor="rgba(255,113,113,0.34)" /><stop offset="100%" stopColor="rgba(219,58,58,0)" /></linearGradient>
      </defs>
      {[0.25, 0.5, 0.75].map((g) => <line key={g} x1={padX} x2={W - padX} y1={padTop + g * (H - padTop - padBottom)} y2={padTop + g * (H - padTop - padBottom)} stroke="rgba(255,255,255,0.05)" strokeWidth="1" />)}
      <line x1={padX} x2={W - padX} y1={H - padBottom} y2={H - padBottom} stroke="rgba(255,255,255,0.12)" strokeWidth="1" />
      <path d={c.area} fill="url(#pdfArea)" />
      <path d={c.line} fill="none" stroke="url(#pdfLine)" strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round" />
      <circle cx={c.peak[0]} cy={c.peak[1]} r="5" fill="#FF7171" stroke="#08090A" strokeWidth="2" />
      <text x={c.peak[0]} y={c.peak[1] - 18} textAnchor="middle" fill="#FF7171" style={{ fontFamily: T.mono, fontSize: 13, fontWeight: 700, letterSpacing: "0.06em" }}>PEAK · {D.peakConcurrent} ACTIVE</text>
    </svg>
  );
}

/* ── static radial gauge (final state) ───────────────────────────────────── */
function PdfGauge({ centerValue, ringPct, label, sub, from, to, gradId, size = 230, stroke = 17 }) {
  const r = (size - stroke) / 2, circ = 2 * Math.PI * r;
  return (
    <div style={{ position: "relative", width: size, height: size }}>
      <svg width={size} height={size} style={{ transform: "rotate(-90deg)", overflow: "visible" }}>
        <defs><linearGradient id={gradId} x1="0" y1="0" x2="1" y2="1"><stop offset="0%" stopColor={from} /><stop offset="100%" stopColor={to} /></linearGradient></defs>
        <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="rgba(255,255,255,0.08)" strokeWidth={stroke} />
        <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke={`url(#${gradId})`} strokeWidth={stroke} strokeLinecap="round"
          strokeDasharray={circ} strokeDashoffset={circ * (1 - ringPct / 100)} style={{ filter: `drop-shadow(0 0 8px ${from}55)` }} />
      </svg>
      <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center" }}>
        <div style={{ fontFamily: T.mono, fontWeight: 700, fontSize: size * 0.30, lineHeight: 1, color: T.fg, letterSpacing: "-0.02em" }}>{centerValue}</div>
        {label && <div style={{ fontFamily: T.mono, fontSize: 11, fontWeight: 700, letterSpacing: "0.12em", color: T.mint, marginTop: 5 }}>{label}</div>}
      </div>
    </div>
  );
}

/* ── shared page chrome ──────────────────────────────────────────────────── */
function PageHead({ eyebrow, eyebrowColor, title, right }) {
  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <img src={(window.__resources && window.__resources.appIcon) || "assets/app-icon.png"} alt="" style={{ width: 30, height: 30, borderRadius: 7 }} />
          <span style={{ fontFamily: T.mono, fontSize: 12, fontWeight: 700, letterSpacing: "0.12em", color: T.fg }}>OPERATION OUTBREAK</span>
        </div>
        {right}
      </div>
      <div style={{ fontFamily: T.mono, fontSize: 11, fontWeight: 700, letterSpacing: "0.16em", color: eyebrowColor, marginTop: 26 }}>{eyebrow}</div>
      <h1 style={{ fontFamily: T.sans, fontWeight: 300, fontSize: 52, letterSpacing: "-0.03em", color: T.fg, margin: "8px 0 0", lineHeight: 1 }}>{title}</h1>
    </div>
  );
}

function PageFoot({ n }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", fontFamily: T.mono, fontSize: 10.5, letterSpacing: "0.08em", color: T.fg3 }}>
      <span>OPERATIONOUTBREAK.ORG</span>
      <span style={{ display: "flex", alignItems: "center", gap: 8 }}><Star size={11} color={accentAlpha(T.mint, 0.7)} /> WRAPPED · {window.OO_DATA.meta.runId}</span>
      <span>{n} / 03</span>
    </div>
  );
}

/* full-width metric row */
function PdfRow({ label, value, sub, accent }) {
  return (
    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", background: T.panel, border: `1px solid ${T.line}`, borderRadius: 14, padding: "16px 22px" }}>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontFamily: T.mono, fontSize: 11, fontWeight: 700, letterSpacing: "0.1em", color: T.fg3, whiteSpace: "nowrap" }}>{label}</div>
        {sub && <div style={{ fontFamily: T.mono, fontSize: 10.5, letterSpacing: "0.05em", color: accent, marginTop: 7 }}>{sub}</div>}
      </div>
      <div style={{ fontFamily: T.mono, fontWeight: 700, fontSize: 42, lineHeight: 1, color: T.fg, letterSpacing: "-0.02em" }}>{value}</div>
    </div>
  );
}

/* ── PAGE 1 · GROUP ──────────────────────────────────────────────────────── */
function PdfPageGroup() {
  const D = window.OO_DATA.group, M = window.OO_DATA.meta;
  return (
    <div className="pdf-page" data-screen-label="01" style={{ background: "radial-gradient(80% 40% at 12% 4%, rgba(134,106,255,0.16), rgba(8,9,10,0) 55%), radial-gradient(80% 45% at 95% 98%, rgba(42,173,154,0.12), rgba(8,9,10,0) 55%), #08090A" }}>
      <PageHead
        eyebrow={`SIMULATION SUMMARY // ${M.runId}`} eyebrowColor={T.mint} title="Our outbreak timeline"
        right={<div style={{ textAlign: "right", fontFamily: T.mono, fontSize: 10.5, lineHeight: 1.9, color: T.fg2, letterSpacing: "0.04em" }}>{M.cohort.toUpperCase()}<br />RUNTIME {M.duration.toUpperCase()}<br />{M.date}</div>}
      />
      <div style={{ border: `1px solid ${T.line}`, borderRadius: 18, background: "linear-gradient(180deg,#12151B,#0E1116)", padding: "16px 18px 6px", marginTop: 24 }}>
        <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 2 }}>
          <span style={{ fontFamily: T.mono, fontSize: 11, fontWeight: 700, letterSpacing: "0.12em", color: T.coral2 }}>EPIDEMIOLOGICAL CURVE · NEW CASES OVER TIME</span>
          <span style={{ fontFamily: T.mono, fontSize: 11, color: T.fg3, letterSpacing: "0.06em" }}>OBSERVED R₀ <b style={{ color: T.coral2 }}>{D.r0}</b> &nbsp;·&nbsp; PEAK <b style={{ color: T.fg }}>{D.peakConcurrent}</b> @ {D.peakMinute}′</span>
        </div>
        <PdfCurve />
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 12, marginTop: 22 }}>
        <PdfRow label="TOTAL INFECTIONS" value={fmt(D.totalInfections)} accent={T.coral2} sub={`${Math.round(D.totalInfections / D.participants * 100)}% OF ${D.participants} PLAYERS`} />
        <PdfRow label="TOTAL DECEASED" value={fmt(D.deceased)} accent={T.coral} sub="FATAL OUTCOMES LOGGED" />
        <PdfRow label="TOTAL INTERACTIONS" value={fmt(D.totalUniquePings)} accent={T.blue2} sub="CLOSE-CONTACT PINGS" />
        <PdfRow label="FIRST TRANSMISSION" value={D.timeFirstTransmission} accent={T.purple} sub="HH:MM:SS · FROM T0" />
      </div>
      <PageFoot n="01" />
    </div>
  );
}

/* ── PAGE 2 · INDIVIDUAL ─────────────────────────────────────────────────── */
function PdfPageIndividual({ player }) {
  const D = player;
  const chaos = D.downstreamInfections > 0;
  return (
    <div className="pdf-page" data-screen-label="02" style={{ background: "radial-gradient(85% 45% at 6% 2%, rgba(134,106,255,0.18), rgba(8,9,10,0) 55%), radial-gradient(70% 40% at 100% 8%, rgba(88,219,166,0.10), rgba(8,9,10,0) 50%), #08090A" }}>
      <PageHead
        eyebrow={`OUTBREAK REPORT CARD // ${D.role}`} eyebrowColor={T.purple} title="Your close calls"
        right={<div style={{ textAlign: "right", fontFamily: T.mono, fontSize: 16, fontWeight: 600, color: T.purple, letterSpacing: "0.02em" }}>{D.handle}</div>}
      />
      {/* hero gauge */}
      <div style={{ display: "flex", flexDirection: "column", alignItems: "center", marginTop: 26 }}>
        <PdfGauge centerValue={fmt(D.nearMisses)} ringPct={D.netEvasionEfficiency} label="CLOSE CALLS" from="#2A3D9A" to="#58DBA6" gradId="pdfNm" />
        <div style={{ fontFamily: T.mono, fontSize: 11, letterSpacing: "0.06em", color: T.fg3, marginTop: 10 }}>High-risk exposures survived</div>
      </div>
      {/* exposure log */}
      <div style={{ border: `1px solid ${T.line}`, borderLeft: `2px solid ${T.mint}`, borderRadius: 12, background: T.panel, padding: "16px 20px", marginTop: 24, fontFamily: T.mono, fontSize: 13, lineHeight: 1.7, color: T.fg2 }}>
        <div style={{ color: T.mint, fontWeight: 700, letterSpacing: "0.12em", marginBottom: 8 }}>EXPOSURE LOG //</div>
        <div>· Out of <b style={{ color: T.fg }}>{D.infectedEncounters}</b> encounters with infected vectors, <b style={{ color: T.fg }}>{D.successfulEvasions}</b> resulted in transmission evasion.</div>
        <div style={{ marginTop: 5 }}>· <b style={{ color: T.fg }}>{D.proximityWhileCarrier}</b> proximity events occurred while you were already an active carrier.</div>
        <div style={{ marginTop: 5 }}>· Net Evasion Efficiency: <b style={{ color: T.mint }}>{D.netEvasionEfficiency}%</b></div>
      </div>
      {/* lower 3-up */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12, marginTop: 22 }}>
        {[
          { label: "UNIQUE PINGS", value: fmt(D.uniquePings), accent: T.blue2, foot: "CLOSE CONTACTS" },
          { label: "COMPLIANCE", value: ordinal(D.compliancePercentile), accent: T.mint, foot: `TOP ${100 - D.compliancePercentile}% OF COHORT` },
          { label: "DOWNSTREAM INFECTIONS", value: fmt(D.downstreamInfections), accent: chaos ? T.coral2 : T.mint, foot: chaos ? "TRANSMISSION CHAINS" : "ZERO CHAINS" },
        ].map((m) => (
          <div key={m.label} style={{ background: T.panel, border: `1px solid ${T.line}`, borderRadius: 14, padding: "16px 16px 14px" }}>
            <div style={{ fontFamily: T.mono, fontSize: 9.5, fontWeight: 700, letterSpacing: "0.08em", color: T.fg3, minHeight: 24, lineHeight: 1.3 }}>{m.label}</div>
            <div style={{ fontFamily: T.mono, fontWeight: 700, fontSize: 34, lineHeight: 1, color: T.fg, marginTop: 10 }}>{m.value}</div>
            <div style={{ fontFamily: T.mono, fontSize: 9, letterSpacing: "0.05em", color: m.accent, marginTop: 8 }}>{m.foot}</div>
          </div>
        ))}
      </div>
      <PageFoot n="02" />
    </div>
  );
}

/* ── PAGE 3 · PERSONALITY (the actual card, revealed) ────────────────────── */
function PdfPagePersonality({ player }) {
  const bucket = window.OO_DATA.resolveBucket(player);
  const p = window.OO_DATA.personalities[bucket];
  const accent = p.mode === "gradient" ? T.coral2 : p.color;
  return (
    <div className="pdf-page" data-screen-label="03" style={{ background: `radial-gradient(70% 38% at 50% 0%, ${accentAlpha(accent, 0.16)}, rgba(8,9,10,0) 55%), #08090A` }}>
      <div style={{ textAlign: "center" }}>
        <div style={{ display: "inline-flex", alignItems: "center", gap: 10 }}>
          <img src={(window.__resources && window.__resources.appIcon) || "assets/app-icon.png"} alt="" style={{ width: 26, height: 26, borderRadius: 6 }} />
          <span style={{ fontFamily: T.mono, fontSize: 11, fontWeight: 700, letterSpacing: "0.16em", color: accent }}>YOUR OO PERSONALITY</span>
        </div>
      </div>
      <div style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center" }}>
        <div style={{ transform: "scale(1.34)" }}>
          <CharacterCard p={p} handle={player.handle} descOverride={p.altDesc && player.downstreamInfections === 0 ? p.altDesc : undefined} />
        </div>
      </div>
      <PageFoot n="03" />
    </div>
  );
}

window.PdfPageGroup = PdfPageGroup;
window.PdfPageIndividual = PdfPageIndividual;
window.PdfPagePersonality = PdfPagePersonality;
