// NextGen Ranking — player profile drawer.
// Triggered by ClassificationTable when a player row is clicked.
// Closes on row-click again, Escape, backdrop click, or close button.
// Stats come from window.getPlayerStatsCached (memoised per session).

const { useEffect, useMemo } = React;

function PlayerProfile({ playerName, tournaments, scopeKey, stages, t, onClose }) {
  // Scoped stats — memoised by (scopeKey, playerName) in stats.js.
  const stats = useMemo(
    () => window.getPlayerStatsCached(tournaments, playerName, scopeKey),
    [tournaments, playerName, scopeKey]
  );

  // Escape closes; body scroll locks while the drawer is open.
  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = prevOverflow;
    };
  }, [onClose]);

  if (!stats) return null;

  const P = t.dict.profile;
  const winRatePct = stats.matchesPlayed > 0
    ? Math.round(stats.winRate * 100) + "%"
    : "—";

  const stageById = new Map(stages.map(s => [s.id, s]));

  const renderPhase = (m) => {
    if (m.phase === "group") return P.phase.group + (m.group ? " " + m.group : "");
    if (P.phase[m.phase]) return P.phase[m.phase];
    return m.phase || "";
  };

  return (
    <div className="profile" role="dialog" aria-modal="true" aria-label={stats.name}>
      <div className="profile__backdrop" aria-hidden="true" />
      <div className="profile__panel" role="document">
        <header className="profile__head">
          <div className="profile__name-wrap">
            <div className="profile__name">{stats.name}</div>
            <div className="profile__record">
              {stats.won}–{stats.lost} · {P.matchesPlayed.toLowerCase()} {stats.matchesPlayed}
            </div>
          </div>
          <button
            type="button"
            className="profile__close"
            onClick={onClose}
            aria-label={P.close}
          >
            ×
          </button>
        </header>

        {stats.matchesPlayed === 0 ? (
          <div className="profile__empty">{P.noMatches}</div>
        ) : (
          <div className="profile__body">
            <section className="profile__headline">
              <div className="stat">
                <div className="stat__num">{stats.matchesPlayed}</div>
                <div className="stat__lbl">{P.matchesPlayed}</div>
              </div>
              <div className="stat stat--win">
                <div className="stat__num">{stats.won}</div>
                <div className="stat__lbl">{P.won}</div>
              </div>
              <div className="stat stat--loss">
                <div className="stat__num">{stats.lost}</div>
                <div className="stat__lbl">{P.lost}</div>
              </div>
              <div className="stat">
                <div className="stat__num">{winRatePct}</div>
                <div className="stat__lbl">{P.winRate}</div>
              </div>
            </section>

            <section className="profile__section">
              <h3 className="profile__h3">{P.partners}</h3>
              {stats.partners.length === 0 ? (
                <div className="profile__hint">{P.noPartners}</div>
              ) : (
                <ul className="profile__list">
                  {stats.partners.map((p) => (
                    <li key={p.partner} className="profile__list-row">
                      <span className="profile__list-name">{p.partner}</span>
                      <span className="profile__list-meta">
                        {P.partnerLine(p.matchesTogether, p.won)}
                      </span>
                    </li>
                  ))}
                </ul>
              )}
            </section>

            <section className="profile__section">
              <h3 className="profile__h3">{P.headToHead}</h3>
              {stats.headToHead.length === 0 ? (
                <div className="profile__hint">{P.noOpponents}</div>
              ) : (
                <ul className="profile__list">
                  {stats.headToHead.map((h) => (
                    <li key={h.opponent} className="profile__list-row">
                      <span className="profile__list-name">{h.opponent}</span>
                      <span className="profile__list-meta">
                        {P.h2hLine(h.matches, h.won, h.lost)}
                      </span>
                    </li>
                  ))}
                </ul>
              )}
            </section>

            <section className="profile__section">
              <h3 className="profile__h3">{P.recent}</h3>
              <ul className="profile__matches">
                {stats.recentMatches.map((m, i) => {
                  const stageLbl = m.stage && stageById.get(m.stage)
                    ? stageById.get(m.stage).label.replace(" Etapa", "")
                    : (m.stage ? m.stage + "" : "");
                  const resultCls = m.playerWon
                    ? "match__result--win"
                    : (m.playerLost ? "match__result--loss" : "match__result--draw");
                  const partnerName = m.myTeam.find(n => n !== playerName);
                  const scoreStr = (m.myScore != null && m.oppScore != null)
                    ? m.myScore + "–" + m.oppScore
                    : "";
                  return (
                    <li key={i} className="match">
                      <div className="match__tag">
                        {stageLbl && <span className="match__stage">{stageLbl}</span>}
                        <span className="match__phase">{renderPhase(m)}</span>
                      </div>
                      <div className="match__teams">
                        {partnerName && (
                          <div className="match__partner">{P.withPartner(partnerName)}</div>
                        )}
                        <div className="match__vs">
                          {P.vs} {m.oppTeam.join(" / ")}
                        </div>
                      </div>
                      <div className={"match__result " + resultCls}>
                        <span className="match__result-mark">
                          {m.playerWon ? P.win : (m.playerLost ? P.loss : "·")}
                        </span>
                        {scoreStr && <span className="match__score">{scoreStr}</span>}
                      </div>
                    </li>
                  );
                })}
              </ul>
            </section>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { PlayerProfile });
