// Shadow Team — pitch layout + 11 slots with CURRENT vs TARGET picks + notes.
// Core USP feature from the Upcoming Features doc.

function ShadowTeam({ profile, onOpenPlayer, onNav }) {
  const D = window.IAMS_DATA;
  const { SHADOW_SLOTS, SHADOW_SUGGESTIONS, findPlayer, TARGETS, camelotFor, profileCamelotKey, camelotMatch } = D;

  // Shadow-team state: slotId → targetId (user's pick)
  const [picks, setPicks] = useState(() => {
    try {
      const v = JSON.parse(localStorage.getItem("ias.shadow") || "null");
      if (v) return v;
    } catch {}
    // Pre-fill with first suggestion per slot
    const seed = {};
    Object.entries(SHADOW_SUGGESTIONS).forEach(([slot, ids]) => { seed[slot] = ids[0] || null; });
    return seed;
  });
  useEffect(() => { localStorage.setItem("ias.shadow", JSON.stringify(picks)); }, [picks]);

  const [notes, setNotes] = useState(() => {
    try { return JSON.parse(localStorage.getItem("ias.shadowNotes") || "{}"); }
    catch { return {}; }
  });
  useEffect(() => { localStorage.setItem("ias.shadowNotes", JSON.stringify(notes)); }, [notes]);

  const [activeSlot, setActiveSlot] = useState("CF");
  const [dragPlayerId, setDragPlayerId] = useState(null);

  // Derive stats
  const slotsWithTargets = SHADOW_SLOTS.filter(s => picks[s.slot]);
  const totalCost = slotsWithTargets.reduce((s, slot) => s + (findPlayer(picks[slot.slot])?.mv || 0), 0);
  const avgAge = slotsWithTargets.length
    ? (slotsWithTargets.reduce((s, slot) => s + (findPlayer(picks[slot.slot])?.age || 0), 0) / slotsWithTargets.length).toFixed(1)
    : "—";
  const avgIams = slotsWithTargets.length
    ? Math.round(slotsWithTargets.reduce((s, slot) => s + (findPlayer(picks[slot.slot])?.iams || 0), 0) / slotsWithTargets.length)
    : "—";
  const coverage = Math.round((slotsWithTargets.length / SHADOW_SLOTS.length) * 100);

  const slot = SHADOW_SLOTS.find(s => s.slot === activeSlot);
  const currentPlayer = slot?.currentId ? findPlayer(slot.currentId) : null;
  const targetId = picks[activeSlot];
  const targetPlayer = targetId ? findPlayer(targetId) : null;

  const profileKey = profileCamelotKey(profile);

  // Position family for the filter
  const posFamily = {
    GK: ["GK"], LB: ["FB"], RB: ["FB"], LCB: ["CB"], RCB: ["CB"],
    DM: ["DM"], LCM: ["CM","AM"], RCM: ["CM","AM"],
    LW: ["W","AM"], RW: ["W","AM"], CF: ["CF","AM"],
  };
  const pool = TARGETS.filter(p => (posFamily[activeSlot] || []).includes(p.pos));

  const setPick = (slotId, playerId) => setPicks(prev => ({ ...prev, [slotId]: playerId }));

  return (
    <div style={{ padding: "28px 40px 60px", maxWidth: 1440, margin: "0 auto", width: "100%" }}
      data-screen-label="08 Shadow Team">
      {/* Header */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr auto", gap: 20, alignItems: "end", marginBottom: 20 }}>
        <div>
          <div className="mono" style={{ fontSize: 11, color: "var(--accent)", letterSpacing: "0.14em", textTransform: "uppercase", marginBottom: 8 }}>
            Shadow Team · Pitch to the Board
          </div>
          <h1 className="display" style={{
            fontSize: "clamp(28px, 3.6vw, 44px)", fontWeight: 600, letterSpacing: "-0.025em",
            lineHeight: 1.02, margin: 0,
          }}>
            Your ideal <span className="underline-accent">XI</span> for {profile.name}.
          </h1>
          <p style={{ marginTop: 10, fontSize: 15, color: "var(--ink-dim)", maxWidth: 680, textWrap: "pretty" }}>
            Build your top-11 across every position using the 400,000-player database. Add notes to each pick, compare
            cost and age structure, then export a board-ready pitch.
          </p>
        </div>
        <div style={{ display: "flex", gap: 10 }}>
          <button className="btn ghost sm">Share link</button>
          <button className="btn accent sm">Pitch to Board →</button>
        </div>
      </div>

      {/* Readouts strip */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12, marginBottom: 20 }}>
        <ReadOut label="Coverage" value={coverage + "%"} sub={`${slotsWithTargets.length} of 11 slots filled`}/>
        <ReadOut label="Budget spend" value={"€" + totalCost.toFixed(0) + "M"} sub={`Band: ${profile.budget}`}/>
        <ReadOut label="Avg age" value={avgAge} sub="years"/>
        <ReadOut label="Avg IAMS" value={avgIams} sub="/200" accent/>
      </div>

      {/* 3-col main: pool | pitch | slot detail */}
      <div style={{ display: "grid", gridTemplateColumns: "260px 1fr 380px", gap: 16 }}>
        {/* Target pool (left) */}
        <div className="card" style={{ padding: 16, maxHeight: 760, overflowY: "auto" }}>
          <div className="mono" style={{ fontSize: 10, color: "var(--ink-muted)", letterSpacing: "0.14em", textTransform: "uppercase", marginBottom: 6 }}>
            Target pool · {activeSlot}
          </div>
          <div style={{ fontSize: 12, color: "var(--ink-muted)", marginBottom: 10 }}>
            Drag onto slot, or click to assign.
          </div>
          <div style={{ display: "grid", gap: 6 }}>
            {pool.map(p => (
              <div key={p.id}
                draggable
                onDragStart={() => setDragPlayerId(p.id)}
                onDragEnd={() => setDragPlayerId(null)}
                onClick={() => setPick(activeSlot, p.id)}
                style={{
                  padding: "8px 10px",
                  border: "1px solid " + (picks[activeSlot] === p.id ? "var(--accent)" : "var(--rule)"),
                  background: picks[activeSlot] === p.id ? "var(--accent-soft)" : "var(--panel-2)",
                  cursor: "grab",
                  display: "grid", gridTemplateColumns: "1fr auto", gap: 8, alignItems: "center",
                }}>
                <div>
                  <div style={{ fontSize: 12.5, fontWeight: 600 }}>{p.name}</div>
                  <div className="mono" style={{ fontSize: 10, color: "var(--ink-muted)", marginTop: 2 }}>
                    {p.pos} · {p.age} · {p.club}
                  </div>
                </div>
                <div style={{ textAlign: "right" }}>
                  <div className="mono tnum" style={{ fontSize: 11, fontWeight: 700, color: fitColor(p.iams/2) }}>
                    {p.iams}
                  </div>
                  <div className="mono" style={{ fontSize: 9, color: "var(--ink-muted)" }}>
                    €{p.mv}M
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Pitch (center) */}
        <div className="card" style={{ padding: 0, overflow: "hidden", position: "relative", minHeight: 700 }}>
          <Pitch slots={SHADOW_SLOTS} picks={picks} activeSlot={activeSlot}
            onSlotClick={setActiveSlot}
            onDropTo={(slotId) => { if (dragPlayerId) setPick(slotId, dragPlayerId); }}
            findPlayer={findPlayer}
          />
        </div>

        {/* Slot detail (right) */}
        <div className="card" style={{ padding: 20, maxHeight: 760, overflowY: "auto" }}>
          <div className="mono" style={{ fontSize: 10, color: "var(--ink-muted)", letterSpacing: "0.14em", textTransform: "uppercase", marginBottom: 10 }}>
            Slot · {activeSlot}
          </div>

          {/* CURRENT */}
          <div>
            <div className="mono" style={{ fontSize: 10, color: "var(--ink-muted)", letterSpacing: "0.1em", textTransform: "uppercase", marginBottom: 6 }}>
              Current starter
            </div>
            {currentPlayer ? (
              <PlayerChip player={currentPlayer} subtle onOpen={() => onOpenPlayer(currentPlayer.id)}/>
            ) : (
              <div style={{ fontSize: 12, color: "var(--ink-muted)", padding: 10, border: "1px dashed var(--rule-strong)" }}>
                No current first-choice · open slot
              </div>
            )}
          </div>

          {/* ARROW */}
          <div style={{ textAlign: "center", margin: "12px 0", color: "var(--accent)", fontSize: 16 }}>↓</div>

          {/* TARGET */}
          <div>
            <div className="mono" style={{ fontSize: 10, color: "var(--accent)", letterSpacing: "0.1em", textTransform: "uppercase", marginBottom: 6 }}>
              Shadow pick
            </div>
            {targetPlayer ? (
              <PlayerChip player={targetPlayer} accent onOpen={() => onOpenPlayer(targetPlayer.id)} profile={profile}/>
            ) : (
              <div style={{ fontSize: 12, color: "var(--ink-muted)", padding: 10, border: "1px dashed var(--accent)" }}>
                Pick from target pool →
              </div>
            )}
          </div>

          {/* DELTA */}
          {currentPlayer && targetPlayer && (
            <div style={{ marginTop: 14, padding: 12, background: "var(--panel-2)", border: "1px solid var(--rule)" }}>
              <div className="mono" style={{ fontSize: 10, color: "var(--ink-muted)", letterSpacing: "0.1em", textTransform: "uppercase", marginBottom: 8 }}>
                Delta
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8 }}>
                <Delta label="Age" from={currentPlayer.age} to={targetPlayer.age} lowerIsBetter/>
                <Delta label="IAMS" from={currentPlayer.iams} to={targetPlayer.iams}/>
                <Delta label="€M" from={currentPlayer.mv} to={targetPlayer.mv}/>
              </div>
            </div>
          )}

          {/* Notes */}
          <div style={{ marginTop: 14 }}>
            <div className="mono" style={{ fontSize: 10, color: "var(--ink-muted)", letterSpacing: "0.1em", textTransform: "uppercase", marginBottom: 6 }}>
              Scout note
            </div>
            <textarea
              value={notes[activeSlot] || ""}
              onChange={e => setNotes(prev => ({ ...prev, [activeSlot]: e.target.value }))}
              placeholder={`Why this player for ${activeSlot}? Role, Camelot, budget rationale...`}
              style={{
                width: "100%", minHeight: 90,
                padding: 10, background: "var(--panel)",
                border: "1px solid var(--rule-strong)", color: "var(--ink)",
                fontSize: 12, lineHeight: 1.5, fontFamily: "var(--body)",
                outline: "none", resize: "vertical",
              }}/>
          </div>
        </div>
      </div>
    </div>
  );
}

// Pitch SVG — 4-3-3 with circular slot markers
function Pitch({ slots, picks, activeSlot, onSlotClick, onDropTo, findPlayer }) {
  // Coord system: 0-100 x, 0-100 y (0 = top = opp goal)
  return (
    <svg viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet" style={{
      display: "block", width: "100%", height: "100%",
      background: "linear-gradient(180deg, var(--accent-soft), transparent 70%), var(--panel-2)",
    }}>
      {/* pitch grass stripes */}
      {Array.from({ length: 8 }).map((_, i) => (
        <rect key={i} x="0" y={i * 12.5} width="100" height="12.5"
          fill={i % 2 === 0 ? "rgba(26,122,54,0.06)" : "rgba(26,122,54,0.12)"}/>
      ))}
      {/* touchlines */}
      <rect x="3" y="3" width="94" height="94" fill="none" stroke="var(--rule-strong)" strokeWidth="0.3"/>
      {/* halfway */}
      <line x1="3" y1="50" x2="97" y2="50" stroke="var(--rule-strong)" strokeWidth="0.3"/>
      <circle cx="50" cy="50" r="8" fill="none" stroke="var(--rule-strong)" strokeWidth="0.3"/>
      {/* boxes */}
      <rect x="25" y="3" width="50" height="14" fill="none" stroke="var(--rule-strong)" strokeWidth="0.3"/>
      <rect x="25" y="83" width="50" height="14" fill="none" stroke="var(--rule-strong)" strokeWidth="0.3"/>
      {/* 6-yd */}
      <rect x="38" y="3" width="24" height="5" fill="none" stroke="var(--rule-strong)" strokeWidth="0.3"/>
      <rect x="38" y="92" width="24" height="5" fill="none" stroke="var(--rule-strong)" strokeWidth="0.3"/>

      {/* slots */}
      {slots.map(slot => {
        const isActive = slot.slot === activeSlot;
        const targetId = picks[slot.slot];
        const target = targetId ? findPlayer(targetId) : null;
        const filled = !!target;
        return (
          <g key={slot.slot}
            transform={`translate(${slot.x}, ${slot.y})`}
            style={{ cursor: "pointer" }}
            onClick={() => onSlotClick(slot.slot)}>
            {/* drop target — invisible larger hitbox */}
            <circle r="8" fill="transparent"
              onDragOver={e => e.preventDefault()}
              onDrop={() => onDropTo(slot.slot)}/>
            {/* ring */}
            <circle r="5.2" fill="var(--panel)"
              stroke={isActive ? "var(--accent)" : filled ? "var(--accent-2)" : "var(--rule-strong)"}
              strokeWidth={isActive ? "0.9" : "0.5"}/>
            <circle r="4.2" fill={filled ? "var(--accent-soft)" : "transparent"}/>
            {/* slot label */}
            <text y="0.7" textAnchor="middle"
              fontFamily="var(--mono)" fontSize="2.2" fontWeight="700"
              fill={filled ? "var(--accent)" : "var(--ink-dim)"}>
              {slot.label}
            </text>
            {/* player name below */}
            {target && (
              <text y="8" textAnchor="middle"
                fontFamily="var(--display)" fontSize="2.2" fontWeight="600"
                fill="var(--ink)" style={{ pointerEvents: "none" }}>
                {target.name.split(" ").slice(-1)[0]}
              </text>
            )}
            {target && (
              <text y="11" textAnchor="middle"
                fontFamily="var(--mono)" fontSize="1.7"
                fill="var(--ink-muted)" style={{ pointerEvents: "none" }}>
                {target.iams} · €{target.mv}M
              </text>
            )}
          </g>
        );
      })}
    </svg>
  );
}

function ReadOut({ label, value, sub, accent }) {
  return (
    <div className="card" style={{ padding: 14 }}>
      <div className="mono" style={{ fontSize: 10, color: "var(--ink-muted)", letterSpacing: "0.14em", textTransform: "uppercase" }}>{label}</div>
      <div style={{ display: "flex", alignItems: "baseline", gap: 6, marginTop: 6 }}>
        <div className="display tnum" style={{ fontSize: 26, fontWeight: 600, letterSpacing: "-0.02em", color: accent ? "var(--accent)" : "var(--ink)" }}>{value}</div>
        <div className="mono" style={{ fontSize: 11, color: "var(--ink-muted)" }}>{sub}</div>
      </div>
    </div>
  );
}

function PlayerChip({ player, accent, subtle, onOpen, profile }) {
  return (
    <div style={{
      padding: 10,
      border: "1px solid " + (accent ? "var(--accent)" : "var(--rule)"),
      background: accent ? "var(--accent-soft)" : "var(--panel-2)",
      display: "grid", gridTemplateColumns: "1fr auto", gap: 6, alignItems: "center",
    }}>
      <div>
        <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
          <button onClick={onOpen} style={{ fontSize: 13.5, fontWeight: 600, textAlign: "left" }}>
            {player.name}
          </button>
          {player.camelotKey && (
            <span className="mono" style={{ fontSize: 10, fontWeight: 700, color: "var(--accent)" }}>
              {player.camelotKey.code}
            </span>
          )}
        </div>
        <div className="mono" style={{ fontSize: 10.5, color: "var(--ink-muted)", marginTop: 2 }}>
          {player.pos} · {player.age} · {player.club}
        </div>
      </div>
      <div style={{ textAlign: "right" }}>
        <div className="display tnum" style={{ fontSize: 18, fontWeight: 600, color: accent ? "var(--accent)" : "var(--ink)" }}>{player.iams}</div>
        <div className="mono" style={{ fontSize: 10, color: "var(--ink-muted)" }}>€{player.mv}M</div>
      </div>
    </div>
  );
}

function Delta({ label, from, to, lowerIsBetter = false }) {
  const d = to - from;
  const positive = lowerIsBetter ? d < 0 : d > 0;
  const neutral = d === 0;
  const color = neutral ? "var(--ink-muted)" : positive ? "var(--good)" : "var(--bad)";
  return (
    <div>
      <div className="mono" style={{ fontSize: 9, color: "var(--ink-muted)", letterSpacing: "0.1em", textTransform: "uppercase" }}>{label}</div>
      <div className="mono tnum" style={{ fontSize: 11, color: "var(--ink-dim)", marginTop: 3 }}>{from} → {to}</div>
      <div className="mono tnum" style={{ fontSize: 13, fontWeight: 700, color, marginTop: 2 }}>
        {d > 0 ? "+" : ""}{typeof d === "number" ? d.toFixed ? d.toFixed(1) : d : d}
      </div>
    </div>
  );
}

Object.assign(window, { ShadowTeam });
