<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="jakarta.tags.core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login & Register</title>
    <link href="https://fonts.googleapis.com/css?family=Nunito:400,600,700" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        /* General Styles */
        * {
            box-sizing: border-box;
        }

        body {
            font-family: "Nunito", sans-serif;
            color: rgba(0, 0, 0, 0.7);
            margin: 0;
            padding: 0;
        }

        .container {
            height: 200vh;
            background-image: url(https://images.unsplash.com/photo-1538137524007-21e48fa42f3f?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=ac9fa0975bd2ebad7afd906c5a3a15ab&auto=format&fit=crop&w=1834&q=80);
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
        }

        .modal {
            position: fixed;
            left: 0;
            bottom: 0;
            width: 100%;
            height: 60px;
            background: rgba(51, 51, 51, 0.5); /* #333 */
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            transition: 0.4s;
            z-index: 1000; /* Ensure modal is on top */
        }

        .modal-container {
            display: flex;
            max-width: 720px;
            width: 100%;
            border-radius: 10px;
            overflow: hidden;
            position: absolute;
            opacity: 0;
            pointer-events: none;
            transition-duration: 0.3s;
            background: #fff;
            transform: translateY(100px) scale(0.4);
        }

        .modal-title {
            font-size: 26px;
            margin: 0;
            font-weight: 400;
            color: #55311c;
        }

        .modal-desc {
            margin: 6px 0 30px 0;
            font-size: 14px;
        }

        .modal-left {
            padding: 60px 30px 20px;
            background: #fff;
            flex: 1.5;
            transition-duration: 0.5s;
            transform: translateY(80px);
            opacity: 0;
            position: relative;
        }

        .modal-button {
            color: #79685d;
            font-family: "Nunito", sans-serif;
            font-size: 18px;
            cursor: pointer;
            border: 0;
            outline: 0;
            padding: 10px 40px;
            border-radius: 30px;
            background: rgb(255, 255, 255);
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.16);
            transition: 0.3s;
        }
        .modal-button:hover {
            border-color: rgba(255, 255, 255, 0.2);
            background: rgba(255, 255, 255, 0.8);
        }

        .modal-right {
            flex: 2;
            font-size: 0;
            transition: 0.3s;
            overflow: hidden;
        }
        .modal-right img {
            width: 100%;
            height: 100%;
            transform: scale(2);
            object-fit: cover;
            transition-duration: 1.2s;
        }

        .modal.is-open {
            height: 100%;
            background: rgba(51, 51, 51, 0.85);
        }
        .modal.is-open .modal-button {
            opacity: 0;
        }
        .modal.is-open .modal-container {
            opacity: 1;
            transition-duration: 0.6s;
            pointer-events: auto;
            transform: translateY(0) scale(1);
        }
        .modal.is-open .modal-right img {
            transform: scale(1);
        }
        .modal.is-open .modal-left {
            transform: translateY(0);
            opacity: 1;
            transition-delay: 0.1s;
        }

        .modal-buttons {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 20px;
            margin-bottom: 20px;
        }
        .modal-buttons a {
            color: rgba(51, 51, 51, 0.6);
            font-size: 14px;
            text-decoration: none;
        }
        .modal-buttons a:hover {
            text-decoration: underline;
        }


        .sign-up {
            margin: 30px 0 0;
            font-size: 14px;
            text-align: center;
        }
        .sign-up a {
            color: #8c7569;
            text-decoration: none;
        }
        .sign-up a:hover {
            text-decoration: underline;
        }

        .input-button {
            padding: 8px 12px;
            outline: none;
            border: 0;
            color: #fff;
            border-radius: 4px;
            background: #8c7569;
            font-family: "Nunito", sans-serif;
            transition: 0.3s;
            cursor: pointer;
            min-width: 120px;
        }
        .input-button:hover {
            background: #55311c;
        }

        .input-label {
            font-size: 11px;
            text-transform: uppercase;
            font-family: "Nunito", sans-serif;
            font-weight: 600;
            letter-spacing: 0.7px;
            color: #8c7569;
            transition: 0.3s;
        }

        .input-block {
            display: flex;
            flex-direction: column;
            padding: 10px 10px 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-bottom: 20px;
            transition: 0.3s;
        }
        .input-block input,
        .input-block select {
            outline: 0;
            border: 0;
            padding: 4px 0 0;
            font-size: 14px;
            font-family: "Nunito", sans-serif;
            background: transparent;
        }
        .input-block input::placeholder {
            color: #ccc;
            opacity: 1;
        }
        .input-block:focus-within {
            border-color: #8c7569;
        }
        .input-block:focus-within .input-label {
            color: rgba(140, 117, 105, 0.8);
        }

        .icon-button {
            outline: 0;
            position: absolute;
            right: 10px;
            top: 12px;
            width: 32px;
            height: 32px;
            border: 0;
            background: 0;
            padding: 0;
            cursor: pointer;
            z-index: 10;
        }

        .scroll-down {
            position: fixed;
            top: 50%;
            left: 50%;
            display: flex;
            flex-direction: column;
            align-items: center;
            text-align: center;
            color: #79685d;
            font-size: 32px;
            font-weight: 800;
            transform: translate(-50%, -50%);
            z-index: 500;
        }
        .scroll-down svg {
            margin-top: 16px;
            width: 52px;
            fill: currentColor;
        }

        /* OTP Section Styling */
        .otp-section {
            display: none;
            text-align: center;
            padding-top: 25px;
            border-top: 1px solid #eee;
            margin-top: 25px;
        }

        .otp-input {
            width: 100%;
            font-size: 1.3em;
            letter-spacing: 5px;
            text-align: center;
        }

        .resend-otp {
            margin-top: 20px;
            font-size: 0.9em;
        }

        .resend-otp a {
            color: #8c7569;
            text-decoration: none;
            transition: color 0.3s ease;
        }

        .resend-otp a:hover {
            text-decoration: underline;
            color: #55311c;
        }

        /* Error/Success messages */
        .error-message, .success-message {
            color: #dc3545;
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
            padding: 10px;
            border-radius: 6px;
            text-align: center;
            margin-bottom: 20px;
            font-weight: 500;
            animation: fadeIn 0.5s ease-out;
            font-size: 0.9em;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .success-message {
            color: #155724;
            background-color: #d4edda;
            border-color: #c3e6cb;
        }

        /* Utility for hiding elements */
        .hidden {
            display: none;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        @media(max-width: 750px) {
            .modal-container {
                width: 90%;
            }
            .modal-right {
                display: none;
            }
        }

        /* --- SUPER LOGIN PAGE STYLES --- */
        #loginForm .modal-title {
            font-size: 32px; /* Larger title */
            color: #333; /* Darker color */
            margin-bottom: 10px;
            font-weight: 700; /* Bolder */
        }
        #loginForm .modal-desc {
            font-size: 16px;
            color: #666;
            margin-bottom: 40px;
        }
        #loginForm .input-block {
            border: 1px solid #c2c2c2; /* Slightly darker border */
            box-shadow: 0 2px 5px rgba(0,0,0,0.05); /* Subtle shadow */
        }
        #loginForm .input-block:focus-within {
            border-color: #5d4037; /* Darker focus border */
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        #loginForm .input-label {
            color: #5d4037; /* Darker label color */
        }
        #loginForm .input-button {
            background: #5d4037; /* A richer, darker brown for login button */
            padding: 12px 25px; /* More padding */
            font-size: 16px; /* Larger font */
            border-radius: 6px; /* Slightly less rounded */
            box-shadow: 0 5px 15px rgba(93, 64, 55, 0.3); /* Button shadow */
        }
        #loginForm .input-button:hover {
            background: #3e2e26; /* Darker on hover */
            box-shadow: 0 7px 20px rgba(93, 64, 55, 0.4);
        }
        #loginForm .modal-buttons a {
            color: #5d4037; /* Match forgot password link to new theme */
            font-weight: 600;
        }
        #loginForm .sign-up a {
            color: #5d4037; /* Match sign up link to new theme */
            font-weight: 600;
        }
        #loginForm .sign-up {
             margin-top: 40px; /* More space below login button */
        }
    </style>
</head>
<body>

    <div class="scroll-down">SCROLL DOWN
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
            <path d="M16 3C8.832031 3 3 8.832031 3 16s5.832031 13 13 13 13-5.832031 13-13S23.167969 3 16 3zm0 2c6.085938 0 11 4.914063 11 11 0 6.085938-4.914062 11-11 11-6.085937 0-11-4.914062-11-11C5 9.914063 9.914063 5 16 5zm-1 4v10.28125l-4-4-1.40625 1.4375L16 23.125l6.40625-6.40625L21 15.28125l-4 4V9z"/>
        </svg>
    </div>

    <div class="container"></div>

    <div class="modal">
        <div class="modal-container">
            <div class="modal-left" id="modalLeftContent">
                <%-- SUPER LOGIN Form --%>
                <div id="loginForm">
                    <h1 class="modal-title">Welcome Back!</h1>
                    <p class="modal-desc">Sign in to your account to continue.</p>
                    <c:if test="${not empty error}">
                        <div class="error-message">
                            <i class="fas fa-exclamation-circle"></i> <c:out value="${error}"/>
                        </div>
                    </c:if>
                    <form action="/login" method="post">
                        <div class="input-block">
                            <label for="username" class="input-label"><i class="fas fa-envelope"></i> Email</label>
                            <input type="email" name="emailId" id="username" placeholder="Email" autocomplete="username" required>
                        </div>
                        <div class="input-block">
                            <label for="password" class="input-label"><i class="fas fa-lock"></i> Password</label>
                            <input type="password" name="password" id="password" placeholder="Password" autocomplete="current-password" required>
                        </div>
                        <div class="modal-buttons">
                            <a href="#" class="">Forgot your password?</a>
                            <button class="input-button" type="submit">Login</button>
                        </div>
                        <p class="sign-up">Don't have an account? <a href="#" id="showRegister">Sign up now</a></p>
                    </form>
                </div>

                <%-- Registration Form Container (initially hidden, maintains previous style) --%>
                <div id="registrationFormContainer" class="hidden">
                    <h1 class="modal-title">User Registration</h1>
                    <p class="modal-desc">Create your account to get started!</p>
                    <c:if test="${not empty successMessage}">
                        <div class="success-message">
                            <i class="fas fa-check-circle"></i> <c:out value="${successMessage}"/>
                        </div>
                    </c:if>
                    <%-- Registration Form (Part 1 - for user details and sending OTP) --%>
                    <form action="sendOtpForRegistration" method="post" id="registrationForm">
                        <div class="input-block">
                            <label for="name" class="input-label">Name</label>
                            <input type="text" id="name" name="name" placeholder="Your full name" required>
                        </div>
                        <div class="input-block">
                            <label for="mobileNumber" class="input-label">Mobile Number</label>
                            <input type="tel" id="mobileNumber" name="mobileNumber" placeholder="Ex: 9876543210" required>
                        </div>
                        <div class="input-block">
                            <label for="emailId" class="input-label">Email Id</label>
                            <input type="email" id="emailId" name="emailId" placeholder="your.email@example.com" required>
                        </div>
                        <div class="input-block">
                            <label for="passwordReg" class="input-label">Password</label>
                            <input type="password" id="passwordReg" name="password" placeholder="Create a strong password" required>
                        </div>
                        <div class="input-block">
                            <label for="confirmPassword" class="input-label">Confirm Password</label>
                            <input type="password" id="confirmPassword" name="confirmPassword" placeholder="Re-enter your password" required>
                        </div>
                        <div class="input-block">
                            <label for="role" class="input-label">Role</label>
                            <select id="role" name="role" required>
                                <option value="USER">User</option>
                                <option value="ADMIN">Admin</option>
                            </select>
                        </div>
                        <div class="modal-buttons" style="justify-content: center;">
                            <button class="input-button" type="submit">Send OTP & Register</button>
                        </div>
                    </form>

                    <%-- OTP Verification Section (Part 2 - for OTP verification) --%>
                    <div id="otpSection" class="otp-section">
                        <h3 class="modal-title">OTP Verification</h3>
                        <p class="modal-desc">An OTP has been sent to your email address: <strong><span id="otpEmailDisplay"></span></strong></p>
                        <form action="verifyOtpAndRegister" method="post" id="otpVerificationForm">
                            <div class="input-block">
                                <label for="otp" class="input-label">Enter OTP</label>
                                <input type="text" id="otp" name="otp" class="otp-input" required maxlength="6" pattern="\d{6}">
                            </div>
                            <input type="hidden" id="hiddenEmail" name="emailId" value="">
                            <input type="hidden" id="hiddenRole" name="role" value="">
                            <div class="modal-buttons" style="justify-content: center;">
                                <button class="input-button" type="submit">Verify OTP & Complete Registration</button>
                            </div>
                        </form>
                        <div class="resend-otp">
                            <p>If you didn't receive the OTP, <a href="sendOtpForRegistration" id="resendOtpLink">click here to resend</a>.</p>
                        </div>
                    </div>

                    <p class="sign-up">Already a user? <a href="#" id="showLogin">Login</a></p>
                </div>
            </div>
            <div class="modal-right">
                <img src="https://images.unsplash.com/photo-1512486130939-2c4f79935e4f?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=dfd2ec5a01006fd8c4d7592a381d3776&auto=format&fit=crop&w=1000&q=80" alt="">
            </div>
            <button class="icon-button close-button">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 50 50">
                    <path d="M 25 3 C 12.86158 3 3 12.86158 3 25 C 3 37.13842 12.86158 47 25 47 C 37.13842 47 47 37.13842 47 25 C 47 12.86158 37.13842 3 25 3 z M 25 5 C 36.05754 5 45 13.94246 45 25 C 45 36.05754 36.05754 45 25 45 C 13.94246 45 5 36.05754 5 25 C 5 13.94246 13.94246 5 25 5 z M 16.990234 15.990234 A 1.0001 1.0001 0 0 0 16.292969 17.707031 L 23.585938 25 L 16.292969 32.292969 A 1.0001 1.0001 0 1 0 17.707031 33.707031 L 25 26.414062 L 32.292969 33.707031 A 1.0001 1.0001 0 1 0 33.707031 32.292969 L 26.414062 25 L 33.707031 17.707031 A 1.0001 1.0001 0 0 0 32.980469 15.990234 A 1.0001 1.0001 0 0 0 32.292969 16.292969 L 25 23.585938 L 17.707031 16.292969 A 1.0001 1.0001 0 0 0 16.990234 15.990234 z"></path>
                </svg>
            </button>
        </div>
        <button class="modal-button">Click here to login</button>
    </div>

    <script>
        const body = document.querySelector("body");
        const modal = document.querySelector(".modal");
        const modalButton = document.querySelector(".modal-button");
        const closeButton = document.querySelector(".close-button");
        const scrollDown = document.querySelector(".scroll-down");
        const loginForm = document.getElementById('loginForm');
        const registrationFormContainer = document.getElementById('registrationFormContainer');
        const showRegisterLink = document.getElementById('showRegister');
        const showLoginLink = document.getElementById('showLogin');
        const registrationForm = document.getElementById('registrationForm');
        const otpSection = document.getElementById('otpSection');
        const otpEmailDisplay = document.getElementById('otpEmailDisplay');
        const hiddenEmail = document.getElementById('hiddenEmail');
        const hiddenRole = document.getElementById('hiddenRole');
        const resendOtpLink = document.getElementById('resendOtpLink');

        let isOpened = false;

        const openModal = () => {
            modal.classList.add("is-open");
            body.style.overflow = "hidden";
        };

        const closeModal = () => {
            modal.classList.remove("is-open");
            body.style.overflow = "initial";
            // Reset to login form when closing modal
            loginForm.classList.remove('hidden');
            registrationFormContainer.classList.add('hidden');
            otpSection.style.display = 'none'; // Hide OTP section if open
            registrationForm.style.display = 'block'; // Show registration form (part 1)
        };

        // Event listener for scrolling to open the modal
        window.addEventListener("scroll", () => {
            if (window.scrollY > window.innerHeight / 3 && !isOpened) {
                isOpened = true;
                scrollDown.style.display = "none";
                openModal();
            }
        });

        // Event listener for the "Click here to login" button
        modalButton.addEventListener("click", openModal);

        // Event listener for the close button within the modal
        closeButton.addEventListener("click", closeModal);

        // Event listener for escape key to close the modal
        document.onkeydown = evt => {
            evt = evt || window.event;
            evt.keyCode === 27 ? closeModal() : false;
        };

        // Handle switching between login and registration forms
        showRegisterLink.addEventListener('click', function(e) {
            e.preventDefault();
            loginForm.classList.add('hidden');
            registrationFormContainer.classList.remove('hidden');
            // Ensure OTP section and registration form are in initial state
            otpSection.style.display = 'none';
            registrationForm.style.display = 'block';
        });

        showLoginLink.addEventListener('click', function(e) {
            e.preventDefault();
            registrationFormContainer.classList.add('hidden');
            loginForm.classList.remove('hidden');
            // Ensure OTP section and registration form are in initial state
            otpSection.style.display = 'none';
            registrationForm.style.display = 'block';
        });

        // --- OTP Flow JavaScript Implementation (adapted for the new modal structure) ---

        // Handle the submission of the initial registration form (Part 1: Send OTP)
        registrationForm.addEventListener('submit', async function(e) {
            e.preventDefault(); // Prevent default form submission

            const password = document.getElementById('passwordReg').value;
            const confirmPassword = document.getElementById('confirmPassword').value;

            if (password !== confirmPassword) {
                alert("Passwords do not match!");
                return; // Stop the function if passwords don't match
            }

            // Collect form data
            const formData = new FormData(this);

            try {
                const response = await fetch('sendOtpForRegistration', {
                    method: 'POST',
                    body: formData
                });

                const contentType = response.headers.get("content-type");
                let data = {};
                if (contentType && contentType.indexOf("application/json") !== -1) {
                    data = await response.json();
                } else {
                    if (!response.ok) {
                         alert('An unexpected error occurred or the server returned an error. Please try again.');
                         console.error('Non-JSON error response, status:', response.status);
                         return;
                    }
                }

                if (response.ok) { // Check if status is 2xx
                    // OTP sent successfully, update hidden fields and show OTP section
                    otpEmailDisplay.textContent = document.getElementById('emailId').value;
                    hiddenEmail.value = document.getElementById('emailId').value;
                    hiddenRole.value = document.getElementById('role').value;

                    registrationForm.style.display = 'none'; // Hide the registration form
                    otpSection.style.display = 'block';     // Show the OTP section
                } else {
                    // Handle server-side error (e.g., email already registered, internal error)
                    alert('Error sending OTP: ' + (data.message || 'Unknown error'));
                }

            } catch (error) {
                console.error('Network error or problem with OTP sending:', error);
                alert('A network error occurred or the server is unreachable. Please try again.');
            }
        });

        // Handle Resend OTP link
        resendOtpLink.addEventListener('click', async function(e) {
            e.preventDefault();
            const emailToResend = hiddenEmail.value; // Get email from the hidden field

            if (!emailToResend) {
                alert("Please enter an email address first to resend OTP.");
                return;
            }

            alert('Attempting to resend OTP to ' + emailToResend + '...');

            try {
                const response = await fetch('resendOtpForRegistration', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ emailId: emailToResend })
                });

                const contentType = response.headers.get("content-type");
                let data = {};
                if (contentType && contentType.indexOf("application/json") !== -1) {
                    data = await response.json();
                }

                if (response.ok) {
                    alert('OTP resent successfully!');
                } else {
                    alert('Failed to resend OTP: ' + (data.message || 'Unknown error'));
                }
            } catch (error) {
                console.error('Network error during OTP resend:', error);
                alert('A network error occurred while resending OTP.');
            }
        });
    </script>
</body>
</html>