/* global React */

// ---- color helpers -------------------------------------------------------
function teamVars(team) {
  const h = team.hue;
  return {
    "--tc":     `oklch(0.71 0.16 ${h})`,
    "--tc-dim": `oklch(0.60 0.14 ${h})`,
    "--tc-deep":`oklch(0.34 0.075 ${h})`,
    "--tc-soft":`oklch(0.27 0.04 ${h})`,
  };
}

// ---- Team badge ----------------------------------------------------------
function Badge({ team, size = 40, onClick }) {
  const cls = "badge" + (team.id === "pppk" ? " badge--brand" : "") + (onClick ? " badge--btn" : "");
  return (
    <span
      className={cls}
      style={{ ...teamVars(team), width: size, height: size, fontSize: size * 0.36 }}
      onClick={onClick ? (e) => { e.stopPropagation(); onClick(team.id); } : undefined}
      title={team.name}
    >
      {team.abbr}
    </span>
  );
}

// ---- Result chip (W / D / L / P) ----------------------------------------
function ResultChip({ kind }) {
  return <span className={"rchip rchip--" + kind}>{kind}</span>;
}

// ---- Stage tag -----------------------------------------------------------
function StageTag({ m }) {
  if (m.stage === "group") return <span className="stage-tag">Group {m.group}</span>;
  const label = { semi: m.label, third: "3rd Place", final: "Final" }[m.stage] || m.label;
  return <span className={"stage-tag stage-tag--ko stage-tag--" + m.stage}>{label}</span>;
}

// ---- one team line within a match ---------------------------------------
function TeamRow({ m, side, onTeam }) {
  const T = window.TOURNAMENT;
  const tid = side === "home" ? m.home : m.away;
  const team = T.TEAMS[tid];
  const sc = side === "home" ? m.hs : m.as;
  const winId = T.winnerOf(m);
  const win = winId === tid;
  const lose = winId && winId !== tid;
  return (
    <span className={"trow" + (win ? " trow--win" : lose ? " trow--lose" : " trow--draw")} style={teamVars(team)}>
      <Badge team={team} size={34} onClick={onTeam} />
      <span className="trow__name" onClick={(e) => { e.stopPropagation(); onTeam(tid); }}>
        {team.short}
        {m.pen && win && <span className="trow__pen">P</span>}
      </span>
      <span className="trow__sc">{sc}</span>
    </span>
  );
}

// ---- Match row -----------------------------------------------------------
function MatchRow({ m, expanded, onToggle, onTeam }) {
  return (
    <div className={"match" + (expanded ? " match--open" : "")}>
      <button className="match__main" onClick={() => onToggle(m.no)}>
        <span className="match__no">{String(m.no).padStart(2, "0")}</span>
        <span className="match__teams">
          <TeamRow m={m} side="home" onTeam={onTeam} />
          <TeamRow m={m} side="away" onTeam={onTeam} />
        </span>
        <span className="match__meta">
          <StageTag m={m} />
          {m.pen && <span className="pens-flag">PENS</span>}
          <svg className="chev" viewBox="0 0 16 16" width="15" height="15"><path d="M4 6l4 4 4-4" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
        </span>
      </button>
      {expanded && <MatchDetail m={m} onTeam={onTeam} />}
    </div>
  );
}

// ---- Expanded detail -----------------------------------------------------
function MatchDetail({ m, onTeam }) {
  const T = window.TOURNAMENT;
  const home = T.TEAMS[m.home];
  const away = T.TEAMS[m.away];
  const winId = T.winnerOf(m);
  const win = winId ? T.TEAMS[winId] : null;
  const hPts = T.pointsFor(m, m.home);
  const aPts = T.pointsFor(m, m.away);

  return (
    <div className="detail">
      <div className="detail__col">
        <div className="detail__label">Result</div>
        {win ? (
          <div className="detail__result">
            <Badge team={win} size={26} onClick={onTeam} />
            <span><b>{win.name}</b> {m.pen ? "won on penalties" : "win"}</span>
          </div>
        ) : (
          <div className="detail__result"><span><b>Draw</b></span></div>
        )}
        {m.pen && <div className="detail__pen">Level at {m.hs}–{m.as} after full time · settled from the spot</div>}
      </div>

      {m.stage === "group" && (
        <div className="detail__col">
          <div className="detail__label">Points awarded</div>
          <div className="detail__pts">
            <span className="pts-row"><Badge team={home} size={22} onClick={onTeam} /> {home.short} <b>+{hPts}</b></span>
            <span className="pts-row"><Badge team={away} size={22} onClick={onTeam} /> {away.short} <b>+{aPts}</b></span>
          </div>
        </div>
      )}

      <div className="detail__col">
        <div className="detail__label">Fixture</div>
        <div className="detail__fixture">
          <StageTag m={m} />
          <span className="detail__matchno">Match {m.no} of {T.META.matchesCount}</span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Badge, ResultChip, StageTag, TeamRow, MatchRow, MatchDetail, teamVars });
