// components.jsx — shared visual components for WCL
const TEAMS = window.WCL_TEAMS;

// ---------- Flag ----------
// Renders a tiny country flag via SVG using the team's flag colors + dir.
function Flag({ code, size = 'sm' }) {
  const t = TEAMS[code];
  if (!t) return <span className={'flag flag-' + size} aria-hidden />;
  const cls = 'flag' + (size === 'lg' ? ' flag-lg' : size === 'xl' ? ' flag-xl' : '');
  const colors = t.flag;
  const dir = t.dir;

  // viewBox-agnostic rendering inside fixed-aspect element
  let inner;
  if (dir === 'h') {
    const h = 100 / colors.length;
    inner = colors.map((c, i) => <rect key={i} x="0" y={i * h} width="100" height={h} fill={c} />);
  } else if (dir === 'v') {
    const w = 100 / colors.length;
    inner = colors.map((c, i) => <rect key={i} x={i * w} y="0" width={w} height="100" fill={c} />);
  } else if (dir === 'v23') {
    inner = <>
      <rect x="0" y="0" width="40" height="100" fill={colors[0]} />
      <rect x="40" y="0" width="60" height="100" fill={colors[1]} />
    </>;
  } else if (dir === 'cross') {
    // white field + red cross (England/Denmark/Switzerland)
    inner = <>
      <rect x="0" y="0" width="100" height="100" fill={colors[0]} />
      <rect x="42" y="0" width="16" height="100" fill={colors[1]} />
      <rect x="0" y="42" width="100" height="16" fill={colors[1]} />
    </>;
  } else if (dir === 'circle') {
    // Japan
    inner = <>
      <rect x="0" y="0" width="100" height="100" fill={colors[0]} />
      <circle cx="50" cy="50" r="20" fill={colors[1]} />
    </>;
  } else if (dir === 'd') {
    // Brazil — green / yellow diamond / blue disc
    inner = <>
      <rect x="0" y="0" width="100" height="100" fill={colors[0]} />
      <polygon points="50,15 90,50 50,85 10,50" fill={colors[1]} />
      <circle cx="50" cy="50" r="14" fill={colors[2]} />
    </>;
  } else if (dir === 'rok') {
    // South Korea — simplified white + center blue/red disc
    inner = <>
      <rect x="0" y="0" width="100" height="100" fill={colors[0]} />
      <path d="M30 50a20 20 0 0 1 40 0a10 10 0 0 1 -20 0a10 10 0 0 0 -20 0z" fill={colors[1]} />
      <path d="M70 50a20 20 0 0 0 -40 0a10 10 0 0 0 20 0a10 10 0 0 1 20 0z" fill={colors[2]} />
    </>;
  } else if (dir === 'aus') {
    // Australia — simplified blue + UK quadrant
    inner = <>
      <rect x="0" y="0" width="100" height="100" fill={colors[0]} />
      <rect x="0" y="0" width="50" height="50" fill={colors[0]} />
      <path d="M0 0l50 50M50 0L0 50" stroke={colors[1]} strokeWidth="6" />
      <rect x="22" y="0" width="6" height="50" fill={colors[1]} />
      <rect x="0" y="22" width="50" height="6" fill={colors[1]} />
      <circle cx="75" cy="60" r="6" fill={colors[1]} />
      <circle cx="60" cy="80" r="3" fill={colors[1]} />
      <circle cx="88" cy="80" r="3" fill={colors[1]} />
      <circle cx="75" cy="30" r="3" fill={colors[1]} />
      <circle cx="90" cy="40" r="3" fill={colors[1]} />
    </>;
  } else if (dir === 'qat') {
    inner = <>
      <rect x="0" y="0" width="32" height="100" fill={colors[1]} />
      <rect x="32" y="0" width="68" height="100" fill={colors[0]} />
    </>;
  } else if (dir === 'h5') {
    // Costa Rica — 5 horizontal stripes (1/6, 1/6, 2/6, 1/6, 1/6)
    inner = <>
      <rect x="0" y="0"  width="100" height="16.66" fill={colors[0]} />
      <rect x="0" y="16.66" width="100" height="16.66" fill={colors[1]} />
      <rect x="0" y="33.33" width="100" height="33.33" fill={colors[2]} />
      <rect x="0" y="66.66" width="100" height="16.66" fill={colors[3]} />
      <rect x="0" y="83.33" width="100" height="16.66" fill={colors[4]} />
    </>;
  } else if (dir === 'norcross') {
    // Norway — red field with blue cross outlined in white
    inner = <>
      <rect x="0" y="0" width="100" height="100" fill={colors[0]} />
      <rect x="36" y="0" width="14" height="100" fill={colors[1]} />
      <rect x="0" y="42" width="100" height="14" fill={colors[1]} />
      <rect x="39" y="0" width="8" height="100" fill={colors[2]} />
      <rect x="0" y="45" width="100" height="8" fill={colors[2]} />
    </>;
  } else if (dir === 'tur') {
    // Türkiye — red field, white crescent + star (simplified)
    inner = <>
      <rect x="0" y="0" width="100" height="100" fill={colors[0]} />
      <circle cx="36" cy="50" r="18" fill={colors[1]} />
      <circle cx="42" cy="50" r="14" fill={colors[0]} />
      <polygon points="62,50 56,46 58,52 52,52 57,56 55,62 62,58 69,62 67,56 72,52 66,52 68,46" fill={colors[1]} />
    </>;
  } else if (dir === 'cze') {
    // Czechia — white top, red bottom, blue triangle on hoist
    inner = <>
      <rect x="0" y="0"  width="100" height="50" fill={colors[0]} />
      <rect x="0" y="50" width="100" height="50" fill={colors[1]} />
      <polygon points="0,0 50,50 0,100" fill={colors[2]} />
    </>;
  } else if (dir === 'quad') {
    // Panama — white/red top, blue/white bottom — 4 quadrants
    inner = <>
      <rect x="0"  y="0"  width="50" height="50" fill={colors[0]} />
      <rect x="50" y="0"  width="50" height="50" fill={colors[1]} />
      <rect x="0"  y="50" width="50" height="50" fill={colors[2]} />
      <rect x="50" y="50" width="50" height="50" fill={colors[3]} />
      <polygon points="25,30 28,42 38,42 30,49 33,60 25,53 17,60 20,49 12,42 22,42" fill={colors[1]} transform="scale(0.6) translate(8 8)" />
    </>;
  } else if (dir === 'jam') {
    // Jamaica — black/green triangles with yellow X (saltire)
    inner = <>
      <polygon points="0,0 50,50 0,100" fill={colors[2]} />
      <polygon points="100,0 50,50 100,100" fill={colors[2]} />
      <polygon points="0,0 50,50 100,0" fill={colors[0]} />
      <polygon points="0,100 50,50 100,100" fill={colors[0]} />
      <path d="M0 0L100 100M100 0L0 100" stroke={colors[1]} strokeWidth="14" />
    </>;
  } else if (dir === 'algv') {
    // Algeria — green/white vertical halves with red crescent
    inner = <>
      <rect x="0" y="0" width="50" height="100" fill={colors[0]} />
      <rect x="50" y="0" width="50" height="100" fill={colors[1]} />
      <circle cx="50" cy="50" r="20" fill="#C8102E" />
      <circle cx="56" cy="50" r="16" fill={colors[1]} />
    </>;
  } else if (dir === 'uae') {
    // UAE — red vertical hoist + green/white/black horizontal stripes
    inner = <>
      <rect x="0" y="0" width="25" height="100" fill={colors[0]} />
      <rect x="25" y="0" width="75" height="33.33" fill={colors[1]} />
      <rect x="25" y="33.33" width="75" height="33.33" fill={colors[2]} />
      <rect x="25" y="66.66" width="75" height="33.33" fill={colors[3]} />
    </>;
  } else if (dir === 'cod') {
    // DR Congo — sky blue with yellow diagonal + red stripe
    inner = <>
      <rect x="0" y="0" width="100" height="100" fill={colors[0]} />
      <polygon points="0,80 80,0 100,0 100,20 20,100 0,100" fill={colors[1]} />
      <polygon points="0,90 90,0 100,0 100,10 10,100 0,100" fill={colors[2]} />
      <polygon points="22,22 26,30 35,30 28,36 30,44 22,40 14,44 16,36 9,30 18,30" fill={colors[1]} />
    </>;
  } else if (dir === 'chil') {
    // Chile — white/red horizontal split + blue canton + star
    inner = <>
      <rect x="0" y="0" width="100" height="50" fill={colors[0]} />
      <rect x="0" y="50" width="100" height="50" fill={colors[1]} />
      <rect x="0" y="0" width="50" height="50" fill="#0039A6" />
      <polygon points="25,18 28,30 38,30 30,37 33,48 25,41 17,48 20,37 12,30 22,30" fill="#FFFFFF" />
    </>;
  } else if (dir === 'zam') {
    // Zambia — green field with orange/black/red tricolor at right + eagle (simplified)
    inner = <>
      <rect x="0" y="0" width="100" height="100" fill={colors[0]} />
      <rect x="60" y="50" width="13" height="50" fill={colors[1]} />
      <rect x="73" y="50" width="13" height="50" fill={colors[2]} />
      <rect x="86" y="50" width="14" height="50" fill={colors[3]} />
      <circle cx="73" cy="25" r="10" fill={colors[1]} />
    </>;
  } else if (dir === 'jor') {
    // Jordan — 3 horizontal stripes + red triangle on hoist + white star
    inner = <>
      <rect x="0" y="0"  width="100" height="33.33" fill={colors[0]} />
      <rect x="0" y="33.33" width="100" height="33.33" fill={colors[1]} />
      <rect x="0" y="66.66" width="100" height="33.33" fill={colors[2]} />
      <polygon points="0,0 50,50 0,100" fill={colors[3]} />
      <polygon points="14,46 17,52 23,52 18,56 20,62 14,58 8,62 10,56 5,52 11,52" fill={colors[1]} />
    </>;
  } else if (dir === 'rsa') {
    // South Africa — Y-shape simplified
    inner = <>
      <rect x="0" y="0" width="100" height="50" fill={colors[3]} />
      <rect x="0" y="50" width="100" height="50" fill={colors[3]} />
      <rect x="0" y="0" width="100" height="50" fill={colors[4]} />
      <rect x="0" y="50" width="100" height="50" fill={colors[5]} />
      <polygon points="0,0 50,50 0,100" fill={colors[2]} />
      <polygon points="0,15 35,50 0,85" fill={colors[1]} />
      <polygon points="0,28 22,50 0,72" fill={colors[0]} />
    </>;
  } else if (dir === 'bih') {
    // Bosnia — blue field with yellow triangle and white stars
    inner = <>
      <rect x="0" y="0" width="100" height="100" fill={colors[0]} />
      <polygon points="20,0 100,0 100,100" fill={colors[1]} />
      {[15, 35, 55, 75].map((x, i) => <circle key={i} cx={x + 10} cy={x + 10} r="3" fill="#FFFFFF" />)}
    </>;
  } else if (dir === 'cuw') {
    // Curaçao — blue with yellow horizontal stripe and two white stars
    inner = <>
      <rect x="0" y="0" width="100" height="100" fill={colors[0]} />
      <rect x="0" y="62" width="100" height="10" fill={colors[1]} />
      <polygon points="20,28 23,36 31,36 25,42 27,50 20,46 13,50 15,42 9,36 17,36" fill={colors[2]} />
      <polygon points="30,18 33,26 41,26 35,32 37,40 30,36 23,40 25,32 19,26 27,26" fill={colors[2]} />
    </>;
  } else if (dir === 'cpv') {
    // Cape Verde — blue field with white/red horizontal stripes + 10 star ring
    inner = <>
      <rect x="0" y="0" width="100" height="100" fill={colors[0]} />
      <rect x="0" y="58" width="100" height="10" fill={colors[1]} />
      <rect x="0" y="63" width="100" height="2" fill={colors[2]} />
      {Array.from({ length: 10 }).map((_, i) => {
        const a = (i / 10) * Math.PI * 2 - Math.PI / 2;
        const r = 12;
        const cx = 33 + r * Math.cos(a);
        const cy = 63 + r * Math.sin(a);
        return <circle key={i} cx={cx} cy={cy} r="1.6" fill={colors[2]} />;
      })}
    </>;
  } else if (dir === 'solid') {
    inner = <>
      <rect x="0" y="0" width="100" height="100" fill={colors[0]} />
      <circle cx="50" cy="50" r="22" fill="#FFF" />
      <circle cx="55" cy="50" r="18" fill={colors[0]} />
    </>;
  } else {
    inner = <rect x="0" y="0" width="100" height="100" fill={colors[0]} />;
  }

  return (
    <span className={cls} title={t.name}>
      <svg viewBox="0 0 100 100" preserveAspectRatio="none" width="100%" height="100%">
        {inner}
      </svg>
    </span>
  );
}

// ---------- TeamRow ----------
function TeamRow({ code, reverse, big, sub }) {
  const t = TEAMS[code];
  const name = t ? t.name : code;
  const cls = 'team-row' + (reverse ? ' away' : '');
  if (reverse) {
    return (
      <span className={cls} style={{ gap: big ? 12 : 8 }}>
        <span style={{ textAlign: 'right' }}>
          <span style={{ fontWeight: 600, fontSize: big ? 18 : 13, display: 'block', color: 'var(--foreground)' }}>{name}</span>
          {sub && <span className="subtle" style={{ fontSize: 11, display: 'block', marginTop: 2 }}>{sub}</span>}
        </span>
        <Flag code={code} size={big ? 'lg' : 'sm'} />
      </span>
    );
  }
  return (
    <span className={cls} style={{ gap: big ? 12 : 8 }}>
      <Flag code={code} size={big ? 'lg' : 'sm'} />
      <span>
        <span style={{ fontWeight: 600, fontSize: big ? 18 : 13, display: 'block', color: 'var(--foreground)' }}>{name}</span>
        {sub && <span className="subtle" style={{ fontSize: 11, display: 'block', marginTop: 2 }}>{sub}</span>}
      </span>
    </span>
  );
}

// ---------- StatBar (live stat row, paired numbers) ----------
function StatBar({ label, left, right, max, fmt = (x) => x }) {
  const mx = max != null ? max : Math.max(left, right, 1);
  const lp = (left / mx) * 100;
  const rp = (right / mx) * 100;
  return (
    <div className="stat-row">
      <div className="side left">
        <div className="bar left"><span style={{ width: lp + '%' }} /></div>
        <div className="val">{fmt(left)}</div>
      </div>
      <div className="name">{label}</div>
      <div className="side">
        <div className="val">{fmt(right)}</div>
        <div className="bar right"><span style={{ width: rp + '%' }} /></div>
      </div>
    </div>
  );
}

// ---------- WinProb stacked bar ----------
function WinProb({ home, draw, away, small, codes }) {
  return (
    <div className={'wp-bar' + (small ? ' sm' : '')}>
      <div className="home" style={{ width: (home * 100) + '%' }}>
        {home >= 0.10 && (small ? Math.round(home * 100) + '%' : (codes ? codes[0] + ' ' : '') + Math.round(home * 100) + '%')}
      </div>
      <div className="draw" style={{ width: (draw * 100) + '%' }}>
        {draw >= 0.10 && (small ? Math.round(draw * 100) + '%' : 'Draw ' + Math.round(draw * 100) + '%')}
      </div>
      <div className="away" style={{ width: (away * 100) + '%' }}>
        {away >= 0.10 && (small ? Math.round(away * 100) + '%' : (codes ? codes[1] + ' ' : '') + Math.round(away * 100) + '%')}
      </div>
    </div>
  );
}

// ---------- Win Prob over time chart ----------
function WinProbChart({ data, codes }) {
  // data: [[min, home, draw, away], ...]
  const W = 600, H = 220, P = { l: 28, r: 12, t: 14, b: 22 };
  const xMax = 90;
  const x = (m) => P.l + (m / xMax) * (W - P.l - P.r);
  const y = (v) => P.t + (1 - v) * (H - P.t - P.b);

  const homeLine = data.map(d => x(d[0]) + ',' + y(d[1])).join(' ');
  const drawLine = data.map(d => x(d[0]) + ',' + y(d[2])).join(' ');
  const awayLine = data.map(d => x(d[0]) + ',' + y(d[3])).join(' ');

  const grid = [0, 0.25, 0.5, 0.75, 1].map(v =>
    <line key={v} x1={P.l} x2={W - P.r} y1={y(v)} y2={y(v)} stroke="var(--border)" strokeDasharray="3 3" />
  );
  const yLabels = [0, 0.25, 0.5, 0.75, 1].map(v =>
    <text key={v} x={P.l - 6} y={y(v) + 3} textAnchor="end" fontSize="10" fill="var(--foreground-muted)">{Math.round(v * 100)}</text>
  );

  // event markers (goals)
  const goals = (window.WCL_FEATURED.events || []).filter(e => e.kind === 'goal');

  return (
    <div className="chart-wp">
      <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none">
        {grid}
        {yLabels}
        {/* x-axis tick marks at 15-minute intervals */}
        {[0,15,30,45,60,75,90].map(m =>
          <g key={m}>
            <line x1={x(m)} x2={x(m)} y1={H - P.b} y2={H - P.b + 4} stroke="var(--foreground-muted)" />
            <text x={x(m)} y={H - 6} textAnchor="middle" fontSize="10" fill="var(--foreground-muted)">{m === 45 ? 'HT' : m === 90 ? 'FT' : m + "'"}</text>
          </g>
        )}
        {/* lines */}
        <polyline points={drawLine} fill="none" stroke="var(--foreground-muted)" strokeWidth="1.5" strokeDasharray="4 4" />
        <polyline points={awayLine} fill="none" stroke="#E78F8E" strokeWidth="2" />
        <polyline points={homeLine} fill="none" stroke={`color-mix(in oklch, var(--brand) 70%, white)`} strokeWidth="2.5" />
        {/* goals */}
        {goals.map((g, i) =>
          <g key={i}>
            <line x1={x(g.min)} x2={x(g.min)} y1={P.t} y2={H - P.b} stroke="var(--trophy)" strokeOpacity="0.5" strokeDasharray="2 3" />
            <circle cx={x(g.min)} cy={P.t} r="3" fill="var(--trophy)" />
          </g>
        )}
        {/* current minute marker */}
        <line x1={x(window.WCL_FEATURED.live.minute)} x2={x(window.WCL_FEATURED.live.minute)} y1={P.t} y2={H - P.b} stroke="var(--live-red)" strokeWidth="2" />
      </svg>
      <div className="legend">
        <span><span className="sw" style={{ background: 'color-mix(in oklch, var(--brand) 70%, white)' }} /> {codes[0]} win</span>
        <span><span className="sw" style={{ background: 'var(--foreground-muted)' }} /> Draw</span>
        <span><span className="sw" style={{ background: '#E78F8E' }} /> {codes[1]} win</span>
        <span><span className="sw" style={{ background: 'var(--trophy)' }} /> Goal</span>
      </div>
    </div>
  );
}

// ---------- Sparkline ----------
function Sparkline({ data, color = 'currentColor', fill = false, height = 36 }) {
  const W = 100, H = height;
  const mn = Math.min(...data), mx = Math.max(...data);
  const rng = mx - mn || 1;
  const pts = data.map((v, i) => {
    const x = (i / (data.length - 1)) * W;
    const y = H - 2 - ((v - mn) / rng) * (H - 4);
    return `${x},${y}`;
  }).join(' ');
  return (
    <svg className="chart-spark" viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none">
      {fill && <polygon points={`0,${H} ${pts} ${W},${H}`} fill={color} opacity="0.15" />}
      <polyline points={pts} fill="none" stroke={color} strokeWidth="1.5" strokeLinejoin="round" strokeLinecap="round" />
    </svg>
  );
}

// ---------- Form row (W/D/L badges) ----------
function FormRow({ form }) {
  return (
    <span className="form-row">
      {form.map((r, i) => <span key={i} className={'form-dot ' + r}>{r}</span>)}
    </span>
  );
}

// ---------- Donut (model probability ring) ----------
function Donut({ value, color = 'var(--pitch)', size = 64, stroke = 6, label }) {
  const r = (size - stroke) / 2;
  const c = 2 * Math.PI * r;
  const off = c - value * c;
  return (
    <div style={{ position: 'relative', width: size, height: size }}>
      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="var(--muted)" strokeWidth={stroke} />
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke={color} strokeWidth={stroke}
                strokeLinecap="round"
                strokeDasharray={c} strokeDashoffset={off}
                transform={`rotate(-90 ${size/2} ${size/2})`} />
      </svg>
      <div style={{
        position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 13, fontWeight: 600, color: 'var(--foreground)', fontVariantNumeric: 'tabular-nums'
      }}>{label || Math.round(value * 100) + '%'}</div>
    </div>
  );
}

Object.assign(window, { Flag, TeamRow, StatBar, WinProb, WinProbChart, Sparkline, FormRow, Donut });
