{% extends "base.html" %}

{% block title %}Sign In - Golden Uniforms{% endblock %}

{% block content %}
<div class="auth-container">
    <div class="auth-wrapper">
        <div class="auth-card">
            <!-- Header -->
            <div class="auth-header">
                <div class="logo-section">
                    <img src="{{ url_for('static', filename='images/logo.png') }}" alt="Golden Uniforms" class="auth-logo">
                    <h1>Golden Uniforms</h1>
                </div>
                <h2 class="auth-title">Welcome Back</h2>
                <p class="auth-subtitle">Sign in to your account or create a new one</p>
            </div>

            <!-- Auth Tabs -->
            <div class="auth-tabs">
                <button class="tab-button active" data-tab="signin">Sign In</button>
                <button class="tab-button" data-tab="register">Register</button>
            </div>

            <!-- Sign In Form -->
            <div class="tab-content active" id="signin-tab">
                <form class="auth-form" id="signin-form">
                    <div class="form-group">
                        <label for="signin-email">Email Address</label>
                        <input type="email" id="signin-email" name="email" class="form-control" required>
                        <i class="fas fa-envelope input-icon"></i>
                    </div>
                    
                    <div class="form-group">
                        <label for="signin-password">Password</label>
                        <input type="password" id="signin-password" name="password" class="form-control" required>
                        <i class="fas fa-lock input-icon"></i>
                        <button type="button" class="password-toggle" onclick="togglePassword('signin-password')">
                            <i class="fas fa-eye"></i>
                        </button>
                    </div>
                    
                    <div class="form-options">
                        <label class="checkbox-label">
                            <input type="checkbox" name="remember"> Remember me
                        </label>
                        <a href="#" class="forgot-link">Forgot password?</a>
                    </div>
                    
                    <button type="submit" class="btn auth-btn primary">
                        <i class="fas fa-sign-in-alt"></i>
                        Sign In
                    </button>
                </form>
            </div>

            <!-- Register Form -->
            <div class="tab-content" id="register-tab">
                <form class="auth-form" id="register-form" action="{{ url_for('register') }}" method="POST">
                    <div class="form-row">
                        <div class="form-group">
                            <label for="register-firstname">First Name</label>
                            <input type="text" id="register-firstname" name="firstname" class="form-control" required minlength="2" maxlength="50">
                            <i class="fas fa-user input-icon"></i>
                            <div class="field-validation"></div>
                        </div>
                        <div class="form-group">
                            <label for="register-lastname">Last Name</label>
                            <input type="text" id="register-lastname" name="lastname" class="form-control" required minlength="2" maxlength="50">
                            <i class="fas fa-user input-icon"></i>
                            <div class="field-validation"></div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="register-email">Email Address</label>
                        <input type="email" id="register-email" name="email" class="form-control" required>
                        <i class="fas fa-envelope input-icon"></i>
                        <div class="field-validation"></div>
                    </div>
                    
                    <div class="form-group">
                        <label for="register-phone">Phone Number</label>
                        <input type="tel" id="register-phone" name="phone" class="form-control" required placeholder="+254 712 345 678">
                        <i class="fas fa-phone input-icon"></i>
                        <div class="field-validation"></div>
                        <small class="form-text">Format: +254 XXX XXX XXX</small>
                    </div>
                    
                    <div class="form-group">
                        <label for="register-password">Password</label>
                        <input type="password" id="register-password" name="password" class="form-control" required minlength="8">
                        <i class="fas fa-lock input-icon"></i>
                        <button type="button" class="password-toggle" onclick="togglePassword('register-password')">
                            <i class="fas fa-eye"></i>
                        </button>
                        <div class="password-strength">
                            <div class="strength-bar">
                                <div class="strength-fill"></div>
                            </div>
                            <div class="strength-text">Password strength</div>
                        </div>
                        <div class="password-requirements">
                            <div class="requirement" data-requirement="length">
                                <i class="fas fa-times"></i> At least 8 characters
                            </div>
                            <div class="requirement" data-requirement="uppercase">
                                <i class="fas fa-times"></i> One uppercase letter
                            </div>
                            <div class="requirement" data-requirement="lowercase">
                                <i class="fas fa-times"></i> One lowercase letter
                            </div>
                            <div class="requirement" data-requirement="number">
                                <i class="fas fa-times"></i> One number
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="register-confirm-password">Confirm Password</label>
                        <input type="password" id="register-confirm-password" name="confirm-password" class="form-control" required minlength="8">
                        <i class="fas fa-lock input-icon"></i>
                        <button type="button" class="password-toggle" onclick="togglePassword('register-confirm-password')">
                            <i class="fas fa-eye"></i>
                        </button>
                        <div class="field-validation"></div>
                    </div>
                    
                    <div class="form-options">
                        <label class="checkbox-label">
                            <input type="checkbox" name="newsletter" id="newsletter-signup"> 
                            Subscribe to our newsletter for new arrivals and exclusive offers
                        </label>
                    </div>
                    
                    <div class="form-options">
                        <label class="checkbox-label">
                            <input type="checkbox" name="agree-terms" required> 
                            I agree to the <a href="{{ url_for('privacy_policy') }}" class="terms-link" target="_blank">Terms & Conditions</a> and <a href="{{ url_for('privacy_policy') }}" class="terms-link" target="_blank">Privacy Policy</a>
                        </label>
                    </div>
                    
                    <button type="submit" class="btn auth-btn primary" id="create-account-btn">
                        <i class="fas fa-user-plus"></i>
                        Create Account
                    </button>
                    
                    <div class="account-benefits">
                        <p><i class="fas fa-gift"></i> Get exclusive discounts and faster checkout with your account!</p>
                    </div>
                </form>
            </div>



            <!-- Footer Links -->
            <div class="auth-footer">
                <p>Need help? <a href="{{ url_for('contact') }}" class="contact-link">Contact Support</a></p>
                <p class="back-link">
                    <a href="{{ url_for('index') }}">
                        <i class="fas fa-arrow-left"></i> Back to Store
                    </a>
                </p>
            </div>
        </div>
    </div>
</div>

<style>
/* Auth Page Styles */
.auth-container {
    min-height: 100vh;
    background: linear-gradient(135deg, #ff6b35 0%, #f7931e 50%, #ffbe0b 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 2rem 1rem;
}

.auth-wrapper {
    width: 100%;
    max-width: 450px;
}

.auth-card {
    background: white;
    border-radius: 20px;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    animation: slideUp 0.6s ease-out;
}

@keyframes slideUp {
    from {
        opacity: 0;
        transform: translateY(30px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.auth-header {
    text-align: center;
    padding: 2rem 2rem 1rem;
    background: linear-gradient(135deg, rgba(255, 107, 53, 0.05), rgba(247, 147, 30, 0.05));
}

.logo-section {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 1rem;
    margin-bottom: 1rem;
}

.auth-logo {
    width: 50px;
    height: 50px;
    border-radius: 12px;
    object-fit: cover;
}

.logo-section h1 {
    font-size: 1.5rem;
    font-weight: 700;
    color: #ff6b35;
    margin: 0;
}

.auth-title {
    font-size: 1.8rem;
    font-weight: 600;
    color: #333;
    margin: 0 0 0.5rem;
}

.auth-subtitle {
    color: #666;
    margin: 0;
    font-size: 0.95rem;
}

.auth-tabs {
    display: flex;
    background: #f8f9fa;
    margin: 0;
}

.tab-button {
    flex: 1;
    padding: 1rem;
    border: none;
    background: transparent;
    font-weight: 500;
    color: #666;
    cursor: pointer;
    transition: all 0.3s ease;
    border-bottom: 3px solid transparent;
}

.tab-button.active {
    color: #ff6b35;
    background: white;
    border-bottom-color: #ff6b35;
}

.tab-content {
    display: none;
    padding: 2rem;
}

.tab-content.active {
    display: block;
}

.auth-form {
    margin-bottom: 1rem;
}

.form-row {
    display: flex;
    gap: 1rem;
}

.form-group {
    margin-bottom: 1.5rem;
    position: relative;
    flex: 1;
}

.form-group label {
    display: block;
    margin-bottom: 0.5rem;
    font-weight: 500;
    color: #333;
    font-size: 0.9rem;
}

.form-control {
    width: 100%;
    padding: 1rem 1rem 1rem 3rem;
    border: 2px solid #e9ecef;
    border-radius: 10px;
    font-size: 1rem;
    transition: all 0.3s ease;
    background: #fafafa;
}

.form-control:focus {
    outline: none;
    border-color: #ff6b35;
    background: white;
    box-shadow: 0 0 0 3px rgba(255, 107, 53, 0.1);
}

.input-icon {
    position: absolute;
    left: 1rem;
    top: 50%;
    transform: translateY(-50%);
    color: #999;
    font-size: 1rem;
    margin-top: 12px;
}

.password-toggle {
    position: absolute;
    right: 1rem;
    top: 50%;
    transform: translateY(-50%);
    border: none;
    background: none;
    color: #999;
    cursor: pointer;
    margin-top: 12px;
}

.form-options {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1.5rem;
    font-size: 0.9rem;
}

.checkbox-label {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    margin: 0;
    cursor: pointer;
}

.forgot-link, .terms-link, .contact-link {
    color: #ff6b35;
    text-decoration: none;
    font-weight: 500;
}

.forgot-link:hover, .terms-link:hover, .contact-link:hover {
    text-decoration: underline;
}

.auth-btn {
    width: 100%;
    padding: 1rem;
    border: none;
    border-radius: 10px;
    font-size: 1rem;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 0.5rem;
}

.auth-btn.primary {
    background: linear-gradient(135deg, #ff6b35, #f7931e);
    color: white;
}

.auth-btn.primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(255, 107, 53, 0.3);
}



.auth-footer {
    text-align: center;
    padding: 1rem 2rem 2rem;
    color: #666;
    font-size: 0.9rem;
}

.auth-footer p {
    margin: 0.5rem 0;
}

.back-link a {
    color: #666;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
}

.back-link a:hover {
    color: #ff6b35;
    text-decoration: none;
}

/* Message Notifications */
.auth-message {
    margin: 0;
    padding: 1rem 1.5rem;
    border-radius: 0;
    display: flex;
    align-items: center;
    gap: 0.75rem;
    font-weight: 500;
    animation: slideDown 0.3s ease-out;
}

.auth-message.success {
    background: linear-gradient(135deg, #d4edda, #c3e6cb);
    color: #155724;
    border-bottom: 3px solid #28a745;
}

.auth-message.error {
    background: linear-gradient(135deg, #f8d7da, #f5c6cb);
    color: #721c24;
    border-bottom: 3px solid #dc3545;
}

.auth-message i {
    font-size: 1.1rem;
}

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

/* Form Validation Styles */
.field-validation {
    font-size: 0.8rem;
    margin-top: 0.25rem;
    min-height: 1rem;
}

.field-validation.success {
    color: #28a745;
}

.field-validation.error {
    color: #dc3545;
}

.form-control.valid {
    border-color: #28a745;
}

.form-control.invalid {
    border-color: #dc3545;
}

.form-text {
    font-size: 0.8rem;
    color: #666;
    margin-top: 0.25rem;
    display: block;
}

/* Password Strength Indicator */
.password-strength {
    margin-top: 0.5rem;
}

.strength-bar {
    height: 4px;
    background: #e9ecef;
    border-radius: 2px;
    overflow: hidden;
    margin-bottom: 0.5rem;
}

.strength-fill {
    height: 100%;
    width: 0%;
    transition: all 0.3s ease;
    border-radius: 2px;
}

.strength-fill.weak {
    width: 25%;
    background: #dc3545;
}

.strength-fill.fair {
    width: 50%;
    background: #ffc107;
}

.strength-fill.good {
    width: 75%;
    background: #28a745;
}

.strength-fill.strong {
    width: 100%;
    background: #198754;
}

.strength-text {
    font-size: 0.8rem;
    color: #666;
    margin-bottom: 0.5rem;
}

/* Password Requirements */
.password-requirements {
    margin-top: 0.5rem;
}

.requirement {
    font-size: 0.8rem;
    margin-bottom: 0.25rem;
    color: #dc3545;
    transition: color 0.3s ease;
}

.requirement.met {
    color: #28a745;
}

.requirement.met i {
    color: #28a745;
}

.requirement i {
    width: 12px;
    margin-right: 0.5rem;
    font-size: 0.7rem;
}

.requirement.met i:before {
    content: "\f00c";
}

/* Account Benefits */
.account-benefits {
    background: linear-gradient(135deg, rgba(255, 107, 53, 0.05), rgba(247, 147, 30, 0.05));
    border-radius: 10px;
    padding: 1rem;
    margin-top: 1.5rem;
    border: 1px solid rgba(255, 107, 53, 0.1);
    text-align: center;
}

.account-benefits p {
    margin: 0;
    font-size: 0.9rem;
    color: #555;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 0.5rem;
}

.account-benefits i {
    color: #ff6b35;
    font-size: 1rem;
}

/* Enhanced Button States */
.auth-btn:disabled {
    opacity: 0.7;
    cursor: not-allowed;
    transform: none !important;
}

.auth-btn.loading {
    position: relative;
    color: transparent;
}

.auth-btn.loading::after {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 20px;
    height: 20px;
    border: 2px solid #ffffff;
    border-top: 2px solid transparent;
    border-radius: 50%;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% { transform: translate(-50%, -50%) rotate(0deg); }
    100% { transform: translate(-50%, -50%) rotate(360deg); }
}

/* Enhanced Form Animations */
.form-group {
    animation: fadeInUp 0.4s ease-out;
    animation-fill-mode: both;
}

.form-group:nth-child(1) { animation-delay: 0.1s; }
.form-group:nth-child(2) { animation-delay: 0.2s; }
.form-group:nth-child(3) { animation-delay: 0.3s; }
.form-group:nth-child(4) { animation-delay: 0.4s; }
.form-group:nth-child(5) { animation-delay: 0.5s; }

@keyframes fadeInUp {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

/* Mobile Responsive */
@media (max-width: 768px) {
    .auth-container {
        padding: 1rem;
        align-items: flex-start;
        padding-top: 2rem;
    }
    
    .auth-wrapper {
        max-width: 100%;
    }
    
    .auth-header {
        padding: 1.5rem 1.5rem 1rem;
    }
    
    .logo-section {
        flex-direction: column;
        gap: 0.5rem;
    }
    
    .tab-content {
        padding: 1.5rem;
    }
    
    .form-row {
        flex-direction: column;
        gap: 0;
    }
    
    .auth-title {
        font-size: 1.5rem;
    }
    
    .auth-footer {
        padding: 1rem 1.5rem 1.5rem;
    }
    
    .auth-message {
        padding: 0.75rem 1rem;
        font-size: 0.9rem;
    }
    
    .password-requirements {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 0.25rem;
    }
    
    .account-benefits {
        padding: 0.75rem;
        margin-top: 1rem;
    }
    
    .account-benefits p {
        font-size: 0.85rem;
    }
}
</style>

<script>
// Tab functionality
document.addEventListener('DOMContentLoaded', function() {
    const tabButtons = document.querySelectorAll('.tab-button');
    const tabContents = document.querySelectorAll('.tab-content');
    
    tabButtons.forEach(button => {
        button.addEventListener('click', function() {
            const targetTab = this.dataset.tab;
            
            // Remove active class from all tabs and contents
            tabButtons.forEach(btn => btn.classList.remove('active'));
            tabContents.forEach(content => content.classList.remove('active'));
            
            // Add active class to clicked tab and corresponding content
            this.classList.add('active');
            document.getElementById(targetTab + '-tab').classList.add('active');
        });
    });
    
    // Form validation and submission
    const signinForm = document.getElementById('signin-form');
    const registerForm = document.getElementById('register-form');
    
    if (signinForm) {
        signinForm.addEventListener('submit', handleSignin);
    }
    
    if (registerForm) {
        registerForm.addEventListener('submit', handleRegister);
    }
});

function togglePassword(inputId) {
    const input = document.getElementById(inputId);
    const toggle = input.nextElementSibling.querySelector('i');
    
    if (input.type === 'password') {
        input.type = 'text';
        toggle.classList.remove('fa-eye');
        toggle.classList.add('fa-eye-slash');
    } else {
        input.type = 'password';
        toggle.classList.remove('fa-eye-slash');
        toggle.classList.add('fa-eye');
    }
}

function handleSignin(e) {
    e.preventDefault();
    const formData = new FormData(e.target);
    const button = e.target.querySelector('button[type="submit"]');
    const originalContent = button.innerHTML;
    
    // Add loading state
    button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Signing In...';
    button.disabled = true;
    
    // Send data to backend
    fetch('/signin-form', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            if (data.redirect) {
                // User exists, redirect to main page
                showMessage(data.message, 'success');
                setTimeout(() => {
                    window.location.href = '{{ url_for("index") }}';
                }, 1500);
            }
        } else {
            showMessage(data.message, 'error');
            button.innerHTML = originalContent;
            button.disabled = false;
        }
    })
    .catch(error => {
        showMessage('Sign-in failed. Please try again.', 'error');
        button.innerHTML = originalContent;
        button.disabled = false;
    });
}

function handleRegister(e) {
    e.preventDefault();
    const formData = new FormData(e.target);
    const button = e.target.querySelector('button[type="submit"]');
    
    // Get form values
    const password = formData.get('password');
    const confirmPassword = formData.get('confirm-password');
    const email = formData.get('email');
    const phone = formData.get('phone');
    const firstname = formData.get('firstname');
    const lastname = formData.get('lastname');
    
    // Reset previous validation states
    clearValidationErrors();
    
    let hasErrors = false;
    
    // Validate required fields
    if (!firstname || firstname.length < 2) {
        showFieldError('register-firstname', 'First name must be at least 2 characters');
        hasErrors = true;
    }
    
    if (!lastname || lastname.length < 2) {
        showFieldError('register-lastname', 'Last name must be at least 2 characters');
        hasErrors = true;
    }
    
    if (!email || !isValidEmail(email)) {
        showFieldError('register-email', 'Please enter a valid email address');
        hasErrors = true;
    }
    
    if (!phone || !isValidPhone(phone)) {
        showFieldError('register-phone', 'Please enter a valid Kenyan phone number (+254 XXX XXX XXX)');
        hasErrors = true;
    }
    
    // Validate password strength
    const passwordStrength = checkPasswordStrength(password);
    if (passwordStrength.score < 3) {
        showFieldError('register-password', 'Please choose a stronger password');
        hasErrors = true;
    }
    
    // Validate passwords match
    if (password !== confirmPassword) {
        showFieldError('register-confirm-password', 'Passwords do not match');
        hasErrors = true;
    }
    
    // Check terms agreement
    if (!formData.get('agree-terms')) {
        showMessage('Please agree to the Terms & Conditions to continue', 'error');
        hasErrors = true;
    }
    
    if (hasErrors) {
        return;
    }
    
    // Add loading state
    button.classList.add('loading');
    button.disabled = true;
    
    // Send data to backend
    fetch('/register', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            firstname: firstname,
            lastname: lastname,
            email: email,
            phone: phone,
            password: password,
            'confirm-password': confirmPassword,
            newsletter: formData.get('newsletter') ? true : false
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showMessage(data.message + ' You can now sign in with your email.', 'success');
            // Switch to sign-in tab after successful registration
            setTimeout(() => {
                document.querySelector('[data-tab="signin"]').click();
                document.getElementById('signin-email').value = email;
                document.getElementById('register-form').reset();
                resetPasswordStrength();
            }, 2500);
        } else {
            showMessage(data.message, 'error');
        }
    })
    .catch(error => {
        showMessage('Registration failed. Please check your connection and try again.', 'error');
    })
    .finally(() => {
        button.classList.remove('loading');
        button.disabled = false;
    });
}

// Enhanced validation functions
function isValidEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
}

function isValidPhone(phone) {
    // Kenyan phone number validation: +254 XXX XXX XXX
    const phoneRegex = /^\+254\s?\d{3}\s?\d{3}\s?\d{3}$/;
    return phoneRegex.test(phone);
}

function checkPasswordStrength(password) {
    let score = 0;
    const requirements = {
        length: password.length >= 8,
        uppercase: /[A-Z]/.test(password),
        lowercase: /[a-z]/.test(password),
        number: /\d/.test(password),
        special: /[!@#$%^&*(),.?":{}|<>]/.test(password)
    };
    
    // Calculate score
    if (requirements.length) score++;
    if (requirements.uppercase) score++;
    if (requirements.lowercase) score++;
    if (requirements.number) score++;
    if (requirements.special) score++;
    
    // Update password requirements UI
    updatePasswordRequirements(requirements);
    
    // Update strength bar
    updatePasswordStrengthBar(score);
    
    return { score, requirements };
}

function updatePasswordRequirements(requirements) {
    const requirementElements = document.querySelectorAll('.requirement');
    requirementElements.forEach(el => {
        const requirement = el.dataset.requirement;
        if (requirements[requirement]) {
            el.classList.add('met');
        } else {
            el.classList.remove('met');
        }
    });
}

function updatePasswordStrengthBar(score) {
    const strengthFill = document.querySelector('.strength-fill');
    const strengthText = document.querySelector('.strength-text');
    
    if (!strengthFill || !strengthText) return;
    
    // Remove existing classes
    strengthFill.classList.remove('weak', 'fair', 'good', 'strong');
    
    if (score <= 2) {
        strengthFill.classList.add('weak');
        strengthText.textContent = 'Weak password';
    } else if (score === 3) {
        strengthFill.classList.add('fair');
        strengthText.textContent = 'Fair password';
    } else if (score === 4) {
        strengthFill.classList.add('good');
        strengthText.textContent = 'Good password';
    } else {
        strengthFill.classList.add('strong');
        strengthText.textContent = 'Strong password';
    }
}

function resetPasswordStrength() {
    const strengthFill = document.querySelector('.strength-fill');
    const strengthText = document.querySelector('.strength-text');
    const requirements = document.querySelectorAll('.requirement');
    
    if (strengthFill) {
        strengthFill.classList.remove('weak', 'fair', 'good', 'strong');
        strengthFill.style.width = '0%';
    }
    
    if (strengthText) {
        strengthText.textContent = 'Password strength';
    }
    
    requirements.forEach(req => req.classList.remove('met'));
}

function showFieldError(fieldId, message) {
    const field = document.getElementById(fieldId);
    const validation = field.parentNode.querySelector('.field-validation');
    
    field.classList.add('invalid');
    field.classList.remove('valid');
    
    if (validation) {
        validation.textContent = message;
        validation.classList.add('error');
        validation.classList.remove('success');
    }
}

function showFieldSuccess(fieldId, message = '') {
    const field = document.getElementById(fieldId);
    const validation = field.parentNode.querySelector('.field-validation');
    
    field.classList.add('valid');
    field.classList.remove('invalid');
    
    if (validation) {
        validation.textContent = message;
        validation.classList.add('success');
        validation.classList.remove('error');
    }
}

function clearValidationErrors() {
    const fields = document.querySelectorAll('.form-control');
    const validations = document.querySelectorAll('.field-validation');
    
    fields.forEach(field => {
        field.classList.remove('valid', 'invalid');
    });
    
    validations.forEach(validation => {
        validation.textContent = '';
        validation.classList.remove('success', 'error');
    });
}

function showMessage(message, type) {
    // Remove existing messages
    const existingMessage = document.querySelector('.auth-message');
    if (existingMessage) {
        existingMessage.remove();
    }
    
    // Create new message element
    const messageEl = document.createElement('div');
    messageEl.className = `auth-message ${type}`;
    messageEl.innerHTML = `
        <i class="fas ${type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle'}"></i>
        <span>${message}</span>
    `;
    
    // Insert message at the top of auth card
    const authCard = document.querySelector('.auth-card');
    authCard.insertBefore(messageEl, authCard.firstChild);
    
    // Auto-remove after 5 seconds
    setTimeout(() => {
        if (messageEl.parentNode) {
            messageEl.remove();
        }
    }, 5000);
}

// Real-time validation for form fields
document.addEventListener('DOMContentLoaded', function() {
    // Password strength checking
    const passwordInput = document.getElementById('register-password');
    if (passwordInput) {
        passwordInput.addEventListener('input', function() {
            checkPasswordStrength(this.value);
        });
    }
    
    // Real-time password match validation
    const confirmPasswordInput = document.getElementById('register-confirm-password');
    if (confirmPasswordInput && passwordInput) {
        confirmPasswordInput.addEventListener('input', function() {
            if (this.value && passwordInput.value) {
                if (this.value === passwordInput.value) {
                    showFieldSuccess('register-confirm-password', 'Passwords match');
                } else {
                    showFieldError('register-confirm-password', 'Passwords do not match');
                }
            }
        });
    }
    
    // Email validation
    const emailInput = document.getElementById('register-email');
    if (emailInput) {
        emailInput.addEventListener('blur', function() {
            if (this.value) {
                if (isValidEmail(this.value)) {
                    showFieldSuccess('register-email');
                } else {
                    showFieldError('register-email', 'Please enter a valid email address');
                }
            }
        });
    }
    
    // Phone validation
    const phoneInput = document.getElementById('register-phone');
    if (phoneInput) {
        phoneInput.addEventListener('input', function() {
            // Auto-format phone number
            let value = this.value.replace(/\D/g, '');
            if (value.startsWith('254')) {
                value = '+' + value;
            } else if (value.startsWith('0')) {
                value = '+254' + value.substring(1);
            } else if (value.startsWith('7') || value.startsWith('1')) {
                value = '+254' + value;
            }
            
            // Format with spaces
            if (value.length > 4) {
                value = value.substring(0, 4) + ' ' + value.substring(4);
            }
            if (value.length > 8) {
                value = value.substring(0, 8) + ' ' + value.substring(8);
            }
            if (value.length > 12) {
                value = value.substring(0, 12) + ' ' + value.substring(12, 15);
            }
            
            this.value = value;
        });
        
        phoneInput.addEventListener('blur', function() {
            if (this.value) {
                if (isValidPhone(this.value)) {
                    showFieldSuccess('register-phone');
                } else {
                    showFieldError('register-phone', 'Please enter a valid Kenyan phone number');
                }
            }
        });
    }
    
    // Name validation
    const firstNameInput = document.getElementById('register-firstname');
    const lastNameInput = document.getElementById('register-lastname');
    
    [firstNameInput, lastNameInput].forEach(input => {
        if (input) {
            input.addEventListener('input', function() {
                // Capitalize first letter
                this.value = this.value.charAt(0).toUpperCase() + this.value.slice(1).toLowerCase();
            });
            
            input.addEventListener('blur', function() {
                if (this.value.length >= 2) {
                    showFieldSuccess(this.id);
                } else if (this.value.length > 0) {
                    showFieldError(this.id, 'Name must be at least 2 characters');
                }
            });
        }
    });
});
</script>
{% endblock %}