"use client";

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

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

export function Projects({ projects }: { projects: DisplayProject[] }) {
  const trackRef = useRef<HTMLUListElement>(null);
  const [atStart, setAtStart] = useState(true);
  const [atEnd, setAtEnd] = useState(false);

  const syncEdges = useCallback(() => {
    const el = trackRef.current;
    if (!el) return;
    // The page is RTL, so scrollLeft runs from 0 down to -(scrollWidth - clientWidth).
    const travelled = Math.abs(el.scrollLeft);
    const max = el.scrollWidth - el.clientWidth;
    setAtStart(travelled < 8);
    setAtEnd(travelled >= max - 8);
  }, []);

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

  const scrollByCard = (direction: "next" | "prev") => {
    const el = trackRef.current;
    if (!el) return;
    const card = el.querySelector("li");
    const step = card ? card.getBoundingClientRect().width + 24 : el.clientWidth * 0.8;
    // In RTL, advancing means moving further into negative scrollLeft.
    el.scrollBy({ left: direction === "next" ? -step : step, behavior: "smooth" });
  };

  return (
    <section id="projects" className="bg-ink py-16 lg:py-24">
      <div className="mx-auto max-w-[1400px] px-5 lg:px-10">
        <div className="flex flex-wrap items-end justify-between gap-8">
          <div>
            <Reveal>
              <p className="kicker mb-6">
                <span className="latin">PORTFOLIO</span>
              </p>
            </Reveal>
            <Reveal delay={90}>
              <h2 className="text-[1.625rem] leading-[1.25] font-extrabold whitespace-nowrap text-white lg:text-[2.625rem]">
                آخرین <span className="text-gold">پروژه‌ها</span>
              </h2>
            </Reveal>
          </div>

          <div className="flex items-center gap-4">
            <Link
              href="/portfolios"
              className="hidden border-b border-white/25 pb-2 text-sm text-white/75 transition-colors hover:border-gold hover:text-white sm:block"
            >
              مشاهده همه پروژه‌ها
            </Link>

            <div className="flex gap-2">
              <button
                type="button"
                onClick={() => scrollByCard("prev")}
                disabled={atStart}
                aria-label="پروژه‌های قبلی"
                className="flex h-12 w-12 items-center justify-center rounded-full border border-white/25 text-white transition-colors duration-300 hover:border-gold hover:bg-gold disabled:pointer-events-none disabled:opacity-30"
              >
                <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.6" />
                </svg>
              </button>
              <button
                type="button"
                onClick={() => scrollByCard("next")}
                disabled={atEnd}
                aria-label="پروژه‌های بعدی"
                className="flex h-12 w-12 items-center justify-center rounded-full border border-white/25 text-white transition-colors duration-300 hover:border-gold hover:bg-gold disabled:pointer-events-none disabled:opacity-30"
              >
                <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.6" />
                </svg>
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* Track bleeds past the container so cards run off the viewport edge. */}
      <ul
        ref={trackRef}
        className="no-scrollbar mt-14 flex snap-x snap-mandatory gap-6 overflow-x-auto scroll-smooth px-5 pb-2 lg:mt-16 lg:px-10"
      >
        {projects.map((project, i) => (
          <li
            key={project.slug}
            className="w-[78vw] shrink-0 snap-start sm:w-[46vw] lg:w-[30vw] xl:w-[23rem]"
          >
            <Link href={`/portfolios/${project.slug}`} className="group block">
              <div className="relative aspect-[3/4] overflow-hidden bg-ink-3">
                <Image
                  src={project.image}
                  alt={`${project.type} ${project.name}`}
                  fill
                  quality={80}
                  sizes="(max-width: 640px) 78vw, (max-width: 1024px) 46vw, 23rem"
                  loading={i < 3 ? "eager" : "lazy"}
                  className="object-cover transition-transform duration-[1100ms] ease-out-soft group-hover:scale-[1.07]"
                />

                <div className="absolute inset-0 bg-gradient-to-t from-black/85 via-black/15 to-transparent" />

                {/* Gold inset border on hover. */}
                <div
                  aria-hidden="true"
                  className="pointer-events-none absolute inset-4 border border-gold opacity-0 transition-opacity duration-500 group-hover:opacity-100"
                />

                <div className="absolute inset-x-0 bottom-0 p-6">
                  <span className="latin block text-[0.68rem] tracking-[0.3em] text-gold-soft">
                    {project.nameLatin}
                  </span>
                  <h3 className="mt-2.5 text-2xl font-bold text-white">{project.name}</h3>
                  <span className="mt-1.5 block text-sm text-white/65">{project.type}</span>

                  <span className="mt-5 flex h-0 items-center gap-2 overflow-hidden text-sm text-white opacity-0 transition-all duration-500 ease-out-soft group-hover:h-6 group-hover:opacity-100">
                    مشاهده پروژه
                    <svg viewBox="0 0 24 24" fill="none" aria-hidden="true" className="h-3.5 w-3.5">
                      <path d="M19 12H5m0 0 6-6m-6 6 6 6" stroke="currentColor" strokeWidth="1.8" />
                    </svg>
                  </span>
                </div>
              </div>
            </Link>
          </li>
        ))}
      </ul>

      <div className="mx-auto mt-10 max-w-[1400px] px-5 sm:hidden lg:px-10">
        <Link
          href="/portfolios"
          className="block border border-white/25 py-3.5 text-center text-sm text-white transition-colors hover:border-gold hover:bg-gold"
        >
          مشاهده همه پروژه‌ها
        </Link>
      </div>
    </section>
  );
}
