// World map screen — map on left, side panel with countries / leagues / top matches

function MapScreen({ profile, onOpenPlayer, onNav }) {
  const [hoverIso, setHoverIso] = useState(null);
  const [selected, setSelected] = useState("PRT");

  const countries = window.IAMS_DATA.COUNTRIES;
  const players = window.IAMS_DATA.PLAYERS;

  const selectedCountry = countries.find(c => c.iso === selected);
  const countryPlayers = players
    .filter(p => p.country === selected)
    .sort((a, b) => b.fit - a.fit);

  const ranked = useMemo(
    () => [...countries].sort((a, b) => b.fit - a.fit),
    [countries]
  );

  return (
    <div style={{
      display: "grid",
      gridTemplateColumns: "1fr 380px",
      height: "calc(100vh - 50px - 57px)",
      minHeight: 640,
    }}>
      {/* Left: Map */}
      <div style={{ position: "relative", borderRight: "1px solid var(--rule)" }}>
        {/* profile summary strip */}
        <div style={{
          position: "absolute", top: 16, left: 16, zIndex: 5,
          background: "var(--panel)", border: "1px solid var(--rule)",
          borderRadius: "var(--radius)",
          padding: "10px 14px",
          fontFamily: "var(--mono)", fontSize: 11,
          color: "var(--ink-dim)", letterSpacing: "0.04em",
          display: "flex", gap: 14, alignItems: "center",
        }}>
          <span style={{ color: "var(--accent)" }}>●</span>
          <span><strong style={{ color: "var(--ink)" }}>{profile.name || "Musterstadt SV"}</strong></span>
          <Sep/>
          <span>{profile.league || "2. Bundesliga"} · tier {profile.tier || 2}</span>
          <Sep/>
          <span>budget: {profile.budget || "mid"}</span>
          <Sep/>
          <span>philosophy: {profile.philosophy || "pressing"}</span>
          <Sep/>
          <span>goal: {profile.goal || "u23"}</span>
        </div>

        <WorldMap
          countries={countries}
          selected={selected}
          hoverIso={hoverIso}
          onHover={setHoverIso}
          onSelect={setSelected}
        />

        {/* hover tooltip */}
        {hoverIso && (() => {
          const h = countries.find(c => c.iso === hoverIso);
          if (!h) return null;
          return (
            <div style={{
              position: "absolute", top: 72, right: 16, zIndex: 6,
              background: "var(--panel)", border: "1px solid var(--rule-strong)",
              borderRadius: "var(--radius)", padding: 14, width: 280,
              pointerEvents: "none",
            }}>
              <div className="mono" style={{ fontSize: 10, color: "var(--ink-muted)", letterSpacing: "0.08em" }}>
                {h.region.toUpperCase()} · {h.iso}
              </div>
              <div className="display" style={{ fontSize: 20, fontWeight: 600, marginTop: 2, letterSpacing: "-0.01em" }}>{h.name}</div>
              <div style={{ marginTop: 10, display: "flex", alignItems: "center", gap: 10 }}>
                <div className="tnum" style={{ fontSize: 22, fontWeight: 600, color: fitColor(h.fit) }}>{h.fit}</div>
                <div style={{ flex: 1 }}><FitBar value={h.fit}/></div>
              </div>
              <div style={{ marginTop: 10, fontSize: 12, color: "var(--ink-dim)", lineHeight: 1.45 }}>{h.note}</div>
              <div style={{ marginTop: 10, fontSize: 11 }} className="mono">
                {h.leagues.slice(0, 2).map((l, i) => (
                  <div key={l} style={{ color: "var(--ink-muted)" }}>↳ {l}</div>
                ))}
              </div>
            </div>
          );
        })()}
      </div>

      {/* Right side: drill-down */}
      <aside style={{
        display: "flex", flexDirection: "column",
        background: "var(--panel)", overflow: "hidden",
      }}>
        {selectedCountry ? (
          <>
            <div style={{ padding: "20px 22px 14px", borderBottom: "1px solid var(--rule)" }}>
              <div className="mono" style={{ fontSize: 10, color: "var(--ink-muted)", letterSpacing: "0.1em", textTransform: "uppercase" }}>
                Selected · {selectedCountry.region}
              </div>
              <div className="display" style={{ fontSize: 28, fontWeight: 600, letterSpacing: "-0.02em", marginTop: 2 }}>
                {selectedCountry.name}
              </div>
              <div style={{ marginTop: 10, display: "grid", gridTemplateColumns: "auto 1fr auto", gap: 10, alignItems: "center" }}>
                <span className="mono" style={{ fontSize: 10, color: "var(--ink-muted)" }}>FIT</span>
                <FitBar value={selectedCountry.fit}/>
                <span className="tnum" style={{ fontWeight: 600, color: fitColor(selectedCountry.fit) }}>{selectedCountry.fit}</span>
              </div>
              <div style={{ marginTop: 12, fontSize: 13, color: "var(--ink-dim)", lineHeight: 1.45 }}>
                {selectedCountry.note}
              </div>
            </div>

            <div style={{ padding: "14px 22px 8px" }}>
              <div className="mono" style={{ fontSize: 10, color: "var(--ink-muted)", letterSpacing: "0.1em", textTransform: "uppercase" }}>
                Top leagues
              </div>
              <div style={{ marginTop: 8, display: "grid", gap: 6 }}>
                {selectedCountry.leagues.map(l => (
                  <div key={l} style={{
                    display: "flex", alignItems: "center", justifyContent: "space-between",
                    padding: "8px 12px",
                    background: "var(--panel-2)",
                    border: "1px solid var(--rule)",
                    borderRadius: "var(--radius)",
                  }}>
                    <span style={{ fontSize: 14 }}>{l}</span>
                    <span className="mono" style={{ fontSize: 11, color: "var(--ink-muted)" }}>↗</span>
                  </div>
                ))}
              </div>
            </div>

            <div style={{ padding: "14px 22px 4px", display: "flex", alignItems: "baseline", justifyContent: "space-between" }}>
              <div className="mono" style={{ fontSize: 10, color: "var(--ink-muted)", letterSpacing: "0.1em", textTransform: "uppercase" }}>
                Shortlist · {countryPlayers.length} flagged
              </div>
              <button className="btn sm ghost" onClick={() => onNav("list")} style={{ fontSize: 11 }}>
                Open full list →
              </button>
            </div>

            <div style={{ padding: "8px 22px 22px", overflow: "auto" }}>
              {countryPlayers.length === 0 && (
                <div style={{ fontSize: 13, color: "var(--ink-muted)", fontStyle: "italic", padding: "18px 0" }}>
                  No flagged players in the prototype dataset for this region.<br/>
                  Live build will pull from Smrt Stats' 330-tournament index.
                </div>
              )}
              {countryPlayers.map(p => (
                <PlayerRow key={p.id} player={p} onClick={() => onOpenPlayer(p.id)} />
              ))}
            </div>
          </>
        ) : (
          <div style={{ padding: 40, color: "var(--ink-muted)" }}>Click a region to drill in.</div>
        )}

        {/* Global leaderboard */}
        <div style={{ borderTop: "1px solid var(--rule)", background: "var(--panel-2)" }}>
          <details>
            <summary style={{
              padding: "14px 22px",
              cursor: "pointer",
              fontFamily: "var(--mono)", fontSize: 10,
              letterSpacing: "0.1em", textTransform: "uppercase",
              color: "var(--ink-muted)",
            }}>
              Regional ranking · top 10 fit
            </summary>
            <div style={{ padding: "0 22px 16px" }}>
              {ranked.slice(0, 10).map((c, i) => (
                <button key={c.iso} onClick={() => setSelected(c.iso)}
                  style={{
                    display: "grid",
                    gridTemplateColumns: "24px 1fr 64px 32px",
                    gap: 10, alignItems: "center",
                    width: "100%", padding: "6px 0", textAlign: "left",
                    borderBottom: "1px solid var(--rule)",
                  }}>
                  <span className="mono tnum" style={{ fontSize: 11, color: "var(--ink-muted)" }}>{String(i+1).padStart(2,"0")}</span>
                  <span style={{ fontSize: 13 }}>{c.name}</span>
                  <FitBar value={c.fit}/>
                  <span className="mono tnum" style={{ fontSize: 11, color: fitColor(c.fit), textAlign: "right" }}>{c.fit}</span>
                </button>
              ))}
            </div>
          </details>
        </div>
      </aside>
    </div>
  );
}

function Sep() { return <span style={{ opacity: 0.4 }}>│</span>; }

// Compact player row — used in sidebar + shortlist screens
function PlayerRow({ player, onClick, dense = false }) {
  return (
    <button onClick={onClick} style={{
      display: "grid",
      gridTemplateColumns: "36px 1fr auto auto",
      gap: 12, alignItems: "center",
      width: "100%", padding: dense ? "8px 10px" : "12px 10px",
      borderBottom: "1px solid var(--rule)",
      textAlign: "left",
    }}>
      <div style={{
        width: 36, height: 36, borderRadius: "50%",
        background: "var(--chip-bg)",
        display: "grid", placeItems: "center",
        fontFamily: "var(--mono)", fontSize: 11, color: "var(--ink-dim)",
      }}>{player.name.split(" ").map(s => s[0]).slice(0,2).join("")}</div>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 500, letterSpacing: "-0.01em", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
          {player.name}
        </div>
        <div style={{ fontSize: 11, color: "var(--ink-muted)", display: "flex", gap: 8 }} className="mono">
          <span>{player.pos}</span><span>·</span><span>{player.age}</span><span>·</span>
          <span style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{player.club}</span>
        </div>
      </div>
      <div style={{ textAlign: "right" }}>
        <div className="mono tnum" style={{ fontSize: 11, color: "var(--ink-muted)", letterSpacing: "0.04em" }}>FIT</div>
        <div className="tnum" style={{ fontWeight: 600, color: fitColor(player.fit), fontSize: 15 }}>{player.fit}</div>
      </div>
      <div style={{ color: "var(--ink-muted)" }}>›</div>
    </button>
  );
}

Object.assign(window, { MapScreen, PlayerRow });
