"use client";
import { useGetQuery } from "@/hooks/mutate/useGetQuery";
import { stringToJson } from "@/utils/helper";
import Link from "next/link";
import ImageLoader from "../ui/ImageLoader";
import Loader from "../ui/Loader";
import GoogleAds from "./GoogleAds";
const AdSense = ({
  position,
  className,
}: {
  position: string;
  className?: string;
}) => {
  const { data: ADDS, isLoading } = useGetQuery({
    isPublic: true,
    url: `get-ads`,
  });

  if (isLoading) return <Loader />;

  const data = ADDS.find((ad: any) => ad.position === position);

  if (!data?.type) return null;

  switch (data.type) {
    case "custom":
      return (
        <div
          dangerouslySetInnerHTML={{ __html: data.code }}
          className={`h-${data?.height || 40} w-${data?.width || 300} ${className ?? ""}`}
        />
      );
    case "adsense":
      let googleAds: any = stringToJson(data?.code || "{}");

      if (!googleAds?.client || !googleAds?.slot) {
        googleAds = googleAds[0] || {};
        if (!googleAds?.client || !googleAds?.slot) {
          return null;
        }
      }
      return (
        <GoogleAds
          client={googleAds?.client}
          slot={googleAds?.slot}
          style={
            data?.height && data?.width
              ? { height: data?.height, width: data?.width }
              : {}
          }
        />
      );
    case "image":
      return (
        <Link
          href={data?.link || "#"}
          target="_blank"
          className={className}
          style={{
            height: data?.height || 40,
            width: data?.width || 300,
          }}
        >
          <ImageLoader
            src={data?.image}
            alt={data?.title}
            className={`h-full w-full object-cover`}
            height={data?.height || 40}
            width={data?.width || 300}
          />
        </Link>
      );

    default:
      return null;
  }
};

export default AdSense;
