'use client';

import { useEffect, useState, useRef } from 'react';
import { useSession } from 'next-auth/react';

import { usePathname } from 'next/navigation';

interface AdBannerProps {
    dataAdSlot: string;
    dataAdFormat?: string;
    fullWidthResponsive?: boolean;
    className?: string;
}

export default function AdBanner({
    dataAdSlot,
    dataAdFormat = 'auto',
    fullWidthResponsive = true,
    className = '',
}: AdBannerProps) {
    const { data: session, status } = useSession();
    const pathname = usePathname();
    const adRef = useRef<HTMLModElement>(null);
    const [adFilled, setAdFilled] = useState(false);

    // Paths where ads should NOT be shown
    const excludedPaths = [
        '/',                // English Home
        '/de',             // German Home
        '/qr-code-erstellen', // German Landing
        '/contact',        // Contact
        '/about',          // About
        '/legal',          // Legal pages
        '/privacy',
        '/terms',
        '/cookie-policy',
        '/impressum',
        '/press',
        '/testimonials',
        '/authors',
    ];

    // Check if current path matches strictly or starts with excluded path (for nested legal/blog pages if needed, though mostly exact matches here)
    const shouldExclude = excludedPaths.some(path => {
        if (path === '/') return pathname === '/';
        return pathname === path || pathname?.startsWith(`${path}/`);
    });

    // Check if user has a paid plan
    const isPaidUser = session?.user && (
        session.user.plan === 'PRO' ||
        session.user.plan === 'PREMIUM' ||
        session.user.plan === 'LIFETIME'
    );



    useEffect(() => {
        // Don't load if loading session or if user is paid
        if (status === 'loading' || isPaidUser) return;

        const loadAd = () => {
            try {
                // @ts-ignore
                (window.adsbygoogle = window.adsbygoogle || []).push({});

                // Check if ad was filled after a short delay
                setTimeout(() => {
                    if (adRef.current) {
                        const adElement = adRef.current;
                        // AdSense sets data-ad-status="filled" when an ad loads
                        const adStatus = adElement.getAttribute('data-ad-status');
                        if (adStatus === 'filled') {
                            setAdFilled(true);
                        }
                        // Also check if child iframe exists (another indicator)
                        if (adElement.querySelector('iframe')) {
                            setAdFilled(true);
                        }
                    }
                }, 1500);
            } catch (err) {
                console.error('AdSense error:', err);
            }
        };

        // Small delay to ensure DOM is ready
        const timer = setTimeout(loadAd, 100);
        return () => clearTimeout(timer);
    }, [isPaidUser, status]);

    // Don't render anything if paid user
    if (status === 'authenticated' && isPaidUser) return null;

    // Don't render anything while session is loading
    if (status === 'loading') return null;

    if (shouldExclude) return null;

    return (
        <div
            className={`ad-container flex justify-center items-center overflow-hidden transition-opacity duration-300 ${adFilled ? 'opacity-100' : 'opacity-0 h-0'} ${className}`}
            aria-hidden={true}
        >
            <ins
                ref={adRef}
                className="adsbygoogle"
                style={{ display: 'block', minWidth: '300px', width: '100%' }}
                data-ad-client="ca-pub-2782770414424875"
                data-ad-slot={dataAdSlot}
                data-ad-format={dataAdFormat}
                data-full-width-responsive={fullWidthResponsive}
            />
        </div>
    );
}
