// Men's squad. First Team = eye-catching player cards (home-shirt graphic +
// sponsor). Reserves = condensed list. No shirt numbers (by request).

const POS_ORDER = ['GK', 'DEF', 'MID', 'ATT'];
const POS_LABEL = { GK: 'Goalkeepers', DEF: 'Defenders', MID: 'Midfielders', ATT: 'Forwards' };

const surnameOf = (name) => {
  const parts = name.trim().split(' ');
  return parts[parts.length - 1];
};

// Home-shirt graphic with the player's surname across it.
const KitShirt = ({ surname }) => (
  <svg viewBox="0 0 200 196" width="100%" height="100%" style={{ display: 'block' }} aria-hidden="true">
    <defs>
      <linearGradient id="shirtGrad" x1="0" y1="0" x2="0" y2="1">
        <stop offset="0%" stopColor="#E01533" />
        <stop offset="100%" stopColor="#A60C22" />
      </linearGradient>
    </defs>
    {/* body + sleeves */}
    <path d="M70 36 L88 28 Q100 40 112 28 L130 36 L164 56 L150 90 L134 80 L134 178 Q100 184 66 178 L66 80 L50 90 L36 56 Z"
      fill="url(#shirtGrad)" stroke="rgba(0,0,0,0.25)" strokeWidth="1.5" />
    {/* white shoulder flashes (home-kit detail) */}
    <path d="M88 28 L70 36 L78 50 L96 40 Z" fill="#fff" opacity="0.92" />
    <path d="M112 28 L130 36 L122 50 L104 40 Z" fill="#fff" opacity="0.92" />
    {/* V collar */}
    <path d="M88 28 Q100 46 112 28 L107 28 Q100 39 93 28 Z" fill="#fff" />
    {/* cuff trim */}
    <path d="M50 90 L36 56 L41 53 L55 86 Z" fill="#fff" opacity="0.85" />
    <path d="M150 90 L164 56 L159 53 L145 86 Z" fill="#fff" opacity="0.85" />
    {/* surname across the shirt */}
    <text x="100" y="120" textAnchor="middle" fontFamily="Bebas Neue, Anton, Impact, sans-serif"
      fontSize="26" fill="#fff" style={{ letterSpacing: '1px' }}>{surname.toUpperCase()}</text>
  </svg>
);

// Sponsor strip: logo (falls back to company name text if file not present yet).
const CardSponsor = ({ player }) => {
  const [failed, setFailed] = React.useState(false);
  if (!player.sponsor) {
    const surname = surnameOf(player.name).toUpperCase();
    // Send people to the enquiry form with "Sponsor" pre-selected and a
    // description naming this player. App listens for this event.
    const requestSponsor = () =>
      window.dispatchEvent(new CustomEvent('wren:sponsor', { detail: { player: player.name } }));
    return (
      <button
        type="button"
        onClick={requestSponsor}
        title={`Sponsor ${player.name} for £50`}
        style={{
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
          width: '100%', padding: '12px 10px',
          border: 'none', borderTop: '1px solid rgba(255,255,255,0.08)',
          background: 'rgba(200,16,46,0.12)', color: '#fff', fontFamily: 'inherit',
          cursor: 'pointer', transition: 'background 160ms ease',
        }}
        onMouseEnter={(e) => { e.currentTarget.style.background = 'var(--red)'; }}
        onMouseLeave={(e) => { e.currentTarget.style.background = 'rgba(200,16,46,0.12)'; }}
      >
        <span className="mono" style={{ fontSize: 8.5, letterSpacing: '0.14em', fontWeight: 700 }}>
          SPONSOR {surname} · £50
        </span>
        <span aria-hidden="true" style={{ fontSize: 11, lineHeight: 1 }}>→</span>
      </button>
    );
  }
  return (
    <div style={{
      padding: '10px 10px', borderTop: '1px solid rgba(255,255,255,0.08)',
      background: 'rgba(255,255,255,0.04)', textAlign: 'center',
    }}>
      <div className="mono" style={{ fontSize: 7.5, letterSpacing: '0.18em', color: 'var(--red)', fontWeight: 700, marginBottom: 6 }}>
        SPONSORED BY
      </div>
      <div style={{
        background: '#fff', borderRadius: 3, height: 40, display: 'flex',
        alignItems: 'center', justifyContent: 'center', padding: '4px 8px',
      }}>
        {(player.sponsorLogo && !failed) ? (
          <img src={player.sponsorLogo} alt={player.sponsor} onError={() => setFailed(true)}
            style={{ maxWidth: '100%', maxHeight: 32, objectFit: 'contain', display: 'block' }} />
        ) : (
          <div className="display" style={{ fontSize: 13, lineHeight: 1, color: 'var(--ink)', textAlign: 'center' }}>
            {player.sponsor.toUpperCase()}
          </div>
        )}
      </div>
    </div>
  );
};

const PlayerCard = ({ p }) => (
  <div style={{
    background: 'linear-gradient(160deg, #181B21 0%, #0E0F12 100%)',
    border: '1px solid rgba(255,255,255,0.09)', overflow: 'hidden',
    display: 'flex', flexDirection: 'column', transition: 'transform 180ms ease, box-shadow 180ms ease',
  }}
    onMouseEnter={(e) => { e.currentTarget.style.transform = 'translateY(-5px)'; e.currentTarget.style.boxShadow = '0 14px 30px rgba(0,0,0,0.45)'; }}
    onMouseLeave={(e) => { e.currentTarget.style.transform = 'none'; e.currentTarget.style.boxShadow = 'none'; }}
  >
    <div style={{ height: 4, background: 'var(--red)' }} />
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px 12px 0' }}>
      <span className="mono" style={{ fontSize: 9, letterSpacing: '0.16em', color: 'rgba(255,255,255,0.45)' }}>WRENS ’26/27</span>
      <span className="mono" style={{
        fontSize: 9, letterSpacing: '0.12em', color: '#fff', fontWeight: 700,
        background: 'var(--red)', padding: '3px 7px',
      }}>{p.pos}</span>
    </div>
    <div style={{ padding: '6px 18px 0', height: 150 }}>
      <KitShirt surname={surnameOf(p.name)} />
    </div>
    <div style={{ padding: '4px 14px 14px', textAlign: 'center' }}>
      <div style={{ color: 'rgba(255,255,255,0.55)', fontSize: 11, fontWeight: 500 }}>
        {p.name.split(' ').slice(0, -1).join(' ')}
      </div>
      <div className="display" style={{ color: '#fff', fontSize: 26, lineHeight: 1 }}>
        {surnameOf(p.name).toUpperCase()}
      </div>
    </div>
    <div style={{ marginTop: 'auto' }}>
      <CardSponsor player={p} />
    </div>
  </div>
);

const FirstTeamCards = ({ players }) => (
  <div>
    {POS_ORDER.map(pos => {
      const list = players.filter(p => p.pos === pos);
      if (!list.length) return null;
      return (
        <div key={pos} style={{ marginBottom: 28 }}>
          <div className="mono" style={{
            fontSize: 11, letterSpacing: '0.22em', color: 'var(--red)', fontWeight: 700,
            marginBottom: 14, paddingBottom: 8, borderBottom: '1px solid rgba(255,255,255,0.12)',
          }}>{POS_LABEL[pos].toUpperCase()} · {list.length}</div>
          <div data-grid="players" style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16 }}>
            {list.map((p, i) => <PlayerCard key={i} p={p} />)}
          </div>
        </div>
      );
    })}
  </div>
);

// Reserves — condensed list grouped by position.
const ReserveRow = ({ p }) => (
  <div style={{
    display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10,
    background: '#fff', border: '1px solid var(--line-soft)', padding: '11px 14px',
  }}>
    <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink)' }}>
      {p.name}
      {p.sponsor && <span className="mono" style={{ fontSize: 8.5, letterSpacing: '0.12em', color: 'var(--muted)', marginLeft: 8 }}>· {p.sponsor.toUpperCase()}</span>}
    </span>
    <span className="mono" style={{ fontSize: 9, letterSpacing: '0.12em', color: 'var(--red)', fontWeight: 700 }}>{p.pos}</span>
  </div>
);

const ReservesList = ({ players }) => (
  <div data-grid="squad-condensed" style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 24, alignItems: 'start' }}>
    {POS_ORDER.map(pos => {
      const list = players.filter(p => p.pos === pos);
      if (!list.length) return null;
      return (
        <div key={pos}>
          <div className="mono" style={{
            fontSize: 10, letterSpacing: '0.2em', color: 'var(--muted)', fontWeight: 700,
            marginBottom: 10, paddingBottom: 6, borderBottom: '1px solid var(--line-soft)',
          }}>{POS_LABEL[pos].toUpperCase()} · {list.length}</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {list.map((p, i) => <ReserveRow key={i} p={p} />)}
          </div>
        </div>
      );
    })}
  </div>
);

const MensSquad = () => {
  const first = MENS_SQUAD.filter(p => p.squad === 'first');
  const reserves = MENS_SQUAD.filter(p => p.squad === 'reserves');
  return (
    <>
      {/* First Team — dark, bold player cards */}
      <section style={{ background: 'var(--ink)', color: '#fff', padding: '56px 0 64px' }} id="first-team">
        <div className="container">
          <SectionHead dark
            kicker="2026/27 · West Lancs Premier"
            title="The First Team"
            right={
              <p style={{ maxWidth: 360, margin: 0, color: 'rgba(255,255,255,0.6)', fontSize: 14, lineHeight: 1.55 }}>
                {first.length} players in red. Want your business on a card? Hit “Sponsor” on any open player, pay £50 via SumUp, and pop their name in at checkout.
              </p>
            }
          />
          <FirstTeamCards players={first} />
        </div>
      </section>

      {/* Reserves — condensed */}
      <section style={{ background: 'var(--paper)', padding: '64px 0 96px' }} id="reserves">
        <div className="container">
          <SectionHead
            kicker="2026/27 · Reserve Team"
            title="Reserves"
            right={
              <span className="mono" style={{ fontSize: 12, letterSpacing: '0.16em', color: 'var(--muted)' }}>
                {reserves.length} PLAYERS
              </span>
            }
          />
          <ReservesList players={reserves} />
        </div>
      </section>
    </>
  );
};

Object.assign(window, { MensSquad });
