// Track component — renders the selected circuit, cars on path, sector overlay, turn markers
const { useState, useEffect, useRef, useMemo } = React;

function Track({ track, cars, focusedNo, onFocus, onZoom, lap, lapsTotal, timeOfDay, weather, showSectors, showTurns, raceProgress, carClass }) {
  const pathRef = useRef(null);
  const [pathLen, setPathLen] = useState(0);

  // Re-measure when the track path changes
  useEffect(() => {
    if (pathRef.current) setPathLen(pathRef.current.getTotalLength());
  }, [track.id]);

  // Color tokens for time of day — calm dark surface, no grass.
  const sky = timeOfDay === "night" ? "#03060B" : timeOfDay === "dusk" ? "#0E0710" : "#000000";
  const asphalt = timeOfDay === "night" ? "#1A1F25" : timeOfDay === "dusk" ? "#22191F" : "#262629";
  const asphaltDark = timeOfDay === "night" ? "#0E1218" : timeOfDay === "dusk" ? "#160F14" : "#15151A";
  const paint = "#D8D2C5";
  const trackStroke = timeOfDay === "night" ? "#3A6E8A" : timeOfDay === "dusk" ? "#7E5A6E" : "#5BB7E2";
  const trackGhost = timeOfDay === "night" ? "#0F1F2A" : timeOfDay === "dusk" ? "#1F1218" : "#0E1F2A";

  // Compute car positions along the path, with lateral offset for side-by-side racing
  const carNodes = useMemo(() => {
    if (!pathLen || !pathRef.current) return [];
    const TRAIL = 6;
    const STEP = 5;
    const path = pathRef.current;

    // First pass: compute raw positions
    const raw = cars.map(c => {
      const t = ((raceProgress + c._offset) % 1) * pathLen;
      const p = path.getPointAtLength(t);
      const p2 = path.getPointAtLength((t + 2) % pathLen);
      const angle = Math.atan2(p2.y - p.y, p2.x - p.x) * 180 / Math.PI;
      const trail = [];
      for (let k = 1; k <= TRAIL; k++) {
        const tt = (t - k * STEP + pathLen) % pathLen;
        const tp = path.getPointAtLength(tt);
        trail.push({ x: tp.x, y: tp.y });
      }
      return { ...c, x: p.x, y: p.y, angle, trail, _t: t, _rad: Math.atan2(p2.y - p.y, p2.x - p.x) };
    });

    // Second pass: offset cars laterally when close to each other (side-by-side)
    const PROXIMITY = 28;
    const LATERAL_OFFSET = 8;
    return raw.map((car, i) => {
      let latOff = 0;
      for (let j = 0; j < raw.length; j++) {
        if (i === j) continue;
        const dx = car.x - raw[j].x, dy = car.y - raw[j].y;
        const dist = Math.sqrt(dx * dx + dy * dy);
        if (dist < PROXIMITY) {
          // offset perpendicular to heading — alternate inside/outside
          const side = car.pos < raw[j].pos ? -1 : 1;
          latOff = side * LATERAL_OFFSET * (1 - dist / PROXIMITY);
        }
      }
      // Apply perpendicular offset
      const nx = -Math.sin(car._rad);
      const ny = Math.cos(car._rad);
      return {
        ...car,
        x: car.x + nx * latOff,
        y: car.y + ny * latOff,
        trail: car.trail.map(tp => ({ x: tp.x + nx * latOff * 0.6, y: tp.y + ny * latOff * 0.6 })),
      };
    });
  }, [cars, raceProgress, pathLen, track.id]);

  // DRS / battle pairs — cars within 10px on the path are visually linked
  const battlePairs = useMemo(() => {
    if (!pathLen) return [];
    const out = [];
    for (let i = 0; i < carNodes.length; i++) {
      for (let j = i+1; j < carNodes.length; j++) {
        const a = carNodes[i], b = carNodes[j];
        const dx = a.x - b.x, dy = a.y - b.y;
        const dist = Math.sqrt(dx*dx + dy*dy);
        if (dist < 22 && Math.abs(a.pos - b.pos) === 1) out.push({ a, b, dist });
      }
    }
    return out;
  }, [carNodes, pathLen]);

  // Focused car: high-brake hotspots along the path (Laguna's T2 + Corkscrew etc.)
  const brakeHotspots = useMemo(() => {
    if (!pathLen || !pathRef.current || !focusedNo) return [];
    const focused = cars.find(c => c.no === focusedNo);
    if (!focused) return [];
    const tele = window.APEX_DATA.generateTelemetry(focused.no);
    const out = [];
    for (let i = 0; i < tele.length; i++) {
      if (tele[i].brake > 60) {
        const t = (i / tele.length) * pathLen;
        const p = pathRef.current.getPointAtLength(t);
        out.push({ x: p.x, y: p.y, intensity: tele[i].brake / 100 });
      }
    }
    return out;
  }, [focusedNo, cars, pathLen, track.id]);

  // Corner chevrons — sample N points along the path near each turn marker.
  // For each turn we drop the cluster of chevrons just BEFORE the apex (entry side),
  // pointing in the racing direction, sitting on the runoff/grass next to the asphalt.
  const cornerChevrons = useMemo(() => {
    if (!pathLen || !pathRef.current) return [];
    const out = [];
    const path = pathRef.current;
    track.turns.forEach((t) => {
      // find the nearest path arc-length to the turn marker by sampling
      let best = 0, bestD = Infinity;
      const SAMPLES = 240;
      for (let i = 0; i < SAMPLES; i++) {
        const s = (i / SAMPLES) * pathLen;
        const p = path.getPointAtLength(s);
        const dx = p.x - t.x, dy = p.y - t.y;
        const d = dx*dx + dy*dy;
        if (d < bestD) { bestD = d; best = s; }
      }
      // 3 chevrons stepping BACK along the path from apex (entry warning)
      const N = t.important ? 3 : 2;
      const STEP = 14;
      for (let k = 1; k <= N; k++) {
        const s = (best - k * STEP + pathLen) % pathLen;
        const p = path.getPointAtLength(s);
        const ahead = path.getPointAtLength((s + 2) % pathLen);
        const angle = Math.atan2(ahead.y - p.y, ahead.x - p.x) * 180 / Math.PI;
        // offset perpendicular to the right of travel by ~14px so chevrons sit on grass
        const rad = Math.atan2(ahead.y - p.y, ahead.x - p.x);
        // pick side based on which side is "outside" — use turn marker side as hint
        const nx = -Math.sin(rad), ny = Math.cos(rad);
        const sideHint = ((t.x - p.x) * nx + (t.y - p.y) * ny) > 0 ? 1 : -1;
        const off = 8;
        out.push({
          x: p.x + nx * off * sideHint,
          y: p.y + ny * off * sideHint,
          angle,
          fade: 1 - (k - 1) / N,
          important: t.important,
        });
      }
    });
    return out;
  }, [pathLen, track.id]);

  // Kerb segments at important turns — short stretches of red/white striping.
  const kerbSegments = useMemo(() => {
    if (!pathLen || !pathRef.current) return [];
    const path = pathRef.current;
    return track.turns
      .filter((t) => t.important)
      .map((t) => {
        let best = 0, bestD = Infinity;
        const SAMPLES = 240;
        for (let i = 0; i < SAMPLES; i++) {
          const s = (i / SAMPLES) * pathLen;
          const p = path.getPointAtLength(s);
          const dx = p.x - t.x, dy = p.y - t.y;
          const d = dx*dx + dy*dy;
          if (d < bestD) { bestD = d; best = s; }
        }
        // Kerb spans ~50px arc-length straddling the apex
        const SPAN = 60;
        return {
          start: (best - SPAN / 2 + pathLen) % pathLen,
          length: SPAN,
        };
      });
  }, [pathLen, track.id]);

  // Sectors: divide the lap into 3 equal portions for any track (data-driven look)
  const sectorBands = [
    { from: 0.00, to: 0.33, color: "#5BB7E2" },
    { from: 0.33, to: 0.66, color: "#C9A24A" },
    { from: 0.66, to: 1.00, color: "#9B6BC8" },
  ];

  const sf = track.sf_line;
  const hill = track.hill;

  // Precompute checkered start/finish geometry (avoid IIFE inside JSX — Babel-standalone choke risk)
  let sfGrid = null;
  if (sf) {
    const _dx = sf.x2 - sf.x1, _dy = sf.y2 - sf.y1;
    const _len = Math.sqrt(_dx*_dx + _dy*_dy);
    const _ang = Math.atan2(_dy, _dx) * 180 / Math.PI;
    const _cx = (sf.x1 + sf.x2) / 2, _cy = (sf.y1 + sf.y2) / 2;
    const _W = Math.max(_len, 22);
    const _H = 24;
    const _cells = 8;
    const _cw = _W / _cells;
    const _rects = [];
    for (let k = 0; k < _cells * 2; k++) {
      const col = k % _cells, row = Math.floor(k / _cells);
      const isWhite = (col + row) % 2 === 0;
      _rects.push({
        key: k,
        x: -_W/2 + col * _cw,
        y: -_H/2 + row * (_H/2),
        w: _cw,
        h: _H/2,
        fill: isWhite ? "#F4EFE5" : "#0a0a0a",
      });
    }
    sfGrid = { cx: _cx, cy: _cy, ang: _ang, W: _W, H: _H, rects: _rects };
  }

  return (
    <div className="track-wrap" style={{ background: sky }}>
      <svg className="track-svg" viewBox="0 0 1000 560" preserveAspectRatio="xMidYMid meet">
        <defs>
          {/* Asphalt — slight diagonal sheen to imply 3D camber */}
          <linearGradient id="asphaltSheen" x1="0%" y1="0%" x2="100%" y2="100%">
            <stop offset="0%" stopColor="rgba(255,255,255,0.04)"/>
            <stop offset="50%" stopColor="rgba(255,255,255,0)"/>
            <stop offset="100%" stopColor="rgba(0,0,0,0.18)"/>
          </linearGradient>
          {/* Red/white kerb stripe */}
          <pattern id="kerbStripe" width="14" height="6" patternUnits="userSpaceOnUse">
            <rect width="7" height="6" fill="#C8102E"/>
            <rect x="7" width="7" height="6" fill="#F4EFE5"/>
          </pattern>
        </defs>

        {/* Topo rings — very subtle elevation hint */}
        {hill && (
          <g opacity="0.10" stroke={trackStroke} fill="none" strokeWidth="0.5">
            <ellipse cx={hill.cx} cy={hill.cy} rx={hill.rx} ry={hill.ry}/>
            <ellipse cx={hill.cx} cy={hill.cy} rx={hill.rx*0.65} ry={hill.ry*0.65}/>
            <ellipse cx={hill.cx} cy={hill.cy} rx={hill.rx*0.35} ry={hill.ry*0.35}/>
          </g>
        )}

        {/* Pit lane — dashed asphalt path next to main track */}
        {track.pit && (
          <g>
            <path d={track.pit} fill="none" stroke={asphaltDark} strokeWidth="10" strokeLinecap="round"/>
            <path d={track.pit} fill="none" stroke={asphalt} strokeWidth="8" strokeLinecap="round"/>
            <path d={track.pit} fill="none" stroke={paint} strokeWidth="0.6" strokeDasharray="3 4" opacity="0.5"/>
            {/* Pit lane entry/exit paint */}
            <path d={track.pit} fill="none" stroke={paint} strokeWidth="8.5" strokeLinecap="round" opacity="0.3" strokeDasharray="0 0"/>
          </g>
        )}

        {/* === TRACK STACK ===
            Layered to fake 3D: gravel runoff → drop shadow → outer paint → asphalt body → inner paint → centerline.
            Wider track allows cars to run side-by-side. */}
        {/* Gravel / run-off area — wider pale strip under the track */}
        <path d={track.path} fill="none" stroke="rgba(180,170,140,0.12)" strokeWidth="52"
          strokeLinecap="round" strokeLinejoin="round"/>
        {/* Soft cast shadow under the track */}
        <path d={track.path} fill="none" stroke="rgba(0,0,0,0.55)" strokeWidth="44"
          strokeLinecap="round" strokeLinejoin="round" transform="translate(0,3)" opacity="0.55"/>
        {/* Outer asphalt edge — dark band, suggests pavement bevel */}
        <path d={track.path} fill="none" stroke={asphaltDark} strokeWidth="42"
          strokeLinecap="round" strokeLinejoin="round"/>
        {/* White outer painted edge */}
        <path d={track.path} fill="none" stroke={paint} strokeWidth="39"
          strokeLinecap="round" strokeLinejoin="round" opacity="0.95"/>
        {/* Asphalt surface */}
        <path d={track.path} fill="none" stroke={asphalt} strokeWidth="36"
          strokeLinecap="round" strokeLinejoin="round"/>
        {/* Asphalt sheen — adds slight gradient tint suggesting camber */}
        <path d={track.path} fill="none" stroke="url(#asphaltSheen)" strokeWidth="36"
          strokeLinecap="round" strokeLinejoin="round" opacity="0.6"/>
        {/* Racing line — subtle darker strip where rubber lays down */}
        <path d={track.path} fill="none" stroke="rgba(0,0,0,0.15)" strokeWidth="6"
          strokeLinecap="round" strokeLinejoin="round"/>
        {/* White inner painted edge */}
        <path d={track.path} fill="none" stroke={paint} strokeWidth="0.9"
          strokeLinecap="round" strokeLinejoin="round" opacity="0.85"
          style={{ filter: "none" }}/>

        {/* Kerbs — red/white striping at important corners */}
        {kerbSegments.map((k, i) => {
          // Two parallel passes to look like both inner and outer kerbs
          const dash = `${k.length} ${pathLen}`;
          const offset = -k.start;
          return (
            <g key={`kerb-${i}`}>
              <path d={track.path} fill="none" stroke="url(#kerbStripe)" strokeWidth="41"
                strokeDasharray={dash} strokeDashoffset={offset}
                strokeLinecap="butt" opacity="0.92"/>
              {/* re-lay asphalt over the inside so kerb only shows as a rim */}
              <path d={track.path} fill="none" stroke={asphalt} strokeWidth="34"
                strokeDasharray={dash} strokeDashoffset={offset}
                strokeLinecap="butt"/>
              {/* white edge re-paint over kerb section */}
              <path d={track.path} fill="none" stroke={paint} strokeWidth="0.9"
                strokeDasharray={dash} strokeDashoffset={offset} opacity="0.85"/>
            </g>
          );
        })}

        {/* Centerline — faint dashed white, like a real track midline reference */}
        <path d={track.path} fill="none" stroke={paint} strokeWidth="0.6"
          strokeLinecap="round" strokeLinejoin="round" opacity="0.35"
          strokeDasharray="6 10"/>

        {/* Sector overlay (when toggled) — sit on top of asphalt as colored band */}
        {showSectors && pathLen > 0 && sectorBands.map((s, i) => {
          const len = pathLen;
          const dash = `${(s.to - s.from) * len} ${len}`;
          const offset = -s.from * len;
          return (
            <path key={i} d={track.path} fill="none" stroke={s.color} strokeWidth="3"
              strokeDasharray={dash} strokeDashoffset={offset} opacity="0.7"/>
          );
        })}

        {/* Hidden ref path used for measurement / car positioning */}
        <path ref={pathRef} d={track.path} fill="none" stroke="none" strokeWidth="0"/>

        {/* CORNER CHEVRONS — only at important corners (less noise) */}
        {cornerChevrons.filter(c => c.important).map((c, i) => (
          <g key={`chev-${i}`} transform={`translate(${c.x},${c.y}) rotate(${c.angle})`}
             opacity={c.fade * 0.55}>
            <path d="M -3 -3 L 0 0 L -3 3" fill="none"
              stroke={paint} strokeWidth="1.4"
              strokeLinecap="round" strokeLinejoin="round"/>
          </g>
        ))}

        {/* Start/finish line tick — checkered grid like a real F1 track */}
        {sfGrid && (
          <g transform={`translate(${sfGrid.cx},${sfGrid.cy}) rotate(${sfGrid.ang})`}>
            <rect x={-sfGrid.W/2} y={-sfGrid.H/2} width={sfGrid.W} height={sfGrid.H} fill="#0a0a0a"/>
            {sfGrid.rects.map((r) => (
              <rect key={r.key} x={r.x} y={r.y} width={r.w} height={r.h} fill={r.fill}/>
            ))}
            <text y={-sfGrid.H/2 - 6} fill="#fff" fontSize="9"
              fontFamily="JetBrains Mono, monospace" letterSpacing="1" textAnchor="middle">START / FINISH</text>
          </g>
        )}

        {/* Turn markers */}
        {showTurns && track.turns.map((t) => (
          <g key={t.n} className={t.important ? "turn-marker turn-marker-important" : "turn-marker"}>
            <line x1={t.x} y1={t.y} x2={t.x + (t.x < 500 ? -18 : 18)} y2={t.y} stroke="rgba(239,234,224,0.55)" strokeWidth="0.6"/>
            <text x={t.x + (t.x < 500 ? -22 : 22)} y={t.y + 3}
              textAnchor={t.x < 500 ? "end" : "start"}
              fill={t.important ? "#FFFFFF" : "rgba(239,234,224,0.85)"}
              fontSize={t.important ? "11" : "9"}
              fontWeight={t.important ? 800 : 500}
              fontFamily="JetBrains Mono, monospace"
              letterSpacing="1"
              stroke="rgba(0,0,0,0.85)"
              strokeWidth={t.important ? 2.6 : 2.0}
              paintOrder="stroke">
              {t.label}
              {t.important && t.name && <tspan fontSize="8" opacity="0.85" dx="8" fontWeight={500}>{t.name}</tspan>}
            </text>
          </g>
        ))}

        {/* Brake hotspots for focused car (red dots where they're hard on the brakes) */}
        {brakeHotspots.map((h, i) => (
          <circle key={i} cx={h.x} cy={h.y} r={1.6 + h.intensity * 1.5}
            fill="#C8102E" opacity={0.18 + h.intensity * 0.35}/>
        ))}

        {/* Battle pair connector lines (cars in close combat) */}
        {battlePairs.map((b, i) => (
          <line key={i} x1={b.a.x} y1={b.a.y} x2={b.b.x} y2={b.b.y}
            stroke="#C9A24A" strokeWidth="0.7" opacity="0.55" strokeDasharray="2 2"/>
        ))}

        {/* Trails behind each car — tinted with livery primary */}
        {carNodes.map(car => {
          const isFocus = car.no === focusedNo;
          return (
            <g key={`trail-${car.no}`} opacity={isFocus ? 0.85 : 0.5}>
              {car.trail.map((tp, k) => (
                <circle key={k} cx={tp.x} cy={tp.y}
                  r={(isFocus ? 3.2 : 2.2) * (1 - k / car.trail.length)}
                  fill={car.livery.accent === "#FFFFFF" ? car.livery.primary : car.livery.accent}
                  opacity={(1 - k / car.trail.length) * 0.7}/>
              ))}
            </g>
          );
        })}

        {/* Cars */}
        {carNodes.map(car => {
          const isFocus = car.no === focusedNo;
          // Bigger, more legible car size — focus is meaningfully larger
          const r = isFocus ? 14 : 10;
          const cls = (carClass && carClass.id) || "open_wheel";
          const accent = car.livery.accent === "#FFFFFF" ? "#E8E4DC" : car.livery.accent;
          // High-contrast outline color depending on body luminance
          const hex = (car.livery.primary || "#888").replace("#","");
          const rr = parseInt(hex.substring(0,2),16) || 0;
          const gg = parseInt(hex.substring(2,4),16) || 0;
          const bb = parseInt(hex.substring(4,6),16) || 0;
          const lum = (0.299*rr + 0.587*gg + 0.114*bb);
          const outline = lum < 100 ? "#FFFFFF" : "#000000";
          return (
            <g key={car.no} className="car-node"
              onClick={() => {
                if (car.no === focusedNo && onZoom) onZoom();
                else onFocus(car.no);
              }}
              onDoubleClick={() => { onFocus(car.no); if (onZoom) onZoom(); }}
              style={{ cursor: "pointer" }}>

              {/* Dark halo plate behind every car for legibility on light/dark track */}
              <circle cx={car.x} cy={car.y} r={r + 4} fill="rgba(0,0,0,0.55)"/>

              {/* Focus pulse — accent-colored ring */}
              {isFocus && (
                <>
                  <circle cx={car.x} cy={car.y} r={r + 7} fill="none" stroke={accent} strokeWidth="1.8" opacity="0.9"/>
                  <circle cx={car.x} cy={car.y} r={r + 7} fill="none" stroke="#C8102E" strokeWidth="1.4" opacity="0.7">
                    <animate attributeName="r" from={r + 7} to={r + 22} dur="1.4s" repeatCount="indefinite"/>
                    <animate attributeName="opacity" from="0.8" to="0" dur="1.4s" repeatCount="indefinite"/>
                  </circle>
                </>
              )}

              <g transform={`translate(${car.x},${car.y}) rotate(${car.angle})`}>
                {cls === "open_wheel" && <>
                  {/* === F1-style top-down — points forward (+X) ===
                       Layout (front -> rear): nose cone, front wing, sidepod body, cockpit, rear wing */}
                  {/* Front wing — wide */}
                  <rect x={r*0.55} y={-r*1.05} width={r*0.30} height={r*2.10}
                        fill={car.livery.secondary || outline} stroke={outline} strokeWidth="0.5"/>
                  {/* Front tyres — fat, slightly outboard */}
                  <rect x={r*0.20} y={-r*1.05} width={r*0.55} height={r*0.42} fill="#0a0a0a" stroke="#222" strokeWidth="0.3"/>
                  <rect x={r*0.20} y={ r*0.63} width={r*0.55} height={r*0.42} fill="#0a0a0a" stroke="#222" strokeWidth="0.3"/>
                  {/* Pencil-thin nose */}
                  <polygon points={`${r*0.20},${-r*0.18} ${r*1.45},0 ${r*0.20},${r*0.18}`}
                           fill={car.livery.primary} stroke={outline} strokeWidth="0.7"/>
                  {/* Sidepod main body — tapers from cockpit to rear */}
                  <polygon points={`${r*0.20},${-r*0.55} ${-r*0.85},${-r*0.70} ${-r*0.95},${-r*0.55} ${-r*0.95},${r*0.55} ${-r*0.85},${r*0.70} ${r*0.20},${r*0.55}`}
                           fill={car.livery.primary} stroke={outline} strokeWidth="0.8"/>
                  {/* Engine cover stripe */}
                  <rect x={-r*0.85} y={-r*0.20} width={r*1.05} height={r*0.40} fill={accent}/>
                  {/* Cockpit halo / driver */}
                  <ellipse cx={-r*0.05} cy={0} rx={r*0.30} ry={r*0.32} fill="#0a0a0a" stroke={outline} strokeWidth="0.5"/>
                  <circle cx={-r*0.05} cy={0} r={r*0.14} fill={car.livery.secondary || "#444"}/>
                  {/* Rear tyres — bigger */}
                  <rect x={-r*0.95} y={-r*1.10} width={r*0.65} height={r*0.50} fill="#0a0a0a" stroke="#222" strokeWidth="0.3"/>
                  <rect x={-r*0.95} y={ r*0.60} width={r*0.65} height={r*0.50} fill="#0a0a0a" stroke="#222" strokeWidth="0.3"/>
                  {/* Rear wing */}
                  <rect x={-r*1.15} y={-r*0.85} width={r*0.22} height={r*1.70}
                        fill={car.livery.secondary || outline} stroke={outline} strokeWidth="0.5"/>
                  {/* T-cam */}
                  <rect x={-r*0.35} y={-r*0.10} width={r*0.18} height={r*0.20} fill={accent}/>
                </>}

                {cls === "gt" && <>
                  {/* === GT3 — wide, hunched, fender flares ===
                       Front (+X) tapers; rear is square */}
                  {/* Body — teardrop pointing forward */}
                  <path d={`
                    M ${r*1.30},0
                    L ${r*0.95},${-r*0.55}
                    L ${r*0.20},${-r*0.85}
                    L ${-r*0.95},${-r*0.85}
                    L ${-r*1.10},${-r*0.55}
                    L ${-r*1.10},${ r*0.55}
                    L ${-r*0.95},${ r*0.85}
                    L ${ r*0.20},${ r*0.85}
                    L ${ r*0.95},${ r*0.55}
                    Z`}
                    fill={car.livery.primary} stroke={outline} strokeWidth="1"/>
                  {/* Front fender flares — slightly darker */}
                  <ellipse cx={r*0.55} cy={-r*0.75} rx={r*0.30} ry={r*0.18} fill="rgba(0,0,0,0.25)"/>
                  <ellipse cx={r*0.55} cy={ r*0.75} rx={r*0.30} ry={r*0.18} fill="rgba(0,0,0,0.25)"/>
                  {/* Greenhouse — narrow cabin, set back */}
                  <path d={`
                    M ${r*0.55},${-r*0.42}
                    L ${r*0.30},${-r*0.55}
                    L ${-r*0.55},${-r*0.55}
                    L ${-r*0.75},${-r*0.42}
                    L ${-r*0.75},${ r*0.42}
                    L ${-r*0.55},${ r*0.55}
                    L ${ r*0.30},${ r*0.55}
                    L ${ r*0.55},${ r*0.42}
                    Z`}
                    fill={accent} stroke={outline} strokeWidth="0.5" opacity="0.95"/>
                  {/* Roof livery stripe */}
                  <rect x={-r*0.65} y={-r*0.12} width={r*1.10} height={r*0.24} fill={car.livery.secondary || "#222"} opacity="0.6"/>
                  {/* Hood vent / nostrils */}
                  <rect x={r*0.75} y={-r*0.30} width={r*0.20} height={r*0.18} fill="#000" opacity="0.55"/>
                  <rect x={r*0.75} y={ r*0.12} width={r*0.20} height={r*0.18} fill="#000" opacity="0.55"/>
                  {/* Rear wing — lifted */}
                  <rect x={-r*1.18} y={-r*0.65} width={r*0.18} height={r*1.30} fill={car.livery.secondary || outline}/>
                  {/* Headlights */}
                  <rect x={r*1.10} y={-r*0.45} width={r*0.12} height={r*0.18} fill="#FFF8C8"/>
                  <rect x={r*1.10} y={ r*0.27} width={r*0.12} height={r*0.18} fill="#FFF8C8"/>
                </>}

                {cls === "stock" && <>
                  {/* === NASCAR-style — long greenhouse, square back, splitter === */}
                  {/* Main body */}
                  <path d={`
                    M ${r*1.20},${-r*0.30}
                    L ${r*1.05},${-r*0.85}
                    L ${-r*1.05},${-r*0.90}
                    L ${-r*1.15},${-r*0.55}
                    L ${-r*1.15},${ r*0.55}
                    L ${-r*1.05},${ r*0.90}
                    L ${ r*1.05},${ r*0.85}
                    L ${ r*1.20},${ r*0.30}
                    Z`}
                    fill={car.livery.primary} stroke={outline} strokeWidth="1"/>
                  {/* Front splitter */}
                  <rect x={r*1.05} y={-r*0.42} width={r*0.22} height={r*0.84} fill="#111" stroke={outline} strokeWidth="0.4"/>
                  {/* Greenhouse */}
                  <path d={`
                    M ${r*0.55},${-r*0.55}
                    L ${ r*0.30},${-r*0.65}
                    L ${-r*0.55},${-r*0.65}
                    L ${-r*0.75},${-r*0.55}
                    L ${-r*0.75},${ r*0.55}
                    L ${-r*0.55},${ r*0.65}
                    L ${ r*0.30},${ r*0.65}
                    L ${ r*0.55},${ r*0.55}
                    Z`}
                    fill={accent} stroke={outline} strokeWidth="0.5" opacity="0.95"/>
                  {/* Center stripe */}
                  <rect x={-r*0.85} y={-r*0.10} width={r*1.95} height={r*0.20} fill={car.livery.secondary || "#222"}/>
                  {/* Big roundel number panel on door — both sides */}
                  <circle cx={-r*0.10} cy={-r*0.74} r={r*0.20} fill="#fff" stroke={outline} strokeWidth="0.4"/>
                  <circle cx={-r*0.10} cy={ r*0.74} r={r*0.20} fill="#fff" stroke={outline} strokeWidth="0.4"/>
                  {/* Spoiler */}
                  <rect x={-r*1.20} y={-r*0.65} width={r*0.18} height={r*1.30} fill={car.livery.secondary || outline}/>
                </>}

                {cls === "prototype" && <>
                  {/* === LMP — closed cockpit, fin, very wide rear === */}
                  {/* Body — fast teardrop */}
                  <path d={`
                    M ${r*1.45},0
                    L ${r*1.00},${-r*0.40}
                    L ${r*0.10},${-r*0.78}
                    L ${-r*0.95},${-r*0.85}
                    L ${-r*1.20},${-r*0.55}
                    L ${-r*1.20},${ r*0.55}
                    L ${-r*0.95},${ r*0.85}
                    L ${r*0.10},${ r*0.78}
                    L ${r*1.00},${ r*0.40}
                    Z`}
                    fill={car.livery.primary} stroke={outline} strokeWidth="0.9"/>
                  {/* Front canards / dive planes */}
                  <polygon points={`${r*0.95},${-r*0.45} ${r*1.20},${-r*0.65} ${r*1.20},${-r*0.45}`} fill={car.livery.secondary || outline}/>
                  <polygon points={`${r*0.95},${ r*0.45} ${r*1.20},${ r*0.65} ${r*1.20},${ r*0.45}`} fill={car.livery.secondary || outline}/>
                  {/* Tinted canopy — driver bubble */}
                  <ellipse cx={r*0.30} cy={0} rx={r*0.55} ry={r*0.40} fill="#0a0a0a" stroke={outline} strokeWidth="0.4"/>
                  <ellipse cx={r*0.30} cy={-r*0.10} rx={r*0.45} ry={r*0.28} fill={accent} opacity="0.85"/>
                  {/* Shark fin (visible from above as a stripe) */}
                  <polygon points={`${-r*0.95},${-r*0.10} ${-r*0.20},${-r*0.10} ${-r*0.20},${ r*0.10} ${-r*0.95},${ r*0.10}`}
                           fill={car.livery.secondary || outline}/>
                  {/* Rear wing — stretches across full width */}
                  <rect x={-r*1.28} y={-r*0.78} width={r*0.18} height={r*1.56}
                        fill={car.livery.secondary || outline}/>
                  {/* Endplates */}
                  <rect x={-r*1.28} y={-r*0.78} width={r*0.10} height={r*0.20} fill={outline}/>
                  <rect x={-r*1.28} y={ r*0.58} width={r*0.10} height={r*0.20} fill={outline}/>
                  {/* Number badge near nose */}
                  <rect x={r*0.75} y={-r*0.18} width={r*0.30} height={r*0.36} fill="#fff"/>
                  {/* Headlight bars */}
                  <rect x={r*1.05} y={-r*0.32} width={r*0.10} height={r*0.12} fill="#FFF8C8"/>
                  <rect x={r*1.05} y={ r*0.20} width={r*0.10} height={r*0.12} fill="#FFF8C8"/>
                </>}

                {cls === "e_spec" && <>
                  {/* === Touring/EV hatch — short, square, glasshouse === */}
                  <rect x={-r*1.05} y={-r*0.70} width={r*2.10} height={r*1.40} rx={r*0.25}
                        fill={car.livery.primary} stroke={outline} strokeWidth="0.9"/>
                  {/* Glasshouse — bigger, more bubble */}
                  <rect x={-r*0.65} y={-r*0.50} width={r*1.40} height={r*1.00} rx={r*0.18}
                        fill={accent} opacity="0.92" stroke={outline} strokeWidth="0.4"/>
                  {/* A-pillar split */}
                  <line x1={r*0.10} y1={-r*0.50} x2={r*0.10} y2={r*0.50} stroke={outline} strokeWidth="0.4"/>
                  {/* Hood */}
                  <rect x={r*0.55} y={-r*0.65} width={r*0.40} height={r*1.30} fill={car.livery.primary} stroke={outline} strokeWidth="0.4"/>
                  {/* Side livery stripe */}
                  <rect x={-r*1.00} y={-r*0.10} width={r*2.00} height={r*0.18} fill={car.livery.secondary || "#222"} opacity="0.6"/>
                  {/* Headlights */}
                  <rect x={r*0.95} y={-r*0.55} width={r*0.10} height={r*0.18} fill="#E8F4FF"/>
                  <rect x={r*0.95} y={ r*0.37} width={r*0.10} height={r*0.18} fill="#E8F4FF"/>
                  {/* Rear hatch line */}
                  <line x1={-r*1.00} y1={-r*0.55} x2={-r*1.00} y2={r*0.55} stroke={outline} strokeWidth="0.4"/>
                  {/* EV charge LED — pulsing, on rear corner */}
                  <circle cx={-r*0.85} cy={0} r={r*0.13} fill="#3DD68C"/>
                  <circle cx={-r*0.85} cy={0} r={r*0.13} fill="none" stroke="#3DD68C" strokeWidth="0.8" opacity="0.6">
                    <animate attributeName="r" values={`${r*0.13};${r*0.32};${r*0.13}`} dur="1.6s" repeatCount="indefinite"/>
                    <animate attributeName="opacity" values="0.7;0;0.7" dur="1.6s" repeatCount="indefinite"/>
                  </circle>
                </>}
              </g>

              {/* Number on solid plate — always legible */}
              <g>
                <rect
                  x={car.x - (isFocus ? 12 : 9)}
                  y={car.y - (isFocus ? 28 : 22)}
                  width={isFocus ? 24 : 18}
                  height={isFocus ? 14 : 11}
                  fill="rgba(0,0,0,0.85)"
                  stroke={isFocus ? "#C8102E" : accent}
                  strokeWidth={isFocus ? 1.2 : 0.8}
                />
                <text x={car.x} y={car.y - (isFocus ? 18 : 14)}
                  fontSize={isFocus ? "12" : "9"}
                  fontFamily="Geist, JetBrains Mono, monospace"
                  fontWeight="900"
                  fill={isFocus ? "#fff" : accent}
                  textAnchor="middle"
                  letterSpacing="0.5">
                  {car.no}
                </text>
              </g>

              {isFocus && (
                <text x={car.x} y={car.y + r + 12} fontSize="9"
                  fontFamily="JetBrains Mono, monospace" fontWeight="800"
                  fill="#fff" stroke="rgba(0,0,0,0.95)" strokeWidth="2.5"
                  paintOrder="stroke" textAnchor="middle" letterSpacing="1.5">
                  P{String(car.pos).padStart(2,"0")} · {car.short}
                </text>
              )}
            </g>
          );
        })}

        {/* Weather effects overlay */}
        {window.WeatherOverlay && <window.WeatherOverlay weather={weather}/>}

        {/* Wet track sheen on asphalt */}
        {(weather === "rain" || weather === "wet") && (
          <path d={track.path} fill="none" stroke="rgba(91,183,226,0.10)" strokeWidth="36"
            strokeLinecap="round" strokeLinejoin="round" style={{ mixBlendMode: "screen" }}/>
        )}
      </svg>

      {/* Track HUD — minimal corner labels only. Detailed circuit info is in the dossier panel. */}
      <div className="track-hud-tl">
        <div className="hud-eyebrow">CIRCUIT</div>
        <div className="hud-title">{track.short}</div>
      </div>

      <div className="track-hud-tr">
        <div className="flag-pill green">
          <span className="dot"/> GREEN FLAG
        </div>
        <div className="hud-eyebrow" style={{marginTop: 10, textAlign: "right"}}>LAP</div>
        <div className="hud-title hud-title-lg" style={{textAlign: "right"}}>{String(lap).padStart(2,"0")}<span className="hud-of">/{lapsTotal}</span></div>
      </div>
    </div>
  );
}

window.Track = Track;
