"use client";

import { LazyMotion, domAnimation, m, useScroll, useTransform } from "motion/react";
import { useEffect, useRef, useState } from "react";
import type { ProcessStep } from "@/content/types";
import { cn } from "@/lib/cn";

const stepId = (step: ProcessStep) => `step-${step.name.toLowerCase()}`;

/** Six-phase process: sticky step index with a scroll-linked progress line, large numerals, three detail rows. */
export function ProcessTimeline({ steps }: { steps: ProcessStep[] }) {
  const [active, setActive] = useState(0);
  const listRef = useRef<HTMLDivElement>(null);
  const stepRefs = useRef<(HTMLElement | null)[]>([]);
  const { scrollYProgress } = useScroll({ target: listRef, offset: ["start 55%", "end 55%"] });
  const progress = useTransform(scrollYProgress, [0, 1], [0, 1]);

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        for (const entry of entries) {
          if (!entry.isIntersecting) continue;
          const index = stepRefs.current.indexOf(entry.target as HTMLElement);
          if (index > -1) setActive(index);
        }
      },
      { rootMargin: "-40% 0px -50% 0px" },
    );
    stepRefs.current.forEach((element) => element && observer.observe(element));
    return () => observer.disconnect();
  }, []);

  return (
    <LazyMotion features={domAnimation} strict>
      <div className="mt-14 grid gap-10 lg:mt-20 lg:grid-cols-12 lg:gap-6">
        <nav aria-label="Process phases" className="hidden lg:col-span-3 lg:block">
          <div className="sticky top-28">
            <div className="relative pl-6">
              <div aria-hidden="true" className="absolute bottom-3 left-0 top-3 w-px bg-line">
                <m.div className="h-full w-px origin-top bg-signal" style={{ scaleY: progress }} />
              </div>
              <ol>
                {steps.map((step, index) => (
                  <li key={step.index}>
                    <a
                      href={`#${stepId(step)}`}
                      aria-current={active === index ? "step" : undefined}
                      className={cn(
                        "flex items-baseline gap-3 py-2 text-lg tracking-[-0.01em] transition-colors duration-300",
                        active === index ? "text-ink" : "text-muted hover:text-ink",
                      )}
                    >
                      <span className={cn("font-mono text-data", active === index && "text-signal")}>{step.index}</span>
                      {step.name}
                    </a>
                  </li>
                ))}
              </ol>
            </div>
          </div>
        </nav>

        <div ref={listRef} className="lg:col-span-9">
          {steps.map((step, index) => (
            <article
              key={step.index}
              id={stepId(step)}
              ref={(element) => {
                stepRefs.current[index] = element;
              }}
              aria-labelledby={`${stepId(step)}-title`}
              className="grid gap-6 border-t border-line py-10 lg:grid-cols-9 lg:gap-6 lg:py-14"
            >
              <div className="lg:col-span-3">
                <span
                  aria-hidden="true"
                  className={cn(
                    "block text-[4.5rem] font-medium leading-none tracking-[-0.06em] transition-colors duration-500 sm:text-[5.5rem]",
                    active === index ? "text-signal" : "text-ink/[0.12]",
                  )}
                >
                  {step.index}
                </span>
                <h3 id={`${stepId(step)}-title`} className="mt-3 text-display-md">
                  {step.name}
                </h3>
              </div>
              <dl className="grid gap-6 sm:grid-cols-3 lg:col-span-6 lg:pt-3">
                <div>
                  <dt className="text-label uppercase text-muted">What happens</dt>
                  <dd className="mt-3 text-[0.9375rem] text-ink-soft">{step.whatHappens}</dd>
                </div>
                <div>
                  <dt className="text-label uppercase text-muted">You receive</dt>
                  <dd className="mt-3 text-[0.9375rem] text-ink">{step.youReceive}</dd>
                </div>
                <div>
                  <dt className="text-label uppercase text-muted">Decision next</dt>
                  <dd className="mt-3 text-[0.9375rem] text-ink-soft">{step.decisionNext}</dd>
                </div>
              </dl>
            </article>
          ))}
        </div>
      </div>
    </LazyMotion>
  );
}
