"use client";

import { useRef } from "react";
import { motion, useScroll, useTransform, useReducedMotion } from "motion/react";
import { timeline } from "@/content/certifications";

/**
 * Seventy years, drawn as one continuous thread.
 *
 * The line fills as you scroll and each milestone knots on as the thread
 * reaches it, so the passage of time is carried by the motion rather than by a
 * row of dates.
 */
export function Timeline() {
  const ref = useRef<HTMLOListElement>(null);
  const reduced = useReducedMotion();

  const { scrollYProgress } = useScroll({
    target: ref,
    offset: ["start 70%", "end 70%"],
  });

  const height = useTransform(scrollYProgress, [0, 1], ["0%", "100%"]);

  return (
    <ol ref={ref} className="relative mt-16">
      {/* The thread. */}
      <div
        aria-hidden="true"
        className="absolute top-2 bottom-2 left-[7px] w-px bg-[var(--rule)] md:left-[calc(9rem+7px)]"
      >
        <motion.span
          className="absolute inset-x-0 top-0 block bg-[var(--thread)]"
          style={{ height }}
        />
      </div>

      {timeline.map((entry, i) => (
        <motion.li
          key={entry.year}
          className="relative pb-14 pl-10 last:pb-0 md:pl-[calc(9rem+2.5rem)]"
          initial={{ opacity: 0, y: 26 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true, amount: 0.5 }}
          transition={{ duration: reduced ? 0 : 0.7, ease: [0.16, 1, 0.3, 1] }}
        >
          {/* The knot. */}
          <span
            aria-hidden="true"
            className="absolute top-2 left-0 block h-[15px] w-[15px] rounded-full border border-[var(--thread)] bg-[var(--ink)] md:left-36"
          >
            <span className="absolute inset-[3px] rounded-full bg-[var(--thread)]" />
          </span>

          <span className="data absolute top-1 left-0 hidden w-32 text-right text-sm text-[var(--thread)] md:block">
            {entry.year}
          </span>

          <span className="data mb-2 block text-sm text-[var(--thread)] md:hidden">
            {entry.year}
          </span>

          <h3 className="display-md text-[1.375rem] text-[var(--cotton)] md:text-[1.75rem]">
            {entry.title}
          </h3>
          <p className="mt-3 max-w-2xl text-sm leading-relaxed text-[var(--melange)] md:text-base">
            {entry.body}
          </p>

          <span className="sr-only">
            Milestone {i + 1} of {timeline.length}
          </span>
        </motion.li>
      ))}
    </ol>
  );
}
