"use client";

import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { useRouter } from "next/navigation";
import Image from "next/image";
import Button from "@/components/ui/Button";

import { Swiper, SwiperSlide } from "swiper/react";
import { Autoplay, Pagination } from "swiper/modules";
import "swiper/css";
import "swiper/css/pagination";

const FALLBACK_IMAGE = "/images/hero-fallback.jpg"; // ضعها داخل public/images/

const HERO_SLIDES = [
  {
    _key: "static-1",
    image:
      "https://images.unsplash.com/photo-1550547660-d9450f859349?auto=format&fit=crop&w=1600&q=80",
    text: null,
    type: "static",
    referenceid: null,
  },
  {
    _key: "static-2",
    image:
      "https://images.unsplash.com/photo-1550547660-d9450f859349?auto=format&fit=crop&w=1600&q=80",
    text: null,
    type: "static",
    referenceid: null,
  },
  {
    _key: "static-3",
    image:
      "https://images.unsplash.com/photo-1550547660-d9450f859349?auto=format&fit=crop&w=1600&q=80",
    text: null,
    type: "static",
    referenceid: null,
  },
];

function SlideImage({ src, alt }) {
  const [imgSrc, setImgSrc] = useState(src || FALLBACK_IMAGE);

  return (
    <Image
      src={imgSrc}
      alt={alt}
      fill
      priority
      unoptimized
      className="object-cover"
      onError={() => setImgSrc(FALLBACK_IMAGE)}
    />
  );
}

export default function HeroSlider({ ads = [] }) {
  const { t, i18n } = useTranslation();
  const router = useRouter();
  const isRTL = i18n.language === "ar";

  const slides = useMemo(() => {
    const safeAds = Array.isArray(ads)
      ? ads.filter(
          (ad) => typeof ad?.image === "string" && ad.image.startsWith("http")
        )
      : [];

    if (safeAds.length === 0) return HERO_SLIDES;

    return safeAds.map((ad, index) => {
      const type = (ad?.type || "").toLowerCase(); // API: restaurant | product
      const referenceid = ad?.referenceid ?? null;

      return {
        _key: `${type || "unknown"}-${referenceid ?? "noid"}-${index}`, // ✅ unique key
        image: ad.image,
        text: ad.text,
        type,
        referenceid,
      };
    });
  }, [ads]);

  const handlePrimaryAction = (slide) => {
    const type = (slide?.type || "").toLowerCase();
    const id = slide?.referenceid;

    if (type === "restaurant" && id) return router.push(`/restaurant/${id}`);
    if (type === "product" && id) return router.push(`/meal/${id}`);

    router.push("/restaurants");
  };

  return (
    <section className="relative">
      <div className="custom-container pt-5">
        <div
          className="relative overflow-hidden rounded-3xl bg-gray-300"
          dir="ltr"
        >
          <Swiper
            modules={[Autoplay, Pagination]}
            autoplay={{ delay: 4500, disableOnInteraction: false }}
            loop
            pagination={{ clickable: true }}
            className="h-[330px] sm:h-[380px] lg:h-[460px]"
          >
            {slides.map((slide) => (
              <SwiperSlide key={slide._key}>
                <div className="relative w-full h-full">
                  {/* Background Image (with fallback) */}
                  <SlideImage src={slide.image} alt={slide.text || "Hero"} />

                  {/* Dark overlay */}
                  <div className="absolute inset-0 bg-black/50 sm:bg-black/45" />

                  {/* Text + Buttons */}
                  <div
                    className={`absolute inset-0 flex items-center justify-center ${
                      isRTL ? "sm:justify-end" : "sm:justify-start"
                    }`}
                  >
                    <div
                      dir={isRTL ? "rtl" : "ltr"}
                      className={`w-full px-4 sm:px-10 lg:px-16 max-w-md sm:max-w-lg lg:max-w-xl space-y-3 sm:space-y-4 text-white text-center ${
                        isRTL ? "sm:text-right" : "sm:text-left"
                      }`}
                    >
                      <h1 className="text-lg sm:text-3xl lg:text-5xl font-bold leading-snug sm:leading-tight">
                        {slide.text || t("home.hero.title")}
                      </h1>

                      <p className="text-xs sm:text-base lg:text-lg text-gray-200 leading-relaxed">
                        {t("home.hero.subtitle")}
                      </p>

                      <div className="flex flex-col sm:flex-row sm:justify-start gap-2 pt-1 sm:pt-2">
                        <Button
                          onClick={() => handlePrimaryAction(slide)}
                          variant="outline"
                          size="md"
                          className="w-full sm:w-auto border-white text-white hover:bg-white/10 !rounded-full"
                        >
                          {t("home.order_now")}
                        </Button>

                        <Button
                          onClick={() => router.push("/restaurants")}
                          variant="primary"
                          size="md"
                          className="w-full sm:w-auto bg-brand hover:bg-brand/90 text-white !rounded-full"
                        >
                          {t("home.browse_restaurants")}
                        </Button>
                      </div>
                    </div>
                  </div>
                </div>
              </SwiperSlide>
            ))}
          </Swiper>
        </div>
      </div>
    </section>
  );
}
