/* ============================================================================
   Operation Outbreak — Wrapped  ·  SLIDE 1 · GROUP DASHBOARD
   Bento grid + self-drawing epidemiological curve.
   ============================================================================ */

/* Build a smooth (Catmull-Rom → cubic Bézier) curve path from a data array. */
function buildCurve(data, w, h, padX, padTop, padBottom) {
  const max = Math.max(...data, 1);
  const n = data.length;
  const X = (i) => padX + (i / (n - 1)) * (w - 2 * padX);
  const Y = (v) => h - padBottom - (v / max) * (h - padTop - padBottom);
  const pts = data.map((v, i) => [X(i), Y(v)]);
  let d = `M ${pts[0][0]} ${pts[0][1]}`;
  for (let i = 0; i < pts.length - 1; i++) {
    const p0 = pts[i - 1] || pts[i];
    const p1 = pts[i];
    const p2 = pts[i + 1];
    const p3 = pts[i + 2] || p2;
    const c1x = p1[0] + (p2[0] - p0[0]) / 6;
    const c1y = p1[1] + (p2[1] - p0[1]) / 6;
    const c2x = p2[0] - (p3[0] - p1[0]) / 6;
    const c2y = p2[1] - (p3[1] - p1[1]) / 6;
    d += ` C ${c1x} ${c1y}, ${c2x} ${c2y}, ${p2[0]} ${p2[1]}`;
  }
  const peakIdx = data.indexOf(max);
  return { line: d, area: d + ` L ${X(n - 1)} ${h - padBottom} L ${X(0)} ${h - padBottom} Z`, peak: pts[peakIdx], max, X, Y };
}

function EpiCurve({ play, fill }) {
  const D = window.OO_DATA.group;
  const W = 1120, H = 360, padX = 8, padTop = 46, padBottom = 30;
  const cases = D.curve, rec = D.recovered || [];
  const n = cases.length;
  const max = Math.max(...cases, ...rec, 1);
  const X = (i) => padX + (i / (n - 1)) * (W - 2 * padX);
  const Y = (v) => H - padBottom - (v / max) * (H - padTop - padBottom);
  const pathFor = (arr) => {
    if (!arr.length) return { line: "", area: "" };
    const pts = arr.map((v, i) => [X(i), Y(v)]);
    let d = `M ${pts[0][0]} ${pts[0][1]}`;
    for (let i = 0; i < pts.length - 1; i++) {
      const p0 = pts[i - 1] || pts[i], p1 = pts[i], p2 = pts[i + 1], p3 = pts[i + 2] || p2;
      const c1x = p1[0] + (p2[0] - p0[0]) / 6, c1y = p1[1] + (p2[1] - p0[1]) / 6;
      const c2x = p2[0] - (p3[0] - p1[0]) / 6, c2y = p2[1] - (p3[1] - p1[1]) / 6;
      d += ` C ${c1x} ${c1y}, ${c2x} ${c2y}, ${p2[0]} ${p2[1]}`;
    }
    return { line: d, area: d + ` L ${X(n - 1)} ${H - padBottom} L ${X(0)} ${H - padBottom} Z` };
  };
  const ci = pathFor(cases), cr = pathFor(rec);
  const peakIdx = cases.indexOf(Math.max(...cases));
  const peakLeft = X(peakIdx) / W * 100, peakTop = Y(cases[peakIdx]) / H * 100;
  const labelLeft = Math.min(Math.max(peakLeft, 18), 82);
  const svgStyle = fill ? { display: "block", width: "100%", height: "100%" } : { display: "block", width: "100%", height: "auto" };

  return (
    <div style={{ position: "relative", width: "100%", height: fill ? "100%" : "auto" }}>
      <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio={fill ? "none" : "xMidYMid meet"} style={svgStyle}>
        <defs>
          <linearGradient id="epiLineR" x1="0" y1="0" x2="1" y2="0"><stop offset="0%" stopColor="#FF7171" /><stop offset="100%" stopColor="#DB3A3A" /></linearGradient>
          <linearGradient id="epiLineB" x1="0" y1="0" x2="1" y2="0"><stop offset="0%" stopColor="#7387F9" /><stop offset="100%" stopColor="#5465E5" /></linearGradient>
          <linearGradient id="epiAreaR" x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stopColor="rgba(255,113,113,0.30)" /><stop offset="100%" stopColor="rgba(219,58,58,0)" /></linearGradient>
          <linearGradient id="epiAreaB" x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stopColor="rgba(84,101,229,0.24)" /><stop offset="100%" stopColor="rgba(84,101,229,0)" /></linearGradient>
        </defs>
        {/* gridlines + baseline */}
        {[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" vectorEffect="non-scaling-stroke" />
        ))}
        <line x1={padX} x2={W - padX} y1={H - padBottom} y2={H - padBottom} stroke="rgba(255,255,255,0.12)" strokeWidth="1" vectorEffect="non-scaling-stroke" />
        {/* reveal both curves left-to-right */}
        <clipPath id="epiReveal"><rect x="0" y="0" width="0" height={H}>
          <animate attributeName="width" from="0" to={W} dur="1.9s" begin="0.35s" fill="freeze" calcMode="spline" keyTimes="0;1" keySplines="0.4 0.1 0.2 1" />
        </rect></clipPath>
        <g clipPath="url(#epiReveal)">
          <path d={ci.area} fill="url(#epiAreaR)" />
          <path d={cr.area} fill="url(#epiAreaB)" />
          <path d={cr.line} fill="none" stroke="url(#epiLineB)" strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round" vectorEffect="non-scaling-stroke" style={{ filter: "drop-shadow(0 0 8px rgba(84,101,229,0.45))" }} />
          <path d={ci.line} fill="none" stroke="url(#epiLineR)" strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round" vectorEffect="non-scaling-stroke" style={{ filter: "drop-shadow(0 0 10px rgba(237,80,80,0.45))" }} />
        </g>
      </svg>
      {/* peak marker — crisp HTML overlay (undistorted), larger label */}
      <div style={{ position: "absolute", left: `${peakLeft}%`, top: `${peakTop}%`, transform: "translate(-50%,-50%)", width: 11, height: 11, borderRadius: 999, background: "#FF7171", boxShadow: "0 0 12px rgba(255,113,113,0.95)", opacity: play ? 1 : 0, transition: "opacity 400ms ease 1.9s" }} />
      <div style={{ position: "absolute", left: `${labelLeft}%`, top: `${peakTop}%`, transform: "translate(-50%, calc(-100% - 10px))", whiteSpace: "nowrap", fontFamily: T.mono, fontSize: fill ? 10 : 13, fontWeight: 700, letterSpacing: "0.06em", color: "#FF7171", background: "rgba(8,9,10,0.82)", padding: "3px 8px", borderRadius: 4, border: "1px solid rgba(255,113,113,0.25)", opacity: play ? 1 : 0, transition: "opacity 400ms ease 1.9s" }}>
        PEAK · {D.peakConcurrent} · {D.peakMinute}′
      </div>
    </div>
  );
}

/* terminal-style timestamp tile */
function TerminalTile({ label, time, accent, play, delay }) {
  return (
    <GlowTile accent={accent} pad={20}>
      <Eyebrow color={T.fg3} style={{ fontSize: 10.5 }}>{label}</Eyebrow>
      <div style={{ marginTop: 14, display: "flex", alignItems: "center", gap: 9 }}>
        <span style={{ width: 7, height: 7, borderRadius: 999, background: accent, boxShadow: `0 0 8px ${accentAlpha(accent, 0.9)}` }} />
        <span style={{ fontFamily: T.mono, fontSize: 30, fontWeight: 600, color: T.fg, letterSpacing: "-0.01em", opacity: play ? 1 : 0, transition: `opacity 500ms ease ${delay}ms` }}>{time}</span>
      </div>
      <div style={{ marginTop: 10, fontFamily: T.mono, fontSize: 10.5, color: T.fg3, letterSpacing: "0.06em" }}>HH : MM : SS · FROM T0</div>
    </GlowTile>
  );
}

/* big counter tile */
function CounterTile({ label, to, accent, play, suffix = "", decimals = 0, sub, span = 1, big = 56, delay = 0, icon }) {
  return (
    <GlowTile accent={accent} span={span} pad={22}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
        <Eyebrow color={T.fg3} style={{ fontSize: 10.5 }}>{label}</Eyebrow>
        {icon && <Icon name={icon} size={17} color={accent} stroke={1.75} />}
      </div>
      <div style={{ marginTop: 12, fontFamily: T.mono, fontWeight: 700, fontSize: big, lineHeight: 1, color: T.fg, letterSpacing: "-0.02em" }}>
        <CountUp to={to} play={play} suffix={suffix} decimals={decimals} duration={1500} delay={delay} />
      </div>
      {sub && <div style={{ marginTop: 12 }}>{sub}</div>}
    </GlowTile>
  );
}

/* mini progress bar for index tiles */
function IndexBar({ value, accent, play }) {
  return (
    <div style={{ marginTop: 14, height: 6, borderRadius: 999, background: "rgba(255,255,255,0.07)", overflow: "hidden" }}>
      <div style={{ height: "100%", width: play ? `${value}%` : "0%", background: accent, borderRadius: 999, boxShadow: `0 0 10px ${accentAlpha(accent, 0.6)}` }} />
    </div>
  );
}

function SlideGroup({ active, onShare }) {
  const D = window.OO_DATA.group;
  const M = window.OO_DATA.meta;
  const play = useReveal(active);

  return (
    <div className="oo-slide-inner">
      {/* header */}
      <div className="oo-s1-head">
        <div>
          <Eyebrow color={T.mint}>SIMULATION SUMMARY // {M.runId}</Eyebrow>
          <h1 className="oo-title" style={{ marginTop: 14 }}>Our outbreak timeline</h1>
          <div style={{ marginTop: 12, display: "flex", gap: 20, flexWrap: "wrap" }}>
            <StatusDot color={T.mint} label={M.cohort.toUpperCase()} />
            <StatusDot color={T.blue2} label={M.simDate || M.date} />
            <StatusDot color={T.coral2} label={M.simStartTime || ''} />
            <StatusDot color={T.fg3} label={M.simEndTime || ''} />
          </div>
        </div>
      </div>

      {/* bento grid */}
      <div className="oo-bento">
        {/* hero curve — full width */}
        <GlowTile accent={T.coral2} span={12} glow={false} pad={24} style={{ background: "linear-gradient(180deg,#12151B 0%,#0E1116 100%)" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", flexWrap: "wrap", gap: 12 }}>
            <Eyebrow color={T.coral2}>EPIDEMIOLOGICAL CURVE · NEW CASES OVER TIME</Eyebrow>
            <div style={{ display: "flex", gap: 22 }}>
              <span style={{ fontFamily: T.mono, fontSize: 11, color: T.fg3, letterSpacing: "0.06em" }}>R₀ OBSERVED&nbsp;&nbsp;<b style={{ color: T.coral2, fontWeight: 700 }}>{D.r0}</b></span>
              <span style={{ fontFamily: T.mono, fontSize: 11, color: T.fg3, letterSpacing: "0.06em" }}>PEAK MIN&nbsp;&nbsp;<b style={{ color: T.fg, fontWeight: 700 }}>{D.peakMinute}′</b></span>
            </div>
          </div>
          <div style={{ marginTop: 10 }}><EpiCurve play={play} /></div>
        </GlowTile>

        {/* infections / deceased */}
        <CounterTile span={4} label="TOTAL INFECTIONS" to={D.totalInfections} accent={T.coral2} play={play} icon="activity" big={58}
          sub={<StatusDot color={T.coral} label={`${Math.round(D.totalInfections / D.participants * 100)}% OF COHORT`} />} />
        <CounterTile span={2} label="DECEASED" to={D.deceased} accent={T.coral} play={play} icon="heart-pulse" big={58} delay={200} />
        <CounterTile span={3} label="PARTICIPANTS" to={D.participants} accent={T.blue2} play={play} icon="users" big={58}
          sub={<StatusDot color={T.blue2} label={`${D.vaccinated} VACCINATED`} />} />
        <CounterTile span={3} label="INTERVENTIONS LOGGED" to={D.interventions} accent={T.purple} play={play} icon="syringe" big={58} delay={120}
          sub={<StatusDot color={T.purple} label="MASKS · VAX · TESTS · RX" />} />

        {/* terminal timestamps */}
        <div style={{ gridColumn: "span 6", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
          <TerminalTile label="TIME OF FIRST INFECTION" time={D.firstInfection} accent={T.coral2} play={play} delay={300} />
          <TerminalTile label="TIME OF FIRST TRANSMISSION" time={D.firstTransmission} accent={T.purple} play={play} delay={450} />
        </div>

        {/* community indices */}
        <GlowTile accent={T.mint} span={3} pad={22}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
            <Eyebrow color={T.fg3} style={{ fontSize: 10.5 }}>SPONGE INDEX · AVG</Eyebrow>
            <Star size={14} color={T.mint} />
          </div>
          <div style={{ marginTop: 12, fontFamily: T.mono, fontWeight: 700, fontSize: 56, lineHeight: 1, color: T.fg, letterSpacing: "-0.02em" }}>
            <CountUp to={D.spongeIndexAvg} play={play} duration={1500} /><span style={{ fontSize: 22, color: T.fg3 }}>/100</span>
          </div>
          <IndexBar value={D.spongeIndexAvg} accent={T.mint} play={play} />
        </GlowTile>
        <GlowTile accent={T.blue2} span={3} pad={22}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
            <Eyebrow color={T.fg3} style={{ fontSize: 10.5 }}>UNIQUE PINGS · AVG</Eyebrow>
            <Icon name="radio" size={16} color={T.blue2} stroke={1.75} />
          </div>
          <div style={{ marginTop: 12, fontFamily: T.mono, fontWeight: 700, fontSize: 56, lineHeight: 1, color: T.fg, letterSpacing: "-0.02em" }}>
            <CountUp to={D.uniquePingsAvg} play={play} duration={1500} delay={150} />
          </div>
          <div style={{ marginTop: 14, fontFamily: T.mono, fontSize: 11, color: T.fg3, letterSpacing: "0.05em" }}>CLOSE CONTACTS / PLAYER</div>
        </GlowTile>
      </div>
    </div>
  );
}
window.SlideGroup = SlideGroup;
