"use client";

import React, { useEffect, useState } from "react";
import Image from "next/image";
import { getListArticle } from "@/service/article";
import Link from "next/link";

type Article = {
  id: number;
  title: string;
  description: string;
  categoryName: string;
  createdAt: string;
  slug: string;
  createdByName: string;
  customCreatorName: string;
  thumbnailUrl: string;
  categories: {
    title: string;
  }[];
  files: {
    file_url: string;
    file_alt: string;
  }[];
};

export default function HeaderLatest() {
  const [article, setArticle] = useState<Article | null>(null);

  useEffect(() => {
    initState();
  }, []);

  async function initState() {
    const req = {
      limit: "1",
      page: 1,
      search: "",
      categorySlug: "",
      sort: "desc",
      isPublish: true,
      sortBy: "created_at",
    };

    try {
      const res = await getListArticle(req);
      setArticle(res?.data?.data?.[0] || null);
    } catch (error) {
      console.error("Gagal memuat artikel:", error);
    }
  }

  return (
    <header className="w-full pt-3 flex justify-center">
      <div className="relative max-w-screen-xl w-full h-[320px] md:h-[480px] mx-3 md:mx-5 overflow-hidden group">
        <Link className="flex" href={`/details/${article?.slug}`}>
          {/* Gambar utama */}
          <Image
            src={article?.thumbnailUrl || "/dummy.jpg"}
            alt={article?.title || "No Title"}
            fill
            className="object-cover transition-transform duration-500 group-hover:scale-110"
          />

          {/* Overlay gradient */}
          <div className="absolute inset-0 bg-gradient-to-t from-black/70 via-black/20 to-transparent" />

          {/* Konten teks */}
          <div className="absolute bottom-5 left-5 text-white max-w-[80%]">
            <span className="bg-orange-600 text-white text-[10px] md:text-xs px-2 py-1 mb-3 inline-block font-semibold uppercase tracking-wide">
              {article?.categoryName || "Berita Terkini"}
            </span>
            <h1 className="text-lg md:text-2xl font-semibold leading-snug md:leading-tight">
              {article?.title || "Memuat..."}
            </h1>
          </div>
        </Link>
      </div>
    </header>
  );
}
