// Camelot Compatibility — dedicated screen.
// The musical Camelot Wheel re-imagined for football: harmonic matching between
// target players and your club across Role / Geo / League / Mental.

function CamelotScreen({ profile, onOpenPlayer, onNav }) {
  const D = window.IAMS_DATA;
  const { TARGETS, findPlayer, camelotFor, camelotKey, profileCamelotKey, camelotMatch, camelotReasoning, COUNTRIES } = D;
  const profileKey = profileCamelotKey(profile);

  const [selectedId, setSelectedId] = useState(TARGETS[0].id);
  const player = findPlayer(selectedId);
  const camAxes = camelotFor(player, profile);
  const reasoning = camelotReasoning(player, profile, camAxes);
  const match = camelotMatch(player.camelotKey, profileKey);

  // Rank targets by overall Camelot score (axis avg)
  const rankedTargets = TARGETS.map(p => {
    const axes = camelotFor(p, profile);
    const avg = Math.round(axes.reduce((s, a) => s + a.score, 0) / axes.length);
    const m = camelotMatch(p.camelotKey, profileKey);
    return { ...p, camelotAxes: axes, camelotAvg: avg, match: m };
  }).sort((a, b) => b.camelotAvg - a.camelotAvg);

  const [filter, setFilter] = useState("all"); // all | harmonic | neutral | clash

  const filtered = rankedTargets.filter(p => {
    if (filter === "all") return true;
    return p.match === filter || (filter === "harmonic" && p.match === "perfect");
  });

  return (
    <div style={{ padding: "28px 40px 60px", maxWidth: 1440, margin: "0 auto", width: "100%" }}
      data-screen-label="09 Camelot">
      {/* Header */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr auto", gap: 20, alignItems: "end", marginBottom: 18 }}>
        <div>
          <div className="mono" style={{ fontSize: 11, color: "var(--accent)", letterSpacing: "0.14em", textTransform: "uppercase", marginBottom: 8 }}>
            Camelot · the harmonic wheel of football
          </div>
          <h1 className="display" style={{
            fontSize: "clamp(28px, 3.6vw, 44px)", fontWeight: 600, letterSpacing: "-0.025em",
            lineHeight: 1.02, margin: 0,
          }}>
            Mix players into your team like a <span className="underline-accent">DJ mixes tracks</span>.
          </h1>
          <p style={{ marginTop: 10, fontSize: 15, color: "var(--ink-dim)", maxWidth: 760, textWrap: "pretty" }}>
            Every player and every club gets a Camelot Key. Adjacent keys blend harmonically; distant keys clash.
            We score compatibility across four axes — <strong>Role · Geo · League · Mental</strong> — so
            you don't just sign a good player; you sign the <em>right</em> player for how you play.
          </p>
        </div>
        <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
          <div>
            <div className="mono" style={{ fontSize: 10, color: "var(--ink-muted)", letterSpacing: "0.1em", textTransform: "uppercase", marginBottom: 4, textAlign: "right" }}>
              Your club key
            </div>
            <CamelotKeyPill keyCode={profileKey.code} match="perfect"/>
          </div>
        </div>
      </div>

      {/* MAIN WHEEL + DETAILS */}
      <div style={{ display: "grid", gridTemplateColumns: "1.1fr 1fr", gap: 20 }}>
        {/* Left: big Camelot Wheel with players placed by key */}
        <div className="card" style={{ padding: 24 }}>
          <div className="mono" style={{ fontSize: 10, color: "var(--ink-muted)", letterSpacing: "0.14em", textTransform: "uppercase", marginBottom: 14 }}>
            Wheel · all {TARGETS.length} targets by key
          </div>
          <BigCamelotWheel
            targets={rankedTargets}
            profileKey={profileKey}
            selectedId={selectedId}
            onSelect={setSelectedId}
          />
          <div style={{ marginTop: 12, display: "flex", gap: 18, justifyContent: "center", flexWrap: "wrap" }}>
            <Legend color="var(--good)" label="Harmonic (±1 key)"/>
            <Legend color="var(--mid)"  label="Neutral (±2)"/>
            <Legend color="var(--bad)"  label="Clash (±4+)"/>
            <Legend color="var(--accent)" label="Your club" filled/>
          </div>
        </div>

        {/* Right: selected player 4-axis reasoning */}
        <div className="card" style={{ padding: 24 }}>
          <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 14 }}>
            <div className="mono" style={{ fontSize: 10, color: "var(--ink-muted)", letterSpacing: "0.14em", textTransform: "uppercase" }}>
              Selected · 4-axis reasoning
            </div>
            <button className="btn ghost sm" onClick={() => onOpenPlayer(player.id)}>Open profile →</button>
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "1fr auto", gap: 12, alignItems: "start" }}>
            <div>
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <div className="display" style={{ fontSize: 26, fontWeight: 600, letterSpacing: "-0.02em" }}>{player.name}</div>
                <CamelotKeyPill keyCode={player.camelotKey.code} match={match}/>
              </div>
              <div className="mono" style={{ fontSize: 11, color: "var(--ink-muted)", marginTop: 4 }}>
                {player.pos} · {player.age} · {player.club} · {COUNTRIES.find(c => c.iso === player.country)?.name}
              </div>
            </div>
            <div style={{ textAlign: "right" }}>
              <div className="display tnum" style={{ fontSize: 32, fontWeight: 600, color: "var(--accent)" }}>
                {Math.round(camAxes.reduce((s, a) => s + a.score, 0) / 4)}
              </div>
              <div className="mono" style={{ fontSize: 10, color: "var(--ink-muted)", letterSpacing: "0.1em", textTransform: "uppercase" }}>avg</div>
            </div>
          </div>

          <div style={{ marginTop: 20, display: "grid", gap: 10 }}>
            {camAxes.map(a => (
              <AxisRow key={a.axis} axis={a.axis} score={a.score} band={a.band}
                reasoning={reasoning[a.axis]}/>
            ))}
          </div>

          <div style={{ marginTop: 20, padding: 14, background: "var(--panel-2)", border: "1px solid var(--rule)" }}>
            <div className="mono" style={{ fontSize: 10, color: "var(--accent)", letterSpacing: "0.14em", textTransform: "uppercase", marginBottom: 8 }}>
              Camelot verdict
            </div>
            <div style={{ fontSize: 14, lineHeight: 1.5, color: "var(--ink)" }}>
              <Verdict match={match} player={player} profile={profile}/>
            </div>
          </div>
        </div>
      </div>

      {/* RANKED TABLE */}
      <div className="card" style={{ marginTop: 20, padding: 0 }}>
        <div style={{
          display: "flex", alignItems: "center", gap: 12, padding: "16px 20px",
          borderBottom: "1px solid var(--rule)",
        }}>
          <div className="mono" style={{ fontSize: 10, color: "var(--ink-muted)", letterSpacing: "0.14em", textTransform: "uppercase" }}>
            Targets ranked by Camelot avg
          </div>
          <div style={{ flex: 1 }}/>
          <div className="seg">
            {[
              { id: "all",      l: "All" },
              { id: "harmonic", l: "Harmonic only" },
              { id: "neutral",  l: "Neutral" },
              { id: "clash",    l: "Hide clashes" },
            ].map(f => (
              <button key={f.id} className={filter === f.id ? "on" : ""}
                onClick={() => setFilter(f.id === "clash" ? "harmonic" : f.id)}>
                {f.l}
              </button>
            ))}
          </div>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "40px 1.5fr 80px 70px 1fr 80px 70px", gap: 12, padding: "10px 20px", borderBottom: "1px solid var(--rule)", fontFamily: "var(--mono)", fontSize: 10, color: "var(--ink-muted)", letterSpacing: "0.08em", textTransform: "uppercase" }}>
          <div>#</div>
          <div>Player</div>
          <div style={{ textAlign: "center" }}>Key</div>
          <div style={{ textAlign: "center" }}>Match</div>
          <div>Role · Geo · League · Mental</div>
          <div style={{ textAlign: "right" }}>Avg</div>
          <div style={{ textAlign: "right" }}>IAMS</div>
        </div>
        {filtered.map((p, i) => (
          <button key={p.id}
            onClick={() => setSelectedId(p.id)}
            style={{
              display: "grid", gridTemplateColumns: "40px 1.5fr 80px 70px 1fr 80px 70px", gap: 12,
              alignItems: "center", padding: "12px 20px", borderBottom: "1px solid var(--rule)",
              textAlign: "left", width: "100%", cursor: "pointer",
              background: p.id === selectedId ? "var(--accent-soft)" : "transparent",
            }}>
            <div className="mono tnum" style={{ fontSize: 11, color: "var(--ink-muted)" }}>{String(i + 1).padStart(2, "0")}</div>
            <div>
              <div style={{ fontSize: 13.5, fontWeight: 600 }}>{p.name}</div>
              <div className="mono" style={{ fontSize: 10.5, color: "var(--ink-muted)" }}>{p.pos} · {p.age} · {p.club}</div>
            </div>
            <div style={{ textAlign: "center" }}>
              <span className="mono" style={{ fontSize: 11.5, fontWeight: 700, color: "var(--accent)" }}>{p.camelotKey.code}</span>
            </div>
            <div style={{ textAlign: "center" }}>
              <MatchPill match={p.match}/>
            </div>
            <div style={{ display: "flex", gap: 4, alignItems: "center" }}>
              <CamelotMini data={p.camelotAxes} size={26}/>
              <div style={{ display: "flex", gap: 3 }}>
                {p.camelotAxes.map(a => (
                  <span key={a.axis} className="mono tnum" style={{
                    fontSize: 10, padding: "1px 5px",
                    color: a.band === "good" ? "var(--good)" : a.band === "mid" ? "var(--mid)" : "var(--bad)",
                    background: "var(--chip-bg)",
                  }}>{a.score}</span>
                ))}
              </div>
            </div>
            <div className="display tnum" style={{ fontSize: 20, fontWeight: 600, textAlign: "right",
              color: p.camelotAvg >= 75 ? "var(--good)" : p.camelotAvg >= 55 ? "var(--mid)" : "var(--bad)" }}>
              {p.camelotAvg}
            </div>
            <div className="mono tnum" style={{ fontSize: 12, textAlign: "right" }}>{p.iams}</div>
          </button>
        ))}
      </div>

      {/* MUSIC THEORY EXPLAINER */}
      <div className="card" style={{ marginTop: 20, padding: 24 }}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 20 }}>
          <div>
            <div className="mono" style={{ fontSize: 10, color: "var(--accent)", letterSpacing: "0.14em", textTransform: "uppercase", marginBottom: 8 }}>
              Borrowed from DJs
            </div>
            <div className="display" style={{ fontSize: 17, fontWeight: 600, lineHeight: 1.3 }}>
              In music, the Camelot Wheel helps DJs mix two tracks without a key clash.
              We apply the same idea to football — compatibility isn't a gut feel, it's a theory.
            </div>
          </div>
          <div>
            <div className="mono" style={{ fontSize: 10, color: "var(--accent)", letterSpacing: "0.14em", textTransform: "uppercase", marginBottom: 8 }}>
              Four axes, not one
            </div>
            <div style={{ fontSize: 13, lineHeight: 1.5, color: "var(--ink-dim)" }}>
              A player can be an elite <strong>Role</strong> match but a poor <strong>Geo</strong> one. Camelot
              surfaces both so you don't get surprised by adaptation risk after signing.
            </div>
          </div>
          <div>
            <div className="mono" style={{ fontSize: 10, color: "var(--accent)", letterSpacing: "0.14em", textTransform: "uppercase", marginBottom: 8 }}>
              Worked example
            </div>
            <div style={{ fontSize: 13, lineHeight: 1.5, color: "var(--ink-dim)" }}>
              Messi → USA (good), Premier League (poor), Eredivisie (good), Bundesliga (medium).
              Same player, four different answers.
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// Big Camelot Wheel — 12 keys × 2 rings (A/B), players plotted as dots
function BigCamelotWheel({ targets, profileKey, selectedId, onSelect }) {
  const size = 460;
  const cx = size / 2, cy = size / 2;
  const rOuter = size / 2 - 40;
  const rInner = rOuter * 0.56;
  const rMid   = (rOuter + rInner) / 2;

  // 12 slices
  return (
    <div style={{ display: "flex", justifyContent: "center" }}>
      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
        {/* 12 slices × 2 rings */}
        {Array.from({ length: 12 }).map((_, i) => {
          const a0 = (i / 12) * 2 * Math.PI - Math.PI / 2;
          const a1 = ((i + 1) / 12) * 2 * Math.PI - Math.PI / 2;
          const amid = (a0 + a1) / 2;
          const keyN = i + 1;
          // Distance from profile key (for color tinting)
          const diff = Math.abs(keyN - profileKey.n);
          const mod = Math.min(diff, 12 - diff);
          const tint = mod === 0 ? "var(--accent-soft)"
                     : mod === 1 ? "rgba(26,122,54,0.10)"
                     : mod === 2 ? "rgba(209,151,18,0.08)"
                     : "rgba(195,50,31,0.06)";
          const ring = (rI, rO, letter) => {
            const p = (a, r) => [cx + Math.cos(a) * r, cy + Math.sin(a) * r];
            const [x0o, y0o] = p(a0, rO);
            const [x1o, y1o] = p(a1, rO);
            const [x0i, y0i] = p(a0, rI);
            const [x1i, y1i] = p(a1, rI);
            return `M ${x0i} ${y0i} L ${x0o} ${y0o} A ${rO} ${rO} 0 0 1 ${x1o} ${y1o} L ${x1i} ${y1i} A ${rI} ${rI} 0 0 0 ${x0i} ${y0i} Z`;
          };
          return (
            <g key={i}>
              {/* outer (B) */}
              <path d={ring(rMid, rOuter)} fill={tint} stroke="var(--rule)" strokeWidth="0.5"/>
              {/* inner (A) */}
              <path d={ring(rInner, rMid)} fill={tint} stroke="var(--rule)" strokeWidth="0.5"/>
              {/* key labels */}
              <text x={cx + Math.cos(amid) * (rOuter + 18)} y={cy + Math.sin(amid) * (rOuter + 18)}
                textAnchor="middle" dominantBaseline="middle"
                fontFamily="var(--mono)" fontSize="10" fontWeight="700"
                fill={mod <= 1 ? "var(--accent)" : "var(--ink-dim)"}>
                {keyN}
              </text>
              <text x={cx + Math.cos(amid) * (rOuter - 8)} y={cy + Math.sin(amid) * (rOuter - 8)}
                textAnchor="middle" dominantBaseline="middle"
                fontFamily="var(--mono)" fontSize="7"
                fill="var(--ink-muted)">B</text>
              <text x={cx + Math.cos(amid) * (rMid - 8)} y={cy + Math.sin(amid) * (rMid - 8)}
                textAnchor="middle" dominantBaseline="middle"
                fontFamily="var(--mono)" fontSize="7"
                fill="var(--ink-muted)">A</text>
            </g>
          );
        })}

        {/* Center = YOUR CLUB */}
        <circle cx={cx} cy={cy} r={rInner - 4} fill="var(--ink)"/>
        <text x={cx} y={cy - 5} textAnchor="middle" dominantBaseline="middle"
          fontFamily="var(--display)" fontSize="13" fontWeight="600" fill="var(--bg)">
          YOU
        </text>
        <text x={cx} y={cy + 12} textAnchor="middle" dominantBaseline="middle"
          fontFamily="var(--mono)" fontSize="16" fontWeight="700" fill="var(--accent)">
          {profileKey.code}
        </text>

        {/* Plot each target as a dot within their key slice */}
        {targets.map((p, idx) => {
          const i = (p.camelotKey.n - 1); // 0..11
          const letter = p.camelotKey.letter;
          const a0 = (i / 12) * 2 * Math.PI - Math.PI / 2;
          const a1 = ((i + 1) / 12) * 2 * Math.PI - Math.PI / 2;
          const jitter = ((idx * 37) % 10) / 10 * 0.7 + 0.15; // within slice
          const amid = a0 + (a1 - a0) * jitter;
          const r = letter === "B" ? (rMid + rOuter) / 2 + ((idx % 3) - 1) * 6
                                   : (rInner + rMid) / 2 + ((idx % 3) - 1) * 5;
          const x = cx + Math.cos(amid) * r;
          const y = cy + Math.sin(amid) * r;
          const sel = p.id === selectedId;
          const col = p.match === "perfect" || p.match === "harmonic" ? "var(--good)"
                   : p.match === "clash" ? "var(--bad)" : "var(--mid)";
          return (
            <g key={p.id} style={{ cursor: "pointer" }} onClick={() => onSelect(p.id)}>
              <circle cx={x} cy={y} r={sel ? 7 : 4.5}
                fill={col} stroke={sel ? "var(--ink)" : "var(--panel)"} strokeWidth={sel ? 2 : 1}/>
              {sel && (
                <text x={x} y={y - 10} textAnchor="middle"
                  fontFamily="var(--display)" fontSize="11" fontWeight="600" fill="var(--ink)">
                  {p.name.split(" ").slice(-1)[0]}
                </text>
              )}
            </g>
          );
        })}
      </svg>
    </div>
  );
}

function AxisRow({ axis, score, band, reasoning }) {
  const color = band === "good" ? "var(--good)" : band === "mid" ? "var(--mid)" : "var(--bad)";
  return (
    <div style={{
      padding: 12,
      border: "1px solid var(--rule)",
      borderLeft: "3px solid " + color,
      background: "var(--panel-2)",
    }}>
      <div style={{ display: "grid", gridTemplateColumns: "1fr auto", gap: 10, alignItems: "center", marginBottom: 6 }}>
        <div className="mono" style={{ fontSize: 10, color: "var(--ink-muted)", letterSpacing: "0.14em", textTransform: "uppercase" }}>
          {axis}
        </div>
        <div className="display tnum" style={{ fontSize: 20, fontWeight: 700, color }}>{score}</div>
      </div>
      <div style={{ fontSize: 12.5, lineHeight: 1.5, color: "var(--ink-dim)" }}>{reasoning}</div>
    </div>
  );
}

function MatchPill({ match }) {
  const map = {
    perfect:  { l: "PERFECT",  c: "var(--good)" },
    harmonic: { l: "HARMONIC", c: "var(--good)" },
    neutral:  { l: "NEUTRAL",  c: "var(--mid)"  },
    clash:    { l: "CLASH",    c: "var(--bad)"  },
  };
  const m = map[match] || map.neutral;
  return (
    <span className="mono" style={{
      padding: "2px 6px", fontSize: 9.5, fontWeight: 700, letterSpacing: "0.1em",
      color: m.c, border: "1px solid " + m.c,
    }}>{m.l}</span>
  );
}

function Verdict({ match, player, profile }) {
  const msg = {
    perfect:  `Perfect key match. ${player.name} fits ${profile.name} the way an 8A mixes into an 8B — pull the trigger.`,
    harmonic: `Adjacent key. ${player.name} blends harmonically into ${profile.name}. Low integration risk, high upside.`,
    neutral:  `Two keys away. ${player.name} can work for ${profile.name} but expect one season of adaptation.`,
    clash:    `Off-key. ${player.name} and ${profile.name} are far apart on the wheel — force-fitting invites a transition that doesn't land.`,
  };
  return msg[match] || msg.neutral;
}

function Legend({ color, label, filled }) {
  return (
    <div style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 11, color: "var(--ink-dim)" }}>
      <span style={{ width: 10, height: 10, background: filled ? color : "transparent",
        border: "2px solid " + color, borderRadius: "50%" }}/>
      {label}
    </div>
  );
}

Object.assign(window, { CamelotScreen });
