"use client";

import { useEffect, useRef, useState } from "react";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { AiImage } from "@/components/AiImage";
import {
  destinationImageUrl,
  fetchPublicDestinations,
  type Destination,
} from "@/lib/destinations-api";

const FALLBACKS = [
  "/img/destinationBg32.webp",
  "/img/image_1863.webp",
  "/img/image_1864.webp",
  "/img/destinationBg.webp",
];

function coverSrc(item: Destination) {
  if (item.image) return destinationImageUrl(item.image);
  return FALLBACKS[item.id % FALLBACKS.length];
}

export function Destinations() {
  const scrollerRef = useRef<HTMLDivElement>(null);
  const dragRef = useRef({
    active: false,
    startX: 0,
    startScroll: 0,
    moved: false,
  });
  const [items, setItems] = useState<Destination[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let active = true;
    (async () => {
      try {
        const res = await fetchPublicDestinations();
        if (!active) return;
        setItems(res.data || []);
      } catch {
        if (!active) return;
        setItems([]);
      } finally {
        if (active) setLoading(false);
      }
    })();
    return () => {
      active = false;
    };
  }, []);

  useEffect(() => {
    const el = scrollerRef.current;
    if (!el) return;

    const onPointerDown = (e: PointerEvent) => {
      if (e.pointerType === "touch") return;
      dragRef.current = {
        active: true,
        startX: e.clientX,
        startScroll: el.scrollLeft,
        moved: false,
      };
      el.setPointerCapture(e.pointerId);
      el.classList.add("cursor-grabbing");
      el.classList.remove("cursor-grab");
    };

    const onPointerMove = (e: PointerEvent) => {
      const d = dragRef.current;
      if (!d.active) return;
      const dx = e.clientX - d.startX;
      if (Math.abs(dx) > 4) d.moved = true;
      el.scrollLeft = d.startScroll - dx;
    };

    const endDrag = (e: PointerEvent) => {
      const d = dragRef.current;
      if (!d.active) return;
      d.active = false;
      el.releasePointerCapture(e.pointerId);
      el.classList.remove("cursor-grabbing");
      el.classList.add("cursor-grab");
    };

    const onClickCapture = (e: MouseEvent) => {
      if (dragRef.current.moved) {
        e.preventDefault();
        e.stopPropagation();
        dragRef.current.moved = false;
      }
    };

    el.addEventListener("pointerdown", onPointerDown);
    el.addEventListener("pointermove", onPointerMove);
    el.addEventListener("pointerup", endDrag);
    el.addEventListener("pointercancel", endDrag);
    el.addEventListener("click", onClickCapture, true);

    return () => {
      el.removeEventListener("pointerdown", onPointerDown);
      el.removeEventListener("pointermove", onPointerMove);
      el.removeEventListener("pointerup", endDrag);
      el.removeEventListener("pointercancel", endDrag);
      el.removeEventListener("click", onClickCapture, true);
    };
  }, [items.length]);

  const scrollBy = (dir: 1 | -1) => {
    const el = scrollerRef.current;
    if (!el) return;
    const card = el.querySelector<HTMLElement>("[data-dest-card]");
    const step = card ? card.offsetWidth + 16 : Math.min(360, el.clientWidth * 0.85);
    el.scrollBy({ left: dir * step, behavior: "smooth" });
  };

  return (
    <section id="destinations" className="bg-white pt-8 pb-6 sm:pt-10 sm:pb-8">
      <div className="container-page">
        {loading && <p className="py-4 text-sm text-muted">Loading destinations…</p>}
        {!loading && items.length === 0 && (
          <p className="py-4 text-sm text-muted">No destinations yet.</p>
        )}
        {!loading && items.length > 0 && (
          <div className="relative">
            {items.length > 1 && (
              <>
                <button
                  type="button"
                  onClick={() => scrollBy(-1)}
                  className="absolute top-1/2 -left-1 z-10 hidden h-10 w-10 -translate-y-1/2 place-items-center rounded-full border border-[var(--line)] bg-white/95 text-brand shadow-sm transition hover:border-accent hover:text-accent sm:-left-2 md:grid"
                  aria-label="Previous destinations"
                >
                  <ChevronLeft className="h-4 w-4" strokeWidth={2.4} />
                </button>
                <button
                  type="button"
                  onClick={() => scrollBy(1)}
                  className="absolute top-1/2 -right-1 z-10 hidden h-10 w-10 -translate-y-1/2 place-items-center rounded-full border border-[var(--line)] bg-white/95 text-brand shadow-sm transition hover:border-accent hover:text-accent sm:-right-2 md:grid"
                  aria-label="Next destinations"
                >
                  <ChevronRight className="h-4 w-4" strokeWidth={2.4} />
                </button>
              </>
            )}

            <div
              ref={scrollerRef}
              className="flex cursor-grab gap-3 overflow-x-auto overscroll-x-contain scroll-smooth pb-1 [-ms-overflow-style:none] [scrollbar-width:none] [scroll-snap-type:x_mandatory] [-webkit-overflow-scrolling:touch] sm:gap-4 [&::-webkit-scrollbar]:hidden"
            >
              {items.map((item) => (
                <a
                  key={item.id}
                  data-dest-card
                  href={`/destinations/${item.slug}`}
                  className="group relative h-[8.125rem] w-[min(16.125rem,78vw)] shrink-0 overflow-hidden rounded-xl [scroll-snap-align:start] sm:h-[10rem] sm:w-[20rem] md:h-[12.5rem] md:w-[min(22rem,32%)]"
                >
                  <AiImage
                    src={coverSrc(item)}
                    alt={item.name}
                    className="h-full w-full transition duration-700 group-hover:scale-105"
                  />
                  <div className="absolute inset-0 bg-gradient-to-t from-black/50 via-transparent to-transparent" />
                  <div className="absolute top-3 left-3">
                    <span className="rounded-md bg-black/55 px-2.5 py-1 text-xs font-semibold text-white backdrop-blur">
                      {item.name}
                    </span>
                    <span className="mt-1.5 block w-fit rounded-md bg-white px-2.5 py-1 text-xs font-bold text-brand">
                      {item.cruise_count} Cruise tour
                    </span>
                  </div>
                </a>
              ))}
            </div>
          </div>
        )}
      </div>
    </section>
  );
}
