<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Mock Meet - Try • Develop • Work</title>
    <link rel="icon" type="image/png" sizes="32x32" href="assets/images/favicon.png">
    <!-- Link CSS file -->
    <link rel="stylesheet" href="assets/css/uikit.min.css">
    <link rel="stylesheet" href="assets/font/inter/inter.css">
    <link rel="stylesheet" href="assets/css/style.css">

</head>

<body class="page-<?php echo basename($_SERVER['PHP_SELF'], '.php'); ?>">

    <!-- Back Button -->
    <a href="index.php" class="back-button">
        <span uk-icon="icon: arrow-left; ratio: 1" class="uk-icon" aria-hidden="true"></span>
    </a>

    <div class="login-container">
        <!-- Left Panel - Branding -->
        <div class="login-branding">
            <div class="branding-content">

                <a class="logo logo-login" href="index.php">
                    <img src="assets/svg/logo.svg" alt="Mock Meet" width="234" height="88">
                </a>

                <h1 class="brand-title">Welcome Back!</h1>

                <p class="brand-subtitle">Login to access your interview preparation dashboard and continue your journey to success.</p>

                <div class="brand-features">
                    <div class="brand-feature">
                        <span uk-icon="icon: users; ratio: 1" class="uk-icon" aria-hidden="true"></span>
                        <span>Expert Trainers</span>
                    </div>
                    <div class="brand-feature">
                        <span uk-icon="icon: video; ratio: 1" class="uk-icon" aria-hidden="true"></span>
                        <span>Live Mock Interviews</span>
                    </div>
                    <div class="brand-feature">
                        <span uk-icon="icon: certifications; ratio: 1.4" class="uk-icon" aria-hidden="true"></span>
                        <span>Skill Improvement</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Right Panel - Login Form -->
        <div class="login-form-panel">
            <div class="form-header">
                <h2 class="form-title">Login to Your Account</h2>
                <p class="form-subtitle">Enter your phone number to get started</p>
            </div>

            <!-- Error Message -->
            <div id="errorMessage" class="error-message">
                <span id="errorText">Please check your phone number and try again.</span>
            </div>

            <!-- Success Message -->
            <div id="successMessage" class="success-message">
                <span uk-icon="icon: check-circle; ratio: .7" class="uk-icon" aria-hidden="true"></span>
                <span id="successText">OTP sent successfully!</span>
            </div>

            <!-- User Type Selection -->
            <div id="userTypeStep" class="form-step">
                <div class="user-type-selection">
                    <div class="user-type-option">
                        <input type="radio" id="trainee" name="userType" value="trainee" checked>
                        <label for="trainee" class="user-type-label">

                            <div class="user-type-name">Job Seeker</div>
                        </label>
                    </div>
                    <div class="user-type-option">
                        <input type="radio" id="trainer" name="userType" value="trainer">
                        <label for="trainer" class="user-type-label">
                            <div class="user-type-name">Trainer</div>
                        </label>
                    </div>
                </div>
            </div>

            <!-- Phone Number Step -->
            <div id="phoneStep" class="phone-step form-step">
                <form id="phoneForm">
                    <div class="phone-input-group">
                        <div class="country-code">
                            <img src="assets/svg/ksa.svg" width="20" height="20" alt="saudi arabia">
                            +966
                        </div>
                        <input
                            type="tel"
                            class="phone-input"
                            id="phoneNumber"
                            placeholder="5xxxxxxxx"
                            pattern="[5][0-9]{8}"
                            maxlength="9"
                            required>
                    </div>
                    <p class="uk-text-small  uk-margin-bottom">
                        <span uk-icon="icon: info; ratio: .7" class="uk-icon" aria-hidden="true"></span>
                        Enter your Saudi mobile number starting with 5
                    </p>

                    <button type="submit" class="uk-button uk-button-primary uk-button-large uk-width-1-1 uk-flex uk-flex-middle uk-flex-center" id="sendOtpBtn">
                        <span id="sendOtpText">Send Verification Code</span>
                    </button>
                </form>
            </div>

            <!-- OTP Verification Step -->
            <div id="otpStep" class="otp-step form-step">
                <div class="otp-info">
                    <p>We've sent a 4-digit verification code to:</p>
                    <p class="phone-display" id="phoneDisplay">+966 50xxxxxxx</p>
                </div>

                <form id="otpForm">
                    <div class="otp-inputs">
                        <input type="text" class="otp-digit" maxlength="1" pattern="[0-9]" id="otp1">
                        <input type="text" class="otp-digit" maxlength="1" pattern="[0-9]" id="otp2">
                        <input type="text" class="otp-digit" maxlength="1" pattern="[0-9]" id="otp3">
                        <input type="text" class="otp-digit" maxlength="1" pattern="[0-9]" id="otp4">
                    </div>

                    <div class="resend-timer">
                        <div class="resend-info" id="resendInfo">
                            Didn't receive the code? You can resend in <span class="timer-display" id="timerDisplay">60</span> seconds
                        </div>
                    </div>

                    <div class="uk-flex uk-flex-center gap-8">
                        <button type="submit" class="uk-button uk-button-primary uk-flex uk-flex-middle" id="verifyOtpBtn" disabled>
                            <span id="verifyOtpText">Verify Code</span>
                        </button>

                        <button type="button" class="uk-button uk-button-default uk-flex uk-flex-middle" id="resendOtpBtn" disabled>
                            Resend Code
                        </button>
                    </div>

                    <div class="uk-flex uk-flex-center">
                        <button type="button" class="uk-button uk-button-link uk-padding-remove uk-margin-small-top uk-display-block" onclick="goBackToPhone()">
                            Change Phone Number
                        </button>
                    </div>

                </form>
            </div>

        </div>
    </div>

    <script>
        // Login form state
        let loginState = {
            phoneNumber: '',
            userType: 'trainee',
            otpSent: false,
            resendTimer: 60,
            resendInterval: null
        };

        document.addEventListener('DOMContentLoaded', function() {
            initializeLoginForm();
        });

        function initializeLoginForm() {
            // Get form elements
            const phoneForm = document.getElementById('phoneForm');
            const otpForm = document.getElementById('otpForm');
            const phoneInput = document.getElementById('phoneNumber');
            const otpInputs = document.querySelectorAll('.otp-digit');
            const sendOtpBtn = document.getElementById('sendOtpBtn');
            const verifyOtpBtn = document.getElementById('verifyOtpBtn');
            const resendOtpBtn = document.getElementById('resendOtpBtn');
            const userTypeRadios = document.querySelectorAll('input[name="userType"]');

            // Phone number formatting and validation
            phoneInput.addEventListener('input', function(e) {
                let value = e.target.value.replace(/\D/g, ''); // Remove non-digits

                // Ensure starts with 5 for Saudi mobile numbers
                if (value && !value.startsWith('5')) {
                    value = '5' + value.slice(1);
                }

                // Limit to 9 digits
                if (value.length > 9) {
                    value = value.slice(0, 9);
                }

                e.target.value = value;

                // Remove error state when user starts typing
                e.target.classList.remove('error');
                hideError();

                // Enable/disable send button
                sendOtpBtn.disabled = value.length !== 9;
            });

            // User type selection
            userTypeRadios.forEach(radio => {
                radio.addEventListener('change', function() {
                    loginState.userType = this.value;
                    updateFormLabels();
                });
            });

            // Phone form submission
            phoneForm.addEventListener('submit', function(e) {
                e.preventDefault();
                sendOTP();
            });

            // OTP form submission
            otpForm.addEventListener('submit', function(e) {
                e.preventDefault();
                verifyOTP();
            });

            // OTP input handling
            otpInputs.forEach((input, index) => {
                input.addEventListener('input', function(e) {
                    const value = e.target.value.replace(/\D/g, ''); // Only digits
                    e.target.value = value;

                    // Move to next input
                    if (value && index < otpInputs.length - 1) {
                        otpInputs[index + 1].focus();
                    }

                    // Check if all inputs are filled
                    checkOTPCompletion();

                    // Remove error state
                    e.target.classList.remove('error');
                });

                input.addEventListener('keydown', function(e) {
                    // Move to previous input on backspace
                    if (e.key === 'Backspace' && !e.target.value && index > 0) {
                        otpInputs[index - 1].focus();
                    }
                });

                input.addEventListener('paste', function(e) {
                    e.preventDefault();
                    const pastedData = e.clipboardData.getData('text').replace(/\D/g, '');

                    if (pastedData.length === 4) {
                        otpInputs.forEach((input, idx) => {
                            input.value = pastedData[idx] || '';
                        });
                        checkOTPCompletion();
                    }
                });
            });

            // Resend OTP button
            resendOtpBtn.addEventListener('click', function() {
                sendOTP(true);
            });

            // Initialize form labels
            updateFormLabels();
        }

        function updateFormLabels() {
            const subtitle = document.querySelector('.form-subtitle');
            if (loginState.userType === 'trainer') {
                subtitle.textContent = 'Trainer login - Enter your registered phone number';
            } else {
                subtitle.textContent = 'Enter your phone number to get started';
            }
        }

        function sendOTP(isResend = false) {
            const phoneNumber = document.getElementById('phoneNumber').value;
            const sendOtpBtn = document.getElementById('sendOtpBtn');
            const sendOtpText = document.getElementById('sendOtpText');
            const resendOtpBtn = document.getElementById('resendOtpBtn');

            // Validate phone number
            if (!phoneNumber || phoneNumber.length !== 9 || !phoneNumber.startsWith('5')) {
                showError('Please enter a valid Saudi mobile number starting with 5');
                document.getElementById('phoneNumber').classList.add('error');
                return;
            }

            // Show loading state
            const button = isResend ? resendOtpBtn : sendOtpBtn;
            const originalText = button.innerHTML;
            button.innerHTML = '<span class="loading-spinner"></span>' + (isResend ? 'Sending...' : 'Sending Code...');
            button.disabled = true;

            // Simulate API call
            setTimeout(() => {
                // Reset button
                button.innerHTML = originalText;
                button.disabled = false;

                // Store phone number
                loginState.phoneNumber = phoneNumber;

                // Show success and move to OTP step
                showSuccess('Verification code sent successfully!');
                showOTPStep();

                // Start resend timer
                startResendTimer();

            }, 2000);
        }

        function showOTPStep() {
            // Hide phone step
            document.getElementById('phoneStep').style.display = 'none';
            document.getElementById('userTypeStep').style.display = 'none';

            // Show OTP step
            document.getElementById('otpStep').classList.add('active');

            // Update phone display (mask middle digits)
            const phone = loginState.phoneNumber;
            const maskedPhone = `+966 ${phone.substring(0,2)}${'x'.repeat(phone.length-4)}${phone.substring(phone.length-2)}`;
            document.getElementById('phoneDisplay').textContent = maskedPhone;

            // Focus first OTP input
            document.getElementById('otp1').focus();

            // Update form title
            document.querySelector('.form-title').textContent = 'Verify Your Phone';
            document.querySelector('.form-subtitle').textContent = 'Enter the 4-digit code we sent you';
        }

        function checkOTPCompletion() {
            const otpInputs = document.querySelectorAll('.otp-digit');
            let otpComplete = true;
            let otpValue = '';

            otpInputs.forEach(input => {
                if (!input.value) {
                    otpComplete = false;
                } else {
                    otpValue += input.value;
                    input.classList.add('filled');
                }
            });

            document.getElementById('verifyOtpBtn').disabled = !otpComplete;

            return {
                complete: otpComplete,
                value: otpValue
            };
        }

        function verifyOTP() {
            const {
                complete,
                value: otpValue
            } = checkOTPCompletion();

            if (!complete) {
                showError('Please enter the complete 4-digit code');
                return;
            }

            const verifyOtpBtn = document.getElementById('verifyOtpBtn');
            const verifyOtpText = document.getElementById('verifyOtpText');

            // Show loading
            verifyOtpBtn.innerHTML = '<span class="loading-spinner"></span>Verifying...';
            verifyOtpBtn.disabled = true;

            // Simulate API verification
            setTimeout(() => {
                // For demo purposes, accept any 4-digit code
                // In real implementation, verify with backend

                if (otpValue.length === 4) {
                    // Success - redirect based on user type
                    showSuccess('Login successful! Redirecting...');

                    // setTimeout(() => {
                    //     if (loginState.userType === 'trainer') {
                    //         window.location.href = 'trainer-dashboard.php';
                    //     } else {
                    //         // Check if it's a returning user or new user
                    //         // For demo, assume returning user
                    //         window.location.href = 'index.php?loggedIn=true';
                    //     }
                    // }, 1500);

                    setTimeout(() => {
                        if (loginState.userType === 'trainer') {
                            window.location.href = 'trainer-dashboard.php?loggedIn=true&userType=trainer';
                        } else {
                            window.location.href = 'user-dashboard.php?loggedIn=true&userType=trainee';
                        }
                    }, 1500);

                } else {
                    // Error
                    showError('Invalid verification code. Please try again.');

                    // Clear OTP inputs and add error state
                    document.querySelectorAll('.otp-digit').forEach(input => {
                        input.value = '';
                        input.classList.remove('filled');
                        input.classList.add('error');
                    });

                    // Reset button
                    verifyOtpBtn.innerHTML = 'Verify Code';
                    verifyOtpBtn.disabled = true;

                    // Focus first input
                    document.getElementById('otp1').focus();
                }
            }, 2000);
        }

        function startResendTimer() {
            loginState.resendTimer = 60;
            const resendOtpBtn = document.getElementById('resendOtpBtn');
            const timerDisplay = document.getElementById('timerDisplay');
            const resendInfo = document.getElementById('resendInfo');

            resendOtpBtn.disabled = true;

            loginState.resendInterval = setInterval(() => {
                loginState.resendTimer--;
                timerDisplay.textContent = loginState.resendTimer;

                if (loginState.resendTimer <= 0) {
                    clearInterval(loginState.resendInterval);
                    resendOtpBtn.disabled = false;
                    resendInfo.innerHTML = 'Didn\'t receive the code? <button type="button" class="btn-link" onclick="document.getElementById(\'resendOtpBtn\').click()">Click to resend</button>';
                }
            }, 1000);
        }

        function goBackToPhone() {
            // Clear timers
            if (loginState.resendInterval) {
                clearInterval(loginState.resendInterval);
            }

            // Show phone step
            document.getElementById('phoneStep').style.display = 'block';
            document.getElementById('userTypeStep').style.display = 'block';
            document.getElementById('otpStep').classList.remove('active');

            // Reset form titles
            document.querySelector('.form-title').textContent = 'Login to Your Account';
            updateFormLabels();

            // Clear OTP inputs
            document.querySelectorAll('.otp-digit').forEach(input => {
                input.value = '';
                input.classList.remove('filled', 'error');
            });

            // Focus phone input
            document.getElementById('phoneNumber').focus();

            // Hide messages
            hideError();
            hideSuccess();
        }

        function showError(message) {
            const errorMessage = document.getElementById('errorMessage');
            const errorText = document.getElementById('errorText');
            errorText.textContent = message;
            errorMessage.classList.add('show');

            // Hide success message
            hideSuccess();
        }

        function hideError() {
            document.getElementById('errorMessage').classList.remove('show');
        }

        function showSuccess(message) {
            const successMessage = document.getElementById('successMessage');
            const successText = document.getElementById('successText');
            successText.textContent = message;
            successMessage.classList.add('show');

            // Hide error message
            hideError();
        }

        function hideSuccess() {
            document.getElementById('successMessage').classList.remove('show');
        }

        // Handle URL parameters for direct login attempts
        const urlParams = new URLSearchParams(window.location.search);
        const returnUrl = urlParams.get('returnUrl');
        const userType = urlParams.get('userType');

        if (userType === 'trainer') {
            document.getElementById('trainer').checked = true;
            loginState.userType = 'trainer';
            updateFormLabels();
        }

        // Store return URL for post-login redirect
        if (returnUrl) {
            loginState.returnUrl = returnUrl;
        }
    </script>

    </main>
    <!-- Link JavaScript file -->
    <script src="assets/js/uikit.min.js"></script>
    <script src="assets/js/scripts.js"></script>
</body>

</html>