// ═══════════════ JOUEURS PAGE (LIVE) ═══════════════
// Fetches /public/players-full and renders bubbles, modal with socials.

const TIER_SIZE = {
  IRON: 26, BRONZE: 28, SILVER: 30, GOLD: 32,
  PLATINUM: 36, EMERALD: 40, DIAMOND: 44,
  MASTER: 52, GRANDMASTER: 56, CHALLENGER: 60, UNRANKED: 28,
};
const ROLE_TO_LABEL = { TOP: 'TOP', JUNGLE: 'JGL', MIDDLE: 'MID', BOTTOM: 'ADC', UTILITY: 'SUP' };

const JoueursPage = () => {
  const { data, loading } = useApi('/public/players-full', []);
  const [openPlayer, setOpenPlayer] = React.useState(null);
  const [divFilter, setDivFilter] = React.useState('all');
  const [roleFilter, setRoleFilter] = React.useState('all');
  const [statusFilter, setStatusFilter] = React.useState('all');
  const [query, setQuery] = React.useState('');

  const players = Array.isArray(data) ? data : [];
  const filtered = players.filter(p => {
    if (divFilter !== 'all' && p.division !== divFilter) return false;
    if (roleFilter !== 'all') {
      const r = ROLE_TO_LABEL[p.role_principal] || p.position_principale;
      if (r !== roleFilter) return false;
    }
    if (statusFilter === 'libre' && p.status !== 'Libre') return false;
    if (statusFilter === 'signe' && p.status === 'Libre') return false;
    if (query) {
      const s = query.toLowerCase();
      if (!(p.discord_tag || '').toLowerCase().includes(s) &&
          !(p.discord_nick || '').toLowerCase().includes(s) &&
          !(p.riot_id || '').toLowerCase().includes(s)) return false;
    }
    return true;
  });
  const bubbles = positionBubbles(filtered);

  return (
    <div className="page-frame grain" data-screen-label="Joueurs" style={{ position: 'relative' }}>
      <CZFHeader active="joueurs" />
      <main style={{ padding: '2.5rem 2.5rem 3rem', position: 'relative' }}>
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: '1.5rem' }}>
          <div>
            <div className="eyebrow" style={{ marginBottom: '.6rem' }}>Roster · saison en cours</div>
            <h1 className="display" style={{ fontSize: '3.2rem' }}>
              JOUEURS <span style={{ color: 'var(--muted-2)' }}>· {players.length}</span>
            </h1>
          </div>
        </div>

        <div style={{
          display: 'flex', gap: '.4rem', alignItems: 'center', flexWrap: 'wrap',
          padding: '.65rem .85rem', background: 'var(--char)',
          border: '1px solid var(--border)', borderRadius: 3, marginBottom: '1.5rem',
        }}>
          <span style={{ fontFamily: 'var(--fc)', fontSize: '.62rem', fontWeight: 700, letterSpacing: '.15em', textTransform: 'uppercase', color: 'var(--muted)', marginRight: '.5rem' }}>Division</span>
          <Btn on={divFilter === 'all'} onClick={() => setDivFilter('all')}>Toutes</Btn>
          {['Yordle','Ixtal','Targon'].map(d => <Btn key={d} on={divFilter === d} onClick={() => setDivFilter(d)}>{d}</Btn>)}
          <Sep />
          <span style={{ fontFamily: 'var(--fc)', fontSize: '.62rem', fontWeight: 700, letterSpacing: '.15em', textTransform: 'uppercase', color: 'var(--muted)', marginRight: '.5rem' }}>Rôle</span>
          <Btn on={roleFilter === 'all'} onClick={() => setRoleFilter('all')}>Tous</Btn>
          {['TOP','JGL','MID','ADC','SUP'].map(r => <Btn key={r} on={roleFilter === r} onClick={() => setRoleFilter(r)}>{r}</Btn>)}
          <Sep />
          <Btn on={statusFilter === 'libre'} onClick={() => setStatusFilter(statusFilter === 'libre' ? 'all' : 'libre')}>Libres</Btn>
          <Btn on={statusFilter === 'signe'} onClick={() => setStatusFilter(statusFilter === 'signe' ? 'all' : 'signe')}>Signés</Btn>
          <div style={{ marginLeft: 'auto', position: 'relative' }}>
            <input value={query} onChange={e => setQuery(e.target.value)} placeholder="Rechercher un joueur…" style={{
              fontFamily: 'var(--fc)', fontSize: '.78rem', fontWeight: 600,
              background: 'var(--red)', border: '1px solid var(--red)', color: '#fff',
              padding: '.4rem .9rem .4rem 2rem', borderRadius: 3, outline: 'none', width: 220, letterSpacing: '.04em',
            }} className="red-search-input" />
            <style>{`.red-search-input::placeholder{color:rgba(255,255,255,.92);font-weight:600;}`}</style>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.5" style={{ position: 'absolute', left: 8, top: '50%', transform: 'translateY(-50%)' }}>
              <circle cx="11" cy="11" r="7" /><line x1="21" y1="21" x2="16.5" y2="16.5" />
            </svg>
          </div>
        </div>

        <div style={{ position: 'relative' }}>
          {loading
            ? <Loading />
            : bubbles.length === 0
              ? <Empty title="AUCUN JOUEUR" sub="Personne ne s'est encore inscrit avec les filtres actuels. Utilise la commande /inscrire sur Discord pour rejoindre le tournoi." />
              : <BubbleCanvas bubbles={bubbles} onSelect={setOpenPlayer} />}
          {openPlayer && <PlayerModal player={openPlayer} onClose={() => setOpenPlayer(null)} />}
        </div>
      </main>
    </div>
  );
};

const Btn = ({ on, onClick, children }) => (
  <button onClick={onClick} className={`filter-btn ${on ? 'on' : ''}`}>{children}</button>
);
const Sep = () => <span style={{ width: 1, height: 16, background: 'var(--border-2)', margin: '0 .25rem' }} />;

const BubbleCanvas = ({ bubbles, onSelect }) => (
  <div style={{
    position: 'relative', width: '100%', height: 540,
    background: 'linear-gradient(180deg, var(--char), var(--ink-2))',
    border: '1px solid var(--border)', borderRadius: 4, overflow: 'hidden',
  }}>
    <svg viewBox="0 0 1200 540" preserveAspectRatio="none"
         style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', pointerEvents: 'none', opacity: .15 }}>
      <defs>
        <pattern id="dot-pat" x="0" y="0" width="24" height="24" patternUnits="userSpaceOnUse">
          <circle cx="2" cy="2" r=".8" fill="#D4A84B" opacity=".5" />
        </pattern>
      </defs>
      <rect width="1200" height="540" fill="url(#dot-pat)" />
      <path d="M 40 140 Q 600 132 1160 140" stroke="#D4A84B" strokeWidth="1" fill="none" opacity=".25" strokeLinecap="round" />
      <path d="M 40 380 Q 600 388 1160 380" stroke="#D4A84B" strokeWidth="1" fill="none" opacity=".25" strokeLinecap="round" />
    </svg>
    <div style={{
      position: 'absolute', left: 14, top: 14, bottom: 14,
      display: 'flex', flexDirection: 'column', justifyContent: 'space-between', pointerEvents: 'none',
    }}>
      {['MASTER', 'DIAMOND', 'PLATINUM', 'GOLD'].map(t => (
        <span key={t} style={{
          fontFamily: 'var(--fc)', fontSize: '.55rem', fontWeight: 700,
          letterSpacing: '.16em', textTransform: 'uppercase',
          color: TIER_COLOR[t] || 'var(--muted)', opacity: .55,
        }}>{t}</span>
      ))}
    </div>
    <div style={{ position: 'absolute', inset: 0 }}>
      {bubbles.map((p, i) => <Bubble key={p.discord_tag || i} p={p} onClick={() => onSelect && onSelect(p)} />)}
    </div>
    <div style={{
      position: 'absolute', bottom: 12, right: 12,
      display: 'flex', alignItems: 'center', gap: '.6rem',
      background: 'rgba(0,0,0,.5)', padding: '.4rem .65rem',
      border: '1px solid var(--border)', borderRadius: 3, backdropFilter: 'blur(4px)',
    }}>
      <span style={{ fontFamily: 'var(--fc)', fontSize: '.6rem', letterSpacing: '.14em', color: 'var(--muted)', textTransform: 'uppercase' }}>Taille</span>
      <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
        <div style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--muted)' }} />
        <div style={{ width: 12, height: 12, borderRadius: '50%', background: 'var(--cream-2)' }} />
        <div style={{ width: 18, height: 18, borderRadius: '50%', background: 'var(--bone)' }} />
      </div>
      <span style={{ fontFamily: 'var(--fc)', fontSize: '.6rem', letterSpacing: '.06em', color: 'var(--cream-2)' }}>Iron → Master</span>
    </div>
  </div>
);

const Bubble = ({ p, onClick }) => {
  const size = TIER_SIZE[p.tier] || 30;
  const divColor = DIV_COLOR[p.div] || 'var(--muted)';
  const tierC = TIER_COLOR[p.tier] || divColor;
  const icon = p.profile_icon_id
    ? `https://raw.communitydragon.org/latest/plugins/rcp-be-lol-game-data/global/default/v1/profile-icons/${p.profile_icon_id}.jpg`
    : null;
  return (
    <div onClick={onClick} style={{
      position: 'absolute', left: p.x - size / 2, top: p.y - size / 2,
      width: size, height: size, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
    }}>
      <div style={{ position: 'absolute', inset: 0, borderRadius: '50%',
        background: `radial-gradient(circle, ${tierC}55 0%, transparent 70%)` }} />
      <div style={{
        width: size, height: size, borderRadius: '50%',
        background: icon ? `url(${icon}) center/cover` : `linear-gradient(135deg, ${tierC}, ${divColor}88)`,
        border: `1.5px solid ${divColor}`, boxShadow: '0 2px 8px rgba(0,0,0,.4)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontFamily: 'var(--fd)', fontSize: size * 0.4, color: '#0a0805',
        letterSpacing: '.02em', position: 'relative', overflow: 'hidden',
      }}>
        {!icon && p.name[0]}
        <div style={{
          position: 'absolute', bottom: -3, right: -3,
          background: 'var(--ink)', color: 'var(--bone)',
          fontFamily: 'var(--fc)', fontSize: 7, fontWeight: 700,
          padding: '1px 3px', borderRadius: 1, border: '1px solid var(--border-2)',
          letterSpacing: '.06em',
        }}>{p.role}</div>
      </div>
    </div>
  );
};

// ── MODAL — cream paper, shows real player data ──
const PlayerModal = ({ player, onClose }) => {
  const p = player;
  const tier = (p.tier || 'UNRANKED').toUpperCase();
  const rankDiv = p.rank_division || '';
  const lp = p.lp ?? 0;
  const wins = p.wins_saison ?? 0;
  const losses = p.losses_saison ?? 0;
  const total = wins + losses;
  const wr = total > 0 ? Math.round((wins/total) * 100) : 0;
  const role = ROLE_TO_LABEL[p.role_principal] || p.position_principale || '?';
  const div = p.division || 'Yordle';
  const divKey = div[0].toLowerCase();
  const icon = p.profile_icon_id
    ? `https://raw.communitydragon.org/latest/plugins/rcp-be-lol-game-data/global/default/v1/profile-icons/${p.profile_icon_id}.jpg`
    : null;
  const opgg = p.riot_id ? `https://www.op.gg/summoners/euw/${p.riot_id.replace('#','-').replace(/ /g,'%20')}` : null;
  const champs = (() => { try { return p.top_champions ? JSON.parse(p.top_champions).slice(0,5) : []; } catch { return []; } })();
  const displayName = p.discord_nick || p.discord_tag?.split('#')[0] || 'Joueur';

  return (
    <>
      <div onClick={onClose} style={{
        position: 'fixed', inset: 0, background: 'rgba(0,0,0,.7)', backdropFilter: 'blur(3px)',
        cursor: 'pointer', zIndex: 500,
      }} />
      <div className="card-paper grain" onClick={e => e.stopPropagation()} style={{
        position: 'fixed', left: '50%', top: '50%', transform: 'translate(-50%, -50%)',
        width: 460, maxHeight: '90vh', overflowY: 'auto', background: 'var(--paper)', color: 'var(--paper-ink)',
        borderRadius: 6, boxShadow: '0 24px 60px rgba(0,0,0,.7)', overflow: 'hidden', zIndex: 501,
      }}>
        <svg viewBox="0 0 200 200" style={{ position: 'absolute', top: -10, right: -20, width: 180, height: 180, opacity: .25, pointerEvents: 'none' }}>
          <path d="M 40 30 Q 100 80 80 140 T 140 200" stroke="#E63946" strokeWidth="36" fill="none" strokeLinecap="round" />
        </svg>
        <button onClick={onClose} style={{
          position: 'absolute', top: 12, right: 12, zIndex: 3,
          width: 28, height: 28, borderRadius: 2, background: 'transparent',
          border: '1px solid rgba(0,0,0,.15)', color: 'var(--paper-mut)',
          fontFamily: 'var(--fc)', fontSize: '1rem', cursor: 'pointer',
        }}>×</button>

        <div style={{ padding: '1.5rem 1.5rem 1rem', display: 'flex', alignItems: 'center', gap: '1rem' }}>
          <div style={{
            width: 76, height: 76, borderRadius: '50%', flexShrink: 0,
            background: icon ? `url(${icon}) center/cover` : 'linear-gradient(135deg, #8fb9e8, #c084fc)',
            border: '3px solid var(--paper-ink)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: 'var(--fd)', fontSize: '2.4rem', color: '#fff',
          }}>{!icon && displayName[0]?.toUpperCase()}</div>
          <div style={{ flex: 1, position: 'relative' }}>
            <div style={{ fontFamily: 'var(--fd)', fontSize: '2rem', color: 'var(--paper-ink)', letterSpacing: '.05em', lineHeight: 1 }}>{displayName.toUpperCase()}</div>
            <div style={{ fontFamily: 'var(--fc)', fontSize: '.75rem', color: 'var(--paper-mut)', letterSpacing: '.06em', marginTop: '.25rem' }}>{p.riot_id || p.discord_tag}</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: '.4rem', marginTop: '.6rem', flexWrap: 'wrap' }}>
              <span className={`chip chip-${divKey}`}>{div.toUpperCase()}</span>
              <span className="chip" style={{ background: 'var(--paper-ink)', color: 'var(--paper)' }}>
                {role} · {tier}{rankDiv ? ` ${rankDiv}` : ''}{lp ? ` ${lp}LP` : ''}
              </span>
            </div>
          </div>
        </div>

        <div style={{ padding: '0 1.5rem 1rem' }}>
          {p.team_name
            ? (
              <div style={{
                display: 'flex', alignItems: 'center', gap: '.65rem',
                padding: '.65rem .85rem', background: 'rgba(0,0,0,.04)',
                border: '1px solid rgba(0,0,0,.1)', borderRadius: 3,
              }}>
                <span style={{ fontFamily: 'var(--fc)', fontSize: '.6rem', fontWeight: 700, letterSpacing: '.18em', textTransform: 'uppercase', color: 'var(--paper-mut)' }}>Équipe</span>
                <div style={{
                  width: 26, height: 26, borderRadius: 3, background: 'var(--paper-ink)', color: DIV_COLOR[div],
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontFamily: 'var(--fd)', fontSize: '.75rem',
                }}>{p.team_name.split(' ').map(w => w[0]).join('').slice(0,3)}</div>
                <div style={{ fontFamily: 'var(--fd)', fontSize: '1.1rem', color: 'var(--paper-ink)', letterSpacing: '.04em', flex: 1 }}>{p.team_name.toUpperCase()}</div>
                <a href="#equipes" style={{ fontFamily: 'var(--fc)', fontSize: '.65rem', letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--paper-mut)', textDecoration: 'none' }}>Voir →</a>
              </div>
            )
            : (
              <div style={{
                display: 'flex', alignItems: 'center', gap: '.65rem',
                padding: '.65rem .85rem', background: 'var(--red)', color: '#fff', borderRadius: 3,
              }}>
                <span style={{ fontFamily: 'var(--fc)', fontSize: '.6rem', fontWeight: 700, letterSpacing: '.18em', textTransform: 'uppercase', color: 'rgba(255,255,255,.85)' }}>Statut</span>
                <span style={{ display: 'inline-block', width: 6, height: 6, borderRadius: '50%', background: '#fff' }} />
                <div style={{ fontFamily: 'var(--fd)', fontSize: '1.1rem', letterSpacing: '.06em' }}>AGENT LIBRE</div>
                <span style={{ marginLeft: 'auto', fontFamily: 'var(--fc)', fontSize: '.65rem', letterSpacing: '.1em', textTransform: 'uppercase', fontWeight: 700, opacity: .85 }}>Recrutable</span>
              </div>
            )}
        </div>

        <div style={{ padding: '0 1.5rem 1rem', display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '.5rem' }}>
          <PStat l="KDA" v={p.kda_moyen != null ? p.kda_moyen.toFixed(2) : '—'} />
          <PStat l="Winrate" v={total > 0 ? `${wr}%` : '—'} />
          <PStat l="Saison" v={total > 0 ? `${wins}V·${losses}D` : '—'} />
          <PStat l="Games" v={p.nb_parties_analysees ?? 0} />
        </div>

        {champs.length > 0 && (
          <div style={{ padding: '0 1.5rem 1.1rem', display: 'flex', alignItems: 'center', gap: '.5rem', flexWrap: 'wrap' }}>
            <span style={{ fontFamily: 'var(--fc)', fontSize: '.6rem', fontWeight: 700, letterSpacing: '.18em', textTransform: 'uppercase', color: 'var(--paper-mut)' }}>Champs</span>
            {champs.map(c => (
              <span key={c.name} style={{
                fontFamily: 'var(--fc)', fontSize: '.72rem', fontWeight: 600,
                padding: '.18rem .5rem', borderRadius: 2,
                background: 'rgba(0,0,0,.07)', color: 'var(--paper-ink)', letterSpacing: '.04em',
              }}>{c.name}</span>
            ))}
          </div>
        )}

        <div style={{
          padding: '.85rem 1.5rem', borderTop: '1px solid rgba(0,0,0,.08)',
          background: 'rgba(0,0,0,.04)', display: 'flex', gap: '.5rem',
        }}>
          {opgg && <BlackBtn href={opgg} icon={<Icon.Opgg />} label="OP.GG" />}
          {p.twitch_url && <BlackBtn href={p.twitch_url} icon={<Icon.Twitch />} label="Twitch" />}
          {p.yt_url && <BlackBtn href={p.yt_url} icon={<Icon.YouTube />} label="YouTube" />}
          {!opgg && !p.twitch_url && !p.yt_url && (
            <span style={{ fontFamily: 'var(--fc)', fontSize: '.7rem', color: 'var(--paper-mut)', letterSpacing: '.04em', textAlign: 'center', flex: 1 }}>
              Le joueur n'a pas renseigné ses liens. /player-social sur Discord.
            </span>
          )}
        </div>
      </div>
    </>
  );
};

const PStat = ({ l, v }) => (
  <div style={{ background: 'rgba(0,0,0,.06)', padding: '.55rem .65rem', borderRadius: 3 }}>
    <div style={{ fontFamily: 'var(--fd)', fontSize: '1.55rem', color: 'var(--paper-ink)', lineHeight: 1 }}>{v}</div>
    <div style={{ fontFamily: 'var(--fc)', fontSize: '.55rem', fontWeight: 700, letterSpacing: '.15em', textTransform: 'uppercase', color: 'var(--paper-mut)', marginTop: 4 }}>{l}</div>
  </div>
);

const BlackBtn = ({ icon, label, href }) => (
  <a href={href || '#'} target={href ? '_blank' : undefined} rel="noopener" style={{
    flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '.4rem',
    fontFamily: 'var(--fc)', fontSize: '.72rem', fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase',
    background: '#0a0805', color: 'var(--bone)', border: '1px solid var(--border-2)',
    padding: '.5rem .75rem', borderRadius: 3, textDecoration: 'none', cursor: 'pointer',
  }}>{icon} {label}</a>
);

Object.assign(window, { JoueursPage });
