// views/Match.jsx — Detailed match view with pre/live/final states
function MatchView({ state, onRoute }) {
  const F = window.WCL_FEATURED;
  const [tab, setTab] = React.useState('stats');

  return (
    <div>
      <div className="page-head">
        <div>
          <div className="breadcrumb" style={{ display: 'flex', gap: 6, color: 'var(--foreground-muted)', fontSize: 12, marginBottom: 8 }}>
            <a className="link" onClick={() => onRoute('home')}>Live Today</a>
            <I.ChevR size={12} />
            <a className="link" onClick={() => onRoute('matches')}>Fixtures</a>
            <I.ChevR size={12} />
            <span>{F.stage}</span>
          </div>
          <h1 className="type-h1" style={{ margin: 0 }}>Argentina vs Croatia</h1>
          <div className="sub">{F.venue} · {F.city} · attendance {F.attendance.toLocaleString()}</div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="btn btn-secondary btn-sm"><I.Pin size={14} /> Watch</button>
          <button className="btn btn-secondary btn-sm">Share <I.ArrowUR size={14} /></button>
        </div>
      </div>

      <FeaturedMatch state={state} onRoute={onRoute} />

      <div className="tabs-row" style={{ marginTop: 16 }}>
        <button className={'tab-btn' + (tab === 'stats' ? ' active' : '')} onClick={() => setTab('stats')}>Stats</button>
        <button className={'tab-btn' + (tab === 'timeline' ? ' active' : '')} onClick={() => setTab('timeline')}>Timeline</button>
        <button className={'tab-btn' + (tab === 'lineups' ? ' active' : '')} onClick={() => setTab('lineups')}>Lineups</button>
        <button className={'tab-btn' + (tab === 'forecast' ? ' active' : '')} onClick={() => setTab('forecast')}>Forecast</button>
        <button className={'tab-btn' + (tab === 'commentary' ? ' active' : '')} onClick={() => setTab('commentary')}>Commentary</button>
      </div>

      {tab === 'stats' && <MatchStats state={state} />}
      {tab === 'timeline' && <MatchTimeline state={state} />}
      {tab === 'lineups' && <MatchLineups />}
      {tab === 'forecast' && <MatchForecast state={state} />}
      {tab === 'commentary' && <MatchCommentary state={state} />}
    </div>
  );
}

// ---------- Stats tab ----------
function MatchStats({ state }) {
  const F = window.WCL_FEATURED;
  const live = F.live;
  return (
    <div className="col2">
      <section className="panel">
        <div className="panel-head"><h3>Match stats</h3><span className="subtle" style={{ fontSize: 11 }}>{state === 'live' ? 'updating · last 0.3s' : 'final'}</span></div>
        <StatBar label="xG"        left={live.xG[0]} right={live.xG[1]} fmt={v => v.toFixed(2)} />
        <StatBar label="Shots"     left={live.shots[0]} right={live.shots[1]} />
        <StatBar label="On target" left={live.sot[0]}   right={live.sot[1]} />
        <StatBar label="Possession" left={live.possession[0]} right={live.possession[1]} max={100} fmt={v => v + '%'} />
        <StatBar label="Passes"    left={live.passes[0]} right={live.passes[1]} />
        <StatBar label="Pass acc." left={live.passAcc[0]} right={live.passAcc[1]} max={100} fmt={v => v + '%'} />
        <StatBar label="Corners"   left={live.corners[0]} right={live.corners[1]} />
        <StatBar label="Fouls"     left={live.fouls[0]} right={live.fouls[1]} />
        <StatBar label="Offsides"  left={live.offsides[0]} right={live.offsides[1]} />
        <div className="stat-row">
          <div className="side left">
            <span className="mono" style={{ fontSize: 13 }}>{live.yc[0]}</span>
            <span className="card-yc" />
            <span className="mono" style={{ fontSize: 13 }}>{live.rc[0]}</span>
            <span className="card-rc" />
          </div>
          <div className="name">Cards</div>
          <div className="side">
            <span className="card-yc" />
            <span className="mono" style={{ fontSize: 13 }}>{live.yc[1]}</span>
            <span className="card-rc" />
            <span className="mono" style={{ fontSize: 13 }}>{live.rc[1]}</span>
          </div>
        </div>
      </section>

      <section className="panel">
        <div className="panel-head"><h3>Pressure heatmap</h3><span className="subtle" style={{ fontSize: 11 }}>last 15 minutes · all attacking actions</span></div>
        <div className="pitch heatmap" style={{ maxWidth: '100%', aspectRatio: '105/68' }}>
          <div className="midline" />
          <div className="center" />
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 12, fontSize: 11, color: 'var(--foreground-muted)' }}>
          <span>← <strong style={{ color: 'var(--foreground)' }}>Argentina</strong> attacks</span>
          <span><strong style={{ color: 'var(--foreground)' }}>Croatia</strong> attacks →</span>
        </div>
        <div className="divider" />
        <div className="col3" style={{ gap: 10 }}>
          <div className="kpi" style={{ padding: 10 }}>
            <div className="kpi-label">Big chances</div>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 20, fontWeight: 600 }}><span>4</span><span style={{ color: 'var(--foreground-muted)' }}>2</span></div>
          </div>
          <div className="kpi" style={{ padding: 10 }}>
            <div className="kpi-label">PPDA</div>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 20, fontWeight: 600 }}><span>8.4</span><span style={{ color: 'var(--foreground-muted)' }}>11.2</span></div>
          </div>
          <div className="kpi" style={{ padding: 10 }}>
            <div className="kpi-label">Final-3rd touches</div>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 20, fontWeight: 600 }}><span>142</span><span style={{ color: 'var(--foreground-muted)' }}>78</span></div>
          </div>
        </div>
      </section>

      <section className="panel" style={{ gridColumn: '1 / -1' }}>
        <div className="panel-head"><h3>Win probability · minute by minute</h3>
          <span className="subtle" style={{ fontSize: 11 }}>poisson model · 50,000 sims per tick</span>
        </div>
        <WinProbChart data={window.WCL_FEATURED.winProbCurve} codes={['ARG', 'CRO']} />
      </section>
    </div>
  );
}

// ---------- Timeline ----------
function MatchTimeline({ state }) {
  const F = window.WCL_FEATURED;
  const events = state === 'pre' ? [] : F.events;
  return (
    <div className="col2">
      <section className="panel">
        <div className="panel-head"><h3>Event timeline</h3>{state === 'live' && <span className="hd-pulse"><span className="dot" /> Updating</span>}</div>
        {state === 'pre' && <div className="empty"><div className="empty-title">Match hasn't started</div><div className="empty-body">Kickoff in 1h 14m.</div></div>}
        <div className="timeline-events">
          {events.slice().reverse().map((e, i) => (
            <div key={i} className={'timeline-row ' + e.kind}>
              <span className="min">{e.min}'</span>
              <span className="badge-mini">
                {e.kind === 'goal' && <I.Trophy size={11} />}
                {e.kind === 'yc' && <span className="card-yc" />}
                {e.kind === 'rc' && <span className="card-rc" />}
                {e.kind === 'sub' && <I.TrendUp size={11} />}
                {e.kind === 'shot' && <I.Dot size={10} />}
                {e.kind === 'ht' && <I.Clock size={11} />}
              </span>
              <span className="text">
                {e.team !== '—' && e.team !== undefined && <Flag code={e.team} /> } {e.text}
                {e.score && <span className="mono" style={{ marginLeft: 8, color: 'var(--trophy)' }}>{e.score[0]} – {e.score[1]}</span>}
              </span>
            </div>
          ))}
        </div>
      </section>

      <section className="panel">
        <div className="panel-head"><h3>Shot chart</h3><span className="subtle" style={{ fontSize: 11 }}>size = xG · color = team</span></div>
        <div className="pitch" style={{ maxWidth: '100%', aspectRatio: '105/68', position: 'relative' }}>
          <div className="midline" />
          <div className="center" />
          {/* simulated shots */}
          {[
            { x: 88, y: 50, xg: 0.42, t: 'h', goal: true },
            { x: 80, y: 38, xg: 0.18, t: 'h' },
            { x: 86, y: 60, xg: 0.55, t: 'h', goal: true },
            { x: 75, y: 30, xg: 0.08, t: 'h' },
            { x: 84, y: 55, xg: 0.23, t: 'h' },
            { x: 78, y: 50, xg: 0.12, t: 'h' },
            { x: 14, y: 50, xg: 0.78, t: 'a', goal: true },
            { x: 22, y: 38, xg: 0.18, t: 'a' },
            { x: 26, y: 62, xg: 0.10, t: 'a' },
            { x: 18, y: 50, xg: 0.34, t: 'a' },
          ].map((s, i) => {
            const sz = 8 + s.xg * 28;
            const color = s.t === 'h' ? 'color-mix(in oklch, var(--brand) 75%, white)' : '#E78F8E';
            return (
              <div key={i} style={{
                position: 'absolute',
                left: s.x + '%', top: s.y + '%',
                width: sz, height: sz,
                marginLeft: -sz/2, marginTop: -sz/2,
                borderRadius: '999px',
                background: color,
                border: s.goal ? '2px solid var(--trophy)' : '1px solid rgba(0,0,0,0.3)',
                opacity: s.goal ? 1 : 0.7,
              }} />
            );
          })}
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 12 }}>
          <div style={{ display: 'flex', gap: 12, fontSize: 11, color: 'var(--foreground-muted)' }}>
            <span><span style={{ display: 'inline-block', width: 8, height: 8, borderRadius: 999, background: 'color-mix(in oklch, var(--brand) 75%, white)', marginRight: 6 }} /> Argentina</span>
            <span><span style={{ display: 'inline-block', width: 8, height: 8, borderRadius: 999, background: '#E78F8E', marginRight: 6 }} /> Croatia</span>
            <span><span style={{ display: 'inline-block', width: 8, height: 8, borderRadius: 999, background: 'transparent', border: '2px solid var(--trophy)', marginRight: 6 }} /> Goal</span>
          </div>
          <span className="mono subtle" style={{ fontSize: 11 }}>Total xG · 1.84 vs 1.12</span>
        </div>
      </section>
    </div>
  );
}

// ---------- Lineups ----------
function MatchLineups() {
  const F = window.WCL_FEATURED;
  const formations = {
    '4-3-3-home': [
      { n: 23, x: 50, y: 88 },
      { n: 4,  x: 80, y: 70 },
      { n: 13, x: 60, y: 72 },
      { n: 19, x: 40, y: 72 },
      { n: 3,  x: 20, y: 70 },
      { n: 7,  x: 65, y: 52 },
      { n: 5,  x: 50, y: 56 },
      { n: 20, x: 35, y: 52 },
      { n: 11, x: 78, y: 30 },
      { n: 9,  x: 50, y: 25 },
      { n: 10, x: 22, y: 30 },
    ],
  };
  return (
    <div className="col2">
      {[F.lineups.ARG, F.lineups.CRO].map((side, i) => (
        <section key={i} className="panel">
          <div className="panel-head">
            <h3>
              <TeamRow code={i === 0 ? 'ARG' : 'CRO'} />
              <span className="subtle" style={{ marginLeft: 12, fontWeight: 400, fontSize: 12 }}>{side.formation}</span>
            </h3>
          </div>
          <div style={{ position: 'relative' }}>
            <div className="pitch" style={{ maxWidth: 360, position: 'relative' }}>
              <div className="midline" />
              <div className="center" />
              {formations['4-3-3-home'].map((pos, k) => {
                const p = side.starters[k];
                return (
                  <div key={k} className={'player' + (i === 1 ? ' away' : '')} style={{ left: pos.x + '%', top: (i === 1 ? 100 - pos.y : pos.y) + '%' }} title={p.name}>
                    {p.n}
                    <span className="label">{p.name.split(' ').slice(-1)[0]}{p.captain ? ' (C)' : ''}</span>
                  </div>
                );
              })}
            </div>
          </div>
          <div className="divider" />
          <table className="table" style={{ fontSize: 12 }}>
            <thead>
              <tr><th>#</th><th>Player</th><th>Pos</th><th style={{ textAlign: 'right' }}>Rating</th></tr>
            </thead>
            <tbody>
              {side.starters.map(p => (
                <tr key={p.n}>
                  <td className="mono">{p.n}</td>
                  <td className="strong">{p.name}{p.captain ? <span className="mono subtle" style={{ marginLeft: 6, fontSize: 10 }}>(C)</span> : null}</td>
                  <td>{p.pos}</td>
                  <td className="mono" style={{ textAlign: 'right', color: p.n === 10 ? 'var(--success)' : 'var(--foreground)' }}>
                    {(5 + Math.random() * 4).toFixed(1)}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </section>
      ))}
    </div>
  );
}

// ---------- Forecast (model breakdown) ----------
function MatchForecast({ state }) {
  const F = window.WCL_FEATURED;
  return (
    <div className="col2">
      <section className="panel">
        <div className="panel-head"><h3>Pre-match odds · model vs market</h3></div>
        <table className="table">
          <thead>
            <tr>
              <th>Outcome</th>
              <th style={{ textAlign: 'right' }}>Market %</th>
              <th style={{ textAlign: 'right' }}>Model %</th>
              <th style={{ textAlign: 'right' }}>Δ</th>
              <th style={{ textAlign: 'right' }}>Best price</th>
            </tr>
          </thead>
          <tbody>
            {[
              { o: 'Argentina win', m: (1/F.odds.home*100).toFixed(1), p: (F.odds.modelHome * 100).toFixed(1), best: F.odds.home, fav: true },
              { o: 'Draw',          m: (1/F.odds.draw*100).toFixed(1), p: (F.odds.modelDraw * 100).toFixed(1), best: F.odds.draw },
              { o: 'Croatia win',   m: (1/F.odds.away*100).toFixed(1), p: (F.odds.modelAway * 100).toFixed(1), best: F.odds.away },
            ].map((r, i) => (
              <tr key={i}>
                <td className="strong">{r.o}</td>
                <td className="mono" style={{ textAlign: 'right' }}>{r.m}%</td>
                <td className="mono" style={{ textAlign: 'right' }}>{r.p}%</td>
                <td className="mono" style={{ textAlign: 'right', color: r.p > r.m ? 'var(--success)' : 'var(--destructive)' }}>
                  {(r.p > r.m ? '+' : '') + (r.p - r.m).toFixed(1)}%
                </td>
                <td className="mono" style={{ textAlign: 'right' }}>{r.best.toFixed(2)}</td>
              </tr>
            ))}
          </tbody>
        </table>

        <div className="divider" />
        <div style={{ fontSize: 12, color: 'var(--foreground-muted)', lineHeight: 1.6 }}>
          <span className="eyebrow" style={{ display: 'block', marginBottom: 6 }}>Model signal</span>
          Argentina hold a +0.40 xG/90 baseline edge over Croatia and a comfortable advantage in possession quality. Squad value differential (€612M vs €387M) adds 4.2pp to ARG. Croatia's recent form (D-L-W in qualifying) trimmed a further 1.8pp.
        </div>
      </section>

      <section className="panel">
        <div className="panel-head"><h3>Most likely scorelines</h3></div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
          {[
            ['2-1', 0.139], ['2-0', 0.122], ['1-1', 0.115],
            ['3-1', 0.092], ['3-0', 0.083], ['1-0', 0.072],
            ['1-2', 0.058], ['0-1', 0.040], ['3-2', 0.038],
          ].map(([s, p]) => (
            <div key={s} style={{
              padding: '12px',
              border: '1px solid var(--border)',
              borderRadius: 'var(--radius-md)',
              background: 'var(--surface)',
              textAlign: 'center',
            }}>
              <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-0.02em', color: s === '2-1' ? 'var(--pitch)' : 'var(--foreground)' }}>{s}</div>
              <div className="mono subtle" style={{ fontSize: 11, marginTop: 4 }}>{(p * 100).toFixed(1)}%</div>
              <div className="probbar model" style={{ marginTop: 8, height: 4 }}><span style={{ width: (p / 0.14) * 100 + '%' }} /></div>
            </div>
          ))}
        </div>
        <div className="divider" />
        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12 }}>
          <span className="subtle">Expected goals (model)</span>
          <span className="mono strong">2.41 total · ARG 1.62 / CRO 0.79</span>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, marginTop: 6 }}>
          <span className="subtle">Both teams to score</span>
          <span className="mono strong">52%</span>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, marginTop: 6 }}>
          <span className="subtle">Over 2.5</span>
          <span className="mono strong">61%</span>
        </div>
      </section>
    </div>
  );
}

// ---------- Commentary ----------
function MatchCommentary({ state }) {
  const C = state === 'pre' ? [] : window.WCL_COMMENTARY;
  return (
    <section className="panel">
      <div className="panel-head"><h3>Live commentary</h3>{state === 'live' && <span className="hd-pulse"><span className="dot" /> Updating</span>}</div>
      {state === 'pre' && <div className="empty"><div className="empty-title">No commentary yet</div><div className="empty-body">Coverage begins at kickoff.</div></div>}
      {C.length > 0 && (
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          {C.map((c, i) => (
            <div key={i} style={{
              display: 'grid', gridTemplateColumns: '52px 1fr', gap: 14,
              padding: '12px 0', borderBottom: '1px solid var(--border)'
            }}>
              <div className="mono" style={{ color: i === 0 ? 'var(--live-red)' : 'var(--foreground)', fontWeight: 600, fontSize: 13 }}>{c.min}'</div>
              <div style={{ fontSize: 13, color: 'var(--foreground-subtle)', lineHeight: 1.6 }}>{c.text}</div>
            </div>
          ))}
        </div>
      )}
    </section>
  );
}

Object.assign(window, { MatchView, MatchStats, MatchTimeline, MatchLineups, MatchForecast, MatchCommentary });
