import { useEffect, useRef, useState, useContext } from "react";

import { Swiper, SwiperSlide } from "swiper/react";
import { Navigation, Pagination, Autoplay, EffectFade, EffectCards } from "swiper/modules";
// Import Swiper styles
import "swiper/css";
import "swiper/css/navigation";
import "swiper/css/pagination";
import "swiper/css/autoplay";
import "swiper/css/effect-fade";
import { Context } from "../context/contex";

const Ads: React.FC = () => {
 const context = useContext(Context);
 const [ads, setAds] = useState<any[]>([]);
 if (!context) {
  return <div>Loading...</div>;
 }

 const { apiURL, settings } = context;

 const getAds = async () => {
  try {
   const response = await fetch(apiURL, {
    method: "POST",
    headers: {
     "Content-Type": "application/x-www-form-urlencoded",
    },
    body: new URLSearchParams({ action: "get_ads" }),
   });

   if (!response.ok) {
    throw new Error(`HTTP error! Status: ${response.status}`);
   }

   const data = await response.json();
   if (data.error) {
    console.error("Error:", data.error);
   } else {
    setAds(data);

    //   console.log("Fetched settings:", data);
   }
  } catch (error: any) {
   console.error("Error:", error?.message);
  }
 };

 useEffect(() => {
  getAds();
  // console.log("LS", lastSlide);
 }, []);

 const isValidLink = (link?: string) =>
  !!link && /^(https?:\/\/)/i.test(link);


 return (
  <div>
   {ads && ads.length > 0 && (
    <Swiper
     modules={[Pagination, EffectFade, Autoplay]}
     autoplay
     effect="slide"
     //   pagination={{ clickable: true }}
     slidesPerView={1}
     centeredSlides={true}
    >
     {ads.map((card, index) => (
      <SwiperSlide key={`slide_${index}`}>
      <div className="slide-content">
  {isValidLink(card.link) ? (
    <a
      href={card.link}
      target="_blank"
      rel="noopener noreferrer"
    >
      <img
        src={settings?.domain + card.image}
        className="image1"
      />
    </a>
  ) : (
    <img
      src={settings?.domain + card.image}
      className="image1"
    />
  )}
</div>

      </SwiperSlide>
     ))}
    </Swiper>
   )}
  </div>
 );
};

export default Ads;
