import { formatTime } from "./editorPresentation";
import type { EditorTimelineWindow, EditorVisibilityTrack } from "./model/editorTypes";

type VisibilityTracksProps = {
  tracks: EditorVisibilityTrack[];
  window: EditorTimelineWindow;
  width: number;
  labelWidth: number;
  top: number;
  rowHeight: number;
};

export function VisibilityTracks({ tracks, window, width, labelWidth, top, rowHeight }: VisibilityTracksProps) {
  const span = Math.max(1, window.toMs - window.fromMs);
  const toX = (timeMs: number) => ((timeMs - window.fromMs) / span) * width;

  return (
    <>
      {tracks.map((track, index) => {
        const rowTop = top + index * rowHeight;
        return (
          <div className="tgu-editor-timeline__lane" key={track.id} style={{ top: rowTop, height: rowHeight }}>
            <div className="tgu-editor-timeline__lane-label" style={{ width: labelWidth }}>
              <span className="tgu-editor-visibility-label">
                <i style={{ background: track.color }} />
                {track.label}
              </span>
              <small>{track.kind === "target" ? "цель · видимость" : "станция · видимость"}</small>
            </div>
            <div className="tgu-editor-timeline__lane-body" style={{ left: labelWidth, width }}>
              {track.windows.map((visibilityWindow) => {
                if (visibilityWindow.endMs < window.fromMs || visibilityWindow.startMs > window.toMs) {
                  return null;
                }

                const left = toX(Math.max(visibilityWindow.startMs, window.fromMs));
                const right = toX(Math.min(visibilityWindow.endMs, window.toMs));
                return (
                  <div
                    className="tgu-editor-visibility-window"
                    key={`${visibilityWindow.startMs}-${visibilityWindow.endMs}`}
                    style={{
                      left,
                      width: Math.max(2, right - left),
                      borderColor: track.color,
                      background: `color-mix(in srgb, ${track.color} 22%, transparent)`
                    }}
                    title={`${track.label}: ${formatTime(visibilityWindow.startMs)}-${formatTime(visibilityWindow.endMs)}`}
                  />
                );
              })}
            </div>
          </div>
        );
      })}
    </>
  );
}
