import { useEffect, useId, useLayoutEffect, useRef, useState } from "react";
import type { PointerEvent } from "react";
import "./overview-timeline.css";

const duration = 60;
const initialMinute = 24;

type Track = "human" | "assisted" | "agent";

const intervals: { kind: Track; start: number; end: number; label: string; anchor?: true }[] = [
  { kind: "human", start: 2, end: 11, label: "Edit a file" },
  { kind: "human", start: 21, end: 32, label: "Edit a different file", anchor: true },
  { kind: "human", start: 50, end: 57, label: "Check the changes" },
  { kind: "assisted", start: 11, end: 16, label: "Write a prompt" },
  { kind: "assisted", start: 41, end: 50, label: "Review the agent’s reply" },
  { kind: "agent", start: 16, end: 41, label: "Agent runs its turn", anchor: true },
];

const tracks = {
  human: "Human work",
  assisted: "AI-assisted work",
  agent: "Agent runtime",
};

const phases = [
  { name: "human", start: 0.02, end: 0.88 },
  { name: "agent", start: 0.09, end: 0.94 },
  { name: "guide", start: 0.18, end: 1 },
  { name: "rail", start: 0, end: 0.76 },
];

const clamp = (value: number) => Math.max(0, Math.min(1, value));

function smoothstep(value: number) {
  const t = clamp(value);
  return t * t * (3 - 2 * t);
}

function clock(minute: number) {
  return minute === duration ? "11:00" : `10:${String(minute).padStart(2, "0")}`;
}

const position = (minute: number) => `${minute / duration * 100}%`;

function pointerMinute(event: PointerEvent<HTMLInputElement>) {
  const bounds = event.currentTarget.getBoundingClientRect();
  return Math.round(clamp((event.clientX - bounds.left) / bounds.width) * duration);
}

export default function OverviewTimeline() {
  const id = useId();
  const stage = useRef<HTMLDivElement>(null);
  const chart = useRef<HTMLElement>(null);
  const explore = useRef<HTMLButtonElement>(null);
  const range = useRef<HTMLInputElement>(null);
  const move = useRef<(target: 0 | 1) => void>(null);
  const redrawGuide = useRef<() => void>(null);
  const dragPointer = useRef<number | null>(null);
  const [minute, setMinute] = useState(initialMinute);
  const [preview, setPreview] = useState<number | null>(null);
  const active = intervals.filter(({ start, end }) => start <= minute && minute < end);
  const time = clock(minute);
  const reading = active.map(({ kind, label }) => `${tracks[kind]}: ${label}`).join(". ") || "No activity at this time";

  useEffect(() => {
    const host = stage.current;
    const panel = chart.current;
    const button = explore.current;
    const slider = range.current;
    if (!host || !panel || !button || !slider) return;

    const pieces = phases.flatMap(phase => {
      const block = host.querySelector<HTMLElement>(`[data-block="${phase.name}"]`);
      const target = panel.querySelector<HTMLElement>(`[data-target="${phase.name}"]`);
      return block && target ? [{ ...phase, block, target }] : [];
    });
    const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)");
    let progress = 0;
    let open = false;
    let frame = 0;
    let override: { to: 0 | 1; scroll: number } | undefined;
    let animation: { from: number; to: 0 | 1; start: number } | undefined;

    function place(piece: typeof pieces[number]) {
      const { block, target, name, start, end } = piece;
      const phase = smoothstep((progress - start) / (end - start));
      // The children share the same stage. The offset parent's bounds give
      // the original mark position independently of the current transform.
      const origin = block.parentElement?.getBoundingClientRect();
      if (!origin) return;
      const mark = getComputedStyle(block);
      const bounds = target.getBoundingClientRect();
      const x = bounds.left - origin.left - parseFloat(mark.left);
      const y = bounds.top - origin.top - parseFloat(mark.top);
      const scaleX = 1 + (bounds.width / parseFloat(mark.width) - 1) * phase;
      const scaleY = 1 + (bounds.height / parseFloat(mark.height) - 1) * phase;
      block.style.transform = phase ? `translate(${x * phase}px, ${y * phase}px) scale(${scaleX}, ${scaleY})` : "";
      if (name === "agent") {
        const radius = bounds.height / 2 * phase;
        block.style.borderRadius = `${radius / scaleX}px / ${radius / scaleY}px`;
      }
    }

    const render = (next: number) => {
      const reveal = smoothstep((next - 0.38) / 0.48);
      const opacity = smoothstep((next - 0.42) / 0.45);
      const detail = smoothstep((next - 0.56) / 0.34);
      const ready = next === 1;
      if (progress > 0 && next === 0) setMinute(initialMinute);
      progress = next;
      host.style.setProperty("--mark-ui", String(1 - smoothstep(next / 0.3)));
      host.style.setProperty("--chart-ui", String(opacity));
      host.style.setProperty("--chart-detail", String(detail));
      host.style.setProperty("--chart-reveal", `${opacity * 100}%`);
      host.style.setProperty("--chart-clip", reveal === 1 ? "none" : `inset(${(1 - reveal) * 50}% 0)`);
      host.toggleAttribute("data-revealing", opacity > 0);
      pieces.forEach(place);

      if (ready === open) return;
      open = ready;
      button.setAttribute("aria-expanded", String(ready));
      if (ready) {
        panel.inert = false;
        if (document.activeElement === button) slider.focus({ preventScroll: true });
        button.inert = true;
      } else {
        dragPointer.current = null;
        setPreview(null);
        button.inert = false;
        if (panel.contains(document.activeElement)) button.focus({ preventScroll: true });
        panel.inert = true;
      }
    };

    const update = (now: number) => {
      frame = 0;
      const viewport = document.documentElement.clientHeight;
      const bounds = host.getBoundingClientRect();
      const start = Math.max(viewport * 0.55, viewport - bounds.height - 20);
      const distance = Math.min(220, start * 0.65);
      const scrolled = clamp((start - bounds.top) / distance);
      const reduce = reducedMotion.matches;

      if (animation) {
        const elapsed = reduce ? 1 : clamp((now - animation.start) / 420);
        const { from, to } = animation;
        render(from + (to - from) * smoothstep(elapsed));
        if (elapsed < 1) {
          queue();
          return;
        }
        animation = undefined;
      }

      if (bounds.bottom <= 0 || bounds.top >= viewport) override = undefined;
      // Continue from the chosen state as scrolling resumes, without moving the page.
      const next = override ? clamp(override.to + (window.scrollY - override.scroll) / distance) : scrolled;
      if (next === scrolled && (next === 0 || next === 1)) override = undefined;
      render(reduce ? Number(next >= 0.6) : next >= 0.995 ? 1 : next);
    };

    const queue = () => {
      if (!frame) frame = requestAnimationFrame(update);
    };

    move.current = (to) => {
      override = { to, scroll: window.scrollY };
      animation = { from: progress, to, start: performance.now() };
      queue();
    };

    redrawGuide.current = () => {
      const guide = pieces.find(piece => piece.name === "guide");
      if (guide && progress > 0) place(guide);
    };

    const resize = new ResizeObserver(queue);
    resize.observe(host);
    resize.observe(panel);
    const visible = new IntersectionObserver(([entry]) => {
      if (entry.isIntersecting) window.addEventListener("scroll", queue, { passive: true });
      else window.removeEventListener("scroll", queue);
      queue();
    });
    visible.observe(host);
    reducedMotion.addEventListener("change", queue);
    queue();

    return () => {
      visible.disconnect();
      resize.disconnect();
      window.removeEventListener("scroll", queue);
      reducedMotion.removeEventListener("change", queue);
      cancelAnimationFrame(frame);
      move.current = null;
      redrawGuide.current = null;
    };
  }, []);

  useLayoutEffect(() => {
    redrawGuide.current?.();
  }, [minute]);

  return (
    <div
      className="overview-timeline"
      ref={stage}
      onKeyDown={(event) => {
        if (event.key === "Escape" && event.target instanceof Node && chart.current?.contains(event.target)) {
          event.preventDefault();
          move.current?.(0);
        }
      }}
    >
      <button
        type="button"
        className="morph-explore"
        ref={explore}
        aria-controls={`${id}-chart`}
        aria-expanded={false}
        onClick={() => move.current?.(1)}
      >
        <span>Explore the timeline <span aria-hidden="true">↓</span></span>
      </button>

      <section className="morph-chart" id={`${id}-chart`} aria-labelledby={`${id}-title`} inert ref={chart}>
        <header className="morph-heading">
          <h3 id={`${id}-title`}>An hour with an agent</h3>
          <div>
            <p>Synthetic activity</p>
            <button type="button" onClick={() => move.current?.(0)}>
              <span aria-hidden="true">↖</span> Back to mark
            </button>
          </div>
        </header>

        <div className="morph-plot">
          <div aria-hidden="true">
            {Object.entries(tracks).map(([kind, name]) => (
              <div key={kind} className="morph-row" data-kind={kind}>
                <div className="morph-label"><i />{name}</div>
                <div className="morph-track">
                  {intervals.filter(span => span.kind === kind).map(span => (
                    <span
                      key={span.start}
                      className="morph-segment"
                      style={{ left: position(span.start), width: position(span.end - span.start) }}
                      data-target={span.anchor ? kind : undefined}
                      data-active={active.includes(span) ? "" : undefined}
                    />
                  ))}
                </div>
              </div>
            ))}
            <div className="morph-grid">{[0, 15, 30, 45, 60].map(tick => <i key={tick} />)}</div>
          </div>

          <div className="morph-axis">
            <label htmlFor={`${id}-minute`}>Scrub the timeline</label>
            <div className="morph-ruler" aria-hidden="true">
              <span className="morph-baseline" data-target="rail" />
              {[0, 15, 30, 45, 60].map(tick => <span key={tick} style={{ left: position(tick) }}>{clock(tick)}</span>)}
            </div>
          </div>
          <div className="morph-scrub">
            <input
              id={`${id}-minute`}
              ref={range}
              type="range"
              min={0}
              max={duration}
              step={1}
              value={minute}
              aria-valuetext={`${time}. ${reading}.`}
              aria-describedby={`${id}-help`}
              onChange={event => setMinute(event.currentTarget.valueAsNumber)}
              onPointerDown={event => {
                if (!event.isPrimary || event.button !== 0) return;
                event.preventDefault();
                dragPointer.current = event.pointerId;
                event.currentTarget.focus({ preventScroll: true });
                event.currentTarget.setPointerCapture(event.pointerId);
                setPreview(null);
                setMinute(pointerMinute(event));
              }}
              onPointerMove={event => {
                if (event.pointerId === dragPointer.current) setMinute(pointerMinute(event));
                else if (event.pointerType === "mouse" && dragPointer.current === null) setPreview(pointerMinute(event));
              }}
              onPointerUp={event => {
                if (event.pointerId === dragPointer.current) setMinute(pointerMinute(event));
              }}
              onLostPointerCapture={() => { dragPointer.current = null; }}
              onPointerLeave={() => setPreview(null)}
            />
            <span className="morph-guide" data-target="guide" style={{ left: position(minute) }} aria-hidden="true" />
            <span className="morph-handle" style={{ left: position(minute) }} aria-hidden="true" />
            {preview !== null && preview !== minute && (
              <span className="morph-preview" style={{ left: position(preview) }} aria-hidden="true">
                <span>{clock(preview)}</span>
              </span>
            )}
          </div>
        </div>

        <p id={`${id}-help`} className="sr-only">
          Use the arrow keys to move one minute. Home and End jump to the start and end of the hour.
          Press Escape to return to the Parallax mark.
        </p>
        <div className="morph-reading">
          <time dateTime={time}>{time}</time>
          <ul aria-label="Activity at the selected time">
            {active.length ? active.map(({ kind, label }) => (
              <li key={kind} data-kind={kind}><i aria-hidden="true" /><strong>{tracks[kind]}</strong> · {label}</li>
            )) : <li>No activity at this time</li>}
          </ul>
        </div>
      </section>

      <div className="morph-blocks" aria-hidden="true">
        {phases.map(({ name }) => (
          <span
            key={name}
            data-block={name}
            data-kind={name}
            data-active={active.some(span => span.anchor && span.kind === name) ? "" : undefined}
          />
        ))}
      </div>
    </div>
  );
}
