import { useEffect, useRef } from 'react';

interface AdSenseAdProps {
  adSlot: string;
  adFormat?: 'auto' | 'rectangle' | 'vertical' | 'horizontal';
  width?: number;
  height?: number;
  className?: string;
  lazy?: boolean;
}

export default function AdSenseAd({ 
  adSlot, 
  adFormat = 'auto',
  width,
  height,
  className = '',
  lazy = false
}: AdSenseAdProps) {
  const adRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const initializeAd = () => {
      const insElement = adRef.current?.querySelector('ins');
      if (!insElement || insElement.dataset.adsbygoogleStatus === 'done') return;

      try {
        // @ts-ignore
        (window.adsbygoogle = window.adsbygoogle || []).push({});
      } catch (error) {
        console.error('AdSense initialization error:', error);
      }
    };

    if (lazy) {
      // Lazy load with IntersectionObserver
      const observer = new IntersectionObserver(
        (entries) => {
          entries.forEach((entry) => {
            if (entry.isIntersecting) {
              initializeAd();
              observer.disconnect();
            }
          });
        },
        { threshold: 0.1 }
      );

      if (adRef.current) {
        observer.observe(adRef.current);
      }

      return () => observer.disconnect();
    } else {
      // Immediate initialization
      initializeAd();
    }
  }, [adSlot, lazy]);

  // Simple non-responsive ad configuration
  const isFixedSize = width && height;
  const adStyle: React.CSSProperties = {
    display: 'inline-block'
  };

  if (isFixedSize) {
    adStyle.width = `${width}px`;
    adStyle.height = `${height}px`;
  } else {
    // Default banner size
    adStyle.width = '728px';
    adStyle.height = '90px';
  }

  return (
    <div 
      className={`adsense-wrapper w-full flex justify-center ${className}`} 
      ref={adRef}
      style={{ width: '100%', minWidth: '320px', position: 'relative', zIndex: 1 }}
    >
      <ins
        className="adsbygoogle"
        style={adStyle}
        data-ad-client="ca-pub-4465464714854276"
        data-ad-slot={adSlot}
        data-ad-format="auto"
      />
    </div>
  );
}