import React, { useEffect, useRef, useMemo } from 'react';
import { cn } from '@/lib/utils';
import { usePage } from '@inertiajs/react';

let adsenseScriptLoaded = false;
const isDevelopment = import.meta.env.VITE_APP_ENV === 'local';

export default function AdSlot({ ad, className }) {
    const adContainerRef = useRef(null);
    const { url } = usePage();

    const fixedStyles = useMemo(() => {
        if (!ad?.dimensions || ad.dimensions.toLowerCase() === 'responsive') {
            return {};
        }

        const match = ad.dimensions.match(/(\d+)\s*[xX*]\s*(\d+)/);
        if (match) {
            const width = match[1];
            const height = match[2];
            return {
                width: `${width}px`,
                height: `${height}px`,
                minWidth: `${width}px`,
                minHeight: `${height}px`,
                display: 'block'
            };
        }
        return {};
    }, [ad?.dimensions]);

    useEffect(() => {
        if (!ad || !ad.is_active || ad.type !== 'code' || !adContainerRef.current || !ad.content) {
            return;
        }

        const container = adContainerRef.current;
        container.innerHTML = '';
        delete container.dataset.adPushed;

        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = ad.content;
        
        const executeScripts = () => {
            const insEl = tempDiv.querySelector('ins.adsbygoogle');

            // --- Google AdSense Logic ---
            if (insEl) {
                insEl.removeAttribute('data-adsbygoogle-status');
                insEl.removeAttribute('data-ad-status');
                
                if (fixedStyles.width) {
                    insEl.style.display = 'inline-block';
                    insEl.style.width = fixedStyles.width;
                    insEl.style.height = fixedStyles.height;
                }

                container.innerHTML = ''; 
                container.appendChild(insEl.cloneNode(true));
                
                const adClient = insEl.getAttribute('data-ad-client');
                
                if (adClient && !adsenseScriptLoaded) {
                    const libScript = document.createElement('script');
                    libScript.src = `https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${adClient}`;
                    libScript.async = true;
                    libScript.crossOrigin = 'anonymous';
                    
                    if (isDevelopment) {
                        libScript.setAttribute('data-adbreak-test', 'on');
                    }
                    
                    document.head.appendChild(libScript);
                    adsenseScriptLoaded = true;
                }

                // Retry logic to prevent "availableWidth=0" error in SPA
                let attempts = 0;
                const pushWhenReady = () => {
                    if (container.offsetWidth > 0) {
                        try {
                            (window.adsbygoogle = window.adsbygoogle ||[]).push({});
                        } catch (e) {
                            console.warn('AdSense push error on SPA navigate:', e);
                        }
                    } else if (attempts < 20) { // Retry up to 2 seconds (20 * 100ms)
                        attempts++;
                        setTimeout(pushWhenReady, 100);
                    }
                };

                pushWhenReady();
                return;
            }

            // --- Generic Script / Other Ad Networks Logic ---
            Array.from(tempDiv.childNodes).forEach(node => {
                if (node.nodeType === Node.ELEMENT_NODE && node.tagName === 'SCRIPT') {
                    const newScript = document.createElement('script');
                    Array.from(node.attributes).forEach(attr => {
                        newScript.setAttribute(attr.name, attr.value);
                    });
                    newScript.textContent = node.textContent;
                    container.appendChild(newScript);
                } else {
                    container.appendChild(node.cloneNode(true));
                }
            });
        };

        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    executeScripts();
                    observer.disconnect();
                }
            });
        }, { threshold: 0.1, rootMargin: '150px' });

        observer.observe(container);

        return () => {
            observer.disconnect();
        };

    }, [ad, url, fixedStyles]);

    if (!ad || !ad.is_active) {
        return null;
    }

    if (ad.type === 'image') {
        return (
            <div 
                className={cn('overflow-hidden rounded-md flex justify-center w-full mx-auto', className)}
                style={fixedStyles}
            >
                <a
                    href={ad.target_url || '#'}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="block relative group w-full h-full"
                >
                    <img
                        src={ad.content}
                        alt={ad.name}
                        className="w-full h-full object-cover transition-opacity group-hover:opacity-90 mx-auto"
                    />
                    <span className="absolute top-0 right-0 bg-black/40 text-[9px] uppercase tracking-widest text-white px-1.5 py-0.5 rounded-bl-md backdrop-blur-sm">
                        Ad
                    </span>
                </a>
            </div>
        );
    }

    if (ad.type === 'code') {
        return (
            <div
                key={`${url}-${ad.id}`} 
                ref={adContainerRef}
                style={fixedStyles}
                className={cn('overflow-hidden flex justify-center items-center w-full min-h-[50px] bg-transparent mx-auto', className)}
            />
        );
    }

    return null;
}