/* global React, TeamDisc, Form, Panel, SlashHeading */
const PLw = window.PL;

/* ---------- Full league table ---------- */
function StandingsTable() {
  const [sort, setSort] = React.useState('pos');
  const rows = [...PLw.table].sort((a, b) => {
    if (sort === 'pos') return a.pos - b.pos;
    if (sort === 'gd') return b.gd - a.gd;
    if (sort === 'gf') return b.gf - a.gf;
    return b.pts - a.pts;
  });
  const zone = (pos) => pos <= 4 ? 'var(--bs-lime)' : pos === 5 ? '#8FB3FF' : pos >= 18 ? 'var(--bs-error)' : 'transparent';
  const Th = ({ k, children, w, sortable }) => (
    <th onClick={sortable ? () => setSort(k) : undefined} style={{
      padding: '0 8px', textAlign: w === 'l' ? 'left' : 'center', width: w === 'l' ? 'auto' : 38,
      fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 11, letterSpacing: '0.06em', textTransform: 'uppercase',
      color: sort === k ? 'var(--text-brand)' : 'var(--text-muted)', cursor: sortable ? 'pointer' : 'default', userSelect: 'none', whiteSpace: 'nowrap',
    }}>{children}</th>
  );
  return (
    <Panel pad={0}>
      <div style={{ padding: '20px 22px 6px' }}>
        <SlashHeading title="League Table" kicker="Top 10 · Standings" action="Full table" />
      </div>
      <div style={{ overflowX: 'auto' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 620 }}>
          <thead>
            <tr style={{ height: 34, borderBottom: '1px solid var(--border-mid)' }}>
              <Th w="c">#</Th>
              <Th w="l">Club</Th>
              <Th k="p" w="c">P</Th>
              <Th w="c">W</Th><Th w="c">D</Th><Th w="c">L</Th>
              <Th k="gd" w="c" sortable>GD</Th>
              <th style={{ padding: '0 12px', textAlign: 'left', fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 11, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--text-muted)' }}>Form</th>
              <Th k="pts" w="c" sortable><span style={{ color: 'var(--text-brand)' }}>PTS</span></Th>
            </tr>
          </thead>
          <tbody>
            {rows.slice(0, 10).map((r) => (
              <tr key={r.t} className="bs-trow" style={{ height: 44, borderBottom: '1px solid var(--border-subtle)' }}>
                <td style={{ padding: 0, width: 34, position: 'relative' }}>
                  <span style={{ position: 'absolute', left: 0, top: 6, bottom: 6, width: 3, background: zone(r.pos), borderRadius: 2 }} />
                  <span style={{ display: 'block', textAlign: 'center', fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: 13, color: 'var(--text-body)' }}>{r.pos}</span>
                </td>
                <td style={{ padding: '0 8px' }}>
                  <span style={{ display: 'inline-flex', alignItems: 'center', gap: 11 }}>
                    <TeamDisc code={r.t} size={28} />
                    <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 14, color: 'var(--text-primary)' }}>{PLw.T[r.t].name}</span>
                  </span>
                </td>
                <Td v={r.p} /><Td v={r.w} /><Td v={r.d} /><Td v={r.l} />
                <Td v={(r.gd > 0 ? '+' : '') + r.gd} strong={r.gd > 0} />
                <td style={{ padding: '0 12px' }}><Form results={r.form} size={20} gap={3} team={r.t} /></td>
                <td style={{ padding: '0 10px', textAlign: 'center' }}>
                  <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: 16, color: 'var(--text-brand)' }}>{r.pts}</span>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div style={{ display: 'flex', gap: 20, padding: '12px 22px', borderTop: '1px solid var(--border-subtle)', flexWrap: 'wrap' }}>
        <Legend c="var(--bs-lime)" label="Champions League" />
        <Legend c="#8FB3FF" label="Europa League" />
        <Legend c="var(--bs-error)" label="Relegation" />
      </div>
    </Panel>
  );
}
function Td({ v, muted, strong }) {
  return <td style={{ padding: '0 4px', textAlign: 'center', fontFamily: 'var(--font-mono)', fontWeight: strong ? 700 : 500, fontSize: 13, color: muted ? 'var(--text-muted)' : strong ? 'var(--bs-blue-navy)' : 'var(--text-body)', fontVariantNumeric: 'tabular-nums' }}>{v}</td>;
}
function Legend({ c, label }) {
  return <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7 }}>
    <span style={{ width: 10, height: 10, borderRadius: 2, background: c }} />
    <span style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--text-muted)' }}>{label}</span>
  </span>;
}

/* ---------- Title race line chart ---------- */
function TitleRace() {
  const teams = ['ARS', 'MCI', 'LIV', 'CHE'];
  const W = 560, H = 292, padL = 44, padB = 40, padT = 14, padR = 46;
  const xs = PLw.raceMW;
  const maxPts = 76, minMW = xs[0], maxMW = xs[xs.length - 1];
  const x = (mw) => padL + (mw - minMW) / (maxMW - minMW) * (W - padL - padR);
  const y = (pts) => padT + (1 - pts / maxPts) * (H - padT - padB);
  const [hover, setHover] = React.useState(null);
  return (
    <Panel pad={0}>
      <div style={{ padding: '20px 22px 4px' }}>
        <SlashHeading title="Title Race" kicker="Points won · by matchweek" action="Predictor" />
      </div>
      <div style={{ padding: '0 14px 8px' }}>
        <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height: 'auto', display: 'block' }}>
          {[0, 19, 38, 57, 76].map((g) => (
            <g key={g}>
              <line x1={padL} y1={y(g)} x2={W - padR} y2={y(g)} stroke="var(--border-subtle)" strokeWidth="1" />
              <text x={padL - 8} y={y(g) + 4} textAnchor="end" fontFamily="var(--font-mono)" fontSize="10" fill="var(--text-muted)">{g}</text>
            </g>
          ))}
          {xs.map((mw) => (
            <text key={mw} x={x(mw)} y={H - 22} textAnchor="middle" fontFamily="var(--font-mono)" fontSize="10" fill="var(--text-muted)">{mw}</text>
          ))}
          {/* axis titles */}
          <text x={padL + (W - padL - padR) / 2} y={H - 5} textAnchor="middle" fontFamily="var(--font-display)" fontWeight="600" fontSize="10" letterSpacing="0.1em" fill="var(--text-muted)">MATCHWEEK</text>
          <text x={11} y={padT + (H - padT - padB) / 2} textAnchor="middle" fontFamily="var(--font-display)" fontWeight="600" fontSize="10" letterSpacing="0.1em" fill="var(--text-muted)" transform={`rotate(-90 11 ${padT + (H - padT - padB) / 2})`}>POINTS</text>
          {teams.map((t) => {
            const pts = PLw.racePts[t];
            const d = pts.map((p, i) => `${i === 0 ? 'M' : 'L'} ${x(xs[i])} ${y(p)}`).join(' ');
            const last = pts.length - 1;
            const dim = hover && hover !== t;
            return (
              <g key={t} opacity={dim ? 0.25 : 1} style={{ transition: 'opacity .2s' }} onMouseEnter={() => setHover(t)} onMouseLeave={() => setHover(null)}>
                <path d={d} fill="none" stroke={PLw.T[t].c} strokeWidth={hover === t ? 3.4 : 2.4} strokeLinejoin="round" strokeLinecap="round" />
                <circle cx={x(xs[last])} cy={y(pts[last])} r="4.5" fill={PLw.T[t].c} stroke="#fff" strokeWidth="1.6" />
                <text x={x(xs[last]) + 8} y={y(pts[last]) + 4} fontFamily="var(--font-display)" fontWeight="700" fontSize="12" fill={PLw.T[t].c}>{pts[last]}</text>
              </g>
            );
          })}
        </svg>
      </div>
      <div style={{ display: 'flex', gap: 18, padding: '8px 22px 20px', flexWrap: 'wrap', borderTop: '1px solid var(--border-subtle)' }}>
        {teams.map((t) => (
          <span key={t} onMouseEnter={() => setHover(t)} onMouseLeave={() => setHover(null)} style={{ display: 'inline-flex', alignItems: 'center', gap: 8, cursor: 'default' }}>
            <TeamDisc code={t} size={22} />
            <span style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 13, color: 'var(--text-primary)' }}>{PLw.T[t].name}</span>
          </span>
        ))}
      </div>
    </Panel>
  );
}

/* ---------- Team season stats (per-team, with team picker) ---------- */
function TrendTile({ value, label, accent }) {
  return (
    <div style={{ padding: '16px 16px', borderRadius: 'var(--radius-sm)', background: 'var(--bs-neutral-100)', border: '1px solid var(--border-subtle)' }}>
      <div style={{ fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: 26, lineHeight: 1, color: accent || 'var(--text-brand)', fontVariantNumeric: 'tabular-nums' }}>{value}</div>
      <div style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--text-muted)', marginTop: 6 }}>{label}</div>
    </div>
  );
}
function GoalTrends() {
  const ordered = [...PLw.table].sort((a, b) => a.pos - b.pos);
  const [code, setCode] = React.useState(ordered[0].t);
  const [split, setSplit] = React.useState('Season');
  const r = PLw.table.find((x) => x.t === code);
  // season per-game base (GF/GA from standings; xG/poss/shots/SOT modelled off quality)
  const base = {
    gf: r.gf / r.p, ga: r.ga / r.p,
    xgf: (r.gf / r.p) * 0.92, xga: (r.ga / r.p) * 0.97,
    poss: 60 - (r.pos - 1) * 0.85,
    shots: 17 - (r.pos - 1) * 0.4,
    sot: (17 - (r.pos - 1) * 0.4) * 0.4,
  };
  const k = split === 'Home' ? { gf: 1.12, ga: 0.88, xgf: 1.1, xga: 0.9, poss: 2.5, shots: 1.08, sot: 1.08 }
    : split === 'Away' ? { gf: 0.88, ga: 1.12, xgf: 0.9, xga: 1.1, poss: -2.5, shots: 0.92, sot: 0.92 }
    : { gf: 1, ga: 1, xgf: 1, xga: 1, poss: 0, shots: 1, sot: 1 };
  const v = {
    gf: base.gf * k.gf, ga: base.ga * k.ga, xgf: base.xgf * k.xgf, xga: base.xga * k.xga,
    poss: base.poss + k.poss, shots: base.shots * k.shots, sot: base.sot * k.sot,
  };
  const metrics = [
    { k: 'Goals For', v: v.gf.toFixed(1), w: v.gf / 3 },
    { k: 'Goals Against', v: v.ga.toFixed(1), w: v.ga / 3 },
    { k: 'xG For', v: v.xgf.toFixed(2), w: v.xgf / 3 },
    { k: 'xG Against', v: v.xga.toFixed(2), w: v.xga / 3 },
    { k: 'Possession', v: v.poss.toFixed(1) + '%', w: v.poss / 100 },
    { k: 'Shots', v: v.shots.toFixed(1), w: v.shots / 22 },
    { k: 'Shots on Target', v: v.sot.toFixed(1), w: v.sot / 9 },
  ];
  const seg = [
    { v: r.w, c: 'var(--bs-lime)', l: 'Won' },
    { v: r.d, c: 'var(--bs-neutral-300)', l: 'Drawn' },
    { v: r.l, c: 'var(--bs-blue-navy)', l: 'Lost' },
  ];
  const winPct = Math.round((r.w / r.p) * 100);
  let acc = 0; const R = 50, C = 2 * Math.PI * R;
  const selStyle = {
    appearance: 'none', WebkitAppearance: 'none', background: 'var(--bs-white)', border: '1px solid var(--border-mid)',
    color: 'var(--text-brand)', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 13, padding: '8px 30px 8px 12px',
    borderRadius: 'var(--radius-sm)', cursor: 'pointer',
  };
  return (
    <Panel pad={0}>
      <div style={{ padding: '20px 22px 4px' }}>
        <SlashHeading title="Season Stats" right={(
          <div style={{ position: 'relative', flex: '0 0 auto' }}>
            <select value={code} onChange={(e) => setCode(e.target.value)} style={selStyle}>
              {ordered.map((row) => <option key={row.t} value={row.t}>{PLw.T[row.t].name}</option>)}
            </select>
            <span style={{ position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none', color: 'var(--bs-blue-electric)', fontSize: 10 }}>▼</span>
          </div>
        )} />
      </div>
      {/* team + split */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '0 22px 14px' }}>
        <TeamDisc code={code} size={32} />
        <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 15, color: 'var(--text-primary)' }}>{PLw.T[code].name}</span>
        <span style={{ marginLeft: 'auto', display: 'inline-flex', alignItems: 'center', gap: 8 }}>
          <span style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--text-muted)' }}>Split</span>
          <span style={{ position: 'relative' }}>
            <select value={split} onChange={(e) => setSplit(e.target.value)} style={{ ...selStyle, fontSize: 13, padding: '9px 34px 9px 12px' }}>
              {['Season', 'Home', 'Away'].map((s) => <option key={s}>{s}</option>)}
            </select>
            <span style={{ position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none', color: 'rgb(25,25,25)', fontSize: 9 }}>▼</span>
          </span>
        </span>
      </div>
      {/* metric rows */}
      <div style={{ padding: '0 22px' }}>
        {metrics.map((m) => (
          <div key={m.k} style={{ padding: '8px 0', borderBottom: '1px solid var(--border-subtle)' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 5 }}>
              <span style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 11.5, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--text-muted)' }}>{m.k}</span>
              <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: 15, color: 'var(--text-brand)' }}>{m.v}</span>
            </div>
            <div style={{ height: 6, borderRadius: 999, background: 'var(--bs-neutral-200)', overflow: 'hidden' }}>
              <div style={{ width: Math.max(4, Math.min(100, m.w * 100)) + '%', height: '100%', background: 'var(--bs-blue-electric)', borderRadius: 999 }} />
            </div>
          </div>
        ))}
      </div>
      {/* W/D/L donut (season record from standings) */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 22, padding: '16px 22px 22px' }}>
        <svg width="116" height="116" viewBox="0 0 120 120" style={{ flex: '0 0 auto' }}>
          <g transform="rotate(-90 60 60)">
            {seg.map((s, i) => {
              const len = (s.v / r.p) * C; const off = (acc / r.p) * C; acc += s.v;
              return <circle key={i} cx="60" cy="60" r={R} fill="none" stroke={s.c} strokeWidth="15" strokeDasharray={`${len} ${C - len}`} strokeDashoffset={-off} />;
            })}
          </g>
          <text x="60" y="56" textAnchor="middle" fontFamily="var(--font-display)" fontWeight="700" fontSize="21" fill="var(--text-brand)">{winPct}%</text>
          <text x="60" y="72" textAnchor="middle" fontFamily="var(--font-display)" fontWeight="600" fontSize="8.5" letterSpacing="0.1em" fill="var(--text-muted)">WIN RATE</text>
        </svg>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--text-muted)', marginBottom: 10 }}>Season record</div>
          {seg.map((s) => (
            <div key={s.l} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 9 }}>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 9 }}>
                <span style={{ width: 11, height: 11, borderRadius: 2, background: s.c }} />
                <span style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 13, color: 'var(--text-body)' }}>{s.l}</span>
              </span>
              <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: 14, color: 'var(--text-brand)' }}>{s.v}</span>
            </div>
          ))}
        </div>
      </div>
    </Panel>
  );
}

Object.assign(window, { StandingsTable, TitleRace, GoalTrends });
