// Apex — main app shell — tab-based section layout

const { useState: useStateA, useEffect: useEffectA } = React;

// ── Section nav ──────────────────────────────────────────────
function SectionNav({ active, onTab }) {
  const tabs = [
    { id: "strategy",  label: "STRATEGY"  },
    { id: "telemetry", label: "TELEMETRY" },
    { id: "standings", label: "STANDINGS" },
    { id: "racelog",   label: "RACE LOG"  },
  ];
  return (
    <nav className="ax-section-nav" aria-label="Dashboard sections">
      <div className="ax-section-tabs">
        {tabs.map(t => (
          <button key={t.id}
            className={`ax-section-tab mono ${active === t.id ? "active" : ""}`}
            onClick={() => onTab(t.id)}>
            {t.label}
          </button>
        ))}
      </div>
      <div className="ax-section-meta">
        <span className="ax-live-badge">
          <span className="ax-live-pulse" aria-hidden="true"></span>
          <span className="mono">LIVE</span>
        </span>
        <span className="mono ax-section-time">14:53:14 · L32/78</span>
      </div>
    </nav>
  );
}

// ── Top bar ──────────────────────────────────────────────────
function TopBar({ scenario, onScenario, focusDriver, onFocus }) {
  const driver = DRIVERS.find(d => d.code === focusDriver);
  return (
    <header className="ax-top">
      <div className="ax-top-l">
        <a href="index.html" className="ax-home-btn" title="Back to home" aria-label="Back to home">
          <svg width="12" height="12" viewBox="0 0 12 12" fill="none" aria-hidden="true">
            <path d="M7.5 2L3 6L7.5 10" stroke="currentColor" strokeWidth="1.4"
              strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </a>
        <div className="ax-brand">
          <ApexChevron size={16} color="#FFB020" />
          <span className="ax-brand-word">APEX</span>
          <span className="ax-brand-dot"></span>
          <span className="ax-brand-tag mono">PIT WALL · STRATEGY COPILOT</span>
        </div>
      </div>

      <div className="ax-top-c">
        <div className="ax-session">
          <span className="ax-session-event mono">MONACO GP · 2024 · R08</span>
          <span className="ax-session-divider"></span>
          <span className="ax-session-lap">
            <span className="mono lap-current">L{String(RACE_META.currentLap).padStart(2,"0")}</span>
            <span className="lap-of mono">/ {RACE_META.totalLaps}</span>
          </span>
          <span className="ax-session-divider"></span>
          <span className="mono ax-session-flag">
            <span className="ax-flag-dot ax-flag-green" aria-hidden="true"></span>
            GREEN
          </span>
        </div>
      </div>

      <div className="ax-top-r">
        <div className="ax-driver-sel">
          <span className="ax-driver-label mono">FOCUS</span>
          <div className="ax-driver-chip">
            <span className="ax-driver-bar" style={{ background: driver.color }}></span>
            <span className="mono ax-driver-num">{String(driver.num).padStart(2,"0")}</span>
            <span className="ax-driver-code">{driver.code}</span>
          </div>
        </div>
        <ScenarioPicker value={scenario} onChange={onScenario} />
      </div>
    </header>
  );
}

// ── Scenario picker ──────────────────────────────────────────
function ScenarioPicker({ value, onChange }) {
  const opts = [
    { id: "default",  label: "DRY"      },
    { id: "undercut", label: "UNDERCUT" },
    { id: "rain",     label: "RAIN"     },
    { id: "safety",   label: "VSC"      },
  ];
  return (
    <div className="ax-scen">
      <span className="ax-scen-label mono">SCENARIO</span>
      <div className="ax-scen-group">
        {opts.map(o => (
          <button key={o.id}
            className={`ax-scen-btn mono ${value === o.id ? "active" : ""}`}
            onClick={() => onChange(o.id)}>
            {o.label}
          </button>
        ))}
      </div>
    </div>
  );
}

// ── Playback bar ─────────────────────────────────────────────
function PlaybackBar({ playing, speed, onPlay, onSpeed }) {
  return (
    <div className="ax-playback">
      <button className="ax-pb-btn" onClick={onPlay} title={playing ? "Pause" : "Play"}>
        {playing
          ? <svg width="10" height="12" viewBox="0 0 10 12"><rect x="0" y="0" width="3.5" height="12" fill="currentColor"/><rect x="6.5" y="0" width="3.5" height="12" fill="currentColor"/></svg>
          : <svg width="10" height="12" viewBox="0 0 10 12"><path d="M0 0 L10 6 L0 12 Z" fill="currentColor"/></svg>
        }
      </button>
      <div className="ax-pb-speeds">
        {[1, 4, 16].map(s => (
          <button key={s} className={`ax-pb-speed mono ${speed === s ? "active" : ""}`} onClick={() => onSpeed(s)}>
            {s}×
          </button>
        ))}
      </div>
      <div className="ax-pb-time mono">14:53:14 · L32 / 78</div>
      <div className="ax-pb-track">
        <div className="ax-pb-track-bg"></div>
        <div className="ax-pb-track-fill" style={{ width: `${(RACE_META.currentLap / RACE_META.totalLaps) * 100}%` }}></div>
        <div className="ax-pb-track-marker" style={{ left: `${(RACE_META.currentLap / RACE_META.totalLaps) * 100}%` }}></div>
      </div>
    </div>
  );
}

// ── Event log ────────────────────────────────────────────────
function EventLog() {
  return (
    <div className="ax-log">
      {EVENT_LOG.slice().reverse().map((e, i) => (
        <div key={i} className={`ax-log-row type-${e.type}`}>
          <span className="ax-log-lap mono">L{String(e.lap).padStart(2,"0")}</span>
          <span className="ax-log-time mono">{e.time}</span>
          <span className={`ax-log-tag type-${e.type} mono`}>{e.type.toUpperCase()}</span>
          <span className="ax-log-text">{e.text}</span>
        </div>
      ))}
    </div>
  );
}

// ── STRATEGY TAB ─────────────────────────────────────────────
function StrategyView({ scenario, focusDriver, onScenarioChange }) {
  const focusState = STATE[focusDriver];
  const focusDeg   = degAt(focusState.compound, focusState.tireAge);
  const nextLapDeg = degAt(focusState.compound, focusState.tireAge + 1);
  const degDelta   = nextLapDeg - focusDeg;

  return (
    <div className="ax-strategy-view">
      {/* Compact KPI strip — always visible at top of strategy */}
      <div className="ax-kpi-row">
        <Card padded={false} className="ax-kpi-card">
          <div className="ax-kpi-strip">
            <Kpi label="POS"       value={focusState.pos} />
            <Kpi label="GAP"       value={focusState.pos === 1 ? "LEAD" : `+${focusState.gap.toFixed(3)}`} unit={focusState.pos === 1 ? "" : "s"} />
            <Kpi label="INTERVAL"  value={focusState.pos === 1 ? "—" : `+${focusState.interval.toFixed(3)}`} unit={focusState.pos === 1 ? "" : "s"} />
            <Kpi label="LAST LAP"  value={formatLapTime(focusState.lastLap)} />
            <Kpi label="BEST LAP"  value={formatLapTime(focusState.bestLap)} accent="var(--ax-purple)" />
            <Kpi label="STINT AGE" value={focusState.tireAge} unit=" laps" />
            <Kpi label="DEG/LAP"   value={`+${degDelta.toFixed(3)}`} unit="s" accent={degDelta > 0.1 ? "var(--ax-red)" : null} />
            <Kpi label="LAPS LEFT" value={RACE_META.totalLaps - RACE_META.currentLap} />
          </div>
        </Card>
      </div>

      {/* Two-column strategy workspace */}
      <div className="ax-strategy-cols">
        {/* Left column: strategy data */}
        <div className="ax-strategy-data">
          <div className="ax-section-label">STRATEGY DATA</div>

          <Card title="Pit window" kicker="STRATEGIC HORIZON"
            right={<Pill tone="amber">OPTIMAL · L{PIT_WINDOW.optimalLap}</Pill>}>
            <PitWindowStrip />
            <div className="ax-pitwin-meta">
              <div><span className="ax-meta-lbl mono">UNDERCUT</span><span className="ax-meta-val mono">+{PIT_WINDOW.undercutGain.toFixed(1)}s vs {PIT_WINDOW.threat}</span></div>
              <div><span className="ax-meta-lbl mono">OVERCUT</span><span className="ax-meta-val mono">+{PIT_WINDOW.overcutRisk.toFixed(1)}s</span></div>
              <div><span className="ax-meta-lbl mono">REJOIN</span><span className="ax-meta-val mono">{PIT_WINDOW.outLapCleanAir ? "CLEAN AIR" : `TRAFFIC: ${PIT_WINDOW.trafficAtRejoin.join(", ")}`}</span></div>
            </div>
          </Card>

          <Card title="Tire degradation" kicker={`${focusState.compound} · STINT ${focusState.stint}`}
            right={<><CompoundDot compound={focusState.compound} /> <Pill tone="amber">PROJECTION</Pill></>}>
            <TireDegChart driver={focusDriver} />
          </Card>

          <Card title="Weather" kicker="RAIN PROBABILITY · NEXT 16 LAPS"
            right={<Pill tone="neutral">{RACE_META.trackTempC}°C TRACK</Pill>}>
            <WeatherStrip />
            <div className="ax-weather-meta">
              <div><span className="ax-meta-lbl mono">AIR</span><span className="ax-meta-val mono">{RACE_META.airTempC}°C</span></div>
              <div><span className="ax-meta-lbl mono">HUM.</span><span className="ax-meta-val mono">{RACE_META.humidity}%</span></div>
              <div><span className="ax-meta-lbl mono">WIND</span><span className="ax-meta-val mono">{RACE_META.windKph}kph NE</span></div>
            </div>
          </Card>
        </div>

        {/* Right column: AI engineer — primary action surface */}
        <div className="ax-strategy-engineer">
          <div className="ax-section-label">
            AI RACE ENGINEER
            <span className="ax-slabel-badge">
              <span className="ax-live-pulse" aria-hidden="true"></span>
              GRANITE 4.0
            </span>
          </div>
          <EngineerPanel
            scenario={scenario}
            focusDriver={focusDriver}
            onScenarioChange={onScenarioChange}
          />
        </div>
      </div>
    </div>
  );
}

// ── TELEMETRY TAB ────────────────────────────────────────────
function TelemetryView({ focusDriver }) {
  return (
    <div className="ax-telemetry-view">
      <div className="ax-section-label">LIVE TELEMETRY · {focusDriver}</div>
      <div className="ax-telemetry-grid">
        <Card title="Gap to leader" kicker="LAP CHART · TOP 6"
          right={<Pill tone="neutral">L1 → L{RACE_META.currentLap}</Pill>}
          className="ax-telem-main">
          <LapChart focusDriver={focusDriver} />
        </Card>
        <Card title="Sector delta" kicker={`MICRO-SECTORS · ${focusDriver} vs ${ORDER[1]}`}
          right={<span className="mono ax-mono-meta"><span className="ax-leg gain"></span> GAIN · <span className="ax-leg loss"></span> LOSS</span>}
          className="ax-telem-sectors">
          <MicroSectors />
        </Card>
        <Card title="Circuit" kicker="MONACO · 3.337 KM" className="ax-telem-track">
          <TrackMap focusDriver={focusDriver} />
        </Card>
      </div>
    </div>
  );
}

// ── STANDINGS TAB ────────────────────────────────────────────
function StandingsView({ focusDriver, onFocus }) {
  const focusState = STATE[focusDriver];
  const focusDrv   = DRIVERS.find(d => d.code === focusDriver);
  return (
    <div className="ax-standings-view">
      <div className="ax-section-label">RACE ORDER · LAP {RACE_META.currentLap}</div>
      <div className="ax-standings-grid">
        <Card title="Live standings" kicker="CLICK ROW TO FOCUS DRIVER"
          right={<Pill tone="neutral">10 RUNNERS</Pill>}
          className="ax-stand-main">
          <Standings focusDriver={focusDriver} onFocus={onFocus} />
        </Card>
        <div className="ax-driver-panel">
          <Card title={`${focusDriver} · Driver detail`} kicker="FOCUS DRIVER"
            right={
              <span style={{ width:"3px", height:"16px", background: focusDrv.color,
                display:"inline-block", borderRadius:"1px" }}></span>
            }>
            <div className="ax-dstats">
              {[
                ["TEAM",      focusDrv.team],
                ["NUMBER",    `#${focusDrv.num}`],
                ["COMPOUND",  focusState.compound],
                ["TIRE AGE",  `${focusState.tireAge} laps`],
                ["BEST LAP",  formatLapTime(focusState.bestLap)],
                ["LAST LAP",  formatLapTime(focusState.lastLap)],
                ["GAP",       focusState.pos === 1 ? "LEADER" : `+${focusState.gap.toFixed(3)}s`],
                ["INTERVAL",  focusState.pos === 1 ? "—" : `+${focusState.interval.toFixed(3)}s`],
                ["PITTED",    focusState.pitted ? "YES" : "NO"],
              ].map(([k, v]) => (
                <div key={k} className="ax-dstat-row">
                  <span className="ax-dstat-k mono">{k}</span>
                  <span className="ax-dstat-v mono">{v}</span>
                </div>
              ))}
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
}

// ── RACE LOG TAB ─────────────────────────────────────────────
function RaceLogView() {
  return (
    <div className="ax-racelog-view">
      <div className="ax-section-label">RACE TIMELINE · MONACO GP 2024</div>
      <Card title="Event log" kicker="SESSION TIMELINE"
        right={<Pill tone="neutral">L{RACE_META.currentLap}</Pill>}>
        <EventLog />
      </Card>
    </div>
  );
}

// ── APP ROOT ─────────────────────────────────────────────────
function App() {
  const [scenario,    setScenario]    = useStateA("default");
  const [focusDriver, setFocusDriver] = useStateA("LEC");
  const [playing,     setPlaying]     = useStateA(true);
  const [speed,       setSpeed]       = useStateA(4);
  const [activeTab,   setActiveTab]   = useStateA("strategy");

  const tweakDefaults = /*EDITMODE-BEGIN*/{
    "accentColor": "#FFB020",
    "showTrackMap": true,
    "showWeather":  true,
    "density":      "comfortable"
  }/*EDITMODE-END*/;
  const [tweaks, setTweak] = window.useTweaks
    ? window.useTweaks(tweakDefaults)
    : [tweakDefaults, () => {}];

  useEffectA(() => {
    document.documentElement.style.setProperty("--ax-amber", tweaks.accentColor);
  }, [tweaks.accentColor]);

  return (
    <div className="ax-app" data-density={tweaks.density}>
      <TopBar
        scenario={scenario}
        onScenario={setScenario}
        focusDriver={focusDriver}
        onFocus={setFocusDriver}
      />
      <SectionNav active={activeTab} onTab={setActiveTab} />

      <main className="ax-main">
        {activeTab === "strategy"  && (
          <StrategyView
            scenario={scenario}
            focusDriver={focusDriver}
            onScenarioChange={setScenario}
          />
        )}
        {activeTab === "telemetry" && <TelemetryView focusDriver={focusDriver} />}
        {activeTab === "standings" && <StandingsView focusDriver={focusDriver} onFocus={setFocusDriver} />}
        {activeTab === "racelog"   && <RaceLogView />}
      </main>

      <PlaybackBar playing={playing} speed={speed}
        onPlay={() => setPlaying(p => !p)} onSpeed={setSpeed} />

      {window.TweaksPanel && (
        <window.TweaksPanel title="Apex Tweaks">
          <window.TweakSection label="Brand">
            <window.TweakColor label="Accent" value={tweaks.accentColor}
              options={["#FFB020","#FF3B30","#27F4D2","#FAFAFA"]}
              onChange={(v) => setTweak("accentColor", v)} />
          </window.TweakSection>
          <window.TweakSection label="Layout">
            <window.TweakRadio label="Density" value={tweaks.density}
              options={[{value:"comfortable",label:"Comfortable"},{value:"compact",label:"Compact"}]}
              onChange={(v) => setTweak("density", v)} />
            <window.TweakToggle label="Track map" value={tweaks.showTrackMap}
              onChange={(v) => setTweak("showTrackMap", v)} />
            <window.TweakToggle label="Weather strip" value={tweaks.showWeather}
              onChange={(v) => setTweak("showWeather", v)} />
          </window.TweakSection>
        </window.TweaksPanel>
      )}
    </div>
  );
}

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