"use client";

import Image from "next/image";
import Link from "next/link";
import { useCallback, useEffect, useRef, useState } from "react";

import type { DisplayProject } from "@/lib/api";

/**
 * Wide 5:4 plates on a snapping rail, echoing the reference page's portfolio
 * carousel. Dots below, arrows to the side — both RTL-aware.
 */
export function ProjectGallery({ projects }: { projects: DisplayProject[] }) {
  const trackRef = useRef<HTMLUListElement>(null);
  const [index, setIndex] = useState(0);

  const syncIndex = useCallback(() => {
    const el = trackRef.current;
    if (!el) return;
    const card = el.querySelector("li");
    if (!card) return;
    const step = card.getBoundingClientRect().width + 24;
    // RTL: scrollLeft runs negative as the rail advances.
    setIndex(Math.round(Math.abs(el.scrollLeft) / step));
  }, []);

  useEffect(() => {
    const el = trackRef.current;
    if (!el) return;
    el.addEventListener("scroll", syncIndex, { passive: true });
    return () => el.removeEventListener("scroll", syncIndex);
  }, [syncIndex]);

  const step = (direction: "next" | "prev") => {
    const el = trackRef.current;
    if (!el) return;
    const card = el.querySelector("li");
    const amount = card ? card.getBoundingClientRect().width + 24 : el.clientWidth * 0.8;
    el.scrollBy({ left: direction === "next" ? -amount : amount, behavior: "smooth" });
  };

  const goTo = (i: number) => {
    const el = trackRef.current;
    if (!el) return;
    const card = el.querySelector("li");
    if (!card) return;
    const amount = card.getBoundingClientRect().width + 24;
    el.scrollTo({ left: -amount * i, behavior: "smooth" });
  };

  if (projects.length === 0) return null;

  return (
    <div className="pb-24 lg:pb-32">
      <ul
        ref={trackRef}
        className="no-scrollbar flex snap-x snap-mandatory gap-6 overflow-x-auto scroll-smooth px-6 lg:px-12"
      >
        {projects.map((project, i) => (
          <li
            key={project.slug}
            className="w-[86vw] shrink-0 snap-center sm:w-[62vw] lg:w-[46vw] xl:w-[40rem]"
          >
            <Link href={`/portfolios/${project.slug}`} className="group block">
              <figure>
                <div className="relative aspect-[5/4] overflow-hidden bg-ink">
                  <Image
                    src={project.image}
                    alt={`${project.type} ${project.name}`}
                    fill
                    quality={80}
                    sizes="(max-width: 640px) 86vw, (max-width: 1024px) 62vw, 40rem"
                    loading={i < 2 ? "eager" : "lazy"}
                    className="object-cover transition-transform duration-[1100ms] ease-out-soft group-hover:scale-[1.04]"
                  />
                </div>

                <figcaption className="flex items-baseline justify-between gap-4 pt-5">
                  <h3 className="text-lg font-light text-ink">{project.name}</h3>
                  <span className="latin text-[0.66rem] tracking-[0.26em] text-gold">
                    {project.nameLatin}
                  </span>
                </figcaption>
              </figure>
            </Link>
          </li>
        ))}
      </ul>

      <div className="mx-auto mt-12 flex max-w-[1400px] items-center justify-center gap-8 px-6 lg:px-12">
        <button
          type="button"
          onClick={() => step("prev")}
          aria-label="قبلی"
          className="flex h-12 w-12 items-center justify-center rounded-full border border-ink/15 text-ink transition-colors duration-300 hover:border-gold hover:bg-gold hover:text-white"
        >
          <svg viewBox="0 0 24 24" fill="none" aria-hidden="true" className="h-4 w-4">
            <path d="M5 12h14m0 0-6-6m6 6-6 6" stroke="currentColor" strokeWidth="1.4" />
          </svg>
        </button>

        <div className="flex items-center gap-2.5">
          {projects.map((project, i) => (
            <button
              key={project.slug}
              type="button"
              onClick={() => goTo(i)}
              aria-label={`پروژه ${project.name}`}
              aria-current={i === index}
              className={`h-1.5 rounded-full transition-all duration-500 ease-out-soft ${
                i === index ? "w-7 bg-gold" : "w-1.5 bg-ink/20 hover:bg-ink/40"
              }`}
            />
          ))}
        </div>

        <button
          type="button"
          onClick={() => step("next")}
          aria-label="بعدی"
          className="flex h-12 w-12 items-center justify-center rounded-full border border-ink/15 text-ink transition-colors duration-300 hover:border-gold hover:bg-gold hover:text-white"
        >
          <svg viewBox="0 0 24 24" fill="none" aria-hidden="true" className="h-4 w-4">
            <path d="M19 12H5m0 0 6-6m-6 6 6 6" stroke="currentColor" strokeWidth="1.4" />
          </svg>
        </button>
      </div>
    </div>
  );
}
