/* global React */

// ---- Knockout bracket card ----------------------------------------------
function BracketCard({ m, onTeam, tone }) {
  const T = window.TOURNAMENT;
  const winId = T.winnerOf(m);
  const rows = [m.home, m.away].map((tid) => {
    const team = T.TEAMS[tid];
    const isHome = tid === m.home;
    const sc = isHome ? m.hs : m.as;
    const win = winId === tid;
    return (
      <button key={tid} className={"bteam" + (win ? " bteam--win" : winId ? " bteam--out" : "")} onClick={() => onTeam(tid)}>
        <window.Badge team={team} size={26} />
        <span className="bteam__name">{team.short}{m.pen && win && <span className="bteam__pen">P</span>}</span>
        <span className="bteam__sc">{sc}</span>
      </button>
    );
  });
  return (
    <div className={"bcard" + (tone ? " bcard--" + tone : "")}>
      <div className="bcard__label">{m.label}</div>
      <div className="bcard__rows">{rows}</div>
    </div>
  );
}

function Bracket({ onTeam }) {
  const T = window.TOURNAMENT;
  const byNo = (n) => T.MATCHES.find((x) => x.no === n);
  const champ = T.TEAMS["pppk"];
  return (
    <div className="bracket">
      <div className="bracket__col">
        <div className="bracket__round">Semi-Finals</div>
        <BracketCard m={byNo(13)} onTeam={onTeam} />
        <div className="bracket__spacer" />
        <BracketCard m={byNo(14)} onTeam={onTeam} />
      </div>
      <div className="bracket__connect" aria-hidden="true">
        <svg viewBox="0 0 60 220" preserveAspectRatio="none"><path d="M0 40 H30 V110 H60 M0 180 H30 V110" fill="none" stroke="currentColor" strokeWidth="2"/></svg>
      </div>
      <div className="bracket__col bracket__col--final">
        <div className="bracket__round">Grand Final</div>
        <BracketCard m={byNo(16)} onTeam={onTeam} tone="final" />
        <div className="champbox">
          <Medal />
          <div>
            <div className="champbox__label">Champions</div>
            <button className="champbox__team" onClick={() => onTeam("pppk")}>{champ.name}</button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ---- Simple medal mark (basic shapes only) ------------------------------
function Medal({ size = 34 }) {
  return (
    <svg className="medal" width={size} height={size} viewBox="0 0 34 34">
      <path d="M11 2 L9 13 M23 2 L25 13" stroke="var(--gold)" strokeWidth="2.4" strokeLinecap="round" />
      <circle cx="17" cy="21" r="11" fill="var(--gold)" />
      <circle cx="17" cy="21" r="7.5" fill="none" stroke="oklch(0.30 0.05 85)" strokeWidth="1.5" />
      <text x="17" y="25.5" textAnchor="middle" fontFamily="Archivo, sans-serif" fontWeight="800" fontSize="11" fill="oklch(0.28 0.05 85)">1</text>
    </svg>
  );
}

// ---- Team detail panel (modal) ------------------------------------------
function TeamPanel({ teamId, onClose, onTeam }) {
  const T = window.TOURNAMENT;
  if (!teamId) return null;
  const team = T.TEAMS[teamId];
  const rec = T.teamRecord(teamId);
  const champ = teamId === "pppk";

  const statCells = [
    ["P", rec.played], ["W", rec.w], ["D", rec.d], ["L", rec.l],
    ["GF", rec.gf], ["GA", rec.ga], ["GD", (rec.gd >= 0 ? "+" : "") + rec.gd], ["PTS", rec.pts],
  ];

  return (
    <div className="modal" onClick={onClose}>
      <div className="panel" style={window.teamVars(team)} onClick={(e) => e.stopPropagation()}>
        <button className="panel__x" onClick={onClose} aria-label="Close">
          <svg viewBox="0 0 20 20" width="20" height="20"><path d="M5 5l10 10M15 5L5 15" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/></svg>
        </button>
        <div className="panel__head">
          <window.Badge team={team} size={68} />
          <div>
            <div className="panel__group">Group {team.group}{champ && <span className="panel__champtag">Champions</span>}</div>
            <h2 className="panel__name">{team.name}</h2>
          </div>
        </div>

        <div className="panel__stats">
          {statCells.map(([k, v]) => (
            <div className="statcell" key={k}>
              <div className="statcell__v">{v}</div>
              <div className="statcell__k">{k}</div>
            </div>
          ))}
        </div>

        {rec.penWins > 0 && (
          <div className="panel__pens">
            <span className="panel__pensdot" aria-hidden="true"></span>
            Won {rec.penWins} match{rec.penWins > 1 ? "es" : ""} on penalties
          </div>
        )}

        <div className="panel__label">All matches</div>
        <div className="panel__matches">
          {rec.games.map((m) => {
            const isHome = m.home === teamId;
            const opp = T.TEAMS[isHome ? m.away : m.home];
            const us = isHome ? m.hs : m.as;
            const them = isHome ? m.as : m.hs;
            const winId = T.winnerOf(m);
            let kind = "D";
            if (m.pen) kind = winId === teamId ? "P" : "L";
            else if (us > them) kind = "W";
            else if (us < them) kind = "L";
            return (
              <button className="pmatch" key={m.no} onClick={() => onTeam(opp.id)}>
                <window.ResultChip kind={kind} />
                <span className="pmatch__opp"><window.Badge team={opp} size={24} /> {opp.short}</span>
                <span className="pmatch__sc">{us}<span>–</span>{them}</span>
                <span className="pmatch__stage"><window.StageTag m={m} /></span>
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Bracket, BracketCard, Medal, TeamPanel });
