document.addEventListener('DOMContentLoaded', () => {
    // Basic setup
    try {
        const params = new URLSearchParams(window.location.search);
        const ref = params.get('ref');
        if (ref) localStorage.setItem('anj_referrer', ref);
    } catch { }

    highlightActiveNav();
    ensureMobileMenuHTML();
    initMobileMenu();
    setupAccountIconLink();
    initScrollAnimations();
    initStickyHeader();
    initBackToTop();

    // Home Page Specific Features (Check if on index.html)
    const isHomePage = window.location.pathname.endsWith('index.html') || window.location.pathname === '/';
    if (isHomePage) {
        renderServiceDiscovery();
        initSearchFilter();
        initLanguageSwitcher();
        initStatCounters();
    }
});

/**
 * 1. STICKY HEADER & SCROLL SHADOW
 */
function initStickyHeader() {
    const header = document.querySelector('.main-header');
    if (!header) return;

    window.addEventListener('scroll', () => {
        if (window.scrollY > 10) {
            header.classList.add('scrolled');
        } else {
            header.classList.remove('scrolled');
        }
    });

    // Handle smooth scrolls for hash links
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function (e) {
            const href = this.getAttribute('href');
            if (href === '#') return;
            e.preventDefault();
            const target = document.querySelector(href);
            if (target) {
                const headerOffset = 80;
                const elementPosition = target.getBoundingClientRect().top;
                const offsetPosition = elementPosition + window.pageYOffset - headerOffset;

                window.scrollTo({
                    top: offsetPosition,
                    behavior: "smooth"
                });
            }
        });
    });
}

/**
 * 2. SERVICE DISCOVERY (Dynamic Rendering)
 */
function renderServiceDiscovery() {
    const container = document.getElementById('service-discovery-container');
    if (!container || !window.CATEGORIES) return;

    container.innerHTML = window.CATEGORIES.map(cat => `
        <div class="service-category mb-20 animate-up" id="cat-${cat.id}">
            <div class="service-category-title mb-10 flex items-center gap-4">
                <div class="w-12 h-12 bg-slate-900 text-white rounded-2xl flex items-center justify-center text-xl shadow-lg">
                    <i class="${cat.icon}"></i>
                </div>
                <h3 class="text-3xl font-black text-slate-900">${cat.title}</h3>
            </div>
            <div class="service-grid grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
                ${cat.services.map(ser => `
                    <a href="javascript:void(0)" class="service-card-lux" 
                         onclick="openServiceWhatsApp('${ser.name}', '${ser.url || ''}', '${ser.type || ''}')">
                        <div class="icon-wrapper">
                            <i class="${ser.icon}"></i>
                        </div>
                        <h4 class="card-title">${ser.name}</h4>
                        <p class="card-desc">Professional consultancy for ${ser.name.toLowerCase()} with fast processing.</p>
                    </a>
                `).join('')}
            </div>
        </div>
    `).join('');
}

function openServiceWhatsApp(serviceName, customUrl, type) {
    if (type === 'form-trigger') {
        openPropertyRequestForm();
        return;
    }
    if (customUrl) {
        window.location.href = customUrl;
        return;
    }
    const text = encodeURIComponent(`I'm interested in ${serviceName}`);
    window.open(`https://wa.me/918686095951?text=${text}`, '_blank');
}

function openPropertyRequestForm() {
    const modal = document.getElementById('property-request-modal');
    if (modal) {
        modal.classList.remove('hidden');
        document.body.style.overflow = 'hidden';
    }
}

function closePropertyRequestForm() {
    const modal = document.getElementById('property-request-modal');
    if (modal) {
        modal.classList.add('hidden');
        document.body.style.overflow = '';
    }
}

function toggleSearch() {
    const isHomePage = window.location.pathname.endsWith('index.html') || window.location.pathname === '/' || window.location.pathname.endsWith('.in/');
    if (isHomePage) {
        const searchContainer = document.querySelector('.search-container');
        if (searchContainer) {
            searchContainer.scrollIntoView({ behavior: 'smooth', block: 'center' });
            document.getElementById('service-search').focus();
        }
    } else {
        window.location.href = 'index.html#services';
    }
}



/**
 * 4. SEARCH FILTERING (Home Page Specific)
 */
function initSearchFilter() {
    const searchInput = document.getElementById('service-search');
    const filterPills = document.querySelectorAll('#service-filters .category-chip');
    
    if (!searchInput) return;

    // Search Logic
    searchInput.addEventListener('input', (e) => {
        const query = e.target.value.toLowerCase();
        const cards = document.querySelectorAll('.service-card-lux');
        const categories = document.querySelectorAll('.service-category');

        cards.forEach(card => {
            const name = card.querySelector('.card-title').innerText.toLowerCase();
            if (name.includes(query)) {
                card.style.display = 'block';
                card.classList.add('animate-up');
            } else {
                card.style.display = 'none';
            }
        });

        categories.forEach(cat => {
            const visibleCards = cat.querySelectorAll('.service-card-lux[style="display: block;"]');
            cat.style.display = visibleCards.length > 0 || query === '' ? 'block' : 'none';
        });
    });

    // Category Filter Logic
    filterPills.forEach(pill => {
        pill.addEventListener('click', () => {
            filterPills.forEach(p => p.classList.remove('active'));
            pill.classList.add('active');
            
            const filter = pill.dataset.filter;
            const categories = document.querySelectorAll('.service-category');
            
            categories.forEach(cat => {
                if (filter === 'all') {
                    cat.style.display = 'block';
                } else {
                    const matches = cat.id.toLowerCase().includes(filter);
                    cat.style.display = matches ? 'block' : 'none';
                }
            });
        });
    });
}

/**
 * 5. BACK TO TOP (Global)
 */
function initBackToTop() {
    const bttBtn = document.getElementById('backToTop');
    if (!bttBtn) return;

    window.addEventListener('scroll', () => {
        if (window.scrollY > 500) {
            bttBtn.classList.remove('translate-y-20', 'opacity-0');
        } else {
            bttBtn.classList.add('translate-y-20', 'opacity-0');
        }
    });

    bttBtn.addEventListener('click', () => {
        window.scrollTo({ top: 0, behavior: 'smooth' });
    });
}

/**
 * 5. LANGUAGE SWITCHER
 */
function initLanguageSwitcher() {
    const switcher = document.querySelector('.lang-switcher');
    if (!switcher) return;

    switcher.addEventListener('click', (e) => {
        if (e.target.classList.contains('lang-option')) {
            document.querySelectorAll('.lang-option').forEach(opt => opt.classList.remove('active'));
            e.target.classList.add('active');
            // Logic for state update would go here
            console.log("Language switched to:", e.target.dataset.lang);
        }
    });
}

/**
 * 6. STAT COUNTERS
 */
function initStatCounters() {
    const stats = document.querySelectorAll('.stat-number');
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const target = parseInt(entry.target.dataset.target);
                let count = 0;
                const increment = target / 50;
                const timer = setInterval(() => {
                    count += increment;
                    if (count >= target) {
                        entry.target.innerText = target + (entry.target.dataset.suffix || '');
                        clearInterval(timer);
                    } else {
                        entry.target.innerText = Math.floor(count) + (entry.target.dataset.suffix || '');
                    }
                }, 30);
                observer.unobserve(entry.target);
            }
        });
    }, { threshold: 0.5 });

    stats.forEach(s => observer.observe(s));
}

function ensureMobileMenuHTML() {
    // Drawer is now injected by header.js — skip if already present
    return;
}

function initMobileMenu() {
    // Mobile menu is now handled by toggleMobileMenu() in header.js
    // Just wire up any legacy .drawer-link close behaviour
    document.addEventListener('click', (e) => {
        const link = e.target.closest('.mob-grid-item, .drawer-link');
        if (link) {
            const href = link.getAttribute('href') || '';
            if (!href.startsWith('#')) {
                const drawer = document.getElementById('mobDrawer');
                const overlay = document.getElementById('mobOverlay');
                if (drawer && drawer.classList.contains('open')) {
                    drawer.classList.remove('open');
                    if (overlay) overlay.classList.remove('open');
                    document.body.style.overflow = '';
                }
            }
        }
    });
}

function highlightActiveNav() {
    const filename = window.location.pathname.split('/').pop() || 'index.html';
    document.querySelectorAll('.desktop-nav a').forEach(link => {
        if (link.getAttribute('href') === filename) link.classList.add('active');
    });
}

function isLoggedIn() {
    try { return !!localStorage.getItem('anj_current_user'); } catch { return false; }
}

function setupAccountIconLink() {
    const accountLink = document.querySelector('.mobile-account');
    if (accountLink) accountLink.setAttribute('href', isLoggedIn() ? 'dashboard.html' : 'login.html');
}


function initScrollAnimations() {
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('animate-fade-in');
                observer.unobserve(entry.target);
            }
        });
    }, { threshold: 0.1, rootMargin: '0px 0px -50px 0px' });

    document.querySelectorAll('.card, .hero-title, .hero-subtitle, .btn').forEach((el, i) => {
        el.style.animationDelay = `${i * 0.1}s`;
        observer.observe(el);
    });
}
