/* global React, Panel, SlashHeading, TeamDisc */
// V2 graph — interactive "Attack vs Defence" quadrant scatter, derived from standings (GF/GA).
const PLg = window.PL;

function AttackDefence() {
  const rows = PLg.table;
  const [hov, setHov] = React.useState(null);
  const [pin, setPin] = React.useState(null);
  const active = hov || pin;
  const W = 560, H = 300, padL = 48, padR = 18, padT = 16, padB = 42;
  const gfs = rows.map((r) => r.gf), gas = rows.map((r) => r.ga);
  const gfMin = Math.min(...gfs) - 4, gfMax = Math.max(...gfs) + 5;
  const gaMin = Math.min(...gas) - 4, gaMax = Math.max(...gas) + 5;
  const x = (gf) => padL + (gf - gfMin) / (gfMax - gfMin) * (W - padL - padR);
  const y = (ga) => padT + (ga - gaMin) / (gaMax - gaMin) * (H - padT - padB); // low GA = top
  const mean = (a) => a.reduce((s, v) => s + v, 0) / a.length;
  const avgGf = mean(gfs), avgGa = mean(gas);
  const mx = x(avgGf), my = y(avgGa);
  const quad = [
    { tx: W - padR - 6, ty: padT + 14, anchor: 'end', label: 'COMPLETE SIDES' },
    { tx: padL + 6, ty: padT + 14, anchor: 'start', label: 'HARD TO BEAT' },
    { tx: W - padR - 6, ty: H - padB - 6, anchor: 'end', label: 'ENTERTAINERS' },
    { tx: padL + 6, ty: H - padB - 6, anchor: 'start', label: 'STRUGGLERS' },
  ];
  const a = active ? rows.find((r) => r.t === active) : null;
  return (
    <Panel pad={0}>
      <div style={{ padding: '20px 22px 4px' }}>
        <SlashHeading title="Attack vs Defence" kicker="Goals scored vs conceded · all 20 teams" />
      </div>
      <div style={{ padding: '0 14px 6px' }}>
        <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height: 'auto', display: 'block' }} onMouseLeave={() => setHov(null)}>
          {/* quadrant tints */}
          <rect x={mx} y={padT} width={W - padR - mx} height={my - padT} fill="rgba(209,242,6,0.10)" />
          <rect x={padL} y={my} width={mx - padL} height={H - padB - my} fill="rgba(220,38,38,0.06)" />
          {/* frame */}
          <rect x={padL} y={padT} width={W - padL - padR} height={H - padT - padB} fill="none" stroke="var(--border-subtle)" strokeWidth="1" />
          {/* median lines */}
          <line x1={mx} y1={padT} x2={mx} y2={H - padB} stroke="var(--border-mid)" strokeWidth="1" strokeDasharray="4 4" />
          <line x1={padL} y1={my} x2={W - padR} y2={my} stroke="var(--border-mid)" strokeWidth="1" strokeDasharray="4 4" />
          {/* quadrant labels */}
          {quad.map((q) => (
            <text key={q.label} x={q.tx} y={q.ty} textAnchor={q.anchor} fontFamily="var(--font-display)" fontWeight="700" fontSize="9.5" letterSpacing="0.08em" fill="var(--text-muted)">{q.label}</text>
          ))}
          {/* axis titles */}
          <text x={padL + (W - padL - padR) / 2} y={H - 6} textAnchor="middle" fontFamily="var(--font-display)" fontWeight="600" fontSize="10" letterSpacing="0.1em" fill="var(--text-brand)">GOALS SCORED →</text>
          <text x={13} y={padT + (H - padT - padB) / 2} textAnchor="middle" fontFamily="var(--font-display)" fontWeight="600" fontSize="10" letterSpacing="0.1em" fill="var(--text-brand)" transform={`rotate(-90 13 ${padT + (H - padT - padB) / 2})`}>← FEWER CONCEDED</text>
          {/* dots */}
          {rows.map((r) => {
            const on = active === r.t, dim = active && !on;
            const c = PLg.T[r.t].c;
            return (
              <g key={r.t} style={{ cursor: 'pointer', transition: 'opacity .15s' }} opacity={dim ? 0.28 : 1}
                onMouseEnter={() => setHov(r.t)} onClick={() => setPin(pin === r.t ? null : r.t)}>
                <circle cx={x(r.gf)} cy={y(r.ga)} r={on ? 9 : 6} fill={c} stroke="#fff" strokeWidth={on ? 2 : 1.2} />
                {on && <circle cx={x(r.gf)} cy={y(r.ga)} r="13" fill="none" stroke={c} strokeWidth="1.5" opacity="0.5" />}
              </g>
            );
          })}
          {/* tooltip */}
          {a && (() => {
            const cxp = x(a.gf), cyp = y(a.ga);
            const bw = 232, bh = 46; let bx = cxp + 14, by = cyp - bh - 10;
            if (bx + bw > W - 4) bx = cxp - bw - 14;
            if (bx < 4) bx = 4;
            if (by < 4) by = cyp + 14;
            if (by + bh > H - 4) by = H - bh - 4;
            return (
              <g pointerEvents="none">
                <rect x={bx} y={by} width={bw} height={bh} rx="5" fill="var(--bs-blue-navy)" />
                <text x={bx + 13} y={by + 19} fontFamily="var(--font-display)" fontWeight="700" fontSize="13" fill="#fff">{PLg.T[a.t].name}</text>
                <text x={bx + 13} y={by + 36} fontFamily="var(--font-mono)" fontSize="10.5" fill="var(--bs-lime)">Scored {a.gf} · Conceded {a.ga} · GD {a.gd > 0 ? '+' : ''}{a.gd}</text>
              </g>
            );
          })()}
        </svg>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '10px 22px 20px', borderTop: '1px solid var(--border-subtle)', flexWrap: 'wrap', gap: 8 }}>
        <span style={{ fontFamily: 'var(--font-body)', fontSize: 12.5, color: 'var(--text-muted)' }}>
          {a ? <span><strong style={{ color: 'var(--text-brand)' }}>{PLg.T[a.t].name}</strong> — {a.gf} scored, {a.ga} conceded</span> : 'Hover or tap a team to inspect · dashed lines = league average'}
        </span>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-muted)' }}>Avg {avgGf.toFixed(0)} GF · {avgGa.toFixed(0)} GA</span>
      </div>
    </Panel>
  );
}

function FormationXI() {
  const xi = PLg.teamOfSeason;
  const [view, setView] = React.useState(PLg.totViews[0]);
  const Marker = ({ p }) => (
    <div style={{ position: 'absolute', left: p.x + '%', top: p.y + '%', transform: 'translate(-50%, -50%)', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4, width: 84 }}>
      <div style={{ position: 'relative' }}>
        <Jersey code={p.t} number={p.n} size={42} />
        <span style={{ position: 'absolute', bottom: -2, left: -8 }}><TeamDisc code={p.t} size={16} /></span>
        <span style={{
          position: 'absolute', top: -7, right: -12, fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: 11,
          padding: '2px 6px', borderRadius: 4, display: 'inline-flex', alignItems: 'center', gap: 3,
          background: p.top ? 'var(--bs-blue-electric)' : 'var(--bs-lime)', color: p.top ? '#fff' : 'var(--bs-blue-navy)',
        }}>{p.r.toFixed(2)}{p.top && <span style={{ fontSize: 9 }}>★</span>}</span>
      </div>
      <span style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 12, color: '#fff', whiteSpace: 'nowrap' }}>{p.name}</span>
    </div>
  );
  return (
    <Panel pad={0}>
      <div style={{ padding: '20px 22px 14px' }}>
        <SlashHeading title="Team of the Season" right={(
          <div style={{ position: 'relative', flex: '0 0 auto' }}>
            <select value={view} onChange={(e) => setView(e.target.value)} style={{
              appearance: 'none', WebkitAppearance: 'none', background: 'var(--bs-white)', border: '1px solid rgb(229,229,229)',
              color: 'rgb(25,25,25)', fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 14, lineHeight: '24px', padding: '10px 38px 10px 14px',
              borderRadius: 2, cursor: 'pointer',
            }}>
              {PLg.totViews.map((o) => <option key={o}>{o}</option>)}
            </select>
            <span style={{ position: 'absolute', right: 14, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none', color: 'rgb(25,25,25)', fontSize: 10 }}>▼</span>
          </div>
        )} />
      </div>
      {/* pitch */}
      <div style={{ position: 'relative', margin: '0 auto 16px', height: 470, maxWidth: '100%', aspectRatio: '46 / 60', background: '#0B0B0B', borderRadius: 'var(--radius-md)', overflow: 'hidden' }}>
        <svg viewBox="0 0 460 600" preserveAspectRatio="none" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
          {/* mown stripes */}
          {Array.from({ length: 10 }).map((_, i) => (
            <rect key={i} x="0" y={i * 60} width="460" height="60" fill={i % 2 ? '#111111' : '#0B0B0B'} />
          ))}
          {(() => {
            const L = { fill: 'none', stroke: 'rgba(255,255,255,0.5)', strokeWidth: 1.6 };
            return (
              <g>
                <rect x="12" y="12" width="436" height="576" {...L} />
                <line x1="12" y1="300" x2="448" y2="300" {...L} />
                <circle cx="230" cy="300" r="54" {...L} />
                <circle cx="230" cy="300" r="2.5" fill="rgba(255,255,255,0.6)" />
                {/* top half */}
                <rect x="140" y="12" width="180" height="92" {...L} />
                <rect x="190" y="12" width="80" height="38" {...L} />
                <circle cx="230" cy="68" r="2.5" fill="rgba(255,255,255,0.6)" />
                <path d="M 212 104 A 40 40 0 0 0 248 104" {...L} />
                <rect x="206" y="8" width="48" height="5" fill="rgba(255,255,255,0.6)" />
                {/* bottom half */}
                <rect x="140" y="496" width="180" height="92" {...L} />
                <rect x="190" y="550" width="80" height="38" {...L} />
                <circle cx="230" cy="532" r="2.5" fill="rgba(255,255,255,0.6)" />
                <path d="M 212 496 A 40 40 0 0 1 248 496" {...L} />
                <rect x="206" y="587" width="48" height="5" fill="rgba(255,255,255,0.6)" />
                {/* corner arcs */}
                <path d="M 12 22 A 10 10 0 0 0 22 12" {...L} />
                <path d="M 438 12 A 10 10 0 0 0 448 22" {...L} />
                <path d="M 12 578 A 10 10 0 0 1 22 588" {...L} />
                <path d="M 438 588 A 10 10 0 0 1 448 578" {...L} />
              </g>
            );
          })()}
        </svg>
        {xi.map((p) => <Marker key={p.name} p={p} />)}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '0 22px 20px', flexWrap: 'wrap' }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7 }}><span style={{ width: 11, height: 11, borderRadius: 3, background: 'var(--bs-lime)' }} /><span style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--text-muted)' }}>Rating</span></span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7 }}><span style={{ width: 11, height: 11, borderRadius: 3, background: 'var(--bs-blue-electric)' }} /><span style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--text-muted)' }}>Star man</span></span>
      </div>
    </Panel>
  );
}

Object.assign(window, { AttackDefence, FormationXI });