@extends('layouts.master')

@section('title', 'Add User - ')

@section('content')
<style>
/* Modern Blue & White Theme */
:root {
    --primary-blue: #2563eb;
    --primary-dark: #1e40af;
    --primary-light: #3b82f6;
    --primary-bg: #eff6ff;
    --primary-gradient: linear-gradient(135deg, #2563eb 0%, #1e40af 100%);
    --secondary-gradient: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
    --white: #ffffff;
    --light-bg: #f8fafc;
    --border-light: #e2e8f0;
    --border-medium: #cbd5e1;
    --text-dark: #1e293b;
    --text-medium: #475569;
    --text-light: #64748b;
    --success: #10b981;
    --warning: #f59e0b;
    --error: #ef4444;
    --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.1);
    --shadow-md: 0 4px 6px rgba(0, 0, 0, 0.1);
    --shadow-lg: 0 10px 25px rgba(0, 0, 0, 0.1);
    --radius-sm: 6px;
    --radius-md: 8px;
    --radius-lg: 12px;
    --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

/* Base Styles */
.user-form-wrapper {
    background: var(--light-bg);
    min-height: 100vh;
    font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
    padding: 2rem 0;
}

.form-container {
    max-width: 1000px;
    margin: 0 auto;
    padding: 0 1.5rem;
}

/* Header Styles */
.form-header {
    text-align: center;
    margin-bottom: 3rem;
    padding: 2rem 0;
}

.form-title {
    font-size: 2.5rem;
    font-weight: 700;
    color: var(--text-dark);
    margin-bottom: 0.75rem;
    position: relative;
    display: inline-block;
}

.form-title::after {
    content: '';
    position: absolute;
    bottom: -8px;
    left: 50%;
    transform: translateX(-50%);
    width: 60px;
    height: 4px;
    background: var(--primary-gradient);
    border-radius: 2px;
}

.form-subtitle {
    color: var(--text-medium);
    font-size: 1.125rem;
    font-weight: 400;
    max-width: 600px;
    margin: 0 auto;
    line-height: 1.6;
}

/* Main Form Card */
.main-form-card {
    background: var(--white);
    border-radius: var(--radius-lg);
    box-shadow: var(--shadow-lg);
    overflow: hidden;
    margin-bottom: 2rem;
}

.form-progress {
    background: var(--primary-gradient);
    padding: 1.5rem 2rem;
    color: white;
}

.progress-steps {
    display: flex;
    justify-content: space-between;
    align-items: center;
    max-width: 600px;
    margin: 0 auto;
    position: relative;
}

.progress-steps::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 0;
    right: 0;
    height: 2px;
    background: rgba(255, 255, 255, 0.3);
    transform: translateY(-50%);
    z-index: 1;
}

.progress-step {
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    z-index: 2;
}

.step-indicator {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.2);
    border: 2px solid rgba(255, 255, 255, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 600;
    margin-bottom: 0.5rem;
    transition: var(--transition);
}

.step-indicator.active {
    background: var(--white);
    color: var(--primary-blue);
    border-color: var(--white);
}

.step-label {
    font-size: 0.875rem;
    font-weight: 500;
    opacity: 0.8;
}

/* Form Sections */
.form-sections {
    padding: 2.5rem;
}

.form-section {
    margin-bottom: 2.5rem;
    padding: 2rem;
    background: var(--light-bg);
    border-radius: var(--radius-md);
    border-left: 4px solid var(--primary-blue);
}

.section-header {
    display: flex;
    align-items: center;
    margin-bottom: 1.5rem;
}

.section-icon {
    width: 48px;
    height: 48px;
    background: var(--primary-bg);
    border-radius: var(--radius-md);
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 1rem;
    color: var(--primary-blue);
    font-size: 1.25rem;
}

.section-title {
    font-size: 1.375rem;
    font-weight: 600;
    color: var(--text-dark);
    margin: 0;
}

.section-subtitle {
    color: var(--text-light);
    font-size: 0.875rem;
    margin-top: 0.25rem;
}

/* Form Grid & Elements */
.form-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: 1.5rem;
}

.form-group {
    display: flex;
    flex-direction: column;
}

.form-label {
    font-size: 0.875rem;
    font-weight: 500;
    color: var(--text-medium);
    margin-bottom: 0.5rem;
    display: flex;
    align-items: center;
}

.required::after {
    content: '*';
    color: var(--error);
    margin-left: 0.25rem;
}

.form-input, .form-select {
    padding: 0.875rem 1rem;
    border: 1.5px solid var(--border-light);
    border-radius: var(--radius-md);
    font-size: 0.875rem;
    transition: var(--transition);
    background: var(--white);
    color: var(--text-dark);
}

.form-input:focus, .form-select:focus {
    outline: none;
    border-color: var(--primary-blue);
    box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
}

.form-input.error, .form-select.error {
    border-color: var(--error);
    box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.1);
}

.error-message {
    color: var(--error);
    font-size: 0.75rem;
    margin-top: 0.375rem;
    display: flex;
    align-items: center;
    gap: 0.375rem;
}

/* Phone Management */
.phone-manager {
    background: var(--white);
    border-radius: var(--radius-md);
    padding: 1.5rem;
    border: 1.5px solid var(--border-light);
}

.phone-entry {
    background: var(--light-bg);
    border-radius: var(--radius-sm);
    padding: 1.25rem;
    margin-bottom: 1rem;
    border: 1px solid var(--border-light);
}

.phone-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1rem;
}

.phone-title {
    font-size: 0.875rem;
    font-weight: 600;
    color: var(--text-medium);
    margin: 0;
}

.phone-actions {
    display: flex;
    gap: 0.5rem;
}

/* Button Styles */
.btn {
    padding: 0.625rem 1.25rem;
    border: none;
    border-radius: var(--radius-md);
    font-size: 0.875rem;
    font-weight: 500;
    cursor: pointer;
    transition: var(--transition);
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
}

.btn-sm {
    padding: 0.5rem 1rem;
    font-size: 0.75rem;
}

.btn-primary {
    background: var(--primary-blue);
    color: white;
}

.btn-primary:hover {
    background: var(--primary-dark);
    transform: translateY(-1px);
    box-shadow: var(--shadow-md);
}

.btn-secondary {
    background: var(--light-bg);
    color: var(--text-medium);
    border: 1.5px solid var(--border-medium);
}

.btn-secondary:hover {
    background: var(--border-light);
}

.btn-success {
    background: var(--success);
    color: white;
}

.btn-success:hover {
    background: #059669;
    transform: translateY(-1px);
}

.btn-danger {
    background: var(--error);
    color: white;
}

.btn-danger:hover {
    background: #dc2626;
}

/* Toggle Switch */
.toggle-group {
    display: flex;
    align-items: center;
    gap: 0.75rem;
}

.toggle {
    position: relative;
    display: inline-block;
    width: 44px;
    height: 24px;
}

.toggle input {
    opacity: 0;
    width: 0;
    height: 0;
}

.toggle-slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: var(--border-medium);
    transition: var(--transition);
    border-radius: 24px;
}

.toggle-slider:before {
    position: absolute;
    content: "";
    height: 18px;
    width: 18px;
    left: 3px;
    bottom: 3px;
    background-color: white;
    transition: var(--transition);
    border-radius: 50%;
}

input:checked + .toggle-slider {
    background-color: var(--primary-blue);
}

input:checked + .toggle-slider:before {
    transform: translateX(20px);
}

.toggle-label {
    font-size: 0.875rem;
    color: var(--text-medium);
    font-weight: 500;
}

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

.strength-meter {
    height: 6px;
    background: var(--border-light);
    border-radius: 3px;
    margin-bottom: 0.5rem;
    overflow: hidden;
}

.strength-fill {
    height: 100%;
    width: 0%;
    transition: var(--transition);
    border-radius: 3px;
}

.strength-weak { background: var(--error); width: 25%; }
.strength-fair { background: var(--warning); width: 50%; }
.strength-good { background: #10b981; width: 75%; }
.strength-strong { background: var(--success); width: 100%; }

.strength-labels {
    display: flex;
    justify-content: space-between;
    font-size: 0.75rem;
    color: var(--text-light);
}

.strength-text {
    font-size: 0.75rem;
    color: var(--text-light);
    margin-top: 0.25rem;
}

/* Form Actions */
.form-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 2rem 0;
    border-top: 1px solid var(--border-light);
    margin-top: 2rem;
}

.action-buttons {
    display: flex;
    gap: 1rem;
}

.btn-large {
    padding: 0.875rem 2rem;
    font-size: 1rem;
    font-weight: 600;
}

.btn-outline {
    background: transparent;
    color: var(--primary-blue);
    border: 1.5px solid var(--primary-blue);
}

.btn-outline:hover {
    background: var(--primary-bg);
}

.form-note {
    color: var(--text-light);
    font-size: 0.875rem;
    max-width: 300px;
}

/* Animations */
@keyframes slideIn {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.animate-slide-in {
    animation: slideIn 0.5s ease-out;
}

/* Responsive Design */
@media (max-width: 768px) {
    .form-container {
        padding: 0 1rem;
    }

    .form-sections {
        padding: 1.5rem;
    }

    .form-section {
        padding: 1.5rem;
    }

    .form-grid {
        grid-template-columns: 1fr;
    }

    .section-header {
        flex-direction: column;
        align-items: flex-start;
    }

    .section-icon {
        margin-bottom: 0.75rem;
    }

    .progress-steps {
        flex-direction: column;
        gap: 1rem;
    }

    .progress-steps::before {
        display: none;
    }

    .form-actions {
        flex-direction: column;
        gap: 1rem;
        text-align: center;
    }

    .action-buttons {
        width: 100%;
        justify-content: center;
    }
}
</style>

<div class="user-form-wrapper">
    <div class="form-container">
        <div class="form-header">
            <h1 class="form-title">Add New User</h1>
            <p class="form-subtitle">Create a new user account with appropriate permissions and access levels</p>
        </div>

        <div class="main-form-card animate-slide-in">
            <div class="form-progress">
                <div class="progress-steps">
                    <div class="progress-step">
                        <div class="step-indicator active">1</div>
                        <span class="step-label">Basic Info</span>
                    </div>
                    <div class="progress-step">
                        <div class="step-indicator">2</div>
                        <span class="step-label">Contact Details</span>
                    </div>
                    <div class="progress-step">
                        <div class="step-indicator">3</div>
                        <span class="step-label">Security</span>
                    </div>
                    <div class="progress-step">
                        <div class="step-indicator">4</div>
                        <span class="step-label">Permissions</span>
                    </div>
                </div>
            </div>

            <form id="add-user-form" class="form-sections" action="{{ route('administration.store-user') }}" method="POST">
                @csrf

                <!-- Basic Information Section -->
                <div class="form-section">
                    <div class="section-header">
                        <div class="section-icon">
                            <i class="fas fa-user-circle"></i>
                        </div>
                        <div>
                            <h2 class="section-title">Basic Information</h2>
                            <p class="section-subtitle">Enter the user's basic identification details</p>
                        </div>
                    </div>

                    <div class="form-grid">
                        <div class="form-group">
                            <label for="name" class="form-label required">Full Name</label>
                            <input type="text" id="name" name="name" class="form-input"
                                   placeholder="Enter full name" required value="{{ old('name') }}">
                            <div class="error-message" id="name-error">
                                <i class="fas fa-exclamation-circle"></i>
                                <span>Please enter a valid name</span>
                            </div>
                            @error('name')
                                <div class="error-message">
                                    <i class="fas fa-exclamation-circle"></i>
                                    <span>{{ $message }}</span>
                                </div>
                            @enderror
                        </div>

                        <div class="form-group">
                            <label for="email" class="form-label required">Email Address</label>
                            <input type="email" id="email" name="email" class="form-input"
                                   placeholder="user@example.com" required value="{{ old('email') }}">
                            <div class="error-message" id="email-error">
                                <i class="fas fa-exclamation-circle"></i>
                                <span>Please enter a valid email address</span>
                            </div>
                            @error('email')
                                <div class="error-message">
                                    <i class="fas fa-exclamation-circle"></i>
                                    <span>{{ $message }}</span>
                                </div>
                            @enderror
                        </div>

                        <div class="form-group">
                            <label for="location" class="form-label">Location</label>
                            <input type="text" id="location" name="location" class="form-input"
                                   placeholder="Enter location" value="{{ old('location') }}">
                        </div>
                    </div>
                </div>

                <!-- Contact Details Section -->
                <div class="form-section">
                    <div class="section-header">
                        <div class="section-icon">
                            <i class="fas fa-address-book"></i>
                        </div>
                        <div>
                            <h2 class="section-title">Contact Details</h2>
                            <p class="section-subtitle">Add phone numbers and contact information</p>
                        </div>
                    </div>

                    <div class="phone-manager">
                        <div id="phone-numbers-container">
                            <!-- Phone entries will be added here dynamically -->
                        </div>

                        <button type="button" class="btn btn-primary" onclick="addPhoneField()">
                            <i class="fas fa-plus"></i> Add Phone Number
                        </button>
                    </div>
                </div>

                <!-- Security Section -->
                <div class="form-section">
                    <div class="section-header">
                        <div class="section-icon">
                            <i class="fas fa-shield-alt"></i>
                        </div>
                        <div>
                            <h2 class="section-title">Security Settings</h2>
                            <p class="section-subtitle">Configure authentication and security preferences</p>
                        </div>
                    </div>

                    <div class="form-grid">
                        <div class="form-group">
                            <label for="password" class="form-label required">Password</label>
                            <input type="password" id="password" name="password" class="form-input"
                                   placeholder="Enter password" required>
                            <div class="password-strength">
                                <div class="strength-meter">
                                    <div class="strength-fill" id="password-strength-meter"></div>
                                </div>
                                <div class="strength-labels">
                                    <span>Weak</span>
                                    <span>Strong</span>
                                </div>
                                <div class="strength-text" id="password-strength-text">Enter a password to check strength</div>
                            </div>
                            <div class="error-message" id="password-error">
                                <i class="fas fa-exclamation-circle"></i>
                                <span id="password-error-text">Please enter a valid password</span>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="confirm_password" class="form-label required">Confirm Password</label>
                            <input type="password" id="confirm_password" name="confirm_password" class="form-input"
                                   placeholder="Confirm password" required>
                            <div class="error-message" id="confirm-password-error">
                                <i class="fas fa-exclamation-circle"></i>
                                <span>Passwords do not match</span>
                            </div>
                        </div>


                    </div>
                </div>

                <!-- Chat Passcode Section -->
                <div class="form-section">
                    <div class="section-header">
                        <div class="section-icon">
                            <i class="fas fa-comments"></i>
                        </div>
                        <div>
                            <h2 class="section-title">Chat Passcode</h2>
                            <p class="section-subtitle">Set a passcode for chat access</p>
                        </div>
                    </div>

                    <div class="form-grid">
                        <div class="form-group">
                            <label for="chat_passcode" class="form-label">Chat Passcode</label>
                            <input type="password" id="chat_passcode" name="chat_passcode" class="form-input"
                                   placeholder="Enter 6-digit passcode" minlength="6" maxlength="6" pattern="\d{6}">
                            <div class="error-message" id="chat-passcode-error">
                                <i class="fas fa-exclamation-circle"></i>
                                <span>Passcode must be exactly 6 digits</span>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="chat_passcode_confirmation" class="form-label">Confirm Chat Passcode</label>
                            <input type="password" id="chat_passcode_confirmation" name="chat_passcode_confirmation" class="form-input"
                                   placeholder="Confirm passcode" minlength="6" maxlength="6" pattern="\d{6}">
                            <div class="error-message" id="chat-passcode-confirm-error">
                                <i class="fas fa-exclamation-circle"></i>
                                <span>Passcodes do not match</span>
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="toggle-group">
                                <label class="toggle">
                                    <input type="checkbox" id="chat_passcode_active" name="chat_passcode_active" {{ old('chat_passcode_active') ? 'checked' : '' }}>
                                    <span class="toggle-slider"></span>
                                </label>
                                <span class="toggle-label">Active</span>
                            </div>
                            <p class="section-subtitle" style="margin-top: 0.5rem;">Enable to activate chat passcode</p>
                        </div>
                    </div>
                </div>

                <!-- Permissions Section -->
                <div class="form-section">
                    <div class="section-header">
                        <div class="section-icon">
                            <i class="fas fa-user-lock"></i>
                        </div>
                        <div>
                            <h2 class="section-title">Permissions & Access</h2>
                            <p class="section-subtitle">Define user roles and access levels</p>
                        </div>
                    </div>

                    <div class="form-grid">
                        <div class="form-group">
                            <label for="tier" class="form-label">User Tier</label>
                            <select id="tier" name="tier" class="form-select">
                                <option value="">Select Tier</option>
                                @foreach($tiers as $tier)
                                    <option value="{{ $tier->tier_id }}" {{ old('tier') == $tier->tier_id ? 'selected' : '' }}>{{ $tier->tier_name }}</option>
                                @endforeach
                            </select>
                            @error('tier')
                                <div class="error-message">
                                    <i class="fas fa-exclamation-circle"></i>
                                    <span>{{ $message }}</span>
                                </div>
                            @enderror
                        </div>

                        <div class="form-group">
                            <label for="group" class="form-label">User Group</label>
                            <select id="group" name="group" class="form-select">
                                <option value="">Select Group</option>
                                @foreach($groups as $group)
                                    <option value="{{ $group->id }}" {{ old('group') == $group->id ? 'selected' : '' }}>{{ $group->group_name }}</option>
                                @endforeach
                            </select>
                            @error('group')
                                <div class="error-message">
                                    <i class="fas fa-exclamation-circle"></i>
                                    <span>{{ $message }}</span>
                                </div>
                            @enderror
                        </div>

                        <div class="form-group">
                            <label for="status" class="form-label">Account Status</label>
                            <select id="status" name="status" class="form-select">
                                <option value="active" {{ old('status', 'active') == 'active' ? 'selected' : '' }}>Active</option>
                                <option value="inactive" {{ old('status') == 'inactive' ? 'selected' : '' }}>Inactive</option>
                                <option value="suspended" {{ old('status') == 'suspended' ? 'selected' : '' }}>Suspended</option>
                                <option value="pending" {{ old('status') == 'pending' ? 'selected' : '' }}>Pending</option>
                            </select>
                        </div>
                    </div>
                </div>

                <!-- Form Actions -->
                <div class="form-actions">
                    <div class="form-note">
                        <i class="fas fa-info-circle"></i>
                        All fields marked with * are required
                    </div>
                    <div class="action-buttons">
                        <a href="{{ route('administration.user-management') }}" class="btn btn-outline btn-large" style="margin-right: 1rem;">
                            <i class="fas fa-arrow-left"></i> Back to Users
                        </a>
                        <button type="button" class="btn btn-secondary btn-large" onclick="document.getElementById('add-user-form').reset();">
                            <i class="fas fa-undo"></i> Clear Fields
                        </button>
                        <button type="submit" class="btn btn-primary btn-large">
                            <i class="fas fa-user-plus"></i> Create User
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// State management
let state = {
    phoneCount: 0,
    currentStep: 1
};

// Initialize the form
document.addEventListener('DOMContentLoaded', function() {
    setupEventListeners();
    addPhoneField(); // Add first phone field by default
    updateProgressSteps();
});

// Setup event listeners
function setupEventListeners() {
    // Form submission
    document.getElementById('add-user-form').addEventListener('submit', handleSubmit);

    // Real-time validation
    document.getElementById('name').addEventListener('blur', validateName);
    document.getElementById('email').addEventListener('blur', validateEmail);
    document.getElementById('password').addEventListener('input', validatePassword);
    document.getElementById('confirm_password').addEventListener('blur', validateConfirmPassword);
    document.getElementById('chat_passcode').addEventListener('input', validateChatPasscode);
    document.getElementById('chat_passcode_confirmation').addEventListener('blur', validateChatPasscodeConfirm);



    // Step navigation (simulated)
    document.querySelectorAll('.step-indicator').forEach((step, index) => {
        step.addEventListener('click', () => {
            state.currentStep = index + 1;
            updateProgressSteps();
        });
    });
}

// Update progress steps
function updateProgressSteps() {
    document.querySelectorAll('.step-indicator').forEach((step, index) => {
        if (index + 1 <= state.currentStep) {
            step.classList.add('active');
        } else {
            step.classList.remove('active');
        }
    });
}

// Phone number management
function addPhoneField(phoneData = {}) {
    state.phoneCount++;
    const phoneId = `phone-${state.phoneCount}`;

    const phoneEntry = document.createElement('div');
    phoneEntry.className = 'phone-entry';
    phoneEntry.id = phoneId;

    phoneEntry.innerHTML = `
        <div class="phone-header">
            <h3 class="phone-title">Phone Number ${state.phoneCount}</h3>
            <div class="phone-actions">
                <button type="button" class="btn btn-secondary btn-sm" onclick="setAsPrimary('${phoneId}')">
                    <i class="fas fa-star"></i> Primary
                </button>
                <button type="button" class="btn btn-danger btn-sm" onclick="removePhoneField('${phoneId}')" ${state.phoneCount === 1 ? 'disabled' : ''}>
                    <i class="fas fa-trash"></i> Remove
                </button>
            </div>
        </div>
        <div class="form-grid">
            <div class="form-group">
                <label for="${phoneId}-number" class="form-label required">Phone Number</label>
                <input type="tel" id="${phoneId}-number" name="phones[${state.phoneCount}][number]"
                       class="form-input" placeholder="+1 (555) 123-4567" required
                       value="${phoneData.number || ''}">
            </div>
            <div class="form-group">
                <label for="${phoneId}-type" class="form-label">Phone Type</label>
                <select id="${phoneId}-type" name="phones[${state.phoneCount}][type]" class="form-select">
                    <option value="primary" ${phoneData.type === 'primary' ? 'selected' : ''}>Primary</option>
                    <option value="secondary" ${phoneData.type === 'secondary' ? 'selected' : ''}>Secondary</option>
                    <option value="work" ${phoneData.type === 'work' ? 'selected' : ''}>Work</option>
                    <option value="emergency" ${phoneData.type === 'emergency' ? 'selected' : ''}>Emergency</option>
                </select>
            </div>

        </div>
    `;

    document.getElementById('phone-numbers-container').appendChild(phoneEntry);
}

function removePhoneField(phoneId) {
    const phoneEntry = document.getElementById(phoneId);
    if (phoneEntry && state.phoneCount > 1) {
        phoneEntry.remove();
        state.phoneCount--;
        // Update remaining phone numbers
        updatePhoneNumbers();
    }
}

function setAsPrimary(phoneId) {
    // Reset all phone types to secondary
    document.querySelectorAll('select[name$="[type]"]').forEach(select => {
        select.value = 'secondary';
    });

    // Set the selected phone as primary
    const primarySelect = document.querySelector(`#${phoneId} select[name$="[type]"]`);
    if (primarySelect) {
        primarySelect.value = 'primary';
    }
}

function updatePhoneNumbers() {
    // Re-index phone numbers if needed
    const phoneEntries = document.querySelectorAll('.phone-entry');
    phoneEntries.forEach((entry, index) => {
        const title = entry.querySelector('.phone-title');
        if (title) {
            title.textContent = `Phone Number ${index + 1}`;
        }
    });
}

// Validation functions
function validateName() {
    const nameInput = document.getElementById('name');
    const errorElement = document.getElementById('name-error');
    const name = nameInput.value.trim();

    if (name.length < 2) {
        showError(nameInput, errorElement, 'Name must be at least 2 characters long');
        return false;
    } else {
        clearError(nameInput, errorElement);
        return true;
    }
}

function validateEmail() {
    const emailInput = document.getElementById('email');
    const errorElement = document.getElementById('email-error');
    const email = emailInput.value.trim();
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

    if (!emailRegex.test(email)) {
        showError(emailInput, errorElement, 'Please enter a valid email address');
        return false;
    } else {
        clearError(emailInput, errorElement);
        return true;
    }
}

function validatePassword() {
    const passwordInput = document.getElementById('password');
    const errorElement = document.getElementById('password-error');
    const strengthMeter = document.getElementById('password-strength-meter');
    const strengthText = document.getElementById('password-strength-text');
    const password = passwordInput.value;

    // Calculate password strength
    let strength = 0;

    if (password.length >= 8) strength++;
    if (password.match(/[a-z]/) && password.match(/[A-Z]/)) strength++;
    if (password.match(/\d/)) strength++;
    if (password.match(/[^a-zA-Z\d]/)) strength++;

    // Update strength meter
    strengthMeter.className = 'strength-fill';
    if (strength === 0) {
        strengthText.textContent = 'Enter a password to check strength';
        strengthText.style.color = 'var(--text-light)';
    } else if (strength <= 1) {
        strengthMeter.classList.add('strength-weak');
        strengthText.textContent = 'Weak password - consider adding numbers and symbols';
        strengthText.style.color = 'var(--error)';
    } else if (strength <= 2) {
        strengthMeter.classList.add('strength-fair');
        strengthText.textContent = 'Fair password - could be stronger';
        strengthText.style.color = 'var(--warning)';
    } else if (strength <= 3) {
        strengthMeter.classList.add('strength-good');
        strengthText.textContent = 'Good password';
        strengthText.style.color = '#10b981';
    } else {
        strengthMeter.classList.add('strength-strong');
        strengthText.textContent = 'Strong password';
        strengthText.style.color = 'var(--success)';
    }

    if (password.length < 8) {
        showError(passwordInput, errorElement, 'Password must be at least 8 characters long');
        return false;
    } else {
        clearError(passwordInput, errorElement);
        return true;
    }
}

function validateConfirmPassword() {
    const passwordInput = document.getElementById('password');
    const confirmInput = document.getElementById('confirm_password');
    const errorElement = document.getElementById('confirm-password-error');

    if (confirmInput.value !== passwordInput.value) {
        showError(confirmInput, errorElement, 'Passwords do not match');
        return false;
    } else {
        clearError(confirmInput, errorElement);
        return true;
    }
}

function showError(input, errorElement, message) {
    input.classList.add('error');
    errorElement.style.display = 'flex';
    errorElement.querySelector('span').textContent = message;
}

function clearError(input, errorElement) {
    input.classList.remove('error');
    errorElement.style.display = 'none';
}

// Chat passcode validation
function validateChatPasscode() {
    const passcodeInput = document.getElementById('chat_passcode');
    const errorElement = document.getElementById('chat-passcode-error');
    const passcode = passcodeInput.value;

    // Only validate if user has entered something
    if (passcode.length > 0) {
        // Check if passcode is exactly 6 digits
        if (!/^\d{6}$/.test(passcode)) {
            showError(passcodeInput, errorElement, 'Passcode must be exactly 6 digits');
            return false;
        } else {
            clearError(passcodeInput, errorElement);
            return true;
        }
    }
    return true;
}

function validateChatPasscodeConfirm() {
    const passcodeInput = document.getElementById('chat_passcode');
    const confirmInput = document.getElementById('chat_passcode_confirmation');
    const errorElement = document.getElementById('chat-passcode-confirm-error');

    // Only validate if user has entered something in confirmation
    if (confirmInput.value.length > 0) {
        if (confirmInput.value !== passcodeInput.value) {
            showError(confirmInput, errorElement, 'Passcodes do not match');
            return false;
        } else {
            clearError(confirmInput, errorElement);
            return true;
        }
    }
    return true;
}

// Form submission
function handleSubmit(event) {
    event.preventDefault();

    // Validate all fields
    const isNameValid = validateName();
    const isEmailValid = validateEmail();
    const isPasswordValid = validatePassword();
    const isConfirmValid = validateConfirmPassword();
    const isChatPasscodeValid = validateChatPasscode();
    const isChatPasscodeConfirmValid = validateChatPasscodeConfirm();

    if (isNameValid && isEmailValid && isPasswordValid && isConfirmValid && isChatPasscodeValid && isChatPasscodeConfirmValid) {
        submitUserData();
    } else {
        // Scroll to first error
        const firstError = document.querySelector('.error');
        if (firstError) {
            firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
    }
}

function submitUserData() {
    // Show loading state
    const submitBtn = document.querySelector('.btn-primary[type="submit"]');
    const originalText = submitBtn.innerHTML;
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Creating User...';
    submitBtn.disabled = true;

    // Simulate API call
    setTimeout(() => {
        alert('User created successfully!');
        submitBtn.innerHTML = originalText;
        submitBtn.disabled = false;

    // Reset form
    document.getElementById('add-user-form').reset();
    document.getElementById('phone-numbers-container').innerHTML = '';
    state.phoneCount = 0;
    addPhoneField();
    document.getElementById('2fa-methods').style.display = 'none';
    document.getElementById('chat-passcode-error').style.display = 'none';
    document.getElementById('chat-passcode-confirm-error').style.display = 'none';
}, 2000);
}
</script>
@endsection

