<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login/Signup</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/5.3.0/css/bootstrap.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>
    <script src="https://www.gstatic.com/firebasejs/9.17.1/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/9.17.1/firebase-auth.js"></script>
    <script src="https://www.gstatic.com/firebasejs/9.x.x/firebase-firestore.js"></script>
    <style>
        body {
            background: linear-gradient(to right, #6a11cb, #2575fc);
            height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0;
            font-family: 'Arial', sans-serif;
            overflow: hidden;
        }
        .card {
            width: 400px;
            animation: slideIn 0.5s ease-out;
            border: none;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0px 10px 15px rgba(0, 0, 0, 0.2);
        }
        .card-header {
            background: linear-gradient(to right, #6a11cb, #2575fc);
            border-bottom: none;
            color: white;
            padding: 20px;
            text-align: center;
        }
        .card-body {
            padding: 30px;
            background-color: #ffffff;
        }
        .form-control {
            border-radius: 10px;
            border: 1px solid #ddd;
            padding: 10px;
        }
        .form-control:focus {
            box-shadow: none;
            border-color: #6a11cb;
        }
        .btn-primary {
            background: linear-gradient(to right, #6a11cb, #2575fc);
            border: none;
            border-radius: 20px;
            padding: 10px 20px;
            transition: transform 0.3s ease, background 0.3s ease;
        }
        .btn-primary:hover {
            background: linear-gradient(to right, #2575fc, #6a11cb);
            transform: scale(1.05);
        }
        .card-footer {
            background-color: #f8f9fa;
            border-top: none;
            padding: 15px;
        }
        a {
            color: #6a11cb;
            text-decoration: none;
        }
        a:hover {
            text-decoration: underline;
        }
        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(-50px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
    </style>
</head>
<body>
    <div class="card shadow-lg">
        <div class="card-header">
            <h4 id="form-title">Login</h4>
        </div>
        <div class="card-body">
            <form id="auth-form">
                <div class="mb-3">
                    <label for="email" class="form-label">Email</label>
                    <input type="email" class="form-control" id="email" required>
                </div>
                <div class="mb-3">
                    <label for="password" class="form-label">Password</label>
                    <input type="password" class="form-control" id="password" required>
                </div>
                <button type="submit" class="btn btn-primary w-100" id="submit-button">Login</button>
            </form>
        </div>
        <div class="card-footer text-center">
            <small id="toggle-text">Don't have an account? <a href="#" id="toggle-form">Sign up</a></small>
        </div>
    </div>

    <script>
        // Firebase Configuration
        const firebaseConfig = {
            apiKey: "AIzaSyB4BNpLQK0RHUmklOMh2HiNMzwFP5uDE5s",
  authDomain: "hosteller-efdb5.firebaseapp.com",
  databaseURL: "https://hosteller-efdb5-default-rtdb.firebaseio.com",
  projectId: "hosteller-efdb5",
  storageBucket: "hosteller-efdb5.firebasestorage.app",
  messagingSenderId: "250843951769",
  appId: "1:250843951769:web:01f0d52d2b1724816cbe08"
        };

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

        // DOM Elements
        const authForm = document.getElementById('auth-form');
        const formTitle = document.getElementById('form-title');
        const submitButton = document.getElementById('submit-button');
        const toggleForm = document.getElementById('toggle-form');
        const toggleText = document.getElementById('toggle-text');

        let isLogin = true;

        // Toggle between Login and Signup
        toggleForm.addEventListener('click', (e) => {
            e.preventDefault();
            isLogin = !isLogin;
            formTitle.textContent = isLogin ? 'Login' : 'Sign Up';
            submitButton.textContent = isLogin ? 'Login' : 'Sign Up';
            toggleText.innerHTML = isLogin 
                ? `Don't have an account? <a href="#" id="toggle-form">Sign up</a>`
                : `Already have an account? <a href="#" id="toggle-form">Login</a>`;
        });

        // Form Submission
        authForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            const email = document.getElementById('email').value;
            const password = document.getElementById('password').value;

            try {
                if (isLogin) {
                    // Login user
                    await firebase.signInWithEmailAndPassword(auth, email, password);
                    alert('Login successful!');
                } else {
                    // Sign up user
                    await firebase.createUserWithEmailAndPassword(auth, email, password);
                    alert('Signup successful!');
                }
            } catch (error) {
                alert(error.message);
            }
        });

        window.handleLogin = async (e) => {
            e.preventDefault();
            const email = document.getElementById('loginEmail').value;
            const password = document.getElementById('loginPassword').value;

            try {
                // Show loading state
                const submitButton = e.target.querySelector('button[type="submit"]');
                submitButton.disabled = true;
                submitButton.textContent = 'Logging in...';

                const userCredential = await signInWithEmailAndPassword(auth, email, password);
                
                // Check if user exists in Firestore
                const userDoc = await getDoc(doc(db, 'users', userCredential.user.uid));
                
                if (!userDoc.exists()) {
                    // If user doesn't exist in Firestore, create a basic profile
                    await setDoc(doc(db, 'users', userCredential.user.uid), {
                        email: email,
                        createdAt: serverTimestamp()
                    });
                }

                // Successful login
                window.location.href = '/profile.html';
            } catch (error) {
                submitButton.disabled = false;
                submitButton.textContent = 'Login';

                // Handle specific error cases
                switch (error.code) {
                    case 'auth/invalid-email':
                        showError('Invalid email address format');
                        break;
                    case 'auth/user-not-found':
                        showError('No account found with this email');
                        break;
                    case 'auth/wrong-password':
                        showError('Incorrect password');
                        break;
                    case 'auth/invalid-login-credentials':
                        showError('Invalid email or password');
                        break;
                    default:
                        showError('Login failed. Please try again.');
                        console.error('Login error:', error);
                }
            }
        };

        // Improved error display function
        function showError(message) {
            // Remove any existing error messages
            const existingError = document.querySelector('.error-message');
            if (existingError) {
                existingError.remove();
            }

            const errorDiv = document.createElement('div');
            errorDiv.className = 'error-message';
            errorDiv.textContent = message;
            
            // Insert error message below the form
            const activeForm = document.querySelector('.active.form-container form');
            activeForm.insertAdjacentElement('afterend', errorDiv);

            // Auto-hide after 5 seconds
            setTimeout(() => {
                errorDiv.style.opacity = '0';
                setTimeout(() => errorDiv.remove(), 300);
            }, 5000);
        }

        // Add these styles to improve error message display
        const styles = `
            .error-message {
                background-color: #fff3f3;
                color: #dc3545;
                padding: 12px;
                border-radius: 4px;
                margin-top: 1rem;
                text-align: center;
                border: 1px solid #ffcdd2;
                transition: opacity 0.3s ease;
            }

            .btn-submit:disabled {
                background-color: #cccccc;
                cursor: not-allowed;
            }
        `;

        // Add styles to document
        const styleSheet = document.createElement("style");
        styleSheet.textContent = styles;
        document.head.appendChild(styleSheet);
    </script>
</body>
</html>
