// Competitions — browse seasons / leagues. Only SSBU CIF Varsity is fully populated.

const CompetitionsPage = ({ persona, onNav }) => {
  const D = window.NASEF_DATA;
  const [filter, setFilter] = React.useState("all");
  const [selected, setSelected] = React.useState(null);

  const filtered = D.competitions.filter(c => {
    if (filter === "registered") return c.registered;
    if (filter === "open") return c.status === "registration";
    return true;
  });

  return (
    <div>
      <PageHeader
        eyebrow="Fall 2026 Season"
        title="Competitions"
        subtitle="Browse active leagues and tournaments. Register your teams for the next season."
        actions={persona === "admin" ? [<button key="new" className="btn primary"><IconPlus size={14} />Create competition</button>] : null}
      />

      <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 20, alignItems: "center", gap: 16 }}>
        <Tabs value={filter} onChange={setFilter} items={[
          { value: "all", label: "All competitions" },
          { value: "registered", label: "My teams" },
          { value: "open", label: "Open registration" },
        ]} />
        <div className="row" style={{ gap: 8, fontSize: 12, color: "var(--text-muted)" }}>
          <IconInfo size={13} />
          <span>Demo: only <strong style={{ color: "var(--text-secondary)" }}>SSBU Varsity</strong> is fully populated</span>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 16 }}>
        {filtered.map(c => {
          const isMain = c.id === "ssbu-cif-26";
          const progress = c.totalWeeks ? (c.week / c.totalWeeks) * 100 : 0;
          return (
            <div key={c.id} className="card" style={{
              padding: 0,
              border: isMain ? "1px solid rgba(242,104,34,0.4)" : "1px solid var(--border)",
              background: isMain ? "linear-gradient(180deg, rgba(242,104,34,0.06) 0%, var(--bg-raised) 50%)" : "var(--bg-raised)",
              opacity: c.populated ? 1 : 0.7,
              cursor: "pointer",
              transition: "all 0.12s",
            }}
              onClick={() => setSelected(c)}
              onMouseEnter={e => e.currentTarget.style.transform = "translateY(-2px)"}
              onMouseLeave={e => e.currentTarget.style.transform = "translateY(0)"}
            >
              <div style={{ padding: "20px 22px", display: "flex", alignItems: "flex-start", gap: 16 }}>
                <div style={{
                  width: 48, height: 48, borderRadius: 10,
                  background: c.game === "SSBU" ? "linear-gradient(135deg, #FF4D9F 0%, #B91C5C 100%)" :
                              c.game === "MK8"  ? "linear-gradient(135deg, #F7B928 0%, #B45309 100%)" :
                              c.game === "RL"   ? "linear-gradient(135deg, #4FE3FF 0%, #1E5C8C 100%)" :
                              c.game === "VAL"  ? "linear-gradient(135deg, #F2455F 0%, #911C2F 100%)" :
                                                  "linear-gradient(135deg, #888, #444)",
                  color: "#0F0817",
                  display: "flex", alignItems: "center", justifyContent: "center",
                  fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 14,
                  flexShrink: 0,
                }}>{c.game}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 8, marginBottom: 4 }}>
                    <h3 style={{ fontSize: 16, fontWeight: 600 }}>{c.title}</h3>
                    {c.registered && <span className="badge orange">Registered</span>}
                  </div>
                  <div className="muted" style={{ fontSize: 12 }}>{c.season} · {c.division} · {c.format}</div>
                </div>
              </div>

              <div style={{ padding: "0 22px 16px" }}>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11, marginBottom: 6, color: "var(--text-muted)" }}>
                  <span className="upper">{c.status === "registration" ? "Registration open" : `Week ${c.week} of ${c.totalWeeks}`}</span>
                  <span>{c.teams} teams</span>
                </div>
                <div style={{ height: 4, background: "var(--bg-deep)", borderRadius: 99, overflow: "hidden" }}>
                  <div style={{
                    height: "100%",
                    width: c.status === "registration" ? "0%" : `${progress}%`,
                    background: isMain ? "linear-gradient(90deg, var(--nasef-orange), var(--nasef-orange-soft))" : "var(--neon-cyan)",
                    transition: "width 0.4s",
                  }} />
                </div>
              </div>

              <div style={{ padding: "12px 22px", borderTop: "1px solid var(--border-soft)", display: "flex", justifyContent: "space-between", alignItems: "center", fontSize: 12 }}>
                <span style={{ color: c.populated ? "var(--text-secondary)" : "var(--text-muted)" }}>
                  {c.populated ? `${c.teams} teams competing` : "Demo placeholder"}
                </span>
                <span className="row-tight" style={{ color: isMain ? "var(--nasef-orange-soft)" : "var(--text-secondary)" }}>
                  View details <IconChevRight size={12} />
                </span>
              </div>
            </div>
          );
        })}
      </div>

      {selected && (
        <CompetitionDetail comp={selected} onClose={() => setSelected(null)} onNav={onNav} persona={persona} />
      )}
    </div>
  );
};

const CompetitionDetail = ({ comp, onClose, onNav, persona }) => {
  const D = window.NASEF_DATA;
  return (
    <div style={{
      position: "fixed", inset: 0, background: "var(--bg-overlay)", backdropFilter: "blur(4px)",
      display: "flex", justifyContent: "center", alignItems: "center", zIndex: 100, padding: 40,
    }} onClick={onClose}>
      <div className="card" style={{ width: 720, maxHeight: "85vh", overflow: "auto", padding: 0 }}
        onClick={e => e.stopPropagation()}>
        <div style={{ padding: "20px 24px", borderBottom: "1px solid var(--border-soft)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <div>
            <div className="upper muted">{comp.season} · {comp.division}</div>
            <h2 style={{ fontSize: 22, marginTop: 4 }}>{comp.title}</h2>
          </div>
          <button className="btn ghost icon" onClick={onClose}><IconX size={14} /></button>
        </div>
        <div style={{ padding: 24 }}>
          {!comp.populated ? (
            <Empty icon={IconInfo} title="Demo placeholder"
              body="This competition exists in the navigation to show breadth, but only the CIF SSBU Varsity competition is fully populated for the demo."
              action={<button className="btn" onClick={onClose}>Close</button>}
            />
          ) : (
            <>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12, marginBottom: 24 }}>
                <Stat label="Format" value={comp.format} />
                <Stat label="Teams" value={comp.teams} />
                <Stat label="Week" value={`${comp.week} / ${comp.totalWeeks}`} />
                <Stat label="Status" value="In progress" color="var(--success)" />
              </div>
              <h3 style={{ fontSize: 13, textTransform: "uppercase", letterSpacing: "0.1em", color: "var(--text-secondary)", marginBottom: 12 }}>Standings</h3>
              <div style={{ borderRadius: "var(--r-md)", border: "1px solid var(--border-soft)", overflow: "hidden", marginBottom: 18 }}>
                <table className="table">
                  <thead><tr><th style={{ width: 30 }}>#</th><th>Team</th><th style={{ textAlign: "right" }}>W-L</th><th style={{ textAlign: "right" }}>+/-</th></tr></thead>
                  <tbody>
                    {D.standings.slice(0, 6).map(s => {
                      const sch = D.schoolsById[s.schoolId];
                      return (
                        <tr key={s.schoolId}>
                          <td className="mono muted">{s.rank}</td>
                          <td><div className="row" style={{ gap: 10 }}><Crest school={sch} size="sm" /><span>{sch.name}</span></div></td>
                          <td className="mono" style={{ textAlign: "right", fontWeight: 600 }}>{s.w}-{s.l}</td>
                          <td className="mono" style={{ textAlign: "right", color: s.pf - s.pa >= 0 ? "var(--success)" : "var(--text-muted)" }}>{s.pf - s.pa >= 0 ? "+" : ""}{s.pf - s.pa}</td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
              <div className="row" style={{ gap: 8 }}>
                <button className="btn primary" onClick={() => { onNav("standings"); onClose(); }}>Full standings</button>
                <button className="btn" onClick={() => { onNav("bracket"); onClose(); }}>View bracket</button>
                <button className="btn ghost">Download rulebook <IconExternal size={12} /></button>
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
};

const Stat = ({ label, value, color }) => (
  <div style={{ padding: 14, background: "var(--bg-base)", borderRadius: "var(--r-md)", border: "1px solid var(--border-soft)" }}>
    <div className="upper muted" style={{ fontSize: 10, marginBottom: 4 }}>{label}</div>
    <div style={{ fontSize: 14, fontWeight: 600, color: color || "var(--text)" }}>{value}</div>
  </div>
);

window.CompetitionsPage = CompetitionsPage;
