// Main App — composes Track + side panels + tweaks
const { useState: useS, useEffect: useE, useMemo: useM, useRef: useR } = React;

function App() {
  const D = window.APEX_DATA;
  const [focusedNo, setFocusedNo] = useS(7);
  const [trackId, setTrackId] = useS("laguna_seca");
  const [classId, setClassId] = useS("open_wheel");
  const track = window.TRACKS[trackId];
  const trackEvent = window.TRACK_EVENTS[trackId];
  const carClass = window.CAR_CLASSES[classId];
  const raceState = useM(() => window.classRaceState(D.RACE_STATE, classId), [classId]);
  const [tweaks, setTweak] = window.useTweaks ? window.useTweaks({ timeOfDay: "day", showSectors: true, showTurns: true, weather: "dry" }) : [{ timeOfDay:"day", showSectors:true, showTurns:true, weather:"dry" }, ()=>{}];
  const [progress, setProgress] = useS(0);
  const [sample, setSample] = useS(0);
  const [tab, setTab] = useS("telem");
  const [lightboxOpen, setLightboxOpen] = useS(false);
  const [broadcast, setBroadcast] = useS(false);
  const [f1Mode, setF1Mode] = useS(false);
  const [f1Cars, setF1Cars] = useS(null);
  const [f1Meta, setF1Meta] = useS(null);
  // Mobile view: which pane is active (left=leaderboard, center=track, right=detail)
  const [mobilePane, setMobilePane] = useS("center");

  const handleF1Data = useR((data) => {
    if (data && data.cars && data.cars.length) {
      setF1Cars(data.cars.map((c, i) => ({ ...c, _offset: (1 - i * 0.065 + 1) % 1 })));
      setF1Meta(data);
      if (!focusedNo || !data.cars.find(c => c.no === focusedNo)) {
        setFocusedNo(data.cars[0].no);
      }
    }
  });
  const onF1Data = React.useCallback((data) => handleF1Data.current(data), []);

  // B-key toggle for broadcast mode + Esc to exit
  useE(() => {
    const onKey = (e) => {
      if (e.target && (e.target.tagName === "INPUT" || e.target.tagName === "TEXTAREA")) return;
      if (e.key === "b" || e.key === "B") setBroadcast(v => !v);
      if (e.key === "Escape") { setBroadcast(false); }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  // Animate cars around the track
  useE(() => {
    let raf;
    let last = performance.now();
    const tick = (now) => {
      const dt = (now - last) / 1000; last = now;
      setProgress(p => (p + dt * 0.012) % 1); // ~83s per virtual lap
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  // Animate telemetry sample
  useE(() => {
    const id = setInterval(() => setSample(s => (s + 1) % 100), 80);
    return () => clearInterval(id);
  }, []);

  // Give each car a stable offset around the track based on position.
  // Spread the 12 cars across the lap so leader is ahead and field is distributed.
  const simCars = useM(() => {
    const transformed = window.applyClassToCars(D.CARS, classId);
    return transformed.map(c => ({ ...c, _offset: (1 - (c.pos - 1) * 0.078 + 1) % 1 }));
  }, [classId]);
  const cars = (f1Mode && f1Cars) ? f1Cars : simCars;
  const focused = cars.find(c => c.no === focusedNo);
  const activeLap = (f1Mode && f1Meta) ? f1Meta.lap : raceState.lap;

  return (
    <div className={`app ${broadcast ? "app-broadcast" : ""} ${f1Mode ? "app-f1" : ""} app-pane-${mobilePane} app-tod-${tweaks.timeOfDay}`}>
      <button
        className={`broadcast-toggle ${broadcast ? "on" : ""}`}
        onClick={() => setBroadcast(v => !v)}
        title="Broadcast mode (B)">
        <span className="bc-dot"/>
        {broadcast ? "EXIT BROADCAST" : "BROADCAST"}
      </button>

      <button
        className={`f1-mode-toggle ${f1Mode ? "on" : ""}`}
        onClick={() => setF1Mode(v => !v)}
        title="Toggle live F1 data">
        {f1Mode ? "EXIT F1 LIVE" : "F1 LIVE"}
      </button>

      {f1Mode && window.F1DataProvider && (
        <window.F1DataProvider onData={onF1Data}/>
      )}

      <div className="mobile-tabs" role="tablist">
        <button className={`mt-tab ${mobilePane === "left" ? "on" : ""}`} onClick={() => setMobilePane("left")}>TIMING</button>
        <button className={`mt-tab ${mobilePane === "center" ? "on" : ""}`} onClick={() => setMobilePane("center")}>TRACK</button>
        <button className={`mt-tab ${mobilePane === "right" ? "on" : ""}`} onClick={() => setMobilePane("right")}>CAR</button>
      </div>

      <div className="app-top">
        <TopBar
          track={track}
          trackEvent={trackEvent}
          trackId={trackId}
          onTrackChange={setTrackId}
          raceState={raceState}
          classId={classId}
          onClassChange={setClassId}
        />
      </div>

      <aside className="app-left">
        <Leaderboard cars={cars} focusedNo={focusedNo} onFocus={setFocusedNo} lap={activeLap}/>
      </aside>

      <main className="app-center">
        <div className="center-track">
          <Track
            track={track}
            cars={cars}
            focusedNo={focusedNo}
            onFocus={setFocusedNo}
            onZoom={() => setLightboxOpen(true)}
            lap={D.RACE_STATE.lap}
            lapsTotal={track.laps}
            timeOfDay={tweaks.timeOfDay}
            weather={tweaks.weather}
            showSectors={tweaks.showSectors}
            showTurns={tweaks.showTurns}
            raceProgress={progress}
            carClass={carClass}
          />
          {window.TrackHistoryPanel && <window.TrackHistoryPanel track={track}/>}
        </div>
        <div className="center-bottom">
          <StrategyPanel car={focused} carClass={carClass}/>
          <PitLogStrip carClass={carClass}/>
        </div>
      </main>

      <aside className="app-right" key={focusedNo}>
        <div className="rr-tabs">
          <button className={tab==="telem"?"rr-tab rr-tab-on":"rr-tab"} onClick={()=>setTab("telem")}>TELEMETRY</button>
          <button className={tab==="car"?"rr-tab rr-tab-on":"rr-tab"} onClick={()=>setTab("car")}>DRIVER</button>
          <button className={tab==="team"?"rr-tab rr-tab-on":"rr-tab"} onClick={()=>setTab("team")}>TEAM</button>
        </div>
        {tab==="telem" && <>
          <FocusedCarHeader car={focused} onZoomPhoto={() => setLightboxOpen(true)} carClass={carClass}
            cars={cars} track={track} raceProgress={progress} sample={sample}/>
          <Telemetry car={focused} sample={sample} carClass={carClass}/>
        </>}
        {tab==="car" && <window.DriverProfile car={focused} onZoomPhoto={() => setLightboxOpen(true)} carClass={carClass}
          cars={cars} track={track} raceProgress={progress} sample={sample}/>}
        {tab==="team" && focused && <TeamTab car={focused} carClass={carClass}/>}
      </aside>

      {lightboxOpen && focused && (
        <div className="cdx-overlay" onClick={(e) => { if (e.target === e.currentTarget) setLightboxOpen(false); }}>
          <div className="cdx-scroll">
            <button className="cdx-close" onClick={() => setLightboxOpen(false)}>
              <span className="cdx-close-x">+</span>
              <span className="cdx-close-label">CLOSE</span>
            </button>

            {/* WIND TUNNEL — centered hero, first thing visible */}
            <section className="cdx-aero-top">
              {window.ShaderBg && <window.ShaderBg
                color1={focused.livery.primary}
                color2={focused.livery.accent === "#FFFFFF" ? "#5BB7E2" : focused.livery.accent}
                color3={focused.livery.secondary || "#333"}
                opacity={0.12}/>}
              <div className="cdx-aero-top-eyebrow">
                <span className="cdx-dot" style={{background: focused.livery.accent}}/>
                {focused.team} · #{String(focused.no).padStart(2,"0")}
              </div>
              <div className="cdx-aero-top-sim">
                {window.AeroSimulator && <window.AeroSimulator car={focused} carClass={carClass} speed={(() => {
                  const tele = window.APEX_DATA.generateTelemetry(focused.no);
                  const cur = tele[sample % 100];
                  const [minSpd, maxSpd] = (carClass && carClass.speedRange) || [80, 310];
                  return Math.round(minSpd + ((cur.speed - 80) / (310 - 80)) * (maxSpd - minSpd));
                })()}/>}
              </div>
            </section>

            {/* HERO SECTION */}
            <section className="cdx-hero">
              <div className="cdx-hero-content">
                <div className="cdx-hero-eyebrow">
                  <span className="cdx-dot" style={{background: focused.livery.accent}}/>
                  {focused.team}
                </div>
                <div className="cdx-hero-no" style={{color: focused.livery.accent === "#FFFFFF" ? "#fff" : focused.livery.accent}}>
                  {String(focused.no).padStart(2,"0")}
                </div>
                <div className="cdx-hero-name">{focused.name}</div>
                <div className="cdx-hero-sub">{focused.chassis} · {focused.engine}</div>
              </div>
              <div className="cdx-hero-photo-small">
                <window.PhotoCard car={focused} carClass={carClass}/>
              </div>
            </section>

            {/* SPEC STRIP */}
            <section className="cdx-specs">
              {[
                { label: "POSITION", val: "P" + focused.pos },
                { label: "LAST LAP", val: focused.last_lap },
                { label: "BEST LAP", val: focused.best_lap },
                { label: "GAP", val: focused.gap },
                { label: "TYRE", val: focused.tire + " · " + focused.tire_age + " LAPS" },
                { label: "FUEL", val: Math.round(focused.fuel) + "%" },
              ].map((s, i) => (
                <div key={i} className="cdx-spec">
                  <div className="cdx-spec-label">{s.label}</div>
                  <div className="cdx-spec-val">{s.val}</div>
                </div>
              ))}
            </section>

            {/* DRIVER & CREW */}
            <section className="cdx-section">
              <div className="cdx-section-eyebrow">DRIVER</div>
              <div className="cdx-section-title">{focused.name}</div>
              <div className="cdx-driver-grid">
                <div className="cdx-driver-card">
                  <window.HelmetPortrait car={focused}/>
                  <div className="cdx-driver-meta">
                    <span>{focused.country} · AGE {focused.age}</span>
                    <span>{focused.team}</span>
                  </div>
                </div>
                <div className="cdx-driver-bio">{focused.bio}</div>
              </div>
              <div className="cdx-crew-row">
                <div className="cdx-crew-card">
                  <div className="cdx-crew-role">CREW CHIEF</div>
                  <div className="cdx-crew-name">{focused.crew_chief}</div>
                </div>
                <div className="cdx-crew-card">
                  <div className="cdx-crew-role">RACE ENGINEER</div>
                  <div className="cdx-crew-name">{focused.race_engineer}</div>
                </div>
              </div>
            </section>

            {/* LIVERY */}
            <section className="cdx-section">
              <div className="cdx-section-eyebrow">LIVERY</div>
              <div className="cdx-section-title">{focused.team}</div>
              <LiveryCard car={focused}/>
            </section>

            {/* SECTORS */}
            <section className="cdx-section">
              <div className="cdx-section-eyebrow">SECTOR TIMES</div>
              <div className="cdx-sectors">
                {focused.sectors.map((s, i) => (
                  <div key={i} className={`cdx-sector cdx-sector-${s.state}`}>
                    <div className="cdx-sector-label">{s.s}</div>
                    <div className="cdx-sector-time">{s.t}</div>
                  </div>
                ))}
              </div>
            </section>

            <div className="cdx-footer">
              <span>APEX SERIES · #{focused.no} {focused.name} · {focused.team}</span>
            </div>
          </div>
        </div>
      )}

      {broadcast && <BroadcastOverlay
        cars={cars}
        focused={focused}
        track={track}
        trackEvent={trackEvent}
        carClass={carClass}
        raceState={raceState}
        sample={sample}
      />}

      {window.TweaksPanel && (
        <window.TweaksPanel title="Tweaks">
          <window.TweakSection title="Track">
            <window.TweakRadio label="Time of day" value={tweaks.timeOfDay} onChange={v => setTweak("timeOfDay", v)} options={[{label:"Day",value:"day"},{label:"Dusk",value:"dusk"},{label:"Night",value:"night"}]}/>
            <window.TweakToggle label="Sector overlay" value={tweaks.showSectors} onChange={v => setTweak("showSectors", v)}/>
            <window.TweakToggle label="Turn labels" value={tweaks.showTurns} onChange={v => setTweak("showTurns", v)}/>
            <window.TweakRadio label="Weather" value={tweaks.weather} onChange={v => setTweak("weather", v)} options={[{label:"Dry",value:"dry"},{label:"Wet",value:"wet"},{label:"Rain",value:"rain"}]}/>
          </window.TweakSection>
        </window.TweaksPanel>
      )}
    </div>
  );
}

// Bottom-right strip: condensed pit replay below the track
function PitLogStrip({ carClass }) {
  const log = window.APEX_DATA.PIT_LOG;
  const cleanS = carClass ? carClass.pit_clean_s : 2.45;
  const goodCut = cleanS;
  const badCut = cleanS * 1.04;
  // Scale base pit log durations against class baseline (open-wheel = 2.45 reference)
  const scale = cleanS / 2.45;
  return (
    <div className="panel pit-panel" style={{paddingBottom: 10}}>
      <div className="panel-head"><div className="panel-eyebrow">PIT REPLAY · LAST 6 STOPS · {carClass ? carClass.short : ""}</div><div className="panel-meta">CLEAN STOP &lt; {cleanS.toFixed(2)}s</div></div>
      <div className="pit-list">
        {log.map((p, i) => {
          const dur = p.duration * scale;
          return (
            <div key={i} className="pit-row">
              <span className="pit-lap">L{p.lap}</span>
              <span className="pit-no">#{p.no}</span>
              <span className="pit-team">{p.team}</span>
              <span className="pit-action">{p.action}</span>
              <span className={`pit-dur ${dur < goodCut ? "good" : dur > badCut ? "bad" : ""}`}>{dur.toFixed(2)}s</span>
              <span className="pit-notes">{p.notes}</span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App/>);

function FocusedCarHeader({ car, onZoomPhoto, carClass, cars, track, raceProgress, sample }) {
  if (!car) return null;
  return (
    <div className="panel" style={{paddingBottom:10}}>
      <div className="panel-head focus-head" style={{borderBottom:"none", marginBottom:8, paddingBottom:0}}>
        <div>
          <div className="panel-eyebrow">FOCUSED · POS {String(car.pos).padStart(2,"0")}</div>
          <div className="focus-no" style={{ color: car.livery.accent === "#FFFFFF" ? "#fff" : car.livery.accent }}>
            {String(car.no).padStart(2,"0")}
          </div>
        </div>
        <div className="focus-flag">
          <div className="focus-country">{car.country}</div>
          <div className="focus-driver">{car.name}</div>
          <div className="focus-team">{car.team}</div>
        </div>
      </div>
      <window.PhotoCard car={car} label={`#${car.no} · ${car.name.split(" ").slice(-1)[0]} · ON TRACK`} onZoom={onZoomPhoto} carClass={carClass}/>
    </div>
  );
}

function SponsorsTab() { return null; }

function TeamTab({ car, carClass }) {
  if (!car) return null;
  const [slide, setSlide] = useS(0);
  const accent = car.livery.accent === "#FFFFFF" ? "#E8E4DC" : car.livery.accent;
  const pri = car.livery.primary;
  const sec = car.livery.secondary || "#222";

  const scenes = [
    { label: "GARAGE", desc: "Race bay preparation" },
    { label: "PIT WALL", desc: "Strategy command center" },
    { label: "ON TRACK", desc: "Race action" },
    { label: "ENGINEERING", desc: "Technical development" },
  ];

  useE(() => {
    const id = setInterval(() => setSlide(s => (s + 1) % scenes.length), 5000);
    return () => clearInterval(id);
  }, []);

  const cls = (carClass && carClass.id) || "open_wheel";

  // Generate team hero SVG scene — cinematic, atmospheric, animated
  const renderScene = (idx) => {
    const VW = 400, VH = 220;
    return (
      <svg viewBox={`0 0 ${VW} ${VH}`} className="team-slide-svg">
        <defs>
          <radialGradient id="tg1" cx="50%" cy="55%" r="65%">
            <stop offset="0%" stopColor={pri} stopOpacity="0.3"/>
            <stop offset="60%" stopColor={pri} stopOpacity="0.05"/>
            <stop offset="100%" stopColor="#000" stopOpacity="0"/>
          </radialGradient>
          <radialGradient id="tg-spot" cx="50%" cy="30%" r="40%">
            <stop offset="0%" stopColor="#fff" stopOpacity="0.08"/>
            <stop offset="100%" stopColor="#000" stopOpacity="0"/>
          </radialGradient>
          <linearGradient id="tg-floor" x1="0" x2="0" y1="0" y2="1">
            <stop offset="0%" stopColor="rgba(255,255,255,0.06)"/>
            <stop offset="50%" stopColor="rgba(255,255,255,0.01)"/>
            <stop offset="100%" stopColor="rgba(0,0,0,0)"/>
          </linearGradient>
          <linearGradient id="tg-vfade" x1="0" x2="0" y1="0" y2="1">
            <stop offset="0%" stopColor="rgba(0,0,0,0.5)"/>
            <stop offset="15%" stopColor="rgba(0,0,0,0)"/>
            <stop offset="70%" stopColor="rgba(0,0,0,0)"/>
            <stop offset="100%" stopColor="rgba(0,0,0,0.95)"/>
          </linearGradient>
          <filter id="tg-blur"><feGaussianBlur stdDeviation="6"/></filter>
          <filter id="tg-blur2"><feGaussianBlur stdDeviation="3"/></filter>
          <filter id="tg-glow"><feGaussianBlur stdDeviation="2" result="b"/><feComposite in="SourceGraphic" in2="b" operator="over"/></filter>
          <clipPath id="tg-clip"><rect width={VW} height={VH}/></clipPath>
        </defs>
        <g clipPath="url(#tg-clip)">
        <rect width={VW} height={VH} fill="#050709"/>
        <rect width={VW} height={VH} fill="url(#tg1)"/>

        {idx === 0 && <g>
          <ellipse cx={VW/2} cy={VH*0.4} rx="200" ry="80" fill={pri} opacity="0.04" filter="url(#tg-blur)"/>
          {[100,200,300].map((x,i) => (
            <g key={i}>
              <rect x={x-18} y="0" width="36" height="3" fill="#2a2a2a"/>
              <line x1={x} y1="3" x2={x} y2="14" stroke="#333" strokeWidth="1.5"/>
              <rect x={x-14} y="12" width="28" height="6" fill="#3a3a3a" rx="1"/>
              <polygon points={`${x-4},18 ${x+4},18 ${x+50},${VH-40} ${x-50},${VH-40}`} fill="rgba(255,240,210,0.02)"/>
              <ellipse cx={x} cy="18" rx="6" ry="2" fill="#FFE4B5" opacity="0.7"/>
              <ellipse cx={x} cy="18" rx="12" ry="4" fill="#FFE4B5" opacity="0.15" filter="url(#tg-blur2)"/>
              <ellipse cx={x} cy={VH-30} rx="55" ry="12" fill="rgba(255,240,210,0.03)"/>
            </g>
          ))}
          <rect x="0" y={VH*0.72} width={VW} height={VH*0.28} fill="url(#tg-floor)"/>
          <line x1="0" y1={VH*0.72} x2={VW} y2={VH*0.72} stroke="rgba(255,255,255,0.05)" strokeWidth="0.5"/>
          <g transform={`translate(${VW/2},${VH*0.58})`}>
            <polygon points="-65,8 -58,30 -72,30" fill="#2a2a2a" stroke="#444" strokeWidth="0.3"/>
            <polygon points="65,8 72,30 58,30" fill="#2a2a2a" stroke="#444" strokeWidth="0.3"/>
            <path d={`M -80,0 C -78,-3 -70,-8 -55,-12 L -30,-15 C -10,-17 10,-18 30,-17 L 55,-12 C 65,-8 72,-4 75,0 L 78,3 L -82,3 Z`} fill={pri} stroke={accent} strokeWidth="1" filter="url(#tg-glow)"/>
            <line x1="-70" y1="-2" x2="70" y2="-2" stroke={sec} strokeWidth="3" opacity="0.5"/>
            <line x1="-68" y1="1" x2="68" y2="1" stroke={accent} strokeWidth="0.8" opacity="0.4"/>
            <ellipse cx="-5" cy="-10" rx="14" ry="5" fill="rgba(0,0,0,0.8)" stroke="rgba(255,255,255,0.1)" strokeWidth="0.4"/>
            <circle cx="-50" cy="4" r="12" fill="#0a0a0a" stroke="#222" strokeWidth="0.5"/>
            <circle cx="55" cy="4" r="13" fill="#0a0a0a" stroke="#222" strokeWidth="0.5"/>
            <line x1="72" y1="-1" x2="82" y2="-5" stroke={accent} strokeWidth="1.5" opacity="0.5"/>
            <rect x="-86" y="-18" width="4" height="16" fill={sec} rx="1" opacity="0.7"/>
            <rect x="-90" y="-20" width="12" height="3" fill={accent} rx="1" opacity="0.6"/>
            <text x="20" y="0" fontSize="10" fontFamily="Geist, sans-serif" fontWeight="900" fill={accent} textAnchor="middle" opacity="0.5">{car.no}</text>
          </g>
          <g transform={`translate(${VW/2},${VH*0.72}) scale(1,-0.25)`} opacity="0.06">
            <path d={`M -80,0 C -78,-3 -70,-8 -55,-12 L -30,-15 C -10,-17 10,-18 30,-17 L 55,-12 C 65,-8 72,-4 75,0 L 78,3 L -82,3 Z`} fill={pri}/>
          </g>
          {[0,1,2,3,4,5].map(i => (
            <circle key={`sp${i}`} cx={150 + i * 7} cy={VH*0.48} r="1" fill="#FFE4B5" opacity="0">
              <animate attributeName="cy" from={VH*0.48} to={VH*0.48 + 25 + i*5} dur={`${0.6+i*0.15}s`} begin={`${i*0.2}s`} repeatCount="indefinite"/>
              <animate attributeName="opacity" values="0;0.9;0" dur={`${0.6+i*0.15}s`} begin={`${i*0.2}s`} repeatCount="indefinite"/>
              <animate attributeName="cx" from={148 + i * 7} to={145 + i * 9} dur={`${0.6+i*0.15}s`} begin={`${i*0.2}s`} repeatCount="indefinite"/>
            </circle>
          ))}
          <rect x="12" y="55" width="22" height="55" fill="#111" rx="2" opacity="0.5"/>
          <rect x="12" y="50" width="22" height="8" fill="#1a1a1a" rx="1"/>
          <rect x={VW-34} y="60" width="22" height="50" fill="#111" rx="2" opacity="0.5"/>
        </g>}

        {idx === 1 && <g>
          <ellipse cx={VW/2} cy={VH*0.35} rx="180" ry="70" fill="rgba(91,183,226,0.04)" filter="url(#tg-blur)"/>
          <path d={`M 10,${VH*0.58} L ${VW-10},${VH*0.58} L ${VW-10},${VH*0.62} L 10,${VH*0.62} Z`} fill="#1a1a1a" stroke="#333" strokeWidth="0.5"/>
          {[0,1,2,3,4].map(i => {
            const mx = 22 + i * 72;
            const isMain = i === 2;
            return (
              <g key={i}>
                <rect x={mx} y={VH*0.18} width="60" height="72" fill="#0a0a0a" stroke={isMain ? accent : "#333"} strokeWidth={isMain ? 1 : 0.5} rx="2"/>
                <rect x={mx+2} y={VH*0.18+2} width="56" height="60" fill={isMain ? `rgba(91,183,226,0.06)` : "rgba(91,183,226,0.03)"}/>
                <polyline points={Array.from({length: 10}, (_, j) => `${mx+6+j*5.2},${VH*0.18+18+Math.sin(j*0.8+i)*12}`).join(" ")} fill="none" stroke={isMain ? accent : "rgba(91,183,226,0.4)"} strokeWidth={isMain ? 1.2 : 0.7}/>
                {[0,1,2].map(j => (
                  <rect key={j} x={mx+6} y={VH*0.18+42+j*8} width={20+j*10} height="2" fill={isMain && j===0 ? accent : "rgba(91,183,226,0.15)"} rx="1" opacity={isMain ? 0.6 : 0.3}/>
                ))}
                <ellipse cx={mx+30} cy={VH*0.58} rx="20" ry="4" fill={isMain ? accent : "rgba(91,183,226,0.3)"} opacity="0.04"/>
                <rect x={mx+25} y={VH*0.18+72} width="10" height="10" fill="#1a1a1a"/>
              </g>
            );
          })}
          {[90,200,310].map((x,i) => (
            <g key={`eng${i}`} opacity="0.12">
              <circle cx={x} cy={VH*0.12} r="5" fill="#fff"/>
              <rect x={x-4} y={VH*0.12+5} width="8" height="12" fill="#fff" rx="2"/>
              <path d={`M ${x-6},${VH*0.12-1} C ${x-6},${VH*0.12-7} ${x+6},${VH*0.12-7} ${x+6},${VH*0.12-1}`} fill="none" stroke="#fff" strokeWidth="1.5"/>
            </g>
          ))}
          {[0,1,2,3,4,5,6,7].map(i => (
            <rect key={`dp${i}`} x={50+i*42} y={VH*0.4} width="2" height="2" fill="rgba(91,183,226,0.3)" rx="0.5">
              <animate attributeName="y" from={VH*0.35} to={VH*0.08} dur={`${2+i*0.5}s`} begin={`${i*0.4}s`} repeatCount="indefinite"/>
              <animate attributeName="opacity" values="0;0.5;0" dur={`${2+i*0.5}s`} begin={`${i*0.4}s`} repeatCount="indefinite"/>
            </rect>
          ))}
          <rect x="0" y={VH*0.62} width={VW} height={VH*0.38} fill="url(#tg-floor)" opacity="0.5"/>
        </g>}

        {idx === 2 && <g>
          <rect width={VW} height={VH*0.35} fill="rgba(20,30,50,0.4)"/>
          {Array.from({length: 30}, (_, i) => {
            const y = 8 + i * 6.5;
            const nearCar = Math.abs(y - VH*0.48) < 30;
            const w = nearCar ? 2 : 0.6 + Math.random() * 0.4;
            const len = 80 + Math.random() * 250;
            const x = Math.random() * (VW - len);
            return <rect key={i} x={x} y={y} width={len} height={w} fill={nearCar ? accent : "rgba(91,183,226,0.12)"} opacity={nearCar ? 0.2 : 0.08} rx={w/2}/>;
          })}
          <rect x="0" y={VH*0.66} width={VW} height={VH*0.34} fill="rgba(30,30,35,0.8)"/>
          <line x1="0" y1={VH*0.66} x2={VW} y2={VH*0.66} stroke="rgba(255,255,255,0.06)" strokeWidth="0.5"/>
          {Array.from({length: 12}, (_, i) => (
            <rect key={i} x={i*34} y={VH*0.66} width="17" height="4" fill={i%2===0 ? "#C8102E" : "#E8E4DC"} opacity="0.2"/>
          ))}
          <g transform={`translate(${VW*0.48},${VH*0.52})`}>
            <rect x="-180" y="-3" width="100" height="6" fill={pri} opacity="0.06" rx="3"/>
            <rect x="-220" y="-1.5" width="70" height="3" fill={pri} opacity="0.03" rx="1.5"/>
            <path d={`M -95,0 C -92,-4 -82,-10 -65,-15 L -35,-19 C -10,-21 15,-22 40,-20 L 68,-14 C 78,-9 85,-4 88,0 L 92,4 L -98,4 Z`} fill={pri} stroke={accent} strokeWidth="1.2" filter="url(#tg-glow)"/>
            <line x1="-85" y1="-2" x2="82" y2="-2" stroke={sec} strokeWidth="4" opacity="0.5"/>
            <line x1="-83" y1="1" x2="80" y2="1" stroke={accent} strokeWidth="1" opacity="0.35"/>
            <ellipse cx="-8" cy="-13" rx="16" ry="6" fill="rgba(0,0,0,0.8)" stroke="rgba(255,255,255,0.08)" strokeWidth="0.4"/>
            <circle cx="-60" cy="6" r="13" fill="#0a0a0a" stroke="#333" strokeWidth="1"/>
            <circle cx="63" cy="6" r="14" fill="#0a0a0a" stroke="#333" strokeWidth="1"/>
            <circle cx="-60" cy="6" r="10" fill="none" stroke="rgba(255,255,255,0.06)" strokeWidth="0.5" strokeDasharray="2 4">
              <animateTransform attributeName="transform" type="rotate" from="0 -60 6" to="360 -60 6" dur="0.3s" repeatCount="indefinite"/>
            </circle>
            <circle cx="63" cy="6" r="11" fill="none" stroke="rgba(255,255,255,0.06)" strokeWidth="0.5" strokeDasharray="2 4">
              <animateTransform attributeName="transform" type="rotate" from="0 63 6" to="360 63 6" dur="0.3s" repeatCount="indefinite"/>
            </circle>
            <rect x="-100" y="-22" width="4" height="20" fill={sec} rx="1" opacity="0.7"/>
            <rect x="-104" y="-24" width="12" height="4" fill={accent} rx="1" opacity="0.6"/>
            <text x="25" y="0" fontSize="12" fontFamily="Geist, sans-serif" fontWeight="900" fill={accent} textAnchor="middle" opacity="0.5">{car.no}</text>
          </g>
          {[0,1,2].map(i => (
            <ellipse key={`ts${i}`} cx={VW*0.48-110-i*25} cy={VH*0.56} rx={15+i*10} ry={6+i*4} fill="rgba(200,200,200,0.03)" filter="url(#tg-blur)">
              <animate attributeName="rx" from={12+i*8} to={25+i*15} dur={`${1.5+i*0.5}s`} repeatCount="indefinite"/>
              <animate attributeName="opacity" values="0.04;0.01;0.04" dur={`${1.5+i*0.5}s`} repeatCount="indefinite"/>
            </ellipse>
          ))}
        </g>}

        {idx === 3 && <g>
          {Array.from({length: 20}, (_, i) => (
            <line key={`eg${i}`} x1={i*20} y1="0" x2={i*20} y2={VH} stroke="rgba(91,183,226,0.03)" strokeWidth="0.5"/>
          ))}
          {Array.from({length: 20}, (_, i) => {
            const y = 20 + i * 10;
            const nearBody = Math.abs(y - VH*0.45) < 28;
            const deflect = nearBody ? (y < VH*0.45 ? -15 : 12) * (1 - Math.abs(y - VH*0.45)/28) : 0;
            return (
              <path key={i} d={`M 0,${y} C 120,${y} 160,${y+deflect*0.5} 200,${y+deflect} S 270,${y+deflect*0.8} ${VW},${y+deflect*0.3}`} fill="none" stroke={nearBody ? accent : "rgba(91,183,226,0.1)"} strokeWidth={nearBody ? 1.5 : 0.6} opacity={nearBody ? 0.35 : 0.12} strokeDasharray={nearBody ? "15 6" : "none"}>
                {nearBody && <animate attributeName="stroke-dashoffset" from="0" to="-42" dur="1s" repeatCount="indefinite"/>}
              </path>
            );
          })}
          <g transform={`translate(${VW*0.5},${VH*0.45})`}>
            <ellipse rx="65" ry="22" fill={pri} opacity="0.5" stroke={accent} strokeWidth="1" filter="url(#tg-glow)"/>
            <text x="0" y="6" textAnchor="middle" fontSize="16" fontFamily="Geist, sans-serif" fontWeight="900" fill={accent} opacity="0.5">{car.no}</text>
          </g>
          {[0,1,2].map(i => {
            const vx = VW*0.5 - 80 - i * 25;
            return (
              <circle key={`vt${i}`} cx={vx} cy={VH*0.45} r={5+i*6} fill="none" stroke="rgba(239,68,68,0.12)" strokeWidth="0.7" strokeDasharray="2 3">
                <animateTransform attributeName="transform" type="rotate" from={`0 ${vx} ${VH*0.45}`} to={`${i%2===0?360:-360} ${vx} ${VH*0.45}`} dur={`${2+i}s`} repeatCount="indefinite"/>
              </circle>
            );
          })}
          <ellipse cx={VW*0.5+60} cy={VH*0.43} rx="10" ry="8" fill="rgba(239,68,68,0.08)">
            <animate attributeName="rx" values="8;12;8" dur="2s" repeatCount="indefinite"/>
          </ellipse>
          <ellipse cx={VW*0.5} cy={VH*0.35} rx="30" ry="5" fill="rgba(59,130,246,0.06)">
            <animate attributeName="opacity" values="0.04;0.08;0.04" dur="3s" repeatCount="indefinite"/>
          </ellipse>
        </g>}

        <rect width={VW} height={VH} fill="url(#tg-vfade)"/>
        </g>
      </svg>
    );
  };
  return (
    <div className="panel team-panel">
      {/* Team header */}
      <div className="team-header">
        <div className="team-badge" style={{borderColor: accent}}>
          <div className="team-badge-inner" style={{background: car.livery.primary}}>
            <span style={{color: accent, fontSize: 18, fontWeight: 900, fontFamily: "Geist, sans-serif"}}>{car.no}</span>
          </div>
        </div>
        <div className="team-info">
          <div className="team-name">{car.team}</div>
          <div className="team-sub">{car.chassis} · {car.engine}</div>
        </div>
      </div>

      {/* Image carousel — cinematic SVG scenes */}
      <div className="team-carousel">
        <div className="team-slide">
          {renderScene(slide)}
          <div className="team-slide-label">{scenes[slide].label}</div>
          <div className="team-slide-desc">{scenes[slide].desc}</div>
        </div>
        <div className="team-dots">
          {scenes.map((_, i) => (
            <button key={i} className={`team-dot ${i === slide ? "on" : ""}`}
              onClick={() => setSlide(i)} style={i === slide ? {background: accent} : {}}/>
          ))}
        </div>
      </div>

      {/* Crew */}
      <div className="team-crew">
        <div className="team-crew-title">CREW</div>
        <div className="team-crew-list">
          <div className="team-crew-item">
            <div className="team-crew-role">CREW CHIEF</div>
            <div className="team-crew-person">{car.crew_chief}</div>
          </div>
          <div className="team-crew-item">
            <div className="team-crew-role">RACE ENGINEER</div>
            <div className="team-crew-person">{car.race_engineer}</div>
          </div>
          <div className="team-crew-item">
            <div className="team-crew-role">DRIVER</div>
            <div className="team-crew-person">{car.name}</div>
          </div>
        </div>
      </div>

      {/* Sponsors */}
      <div className="team-sponsors">
        <div className="team-crew-title">PARTNERS</div>
        <div className="team-sponsor-row">
          <span className="team-sponsor-badge title" style={{borderColor: accent}}>{car.sponsors.title}</span>
          {car.sponsors.primary.map((s, i) => <span key={i} className="team-sponsor-badge">{s}</span>)}
        </div>
      </div>

      {/* Hear from the Pros */}
      <div className="team-pros">
        <div className="team-crew-title">HEAR FROM THE PROS</div>
        <div className="team-video">
          <iframe src="https://www.youtube.com/embed/ZvANa1aZCw0" title="Team Insight"
            frameBorder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
            allowFullScreen className="team-video-iframe"/>
        </div>
        <div className="team-pros-list">
          <div className="team-pro-card">
            <div className="team-pro-play">
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
                <circle cx="12" cy="12" r="11" stroke={accent} strokeWidth="1.5" opacity="0.6"/>
                <polygon points="10,7 18,12 10,17" fill={accent} opacity="0.8"/>
              </svg>
            </div>
            <div className="team-pro-info">
              <div className="team-pro-name">{car.crew_chief}</div>
              <div className="team-pro-role">CREW CHIEF</div>
              <div className="team-pro-quote">"Setup is everything at {car.team}. We chase the balance lap by lap."</div>
            </div>
          </div>
          <div className="team-pro-card">
            <div className="team-pro-play">
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
                <circle cx="12" cy="12" r="11" stroke={accent} strokeWidth="1.5" opacity="0.6"/>
                <polygon points="10,7 18,12 10,17" fill={accent} opacity="0.8"/>
              </svg>
            </div>
            <div className="team-pro-info">
              <div className="team-pro-name">{car.race_engineer}</div>
              <div className="team-pro-role">RACE ENGINEER</div>
              <div className="team-pro-quote">"Strategy calls win races. We model every scenario before the lights go out."</div>
            </div>
          </div>
          <div className="team-pro-card">
            <div className="team-pro-play">
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
                <circle cx="12" cy="12" r="11" stroke={accent} strokeWidth="1.5" opacity="0.6"/>
                <polygon points="10,7 18,12 10,17" fill={accent} opacity="0.8"/>
              </svg>
            </div>
            <div className="team-pro-info">
              <div className="team-pro-name">AERO DEPARTMENT</div>
              <div className="team-pro-role">TECHNICAL INSIGHT</div>
              <div className="team-pro-quote">"Every surface is a wing. We find downforce in places the regulations forgot to restrict."</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// =============================================================
// BROADCAST OVERLAY — full-bleed track + 3 lower-thirds
// =============================================================
function BroadcastOverlay({ cars, focused, track, trackEvent, carClass, raceState, sample }) {
  if (!focused) return null;
  const sorted = [...cars].sort((a,b) => a.pos - b.pos);
  const top3 = sorted.slice(0, 3);
  const tele = useM(() => window.APEX_DATA.generateTelemetry(focused.no), [focused.no]);
  const cur = tele[sample % 100];
  const tint = focused.livery.accent === "#FFFFFF" ? "#E8E4DC" : focused.livery.accent;

  return (
    <div className="bcast">
      <window.AudioToggle/>
      {/* Top eyebrow band */}
      <div className="bcast-top">
        <div className="bcast-network">
          <span className="brand-mark">▲</span>
          <span className="bcast-net-name">APEX</span>
          <span className="bcast-net-sub">LIVE · ROUND 04</span>
        </div>
        <div className="bcast-event">{trackEvent.event} · {trackEvent.date}</div>
        <div className="bcast-flag">
          <span className="bc-dot" style={{background: "#7DC383", boxShadow: "0 0 8px #7DC383"}}/>
          GREEN FLAG
        </div>
      </div>

      {/* LEFT lower-third: standings (top 3) */}
      <div className="bcast-lt bcast-lt-l">
        <div className="bcast-lt-head">
          <span className="bcast-lt-eyebrow">RUNNING ORDER</span>
          <span className="bcast-lt-meta">L{raceState.lap}/{track.laps}</span>
        </div>
        {top3.map((c, i) => (
          <div key={c.no} className={`bcast-row ${focused.no === c.no ? "on" : ""}`}>
            <span className="bcast-pos">{String(c.pos).padStart(2,"0")}</span>
            <span className="bcast-livery" style={{background: c.livery.primary, borderColor: c.livery.secondary}}/>
            <span className="bcast-driver">{c.name.split(" ").slice(-1)[0]}</span>
            <span className="bcast-team">{c.short}</span>
            <span className="bcast-gap">{c.gap}</span>
          </div>
        ))}
      </div>

      {/* CENTER lower-third: focused driver hero */}
      <div className="bcast-lt bcast-lt-c" style={{borderTopColor: tint}}>
        <div className="bcast-hero-no" style={{color: tint}}>{String(focused.no).padStart(2,"0")}</div>
        <div className="bcast-hero-info">
          <div className="bcast-lt-eyebrow">FOCUSED · POS {String(focused.pos).padStart(2,"0")}</div>
          <div className="bcast-hero-name">{focused.name}</div>
          <div className="bcast-hero-team" style={{color: tint}}>{focused.team}</div>
          <div className="bcast-hero-stats">
            <span><b>{focused.last_lap}</b><i>LAST</i></span>
            <span><b>{focused.best_lap}</b><i>BEST</i></span>
            <span><b>{focused.tire}<sub>{focused.tire_age}</sub></b><i>TYRE</i></span>
            <span><b>{focused.gap}</b><i>GAP</i></span>
          </div>
        </div>
      </div>

      {/* RIGHT lower-third: live telemetry stack */}
      <div className="bcast-lt bcast-lt-r">
        <div className="bcast-lt-head">
          <span className="bcast-lt-eyebrow">TELEMETRY · #{focused.no}</span>
          <span className="bcast-live"><span className="bc-dot"/>LIVE</span>
        </div>
        <div className="bcast-tele-row">
          <div className="bcast-tele-stat">
            <i>SPEED</i>
            <b>{Math.round(cur.speed)}</b><u>kph</u>
          </div>
          <div className="bcast-tele-stat">
            <i>THR</i>
            <b style={{color: "#7DC383"}}>{Math.round(cur.throttle)}</b><u>%</u>
          </div>
          <div className="bcast-tele-stat">
            <i>BRK</i>
            <b style={{color: "#C8102E"}}>{Math.round(cur.brake)}</b><u>%</u>
          </div>
        </div>
        <div className="bcast-tb-bars">
          <div className="bcast-tb-bar"><div className="bcast-tb-fill bcast-thr" style={{width: `${cur.throttle}%`}}/></div>
          <div className="bcast-tb-bar"><div className="bcast-tb-fill bcast-brk" style={{width: `${cur.brake}%`}}/></div>
        </div>
      </div>

      {/* Corner marks — TV bug */}
      <div className="bcast-bug">
        <span className="bcast-bug-mark">▲</span>
        <span className="bcast-bug-text">APEX</span>
        <span className="bcast-bug-live"><span className="bc-dot"/>LIVE</span>
      </div>

      <div className="bcast-hint">PRESS <kbd>B</kbd> OR <kbd>ESC</kbd> TO EXIT</div>
    </div>
  );
}

