/**
 * CMS Content Loader
 * Dynamically loads content from the CMS API
 */

class CMSLoader {
    constructor() {
        this.apiBase = 'cms/api/content.php';
        this.cache = new Map();
        this.cacheTimeout = 5 * 60 * 1000; // 5 minutes
    }

    async fetchContent(action, params = {}) {
        const cacheKey = `${action}_${JSON.stringify(params)}`;
        const cached = this.cache.get(cacheKey);
        
        if (cached && Date.now() - cached.timestamp < this.cacheTimeout) {
            return cached.data;
        }

        try {
            const url = new URL(this.apiBase, window.location.origin);
            url.searchParams.set('action', action);
            
            Object.keys(params).forEach(key => {
                url.searchParams.set(key, params[key]);
            });

            const response = await fetch(url);
            const result = await response.json();

            if (result.success) {
                this.cache.set(cacheKey, {
                    data: result.data,
                    timestamp: Date.now()
                });
                return result.data;
            } else {
                console.error('API Error:', result.message);
                return null;
            }
        } catch (error) {
            console.error('Fetch Error:', error);
            return null;
        }
    }

    async loadHeroContent() {
        const hero = await this.fetchContent('hero');
        if (hero) {
            this.updateHeroSection(hero);
        }
    }

    updateHeroSection(hero) {
        const titleElement = document.querySelector('#section-hero h2');
        const descriptionElement = document.querySelector('#section-hero h5');
        const primaryButton = document.querySelector('#section-hero .btn-main:first-of-type');
        const secondaryButton = document.querySelector('#section-hero .btn-main:last-of-type');

        if (titleElement && hero.title) {
            titleElement.textContent = hero.title;
        }
        if (descriptionElement && hero.description) {
            descriptionElement.textContent = hero.description;
        }
        if (primaryButton && hero.primary_button_text) {
            primaryButton.querySelector('span').textContent = hero.primary_button_text;
            if (hero.primary_button_link) {
                primaryButton.href = hero.primary_button_link;
            }
        }
        if (secondaryButton && hero.secondary_button_text) {
            secondaryButton.querySelector('span').textContent = hero.secondary_button_text;
            if (hero.secondary_button_link) {
                secondaryButton.href = hero.secondary_button_link;
            }
        }
    }

    async loadOverviewContent() {
        const overview = await this.fetchContent('overview');
        if (overview) {
            this.updateOverviewSection(overview);
        }
    }

    updateOverviewSection(overview) {
        const subtitleElement = document.querySelector('#section-overview .subtitle');
        const titleElement = document.querySelector('#section-overview h2');
        const descriptionElement = document.querySelector('#section-overview p');
        const imageElement = document.querySelector('#section-overview img');

        if (subtitleElement && overview.subtitle) {
            subtitleElement.textContent = overview.subtitle;
        }
        if (titleElement && overview.title) {
            titleElement.textContent = overview.title;
        }
        if (descriptionElement && overview.description) {
            descriptionElement.textContent = overview.description;
        }
        if (imageElement && overview.image_path) {
            imageElement.src = `uploads/${overview.image_path}`;
        }
    }

    async loadProperties() {
        const properties = await this.fetchContent('properties');
        if (properties) {
            this.updatePropertiesSection(properties);
        }
    }

    updatePropertiesSection(properties) {
        const container = document.getElementById('propertiesContainer');
        if (!container) return;

        container.innerHTML = '';

        properties.forEach(property => {
            const propertyHTML = this.createPropertyHTML(property);
            container.insertAdjacentHTML('beforeend', propertyHTML);
        });

        // Reinitialize any interactive elements
        this.initializePropertyInteractions();
    }

    createPropertyHTML(property) {
        const price = this.formatPrice(property.price);
        const imageSrc = property.image_path ? `uploads/${property.image_path}` : 'images/placeholder.jpg';
        
        return `
            <div class="col-md-6 property-item" data-location="${property.location}" data-type="${property.bedrooms}" data-price="${property.price}">
                <div class="hover overflow-hidden relative text-light text-center wow zoomIn" data-wow-delay=".0s">
                    ${property.is_featured ? '<span class="position-absolute top-0 start-0 m-2 px-3 py-1 bg-light text-dark text-white badge z-3" style="font-size: 0.85rem;">Featured</span>' : ''}
                    <div class="wow scaleIn overflow-hidden">
                        <img src="${imageSrc}" class="hover-scale-1-1 w-100" alt="${property.name}">
                    </div>
                    <div class="abs w-100 px-4 hover-op-1 z-4 hover-mt-40 abs-centered">
                        <a class="btn-main btn-line fx-slide" href="${property.link_url || '#'}"><span>View Details</span></a>
                    </div>
                    <div class="abs bg-blur z-2 top-0 w-100 h-100 hover-op-1"></div>
                    <div class="abs z-2 bottom-0 p-10 w-100 text-center hover-op-0">
                        <div class="d-flex justify-content-between align-items-center">
                            <h3 class="mb-0">${property.name}</h3>
                        </div>
                        <div class="d-flex justify-content-between align-items-center">
                            <span>${property.location}</span>
                            <span class="badge bg-dark"> <i class="fa-solid fa-bed me-1"></i>${property.bedrooms}</span>
                        </div>
                        <div class="d-flex justify-content-between align-items-center mt-2">
                            <span class="badge bg-dark">${property.property_type}</span>
                            <span class="badge bg-light text-dark">Starting from ${price}</span>
                        </div>
                        <small class="d-block mt-4" style="font-size: 0.85em; color: #e0cf1b;">*Prices are subject to change based on inventory availability*</small>
                    </div>
                    <div class="gradient-edge-bottom abs w-100 h-40 bottom-0"></div>
                </div>
            </div>
        `;
    }

    formatPrice(price) {
        return new Intl.NumberFormat('en-AE', {
            style: 'currency',
            currency: 'AED',
            minimumFractionDigits: 0
        }).format(price);
    }

    async loadAgents() {
        const agents = await this.fetchContent('agents');
        if (agents) {
            this.updateAgentsSection(agents);
        }
    }

    updateAgentsSection(agents) {
        const carouselInner = document.querySelector('#agentCarousel .carousel-inner');
        if (!carouselInner) return;

        // Clear existing content
        carouselInner.innerHTML = '';

        // Group agents into slides (3 per slide)
        const agentsPerSlide = 3;
        for (let i = 0; i < agents.length; i += agentsPerSlide) {
            const slideAgents = agents.slice(i, i + agentsPerSlide);
            const slideHTML = this.createAgentSlideHTML(slideAgents, i === 0);
            carouselInner.insertAdjacentHTML('beforeend', slideHTML);
        }
    }

    createAgentSlideHTML(agents, isActive = false) {
        const activeClass = isActive ? 'active' : '';
        
        return `
            <div class="carousel-item ${activeClass}">
                <div class="row justify-content-center">
                    ${agents.map(agent => this.createAgentHTML(agent)).join('')}
                </div>
            </div>
        `;
    }

    createAgentHTML(agent) {
        const imageSrc = agent.image_path ? `uploads/${agent.image_path}` : 'images/placeholder-agent.jpg';
        
        return `
            <div class="col-md-3">
                <div class="text-center">
                    <img src="${imageSrc}" class="w-60" alt="${agent.name}">
                    <div class="mt-3">
                        <h4 class="mb-0">${agent.name}</h4>
                        <div class="fw-500 id-color">${agent.title}</div>
                        <div class="fw-500 id-color">${agent.languages}</div>
                        <div class="mt-2">
                            <a href="mailto:${agent.email}" title="Email" class="me-3">
                                <i class="fa-solid fa-envelope fa-lg"></i>
                            </a>
                            <a title="Call" class="me-3 callBtn" data-agent="${agent.name}" data-phone="${agent.phone}" data-agent-inc="${agent.agent_code}">
                                <i class="fa-solid fa-phone fa-lg"></i>
                            </a>
                            <a title="WhatsApp" class="whatsappBtn" data-agent="${agent.name}" data-phone="${agent.phone}" data-agent-inc="${agent.agent_code}">
                                <i class="fa-brands fa-whatsapp fa-lg"></i>
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    async loadFAQs() {
        const faqs = await this.fetchContent('faqs');
        if (faqs) {
            this.updateFAQsSection(faqs);
        }
    }

    updateFAQsSection(faqs) {
        const faqContainer = document.querySelector('#faq .container');
        if (!faqContainer) return;

        // Find the FAQ content area and update it
        const leftColumn = faqContainer.querySelector('.col-lg-6:first-child');
        const rightColumn = faqContainer.querySelector('.col-lg-6:last-child');

        if (leftColumn && rightColumn) {
            const leftFAQs = faqs.slice(0, Math.ceil(faqs.length / 2));
            const rightFAQs = faqs.slice(Math.ceil(faqs.length / 2));

            leftColumn.innerHTML = this.createFAQsHTML(leftFAQs);
            rightColumn.innerHTML = this.createFAQsHTML(rightFAQs);
        }
    }

    createFAQsHTML(faqs) {
        return `
            <div class="pe-lg-4 py-5 my-5">
                <div class="subtitle wow fadeInUp" data-wow-delay=".2s">FAQ's</div>
                <h2 class="wow fadeInUp" data-wow-delay=".3s">FAQs About Dubai Hills Estate</h2>
                ${faqs.map((faq, index) => `
                    <div class="mt-4 wow fadeInUp" data-wow-delay="${0.4 + (index * 0.2)}s">
                        <h5>${faq.question}</h5>
                        <p>${faq.answer}</p>
                    </div>
                `).join('')}
            </div>
        `;
    }

    async loadAboutContent() {
        const aboutContent = await this.fetchContent('about');
        if (aboutContent) {
            this.updateAboutSection(aboutContent);
        }
    }

    updateAboutSection(aboutContent) {
        // Group content by section
        const contentBySection = {};
        aboutContent.forEach(item => {
            if (!contentBySection[item.section]) {
                contentBySection[item.section] = [];
            }
            contentBySection[item.section].push(item);
        });

        // Update each section
        Object.keys(contentBySection).forEach(section => {
            const sectionElement = document.querySelector(`[data-section="${section}"]`);
            if (sectionElement) {
                const content = contentBySection[section];
                sectionElement.innerHTML = content.map(item => `
                    <h4 class="mt-4 wow fadeInUp">${item.title}</h4>
                    <p class="wow fadeInUp text-white">${item.content}</p>
                `).join('');
            }
        });
    }

    async loadContactInfo() {
        const contactInfo = await this.fetchContent('contact');
        if (contactInfo) {
            this.updateContactSection(contactInfo);
        }
    }

    updateContactSection(contactInfo) {
        // Update contact information in footer or contact section
        contactInfo.forEach(contact => {
            const element = document.querySelector(`[data-contact-type="${contact.type}"]`);
            if (element) {
                if (contact.link) {
                    element.href = contact.link;
                    element.textContent = contact.value;
                } else {
                    element.textContent = contact.value;
                }
            }
        });
    }

    async loadFooterLinks() {
        const footerLinks = await this.fetchContent('footer_links');
        if (footerLinks) {
            this.updateFooterLinks(footerLinks);
        }
    }

    updateFooterLinks(footerLinks) {
        // Group links by section
        const linksBySection = {};
        footerLinks.forEach(link => {
            if (!linksBySection[link.section]) {
                linksBySection[link.section] = [];
            }
            linksBySection[link.section].push(link);
        });

        // Update each footer section
        Object.keys(linksBySection).forEach(section => {
            const sectionElement = document.querySelector(`[data-footer-section="${section}"]`);
            if (sectionElement) {
                const links = linksBySection[section];
                sectionElement.innerHTML = links.map(link => `
                    <li><i class="fas fa-angle-right me-2"></i> <a href="${link.url}" class="text-light text-decoration-none">${link.title}</a></li>
                `).join('');
            }
        });
    }

    initializePropertyInteractions() {
        // Reinitialize property search and filter functionality
        if (typeof initializePropertySearch === 'function') {
            initializePropertySearch();
        }
    }

    async loadAllContent() {
        try {
            await Promise.all([
                this.loadHeroContent(),
                this.loadOverviewContent(),
                this.loadProperties(),
                this.loadAgents(),
                this.loadFAQs(),
                this.loadAboutContent(),
                this.loadContactInfo(),
                this.loadFooterLinks()
            ]);
        } catch (error) {
            console.error('Error loading content:', error);
        }
    }

    // Clear cache
    clearCache() {
        this.cache.clear();
    }

    // Refresh content
    async refreshContent() {
        this.clearCache();
        await this.loadAllContent();
    }
}

// Initialize CMS Loader when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
    window.cmsLoader = new CMSLoader();
    
    // Load all content
    window.cmsLoader.loadAllContent();
    
    // Optional: Add refresh button for admin users
    if (window.location.pathname.includes('cms')) {
        const refreshBtn = document.createElement('button');
        refreshBtn.className = 'btn btn-sm btn-outline-secondary';
        refreshBtn.innerHTML = '<i class="fas fa-sync-alt"></i> Refresh Content';
        refreshBtn.onclick = () => window.cmsLoader.refreshContent();
        
        const header = document.querySelector('.header .container-fluid .row .col-auto');
        if (header) {
            header.appendChild(refreshBtn);
        }
    }
});
