// views/Players.jsx — Player gallery with Wikipedia images, sorting, and a
// master–detail preview: click a card and the grid shrinks to make room for a
// full profile pulled live from Wikipedia.

function playerPopularity(p) {
  let s = (p.goals || 0) * 1.1 + (p.caps || 0) * 0.5;
  if (p.tags.includes('legend')) s += 80;
  if (p.tags.includes('star')) s += 30;
  if (p.tags.includes('top')) s += 22;
  if (p.tags.includes('captain')) s += 16;
  if (p.tags.includes('wonderkid')) s += 12;
  return s;
}

function PlayersView({ onRoute }) {
  const all = window.WCL_PLAYERS;
  const [filter, setFilter] = React.useState('');
  const [pos, setPos] = React.useState('all');
  const [tag, setTag] = React.useState('all');
  const [sort, setSort] = React.useState('pop');
  const [sel, setSel] = React.useState(null); // selected player name

  const ranked = React.useMemo(() => {
    const withPop = all.map(p => ({ ...p, _pop: playerPopularity(p) }));
    withPop.sort((a, b) => b._pop - a._pop);
    withPop.forEach((p, i) => { p._rank = i + 1; });
    return withPop;
  }, [all]);

  let items = ranked.filter(p => {
    if (pos !== 'all' && p.pos !== pos) return false;
    if (tag !== 'all' && !p.tags.includes(tag)) return false;
    if (filter) {
      const q = filter.toLowerCase();
      const team = window.WCL_TEAMS[p.team];
      return p.name.toLowerCase().includes(q) || p.team.toLowerCase().includes(q) || (team && team.name.toLowerCase().includes(q));
    }
    return true;
  });
  items = items.slice().sort((a, b) => {
    if (sort === 'name') return a.name.localeCompare(b.name);
    if (sort === 'age') return (b.age || 0) - (a.age || 0);
    return a._rank - b._rank;
  });

  const selected = sel ? ranked.find(p => p.name === sel) : null;

  return (
    <div>
      <div className="page-head">
        <div>
          <div className="eyebrow">{all.length} players · 2026 stars + all-time greats</div>
          <h1 className="type-h1">Players</h1>
          <div className="sub">Ranked by popularity · photos &amp; bios pulled live from Wikipedia · click any player for the full profile.</div>
        </div>
        <input className="input" placeholder="Search name or country…" value={filter} onChange={e => setFilter(e.target.value)} style={{ width: 220 }} />
      </div>

      <section className="panel" style={{ marginBottom: 16, padding: '12px 16px' }}>
        <div style={{ display: 'flex', gap: 16, alignItems: 'center', flexWrap: 'wrap' }}>
          <span className="eyebrow">Sort</span>
          <div className="seg">
            {[['pop','Ranked'],['name','Name'],['age','Age']].map(([v, l]) => (
              <button key={v} className={sort === v ? 'active' : ''} onClick={() => setSort(v)}>{l}</button>
            ))}
          </div>
          <span className="eyebrow" style={{ marginLeft: 8 }}>Position</span>
          <div className="seg">
            {[['all','All'],['GK','GK'],['CB','DEF'],['CM','MID'],['AM','AM'],['LW','WIDE'],['ST','ST']].map(([v, l]) => (
              <button key={v} className={pos === v ? 'active' : ''} onClick={() => setPos(v)}>{l}</button>
            ))}
          </div>
          <span className="eyebrow" style={{ marginLeft: 8 }}>Tag</span>
          <div className="seg">
            {[['all','All'],['captain','Cap'],['star','Star'],['wonderkid','Kid'],['top','Scorer'],['legend','Legend']].map(([v, l]) => (
              <button key={v} className={tag === v ? 'active' : ''} onClick={() => setTag(v)}>{l}</button>
            ))}
          </div>
          <span className="subtle" style={{ marginLeft: 'auto', fontSize: 12 }}>{items.length} of {all.length}</span>
        </div>
      </section>

      <div style={{ display: 'grid', gridTemplateColumns: selected ? 'minmax(0,1fr) 380px' : '1fr', gap: 16, alignItems: 'start' }}>
        <div style={{
          display: 'grid',
          gridTemplateColumns: selected ? 'repeat(auto-fill, minmax(140px, 1fr))' : 'repeat(auto-fill, minmax(210px, 1fr))',
          gap: 14,
        }}>
          {items.map(p => (
            <PlayerCard key={p.name} p={p} compact={!!selected} selected={sel === p.name}
                        showRank={sort === 'pop'}
                        onSelect={() => setSel(sel === p.name ? null : p.name)} />
          ))}
        </div>

        {selected && (
          <div style={{ position: 'sticky', top: 12 }}>
            <PlayerPreview p={selected} onRoute={onRoute} onClose={() => setSel(null)} />
          </div>
        )}
      </div>
    </div>
  );
}

// ---------- shared image fetch hook ----------
function useWikiSummary(title) {
  const [data, setData] = React.useState({ img: null, extract: null, desc: null, url: null, loaded: false, failed: false });
  React.useEffect(() => {
    let cancelled = false;
    setData(d => ({ ...d, loaded: false, failed: false }));
    fetch(`https://en.wikipedia.org/api/rest_v1/page/summary/${title}`, { headers: { 'Api-User-Agent': 'WorldCupLive-prototype' } })
      .then(r => r.ok ? r.json() : null)
      .then(j => {
        if (cancelled) return;
        if (!j) { setData(d => ({ ...d, failed: true, loaded: true })); return; }
        setData({
          img: j.thumbnail?.source || j.originalimage?.source || null,
          extract: j.extract || null,
          desc: j.description || null,
          url: j.content_urls?.desktop?.page || `https://en.wikipedia.org/wiki/${title}`,
          loaded: true, failed: false,
        });
      })
      .catch(() => { if (!cancelled) setData(d => ({ ...d, failed: true, loaded: true })); });
    return () => { cancelled = true; };
  }, [title]);
  return data;
}

function PlayerCard({ p, onSelect, selected, compact, showRank }) {
  const { img, loaded, failed } = useWikiSummary(p.wikipedia);
  const initials = p.name.split(' ').map(s => s[0]).join('').slice(0, 2);
  const tagPills = p.tags.slice(0, compact ? 1 : 2);

  return (
    <article
      onClick={onSelect}
      style={{
        background: 'var(--surface)',
        border: '1px solid ' + (selected ? 'var(--brand)' : 'var(--border)'),
        boxShadow: selected ? '0 0 0 1px var(--brand)' : 'none',
        borderRadius: 'var(--radius)',
        overflow: 'hidden',
        cursor: 'pointer',
        transition: 'border-color var(--dur-fast) var(--ease-out), background var(--dur-fast) var(--ease-out)',
      }}
      onMouseEnter={e => { if (!selected) e.currentTarget.style.borderColor = 'var(--border-hover)'; }}
      onMouseLeave={e => { if (!selected) e.currentTarget.style.borderColor = 'var(--border)'; }}
    >
      <div style={{ position: 'relative', aspectRatio: '1/1', background: 'linear-gradient(135deg, color-mix(in oklch, var(--brand) 18%, var(--muted)), var(--muted))', overflow: 'hidden' }}>
        {img && !failed && (
          <img src={img} alt={p.name} style={{ width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'center top', opacity: loaded ? 1 : 0, transition: 'opacity 240ms var(--ease-out)', filter: p.historical ? 'grayscale(0.3) contrast(1.05)' : 'none' }} />
        )}
        {(!img || failed) && (
          <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 42, fontWeight: 700, letterSpacing: '-0.04em', color: 'rgba(255,255,255,0.4)' }}>{initials}</div>
        )}
        {showRank && (
          <div style={{ position: 'absolute', top: 10, left: 10, minWidth: 24, height: 24, padding: '0 6px', borderRadius: 7, background: p._rank <= 3 ? 'color-mix(in oklch, var(--trophy) 85%, black)' : 'rgba(0,0,0,0.6)', backdropFilter: 'blur(8px)', border: '1px solid rgba(255,255,255,0.12)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-mono)', fontSize: 11, fontWeight: 700, color: 'white' }}>#{p._rank}</div>
        )}
        <div style={{ position: 'absolute', top: 10, right: 10, display: 'flex', alignItems: 'center', gap: 6, padding: '4px 8px', background: 'rgba(0,0,0,0.55)', backdropFilter: 'blur(8px)', border: '1px solid rgba(255,255,255,0.10)', borderRadius: 999, fontSize: 11, fontWeight: 600, color: 'white' }}>
          <Flag code={p.team} /> {p.team}
        </div>
        {tagPills.length > 0 && (
          <div style={{ position: 'absolute', bottom: 10, left: 10, display: 'flex', gap: 4 }}>
            {tagPills.map(t => (
              <span key={t} style={{ padding: '3px 8px', fontSize: 10, fontWeight: 600, background: t === 'captain' ? 'color-mix(in oklch, var(--brand) 60%, transparent)' : t === 'legend' ? 'color-mix(in oklch, var(--trophy) 60%, transparent)' : t === 'star' ? 'color-mix(in oklch, var(--pitch) 50%, transparent)' : t === 'top' ? 'color-mix(in oklch, var(--destructive) 50%, transparent)' : 'rgba(0,0,0,0.55)', backdropFilter: 'blur(8px)', color: 'white', border: '1px solid rgba(255,255,255,0.10)', borderRadius: 999, letterSpacing: '0.04em', textTransform: 'uppercase' }}>{t}</span>
            ))}
          </div>
        )}
      </div>
      <div style={{ padding: compact ? '10px 12px' : '12px 14px' }}>
        <div className="strong" style={{ fontSize: compact ? 13 : 14, fontWeight: 600, letterSpacing: '-0.01em', lineHeight: 1.2 }}>{p.name}</div>
        <div className="subtle" style={{ fontSize: 11, marginTop: 4, fontFamily: 'var(--font-mono)' }}>
          {p.pos} · {p.age ? p.age + 'yo · ' : ''}{p.caps} caps · {p.goals}g
        </div>
        {!compact && <div className="subtle" style={{ fontSize: 12, marginTop: 8, lineHeight: 1.45, textWrap: 'pretty' }}>{p.note}</div>}
      </div>
    </article>
  );
}

function PlayerPreview({ p, onRoute, onClose }) {
  const { img, extract, desc, url, loaded, failed } = useWikiSummary(p.wikipedia);
  const team = window.WCL_TEAMS[p.team];
  const initials = p.name.split(' ').map(s => s[0]).join('').slice(0, 2);

  return (
    <section className="panel" style={{ padding: 0, overflow: 'hidden' }}>
      <div style={{ position: 'relative', aspectRatio: '16/10', background: 'linear-gradient(135deg, color-mix(in oklch, var(--brand) 22%, var(--muted)), var(--muted))', overflow: 'hidden' }}>
        {img && !failed && <img src={img} alt={p.name} style={{ width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'center top', opacity: loaded ? 1 : 0, transition: 'opacity 240ms var(--ease-out)', filter: p.historical ? 'grayscale(0.25)' : 'none' }} />}
        {(!img || failed) && <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 56, fontWeight: 700, color: 'rgba(255,255,255,0.4)' }}>{initials}</div>}
        <button className="btn btn-ghost btn-icon" onClick={onClose} aria-label="close" style={{ position: 'absolute', top: 10, right: 10, background: 'rgba(0,0,0,0.5)', backdropFilter: 'blur(8px)', color: 'white', border: '1px solid rgba(255,255,255,0.15)' }}><I.X size={15} /></button>
        <div style={{ position: 'absolute', left: 14, bottom: 12, right: 14 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
            <Flag code={p.team} size="lg" />
            <span style={{ color: 'white', fontWeight: 600, fontSize: 13, textShadow: '0 1px 4px rgba(0,0,0,0.8)' }}>{team?.name || p.team}</span>
          </div>
          <div style={{ color: 'white', fontSize: 24, fontWeight: 700, letterSpacing: '-0.02em', textShadow: '0 1px 6px rgba(0,0,0,0.85)' }}>{p.name}</div>
        </div>
      </div>

      <div style={{ padding: 16 }}>
        <div className="subtle" style={{ fontSize: 12, marginBottom: 12 }}>{desc || (p.pos + ' · ' + (team?.name || p.team))}</div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8, marginBottom: 14 }}>
          {[['No.', p.n], ['Age', p.age || '—'], ['Caps', p.caps], ['Goals', p.goals]].map(([k, v]) => (
            <div key={k} style={{ padding: '8px 6px', background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--radius-sm)', textAlign: 'center' }}>
              <div className="kpi-value" style={{ fontSize: 18 }}>{v}</div>
              <div className="eyebrow" style={{ fontSize: 9, marginTop: 2 }}>{k}</div>
            </div>
          ))}
        </div>

        <div className="eyebrow" style={{ marginBottom: 6 }}>From Wikipedia</div>
        <p className="subtle" style={{ fontSize: 13, lineHeight: 1.55, margin: '0 0 12px', textWrap: 'pretty' }}>
          {!loaded ? 'Loading biography…' : (extract || p.note)}
        </p>

        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 14 }}>
          {p.tags.map(t => <span key={t} className="badge neutral" style={{ textTransform: 'capitalize' }}>{t}</span>)}
        </div>

        <div style={{ display: 'flex', gap: 6 }}>
          <button className="btn btn-primary btn-sm" style={{ flex: 1 }} onClick={() => onRoute('team', { code: p.team })}><I.Shield size={14} /> {team?.name || p.team}</button>
          {url && <a className="btn btn-secondary btn-sm" href={url} target="_blank" rel="noreferrer"><I.ArrowUR size={13} /> Wikipedia</a>}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { PlayersView, PlayerCard, PlayerPreview, useWikiSummary, playerPopularity });
