import { HISTORICAL_EVENTS, eventEndYear, eventInView } from '../data/historical-events';
import './TimelineEventGuides.css';

function yearToPercent(year: number, start: number, end: number): number {
  return ((year - start) / (end - start)) * 100;
}

interface Props {
  viewStart: number;
  viewEnd: number;
}

export default function TimelineEventGuides({ viewStart, viewEnd }: Props) {
  const events = HISTORICAL_EVENTS.filter((event) => eventInView(event, viewStart, viewEnd));

  return (
    <div className="timeline-event-guides" aria-hidden>
      {events.map((event) => {
        const end = eventEndYear(event);
        const isSpan = event.endYear != null && event.endYear !== event.startYear;

        if (isSpan) {
          const left = yearToPercent(Math.max(event.startYear, viewStart), viewStart, viewEnd);
          const right = yearToPercent(Math.min(end, viewEnd), viewStart, viewEnd);
          if (right <= 0 || left >= 100) return null;
          const width = Math.min(100, right) - Math.max(0, left);

          return (
            <div
              key={event.id}
              className="timeline-event-guide-span"
              style={{
                left: `${Math.max(0, left)}%`,
                width: `${width}%`,
              }}
            />
          );
        }

        if (event.startYear < viewStart || event.startYear > viewEnd) return null;
        const left = yearToPercent(event.startYear, viewStart, viewEnd);

        return (
          <div
            key={event.id}
            className="timeline-event-guide-line"
            style={{ left: `${left}%` }}
          />
        );
      })}
    </div>
  );
}
