"use client";

import { useEffect, useState } from "react";
import { AiImage } from "@/components/AiImage";
import { useHomeSettings } from "@/components/HomeProvider";
import {
  fetchPublicNews,
  newsImageUrl,
  type NewsItem,
} from "@/lib/news-api";

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

function coverSrc(item: NewsItem) {
  if (item.cover_image) return newsImageUrl(item.cover_image);
  return FALLBACK_COVERS[item.id % FALLBACK_COVERS.length];
}

export function BlogGallery() {
  const { home } = useHomeSettings();
  const section = home.sections.blog || {};
  const [posts, setPosts] = useState<NewsItem[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let active = true;
    (async () => {
      try {
        const res = await fetchPublicNews({ per_page: 4, page: 1 });
        if (!active) return;
        setPosts(res.data || []);
      } catch {
        if (!active) return;
        setPosts([]);
      } finally {
        if (active) setLoading(false);
      }
    })();
    return () => {
      active = false;
    };
  }, []);

  return (
    <section id="blog" className="pb-10 sm:pb-12">
      <div className="container-page">
        <div className="mb-5 flex flex-col gap-4 sm:mb-6 sm:flex-row sm:items-end sm:justify-between">
          <div className="max-w-2xl">
            <h2 className="font-[family-name:var(--font-display)] text-2xl font-semibold text-brand sm:text-3xl">
              {section.title || "News suggestions for your trip"}
            </h2>
            <p className="mt-2 text-sm text-muted sm:text-base">
              {section.description ||
                "Tips, itineraries and local insights to help you plan the perfect Ha Long Bay cruise."}
            </p>
          </div>
          <a
            href="/news"
            className="inline-flex items-center gap-2 rounded-full border border-[var(--line)] bg-white px-5 py-2.5 text-sm font-semibold text-brand transition hover:border-accent hover:text-accent"
          >
            See All
            <span aria-hidden>→</span>
          </a>
        </div>

        {loading && <p className="py-6 text-sm text-muted">Loading news…</p>}

        {!loading && posts.length === 0 && (
          <p className="rounded-xl border border-dashed border-[var(--line)] px-4 py-8 text-center text-sm text-muted">
            No published articles yet.
          </p>
        )}

        {!loading && posts.length > 0 && (
          <div className="flex gap-4 overflow-x-auto pb-1 [-ms-overflow-style:none] [scrollbar-width:none] md:grid md:grid-cols-4 md:overflow-visible [&::-webkit-scrollbar]:hidden">
            {posts.map((post) => (
              <a
                key={post.id}
                href={`/news/${post.slug}`}
                className="group w-[16rem] shrink-0 overflow-hidden rounded-xl border border-[var(--line)] bg-white md:w-auto"
              >
                <div className="relative aspect-[4/3] overflow-hidden">
                  <AiImage
                    src={coverSrc(post)}
                    alt={post.title}
                    className="h-full w-full transition duration-700 group-hover:scale-105"
                  />
                </div>
                <div className="space-y-2 p-4">
                  <p className="text-[11px] font-semibold tracking-wide text-accent uppercase">
                    {post.category}
                  </p>
                  <h3 className="line-clamp-3 text-sm leading-snug font-semibold text-brand sm:text-[15px]">
                    {post.title}
                  </h3>
                </div>
              </a>
            ))}
          </div>
        )}
      </div>
    </section>
  );
}
