// Animated formation — starting XI on a pitch
const FORMATIONS = {
  '4-3-3': [
    { pos: 'GK', x: 50, y: 92, no: 1 },
    { pos: 'LB', x: 12, y: 72, no: 3 }, { pos: 'CB', x: 36, y: 76, no: 4 },
    { pos: 'CB', x: 64, y: 76, no: 5 }, { pos: 'RB', x: 88, y: 72, no: 2 },
    { pos: 'CM', x: 28, y: 52, no: 6 }, { pos: 'CM', x: 50, y: 56, no: 8 }, { pos: 'CM', x: 72, y: 52, no: 10 },
    { pos: 'LW', x: 18, y: 28, no: 11 }, { pos: 'ST', x: 50, y: 22, no: 9 }, { pos: 'RW', x: 82, y: 28, no: 7 },
  ],
  '4-4-2': [
    { pos: 'GK', x: 50, y: 92, no: 1 },
    { pos: 'LB', x: 12, y: 72, no: 3 }, { pos: 'CB', x: 36, y: 76, no: 4 },
    { pos: 'CB', x: 64, y: 76, no: 5 }, { pos: 'RB', x: 88, y: 72, no: 2 },
    { pos: 'LM', x: 14, y: 50, no: 11 }, { pos: 'CM', x: 38, y: 54, no: 6 },
    { pos: 'CM', x: 62, y: 54, no: 8 }, { pos: 'RM', x: 86, y: 50, no: 7 },
    { pos: 'ST', x: 38, y: 22, no: 9 }, { pos: 'ST', x: 62, y: 22, no: 10 },
  ],
  '3-5-2': [
    { pos: 'GK', x: 50, y: 92, no: 1 },
    { pos: 'CB', x: 22, y: 76, no: 4 }, { pos: 'CB', x: 50, y: 80, no: 5 }, { pos: 'CB', x: 78, y: 76, no: 2 },
    { pos: 'LWB', x: 8, y: 56, no: 3 }, { pos: 'CM', x: 32, y: 56, no: 6 },
    { pos: 'CM', x: 50, y: 50, no: 8 }, { pos: 'CM', x: 68, y: 56, no: 10 }, { pos: 'RWB', x: 92, y: 56, no: 11 },
    { pos: 'ST', x: 38, y: 22, no: 9 }, { pos: 'ST', x: 62, y: 22, no: 7 },
  ],
};

// Reusable pitch — keyed by player # so transitions are smooth across formation changes
const FormationPitch = ({ shape = '4-3-3' }) => {
  const positions = FORMATIONS[shape];
  // Build a map: player number → {x, y, pos} for current shape
  const byNo = Object.fromEntries(positions.map(p => [p.no, p]));
  // Stable list of all player numbers across all formations
  const allNumbers = [...new Set(Object.values(FORMATIONS).flat().map(p => p.no))];
  const findPlayer = (no) => MENS_SQUAD.find(p => p.no === no);

  return (
    <div data-pitch style={{
      position: 'relative',
      background: 'linear-gradient(180deg, #1f5e2a 0%, #2a7a3a 50%, #1f5e2a 100%)',
      backgroundImage: 'repeating-linear-gradient(0deg, rgba(0,0,0,0.08) 0 50px, transparent 50px 100px), linear-gradient(180deg, #1f5e2a 0%, #2a7a3a 50%, #1f5e2a 100%)',
      border: '2px solid rgba(255,255,255,0.6)',
      aspectRatio: '0.72', padding: 0, overflow: 'hidden',
    }}>
      <svg viewBox="0 0 100 140" preserveAspectRatio="none" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
        <rect x="2" y="2" width="96" height="136" fill="none" stroke="rgba(255,255,255,0.5)" strokeWidth="0.4" />
        <line x1="2" y1="70" x2="98" y2="70" stroke="rgba(255,255,255,0.5)" strokeWidth="0.4" />
        <circle cx="50" cy="70" r="9" fill="none" stroke="rgba(255,255,255,0.5)" strokeWidth="0.4" />
        <circle cx="50" cy="70" r="0.6" fill="rgba(255,255,255,0.7)" />
        <rect x="22" y="2" width="56" height="14" fill="none" stroke="rgba(255,255,255,0.5)" strokeWidth="0.4" />
        <rect x="36" y="2" width="28" height="6" fill="none" stroke="rgba(255,255,255,0.5)" strokeWidth="0.4" />
        <rect x="22" y="124" width="56" height="14" fill="none" stroke="rgba(255,255,255,0.5)" strokeWidth="0.4" />
        <rect x="36" y="132" width="28" height="6" fill="none" stroke="rgba(255,255,255,0.5)" strokeWidth="0.4" />
      </svg>

      {/* Players — keyed by number so they animate between positions */}
      {allNumbers.map(no => {
        const pp = byNo[no];
        const player = findPlayer(no);
        const initials = player ? player.name.split(' ').map(n => n[0]).slice(0, 2).join('') : '??';
        // Hide if not on current sheet (some formations may not include all)
        const onSheet = !!pp;
        return (
          <div key={no} style={{
            position: 'absolute',
            left: `${onSheet ? pp.x : 50}%`, top: `${onSheet ? pp.y : 110}%`,
            transform: `translate(-50%, -50%) ${onSheet ? 'scale(1)' : 'scale(0.5)'}`,
            opacity: onSheet ? 1 : 0,
            transition: 'left 800ms cubic-bezier(0.4, 0.0, 0.2, 1), top 800ms cubic-bezier(0.4, 0.0, 0.2, 1), transform 800ms cubic-bezier(0.34, 1.56, 0.64, 1), opacity 400ms ease',
            textAlign: 'center', cursor: 'pointer',
            willChange: 'left, top, transform',
          }}>
            <div data-pitch-chip style={{
              width: 78, height: 100, position: 'relative',
              filter: 'drop-shadow(0 6px 14px rgba(0,0,0,0.6))',
            }}>
              <svg viewBox="0 0 78 100" style={{ width: '100%', height: '100%' }}>
                <defs>
                  <linearGradient id={`mini-${no}`} x1="0" y1="0" x2="1" y2="1">
                    <stop offset="0%" stopColor="#E1142E" />
                    <stop offset="60%" stopColor="#9B0B22" />
                    <stop offset="100%" stopColor="#3D0309" />
                  </linearGradient>
                  <clipPath id={`miniclip-${no}`}>
                    <path d="M 8 0 L 70 0 Q 76 0 76 6 L 74 92 Q 72 99 64 99 L 14 99 Q 6 99 4 92 L 2 6 Q 2 0 8 0 Z" />
                  </clipPath>
                </defs>
                <path d="M 8 0 L 70 0 Q 76 0 76 6 L 74 92 Q 72 99 64 99 L 14 99 Q 6 99 4 92 L 2 6 Q 2 0 8 0 Z"
                      fill={`url(#mini-${no})`} stroke="#0E0F12" strokeWidth="2" />
                {player && (
                  <g clipPath={`url(#miniclip-${no})`}>
                    <foreignObject x="14" y="6" width="50" height="60">
                      <div xmlns="http://www.w3.org/1999/xhtml" style={{ width: 50, height: 60, overflow: 'hidden' }}>
                        <PlayerPortrait player={player} team="mens" size={50} />
                      </div>
                    </foreignObject>
                  </g>
                )}
                <text x="10" y="14" fontFamily="Bebas Neue, Impact" fontSize="14" fill="#fff">{no}</text>
                <text x="10" y="26" fontFamily="Bebas Neue, Impact" fontSize="9" fill="#fff" opacity="0.85">{onSheet ? pp.pos : ''}</text>
                <line x1="6" y1="72" x2="72" y2="72" stroke="#fff" strokeWidth="0.6" opacity="0.5" />
                <text x="39" y="84" fontFamily="Bebas Neue, Impact" fontSize="11" fill="#fff" textAnchor="middle" letterSpacing="0.5">
                  {player ? player.name.split(' ').slice(-1)[0].toUpperCase() : initials}
                </text>
              </svg>
            </div>
          </div>
        );
      })}

      {/* Watermark */}
      <div style={{ position: 'absolute', bottom: 12, left: 12, opacity: 0.18 }}>
        <WrenBadge size={64} mono color="#fff" />
      </div>
    </div>
  );
};

const FormationSection = () => {
  const [shape, setShape] = React.useState('4-3-3');

  return (
    <section style={{ background: 'var(--ink)', color: '#fff', padding: '96px 0' }}>
      <div className="container">
        <SectionHead
          dark
          kicker="Starting XI · Predicted"
          title="On the teamsheet."
          right={
            <div data-tab-row style={{ display: 'flex', gap: 0, border: '1.5px solid #fff' }}>
              {Object.keys(FORMATIONS).map(s => (
                <button key={s} onClick={() => setShape(s)} style={{
                  padding: '10px 18px', border: 'none', cursor: 'pointer',
                  background: shape === s ? '#fff' : 'transparent',
                  color: shape === s ? 'var(--ink)' : '#fff',
                  fontFamily: 'Bebas Neue', fontSize: 22,
                }}>{s}</button>
              ))}
            </div>
          }
        />

        <div data-formation style={{ display: 'grid', gridTemplateColumns: '1fr 380px', gap: 32, alignItems: 'flex-start' }}>
          <FormationPitch shape={shape} />

          {/* Side panel — Manager + bench */}
          <div>
            <div style={{ background: 'var(--ink-2)', border: '1px solid var(--ink-3)', padding: '24px 24px' }}>
              <div className="mono" style={{ fontSize: 10, letterSpacing: '0.22em', color: 'var(--red)', fontWeight: 700 }}>
                MANAGER
              </div>
              <div className="display" style={{ fontSize: 30, marginTop: 6 }}>BARRY BRIGGS</div>
              <p style={{ fontSize: 13, color: 'rgba(255,255,255,0.7)', lineHeight: 1.55, margin: '12px 0 0' }}>
                "Same shape, sharper press. We've earned the right to back ourselves at home."
              </p>
            </div>

            <div style={{ background: 'var(--ink-2)', border: '1px solid var(--ink-3)', borderTop: 'none', padding: '20px 24px' }}>
              <div className="mono" style={{ fontSize: 10, letterSpacing: '0.22em', color: 'rgba(255,255,255,0.5)', fontWeight: 700, marginBottom: 12 }}>
                ON THE BENCH
              </div>
              {[12, 13, 14, 15, 16].map((n, i) => {
                const sub = MENS_SQUAD[(i + 4) % MENS_SQUAD.length];
                return (
                  <div key={n} style={{
                    display: 'grid', gridTemplateColumns: '32px 1fr 40px', gap: 12,
                    padding: '8px 0', alignItems: 'center',
                    borderBottom: i < 4 ? '1px solid var(--ink-3)' : 'none',
                  }}>
                    <div className="display" style={{ fontSize: 22, color: 'var(--red)' }}>{n}</div>
                    <div style={{ fontSize: 13, fontWeight: 600 }}>{sub?.name || '—'}</div>
                    <div className="mono" style={{ fontSize: 10, color: 'rgba(255,255,255,0.5)', letterSpacing: '0.16em' }}>{sub?.pos}</div>
                  </div>
                );
              })}
            </div>

            <div style={{ background: 'var(--red)', padding: '20px 24px', marginTop: 0 }}>
              <div className="mono" style={{ fontSize: 10, letterSpacing: '0.22em', color: 'rgba(255,255,255,0.7)', fontWeight: 700 }}>
                MATCH OFFICIAL
              </div>
              <div className="display" style={{ fontSize: 24, marginTop: 4 }}>REF: G. WALMSLEY</div>
              <div className="mono" style={{ fontSize: 10, letterSpacing: '0.18em', marginTop: 6, color: 'rgba(255,255,255,0.85)' }}>
                ATTENDANCE EXPECTED · 280
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

Object.assign(window, { FormationSection, FormationPitch, FORMATIONS });
