"use client";

import { useRef } from "react";
import Link from "next/link";
import { motion, useScroll, useTransform } from "motion/react";
import { divisions } from "@/content/divisions";
import { FabricPattern, type FabricKind } from "@/components/media/FabricPattern";
import { cn } from "@/lib/utils";

const PANEL_ART: Record<string, { kind: FabricKind; tone: React.CSSProperties }> = {
  knitwear: {
    kind: "knit",
    tone: {
      "--pattern-a": "#171c2b",
      "--pattern-b": "#222b40",
      "--pattern-c": "#0d1220",
      "--pattern-thread": "#f5f1e8",
      "--pattern-glow": "#e0a458",
      "--pattern-slub": "#f5f1e8",
    } as React.CSSProperties,
  },
  denim: {
    kind: "twill",
    tone: {
      "--pattern-a": "#101838",
      "--pattern-b": "#1b2a5b",
      "--pattern-c": "#060a18",
      "--pattern-thread": "#93a7e8",
      "--pattern-glow": "#3a56a6",
      "--pattern-slub": "#f5f1e8",
    } as React.CSSProperties,
  },
  "workwear-uniforms": {
    kind: "weave",
    tone: {
      "--pattern-a": "#191a0d",
      "--pattern-b": "#262713",
      "--pattern-c": "#0b0c06",
      "--pattern-thread": "#d8e04a",
      "--pattern-glow": "#d8e04a",
      "--pattern-slub": "#f5f1e8",
    } as React.CSSProperties,
  },
};

/**
 * The three divisions as a pinned horizontal run.
 *
 * The section is three viewports tall. While it is pinned, vertical scroll is
 * translated into horizontal travel across the panels. On narrow screens it
 * degrades to an ordinary vertical stack, because a pinned rail on a phone
 * fights the scroll gesture rather than helping it.
 */
export function DivisionsShowcase() {
  const ref = useRef<HTMLDivElement>(null);

  const { scrollYProgress } = useScroll({ target: ref });

  // Two panel widths of travel for three panels.
  const x = useTransform(scrollYProgress, [0, 1], ["0%", "-66.666%"]);

  return (
    <>
      {/* Pinned rail, wide screens. */}
      <section
        ref={ref}
        className="relative hidden h-[300vh] bg-[var(--ink-2)] lg:block"
        aria-labelledby="divisions-heading"
      >
        <div className="sticky top-0 h-screen overflow-hidden">
          <h2 id="divisions-heading" className="sr-only">
            Our divisions
          </h2>

          <motion.div
            className="flex h-full w-[300%]"
            // The rail is the only way to reach panels two and three, so it
            // stays scroll linked for everyone. It moves at the reader's own
            // pace and never on a timer.
            style={{ x }}
          >
            {divisions.map((division) => (
              <Panel key={division.id} division={division} />
            ))}
          </motion.div>

          <Progress progress={scrollYProgress} />
        </div>
      </section>

      {/* Vertical stack, narrow screens. */}
      <section className="bg-[var(--ink-2)] lg:hidden" aria-label="Our divisions">
        {divisions.map((division) => (
          <div key={division.id} className="relative min-h-[85svh]">
            <Panel division={division} />
          </div>
        ))}
      </section>
    </>
  );
}

function Panel({ division }: { division: (typeof divisions)[number] }) {
  const art = PANEL_ART[division.id];

  return (
    <article className="relative flex h-full w-full min-w-0 shrink-0 basis-full items-end overflow-hidden border-r border-[var(--rule)]">
      <FabricPattern
        kind={art.kind}
        seed={division.index.charCodeAt(1) * 31}
        className="absolute inset-0 h-full w-full"
        style={art.tone}
      />
      <div className="absolute inset-0 bg-gradient-to-t from-[var(--ink)] via-[var(--ink)]/55 to-transparent" />

      <div className="relative w-full px-[var(--gutter)] pb-16 pt-24 lg:pb-24">
        <div className="max-w-2xl">
          <p className="eyebrow flex items-center gap-3">
            <span className="data text-[var(--thread)]">{division.index}</span>
            <span className="h-px w-8 bg-[var(--thread)]" />
            {division.kicker}
          </p>

          <h3 className="display-lg mt-5 text-[var(--cotton)]">
            {division.name}
          </h3>

          <p className="lede mt-5 text-pretty">{division.blurb}</p>

          <ul className="mt-8 flex flex-wrap gap-2">
            {division.highlights.map((item) => (
              <li
                key={item}
                className="rounded-full border border-[var(--rule)] bg-[var(--ink)]/40 px-3.5 py-1.5 font-mono text-[11px] tracking-wide text-[var(--cotton)]/80 backdrop-blur-sm"
              >
                {item}
              </li>
            ))}
          </ul>

          <Link
            href={division.href}
            className="group mt-10 inline-flex items-center gap-3 text-sm text-[var(--cotton)]"
          >
            <span className="relative">
              Enter {division.name.toLowerCase()}
              <span className="absolute -bottom-1 left-0 h-px w-full origin-left scale-x-0 bg-[var(--thread)] transition-transform duration-500 ease-[cubic-bezier(0.16,1,0.3,1)] group-hover:scale-x-100" />
            </span>
            <span
              aria-hidden="true"
              className="transition-transform duration-500 ease-[cubic-bezier(0.16,1,0.3,1)] group-hover:translate-x-1.5"
            >
              &rarr;
            </span>
          </Link>
        </div>
      </div>
    </article>
  );
}

function Progress({
  progress,
}: {
  progress: ReturnType<typeof useScroll>["scrollYProgress"];
}) {
  const width = useTransform(progress, [0, 1], ["0%", "100%"]);

  return (
    <div
      className={cn(
        "absolute inset-x-[var(--gutter)] bottom-8 h-px bg-[var(--rule)]",
      )}
      aria-hidden="true"
    >
      <motion.span
        className="absolute inset-y-0 left-0 block bg-[var(--thread)]"
        style={{ width }}
      />
    </div>
  );
}
