import { useEffect, useRef, useState } from 'react';
import './GoogleAd.css';

interface GoogleAdProps {
    isPaidUser?: boolean;
}

declare global {
    interface Window {
        adsbygoogle: any[];
    }
}

const GoogleAd: React.FC<GoogleAdProps> = ({ isPaidUser = false }) => {
    const adRef = useRef<HTMLModElement>(null);
    const [scriptLoaded, setScriptLoaded] = useState(false);

    useEffect(() => {
        // 如果是付费用户，不加载广告
        if (isPaidUser) return;

        // 加载 Google Ads 脚本
        const loadAdScript = () => {
            if (!document.querySelector('script[src*="adsbygoogle.js"]')) {
                const script = document.createElement('script');
                script.src = 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-9165036986914822';
                script.async = true;
                script.crossOrigin = 'anonymous';
                script.onload = () => setScriptLoaded(true);
                document.head.appendChild(script);
            } else {
                setScriptLoaded(true);
            }
        };

        loadAdScript();
    }, [isPaidUser]);

    useEffect(() => {
        // 初始化广告
        if (scriptLoaded && !isPaidUser && adRef.current) {
            try {
                (window.adsbygoogle = window.adsbygoogle || []).push({});
            } catch (e) {
                console.error('AdSense error:', e);
            }
        }
    }, [scriptLoaded, isPaidUser]);

    if (isPaidUser) return null;

    return (
        <div className="ad-container">
            <ins
                ref={adRef}
                className="adsbygoogle"
                style={{ display: 'block' }}
                data-ad-client="ca-pub-9165036986914822"
                data-ad-slot="YOUR_AD_SLOT_ID"
                data-ad-format="auto"
                data-full-width-responsive="true"
            ></ins>
        </div>
    );
};

export default GoogleAd;
