"use client";

import { useCallback, useState } from "react";

const STORAGE_KEY = "ad_interstitial_click_count";

export function useAdInterstitial(triggerAfter: number, enabled: boolean) {
  const [showAd, setShowAd] = useState(false);

  const recordClick = useCallback(() => {
    if (!enabled || triggerAfter <= 0) return;

    const current = parseInt(sessionStorage.getItem(STORAGE_KEY) ?? "0", 10);
    const next = current + 1;

    if (next >= triggerAfter) {
      sessionStorage.setItem(STORAGE_KEY, "0");
      setShowAd(true);
    } else {
      sessionStorage.setItem(STORAGE_KEY, String(next));
    }
  }, [enabled, triggerAfter]);

  const dismissAd = useCallback(() => {
    setShowAd(false);
  }, []);

  return { showAd, recordClick, dismissAd };
}
