// LAP TIMELINE — horizontal scrub bar showing race events lap by lap
(function() {
  const useS = React.useState;
  const useM = React.useMemo;

  // Generate lap events from race data
  function generateLapEvents(totalLaps, pitLog) {
    const events = [];
    const pitLaps = new Set();
    if (pitLog) pitLog.forEach(p => pitLaps.add(p.lap));

    for (let i = 1; i <= totalLaps; i++) {
      if (i === 1) events.push({ lap: i, type: "start" });
      else if (pitLaps.has(i)) events.push({ lap: i, type: "pit" });
      else if (i === 31) events.push({ lap: i, type: "fastest" });
      else if (i % 17 === 0 || i % 23 === 0) events.push({ lap: i, type: "overtake" });
      else if (i === Math.floor(totalLaps * 0.33) || i === Math.floor(totalLaps * 0.66))
        events.push({ lap: i, type: "sc" });
      else events.push({ lap: i, type: "green" });
    }
    return events;
  }

  function LapTimeline({ currentLap, totalLaps, focusedCar }) {
    const [hoverLap, setHoverLap] = useS(null);
    const events = useM(() => generateLapEvents(totalLaps), [totalLaps]);

    return (
      <div className="tl-wrap">
        <div className="tl-header">
          <span className="tl-label">LAP TIMELINE</span>
          <span className="tl-range">
            {hoverLap ? `L${hoverLap}` : `L${currentLap}/${totalLaps}`}
          </span>
        </div>
        <div className="tl-track">
          {events.map((e, i) => {
            const isCurrent = e.lap === currentLap;
            const isPast = e.lap < currentLap;
            return (
              <div
                key={i}
                className={`tl-col tl-${e.type} ${isCurrent ? "tl-current" : ""} ${isPast ? "tl-past" : ""} ${hoverLap === e.lap ? "tl-hover" : ""}`}
                onMouseEnter={() => setHoverLap(e.lap)}
                onMouseLeave={() => setHoverLap(null)}
                title={`Lap ${e.lap} — ${e.type}`}
              />
            );
          })}
        </div>
        <div className="tl-legend">
          <span className="tl-leg-item"><span className="tl-dot tl-dot-green"/>GREEN</span>
          <span className="tl-leg-item"><span className="tl-dot tl-dot-pit"/>PIT</span>
          <span className="tl-leg-item"><span className="tl-dot tl-dot-fastest"/>FASTEST</span>
          <span className="tl-leg-item"><span className="tl-dot tl-dot-overtake"/>OVERTAKE</span>
          <span className="tl-leg-item"><span className="tl-dot tl-dot-sc"/>SC</span>
        </div>
      </div>
    );
  }

  window.LapTimeline = LapTimeline;
})();
