<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Signup / Login</title>
    <link rel="stylesheet" href="styles.css">
    <link rel="icon" href="assets/pyramidtiles.png">
</head>
<body>

    <div class="game-container">
        <h1>👋Welcome to,<br>Word Pyramid</h1>

        <div id="login-section" class="auth-section">
            <h2>Login</h2>
            <input type="email" id="login-email" placeholder="Email" required><br>
            <input type="password" id="login-password" placeholder="Password" required><br>
            <button id="login-btn">Login</button>
            <p id="login-message"></p>
            <p class="toggle-text" id="toggle-signup">Don't have an account? Create one</p>
        </div>

        <div id="signup-section" class="auth-section" style="display: none;">
            <h2>Sign Up</h2>
            <input type="email" id="signup-email" placeholder="Email" required><br>
            <input type="password" id="signup-password" placeholder="Password" required><br>
            <button id="signup-btn">Sign Up</button>
            <p id="signup-message"></p>
            <p class="toggle-text" id="toggle-login">Already have an account? Login</p>
        </div>

        <button id="logout-btn" style="display:none;">Logout</button>
    </div>

    <script type="module">
        import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.1/firebase-app.js";
        import { getAuth, signInWithEmailAndPassword, createUserWithEmailAndPassword, signOut, onAuthStateChanged } from "https://www.gstatic.com/firebasejs/9.6.1/firebase-auth.js";
        import { getDatabase, ref, set, get } from "https://www.gstatic.com/firebasejs/9.6.1/firebase-database.js";

        const firebaseConfig = {
            apiKey: "AIzaSyDW7UYkz_GI-DlmhFnZnnPQm3zVvkEyGnA",
            authDomain: "wordpyramid-5ccee.firebaseapp.com",
            projectId: "wordpyramid-5ccee",
            storageBucket: "wordpyramid-5ccee.appspot.com",
            messagingSenderId: "908437368708",
            appId: "1:908437368708:web:91b0dcc0cfbc70d26977d1"
        };

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

        // Handle user state changes
        onAuthStateChanged(auth, (user) => {
            if (user) {
                document.getElementById("login-section").style.display = "none";
                document.getElementById("signup-section").style.display = "none";
                document.getElementById("logout-btn").style.display = "block";
                window.location.href = "game.html";
            } else {
                document.getElementById("login-section").style.display = "block";
                document.getElementById("signup-section").style.display = "none";
                document.getElementById("logout-btn").style.display = "none";
            }
        });

        // Login functionality
        document.getElementById('login-btn').addEventListener('click', async () => {
            const email = document.getElementById('login-email').value;
            const password = document.getElementById('login-password').value;

            try {
                const userCredential = await signInWithEmailAndPassword(auth, email, password);
                const user = userCredential.user;

                // Fetch user data from Realtime Database
                const userRef = ref(db, 'users/' + user.uid);
                const snapshot = await get(userRef);

                if (snapshot.exists()) {
                    const userData = snapshot.val();
                    console.log(`Welcome back, ${userData.email}. Premium user: ${userData.isPremium}`);
                    window.location.href = "game.html"; // Redirect after login
                } else {
                    console.error("No user data found.");
                }
            } catch (error) {
                document.getElementById('login-message').textContent = error.message;
            }
        });

        // Signup functionality
        document.getElementById('signup-btn').addEventListener('click', async () => {
            const email = document.getElementById('signup-email').value;
            const password = document.getElementById('signup-password').value;

            try {
                const userCredential = await createUserWithEmailAndPassword(auth, email, password);
                const user = userCredential.user;

                // Save user data in Realtime Database
                await set(ref(db, 'users/' + user.uid), {
                    email: user.email,
                    isPremium: false
                });

                window.location.href = "game.html"; // Redirect after signup
            } catch (error) {
                document.getElementById('signup-message').textContent = error.message;
            }
        });

        // Logout functionality
        document.getElementById('logout-btn').addEventListener('click', async () => {
            try {
                await signOut(auth);
                console.log("User signed out.");
                document.getElementById("login-section").style.display = "block";
                document.getElementById("signup-section").style.display = "none";
                document.getElementById("logout-btn").style.display = "none";
                window.location.href = "index.html";
            } catch (error) {
                console.error("Error signing out: ", error.message);
            }
        });

        // Toggle between login and signup
        document.getElementById("toggle-signup").addEventListener("click", () => {
            document.getElementById("login-section").style.display = "none";
            document.getElementById("signup-section").style.display = "block";
        });

        document.getElementById("toggle-login").addEventListener("click", () => {
            document.getElementById("login-section").style.display = "block";
            document.getElementById("signup-section").style.display = "none";
        });
    </script>
</body>
</html>