import Image from "next/image";
import type { CSSProperties } from "react";
import { revealProps } from "@/components/ui/reveal";
import type { PlatformItem } from "@/content/types";
import { cn } from "@/lib/cn";

/** Copies of each row in the track. Five keeps the loop filled past 4K widths. */
const COPIES = 5;

/** One pill: the platform's official mark in its own colours, with the name in the site face. */
function PlatformPill({ platform }: { platform: PlatformItem }) {
  return (
    <li className="flex shrink-0 items-center gap-3 rounded-lg border border-line bg-surface px-5 py-4 sm:px-6">
      <Image src={`/logos/${platform.logo}.svg`} alt="" width={32} height={28} className="h-7 w-8 shrink-0 object-contain" />
      <span className="whitespace-nowrap text-[1.0625rem] font-medium tracking-[-0.01em] sm:text-lg">{platform.name}</span>
    </li>
  );
}

interface MarqueeRowProps {
  platforms: PlatformItem[];
  direction: "left" | "right";
  /** Seconds for one copy to pass; the drift itself never ends. */
  seconds: number;
  /** Negative offset so the row is already mid-drift on first paint. */
  offset: number;
}

function MarqueeRow({ platforms, direction, seconds, offset }: MarqueeRowProps) {
  return (
    <div className="marquee overflow-hidden [mask-image:linear-gradient(90deg,transparent,#000_6%,#000_94%,transparent)]">
      <div
        className="marquee-track"
        data-direction={direction}
        style={
          {
            "--marquee-duration": `${seconds}s`,
            "--marquee-delay": `-${offset}s`,
            "--marquee-copies": COPIES,
          } as CSSProperties
        }
      >
        {Array.from({ length: COPIES }, (_, copy) => (
          <ul
            key={copy}
            className={cn("flex gap-4 pr-4", copy > 0 && "marquee-clone")}
            aria-hidden={copy > 0 ? "true" : undefined}
          >
            {platforms.map((platform) => (
              <PlatformPill key={`${platform.name}-${copy}`} platform={platform} />
            ))}
          </ul>
        ))}
      </div>
    </div>
  );
}

/** Platforms as two endlessly drifting rows: the top row to the right, the row below it to the left. */
export function PlatformMarquee({ platforms, footnote, className }: { platforms: PlatformItem[]; footnote: string; className?: string }) {
  const half = Math.ceil(platforms.length / 2);

  return (
    <div className={cn("mt-14 lg:mt-20", className)} {...revealProps()}>
      <div className="flex flex-col gap-4">
        <MarqueeRow platforms={platforms.slice(0, half)} direction="right" seconds={38} offset={11} />
        <MarqueeRow platforms={platforms.slice(half)} direction="left" seconds={44} offset={27} />
      </div>
      <div className="container-page">
        <p className="mt-10 max-w-3xl text-sm text-muted">{footnote}</p>
      </div>
    </div>
  );
}
