// ============================================================
// screens/SquadBuilder.jsx — pitch formation w/ drag-drop
// ============================================================
const { useState: useState_S, useMemo: useMemo_S } = React;

function SquadBuilder({ collection, squad, setSquad, squadSize, onStartMatch }) {
  const [draggingCardId, setDraggingCardId] = useState_S(null);
  const [hoverSlot, setHoverSlot] = useState_S(null);
  const [filterPos, setFilterPos] = useState_S('ALL');
  const formation = window.FORMATIONS[squadSize];

  // squad is array of cardIds (or null) matched to formation slots
  const slotsFilled = squad.filter(Boolean).length;

  const assignedIds = new Set(squad.filter(Boolean));
  const benchCards = useMemo_S(() => {
    let list = collection
      .filter(id => !assignedIds.has(id))
      .map(id => window.CARDS.find(c => c.id === id))
      .filter(Boolean);
    if (filterPos !== 'ALL') list = list.filter(c => c.pos === filterPos);
    list.sort((a,b) => b.ovr - a.ovr);
    return list;
  }, [collection, squad, filterPos]);

  const placeCard = (slotIdx, cardId) => {
    // If card already in another slot, swap
    const existing = squad.indexOf(cardId);
    const newSquad = [...squad];
    if (existing !== -1) newSquad[existing] = newSquad[slotIdx];
    newSquad[slotIdx] = cardId;
    setSquad(newSquad);
  };

  const removeFromSlot = (slotIdx) => {
    const n = [...squad]; n[slotIdx] = null; setSquad(n);
  };

  // Rating
  const avgOvr = useMemo_S(() => {
    const filled = squad.filter(Boolean).map(id => window.CARDS.find(c=>c.id===id));
    if (!filled.length) return 0;
    return Math.round(filled.reduce((a,c) => a + c.ovr, 0) / filled.length);
  }, [squad]);

  // Dominant type
  const typeSplit = useMemo_S(() => {
    const t = {};
    squad.filter(Boolean).forEach(id => {
      const c = window.CARDS.find(x=>x.id===id);
      t[c.type] = (t[c.type]||0) + 1;
    });
    return t;
  }, [squad]);

  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'minmax(460px, 1fr) 420px', gap: 24, padding: '24px 32px', maxWidth: 1600, margin: '0 auto' }}>
      {/* pitch */}
      <div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 20, marginBottom: 16 }}>
          <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 36, margin: 0, color: '#fff', fontWeight: 600 }}>Squad</h1>
          <span style={{ color: '#6a7380', fontSize: 12, letterSpacing: '0.08em', textTransform: 'uppercase' }}>
            {formation.label} · {slotsFilled}/{squad.length} placed
          </span>
          <div style={{ flex: 1 }} />
          <SquadMeta avgOvr={avgOvr} typeSplit={typeSplit} />
        </div>

        <Pitch
          formation={formation}
          squad={squad}
          draggingCardId={draggingCardId}
          hoverSlot={hoverSlot}
          onHover={setHoverSlot}
          onDrop={(slotIdx) => {
            if (draggingCardId) placeCard(slotIdx, draggingCardId);
            setDraggingCardId(null);
            setHoverSlot(null);
          }}
          onSlotClick={(slotIdx) => {
            if (squad[slotIdx]) removeFromSlot(slotIdx);
          }}
        />

        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 20, alignItems: 'center' }}>
          <div style={{ color: '#6a7380', fontSize: 12 }}>
            Drag cards from your bench onto pitch positions. Click a slot to remove.
          </div>
          <button
            disabled={slotsFilled < squad.length}
            onClick={onStartMatch}
            style={{
              background: slotsFilled < squad.length ? '#1a1f26' : 'linear-gradient(135deg, #ffc43d, #ff9500)',
              color: slotsFilled < squad.length ? '#5a6169' : '#0a0d0e',
              border: 'none',
              padding: '12px 28px',
              borderRadius: 8,
              fontFamily: 'var(--font-display)', fontSize: 17,
              fontWeight: 700, letterSpacing: '0.04em',
              cursor: slotsFilled < squad.length ? 'not-allowed' : 'pointer',
              boxShadow: slotsFilled < squad.length ? 'none' : '0 0 24px rgba(255,196,61,0.4)',
              transition: 'all 0.2s',
            }}
          >Find Match ▸</button>
        </div>
      </div>

      {/* bench */}
      <div>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12,
          borderBottom: '1px solid #1a1f26', paddingBottom: 10,
        }}>
          <div style={{
            fontSize: 11, color: '#8a9099', textTransform: 'uppercase',
            letterSpacing: '0.12em', fontWeight: 700,
          }}>◆ Bench · {benchCards.length}</div>
          <div style={{ flex: 1 }} />
          {['ALL','GK','DEF','MID','FWD'].map(p => (
            <button key={p} onClick={()=>setFilterPos(p)} style={{
              background: filterPos === p ? '#1e2329' : 'transparent',
              color: filterPos === p ? '#fff' : '#6a7380',
              border: '1px solid ' + (filterPos === p ? '#2a3139' : 'transparent'),
              fontSize: 10, padding: '4px 8px', borderRadius: 4, cursor: 'pointer',
              fontWeight: 700, letterSpacing: '0.08em',
            }}>{p}</button>
          ))}
        </div>
        <div style={{
          display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10,
          maxHeight: 'calc(100vh - 180px)', overflowY: 'auto', paddingRight: 6,
        }}>
          {benchCards.map(c => (
            <div
              key={c.id}
              draggable
              onDragStart={() => setDraggingCardId(c.id)}
              onDragEnd={() => { setDraggingCardId(null); setHoverSlot(null); }}
              onDoubleClick={() => {
                // auto-place in first matching empty slot
                const idx = formation.slots.findIndex((s,i) => !squad[i] && (s.pos === c.pos));
                if (idx >= 0) placeCard(idx, c.id);
              }}
              style={{
                opacity: draggingCardId === c.id ? 0.4 : 1,
                cursor: 'grab',
              }}
              title="Drag onto pitch or double-click to auto-place"
            >
              <window.PlayerCard cardId={c.id} size="sm" layout="minimal" />
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function Pitch({ formation, squad, draggingCardId, hoverSlot, onHover, onDrop, onSlotClick }) {
  const draggingCard = draggingCardId ? window.CARDS.find(c=>c.id===draggingCardId) : null;
  return (
    <div style={{
      position: 'relative',
      aspectRatio: '0.72',
      background: `
        repeating-linear-gradient(0deg, #0f1e15 0 60px, #0d1b13 60px 120px),
        linear-gradient(180deg, #0f1e15 0%, #0a140e 100%)
      `,
      borderRadius: 14,
      border: '1.5px solid #1a2820',
      overflow: 'hidden',
      boxShadow: 'inset 0 0 80px rgba(0,0,0,0.4), 0 20px 50px rgba(0,0,0,0.4)',
    }}>
      {/* Pitch lines */}
      <svg viewBox="0 0 100 140" preserveAspectRatio="none" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
        <g fill="none" stroke="rgba(255,255,255,0.12)" strokeWidth="0.3">
          <rect x="3" y="3" width="94" height="134" />
          <line x1="3" y1="70" x2="97" y2="70" />
          <circle cx="50" cy="70" r="9" />
          <circle cx="50" cy="70" r="0.8" fill="rgba(255,255,255,0.2)" />
          <rect x="28" y="3" width="44" height="14" />
          <rect x="38" y="3" width="24" height="6" />
          <rect x="28" y="123" width="44" height="14" />
          <rect x="38" y="131" width="24" height="6" />
        </g>
      </svg>

      {/* slots */}
      {formation.slots.map((slot, i) => {
        const cardId = squad[i];
        const card = cardId ? window.CARDS.find(c => c.id === cardId) : null;
        const isHovered = hoverSlot === i;
        const isValidDrop = draggingCard && draggingCard.pos === slot.pos;
        const isInvalidDrop = draggingCard && draggingCard.pos !== slot.pos;
        return (
          <div
            key={i}
            onDragOver={(e) => { e.preventDefault(); onHover(i); }}
            onDragLeave={() => onHover(null)}
            onDrop={(e) => { e.preventDefault(); onDrop(i); }}
            onClick={() => onSlotClick(i)}
            style={{
              position: 'absolute',
              left: `${slot.x}%`, top: `${slot.y}%`,
              transform: 'translate(-50%,-50%)',
              width: 104, height: 132,
              cursor: card ? 'pointer' : 'default',
            }}
          >
            {card ? (
              <div style={{
                transform: isHovered && draggingCard && draggingCard.id !== card.id ? 'scale(1.06)' : 'scale(1)',
                transition: 'transform 0.15s',
              }}>
                <PitchCard card={card} />
              </div>
            ) : (
              <div style={{
                width: '100%', height: '100%',
                border: `2px dashed ${isHovered ? (isValidDrop ? '#ffc43d' : '#ff5a3c') : 'rgba(255,255,255,0.18)'}`,
                borderRadius: 10,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                flexDirection: 'column',
                background: isHovered && isValidDrop ? 'rgba(255,196,61,0.1)' : 'rgba(255,255,255,0.02)',
                color: isHovered && isValidDrop ? '#ffc43d' : '#6a7380',
                transition: 'all 0.15s',
              }}>
                <div style={{ fontFamily: 'var(--font-display)', fontSize: 28, fontWeight: 600, lineHeight: 1 }}>{slot.pos}</div>
                <div style={{ fontSize: 9, letterSpacing: '0.14em', textTransform: 'uppercase', marginTop: 4, opacity: 0.6 }}>Slot {i+1}</div>
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}

function PitchCard({ card }) {
  const rarity = window.RARITIES[card.rarity];
  const type = window.TYPES[card.type];
  const team = window.TEAMS[card.team];
  return (
    <div style={{
      width: '100%', height: '100%',
      background: `linear-gradient(155deg, ${rarity.border}22 0%, #0a0d0e 50%, #05070a 100%)`,
      border: `1.5px solid ${rarity.border}`,
      borderRadius: 10,
      padding: 6,
      boxShadow: `0 0 16px ${rarity.glow}, 0 4px 12px rgba(0,0,0,0.6)`,
      position: 'relative',
      overflow: 'hidden',
    }}>
      <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 2, background: `linear-gradient(90deg, ${type.color}, ${rarity.color})`}} />
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 26, color: '#fff', lineHeight: 1, fontWeight: 700 }}>{card.ovr}</div>
          <div style={{ fontSize: 8, color: rarity.color, letterSpacing: '0.1em', fontWeight: 700, marginTop: 2 }}>{card.pos}</div>
        </div>
        <div style={{ fontSize: 11, color: type.color, textShadow: `0 0 6px ${type.glow}` }}>●</div>
      </div>
      <div style={{ marginTop: 22, fontFamily: 'var(--font-display)', fontSize: 12, color: '#fff', lineHeight: 1.05, fontWeight: 600 }}>
        {card.name.split(' ').slice(-1)[0]}
      </div>
      <div style={{ fontSize: 7.5, color: team.color, letterSpacing: '0.1em', textTransform: 'uppercase', fontWeight: 600, marginTop: 2 }}>
        {team.short}
      </div>
    </div>
  );
}

function SquadMeta({ avgOvr, typeSplit }) {
  const total = Object.values(typeSplit).reduce((a,b)=>a+b,0);
  return (
    <div style={{ display: 'flex', gap: 18, alignItems: 'center' }}>
      <div>
        <div style={{ fontSize: 9, color: '#5a6169', letterSpacing: '0.12em', textTransform: 'uppercase', fontWeight: 600 }}>Squad OVR</div>
        <div style={{ fontFamily: 'var(--font-display)', fontSize: 26, color: '#fff', lineHeight: 1, fontWeight: 700 }}>{avgOvr || '—'}</div>
      </div>
      <div style={{ display: 'flex', gap: 2, alignItems: 'center', height: 22 }}>
        {Object.entries(window.TYPES).map(([k,t]) => {
          const n = typeSplit[k] || 0;
          return (
            <div key={k} title={`${t.name}: ${n}`} style={{
              width: 16, display: 'flex', flexDirection: 'column', alignItems: 'center',
            }}>
              <div style={{
                fontSize: 9, color: n ? t.color : '#2a3139', fontWeight: 700,
              }}>{n || '·'}</div>
              <div style={{
                width: 6, height: 6, borderRadius: '50%',
                background: n ? t.color : '#1a1f26',
                boxShadow: n ? `0 0 8px ${t.glow}` : 'none',
                marginTop: 2,
              }} />
            </div>
          );
        })}
      </div>
    </div>
  );
}

window.SquadBuilder = SquadBuilder;
