// ==========================================
// 🎠 Home Banners
// ==========================================
async function loadHomeBanners() {
    try {
        const city = typeof CityService !== 'undefined' ? CityService.getCity() : 'all';
        const baseUrl = window.API_URL || '';
        const res = await fetch(`${baseUrl}/api/banners?city=${city}`);
        const data = await res.json();
        
        const bannersSection = document.getElementById('home-banners-section');
        const bannersInner = document.getElementById('homeBannersInner');
        
        if (!bannersSection || !bannersInner) return;
        
        if (!data || data.length === 0) {
            bannersSection.style.display = 'none';
            return;
        }
        
        bannersSection.style.display = 'block';
        
        let innerHtml = '';
        
        data.forEach((banner, idx) => {
            const active = idx === 0 ? 'active' : '';
            // ✅ الحقل الصحيح في النموذج هو image_url
            const imgUrl = banner.image_url || '';
            const isClickable = !!(banner.link && banner.link.trim());
            
            let bannerContent = `<img src="${imgUrl}" class="d-block w-100 home-banner-img" alt="${banner.title || 'Banner'}" onerror="this.parentElement.style.display='none'">`;
            
            if (isClickable) {
                bannerContent = `<a href="${banner.link}" target="_blank" onclick="trackHomeBannerClick('${banner._id}')" style="display:block;">${bannerContent}</a>`;
            }
            
            innerHtml += `
                <div class="carousel-item ${active}">
                    ${bannerContent}
                </div>
            `;
        });
        
        bannersInner.innerHTML = innerHtml;
    } catch (err) {
        console.error('Error loading home banners:', err);
    }
}

async function trackHomeBannerClick(id) {
    try {
        const baseUrl = window.API_URL || '';
        await fetch(`${baseUrl}/api/banners/${id}/click`, { method: 'POST' });
    } catch (e) {}
}

// Ensure it loads when DOM is ready or right now if it's already ready
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', loadHomeBanners);
} else {
    loadHomeBanners();
}
