import { initializeApp } from "https://www.gstatic.com/firebasejs/12.11.0/firebase-app.js";
import { 
    getAuth, 
    RecaptchaVerifier, 
    signInWithPhoneNumber 
} from "https://www.gstatic.com/firebasejs/12.11.0/firebase-auth.js";

// ==========================
// Firebase Configuration
// ==========================
const firebaseConfig = {
    apiKey: "AIzaSyDzFDrIDPTxEdVbrkTMik8G8k5d3-3xNow",
    authDomain: "cusella-ebbad.firebaseapp.com",
    projectId: "cusella-ebbad",
    storageBucket: "cusella-ebbad.firebasestorage.app",
    messagingSenderId: "749098079888",
    appId: "1:749098079888:web:ce59d2b5c590ccb2ae2a15"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

let recaptchaVerifier = null;
let confirmationResult = null;
let selectedUserType = 'customer';
let lastFirebaseToken = null;

// ==========================
// Modal Management
// ==========================
window.openLoginModal = function() {
    const modal = document.getElementById("loginModal");
    resetModal();
    modal.classList.add('active');
};

window.closeLoginModal = function() {
    const modal = document.getElementById("loginModal");
    modal.classList.remove('active');
    setTimeout(() => {
        resetModal();
    }, 250);
};

function resetModal() {
    // Reset to step 1
    document.querySelectorAll('.auth-step').forEach(step => {
        step.classList.remove('active');
        step.style.display = 'none';
    });
    document.getElementById("step1").classList.add('active');
    document.getElementById("step1").style.display = 'block';
    
    // Reset form fields
    document.getElementById("phone").value = '';
    document.getElementById("name").value = '';
    document.getElementById("email").value = '';
    document.querySelectorAll('.otp-box').forEach(box => box.value = '');
    document.getElementById("legal_shop_name").value = '';
    document.getElementById("legal_shop_address").value = '';
    document.getElementById("shop_mobile_number").value = '';
    document.getElementById("gst_number").value = '';
    document.getElementById("franchiseFields").style.display = 'none';
    selectedUserType = 'customer';
    lastFirebaseToken = null;
}

// ==========================
// Step 1: User Type Selection
// ==========================
window.goToPhoneStep = function() {
    selectedUserType = document.querySelector('input[name="userType"]:checked').value;
    console.log("Selected user type:", selectedUserType);
    
    // Move to step 2
    document.getElementById("step1").style.display = 'none';
    document.getElementById("step2").style.display = 'block';
    
    // Initialize reCAPTCHA
    setTimeout(() => {
        initializeRecaptcha();
    }, 100);
};

window.goToUserTypeStep = function() {
    document.getElementById("step2").style.display = 'none';
    document.getElementById("step1").style.display = 'block';
};

function updateFranchiseFieldVisibility() {
    const franchiseSection = document.getElementById("franchiseFields");
    if (!franchiseSection) return;

    franchiseSection.style.display = selectedUserType === 'franchise' ? 'block' : 'none';
}

// ==========================
// Step 2: Phone Number & reCAPTCHA
// ==========================
function initializeRecaptcha() {
    const container = document.getElementById('recaptcha-container');
    
    if (recaptchaVerifier) {
        try {
            recaptchaVerifier.clear();
        } catch (e) {
            console.log("reCAPTCHA already cleared");
        }
        recaptchaVerifier = null;
    }

    const config = {
        size: 'normal',
        type: 'image',
        callback: (token) => {
            console.log("reCAPTCHA verified");
        },
        'expired-callback': () => {
            console.log("reCAPTCHA expired");
        },
        badge: 'bottomright'
    };

    recaptchaVerifier = new RecaptchaVerifier('recaptcha-container', config, auth);

    return recaptchaVerifier.render().catch(async error => {
        console.warn("reCAPTCHA render error:", error);

        // Retry with explicit v2 image mode if enterprise config fails
        if (error.code === 'auth/invalid-app-credential' ||
            error.message?.includes('reCAPTCHA Enterprise') ||
            error.message?.includes('Invalid app credential')) {
            try {
                if (recaptchaVerifier) {
                    recaptchaVerifier.clear();
                }
            } catch (clearError) {
                console.log("Failed to clear reCAPTCHA verifier:", clearError);
            }

            recaptchaVerifier = new RecaptchaVerifier('recaptcha-container', {
                size: 'normal',
                type: 'image',
                callback: (token) => {
                    console.log("reCAPTCHA verified on fallback");
                },
                'expired-callback': () => {
                    console.log("reCAPTCHA expired");
                },
                badge: 'bottomright'
            }, auth);

            return recaptchaVerifier.render();
        }

        showNotification("Error loading reCAPTCHA. Please refresh and try again.", 'error');
        throw error;
    });
}

window.sendOtp = async function(event) {
    const btn = event?.target;
    const phoneInput = document.getElementById("phone").value.trim().replace(/\D/g, '');
    
    // Validation
    if (!phoneInput) {
        showNotification("Please enter a phone number", 'error');
        return;
    }
    
    if (phoneInput.length !== 10) {
        showNotification("Please enter a valid 10-digit phone number", 'error');
        return;
    }
    
    const phoneNumber = "+91" + phoneInput;
    let originalText = "Send OTP";
    
    try {
        if (btn) {
            originalText = btn.textContent;
            btn.disabled = true;
            btn.textContent = "Sending...";
        }
        
        await initializeRecaptcha();
        confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, recaptchaVerifier);
        
        showNotification("OTP sent successfully to " + phoneNumber, 'success');
        
        document.getElementById("step2").style.display = 'none';
        document.getElementById("step3").style.display = 'block';
        
        document.querySelector('.otp-box').focus();
        setupOtpAutoFocus();
        
    } catch (error) {
        console.error("Error sending OTP:", error);
        
        if (error.code === 'auth/invalid-phone-number') {
            showNotification("Invalid phone number format", 'error');
        } else if (error.code === 'auth/too-many-requests') {
            showNotification("Too many attempts. Please try again later.", 'error');
        } else if (error.code === 'auth/invalid-app-credential') {
            showNotification("Firebase reCAPTCHA validation failed. Please reload the page and retry.", 'error');
        } else {
            showNotification("Error: " + error.message, 'error');
        }
    } finally {
        if (btn) {
            btn.disabled = false;
            btn.textContent = originalText;
        }
    }
};

// Auto-focus next OTP input
function setupOtpAutoFocus() {
    const otpBoxes = document.querySelectorAll('.otp-box');
    
    otpBoxes.forEach((box, index) => {
        box.addEventListener('input', (e) => {
            if (e.target.value.length === 1 && index < otpBoxes.length - 1) {
                otpBoxes[index + 1].focus();
            }
        });
        
        box.addEventListener('keydown', (e) => {
            if (e.key === 'Backspace' && e.target.value === '' && index > 0) {
                otpBoxes[index - 1].focus();
            }
        });
    });
}

// ==========================
// Step 3: Verify OTP
// ==========================
window.verifyOtp = async function(event) {
    const phoneInput = document.getElementById("phone").value.trim().replace(/\D/g, '');
    const phoneNumber = "+91" + phoneInput;
    
    // Test mode: if phone is 9999999999, use test token
    if (phoneInput === '9999999999') {
        localStorage.setItem('cusellaAuthToken', '156|JDlpEevKT32QQoM1zilWoU0oiKGdZzis0knEBgZXafa84008');
        showNotification("Test login successful!", 'success');
        setTimeout(() => {
            closeLoginModal();
            window.location.reload();
        }, 1500);
        return;
    }
    
    if (!confirmationResult) {
        showNotification("Please request OTP first", 'error');
        return;
    }
    
    const otp = Array.from(document.querySelectorAll('.otp-box'))
        .map(input => input.value)
        .join('');
    
    if (otp.length !== 6) {
        showNotification("Please enter the complete 6-digit OTP", 'error');
        return;
    }
    
    const btn = event?.target;
    let originalText = "Verify OTP";
    
    try {
        if (btn) {
            originalText = btn.textContent;
            btn.disabled = true;
            btn.textContent = "Verifying...";
        }
        
        const result = await confirmationResult.confirm(otp);
        const user = result.user;
        const token = await user.getIdToken();
        lastFirebaseToken = token;
        
        const response = await fetch('/api/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-Token': getCsrfToken()
            },
            body: JSON.stringify({
                phone: user.phoneNumber,
                user_type: selectedUserType,
                firebase_token: token
            })
        });
        
        const data = await response.json();
        
        if (!response.ok) {
            throw new Error(data.message || 'Login failed');
        }
        
        if (data.token || data.access_token) {
            localStorage.setItem('cusellaAuthToken', data.token || data.access_token);
        }
        
        const needsProfile = data.hasOwnProperty('is_new_user')
            ? data.is_new_user === false
            : !user.displayName;
        
        if (needsProfile) {
            document.getElementById("step3").style.display = 'none';
            document.getElementById("step4").style.display = 'block';
            document.getElementById("profile_phone").value = user.phoneNumber;
            updateFranchiseFieldVisibility();
        } else {
            showNotification("Login successful!", 'success');
            setTimeout(() => {
                closeLoginModal();
                window.location.reload();
            }, 1500);
        }
        
    } catch (error) {
        console.error("❌ OTP Verification Error:", error);
        showNotification("Invalid or expired OTP. Please try again.", 'error');
    } finally {
        if (btn) {
            btn.disabled = false;
            btn.textContent = originalText;
        }
    }
};

// ==========================
// Step 4: Complete Profile
// ==========================
window.updateProfile = async function(event) {
    const name = document.getElementById("name").value.trim();
    const email = document.getElementById("email").value.trim();
    const phone = document.getElementById("profile_phone").value;
    const legalShopName = document.getElementById("legal_shop_name").value.trim();
    const legalShopAddress = document.getElementById("legal_shop_address").value.trim();
    const shopMobileNumber = document.getElementById("shop_mobile_number").value.trim();
    const gstNumber = document.getElementById("gst_number").value.trim();
    
    if (!name) {
        showNotification("Please enter your name", 'error');
        return;
    }
    
    if (!email || !isValidEmail(email)) {
        showNotification("Please enter a valid email address", 'error');
        return;
    }
    
    if (selectedUserType === 'franchise') {
        if (!legalShopName || !legalShopAddress || !shopMobileNumber || !gstNumber) {
            showNotification("Please complete all franchise details", 'error');
            return;
        }
    }
    
    const btn = event?.target;
    let originalText = "Save & Continue";
    
    try {
        if (btn) {
            originalText = btn.textContent;
            btn.disabled = true;
            btn.textContent = "Saving...";
        }
        
        const userData = {
            phone: phone,
            name: name,
            email: email,
            user_type: selectedUserType,
            firebase_token: lastFirebaseToken
        };
        
        if (selectedUserType === 'franchise') {
            userData.legal_shop_name = legalShopName;
            userData.legal_shop_address = legalShopAddress;
            userData.shop_mobile_number = shopMobileNumber;
            userData.gst_number = gstNumber;
        }
        
        const response = await fetch('/api/register', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-Token': getCsrfToken()
            },
            body: JSON.stringify(userData)
        });
        
        if (!response.ok) {
            const error = await response.json();
            throw new Error(error.message || 'Registration failed');
        }
        
        const data = await response.json();
        
        if (data.token || data.access_token) {
            localStorage.setItem('cusellaAuthToken', data.token || data.access_token);
        }
        
        showNotification("Registration successful!", 'success');
        setTimeout(() => {
            closeLoginModal();
            window.location.reload();
        }, 1500);
        
    } catch (error) {
        console.error("Registration Error:", error);
        showNotification("Error: " + error.message, 'error');
    } finally {
        if (btn) {
            btn.disabled = false;
            btn.textContent = originalText;
        }
    }
};

// ==========================
// Helper Functions
// ==========================
function loginUser(phone, name, userType, token) {
    // Send login data to your backend
    fetch('/api/login', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-Token': getCsrfToken()
        },
        body: JSON.stringify({
            phone: phone,
            name: name,
            user_type: userType,
            firebase_token: token
        })
    })
    .then(response => response.json())
    .then(data => {
        showNotification("Login successful!", 'success');
        setTimeout(() => {
            closeLoginModal();
            window.location.reload();
        }, 1500);
    })
    .catch(error => {
        console.error("Login error:", error);
        showNotification("Error: " + error.message, 'error');
    });
}

function isValidEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
}

function getCsrfToken() {
    const name = 'XSRF-TOKEN=';
    const decodedCookie = decodeURIComponent(document.cookie);
    const cookieArray = decodedCookie.split(';');
    
    for (let cookie of cookieArray) {
        cookie = cookie.trim();
        if (cookie.indexOf(name) === 0) {
            return cookie.substring(name.length, cookie.length);
        }
    }
    
    // Fallback: try to get from meta tag
    const token = document.querySelector('meta[name="csrf-token"]');
    return token ? token.getAttribute('content') : '';
}

function showNotification(message, type = 'info') {
    // Using SweetAlert2 if available, otherwise fallback to alert
    if (typeof Swal !== 'undefined') {
        Swal.fire({
            icon: type === 'error' ? 'error' : type === 'success' ? 'success' : 'info',
            title: type === 'error' ? 'Error' : type === 'success' ? 'Success' : 'Info',
            text: message,
            toast: true,
            position: 'top-end',
            showConfirmButton: false,
            timer: 3000
        });
    } else {
        alert(message);
    }
}

// Make logout function available globally
window.logout = function() {
    auth.signOut().then(() => {
        console.log("User logged out");
        fetch('/api/logout', {
            method: 'POST',
            headers: {
                'X-CSRF-Token': getCsrfToken()
            }
        }).then(() => {
            showNotification("Logged out successfully", 'success');
            setTimeout(() => {
                window.location.reload();
            }, 1500);
        });
    }).catch(error => {
        console.error("Logout error:", error);
        showNotification("Error: " + error.message, 'error');
    });
};
