import { useEffect, useRef } from 'react';

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

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

  useEffect(() => {
    try {
      // Ensure adsbygoogle is loaded
      if (typeof window !== 'undefined') {
        // @ts-ignore
        (window.adsbygoogle = window.adsbygoogle || []).push({});
      }
    } catch (error) {
      console.error('AdSense initialization error:', error);
    }
  }, [adSlot]);

  const adStyle: React.CSSProperties = {
    display: 'block',
    minWidth: '300px',
    minHeight: '250px'
  };

  if (adFormat !== 'auto' && width && height) {
    adStyle.width = `${width}px`;
    adStyle.height = `${height}px`;
  } else {
    adStyle.width = '100%';
    adStyle.height = 'auto';
  }

  return (
    <div className={`adsense-wrapper ${className}`} ref={adRef}>
      <ins
        className="adsbygoogle"
        style={adStyle}
        data-ad-client="ca-pub-4465464714854276"
        data-ad-slot={adSlot}
        data-ad-format={adFormat}
        data-full-width-responsive="true"
      />
    </div>
  );
}