"use client";

import { useEffect, useState } from "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 DestinationsIndex() {
  const [items, setItems] = useState<Destination[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    let active = true;
    (async () => {
      setLoading(true);
      setError("");
      try {
        const res = await fetchPublicDestinations();
        if (!active) return;
        setItems(res.data || []);
      } catch (err) {
        if (!active) return;
        setError(err instanceof Error ? err.message : "Failed to load destinations");
      } finally {
        if (active) setLoading(false);
      }
    })();
    return () => {
      active = false;
    };
  }, []);

  if (loading) {
    return <p className="py-10 text-center text-sm text-muted">Loading destinations…</p>;
  }

  if (error) {
    return (
      <p className="rounded-xl border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">
        {error}
      </p>
    );
  }

  if (!items.length) {
    return (
      <div className="rounded-2xl border border-dashed border-[var(--line)] px-6 py-16 text-center text-muted">
        No destinations published yet.
      </div>
    );
  }

  return (
    <div className="grid gap-5 sm:grid-cols-2 lg:grid-cols-3">
      {items.map((dest) => (
        <a
          key={dest.id}
          href={`/destinations/${dest.slug}`}
          className="group overflow-hidden rounded-2xl border border-[var(--line)] bg-white shadow-[0_8px_24px_rgba(13,58,77,0.04)] transition hover:-translate-y-0.5 hover:shadow-[0_14px_36px_rgba(13,58,77,0.1)]"
        >
          <div className="relative aspect-[16/11] overflow-hidden">
            <AiImage
              src={coverSrc(dest)}
              alt={dest.name}
              className="h-full w-full transition duration-700 group-hover:scale-105"
            />
            <div className="absolute inset-0 bg-gradient-to-t from-black/55 via-transparent to-transparent" />
            {dest.tagline ? (
              <span className="absolute top-3 left-3 rounded-full bg-white/95 px-3 py-1 text-[11px] font-bold text-brand-deep">
                {dest.tagline}
              </span>
            ) : null}
          </div>
          <div className="space-y-2 p-4 sm:p-5">
            <h2 className="text-lg font-bold text-brand-deep">{dest.name}</h2>
            {dest.description ? (
              <p className="line-clamp-2 text-sm text-muted">{dest.description}</p>
            ) : null}
            <p className="text-xs font-semibold text-accent">
              {dest.cruise_count > 0
                ? `${dest.cruise_count} cruise tours`
                : "Explore destination"}{" "}
              →
            </p>
          </div>
        </a>
      ))}
    </div>
  );
}
