import React, { useEffect, useRef } from 'react';

interface GoogleAdProps {
  slotId?: string;
  className?: string;
  format?: 'auto' | 'rectangle' | 'vertical' | 'horizontal';
}

const GoogleAd: React.FC<GoogleAdProps> = ({ 
  slotId, 
  className,
  format = 'auto' 
}) => {
  const adRef = useRef<HTMLModElement>(null);
  const hasRequestedAd = useRef(false);

  // Use the provided ID or the placeholder
  const effectiveSlotId = slotId || "1234567890";
  const isPlaceholder = effectiveSlotId === "1234567890";

  useEffect(() => {
    // If it's a placeholder, do not attempt to fetch an ad (prevents 400 errors)
    if (isPlaceholder) return;

    // Prevent double execution in React Strict Mode
    if (hasRequestedAd.current) return;

    try {
      // @ts-ignore
      const adsbygoogle = window.adsbygoogle || [];
      
      // Safety Check: Only push ad if the element is actually visible in the DOM
      if (adRef.current && adRef.current.offsetWidth > 0 && adRef.current.innerHTML === "") {
          adsbygoogle.push({});
          hasRequestedAd.current = true;
      }
    } catch (e) {
      console.error("AdSense error:", e);
    }
  }, [isPlaceholder]);

  // Render a placeholder box if no valid Slot ID is provided
  if (isPlaceholder) {
    return (
      <div className={`w-full flex flex-col items-center justify-center bg-slate-900/50 rounded border border-slate-800 border-dashed min-h-[100px] p-4 text-center ${className}`}>
        <span className="text-xs text-slate-500 font-medium">Ad Space</span>
        <span className="text-[10px] text-slate-600">Configure Slot ID in Code</span>
      </div>
    );
  }

  return (
    <div className={`w-full flex justify-center bg-slate-900/50 rounded overflow-hidden min-h-[100px] ${className}`}>
        <ins className="adsbygoogle"
             ref={adRef}
             style={{ display: 'block', width: '100%' }}
             data-ad-client="ca-pub-1194928369043500"
             data-ad-slot={effectiveSlotId} 
             data-ad-format={format}
             // CRITICAL: Set to false to prevent the ad from expanding beyond the sidebar/panel width 
             // and overlaying the entire application, which blocks clicks on desktop.
             data-full-width-responsive="false"></ins>
    </div>
  );
};

export default GoogleAd;