@extends('layouts.app')

@section('content')

<div class="container py-5">
    <div class="row justify-content-center">
        <div class="col-md-7 col-lg-6">
            <div class="card-modern p-4">
                <div class="text-center mb-4">
                    <div class="icon-container bg-primary bg-opacity-10 mb-3 mx-auto rounded-5 d-flex align-items-center justify-content-center"
                         style="width: 80px; height: 80px;">
                        <i class="bi bi-person-plus text-primary" style="font-size: 2rem;"></i>
                    </div>
                    <h2 class="fw-bold text-gradient mb-2">Créer un compte</h2>
                    <p class="text-muted small">Accès à la plateforme administrative</p>
                </div>

                <form method="POST" action="{{ route('register.submit') }}" id="registerForm">
                    @csrf

                    <div class="row">
                        <!-- Prénom -->
                        <div class="col-md-6 mb-4 form-group-modern">
                            <label class="form-label-modern required-field">Prénom</label>
                            <input type="text" name="first_name"
                                   class="form-control-modern @error('first_name') is-invalid @enderror"
                                   value="{{ old('first_name') }}" required>
                            @error('first_name') <div class="text-danger small">{{ $message }}</div> @enderror
                        </div>

                        <!-- Nom -->
                        <div class="col-md-6 mb-4 form-group-modern">
                            <label class="form-label-modern required-field">Nom</label>
                            <input type="text" name="last_name"
                                   class="form-control-modern @error('last_name') is-invalid @enderror"
                                   value="{{ old('last_name') }}" required>
                            @error('last_name') <div class="text-danger small">{{ $message }}</div> @enderror
                        </div>
                    </div>

                    <!-- Email -->
                    <div class="mb-4 form-group-modern">
                        <label class="form-label-modern required-field">Adresse Email</label>
                        <input type="email" name="email"
                               class="form-control-modern @error('email') is-invalid @enderror"
                               value="{{ old('email') }}" required>
                        @error('email') <div class="text-danger small">{{ $message }}</div> @enderror
                    </div>

                    <!-- Mobile -->
                    <div class="mb-4 form-group-modern">
                        <label class="form-label-modern required-field"> Contact WhatsApp</label>
                        <input type="text" name="mobile"
                               class="form-control-modern @error('mobile') is-invalid @enderror"
                               value="{{ old('mobile') }}" required placeholder="Ex: 229xxxxxxxx">
                        @error('mobile') <div class="text-danger small">{{ $message }}</div> @enderror
                    </div>
<!-- Membre du rectorat -->
                    <div class="mb-4 form-group-modern">
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" id="isRectorate" name="is_rectorate"
                                value="1" {{ old('is_rectorate') ? 'checked' : '' }}>
                            <label class="form-check-label fw-semibold" for="isRectorate">
                                Membre du rectorat
                            </label>
                        </div>
                    </div>
                    <!-- Institution -->
               <div class="mb-4 form-group-modern" id="institutionBlock">
                    <label class="form-label-modern required-field">Institution</label>
                    <select name="institution_id"
                            class="form-control-modern @error('institution_id') is-invalid @enderror">
                        <option value="">-- Choisir une institution --</option>
                        @foreach($institutions as $institution)
                            <option value="{{ $institution->id }}"
                                {{ old('institution_id') == $institution->id ? 'selected' : '' }}>
                                {{ $institution->name }}
                            </option>
                        @endforeach
                    </select>
                    @error('institution_id') <div class="text-danger small">{{ $message }}</div> @enderror
                </div>

                    <div class="mb-4 form-group-modern d-none" id="serviceBlock">
                        <label class="form-label-modern required-field">Service du rectorat</label>
                        <select name="service_id"
                                class="form-control-modern @error('service_id') is-invalid @enderror">
                            <option value="">-- Choisir un service --</option>
                            @foreach($services as $service)
                                <option value="{{ $service->id }}"
                                    {{ old('service_id') == $service->id ? 'selected' : '' }}>
                                    {{ $service->name }}
                                </option>
                            @endforeach
                        </select>
                        @error('service_id') <div class="text-danger small">{{ $message }}</div> @enderror
                    </div>

                    <!-- Rôle -->
                   <div class="mb-4 form-group-modern">
                        <label class="form-label-modern required-field">Rôle</label>
                        <select name="role"
                                class="form-control-modern @error('role') is-invalid @enderror" required>
                            <option value="">-- Choisir un rôle --</option>
                            <option value="secretaire" @selected(old('role') == 'secretaire')>Secrétaire</option>
                            <option value="chef-institution" @selected(old('role') == 'chef-institution')>
                                Chef d’institution
                            </option>
                        </select>
                        @error('role') <div class="text-danger small">{{ $message }}</div> @enderror
                    </div>


                    <!-- Mot de passe -->
                    <div class="mb-4 form-group-modern">
                        <label class="form-label-modern required-field">Mot de passe</label>
                        <input type="password" name="password"
                               class="form-control-modern @error('password') is-invalid @enderror" required>
                        @error('password') <div class="text-danger small">{{ $message }}</div> @enderror
                    </div>

                    <!-- Confirmation -->
                    <div class="mb-4 form-group-modern">
                        <label class="form-label-modern required-field">Confirmation du mot de passe</label>
                        <input type="password" name="password_confirmation"
                               class="form-control-modern" required>
                    </div>

                    <!-- Bouton -->
                    <button type="submit" class="btn btn-primary-modern btn-modern w-100">
                        <i class="bi bi-person-plus me-2"></i> Créer le compte
                    </button>

                </form>
            </div>
        </div>
    </div>
</div>
<style>
    /* ============================
       Styles spécifiques Register
       ============================ */

    .password-wrapper {
        position: relative;
    }

    .password-wrapper .btn-link {
        background: transparent !important;
        border: none !important;
        color: var(--text-muted) !important;
        padding: 0.5rem;
        cursor: pointer;
        transition: color var(--transition-fast);
    }

    .password-wrapper .btn-link:hover {
        color: var(--primary-500) !important;
    }

    /* Carte principale */
    .card-modern {
        animation: fadeInUp 0.6s ease-out;
        max-width: 100%;
    }

    /* Icône d'inscription */
    .icon-container {
        animation: float 3s ease-in-out infinite;
    }

    /* Champs du formulaire */
    .form-control-modern,
    .form-control-modern select {
        border-radius: 0.75rem;
    }

    select.form-control-modern {
        padding-right: 2.5rem;
        cursor: pointer;
    }

    /* Groupes de champs plus aérés */
    .form-group-modern {
        margin-bottom: 1.25rem;
    }

    /* Validation visuelle */
    .form-control-modern.is-valid {
        border-color: var(--success-500);
        box-shadow: 0 0 0 2px rgba(34, 197, 94, 0.15);
    }

    .form-control-modern.is-invalid {
        border-color: var(--danger-500);
        box-shadow: 0 0 0 2px rgba(239, 68, 68, 0.15);
    }

    /* Bouton principal */
    .btn-modern {
        font-weight: 600;
        letter-spacing: 0.02em;
    }

    /* Texte d’aide */
    .form-text {
        font-size: 0.8rem;
        color: var(--text-muted);
    }

    /* Responsive : formulaire long */
    @media (max-width: 768px) {
        .container.py-5 {
            padding-top: 2rem !important;
            padding-bottom: 2rem !important;
        }

        .card-modern {
            padding: 1.5rem !important;
        }

        .form-group-modern {
            margin-bottom: 1rem;
        }
    }
</style>

<script>
document.addEventListener('DOMContentLoaded', function () {

    /* =========================
       TOGGLE PASSWORD
    ========================== */
    const togglePassword = document.getElementById('togglePassword');
    const passwordInput = document.getElementById('password');

    if (togglePassword && passwordInput) {
        togglePassword.addEventListener('click', function () {
            const type = passwordInput.type === 'password' ? 'text' : 'password';
            passwordInput.type = type;

            const icon = this.querySelector('i');
            icon.className = type === 'password'
                ? 'bi bi-eye'
                : 'bi bi-eye-slash';
        });
    }

    /* =========================
       FORM VALIDATION
    ========================== */
    const form = document.getElementById('registerForm');

    const fields = {
        first_name: document.getElementById('first_name'),
        last_name: document.getElementById('last_name'),
        email: document.getElementById('email'),
        mobile: document.getElementById('mobile'),
        institution: document.getElementById('institution_id'),
        role: document.getElementById('role'),
        password: document.getElementById('password'),
        password_confirmation: document.getElementById('password_confirmation'),
    };

    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

    function setValidation(field, valid) {
        field.classList.toggle('is-valid', valid);
        field.classList.toggle('is-invalid', !valid);
    }

    function validateField(field, condition) {
        if (!field) return true;
        setValidation(field, condition);
        return condition;
    }

    /* =========================
       SUBMIT HANDLER
    ========================== */
    form.addEventListener('submit', function (e) {
        let isValid = true;

        isValid &= validateField(fields.first_name, fields.first_name.value.trim() !== '');
        isValid &= validateField(fields.last_name, fields.last_name.value.trim() !== '');
        isValid &= validateField(fields.email, emailRegex.test(fields.email.value.trim()));
        isValid &= validateField(fields.mobile, fields.mobile.value.trim().length >= 8);
        isValid &= validateField(fields.institution, fields.institution.value !== '');
        isValid &= validateField(fields.role, fields.role.value !== '');
        isValid &= validateField(fields.password, fields.password.value.length >= 8);
        isValid &= validateField(
            fields.password_confirmation,
            fields.password.value === fields.password_confirmation.value
        );

        if (!isValid) {
            e.preventDefault();

            Swal.fire({
                icon: 'error',
                title: 'Formulaire incomplet',
                text: 'Veuillez vérifier les champs obligatoires.',
                confirmButtonColor: 'var(--primary-500)',
            });

            return;
        }

        /* =========================
           LOADER
        ========================== */
        const submitBtn = form.querySelector('button[type="submit"]');
        submitBtn.disabled = true;
        submitBtn.innerHTML = `
            <span class="spinner-border spinner-border-sm me-2"></span>
            Création du compte...
        `;
    });

    /* =========================
       UX : LABEL FOCUS
    ========================== */
    document.querySelectorAll('.form-control-modern').forEach(input => {
        input.addEventListener('focus', () => {
            input.closest('.form-group-modern')
                 ?.querySelector('.form-label-modern')
                 ?.style.setProperty('color', 'var(--primary-500)');
        });

        input.addEventListener('blur', () => {
            if (!input.value.trim()) {
                input.closest('.form-group-modern')
                     ?.querySelector('.form-label-modern')
                     ?.style.setProperty('color', 'var(--text-secondary)');
            }
        });
    });

});
</script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    const rectorateSwitch = document.getElementById('isRectorate');
    const institutionBlock = document.getElementById('institutionBlock');
    const serviceBlock = document.getElementById('serviceBlock');

    function toggleBlocks() {
        if (rectorateSwitch.checked) {
            institutionBlock.classList.add('d-none');
            serviceBlock.classList.remove('d-none');
        } else {
            institutionBlock.classList.remove('d-none');
            serviceBlock.classList.add('d-none');
        }
    }

    rectorateSwitch.addEventListener('change', toggleBlocks);
    toggleBlocks(); // init au chargement
});
</script>

@endsection
