const services = [
    // --- MANICURE & PEDICURE ---
    { id: 1, name: 'Cuccio Bella Manicure', price: 1200, category: 'manicure', description: 'Classic beauty with Cuccio Bella.' },
    { id: 2, name: 'Cuccio Bella Pedicure', price: 1600, category: 'pedicure', description: 'Classic beauty with Cuccio Bella.' },
    { id: 3, name: 'Lavender Relieve Manicure', price: 1200, category: 'manicure', description: 'Soothing lavender experience.' },
    { id: 4, name: 'Lavender Relieve Pedicure', price: 1600, category: 'pedicure', description: 'Soothing lavender experience.' },
    { id: 5, name: 'De-tan Manicure', price: 1400, category: 'manicure', description: 'Remove tan and restore glow.' },
    { id: 6, name: 'De-tan Pedicure', price: 1800, category: 'pedicure', description: 'Remove tan and restore glow.' },
    { id: 7, name: 'GreenTea Detox Manicure', price: 1400, category: 'manicure', description: 'Detoxifying green tea therapy.' },
    { id: 8, name: 'GreenTea Detox Pedicure', price: 1800, category: 'pedicure', description: 'Detoxifying green tea therapy.' },
    { id: 9, name: 'Pomegranate Radiant Mani', price: 1400, category: 'manicure', description: 'Radiant skin with pomegranate.' },
    { id: 10, name: 'Pomegranate Radiant Pedi', price: 1800, category: 'pedicure', description: 'Radiant skin with pomegranate.' },
    { id: 11, name: 'Heel Peel Treatment', price: 1400, category: 'pedicure', description: 'Expert callus and heel care.' },
    { id: 12, name: 'Coffee & Choco Manicure', price: 1600, category: 'manicure', description: 'Rich coffee and cocoa indulgence.' },
    { id: 13, name: 'Coffee & Choco Pedicure', price: 1900, category: 'pedicure', description: 'Rich coffee and cocoa indulgence.' },
    { id: 14, name: 'Cuccio Paradise Manicure', price: 1850, category: 'manicure', description: 'Premium tropical paradise spa.' },
    { id: 15, name: 'Cuccio Paradise Pedicure', price: 2050, category: 'pedicure', description: 'Premium tropical paradise spa.' },
    { id: 16, name: 'Bombini Donut Manicure', price: 1700, category: 'manicure', description: 'Sweet Bombini donut ritual.' },
    { id: 17, name: 'Bombini Donut Pedicure', price: 1950, category: 'pedicure', description: 'Sweet Bombini donut ritual.' },
    { id: 18, name: 'Milk and Honey Manicure', price: 2050, category: 'manicure', description: 'Classic milk and honey hydration.' },
    { id: 19, name: 'Milk and Honey Pedicure', price: 2450, category: 'pedicure', description: 'Classic milk and honey hydration.' },

    // --- NAIL SERVICES ---
    { id: 20, name: 'Gelpolish', price: 1250, category: 'nail_services', description: 'High-shine long-lasting gel polish.' },
    { id: 21, name: 'French Gel Polish', price: 1750, category: 'nail_services', description: 'Elegant French tip in gel.' },
    { id: 22, name: 'Russian Overlays', price: 2050, category: 'nail_services', description: 'Professional Russian-style nail overlays.' },
    { id: 23, name: 'Temporary Extensions', price: 2200, category: 'nail_services', description: 'Perfect extensions for special occasions.' },
    { id: 24, name: 'Flexo Extensions', price: 2700, category: 'nail_services', description: 'Flexible and natural-looking extensions.' },
    { id: 25, name: 'Permanent Extensions', price: 3700, category: 'nail_services', description: 'Ultra-durable permanent extensions.' },
    { id: 26, name: 'French Extensions', price: 4000, category: 'nail_services', description: 'Classic French extensions.' },
    { id: 27, name: 'Nail Refills', price: 2400, category: 'nail_services', description: 'Refresh your existing extensions.' },
    { id: 28, name: 'Nail Art (Per Nail)', price: 40, category: 'nail_services', description: 'Custom hand-painted nail designs.' },

    // --- COUPLE REJUVENATION ---
    { id: 29, name: 'Classic Package (Mani+Pedi)', price: 5400, category: 'couple_rejuvenation', description: 'The Bella experience for two.' },
    { id: 30, name: 'Classic Package (Pedicure)', price: 3000, category: 'couple_rejuvenation', description: 'The Bella pedicure for two.' },
    { id: 31, name: 'Signature Package (Mani+Pedi)', price: 6000, category: 'couple_rejuvenation', description: 'Green Tea detox for two.' },
    { id: 32, name: 'Signature Package (Pedicure)', price: 3400, category: 'couple_rejuvenation', description: 'Green Tea pedicure for two.' },
    { id: 33, name: 'Premium Package (Mani+Pedi)', price: 6800, category: 'couple_rejuvenation', description: 'Bombini Detox / Golden Glimmer for two.' },
    { id: 34, name: 'Premium Package (Pedicure)', price: 3800, category: 'couple_rejuvenation', description: 'Bombini / Glimmer pedicure for two.' }
];

const technicians = [
    { id: 1, name: 'Divyata', role: 'Manager', branch: 'thaltej', img: 'https://images.unsplash.com/photo-1573496359142-b8d87734a5a2?w=150&h=150&fit=crop' },
    { id: 2, name: 'Vishwa', role: 'Nail Artist', branch: 'thaltej', img: 'https://images.unsplash.com/photo-1544005313-94ddf0286df2?w=150&h=150&fit=crop' },
    { id: 3, name: 'Lishita', role: 'Nail Tech', branch: 'thaltej', img: 'https://images.unsplash.com/photo-1494790108377-be9c29b29330?w=150&h=150&fit=crop' },
    { id: 4, name: 'Pinal', role: 'Nail Tech', branch: 'one42', img: 'https://images.unsplash.com/photo-1531123897727-8f129e1688ce?w=150&h=150&fit=crop' },
    { id: 5, name: 'Mayuri', role: 'Manicurist', branch: 'one42', img: 'https://images.unsplash.com/photo-1554151228-14d9def656e4?w=150&h=150&fit=crop' },
    { id: 6, name: 'Payal', role: 'Manicurist', branch: 'thaltej', img: 'https://images.unsplash.com/photo-1580489944761-15a19d654956?w=150&h=150&fit=crop' },
    { id: 7, name: 'Shital', role: 'Manicurist', branch: 'one42', img: 'https://images.unsplash.com/photo-1567532939604-b6b5b0db2a04?w=150&h=150&fit=crop' },
    { id: 8, name: 'Rupal', role: 'Pedicurist', branch: 'thaltej', img: 'https://images.unsplash.com/photo-1548142813-c348350df52b?w=150&h=150&fit=crop' },
    { id: 9, name: 'Maitri', role: 'Manicurist', branch: 'one42', img: 'https://images.unsplash.com/photo-1544717297-fa95b35c7a08?w=150&h=150&fit=crop' },
    { id: 10, name: 'Sanju', role: 'Nail Tech', branch: 'thaltej', img: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=150&h=150&fit=crop' },
    { id: 11, name: 'Animita', role: 'Nail Tech', branch: 'one42', img: 'https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=150&h=150&fit=crop' },
    { id: 12, name: 'Soumen', role: 'Nail Artist', branch: 'thaltej', img: 'https://images.unsplash.com/photo-1500648767791-00dcc994a43e?w=150&h=150&fit=crop' },
    { id: 13, name: 'Paritosh', role: 'Nail Tech', branch: 'one42', img: 'https://images.unsplash.com/photo-1506794778202-cad84cf45f1d?w=150&h=150&fit=crop' },
    { id: 14, name: 'Biswajit', role: 'Nail Artist', branch: 'thaltej', img: 'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=150&h=150&fit=crop' },
    { id: 15, name: 'Vijay', role: 'Nail Tech', branch: 'one42', img: 'https://images.unsplash.com/photo-1552058544-f2b08422138a?w=150&h=150&fit=crop' },
    { id: 16, name: 'Sabir', role: 'Pedicurist', branch: 'thaltej', img: 'https://images.unsplash.com/photo-1539571696357-5a69c17a67c6?w=150&h=150&fit=crop' },
    { id: 17, name: 'Avinay', role: 'Pedicurist', branch: 'one42', img: 'https://images.unsplash.com/photo-1519085360753-af0119f7cbe7?w=150&h=150&fit=crop' },
    { id: 18, name: 'Mukesh', role: 'Pedicurist', branch: 'thaltej', img: 'https://images.unsplash.com/photo-1508214751196-bcfd4ca60f91?w=150&h=150&fit=crop' },
    { id: 19, name: 'Mahek', role: 'Manager', branch: 'thaltej', img: 'https://images.unsplash.com/photo-1520813792240-56fc4a3765a7?w=150&h=150&fit=crop' },
    { id: 20, name: 'Suman', role: 'Nail Tech', branch: 'thaltej', img: 'https://images.unsplash.com/photo-1488426862026-3ee34a7d66df?w=150&h=150&fit=crop' },
    { id: 21, name: 'Sujoy', role: 'Nail Tech', branch: 'thaltej', img: 'https://images.unsplash.com/photo-1501196354995-cbb51c65aaea?w=150&h=150&fit=crop' },
    { id: 22, name: 'Nidhi', role: 'Nail Tech', branch: 'thaltej', img: 'https://images.unsplash.com/photo-1517841905240-472988babdf9?w=150&h=150&fit=crop' },
    { id: 23, name: 'Nisha', role: 'Nail Tech', branch: 'thaltej', img: 'https://images.unsplash.com/photo-1524504388940-b1c1722653e1?w=150&h=150&fit=crop' },
    { id: 24, name: 'Manpreet', role: 'Nail Tech', branch: 'thaltej', img: 'https://images.unsplash.com/photo-1529626455594-4ff0802cfb7e?w=150&h=150&fit=crop' },
    { id: 25, name: 'Tisha', role: 'Nail Tech', branch: 'thaltej', img: 'https://images.unsplash.com/photo-1502685104226-ee32379fefbe?w=150&h=150&fit=crop' },
    { id: 26, name: 'Himali', role: 'Manicurist', branch: 'thaltej', img: 'https://images.unsplash.com/photo-1438761681033-6461ffad8d80?w=150&h=150&fit=crop' },
    { id: 27, name: 'Ratan', role: 'Pedicurist', branch: 'thaltej', img: 'https://images.unsplash.com/photo-1554151228-14d9def656e4?w=150&h=150&fit=crop' },
    { id: 28, name: 'Megha', role: 'Nail Tech', branch: 'thaltej', img: 'https://images.unsplash.com/photo-1514315384763-ba401779410f?w=150&h=150&fit=crop' },
    { id: 29, name: 'Sumi', role: 'Nail Tech', branch: 'thaltej', img: 'https://images.unsplash.com/photo-1521119907119-635583685e12?w=150&h=150&fit=crop' },
    { id: 30, name: 'Pratik', role: 'Pedicurist', branch: 'thaltej', img: 'https://images.unsplash.com/photo-1506794778202-cad84cf45f1d?w=150&h=150&fit=crop' },
    { id: 31, name: 'Tanisha', role: 'Manicurist', branch: 'thaltej', img: 'https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=150&h=150&fit=crop' },
    { id: 32, name: 'Bhakti', role: 'Pedicurist', branch: 'thaltej', img: 'https://images.unsplash.com/photo-1524250502761-1ac6f2e30d43?w=150&h=150&fit=crop' },
    { id: 33, name: 'Ajay', role: 'Pedicurist', branch: 'thaltej', img: 'https://images.unsplash.com/photo-1500648767791-00dcc994a43e?w=150&h=150&fit=crop' },
    { id: 34, name: 'Hinal', role: 'Manicurist', branch: 'thaltej', img: 'https://images.unsplash.com/photo-1488426862026-3ee34a7d66df?w=150&h=150&fit=crop' },
    { id: 35, name: 'Ajit', role: 'Pedicurist', branch: 'thaltej', img: 'https://images.unsplash.com/photo-1519085360753-af0119f7cbe7?w=150&h=150&fit=crop' }
];

let cart = [];
let currentMonth = new Date().getMonth();
let currentYear = new Date().getFullYear();
let selectedDate = null;
let selectedTime = null;
let selectedTechnician = null;

document.addEventListener('DOMContentLoaded', () => {
    const catalogGrid = document.getElementById('servicesGrid');
    const summaryItems = document.getElementById('cartList');
    const totalPriceEl = document.getElementById('totalPrice');
    const tabBtns = document.querySelectorAll('.tab-btn');
    const monthLabel = document.getElementById('monthDisplay');
    const daysGrid = document.getElementById('daysGrid');
    const timeGrid = document.getElementById('timeGrid');
    const techGrid = document.getElementById('techGrid');

    window.renderCatalog = (cat) => {
        catalogGrid.innerHTML = '';
        const filtered = cat === 'all' ? services : services.filter(s => s.category === cat);
        filtered.forEach((s, index) => {
            const el = document.createElement('div');
            el.className = 'service-item';
            el.innerHTML = `
                <div class="service-details">
                    <h3 class="service-name">${s.name}</h3>
                    <p class="service-desc">${s.description}</p>
                    <div class="service-price">₹${s.price}</div>
                </div>
                <button class="add-btn" onclick="addToCart(${s.id})">Add to Package</button>
            `;
            catalogGrid.appendChild(el);
        });
    };

    window.addToCart = (id) => {
        const item = services.find(s => s.id === id);
        if (!cart.find(c => c.id === id)) {
            cart.push(item);
            showToast(`${item.name} added!`);
            updateCart();
        } else {
            showToast('Already added.');
        }
    };

    window.removeFromCart = (id) => {
        cart = cart.filter(c => c.id !== id);
        updateCart();
    };

    function updateCart() {
        summaryItems.innerHTML = '';
        let baseTotal = 0;
        cart.forEach(item => {
            const div = document.createElement('div');
            div.className = 'selected-item';
            div.innerHTML = `
                <div class="selected-details">
                    <span class="selected-name">${item.name}</span>
                    <span class="selected-price">₹${item.price}</span>
                </div>
                <button class="remove-btn" onclick="removeFromCart(${item.id})">
                    <i class="fas fa-trash-alt"></i>
                </button>
            `;
            summaryItems.appendChild(div);
            baseTotal += item.price;
        });

        const isGroup = document.getElementById('groupBookingToggle').checked;
        const groupSize = parseInt(document.getElementById('groupSize').value) || 1;
        const total = isGroup ? baseTotal * groupSize : baseTotal;

        totalPriceEl.textContent = '₹' + total;
        
        // Logic for Dynamic Suggestions
        let recommended = [];
        if (cart.length === 0) {
            summaryItems.innerHTML = `
                <div class="empty-cart-state">
                    <p>No services added yet.</p>
                </div>
            `;
        } else {
            // Context-Aware: Show ALL services from related categories
            const currentCategories = new Set(cart.map(s => s.category));
            
            if (currentCategories.size > 0) {
                recommended = services.filter(s => currentCategories.has(s.category));
            } else {
                recommended = services.slice(0, 15);
            }

            // Filter out items already in cart
            recommended = recommended.filter(r => !cart.some(c => c.id === r.id));

            // Create a truly "Infinite" feel by repeating the list 20 times
            let repeatedItems = '';
            if (recommended.length > 0) {
                const itemsHTML = recommended.map(r => `<button class="suggestion-chip" onclick="addToCart(${r.id})">+ ${r.name}</button>`).join('');
                for (let i = 0; i < 20; i++) {
                    repeatedItems += itemsHTML;
                }
            }

            const suggestionsHTML = recommended.length > 0 ? `
                <div class="cart-suggestions">
                    <span class="suggestion-label">Perfect Add-ons:</span>
                    <div class="suggestion-chips-container">
                        <button class="nav-arrow left" onclick="document.querySelector('.suggestion-chips').scrollBy({left: -200, behavior: 'smooth'})"><i class="fas fa-chevron-left"></i></button>
                        <div class="suggestion-chips">
                            <div class="suggestion-chips-inner">
                                ${repeatedItems}
                            </div>
                        </div>
                        <button class="nav-arrow right" onclick="document.querySelector('.suggestion-chips').scrollBy({left: 200, behavior: 'smooth'})"><i class="fas fa-chevron-right"></i></button>
                    </div>
                </div>
            ` : '';

            if (suggestionsHTML) {
                const suggestionContainer = document.createElement('div');
                suggestionContainer.innerHTML = suggestionsHTML;
                summaryItems.appendChild(suggestionContainer);
            }
        }
    }

    // Group Booking Logic
    const groupToggle = document.getElementById('groupBookingToggle');
    const groupDetails = document.getElementById('groupDetailsContainer');
    const groupSizeInput = document.getElementById('groupSize');

    groupToggle.addEventListener('change', () => {
        if (groupToggle.checked) {
            groupDetails.style.display = 'block';
        } else {
            groupDetails.style.display = 'none';
        }
        updateCart();
    });

    groupSizeInput.addEventListener('input', () => {
        let val = parseInt(groupSizeInput.value);
        if (val < 2) val = 2;
        if (val > 10) val = 10;
        groupSizeInput.value = val;
        updateCart();
    });

    tabBtns.forEach(btn => {
        btn.onclick = () => {
            tabBtns.forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
            renderCatalog(btn.dataset.category);
        };
    });

    window.renderCalendar = () => {
        daysGrid.innerHTML = '';
        const date = new Date(currentYear, currentMonth, 1);
        const lastDay = new Date(currentYear, currentMonth + 1, 0).getDate();
        const startDay = date.getDay();
        monthLabel.textContent = date.toLocaleString('default', { month: 'long', year: 'numeric' });
        for (let i = 0; i < startDay; i++) {
            const empty = document.createElement('div'); empty.className = 'day disabled'; daysGrid.appendChild(empty);
        }
        for (let i = 1; i <= lastDay; i++) {
            const dayEl = document.createElement('div'); dayEl.className = 'day'; dayEl.textContent = i;
            if (selectedDate === i) dayEl.classList.add('active');
            dayEl.onclick = () => { selectedDate = i; renderCalendar(); showToast(`Date: ${i} ${monthLabel.textContent}`); };
            daysGrid.appendChild(dayEl);
        }
    };

    document.getElementById('prevMonth').onclick = () => { currentMonth--; renderCalendar(); };
    document.getElementById('nextMonth').onclick = () => { currentMonth++; renderCalendar(); };

    window.generateTimes = () => {
        timeGrid.innerHTML = '';
        const times = ['11:00 AM', '01:30 PM', '03:30 PM', '05:30 PM'];
        times.forEach(t => {
            const chip = document.createElement('div'); chip.className = 'time-chip';
            if (selectedTime === t) chip.classList.add('active');
            chip.textContent = t;
            chip.onclick = () => { selectedTime = t; generateTimes(); showToast(`Time: ${t}`); };
            timeGrid.appendChild(chip);
        });
    };

    window.renderTechnicians = () => {
        const branch = document.getElementById('branchSelectValue').value;
        techGrid.innerHTML = '';
        
        // Filter technicians based on branch
        const filteredTechs = branch ? technicians.filter(t => t.branch === branch) : technicians;
        
        if (filteredTechs.length === 0 && branch) {
            techGrid.innerHTML = '<p style="grid-column: 1/-1; text-align: center; color: #888; padding: 20px;">No technicians available at this branch.</p>';
            return;
        }

        filteredTechs.forEach(tech => {
            const card = document.createElement('div');
            card.className = 'tech-card';
            if (selectedTechnician === tech.id) card.classList.add('active');
            card.innerHTML = `
                <img src="${tech.img}" alt="${tech.name}" class="tech-img">
                <div class="tech-info">
                    <h5 class="tech-name">${tech.name}</h5>
                    <p class="tech-role">${tech.role}</p>
                </div>
                <div class="tech-check"><i class="fas fa-check"></i></div>
            `;
            card.onclick = () => {
                if (selectedTechnician === tech.id) {
                    selectedTechnician = null;
                    showToast('Technician selection cleared');
                } else {
                    selectedTechnician = tech.id;
                    showToast(`Technician: ${tech.name}`);
                }
                renderTechnicians();
            };
            techGrid.appendChild(card);
        });
    };

    window.showToast = (msg) => {
        const t = document.createElement('div'); t.className = 'toast'; t.textContent = msg;
        document.getElementById('toastContainer').appendChild(t);
        setTimeout(() => t.remove(), 3000);
    };

    window.closeModal = () => {
        document.getElementById('successModal').style.display = 'none';
        document.getElementById('groupInfoModal').style.display = 'none';
        cart = []; updateCart(); selectedDate = null; selectedTime = null;
        renderCalendar(); generateTimes();
    };

    const bubbleContainer = document.getElementById('bubbleContainer');
    const createBubbles = () => {
        if (!bubbleContainer) return; // Safety check
        for (let i = 0; i < 3; i++) {
            const b = document.createElement('div'); b.className = 'bubble';
            const s = Math.random() * 80 + 20; b.style.width = s + 'px'; b.style.height = s + 'px';
            b.style.left = Math.random() * 100 + '%'; b.style.animationDuration = (Math.random() * 15 + 15) + 's';
            bubbleContainer.appendChild(b);
        }
    };

    renderCatalog('manicure');
    renderCalendar();
    generateTimes();
    renderTechnicians();
    createBubbles();

    window.createSparklePopper = () => {
        const colors = ['#d57e72', '#002366', '#D4AF37', '#ff1f5a', '#74b9ff', '#55efc4'];
        const container = document.getElementById('successModal');
        for (let i = 0; i < 60; i++) {
            const s = document.createElement('div');
            s.className = 'sparkle';
            const color = colors[Math.floor(Math.random() * colors.length)];
            s.style.backgroundColor = color;
            s.style.boxShadow = `0 0 10px ${color}`;
            
            // Random direction and distance
            const angle = Math.random() * Math.PI * 2;
            const dist = Math.random() * 300 + 100;
            const tx = Math.cos(angle) * dist + 'px';
            const ty = Math.sin(angle) * dist + 'px';
            
            s.style.setProperty('--tx', tx);
            s.style.setProperty('--ty', ty);
            
            // Start from center of modal
            s.style.left = '50%';
            s.style.top = '50%';
            
            container.appendChild(s);
            setTimeout(() => s.remove(), 1500);
        }
    };

    document.getElementById('submitBtn').onclick = (e) => {
        e.preventDefault();
        const mainName = document.getElementById('fullName').value;
        const mobile = document.getElementById('mobileNumber').value;
        const email = document.getElementById('emailAddress').value;
        const isGroup = document.getElementById('groupBookingToggle').checked;
        const groupSize = parseInt(document.getElementById('groupSize').value);
        
        if (!mainName) { showToast('Please enter your Full Name.'); return; }
        if (!mobile) { showToast('Please enter your Mobile Number.'); return; }
        if (!email) { showToast('Please enter your Email Address.'); return; }
        if (cart.length === 0) { showToast('Please select at least one service.'); return; }
        if (!selectedDate) { showToast('Please select an appointment Date.'); return; }
        if (!selectedTime) { showToast('Please select a Time Slot.'); return; }
        if (!selectedTechnician) { showToast('Please select an Elite Technician.'); return; }

        const groupInfoEl = document.getElementById('groupInfoModal');
        if (isGroup) {
            groupInfoEl.innerHTML = `<strong>Group Booking</strong><br>Total People: ${groupSize}`;
            groupInfoEl.style.display = 'inline-block';
        } else {
            groupInfoEl.style.display = 'none';
        }
        
        const tech = technicians.find(t => t.id === selectedTechnician);
        document.querySelector('.success-msg').innerHTML = `Dear <strong>${mainName}</strong>, your luxury session with <strong>${tech.name}</strong> has been requested for <strong>${selectedDate} ${monthLabel.textContent} at ${selectedTime}</strong>. Confirmation will be sent to <strong>${email}</strong>. Our elite concierges are now ensuring availability.`;
        
        const refId = 'NL-' + Math.floor(Math.random() * 9000 + 1000);
        document.getElementById('refTag').textContent = 'REF: ' + refId;

        // Trigger Luxury Transition
        const curtain = document.getElementById('transitionCurtain');
        curtain.classList.add('animate');
        
        setTimeout(() => {
            document.getElementById('successModal').style.display = 'flex';
            window.createSparklePopper();
        }, 700); // Show modal when curtain is at 100% scale

        setTimeout(() => {
            curtain.classList.remove('animate');
        }, 1400); // Clean up after animation finishes

        // Prepare data for single booking entry
        const bookingData = {
            mainContact: { name: mainName, mobile: mobile, email: email },
            isGroup: isGroup,
            groupSize: isGroup ? groupSize : 1,
            services: cart.map(s => s.name),
            totalPrice: document.getElementById('totalPrice').textContent,
            date: `${selectedDate} ${monthLabel.textContent}`,
            time: selectedTime,
            technician: tech.name,
            refId: refId
        };
        console.log('Booking Request Payload:', bookingData);
    };

    const customSelect = document.getElementById('customBranchSelect');
    if (customSelect) {
        const selectTrigger = customSelect.querySelector('.custom-select-trigger');
        const options = customSelect.querySelectorAll('.custom-option');
        const hiddenInput = document.getElementById('branchSelectValue');
        const viewBranchBtn = document.getElementById('viewBranchGalleryBtn');
        
        if (selectTrigger) {
            selectTrigger.addEventListener('click', () => {
                customSelect.classList.toggle('open');
            });
        }

        options.forEach(option => {
            option.addEventListener('click', () => {
                const val = option.getAttribute('data-value');
                const name = option.querySelector('.option-name').textContent;
                
                const selectedText = document.getElementById('selectedBranchText');
                if (selectedText) selectedText.textContent = name;
                if (hiddenInput) hiddenInput.value = val;
                customSelect.classList.remove('open');
                
                // Update technicians list based on branch
                renderTechnicians();
                
                // Show gallery button
                if (viewBranchBtn) viewBranchBtn.style.display = 'flex';
            });
        });

        // Close dropdown when clicking outside
        document.addEventListener('click', (e) => {
            if (!customSelect.contains(e.target)) {
                customSelect.classList.remove('open');
            }
        });
    }

    const branchData = {
        thaltej: {
            name: 'Thaltej Branch',
            images: ['thaltej_reception.png', 'thaltej_entrance.png', 'thaltej_interior_1.png', 'thaltej_interior_2.png', 'thaltej_interior_1.png', 'thaltej_interior_2.png']
        },
        one42: {
            name: 'One42 Branch',
            images: ['vastrapur_interior_1.png', 'vastrapur_interior_2.png', 'vastrapur_pedicure.png', 'vastrapur_stations.png', 'vastrapur_entrance.png', 'vastrapur_lounge.png']
        }
    };

    window.openBranchGallery = () => {
        const branchInput = document.getElementById('branchSelectValue');
        const branch = branchInput ? branchInput.value : '';
        if(!branch) return;

        const data = branchData[branch];
        document.getElementById('branchGalleryTitle').textContent = data.name;
        
        const grid = document.getElementById('branchGalleryGrid');
        grid.innerHTML = '';
        
        data.images.forEach(src => {
            const img = document.createElement('img');
            img.src = src;
            img.alt = data.name;
            img.onclick = () => openLightbox(src);
            grid.appendChild(img);
        });

        document.getElementById('branchGalleryModal').style.display = 'flex';
        document.body.style.overflow = 'hidden';
    };

    window.closeBranchGallery = () => {
        document.getElementById('branchGalleryModal').style.display = 'none';
        document.body.style.overflow = 'auto';
    };

    // Correctly assign click handler after function is defined
    const viewBranchBtn = document.getElementById('viewBranchGalleryBtn');
    if (viewBranchBtn) viewBranchBtn.onclick = openBranchGallery;



    // Initial Render
    renderCatalog('manicure');
    renderCalendar();
    generateTimes();
    renderTechnicians();
    createBubbles();
    updateCart();
});

// Lightbox Controls
function openLightbox(src) {
    const lb = document.getElementById('lightbox');
    const img = document.getElementById('lightbox-img');
    img.src = src;
    lb.style.display = 'flex';
    document.body.style.overflow = 'hidden';
}

function closeLightbox() {
    document.getElementById('lightbox').style.display = 'none';
    document.body.style.overflow = 'auto';
}
