/* global React, TeamDisc, Jersey, Form, Panel, SlashHeading, SplitBar */
const PLx = window.PL;

/* ---------- Player leaders: Goals / Assists tabbed ---------- */
function PlayerLeaders() {
  const [tab, setTab] = React.useState('goals');
  const list = tab === 'goals' ? PLx.scorers : PLx.assisters;
  const max = tab === 'goals' ? list[0].g : list[0].a;
  const leader = list[0];
  return (
    <Panel pad={0}>
      <div style={{ padding: '20px 22px 0' }}>
        <SlashHeading title="Player Leaders" kicker="Season totals" />
        <div style={{ marginBottom: 16 }}>
          <Tabs tone="light" active={tab} onChange={setTab} tabs={[
            { id: 'goals', label: 'Top Scorers' }, { id: 'assists', label: 'Top Assists' },
          ]} />
        </div>
      </div>
      {/* hero leader */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 18, padding: '0 22px 18px', borderBottom: '1px solid var(--border-subtle)' }}>
        <div style={{ background: 'var(--bs-neutral-100)', borderRadius: 'var(--radius-md)', padding: '10px 14px 4px' }}>
          <Jersey code={leader.t} number={leader.n} size={72} />
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
            <span style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase', background: 'var(--bs-lime)', color: 'var(--bs-blue-navy)', padding: '3px 8px', borderRadius: 3 }}>{tab === 'goals' ? 'Golden Boot' : 'Playmaker'}</span>
          </div>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 22, color: 'var(--text-primary)', lineHeight: 1.1 }}>{leader.name}</div>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 7, marginTop: 5 }}>
            <TeamDisc code={leader.t} size={20} /><span style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--text-muted)' }}>{PLx.T[leader.t].name}</span>
          </div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div style={{ fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: 38, lineHeight: 1, color: 'var(--bs-blue-electric)' }}>{tab === 'goals' ? leader.g : leader.a}</div>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--text-muted)' }}>{tab === 'goals' ? 'Goals' : 'Assists'}</div>
        </div>
      </div>
      {/* rest */}
      <div style={{ padding: '6px 22px 18px' }}>
        {list.slice(1, 5).map((p) => {
          const val = tab === 'goals' ? p.g : p.a;
          const sub = tab === 'goals' ? `${p.a} ast · ${p.pens || 0} pens` : `${p.g} gls · ${p.key} key passes`;
          return (
            <div key={p.name} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '9px 0', borderBottom: '1px solid var(--border-subtle)' }}>
              <span style={{ width: 18, fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: 13, color: 'var(--text-muted)' }}>{p.rk}</span>
              <Jersey code={p.t} number={p.n} size={30} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 14, color: 'var(--text-primary)' }}>{p.name}</div>
                <div style={{ fontFamily: 'var(--font-body)', fontSize: 11.5, color: 'var(--text-muted)' }}>{sub}</div>
              </div>
              <div style={{ width: 90, height: 6, borderRadius: 999, background: 'var(--bs-neutral-200)', overflow: 'hidden' }}>
                <div style={{ width: (val / max * 100) + '%', height: '100%', background: 'var(--bs-blue-electric)', borderRadius: 999 }} />
              </div>
              <span style={{ width: 26, textAlign: 'right', fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: 16, color: 'var(--text-brand)' }}>{val}</span>
            </div>
          );
        })}
      </div>
    </Panel>
  );
}

/* ---------- In-form table (last 5) ---------- */
function FormGuide() {
  const rows = [...PLx.inForm].sort((a, b) => b.pts5 - a.pts5 || b.gd5 - a.gd5);
  const max = 15;
  return (
    <Panel pad={0}>
      <div style={{ padding: '20px 22px 4px' }}>
        <SlashHeading title="Form Guide" kicker="Last 5 matches" action="Full form" />
      </div>
      <div style={{ padding: '4px 22px 20px' }}>
        {rows.map((r, i) => (
          <div key={r.t} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '11px 0', borderBottom: i < rows.length - 1 ? '1px solid var(--border-subtle)' : 'none' }}>
            <span style={{ width: 16, fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: 13, color: 'var(--text-muted)' }}>{i + 1}</span>
            <TeamDisc code={r.t} size={30} />
            <span style={{ flex: 1, fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 14, color: 'var(--text-primary)' }}>{PLx.T[r.t].name}</span>
            <Form results={r.form} size={20} gap={3} />
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', minWidth: 52 }}>
              <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: 15, color: 'var(--bs-blue-electric)' }}>{r.pts5} pts</span>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-muted)' }}>GD {r.gd5 > 0 ? '+' : ''}{r.gd5}</span>
            </div>
          </div>
        ))}
      </div>
    </Panel>
  );
}

/* ---------- Match of the weekend spotlight ---------- */
function MatchSpotlight() {
  const s = PLx.spotlight;
  const hc = PLx.T[s.h], ac = PLx.T[s.a];
  const hForm = (PLx.table.find((r) => r.t === s.h) || {}).form || [];
  const aForm = (PLx.table.find((r) => r.t === s.a) || {}).form || [];
  const ord = (n) => n + (n === 1 ? 'st' : n === 2 ? 'nd' : n === 3 ? 'rd' : 'th');
  const hPos = (PLx.table.find((r) => r.t === s.h) || {}).pos;
  const aPos = (PLx.table.find((r) => r.t === s.a) || {}).pos;
  const [tab, setTab] = React.useState('season');
  return (
    <Panel pad={0} style={{ background: 'var(--bs-blue-navy)' }}>
      <div style={{ position: 'relative', overflow: 'hidden' }}>
        <img src="assets/background-pattern.svg" alt="" aria-hidden="true" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', color: '#1A0A78', opacity: 0.4, mixBlendMode: 'screen', pointerEvents: 'none' }} />
        <div style={{ position: 'relative', padding: '24px 28px' }}>
          <SlashHeading title="Next Big Match" onLight={false} right={(
            <span style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 12, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--bs-lime)' }}>{ord(hPos)} v {ord(aPos)}</span>
          )} />
          {/* teams + kickoff */}
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16 }}>
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10, flex: 1 }}>
              <TeamDisc code={s.h} size={64} ring />
              <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 16, color: 'var(--bs-white)' }}>{hc.name}</span>
            </div>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 26, color: 'var(--bs-lime)', lineHeight: 1 }}>{s.time}</div>
              <div style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: 'rgba(255,255,255,0.6)', marginTop: 4 }}>{s.day}</div>
              <div style={{ fontFamily: 'var(--font-body)', fontSize: 11, color: 'rgba(255,255,255,0.45)', marginTop: 2 }}>{s.venue}</div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10, flex: 1 }}>
              <TeamDisc code={s.a} size={64} ring />
              <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 16, color: 'var(--bs-white)' }}>{ac.name}</span>
            </div>
          </div>
        </div>
        {/* tabbed comparison on white */}
        <div style={{ position: 'relative', background: 'var(--bs-white)', padding: '18px 28px 22px' }}>
          <div style={{ marginBottom: 18 }}>
            <Tabs tone="light" active={tab} onChange={setTab} tabs={[{ id: 'season', label: 'Season Comparison' }, { id: 'h2h', label: 'Head to Head' }]} />
          </div>
          {tab === 'season' ? (
            <div>
              {s.stats.map((st) => {
                const total = (st.h + st.a) || 1;
                const u = st.unit || '';
                return (
                  <div key={st.label} style={{ marginBottom: 12 }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 5 }}>
                      <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: 14, color: st.h >= st.a ? 'var(--text-brand)' : 'var(--text-muted)' }}>{st.h}{u}</span>
                      <span style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 11, letterSpacing: '0.05em', textTransform: 'uppercase', color: 'var(--text-muted)' }}>{st.label}</span>
                      <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: 14, color: st.a >= st.h ? 'var(--text-brand)' : 'var(--text-muted)' }}>{st.a}{u}</span>
                    </div>
                    <div style={{ display: 'flex', height: 7, gap: 3 }}>
                      <div style={{ flex: st.h / total, background: hc.c, borderRadius: '999px 0 0 999px', minWidth: 4 }} />
                      <div style={{ flex: st.a / total, background: ac.c, borderRadius: '0 999px 999px 0', minWidth: 4 }} />
                    </div>
                  </div>
                );
              })}
            </div>
          ) : (
            <div>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}><TeamDisc code={s.h} size={22} /><span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 14, color: 'var(--text-brand)' }}>{hc.name}</span></span>
                <span style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 11, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--text-muted)' }}>Last {s.h2h.meetings} meetings</span>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}><span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 14, color: 'var(--text-brand)' }}>{ac.name}</span><TeamDisc code={s.a} size={22} /></span>
              </div>
              {s.h2h.rows.map((row) => (
                <div key={row.label} style={{ display: 'grid', gridTemplateColumns: '1fr auto 1fr', alignItems: 'center', padding: '10px 0', borderTop: '1px solid var(--border-subtle)' }}>
                  <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: 17, color: 'var(--text-brand)', textAlign: 'left' }}>{row.h}</span>
                  <span style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 11, letterSpacing: '0.05em', textTransform: 'uppercase', color: 'var(--text-muted)' }}>{row.label}</span>
                  <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: 17, color: 'var(--text-brand)', textAlign: 'right' }}>{row.a}</span>
                </div>
              ))}
            </div>
          )}
          {/* recent form into the match */}
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, marginTop: 18, paddingTop: 16, borderTop: '1px solid var(--border-subtle)' }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 9 }}>
              <TeamDisc code={s.h} size={22} />
              <Form results={hForm} size={20} gap={3} />
            </span>
            <span style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--text-muted)' }}>Last 5</span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 9 }}>
              <Form results={aForm} size={20} gap={3} />
              <TeamDisc code={s.a} size={22} />
            </span>
          </div>
        </div>
      </div>
    </Panel>
  );
}

/* ---------- Fixtures + live results ---------- */
function Scoreline({ m }) {
  const live = m.state === 'live';
  const epo = live && Math.abs(m.hs - m.as) >= 2;
  const nm = { fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 13, color: 'var(--text-primary)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' };
  return (
    <div className="bs-fixrow" style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px', borderRadius: 'var(--radius-sm)' }}>
      <span style={{ flex: 1, display: 'inline-flex', alignItems: 'center', gap: 8, justifyContent: 'flex-end', minWidth: 0 }}>
        <span style={nm}>{PLx.T[m.h].name}</span>
        <TeamDisc code={m.h} size={24} />
      </span>
      <span style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flex: '0 0 auto', minWidth: 54 }}>
        {live
          ? <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: 16, color: 'var(--bs-blue-navy)', background: 'var(--bs-neutral-100)', padding: '2px 10px', borderRadius: 3, whiteSpace: 'nowrap' }}>{m.hs}–{m.as}</span>
          : <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 600, fontSize: 13, color: 'var(--text-muted)', whiteSpace: 'nowrap' }}>{m.day} {m.time}</span>}
        {live && <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: 10, color: 'var(--bs-success)', marginTop: 3 }}>{m.min}</span>}
      </span>
      <span style={{ flex: 1, display: 'inline-flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
        <TeamDisc code={m.a} size={24} />
        <span style={nm}>{PLx.T[m.a].name}</span>
        {epo && <span style={{ marginLeft: 'auto', flex: '0 0 auto' }}><EPOBadge height={16} /></span>}
      </span>
    </div>
  );
}
function Fixtures() {
  const [tab, setTab] = React.useState('upcoming');
  const Team = ({ code, align }) => (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, minWidth: 0 }}>
      <TeamDisc code={code} size={38} />
      <span style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 13, color: 'var(--text-primary)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: '100%' }}>{PLx.T[code].name}</span>
    </div>
  );
  const Row = ({ m, result }) => (
    <div style={{ display: 'grid', gridTemplateColumns: 'minmax(104px, 0.9fr) 1fr auto 1fr', alignItems: 'center', gap: 10, padding: '15px 20px', borderTop: '1px solid var(--border-subtle)' }}>
      <div>
        <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 14, color: 'var(--text-brand)', lineHeight: 1.2 }}>{m.date}</div>
        <div style={{ fontFamily: 'var(--font-body)', fontSize: 13.5, color: 'var(--text-muted)', marginTop: 3 }}>{result ? 'Full time' : m.time}</div>
      </div>
      <Team code={m.h} />
      {result ? (
        <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: 18, color: 'var(--bs-blue-navy)', background: 'var(--bs-neutral-100)', padding: '5px 12px', borderRadius: 4, flex: '0 0 auto', whiteSpace: 'nowrap' }}>{m.hs}–{m.as}</span>
      ) : (
        <span style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', background: 'var(--bs-lime)', transform: 'skewX(-18deg)', padding: '5px 13px', flex: '0 0 auto' }}>
          <span style={{ transform: 'skewX(18deg)', fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 13, letterSpacing: '0.04em', color: 'var(--bs-blue-navy)' }}>VS</span>
        </span>
      )}
      <Team code={m.a} />
    </div>
  );
  return (
    <Panel pad={0}>
      <div style={{ padding: '20px 22px 8px' }}>
        <SlashHeading title="Fixtures" action="All fixtures & results" />
        <Tabs tone="light" active={tab} onChange={setTab} tabs={[
          { id: 'results', label: 'Latest Results' },
          { id: 'upcoming', label: 'Upcoming Fixtures' },
        ]} />
      </div>
      <div>
        {tab === 'results'
          ? PLx.results.map((m, i) => <Row key={i} m={m} result />)
          : PLx.upcoming.map((m, i) => <Row key={i} m={m} />)}
      </div>
    </Panel>
  );
}

Object.assign(window, { PlayerLeaders, FormGuide, MatchSpotlight, Fixtures });
