/**
 * World Impo Solution - Elite Logic Engine
 * High-performance UI logic for Logistics & Global Trade.
 */

document.addEventListener('DOMContentLoaded', () => {
    // 1. Initialize Lucide Icons
    if ((window as any).lucide) {
        (window as any).lucide.createIcons();
    }

    // 2. Mobile Navigation Toggle Logic
    const mobileToggle = document.getElementById('mobile-toggle');
    const mobileMenu = document.getElementById('mobile-menu');
    
    if (mobileToggle && mobileMenu) {
        mobileToggle.addEventListener('click', () => {
            const isHidden = mobileMenu.classList.contains('hidden');
            if (isHidden) {
                mobileMenu.classList.remove('hidden');
                mobileToggle.innerHTML = '<i data-lucide="x" class="w-7 h-7"></i>';
            } else {
                mobileMenu.classList.add('hidden');
                mobileToggle.innerHTML = '<i data-lucide="menu" class="w-7 h-7"></i>';
            }
            (window as any).lucide.createIcons();
        });
    }

    // 3. Mobile Dropdown Accordion
    const mobileDropdownToggles = document.querySelectorAll('.mobile-dropdown-toggle');
    mobileDropdownToggles.forEach(toggle => {
        toggle.addEventListener('click', () => {
            const content = toggle.nextElementSibling;
            if (content) {
                const isHidden = content.classList.contains('hidden');
                content.classList.toggle('hidden');
                const icon = (toggle as HTMLElement).querySelector('i');
                if (icon) {
                    icon.style.transform = isHidden ? 'rotate(180deg)' : 'rotate(0deg)';
                    icon.style.transition = 'transform 0.4s cubic-bezier(0.165, 0.84, 0.44, 1)';
                }
            }
        });
    });

    // 4. Hero Slider Engine (Auto-rotate with 6s cross-fade)
    const slides = document.querySelectorAll('.hero-slide');
    const nextBtn = document.getElementById('hero-next');
    const prevBtn = document.getElementById('hero-prev');
    let currentSlideIndex = 0;
    let autoSlideInterval: any;

    const updateSlider = (index: number) => {
        slides.forEach(s => s.classList.remove('active'));
        if (slides[index]) {
            slides[index].classList.add('active');
        }
    };

    const nextSlideAction = () => {
        currentSlideIndex = (currentSlideIndex + 1) % slides.length;
        updateSlider(currentSlideIndex);
    };

    const prevSlideAction = () => {
        currentSlideIndex = (currentSlideIndex - 1 + slides.length) % slides.length;
        updateSlider(currentSlideIndex);
    };

    if (nextBtn) nextBtn.addEventListener('click', () => {
        nextSlideAction();
        restartAutoTimer();
    });
    
    if (prevBtn) prevBtn.addEventListener('click', () => {
        prevSlideAction();
        restartAutoTimer();
    });

    const restartAutoTimer = () => {
        if (autoSlideInterval) clearInterval(autoSlideInterval);
        autoSlideInterval = setInterval(nextSlideAction, 6000); 
    };

    restartAutoTimer();

    // 5. Dynamic Grid Generation (EXACTLY 23 items for "Trending Trade Requests")
    const bestSellersGrid = document.getElementById('best-sellers-grid');

    const generateProductHTML = (id: number) => {
        const categories = [
            'Precision IC Hardware X-90', 'Automotive Alloy Wheels PRO', 'Sourcing: 24mm Mist Pump', 
            'Industrial CNC Carbide Drills', 'Lotion Dispenser LX-Gold', 'Sea Freight: Container LCL',
            'Solar Cell Inverters Gen-V', 'Luxury Glass Flask 500ml', 'Advanced Circuit Boards G4',
            'Heavy Duty Valve Systems', 'Metallic Closure Rings', 'Fragrance Atomizer Elite'
        ];
        
        const label = categories[id % categories.length];
        const sourcePort = ['Shanghai Hub', 'Rotterdam Port', 'Busan Terminal', 'Los Angeles Port', 'Hamburg Zone'][id % 5];
        const imageUrl = `https://picsum.photos/seed/impo-${id + 3000}/800/800`;
        
        return `
            <div class="flex-shrink-0 w-[300px] md:w-full bg-white border border-gray-100 rounded-[3rem] overflow-hidden product-card snap-start group shadow-xl shadow-gray-200/20">
                <div class="relative aspect-square bg-gray-50 overflow-hidden">
                    <img src="${imageUrl}" alt="${label}" loading="lazy" class="w-full h-full object-cover group-hover:scale-110 transition-transform duration-1000">
                    <div class="absolute inset-0 bg-black/0 group-hover:bg-amber-900/10 transition-colors"></div>
                    <div class="absolute top-6 left-6 flex flex-col gap-2">
                         <span class="bg-amber-600 text-white text-[9px] font-black px-4 py-2 rounded-full uppercase tracking-widest shadow-2xl">Verified Hub</span>
                         <span class="bg-black text-white text-[9px] font-black px-4 py-2 rounded-full uppercase tracking-widest opacity-80">${sourcePort}</span>
                    </div>
                    <button class="absolute bottom-6 right-6 bg-white p-5 rounded-[2rem] shadow-2xl transform translate-y-24 group-hover:translate-y-0 opacity-0 group-hover:opacity-100 transition-all duration-700 hover:bg-gold-gradient hover:text-white">
                        <i data-lucide="external-link" class="w-6 h-6"></i>
                    </button>
                </div>
                <div class="p-10">
                    <div class="flex items-center space-x-2 mb-3">
                         <div class="w-3 h-3 bg-gold rounded-full animate-pulse"></div>
                         <p class="text-[10px] font-black uppercase text-amber-600 tracking-[0.4em]">Ready To Export</p>
                    </div>
                    <h4 class="text-xl font-bold text-gray-900 line-clamp-2 min-h-[3.6rem] font-luxury leading-tight">${label}</h4>
                    <div class="mt-8 flex justify-between items-center border-t border-gray-50 pt-8">
                        <div class="flex flex-col">
                             <span class="text-[10px] text-gray-400 font-bold uppercase tracking-widest">Min Sourcing Vol.</span>
                             <span class="text-gray-900 font-black text-xl tracking-tighter">5,000 Units</span>
                        </div>
                        <button class="text-[10px] font-black uppercase tracking-[0.2em] text-amber-600 hover:text-black transition-colors">Audit File</button>
                    </div>
                </div>
            </div>
        `;
    };

    if (bestSellersGrid) {
        let gridContent = '';
        for (let i = 1; i <= 23; i++) {
            gridContent += generateProductHTML(i);
        }
        bestSellersGrid.innerHTML = gridContent;
    }

    // 6. Intersection Observer for Scroll Animations
    const observerOptions = { threshold: 0.1 };
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('opacity-100', 'translate-y-0');
                entry.target.classList.remove('opacity-0', 'translate-y-12');
            }
        });
    }, observerOptions);

    document.querySelectorAll('section').forEach(section => {
        section.classList.add('transition-all', 'duration-1000', 'opacity-0', 'translate-y-12');
        observer.observe(section);
    });

    // 7. Form Submission Simulation
    const contactForm = document.getElementById('quote-form') as HTMLFormElement | null;
    if (contactForm) {
        contactForm.addEventListener('submit', (e) => {
            e.preventDefault();
            const btn = contactForm.querySelector('button');
            if (btn) {
                const originalText = btn.innerHTML;
                btn.innerHTML = 'Analyzing Logistics...';
                btn.classList.add('opacity-70', 'pointer-events-none');
                setTimeout(() => {
                    btn.innerHTML = 'Global Inquiry Dispatched';
                    btn.classList.replace('bg-gold-gradient', 'bg-green-600');
                    contactForm.reset();
                    setTimeout(() => {
                        btn.innerHTML = originalText;
                        btn.classList.replace('bg-green-600', 'bg-gold-gradient');
                        btn.classList.remove('opacity-70', 'pointer-events-none');
                    }, 3000);
                }, 2000);
            }
        });
    }

    // Refresh Lucide Icons after dynamic generation
    if ((window as any).lucide) {
        (window as any).lucide.createIcons();
    }
});