// Tournament Bracket — single elim playoff visualizer with aligned headers + connectors

const BracketPage = ({ persona }) => {
  const D = window.NASEF_DATA;
  const b = D.bracket;
  const cellW = 220;
  const cellH = 84;
  const gapX = 72;

  return (
    <div>
      <PageHeader
        eyebrow={b.format}
        title={b.title}
        subtitle="Quarterfinals complete · Semifinals in progress · Final May 22, 2026"
        actions={persona === "admin" ? [
          <button key="seed" className="btn"><IconEdit size={12} />Edit seeding</button>,
          <button key="reset" className="btn ghost">Reset bracket</button>,
        ] : null}
      />

      <div className="card" style={{ padding: 0, overflow: "auto" }}>
        <div style={{ padding: 32, minWidth: "fit-content" }}>
          {/* Round headers — all flush at top */}
          <div style={{ display: "flex", gap: gapX, marginBottom: 18 }}>
            {b.rounds.map((round, ri) => {
              const hasLive = round.matches.some(m => m.status === "live");
              return (
                <div key={ri} style={{ width: cellW, textAlign: "center", position: "relative" }}>
                  <div className="row-tight" style={{ justifyContent: "center", gap: 8 }}>
                    <div className="upper" style={{ color: hasLive ? "var(--danger)" : "var(--text-secondary)", fontSize: 12, letterSpacing: "0.14em", fontWeight: 700 }}>{round.name}</div>
                    {hasLive && (
                      <span className="badge live" style={{ fontSize: 9, padding: "2px 6px" }}>
                        <span className="dot" style={{ width: 5, height: 5 }} />LIVE
                      </span>
                    )}
                  </div>
                </div>
              );
            })}
            <div style={{ width: cellW, textAlign: "center", paddingLeft: 30 }}>
              <div className="upper" style={{ color: "var(--nasef-orange-soft)", fontSize: 12, letterSpacing: "0.14em", fontWeight: 700 }}>Champion</div>
            </div>
          </div>

          {/* Bracket body */}
          <div style={{ display: "flex", gap: gapX, position: "relative" }}>
            {b.rounds.map((round, ri) => {
              const offsetMul = Math.pow(2, ri);
              const innerGap = 16 * offsetMul + (offsetMul - 1) * cellH;
              const topPad = ri > 0 ? (offsetMul - 1) * (cellH / 2 + 8) : 0;
              return (
                <div key={ri} style={{ display: "flex", flexDirection: "column", gap: innerGap, paddingTop: topPad, width: cellW, position: "relative" }}>
                  {round.matches.map((m, mi) => (
                    <BracketCell
                      key={m.id}
                      m={m}
                      schools={D.schoolsById}
                      width={cellW}
                      height={cellH}
                      showRight={ri < b.rounds.length}
                      showLeft={ri > 0}
                      pairIndex={mi}
                    />
                  ))}
                </div>
              );
            })}

            {/* Champion column — aligned at top so it sits on the same horizontal line as the Final cell */}
            <div style={{ display: "flex", flexDirection: "column", justifyContent: "flex-start", paddingTop: (() => {
              // Final round vertical centering math — final cell sits at half the column height
              const finalOffsetMul = Math.pow(2, b.rounds.length - 1);
              return (finalOffsetMul - 1) * (cellH / 2 + 8);
            })(), paddingLeft: 30, position: "relative" }}>
              <div style={{
                width: cellW, minHeight: cellH, padding: "18px 16px",
                borderRadius: "var(--r-md)",
                background: "linear-gradient(135deg, rgba(242,104,34,0.18) 0%, rgba(242,104,34,0.04) 100%)",
                border: "1px solid rgba(242,104,34,0.35)",
                textAlign: "center",
                boxShadow: "0 0 24px -8px rgba(242,104,34,0.4)",
                display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 6,
              }}>
                <IconTrophy size={28} style={{ color: "var(--nasef-orange)" }} />
                <div style={{ fontSize: 13, fontWeight: 600, color: "var(--text-secondary)" }}>To be decided</div>
                <div className="upper muted" style={{ fontSize: 10 }}>May 29, 2026</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div style={{ marginTop: 18, display: "flex", gap: 16, color: "var(--text-muted)", fontSize: 12 }}>
        <div className="row-tight"><span style={{ width: 10, height: 10, borderRadius: 2, background: "rgba(45,212,120,0.2)", border: "1px solid rgba(45,212,120,0.4)" }} />Complete</div>
        <div className="row-tight"><span style={{ width: 10, height: 10, borderRadius: 2, background: "rgba(255,59,92,0.15)", border: "1px solid rgba(255,59,92,0.4)" }} />Live</div>
        <div className="row-tight"><span style={{ width: 10, height: 10, borderRadius: 2, background: "var(--bg-elevated)", border: "1px solid var(--border)" }} />Upcoming</div>
      </div>
    </div>
  );
};

const BracketCell = ({ m, schools, width, height, showRight, showLeft, pairIndex }) => {
  const a = schools[m.a];
  const b = schools[m.b];
  const isLive = m.status === "live";
  const isDone = m.status === "complete";
  const connectorColor = isDone ? "rgba(45,212,120,0.45)" : isLive ? "rgba(255,59,92,0.45)" : "var(--border)";

  return (
    <div style={{ position: "relative" }}>
      {/* Right-side connector line (out to the next round) */}
      {showRight && (
        <>
          {/* horizontal stub */}
          <div style={{
            position: "absolute",
            right: -36, top: "50%",
            width: 36, height: 1.5,
            background: connectorColor,
            zIndex: 0,
          }} />
          {/* vertical pair connector — extends down if even pairIndex, up if odd */}
          <div style={{
            position: "absolute",
            right: -36,
            top: pairIndex % 2 === 0 ? "50%" : "auto",
            bottom: pairIndex % 2 === 1 ? "50%" : "auto",
            width: 1.5,
            height: `calc(${height / 2}px + 8px)`,
            background: connectorColor,
            zIndex: 0,
          }} />
        </>
      )}

      <div style={{
        width, minHeight: height,
        borderRadius: "var(--r-md)",
        border: "1px solid",
        borderColor: isLive ? "rgba(255,59,92,0.4)" : isDone ? "rgba(45,212,120,0.25)" : "var(--border)",
        background: isLive ? "rgba(255,59,92,0.06)" : "var(--bg-base)",
        overflow: "hidden",
        position: "relative",
        zIndex: 1,
      }}>
        {isLive && (
          <div style={{ position: "absolute", top: 4, right: 4 }}>
            <span className="badge live" style={{ fontSize: 9, padding: "1px 5px" }}><span className="dot" style={{ width: 4, height: 4 }} />LIVE</span>
          </div>
        )}
        {[{ team: m.a, score: m.aScore, school: a, win: m.winner === m.a },
          { team: m.b, score: m.bScore, school: b, win: m.winner === m.b }].map((side, i) => (
          <div key={i} style={{
            display: "flex", alignItems: "center", gap: 10,
            padding: "10px 12px",
            borderBottom: i === 0 ? "1px solid var(--border-soft)" : "none",
            background: side.win ? "rgba(45,212,120,0.08)" : "transparent",
          }}>
            {side.school ? <Crest school={side.school} size="sm" /> : <div className="crest sm" style={{ "--c1": "#1F2937", "--c2": "#0B0F18" }}>—</div>}
            <span style={{
              flex: 1, fontSize: 13,
              fontWeight: side.win ? 700 : 500,
              color: side.school ? (side.win ? "var(--text)" : "var(--text-secondary)") : "var(--text-muted)",
            }}>
              {side.school ? side.school.short : "TBD"}
            </span>
            {side.score != null && (
              <span className="mono" style={{ fontWeight: 700, color: side.win ? "var(--success)" : "var(--text-muted)" }}>{side.score}</span>
            )}
          </div>
        ))}
      </div>
    </div>
  );
};

window.BracketPage = BracketPage;
