document.addEventListener('DOMContentLoaded', () => {
    // Elements
    const profileBtn = document.getElementById('profileBtn');
    const profileDropdown = document.getElementById('profileDropdown');
    const logoutBtn = document.getElementById('logoutBtn');
    const profileName = document.getElementById('profileName');
    const profilePhoneDisplay = document.getElementById('profilePhoneDisplay');
    
    const editProfileBtn = document.getElementById('editProfileBtn');
    const editProfileModal = document.getElementById('editProfileModal');
    const closeEditModal = document.getElementById('closeEditModal');
    const saveProfileBtn = document.getElementById('saveProfileBtn');
    const phoneInput = document.getElementById('phoneInput');

    const rechargeBtn = document.querySelector('.action-btn'); // The "Recharge" button
    const rechargeModal = document.getElementById('rechargeModal');
    const closeRechargeModal = document.getElementById('closeRechargeModal');
    const confirmRechargeBtn = document.getElementById('confirmRechargeBtn');
    const methodItems = document.querySelectorAll('.method-item');

    let selectedMethod = null;

    // Load user data
    const username = localStorage.getItem('username');
    if (!username) {
        window.location.href = 'index.html';
        return;
    }

    profileName.textContent = username;

    async function loadUserProfile() {
        try {
            const response = await fetch(`http://localhost:5000/api/profile/${username}`);
            const data = await response.json();
            if (response.ok) {
                const phone = data.phone || '+880 1XXX XXXXXX';
                profilePhoneDisplay.textContent = phone;
                phoneInput.value = phone === '+880 1XXX XXXXXX' ? '' : phone;
            }
        } catch (err) {
            console.error('Error loading profile:', err);
        }
    }

    loadUserProfile();

    // --- Profile Dropdown ---
    profileBtn.addEventListener('click', (e) => {
        e.stopPropagation();
        profileDropdown.classList.toggle('hidden');
    });

    document.addEventListener('click', () => {
        profileDropdown.classList.add('hidden');
    });

    // --- Edit Profile Logic ---
    editProfileBtn.addEventListener('click', () => {
        editProfileModal.classList.remove('hidden');
        profileDropdown.classList.add('hidden');
    });

    closeEditModal.addEventListener('click', () => {
        editProfileModal.classList.add('hidden');
    });

    saveProfileBtn.addEventListener('click', async () => {
        const newPhone = phoneInput.value.trim();
        if (newPhone) {
            saveProfileBtn.disabled = true;
            saveProfileBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Saving...';
            
            try {
                const response = await fetch('http://localhost:5000/api/update-profile', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ username, phone: newPhone })
                });

                if (response.ok) {
                    profilePhoneDisplay.textContent = newPhone;
                    alert('Profile updated successfully!');
                    editProfileModal.classList.add('hidden');
                } else {
                    alert('Failed to update profile.');
                }
            } catch (err) {
                alert('Server error. Please try again.');
            } finally {
                saveProfileBtn.disabled = false;
                saveProfileBtn.innerHTML = 'Save Changes';
            }
        } else {
            alert('Please enter a valid mobile number.');
        }
    });

    // --- Recharge Logic ---
    rechargeBtn.addEventListener('click', () => {
        rechargeModal.classList.remove('hidden');
    });

    closeRechargeModal.addEventListener('click', () => {
        rechargeModal.classList.add('hidden');
    });

    methodItems.forEach(item => {
        item.addEventListener('click', () => {
            methodItems.forEach(i => i.classList.remove('selected'));
            item.classList.add('selected');
            selectedMethod = item.dataset.method;
        });
    });

    confirmRechargeBtn.addEventListener('click', () => {
        const amount = document.getElementById('rechargeAmount').value;
        if (!amount || amount <= 0) {
            alert('Please enter a valid amount.');
            return;
        }
        if (!selectedMethod) {
            alert('Please select a payment method (bKash/Nagad).');
            return;
        }

        confirmRechargeBtn.innerHTML = `<i class="fas fa-spinner fa-spin"></i> Connecting to ${selectedMethod}...`;
        confirmRechargeBtn.disabled = true;

        setTimeout(() => {
            alert(`Success! ৳ ${amount} has been recharged via ${selectedMethod.toUpperCase()}.\nTransaction ID: TRN${Math.random().toString(36).substr(2, 9).toUpperCase()}`);
            rechargeModal.classList.add('hidden');
            confirmRechargeBtn.innerHTML = 'Pay Now';
            confirmRechargeBtn.disabled = false;
            
            // Mock balance update
            const balanceEl = document.getElementById('userBalance');
            const currentBalance = parseFloat(balanceEl.textContent.replace('৳ ', ''));
            balanceEl.textContent = `৳ ${(currentBalance + parseFloat(amount)).toFixed(2)}`;
        }, 2000);
    });

    // Logout
    logoutBtn.addEventListener('click', () => {
        localStorage.removeItem('username');
        window.location.href = 'index.html';
    });

    // Close modals on outside click
    window.addEventListener('click', (e) => {
        if (e.target === editProfileModal) editProfileModal.classList.add('hidden');
        if (e.target === rechargeModal) rechargeModal.classList.add('hidden');
    });

    // Parallax effect
    document.addEventListener('mousemove', (e) => {
        const moveX = (e.clientX - window.innerWidth / 2) * 0.01;
        const moveY = (e.clientY - window.innerHeight / 2) * 0.01;
        const mountainBack = document.querySelector('.mountain-back');
        const mountainMid = document.querySelector('.mountain-mid');
        const mountainFront = document.querySelector('.mountain-front');
        if (mountainBack) mountainBack.style.transform = `translate(${moveX * 0.5}px, ${moveY * 0.2}px)`;
        if (mountainMid) mountainMid.style.transform = `translate(${moveX * 0.8}px, ${moveY * 0.4}px)`;
        if (mountainFront) mountainFront.style.transform = `translate(${moveX}px, ${moveY * 0.6}px)`;
    });

    // Buy Now handlers
    const buyButtons = document.querySelectorAll('.buy-btn');
    buyButtons.forEach(btn => {
        btn.addEventListener('click', () => {
            const offerTitle = btn.parentElement.querySelector('h3').textContent;
            alert(`Processing purchase for: ${offerTitle}\nPlease recharge your balance if needed.`);
        });
    });
});
