"use client";

import { useLayoutEffect, useRef } from "react";

import gsap from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";

gsap.registerPlugin(ScrollTrigger);

const MILESTONES = [
  {
    year: "2000",
    text: "Established the supply and maintenance business for UPS systems under the registered GV PowerGuard® brand.",
  },
  {
    year: "2014",
    text: "Expanded the business into renewable energy, offering solutions in solar photovoltaic, bio-energy, hydro electric power and geothermal.",
  },
];

/** Two milestone rows joined by a line that draws across on scroll. */
export default function Timeline() {
  const lineRef = useRef<HTMLDivElement | null>(null);

  useLayoutEffect(() => {
    const el = lineRef.current;
    if (!el) return;

    const mq = gsap.matchMedia();
    mq.add("(prefers-reduced-motion: no-preference)", () => {
      // The line is 1px wide; growth must happen along its length (scaleY).
      const tween = gsap.fromTo(
        el,
        { scaleY: 0 },
        {
          scaleY: 1,
          ease: "none",
          scrollTrigger: {
            trigger: el,
            start: "top 85%",
            end: "bottom 60%",
            scrub: 1,
          },
        }
      );
      return () => {
        tween.scrollTrigger?.kill();
        tween.kill();
      };
    });

    return () => mq.revert();
  }, []);

  return (
    <div className="relative">
      {/* Runners */}
      <div className="absolute left-8 top-0 bottom-0 hidden w-px -translate-x-1/2 border-l border-dashed border-line md:block" />
      <div className="absolute left-8 top-0 bottom-0 hidden w-px -translate-x-1/2 md:block">
        <div
          ref={lineRef}
          className="h-full w-px origin-top bg-accent"
          style={{ transform: "scaleY(1)" }}
        />
      </div>

      <ol className="space-y-10 md:ml-16 md:space-y-14">
        {MILESTONES.map((m) => (
          <li key={m.year} className="relative flex items-start gap-6 md:gap-10">
            <div className="relative z-10 mt-1 hidden h-5 w-5 shrink-0 rounded-full border-[3px] border-accent bg-surface md:block" />
            <div>
              <p className="font-display text-2xl font-semibold tracking-tight text-accent">
                {m.year}
              </p>
              <p className="mt-2 max-w-md text-base leading-relaxed text-ink-soft">
                {m.text}
              </p>
            </div>
          </li>
        ))}
      </ol>
    </div>
  );
}
