document.addEventListener('DOMContentLoaded', () => {
    updatePrices();
});

async function updatePrices() {
    let customPrices = {};

    try {
        // 1. Fetch custom prices from the server (JSON file)
        // Adding a timestamp to prevent caching
        const response = await fetch('admin/prices.json?t=' + new Date().getTime());
        if (response.ok) {
            customPrices = await response.json();
        }
    } catch (error) {
        console.error('CRITICAL ERROR: Could not load custom prices from server.', error);
        console.log('Ensure "admin/prices.json" exists and is accessible.');
        console.warn('Falling back to default base prices.');
    }

    // 2. Iterate through all room data
    roomData.forEach(room => {
        let actualPrice = room.basePrice + 2500; // Default actual price higher than base to show offer
        let offerPrice = room.basePrice;
        let isLocked = false;

        if (customPrices[room.id]) {
            if (typeof customPrices[room.id] === 'object') {
                actualPrice = customPrices[room.id].actual || (room.basePrice + 2500);
                offerPrice = customPrices[room.id].offer || room.basePrice;

                // Determine whether today is locked based on the lockedDates array
                // The resort is in India (Kodaikanal), so we calculate "today" in IST
                const todayStr = new Date().toLocaleDateString('en-CA', { timeZone: 'Asia/Kolkata' });

                const lockedDates = customPrices[room.id].lockedDates || "";
                const lockedDatesArray = lockedDates.split(",").map(d => d.trim());

                const isLegacyLocked = customPrices[room.id].locked === true || customPrices[room.id].locked === "true" || customPrices[room.id].locked == 1;

                isLocked = isLegacyLocked || lockedDatesArray.includes(todayStr);
            } else {
                // Backwards compatibility
                actualPrice = parseInt(customPrices[room.id]) + 2500;
                offerPrice = customPrices[room.id];
            }
        }

        // Format price with commas (e.g., 14,000)
        const formattedActual = '₹' + parseInt(actualPrice).toLocaleString('en-IN');
        const formattedOffer = '₹' + parseInt(offerPrice).toLocaleString('en-IN');

        // 3. Find elements on the page that need this price
        // We look for elements with data-room-id="ID"
        const elements = document.querySelectorAll(`[data-room-id="${room.id}"]`);

        elements.forEach(el => {
            if (parseInt(actualPrice) > parseInt(offerPrice)) {
                // Improve UI aesthetics for pricing
                const parentTextCentered = el.parentElement;
                if (parentTextCentered && parentTextCentered.tagName === 'H3' && parentTextCentered.classList.contains('text-center')) {
                    // For room pages (card sticky top)
                    el.innerHTML = `
                        <div class="d-flex flex-column align-items-center justify-content-center">
                            <span class="room-actual-price text-decoration-line-through text-muted fs-6 mb-1">${formattedActual}</span>
                            <span class="room-offer-price text-gold fw-bold display-6 mb-0">${formattedOffer}</span>
                        </div>
                     `;
                } else {
                    // For room cards on index
                    el.innerHTML = `<span class="room-actual-price text-decoration-line-through text-dark small me-2" style="opacity: 0.7;">${formattedActual}</span><span class="room-offer-price text-black fw-bold">${formattedOffer}</span>`;
                }
            } else {
                // If it's single price, keep it simple
                el.innerHTML = `<span class="room-offer-price text-black fw-bold">${formattedOffer}</span>`;
            }
        });

        // ==========================================
        // UI HANDLING FOR LOCKED (BOOKED) ROOMS
        // ==========================================

        // 1. Handling Room Cards (Globally on Index & Rooms page)
        const roomWrappers = document.querySelectorAll('.room-img-wrapper');
        roomWrappers.forEach(wrapper => {
            // Check if wrapper belongs to this room by finding the price element inside its parent
            const card = wrapper.closest('.room-card');
            if (card) {
                const priceEl = card.querySelector(`[data-room-id="${room.id}"]`);
                if (priceEl) {
                    if (isLocked) {
                        // Apply Booked UI
                        if (!wrapper.querySelector('.booked-tag')) {
                            const tag = document.createElement('div');
                            tag.className = 'booked-tag bg-danger text-white px-3 py-1 fw-bold rounded shadow-sm';
                            tag.style.position = 'absolute';
                            tag.style.top = '15px';
                            tag.style.left = '15px';
                            tag.style.zIndex = '10';
                            tag.style.fontSize = '0.9rem';
                            tag.innerHTML = '<i class="fas fa-lock me-1"></i> BOOKED';
                            wrapper.appendChild(tag);

                            // Dim the image slightly
                            const img = wrapper.querySelector('img');
                            if (img) img.style.opacity = '0.6';
                            if (img) img.style.filter = 'grayscale(50%)';
                        }
                    } else {
                        // 4. Add "1 Room Left!" Urgency Tag ONLY if NOT locked
                        if (!wrapper.querySelector('.urgency-tag')) {
                            const tag = document.createElement('div');
                            tag.className = 'urgency-tag';
                            tag.innerHTML = '<i class="fas fa-fire me-1"></i> 1 Room Left!';
                            wrapper.appendChild(tag);
                        }
                    }
                }
            }
        });

        // 2. Handling Specific Room Page Booking CTAs
        if (isLocked) {
            // Look for desktop sticky card and mobile booking options specifically matching this room id
            const bookingContainers = [
                document.querySelector('.card.sticky-top'),
                document.querySelector('#mobileBookingOptions')
            ];

            bookingContainers.forEach(container => {
                if (container) {
                    const hasThisRoomPrice = container.querySelector(`[data-room-id="${room.id}"]`);
                    if (hasThisRoomPrice) {
                        // We are on the page of the locked room.
                        // Disable the main Book Now button
                        const bookBtn = container.querySelector('a.btn-luxury');
                        if (bookBtn) {
                            bookBtn.classList.remove('btn-luxury');
                            bookBtn.classList.add('btn', 'btn-secondary', 'disabled');
                            bookBtn.innerHTML = '<i class="fas fa-lock me-2"></i> ROOM BOOKED';
                            bookBtn.style.cursor = 'not-allowed';
                            bookBtn.removeAttribute('href');
                        }

                        // Pass locked dates to WhatsApp button to prevent booking locked dates
                        const whatsappBtn = container.querySelector('.btn-whatsapp-promo');
                        if (whatsappBtn) {
                            let datesToLock = [];
                            if (lockedDatesArray && lockedDatesArray.length > 0 && lockedDatesArray[0] !== "") {
                                datesToLock = [...lockedDatesArray];
                            }
                            if (isLegacyLocked && !datesToLock.includes(todayStr)) {
                                datesToLock.push(todayStr);
                            }
                            if (datesToLock.length > 0) {
                                whatsappBtn.setAttribute('data-locked-dates', datesToLock.join(','));
                            }
                        }

                        // Call button should remain active even if the room is locked
                        const callBtn = container.querySelector('.btn-call-promo');
                        // if (callBtn) {
                        //     callBtn.classList.add('disabled');
                        //     callBtn.style.opacity = '0.5';
                        //     callBtn.style.cursor = 'not-allowed';
                        //     callBtn.removeAttribute('href');
                        // }
                    }
                }
            });
        }

        // For individual room pages' pricing card Urgency tag (Only if NOT locked)
        if (!isLocked) {
            const stickyCard = document.querySelector('.card.sticky-top');
            if (stickyCard) {
                // Check if this page is for THIS room 
                const hasThisRoomPrice = document.querySelector(`[data-room-id="${room.id}"]`);
                if (hasThisRoomPrice && !stickyCard.querySelector('.urgency-tag-main')) {
                    const tag = document.createElement('div');
                    tag.className = 'urgency-tag-main text-center mb-3 text-danger fw-bold';
                    tag.style.animation = 'pulse-red 2s infinite';
                    tag.innerHTML = '<i class="fas fa-fire me-1 text-warning"></i> Hurry! Only 1 Room Left!';

                    // Insert it right after the HR in the sticky top card
                    const hrElement = stickyCard.querySelector('hr');
                    if (hrElement) {
                        hrElement.parentNode.insertBefore(tag, hrElement.nextSibling);
                    }
                }
            }
        }
    });
}
