<%@ 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>HealthPlus - Login & Registration</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        /* General Styles */
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%); /* Softer gradient background */
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            position: relative;
            overflow-x: hidden;
        }

        .container {
            max-width: 500px;
            background-color: #fff;
            padding: 30px 40px;
            border-radius: 12px;
            box-shadow: 0 12px 25px rgba(0, 0, 0, 0.15); /* Enhanced shadow */
            width: 100%;
            transition: transform 0.5s ease, box-shadow 0.3s ease; /* Added box-shadow transition */
            position: relative; /* For potential pseudo-elements or absolute positioning */
        }

        .container:hover {
            box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2); /* Slight shadow increase on hover */
        }

        h2, h1 {
            text-align: center;
            color: #007bff;
            margin-bottom: 25px;
            font-family: 'Poppins', sans-serif; /* Poppins for headings */
            font-weight: 700; /* Bolder headings */
            letter-spacing: 0.5px;
        }

        label {
            font-weight: 600; /* Slightly bolder label */
            display: block;
            margin-bottom: 8px; /* Increased margin */
            color: #333;
            font-size: 0.95em;
        }

        input[type="text"],
        input[type="tel"],
        input[type="email"],
        input[type="password"],
        select {
            width: 100%;
            padding: 12px 15px; /* Increased padding */
            margin-bottom: 22px; /* Increased margin */
            border: 1px solid #dcdcdc; /* Lighter border */
            border-radius: 8px; /* More rounded corners */
            box-sizing: border-box;
            font-size: 1em;
            transition: border-color 0.3s ease, box-shadow 0.3s ease; /* Smooth transition */
        }

        input[type="text"]:focus,
        input[type="tel"]:focus,
        input[type="email"]:focus,
        input[type="password"]:focus,
        select:focus {
            border-color: #007bff;
            box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.25); /* Focus highlight */
            outline: none;
        }

        button {
            width: 100%;
            background-color: #28a745;
            color: white;
            padding: 14px; /* Increased padding */
            border: none;
            border-radius: 8px; /* More rounded corners */
            font-size: 17px; /* Slightly larger font */
            font-weight: 600; /* Bolder text */
            cursor: pointer;
            transition: background-color 0.3s ease, transform 0.2s ease; /* Added transform transition */
            letter-spacing: 0.5px;
            box-shadow: 0 4px 10px rgba(40, 167, 69, 0.2); /* Subtle button shadow */
        }

        button:hover {
            background-color: #218838;
            transform: translateY(-2px); /* Slight lift on hover */
            box-shadow: 0 6px 12px rgba(40, 167, 69, 0.3); /* Enhanced shadow on hover */
        }

        .error-message, .success-message {
            color: #dc3545;
            background-color: #f8d7da; /* Light red background */
            border: 1px solid #f5c6cb;
            padding: 10px;
            border-radius: 6px;
            text-align: center;
            margin-bottom: 20px;
            font-weight: 500;
            animation: fadeIn 0.5s ease-out; /* Fade-in animation */
        }

        .success-message {
            color: #155724;
            background-color: #d4edda; /* Light green background */
            border-color: #c3e6cb;
        }

        .login-link {
            text-align: center;
            margin-top: 25px; /* Increased margin */
            font-size: 0.95em;
        }

        .login-link p {
            color: #555;
            margin-bottom: 10px;
        }

        .login-link a {
            color: #007bff;
            text-decoration: none;
            font-weight: bold;
            transition: color 0.3s ease;
        }

        .login-link a:hover {
            text-decoration: underline;
            color: #0056b3;
        }

        /* Animation for form transition */
        .hidden {
            display: none;
        }

        /* Styles for OTP section - initially hidden */
        .otp-section {
            display: none; /* Controlled by JavaScript */
            text-align: center;
            padding-top: 25px; /* Increased padding */
            border-top: 1px solid #eee;
            margin-top: 25px; /* Increased margin */
        }

        .otp-input {
            width: calc(100% - 24px);
            font-size: 1.3em; /* Slightly larger OTP input */
            letter-spacing: 5px; /* More spacing for OTP */
            text-align: center;
            padding: 12px;
            border-radius: 8px;
        }

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

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

        .resend-otp a:hover {
            text-decoration: underline;
            color: #0056b3;
        }

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

        @keyframes slideInFromLeft {
            from { transform: translateX(-100%); opacity: 0; }
            to { transform: translateX(0); opacity: 1; }
        }

        @keyframes slideInFromRight {
            from { transform: translateX(100%); opacity: 0; }
            to { transform: translateX(0); opacity: 1; }
        }

        /* Apply animations to forms */
        #loginForm {
            animation: fadeIn 0.6s ease-out;
        }

        #registrationFormContainer { /* Apply animation to the container of both registration parts */
            animation: fadeIn 0.6s ease-out;
        }

        /* Bubble background effect */
        .bubble {
            position: absolute;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 50%;
            animation: float 10s infinite ease-in-out;
        }

        .bubble:nth-child(1) { width: 60px; height: 60px; left: 10%; top: 20%; animation-duration: 12s; }
        .bubble:nth-child(2) { width: 80px; height: 80px; left: 80%; top: 40%; animation-duration: 15s; }
        .bubble:nth-child(3) { width: 50px; height: 50px; left: 30%; top: 70%; animation-duration: 10s; }
        .bubble:nth-child(4) { width: 70px; height: 70px; left: 5%; top: 90%; animation-duration: 13s; }
        .bubble:nth-child(5) { width: 90px; height: 90px; left: 90%; top: 10%; animation-duration: 11s; }

        @keyframes float {
            0%, 100% { transform: translateY(0) translateX(0); }
            50% { transform: translateY(-20px) translateX(10px); }
        }
    </style>
</head>
<body>

    <div class="bubble"></div>
    <div class="bubble"></div>
    <div class="bubble"></div>
    <div class="bubble"></div>
    <div class="bubble"></div>

    <div class="container" id="formContainer">
        <div id="loginForm">
            <h1>Welcome Back</h1>
            <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">
                <label for="username"><i class="fas fa-user"></i> Username/Email</label>
                <input type="text" id="username" name="emailId" required placeholder="Enter your username or email" autocomplete="username">

                <label for="password"><i class="fas fa-lock"></i> Password</label>
                <input type="password" id="password" name="password" required placeholder="Enter your password" autocomplete="current-password">

                <button type="submit"><i class="fas fa-sign-in-alt"></i> Sign In</button>
            </form>
            <div class="login-link">
                <p>Don't have an account? <a href="#" id="showRegister">Create Account</a></p>
            </div>
        </div>

        <div id="registrationFormContainer" class="hidden">
            <h2>User Registration</h2>
            <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">
                <label for="name"><i class="fas fa-user-plus"></i> Name:</label>
                <input type="text" id="name" name="name" required placeholder="Your full name">

                <label for="mobileNumber"><i class="fas fa-mobile-alt"></i> Mobile Number:</label>
                <input type="tel" id="mobileNumber" name="mobileNumber" placeholder="Ex: 9876543210" required>

                <label for="emailId"><i class="fas fa-envelope"></i> Email Id:</label>
                <input type="email" id="emailId" name="emailId" required placeholder="your.email@example.com">

                <label for="passwordReg"><i class="fas fa-lock"></i> Password:</label>
                <input type="password" id="passwordReg" name="password" required placeholder="Create a strong password">

                <label for="confirmPassword"><i class="fas fa-lock"></i> Confirm Password:</label>
                <input type="password" id="confirmPassword" name="confirmPassword" required placeholder="Re-enter your password">

                <label for="role"><i class="fas fa-user-tag"></i> Role:</label>
                <select id="role" name="role" required>
                    <option value="USER">User</option>
                    <option value="ADMIN">Admin</option>
                </select>

                <button type="submit"><i class="fas fa-paper-plane"></i> Send OTP & Register</button>
            </form>

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

            <div class="login-link">
                <p>Already a user? <a href="#" id="showLogin">Login</a></p>
            </div>
        </div>
    </div>

    <script>
        document.getElementById('showRegister').addEventListener('click', function(e) {
            e.preventDefault();
            const loginForm = document.getElementById('loginForm');
            const registrationFormContainer = document.getElementById('registrationFormContainer');
            const formContainer = document.getElementById('formContainer');

            loginForm.classList.add('hidden');
            registrationFormContainer.classList.remove('hidden');
            registrationFormContainer.style.animation = 'fadeIn 0.6s ease-out'; // Apply animation on display

            formContainer.style.transform = 'translateY(-20px)';
            setTimeout(() => {
                formContainer.style.transform = 'translateY(0)';
            }, 50);
        });

        document.getElementById('showLogin').addEventListener('click', function(e) {
            e.preventDefault();
            const loginForm = document.getElementById('loginForm');
            const registrationFormContainer = document.getElementById('registrationFormContainer');
            const formContainer = document.getElementById('formContainer');

            registrationFormContainer.classList.add('hidden');
            loginForm.classList.remove('hidden');
            loginForm.style.animation = 'fadeIn 0.6s ease-out'; // Apply animation on display

            formContainer.style.transform = 'translateY(-20px)';
            setTimeout(() => {
                formContainer.style.transform = 'translateY(0)';
            }, 50);
        });

        // --- OTP Flow JavaScript Implementation ---

        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');

        // 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 // FormData handles content-type for multipart/form-data
                });

                // Check if the response is JSON
                const contentType = response.headers.get("content-type");
                if (contentType && contentType.indexOf("application/json") !== -1) {
                    const data = await response.json();
                    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
                        otpSection.style.animation = 'fadeIn 0.6s ease-out'; // Animate OTP section in
                    } else {
                        // Handle server-side error (e.g., email already registered, internal error)
                        alert('Error sending OTP: ' + (data.message || 'Unknown error'));
                    }
                } else {
                    // If response is not JSON, it might be a redirect or a plain error page
                    // For example, if your backend redirects on success or error.
                    // You might need to handle this differently based on your backend's behavior.
                    if (response.ok) {
                        // Assuming success if not JSON but still 2xx status, might be a redirect.
                        // You could potentially parse HTML response here if your server sends it.
                        alert('OTP sent successfully. Please check your email.');
                        otpEmailDisplay.textContent = document.getElementById('emailId').value;
                        hiddenEmail.value = document.getElementById('emailId').value;
                        hiddenRole.value = document.getElementById('role').value;

                        registrationForm.style.display = 'none';
                        otpSection.style.display = 'block';
                        otpSection.style.animation = 'fadeIn 0.6s ease-out';
                    } else {
                        alert('An unexpected error occurred. Please try again.');
                        console.error('Non-JSON response, status:', response.status);
                    }
                }

            } 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', { // Assuming a different endpoint for resend
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ emailId: emailToResend })
                });

                const contentType = response.headers.get("content-type");
                if (contentType && contentType.indexOf("application/json") !== -1) {
                    const data = await response.json();
                    if (response.ok) {
                        alert('OTP resent successfully!');
                    } else {
                        alert('Failed to resend OTP: ' + (data.message || 'Unknown error'));
                    }
                } else {
                    if (response.ok) {
                        alert('OTP resent successfully!');
                    } else {
                        alert('An unexpected error occurred while resending OTP.');
                        console.error('Non-JSON response on resend, status:', response.status);
                    }
                }
            } catch (error) {
                console.error('Network error during OTP resend:', error);
                alert('A network error occurred while resending OTP.');
            }
        });

        // Client-side password confirmation validation for the registration form
        // (Moved inside the submit event listener and now runs before the AJAX call)
        // This was already present, but important to note its position in the flow.
    </script>
</body>
</html>