<!-- Auth Modal Component -->
<div id="authModal" class="fixed inset-0 bg-black/60 backdrop-blur-sm z-50 hidden items-center justify-center p-4">
    <div class="bg-white rounded-2xl max-w-md w-full shadow-2xl relative overflow-hidden animate-fadeIn">

        <!-- Close Button -->
        <button onclick="closeAuthModal()"
            class="absolute top-4 right-4 text-slate-400 hover:text-slate-600 transition-colors z-10">
            <i class="fa-solid fa-xmark text-2xl"></i>
        </button>

        <!-- Tabs -->
        <div class="flex border-b border-slate-200">
            <button onclick="switchAuthTab('login')" id="loginTab"
                class="flex-1 py-4 font-bold text-slate-900 border-b-2 border-blue-600 transition-all">
                Login
            </button>
            <button onclick="switchAuthTab('signup')" id="signupTab"
                class="flex-1 py-4 font-bold text-slate-400 border-b-2 border-transparent hover:text-slate-600 transition-all">
                Sign Up
            </button>
        </div>

        <!-- Login Form -->
        <div id="loginForm" class="p-8">
            <div class="text-center mb-6">
                <div class="inline-flex items-center justify-center w-16 h-16 bg-blue-50 rounded-full mb-3">
                    <i class="fa-solid fa-user text-2xl text-blue-600"></i>
                </div>
                <h2 class="text-2xl font-bold text-slate-900">Welcome Back</h2>
                <p class="text-slate-500 text-sm mt-1">Sign in to continue your journey</p>
            </div>

            <div id="loginError"
                class="hidden bg-red-50 border-l-4 border-red-500 text-red-700 p-3 mb-4 rounded text-sm"></div>

            <form id="loginFormElement" class="space-y-4">
                <div>
                    <label class="block text-sm font-semibold text-slate-700 mb-1">Email</label>
                    <input type="email" name="email" required
                        class="w-full px-4 py-2.5 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none transition-all"
                        placeholder="your@email.com">
                </div>

                <div>
                    <label class="block text-sm font-semibold text-slate-700 mb-1">Password</label>
                    <input type="password" name="password" required
                        class="w-full px-4 py-2.5 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none transition-all"
                        placeholder="••••••••">
                </div>

                <div class="flex justify-center my-2">
                    <div class="g-recaptcha"
                        data-sitekey="<?php echo defined('RECAPTCHA_SITE_KEY') ? RECAPTCHA_SITE_KEY : ''; ?>"></div>
                </div>

                <button type="submit"
                    class="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 rounded-lg transition-all transform hover:-translate-y-0.5">
                    Sign In
                </button>

                <?php if (defined('GOOGLE_OAUTH_ENABLED') && GOOGLE_OAUTH_ENABLED): ?>
                    <div class="relative my-6">
                        <div class="absolute inset-0 flex items-center">
                            <div class="w-full border-t border-slate-200"></div>
                        </div>
                        <div class="relative flex justify-center text-xs"><span
                                class="bg-white px-3 text-slate-400 uppercase tracking-wider">or</span></div>
                    </div>
                    <a href="/auth/google-login.php"
                        class="w-full flex items-center justify-center gap-3 py-2.5 px-4 border border-slate-300 rounded-lg hover:bg-slate-50 transition-all text-slate-700 font-medium text-sm">
                        <svg width="20" height="20" viewBox="0 0 48 48">
                            <path fill="#EA4335"
                                d="M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z">
                            </path>
                            <path fill="#4285F4"
                                d="M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z">
                            </path>
                            <path fill="#FBBC05"
                                d="M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z">
                            </path>
                            <path fill="#34A853"
                                d="M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.15 1.45-4.92 2.3-8.16 2.3-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z">
                            </path>
                        </svg>
                        Sign in with Google
                    </a>
                <?php endif; ?>
            </form>

            <div class="mt-6 text-center border-t border-slate-100 pt-6">
                <p class="text-sm text-slate-500">
                    Don't have an account?
                    <button onclick="switchAuthTab('signup')"
                        class="text-blue-600 font-semibold hover:text-blue-800">Sign up</button>
                </p>
            </div>
        </div>

        <!-- Signup Form -->
        <div id="signupForm" class="p-8 hidden">
            <div class="text-center mb-6">
                <div class="inline-flex items-center justify-center w-16 h-16 bg-green-50 rounded-full mb-3">
                    <i class="fa-solid fa-user-plus text-2xl text-green-600"></i>
                </div>
                <h2 class="text-2xl font-bold text-slate-900">Create Account</h2>
                <p class="text-slate-500 text-sm mt-1">Join the sanitation movement</p>
            </div>

            <div id="signupError"
                class="hidden bg-red-50 border-l-4 border-red-500 text-red-700 p-3 mb-4 rounded text-sm"></div>
            <div id="signupSuccess"
                class="hidden bg-green-50 border-l-4 border-green-500 text-green-700 p-3 mb-4 rounded text-sm"></div>

            <form id="signupFormElement" class="space-y-4">
                <div>
                    <label class="block text-sm font-semibold text-slate-700 mb-1">Organization / Name</label>
                    <input type="text" name="org_name" required
                        class="w-full px-4 py-2.5 border border-slate-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500 outline-none transition-all"
                        placeholder="Your name or organization">
                </div>

                <div>
                    <label class="block text-sm font-semibold text-slate-700 mb-1">Email</label>
                    <input type="email" name="email" required
                        class="w-full px-4 py-2.5 border border-slate-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500 outline-none transition-all"
                        placeholder="your@email.com">
                </div>

                <div>
                    <label class="block text-sm font-semibold text-slate-700 mb-1">Password</label>
                    <input type="password" name="password" required minlength="6"
                        class="w-full px-4 py-2.5 border border-slate-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500 outline-none transition-all"
                        placeholder="At least 6 characters">
                </div>

                <div>
                    <label class="block text-sm font-semibold text-slate-700 mb-1">Confirm Password</label>
                    <input type="password" name="confirm_password" required minlength="6"
                        class="w-full px-4 py-2.5 border border-slate-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500 outline-none transition-all"
                        placeholder="Re-enter password">
                </div>

                <div class="flex justify-center my-2">
                    <div class="g-recaptcha"
                        data-sitekey="<?php echo defined('RECAPTCHA_SITE_KEY') ? RECAPTCHA_SITE_KEY : ''; ?>"></div>
                </div>

                <button type="submit"
                    class="w-full bg-green-600 hover:bg-green-700 text-white font-bold py-3 rounded-lg transition-all transform hover:-translate-y-0.5">
                    Create Account
                </button>

                <?php if (defined('GOOGLE_OAUTH_ENABLED') && GOOGLE_OAUTH_ENABLED): ?>
                    <div class="relative my-6">
                        <div class="absolute inset-0 flex items-center">
                            <div class="w-full border-t border-slate-200"></div>
                        </div>
                        <div class="relative flex justify-center text-xs"><span
                                class="bg-white px-3 text-slate-400 uppercase tracking-wider">or</span></div>
                    </div>
                    <a href="/auth/google-login.php"
                        class="w-full flex items-center justify-center gap-3 py-2.5 px-4 border border-slate-300 rounded-lg hover:bg-slate-50 transition-all text-slate-700 font-medium text-sm">
                        <svg width="20" height="20" viewBox="0 0 48 48">
                            <path fill="#EA4335"
                                d="M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z">
                            </path>
                            <path fill="#4285F4"
                                d="M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z">
                            </path>
                            <path fill="#FBBC05"
                                d="M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z">
                            </path>
                            <path fill="#34A853"
                                d="M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.15 1.45-4.92 2.3-8.16 2.3-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z">
                            </path>
                        </svg>
                        Sign up with Google
                    </a>
                <?php endif; ?>
            </form>

            <div class="mt-6 text-center border-t border-slate-100 pt-6">
                <p class="text-sm text-slate-500">
                    Already have an account?
                    <button onclick="switchAuthTab('login')"
                        class="text-blue-600 font-semibold hover:text-blue-800">Sign in</button>
                </p>
            </div>
        </div>

    </div>
</div>

<style>
    @keyframes fadeIn {
        from {
            opacity: 0;
            transform: scale(0.95);
        }

        to {
            opacity: 1;
            transform: scale(1);
        }
    }

    .animate-fadeIn {
        animation: fadeIn 0.2s ease-out;
    }
</style>

<!-- Load reCAPTCHA API for the auth modal -->
<script src="https://www.google.com/recaptcha/api.js" async defer></script>

<script>
    function openAuthModal(tab = 'login') {
        document.getElementById('authModal').classList.remove('hidden');
        document.getElementById('authModal').classList.add('flex');
        switchAuthTab(tab);
        document.body.style.overflow = 'hidden';
    }

    function closeAuthModal() {
        document.getElementById('authModal').classList.add('hidden');
        document.getElementById('authModal').classList.remove('flex');
        document.body.style.overflow = '';
        // Clear forms
        document.getElementById('loginFormElement').reset();
        document.getElementById('signupFormElement').reset();
        // Clear messages
        document.getElementById('loginError').classList.add('hidden');
        document.getElementById('signupError').classList.add('hidden');
        document.getElementById('signupSuccess').classList.add('hidden');

        // Reset reCAPTCHA widgets if they exist
        if (typeof grecaptcha !== 'undefined' && grecaptcha.reset) {
            try {
                // Determine how many widgets are rendered
                // Safe approach: just reset. If multiple, reset might only do the first or last depending on implementation,
                // but usually resetting without ID resets the first one. To be safe, we can try to reset potential IDs if we knew them.
                // Since we don't have IDs stored, we rely on the API.
                grecaptcha.reset();
            } catch (e) {
                // Ignore error if widget not ready
            }
        }
    }

    function switchAuthTab(tab) {
        const loginTab = document.getElementById('loginTab');
        const signupTab = document.getElementById('signupTab');
        const loginForm = document.getElementById('loginForm');
        const signupForm = document.getElementById('signupForm');

        if (tab === 'login') {
            loginTab.classList.remove('text-slate-400', 'border-transparent');
            loginTab.classList.add('text-slate-900', 'border-blue-600');
            signupTab.classList.remove('text-slate-900', 'border-blue-600');
            signupTab.classList.add('text-slate-400', 'border-transparent');
            loginForm.classList.remove('hidden');
            signupForm.classList.add('hidden');
        } else {
            signupTab.classList.remove('text-slate-400', 'border-transparent');
            signupTab.classList.add('text-slate-900', 'border-blue-600');
            loginTab.classList.remove('text-slate-900', 'border-blue-600');
            loginTab.classList.add('text-slate-400', 'border-transparent');
            signupForm.classList.remove('hidden');
            loginForm.classList.add('hidden');
        }
    }

    // Login Form Submission
    document.getElementById('loginFormElement').addEventListener('submit', async (e) => {
        e.preventDefault();
        const form = e.target;
        const formData = new FormData(form);
        const errorDiv = document.getElementById('loginError');

        try {
            const response = await fetch('/login.php', {
                method: 'POST',
                body: formData
            });

            const result = await response.text();

            // Check if redirect happened (successful login)
            if (result.includes('window.location') || response.redirected || result.trim() === '') {
                window.location.reload();
            } else {
                // Show error
                const parser = new DOMParser();
                const doc = parser.parseFromString(result, 'text/html');
                const errorHtml = doc.querySelector('.bg-red-50, .text-red')?.innerHTML || 'Invalid credentials';
                errorDiv.innerHTML = errorHtml;
                errorDiv.classList.remove('hidden');
            }
        } catch (error) {
            errorDiv.textContent = 'Connection error. Please try again.';
            errorDiv.classList.remove('hidden');
        }
    });

    // Signup Form Submission
    document.getElementById('signupFormElement').addEventListener('submit', async (e) => {
        e.preventDefault();
        const form = e.target;
        const formData = new FormData(form);
        const errorDiv = document.getElementById('signupError');
        const successDiv = document.getElementById('signupSuccess');

        // Client-side validation
        const password = formData.get('password');
        const confirmPassword = formData.get('confirm_password');

        if (password !== confirmPassword) {
            errorDiv.textContent = 'Passwords do not match.';
            errorDiv.classList.remove('hidden');
            successDiv.classList.add('hidden');
            return;
        }

        try {
            const response = await fetch('/signup.php', {
                method: 'POST',
                body: formData
            });

            const result = await response.text();

            if (result.trim() === 'success' || result.trim() === 'verify_email') {
                successDiv.textContent = 'Account created! Please check your email to verify your account.';
                successDiv.classList.remove('hidden');
                errorDiv.classList.add('hidden');
                form.reset();

                // Switch to login after 3 seconds
                setTimeout(() => {
                    switchAuthTab('login');
                    successDiv.classList.add('hidden');
                }, 3000);
                return;
            }

            const parser = new DOMParser();
            const doc = parser.parseFromString(result, 'text/html');

            // Check for success message
            const successMsg = doc.querySelector('.bg-green-50, .text-green')?.textContent?.trim();
            const errorMsg = doc.querySelector('.bg-red-50, .text-red')?.textContent?.trim();

            if (successMsg) {
                successDiv.textContent = 'Account created! Please check your email to verify your account.';
                successDiv.classList.remove('hidden');
                errorDiv.classList.add('hidden');
                form.reset();

                // Switch to login after 3 seconds
                setTimeout(() => {
                    switchAuthTab('login');
                    successDiv.classList.add('hidden');
                }, 3000);
            } else if (errorMsg) {
                errorDiv.textContent = errorMsg;
                errorDiv.classList.remove('hidden');
                successDiv.classList.add('hidden');
            }
        } catch (error) {
            errorDiv.textContent = 'Connection error. Please try again.';
            errorDiv.classList.remove('hidden');
            successDiv.classList.add('hidden');
        }
    });

    // Close modal on outside click
    document.getElementById('authModal').addEventListener('click', (e) => {
        if (e.target.id === 'authModal') {
            closeAuthModal();
        }
    });

    // Close modal on Escape key
    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape' && !document.getElementById('authModal').classList.contains('hidden')) {
            closeAuthModal();
        }
    });
</script>