File size: 2,323 Bytes
d359dfb
518de38
 
 
 
d359dfb
518de38
 
d359dfb
 
 
 
 
 
 
 
49240aa
 
 
 
518de38
49240aa
 
 
d359dfb
 
 
518de38
 
 
d359dfb
 
 
 
 
 
518de38
 
 
49240aa
 
 
 
 
 
 
 
 
 
 
518de38
 
 
 
d359dfb
518de38
336e2f0
49240aa
d359dfb
 
 
 
518de38
 
 
 
49240aa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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;