// Original shield-silhouette card with empty photo placeholder
const PlayerCard = ({ p, team = 'mens' }) => {
  const [flipped, setFlipped] = React.useState(false);
  const stats = p.stats || { BNT: 70, BRW: 70, PIE: 70, KIT: 70, CHT: 70, GRF: 70 };

  // Card shield path — original "tapered tablet with curved shoulders" silhouette
  const cardShape = "M 30 0 L 270 0 Q 295 0 296 25 L 290 380 Q 285 410 250 412 L 50 412 Q 15 410 10 380 L 4 25 Q 5 0 30 0 Z";

  return (
    <div data-player-card onClick={() => setFlipped(f => !f)} style={{
      perspective: 1400, cursor: 'pointer', height: 480, position: 'relative',
    }}>
      <div style={{
        position: 'relative', width: '100%', height: '100%',
        transition: 'transform 700ms cubic-bezier(0.4, 0, 0.2, 1)',
        transformStyle: 'preserve-3d',
        transform: flipped ? 'rotateY(180deg)' : 'rotateY(0deg)',
      }}>
        {/* FRONT */}
        <div style={{
          position: 'absolute', inset: 0, backfaceVisibility: 'hidden',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg viewBox="0 0 300 420" style={{ width: '100%', height: '100%', filter: 'drop-shadow(0 18px 30px rgba(0,0,0,0.35))' }}>
            <defs>
              <linearGradient id={`card-${p.no}-${team}`} x1="0" y1="0" x2="1" y2="1">
                <stop offset="0%" stopColor="#E1142E" />
                <stop offset="35%" stopColor="#C8102E" />
                <stop offset="65%" stopColor="#7A0815" />
                <stop offset="100%" stopColor="#3D0309" />
              </linearGradient>
              <radialGradient id={`spot-${p.no}-${team}`} cx="50%" cy="35%" r="65%">
                <stop offset="0%" stopColor="#F23A4F" stopOpacity="0.55" />
                <stop offset="60%" stopColor="#C8102E" stopOpacity="0" />
              </radialGradient>
              <linearGradient id={`sheen-${p.no}-${team}`} x1="0" y1="0" x2="1" y2="1">
                <stop offset="0%" stopColor="rgba(255,255,255,0.18)" />
                <stop offset="50%" stopColor="rgba(255,255,255,0)" />
              </linearGradient>
              <pattern id={`stripes-${p.no}-${team}`} width="14" height="14" patternUnits="userSpaceOnUse" patternTransform="rotate(35)">
                <rect width="14" height="14" fill="transparent" />
                <line x1="0" y1="0" x2="0" y2="14" stroke="#fff" strokeWidth="0.6" opacity="0.08" />
                <line x1="7" y1="0" x2="7" y2="14" stroke="#fff" strokeWidth="0.3" opacity="0.05" />
              </pattern>
              <pattern id={`hex-${p.no}-${team}`} width="22" height="38" patternUnits="userSpaceOnUse">
                <polygon points="11,2 21,8 21,20 11,26 1,20 1,8" fill="none" stroke="#fff" strokeWidth="0.4" opacity="0.07" />
                <polygon points="0,21 11,27 11,39 0,45" fill="none" stroke="#fff" strokeWidth="0.4" opacity="0.07" />
              </pattern>
              <clipPath id={`clip-${p.no}-${team}`}>
                <path d={cardShape} />
              </clipPath>
            </defs>

            {/* Card body — layered: base gradient → spot light → hex pattern → diagonal stripes → sheen */}
            <path d={cardShape} fill={`url(#card-${p.no}-${team})`} />
            <g clipPath={`url(#clip-${p.no}-${team})`}>
              <rect x="0" y="0" width="300" height="420" fill={`url(#spot-${p.no}-${team})`} />
              <rect x="0" y="0" width="300" height="420" fill={`url(#hex-${p.no}-${team})`} />
              <rect x="0" y="0" width="300" height="420" fill={`url(#stripes-${p.no}-${team})`} />
              {/* Stadium-light streaks */}
              <path d="M -20 380 L 320 80" stroke="#fff" strokeWidth="40" opacity="0.04" />
              <path d="M -20 420 L 320 140" stroke="#fff" strokeWidth="20" opacity="0.05" />
            </g>
            <path d={cardShape} fill="none" stroke="#0E0F12" strokeWidth="3" />
            <path d={cardShape} fill={`url(#sheen-${p.no}-${team})`} opacity="0.5" />

            {/* Top-left rating block */}
            <text x="36" y="58" fontFamily="Bebas Neue, Impact" fontSize="48" fill="#fff" letterSpacing="-0.5">
              {p.rating}
            </text>
            <text x="36" y="84" fontFamily="Bebas Neue, Impact" fontSize="22" fill="#fff" letterSpacing="0.5">
              {p.pos}
            </text>

            {/* British flag */}
            <g transform="translate(28, 96)">
              <rect width="40" height="24" fill="#012169" />
              <path d="M 0 0 L 40 24 M 40 0 L 0 24" stroke="#fff" strokeWidth="4.5" />
              <path d="M 0 0 L 40 24 M 40 0 L 0 24" stroke="#C8102E" strokeWidth="1.8" />
              <path d="M 20 0 L 20 24 M 0 12 L 40 12" stroke="#fff" strokeWidth="6.5" />
              <path d="M 20 0 L 20 24 M 0 12 L 40 12" stroke="#C8102E" strokeWidth="3.5" />
              <rect width="40" height="24" fill="none" stroke="#0E0F12" strokeWidth="0.8" />
            </g>

            {/* Club logo */}
            <g transform="translate(28, 132)">
              <foreignObject x="0" y="0" width="44" height="44">
                <div xmlns="http://www.w3.org/1999/xhtml" style={{
                  width: 44, height: 44, borderRadius: '50%', overflow: 'hidden',
                  background: '#fff', border: '1.5px solid #fff',
                  boxShadow: '0 2px 6px rgba(0,0,0,0.4)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  <img src="assets/logo.jpg" alt="Wren Rovers" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                </div>
              </foreignObject>
            </g>

            {/* Player portrait window — empty placeholder */}
            <g clipPath={`url(#clip-${p.no}-${team})`}>
              <foreignObject x="80" y="20" width="220" height="260">
                <div xmlns="http://www.w3.org/1999/xhtml" style={{ width: 220, height: 260, overflow: 'hidden' }}>
                  <PlayerPortrait player={p} team={team} size={220} />
                </div>
              </foreignObject>
            </g>

            {/* Divider */}
            <line x1="36" y1="290" x2="264" y2="290" stroke="#fff" strokeWidth="1" opacity="0.6" />

            {/* Player name */}
            <text x="150" y="316" fontFamily="Bebas Neue, Impact" fontSize="30" fill="#fff" textAnchor="middle" letterSpacing="1.5">
              {p.name.split(' ').slice(-1)[0].toUpperCase()}
            </text>

            <line x1="36" y1="328" x2="264" y2="328" stroke="#fff" strokeWidth="1" opacity="0.4" />

            {/* 6-stat block */}
            <g transform="translate(50, 348)">
              {[
                { k: 'BNT', v: stats.BNT, x: 0, y: 0 },
                { k: 'BRW', v: stats.BRW, x: 0, y: 22 },
                { k: 'PIE', v: stats.PIE, x: 0, y: 44 },
                { k: 'KIT', v: stats.KIT, x: 110, y: 0 },
                { k: 'CHT', v: stats.CHT, x: 110, y: 22 },
                { k: 'GRF', v: stats.GRF, x: 110, y: 44 },
              ].map(s => (
                <g key={s.k} transform={`translate(${s.x}, ${s.y})`}>
                  <text x="0" y="0" fontFamily="Bebas Neue, Impact" fontSize="20" fill="#fff" letterSpacing="0.5">{s.v}</text>
                  <text x="36" y="0" fontFamily="Bebas Neue, Impact" fontSize="20" fill="#fff" letterSpacing="1" opacity="0.85">{s.k}</text>
                </g>
              ))}
              <line x1="100" y1="-14" x2="100" y2="50" stroke="#fff" strokeWidth="0.8" opacity="0.5" />
            </g>

            {/* Bottom corner — shirt number */}
            <text x="270" y="60" fontFamily="Bebas Neue, Impact" fontSize="28" fill="#fff" textAnchor="end" opacity="0.85">
              #{p.no}
            </text>
          </svg>

          <div className="mono" style={{
            position: 'absolute', bottom: 6, right: 14, fontSize: 8.5,
            letterSpacing: '0.22em', color: 'rgba(255,255,255,0.55)', pointerEvents: 'none',
          }}>TAP →</div>
        </div>

        {/* BACK */}
        <div style={{
          position: 'absolute', inset: 0, backfaceVisibility: 'hidden',
          background: 'var(--ink)', color: '#fff',
          transform: 'rotateY(180deg)',
          padding: '24px 24px',
          display: 'flex', flexDirection: 'column',
          border: '2px solid #0E0F12',
          borderRadius: 0,
          boxShadow: '0 18px 30px rgba(0,0,0,0.35)',
          backgroundImage: 'linear-gradient(135deg, #1A0608 0%, #0E0F12 50%, #1A0608 100%)',
        }}>
          <div className="mono" style={{ fontSize: 10, letterSpacing: '0.22em', color: 'var(--red)', fontWeight: 700 }}>
            #{p.no} · {p.pos} · DOSSIER
          </div>
          <div className="display" style={{ fontSize: 28, marginTop: 8, lineHeight: 0.95 }}>{p.name}</div>

          <div style={{ marginTop: 14, paddingTop: 14, borderTop: '1px solid rgba(255,255,255,0.15)', fontSize: 12, lineHeight: 1.6 }}>
            <div style={{ display: 'grid', gridTemplateColumns: '90px 1fr', rowGap: 5 }}>
              <span style={{ color: 'rgba(255,255,255,0.5)' }}>Joined</span><span style={{ fontWeight: 600 }}>{p.joined}</span>
              <span style={{ color: 'rgba(255,255,255,0.5)' }}>From</span><span style={{ fontWeight: 600 }}>{p.from}</span>
              {p.height && (<><span style={{ color: 'rgba(255,255,255,0.5)' }}>Height</span><span style={{ fontWeight: 600 }}>{p.height}</span></>)}
              <span style={{ color: 'rgba(255,255,255,0.5)' }}>Apps</span><span style={{ fontWeight: 600 }}>{p.apps} · {p.goals} goals</span>
              <span style={{ color: 'rgba(255,255,255,0.5)' }}>Nationality</span><span style={{ fontWeight: 600 }}>British 🇬🇧</span>
            </div>
          </div>

          <div style={{ marginTop: 14, paddingTop: 14, borderTop: '1px solid rgba(255,255,255,0.15)' }}>
            <div className="mono" style={{ fontSize: 9.5, letterSpacing: '0.2em', color: 'rgba(255,255,255,0.5)', marginBottom: 6 }}>
              FUN FACT
            </div>
            <div style={{ fontSize: 13, lineHeight: 1.55, fontStyle: 'italic' }}>"{p.funFact}"</div>
          </div>

          <div style={{ marginTop: 'auto', paddingTop: 14, borderTop: '1px solid rgba(255,255,255,0.15)' }}>
            <div className="mono" style={{ fontSize: 9.5, letterSpacing: '0.2em', color: 'rgba(255,255,255,0.5)', marginBottom: 8 }}>
              SEASON FORM
            </div>
            {[['Banter', stats.BNT], ['Brew Making', stats.BRW], ['Graft', stats.GRF]].map(([k, v]) => (
              <div key={k} style={{ marginBottom: 6 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10.5, marginBottom: 2 }}>
                  <span className="mono" style={{ letterSpacing: '0.18em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.6)' }}>{k}</span>
                  <span className="mono" style={{ fontWeight: 700 }}>{v}</span>
                </div>
                <div style={{ height: 4, background: 'rgba(255,255,255,0.12)' }}>
                  <div style={{ width: `${v}%`, height: '100%', background: 'var(--red)' }} />
                </div>
              </div>
            ))}
          </div>

          <div className="mono" style={{ fontSize: 9, color: 'rgba(255,255,255,0.4)', textAlign: 'center', marginTop: 12, letterSpacing: '0.2em' }}>
            ◀ TAP TO FLIP BACK
          </div>
        </div>
      </div>
    </div>
  );
};

const SquadGrid = ({ team }) => {
  const squad = team === 'mens' ? MENS_SQUAD : WOMENS_SQUAD;
  const [filter, setFilter] = React.useState('ALL');
  const groups = ['ALL', 'GK', 'DEF', 'MID', 'FWD'];
  const filt = squad.filter(p => {
    if (filter === 'ALL') return true;
    if (filter === 'GK') return p.pos === 'GK';
    if (filter === 'DEF') return ['CB','RB','LB'].includes(p.pos);
    if (filter === 'MID') return ['CDM','CM','CAM'].includes(p.pos);
    if (filter === 'FWD') return ['ST','RW','LW'].includes(p.pos);
  });

  return (
    <section style={{ background: 'var(--paper-2)', padding: '96px 0' }}>
      <div className="container">
        <SectionHead
          kicker={team === 'mens' ? "Men's First Team · Squad" : "Women's First Team · Squad"}
          title={team === 'mens' ? 'The eleven, the bench, the badge.' : "The Wrens — Women's 1st."}
          right={
            <div data-tab-row style={{ display: 'flex', gap: 0, border: '1.5px solid var(--ink)' }}>
              {groups.map(g => (
                <button key={g} onClick={() => setFilter(g)} style={{
                  padding: '10px 16px', border: 'none', cursor: 'pointer',
                  background: filter === g ? 'var(--ink)' : 'transparent',
                  color: filter === g ? '#fff' : 'var(--ink)',
                  fontSize: 11, fontWeight: 700, letterSpacing: '0.18em',
                }}>{g}</button>
              ))}
            </div>
          }
        />
        <div className="mono" style={{ fontSize: 11, letterSpacing: '0.18em', color: 'var(--muted)', marginBottom: 20, textTransform: 'uppercase' }}>
          ▸ Tap any card to flip · BNT banter · BRW brew making · PIE pies · KIT kit washing · CHT chat · GRF graft
        </div>
        <div data-grid="squad" style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 24 }}>
          {filt.map(p => <PlayerCard key={p.no} p={p} team={team} />)}
        </div>
      </div>
    </section>
  );
};

Object.assign(window, { PlayerCard, SquadGrid });
