"use client";

import {
  createContext,
  useContext,
  useEffect,
  useMemo,
  useState,
} from "react";
import { fetchAdPlacements } from "@/services/adsService";
import type { AdPlacement } from "@/types/ads.types";

interface GoogleAdsContextValue {
  placements: AdPlacement[];
  isLoading: boolean;
  getPlacement: (type: string) => AdPlacement | null;
}

const GoogleAdsContext = createContext<GoogleAdsContextValue>({
  placements: [],
  isLoading: true,
  getPlacement: () => null,
});

export function GoogleAdsProvider({ children }: { children: React.ReactNode }) {
  const [placements, setPlacements] = useState<AdPlacement[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    fetchAdPlacements()
      .then(setPlacements)
      .catch(() => {})
      .finally(() => setIsLoading(false));
  }, []);

  const value = useMemo<GoogleAdsContextValue>(
    () => ({
      placements,
      isLoading,
      getPlacement: (type) =>
        placements.find((p) => p.placement_type === type && p.status === 1) ??
        null,
    }),
    [placements, isLoading],
  );

  return (
    <GoogleAdsContext.Provider value={value}>
      {children}
    </GoogleAdsContext.Provider>
  );
}

export const useGoogleAds = () => useContext(GoogleAdsContext);
