@extends('layouts.dashboard')

@section('title', __('Usuarios'))

@push('head')
    <style>
        .rt-dash-modal .modal-content {
            border-radius: 24px;
            border: none;
            box-shadow: 0 15px 50px rgba(0,0,0,0.15);
        }
        .rt-dash-modal .modal-header {
            border-bottom: 1px solid rgba(0,0,0,0.04);
            padding: 1.5rem 2rem;
        }
        .rt-ios-input-group {
            position: relative;
            display: flex;
            align-items: center;
        }
        .rt-ios-input-icon {
            position: absolute;
            left: 1rem;
            color: #8e8e93;
            font-size: 1rem;
            z-index: 10;
        }
        .rt-ios-input {
            border-radius: 12px !important;
            border: 1px solid rgba(0,0,0,0.08) !important;
            padding: 0.75rem 1rem 0.75rem 2.8rem !important;
            font-size: 0.95rem !important;
            background-color: #f9f9fb !important;
            transition: all 0.2s;
            height: 48px !important;
            width: 100%;
        }
        .rt-ios-input:focus {
            background-color: #ffffff !important;
            border-color: var(--rt-cherry) !important;
            box-shadow: 0 0 0 4px rgba(185, 24, 48, 0.1) !important;
        }
        .rt-label {
            font-weight: 700;
            font-size: 0.75rem;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            color: #8e8e93;
            margin-bottom: 0.5rem;
            display: block;
        }
        .rt-password-toggle-btn, .rt-password-gen-btn {
            position: absolute;
            right: 0.75rem;
            background: transparent;
            border: none;
            color: #8e8e93;
            cursor: pointer;
            z-index: 10;
            padding: 0.5rem;
            transition: all 0.2s;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .rt-password-gen-btn {
            right: 2.75rem;
        }
        .rt-password-toggle-btn:hover, .rt-password-gen-btn:hover { color: var(--rt-cherry); transform: scale(1.1); }
    </style>
@endpush

@section('content')
    @include('dashboard.partials.bootstrap-table-assets')

    <div class="container-fluid px-0">
        <div class="d-flex align-items-center justify-content-between flex-wrap gap-3 mb-4">
            <div>
                <h1 class="h3 mb-1 text-dark font-weight-bold">{{ __('Usuarios') }}</h1>
                <p class="text-muted mb-0 small">{{ __('Cuentas registradas en la plataforma (incluye archivados lógicos).') }}</p>
            </div>
            <div class="rt-dash-toolbar-actions d-flex flex-wrap align-items-center">
                @can('create', \App\Models\User::class)
                    <button
                        type="button"
                        class="btn btn-sm btn-primary shadow-sm"
                        data-toggle="modal"
                        data-target="#createUserModal"
                    >
                        <i class="bi bi-person-plus" aria-hidden="true"></i>{{ __('Nuevo usuario') }}
                    </button>
                @endcan
                <a
                    href="{{ url()->full() }}"
                    class="btn btn-sm btn-outline-secondary shadow-sm"
                    title="{{ __('Actualizar listado') }}"
                >
                    <i class="bi bi-arrow-clockwise" aria-hidden="true"></i>{{ __('Actualizar') }}
                </a>
            </div>
        </div>

        <div class="card shadow-sm border-0">
            <div class="card-body p-0">
                @if ($users->isEmpty())
                    <div class="p-5 text-center text-muted">
                        <i class="bi bi-people mb-3 opacity-25 d-block" style="font-size: 2rem" aria-hidden="true"></i>
                        <p class="mb-0">{{ __('No hay usuarios que coincidan.') }}</p>
                    </div>
                @else
                    <div class="table-responsive">
                        <table
                            class="table table-hover align-middle mb-0"
                            data-toggle="table"
                            data-locale="es-ES"
                            data-search="true"
                            data-show-columns="true"
                            data-pagination="true"
                            data-page-size="10"
                            data-page-list='[10, 20, 50, 100, "all"]'
                            data-pagination-pre-text="{{ __('Anterior') }}"
                            data-pagination-next-text="{{ __('Siguiente') }}"
                        >
                            <thead class="table-light">
                                <tr>
                                    <th data-field="id" data-sortable="true" class="ps-4">{{ __('ID') }}</th>
                                    <th data-field="name" data-sortable="true">{{ __('Nombre') }}</th>
                                    <th data-field="email" data-sortable="true">{{ __('Correo') }}</th>
                                    <th data-field="role" data-sortable="true">{{ __('Rol') }}</th>
                                    <th data-field="status" data-sortable="true">{{ __('Estado cuenta') }}</th>
                                    <th data-field="created" data-sortable="true">{{ __('Registro') }}</th>
                                    <th data-field="actions" data-sortable="false" data-switchable="false" class="pe-4 text-center text-nowrap">{{ __('Acciones') }}</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach ($users as $u)
                                    <tr @class(['table-secondary' => $u->trashed()])>
                                        <td class="ps-4 small text-muted">#{{ $u->id }}</td>
                                        <td class="font-weight-bold text-dark">{{ $u->name }}</td>
                                        <td class="small">{{ $u->email }}</td>
                                        <td><span class="badge badge-light border">{{ $u->role?->slug ?? '—' }}</span></td>
                                        <td>
                                            @if ($u->trashed())
                                                <span class="badge badge-dark">{{ __('Archivado') }}</span>
                                            @elseif ($u->hasRole(\App\Models\Role::SLUG_ORGANIZADOR))
                                                @switch($u->account_status)
                                                    @case(\App\Enums\AccountStatus::AwaitingReview)
                                                        <span class="badge badge-warning text-dark">{{ __('En revisión') }}</span>
                                                        @break
                                                    @case(\App\Enums\AccountStatus::Approved)
                                                        <span class="badge badge-success">{{ __('Aprobado') }}</span>
                                                        @break
                                                    @case(\App\Enums\AccountStatus::Rejected)
                                                        <span class="badge badge-danger">{{ __('Rechazado') }}</span>
                                                        @break
                                                    @case(\App\Enums\AccountStatus::Inactive)
                                                        <span class="badge badge-secondary">{{ __('Inactivo') }}</span>
                                                        @break
                                                @endswitch
                                            @else
                                                <span class="badge badge-light border text-muted">{{ __('N/A') }}</span>
                                            @endif
                                        </td>
                                        <td class="small text-muted text-nowrap">
                                            {{ $u->created_at?->timezone(config('app.timezone'))->format('Y-m-d H:i') }}
                                        </td>
                                        <td class="pe-4 text-center">
                                            @php
                                                $archived = $u->trashed();
                                                $isOrganizer = $u->hasRole(\App\Models\Role::SLUG_ORGANIZADOR);
                                                $canManageOrg = auth()->user()?->can('manage-organizer-requests');
                                            @endphp
                                            <div class="d-inline-flex flex-wrap align-items-center justify-content-center">
                                                @can('update', $u)
                                                    @if (! $archived)
                                                        <button
                                                            type="button"
                                                            class="btn btn-sm btn-outline-primary mr-1 mb-1 js-dashboard-user-edit-sw"
                                                            data-href="{{ route('dashboard.users.edit', $u) }}"
                                                            data-name="{{ e($u->name) }}"
                                                            data-email="{{ e($u->email) }}"
                                                            title="{{ __('Editar usuario') }}"
                                                        >
                                                            <i class="bi bi-pencil-square mr-1" aria-hidden="true"></i>{{ __('Editar') }}
                                                        </button>
                                                    @endif
                                                @endcan
                                                <a
                                                    href="mailto:{{ $u->email }}"
                                                    class="btn btn-sm btn-outline-secondary mr-1 mb-1"
                                                    title="{{ __('Enviar correo') }}"
                                                >
                                                    <i class="bi bi-envelope mr-1" aria-hidden="true"></i>{{ __('Correo') }}
                                                </a>

                                                @if ($canManageOrg && $isOrganizer && ! $archived)
                                                    @if ($u->account_status === \App\Enums\AccountStatus::AwaitingReview)
                                                        <form method="post" action="{{ route('dashboard.organizers.approve', $u) }}" class="d-inline mr-1 mb-1 js-organizer-approve-users">
                                                            @csrf
                                                            <button type="submit" class="btn btn-sm btn-success" title="{{ __('Aprobar organizador') }}">
                                                                <i class="bi bi-check-lg mr-1" aria-hidden="true"></i>{{ __('Aprobar') }}
                                                            </button>
                                                        </form>
                                                        <button
                                                            type="button"
                                                            class="btn btn-sm btn-outline-danger mr-1 mb-1"
                                                            data-toggle="modal"
                                                            data-target="#rejectUserModal"
                                                            data-user-name="{{ $u->name }}"
                                                            data-reject-url="{{ route('dashboard.organizers.reject', $u) }}"
                                                        >
                                                            <i class="bi bi-x-lg mr-1" aria-hidden="true"></i>{{ __('Rechazar') }}
                                                        </button>
                                                    @endif

                                                    @if ($u->id !== auth()->id())
                                                        @if ($u->account_status === \App\Enums\AccountStatus::Inactive)
                                                            <form method="post" action="{{ route('dashboard.organizers.activate', $u) }}" class="d-inline mr-1 mb-1 js-organizer-activate-users">
                                                                @csrf
                                                                <button type="submit" class="btn btn-sm btn-success" title="{{ __('Reactivar cuenta') }}">
                                                                    <i class="bi bi-arrow-counterclockwise mr-1" aria-hidden="true"></i>{{ __('Activar cuenta') }}
                                                                </button>
                                                            </form>
                                                        @elseif (in_array($u->account_status, [\App\Enums\AccountStatus::Approved, \App\Enums\AccountStatus::AwaitingReview, \App\Enums\AccountStatus::Rejected], true))
                                                            <form method="post" action="{{ route('dashboard.organizers.deactivate', $u) }}" class="d-inline mr-1 mb-1 js-organizer-deactivate-users">
                                                                @csrf
                                                                <button type="submit" class="btn btn-sm btn-outline-secondary" title="{{ __('Marcar inactivo') }}">
                                                                    <i class="bi bi-eye-slash mr-1" aria-hidden="true"></i>{{ __('Desactivar') }}
                                                                </button>
                                                            </form>
                                                        @endif

                                                        <form
                                                            method="post"
                                                            action="{{ route('dashboard.organizers.archive', $u) }}"
                                                            class="d-inline js-soft-archive mr-1 mb-1"
                                                            data-confirm="{{ __('¿Archivar este usuario? No se pierden datos históricos.') }}"
                                                        >
                                                            @csrf
                                                            <button type="submit" class="btn btn-sm btn-outline-danger" title="{{ __('Archivar usuario') }}">
                                                                <i class="bi bi-archive mr-1" aria-hidden="true"></i>{{ __('Eliminar') }}
                                                            </button>
                                                        </form>
                                                    @endif
                                                @endif

                                                @if ($canManageOrg && $isOrganizer && $archived)
                                                    <form method="post" action="{{ route('dashboard.organizers.restore', $u->id) }}" class="d-inline mb-1 js-organizer-restore-users">
                                                        @csrf
                                                        <button type="submit" class="btn btn-sm btn-success" title="{{ __('Reactivar usuario') }}">
                                                            <i class="bi bi-arrow-counterclockwise mr-1" aria-hidden="true"></i>{{ __('Activar') }}
                                                        </button>
                                                    </form>
                                                @endif
                                            </div>
                                        </td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                @endif
            </div>
        </div>
    </div>

    @can('create', \App\Models\User::class)
        <div class="modal fade rt-dash-modal" id="createUserModal" tabindex="-1" role="dialog" aria-labelledby="createUserModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg modal-dialog-scrollable" role="document">
                <form method="post" action="{{ route('dashboard.users.store') }}" id="dashboard-create-user-form" autocomplete="off" class="modal-content">
                    @csrf
                    <div class="modal-header align-items-center">
                        <div>
                            <h5 class="modal-title font-weight-bold mb-0" id="createUserModalLabel">{{ __('Nuevo usuario') }}</h5>
                            <p class="text-muted small mb-0 mt-1">{{ __('Define credenciales y rol. Si eliges organizador, completa también los datos de la organización.') }}</p>
                        </div>
                        <button type="button" class="close" data-dismiss="modal" aria-label="{{ __('Cerrar') }}">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body p-4 pt-3">
                        <div class="row g-3">
                            <div class="col-md-6 mb-3">
                                <label class="rt-label" for="cu-name">{{ __('Nombre completo') }}</label>
                                <div class="rt-ios-input-group">
                                    <i class="fas fa-user rt-ios-input-icon"></i>
                                    <input type="text" name="name" id="cu-name" class="form-control rt-ios-input rt-ios-input-with-icon @error('name') is-invalid @enderror" value="{{ old('name') }}" required maxlength="255">
                                </div>
                                @error('name')<div class="invalid-feedback d-block">{{ $message }}</div>@enderror
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="rt-label" for="cu-email">{{ __('Correo electrónico') }}</label>
                                <div class="rt-ios-input-group">
                                    <i class="fas fa-envelope rt-ios-input-icon"></i>
                                    <input type="email" name="email" id="cu-email" class="form-control rt-ios-input rt-ios-input-with-icon @error('email') is-invalid @enderror" value="{{ old('email') }}" required maxlength="255">
                                </div>
                                @error('email')<div class="invalid-feedback d-block">{{ $message }}</div>@enderror
                            </div>
                            </div>
                            <div class="row g-3">
                            <div class="col-md-6 mb-3">
                                <label class="rt-label" for="cu-password">{{ __('Contraseña') }}</label>
                                <div class="rt-ios-input-group">
                                    <i class="fas fa-key rt-ios-input-icon"></i>
                                    <input type="password" name="password" id="cu-password" class="form-control rt-ios-input rt-ios-input-with-icon @error('password') is-invalid @enderror" required autocomplete="new-password">
                                    <button type="button" class="rt-password-gen-btn" data-target="cu-password" title="{{ __('Generar segura') }}">
                                        <i class="fas fa-magic"></i>
                                    </button>
                                    <button type="button" class="rt-password-toggle-btn" data-target="cu-password">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                </div>
                                @error('password')<div class="invalid-feedback d-block">{{ $message }}</div>@enderror
                                <small class="form-text text-muted" style="font-size: 0.65rem;">{{ __('Mínimo 8 caracteres, mayúscula y número.') }}</small>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="rt-label" for="cu-password-confirmation">{{ __('Confirmar contraseña') }}</label>
                                <div class="rt-ios-input-group">
                                    <i class="fas fa-shield-alt rt-ios-input-icon"></i>
                                    <input type="password" name="password_confirmation" id="cu-password-confirmation" class="form-control rt-ios-input rt-ios-input-with-icon" required autocomplete="new-password">
                                    <button type="button" class="rt-password-toggle-btn" data-target="cu-password-confirmation">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                </div>
                            </div>

                        </div>
                        <div class="form-group mb-4">
                            <label class="rt-label" for="dashboard-create-user-role">{{ __('Rol en la plataforma') }}</label>
                            <select
                                name="role_id"
                                id="dashboard-create-user-role"
                                class="custom-select rt-ios-input @error('role_id') is-invalid @enderror"
                                style="padding-left: 1rem !important;"
                                required
                            >
                                <option value="" disabled @selected(old('role_id') === null)>{{ __('Selecciona un rol…') }}</option>
                                @foreach ($roles as $r)
                                    <option
                                        value="{{ $r->id }}"
                                        data-slug="{{ $r->slug }}"
                                        @selected((string) old('role_id') === (string) $r->id)
                                    >{{ $r->name }}</option>
                                @endforeach
                            </select>
                            @error('role_id')<div class="invalid-feedback d-block">{{ $message }}</div>@enderror
                        </div>

                        <div class="js-organizer-fields-dashboard-user border-0 rounded-4 p-4 bg-light mt-2" style="display: none; border-radius: 16px;">
                            <div class="d-flex align-items-center mb-3">
                                <div class="rounded-circle bg-white d-flex align-items-center justify-content-center mr-2 shadow-sm" style="width: 28px; height: 28px;">
                                    <i class="fas fa-building text-primary fa-xs"></i>
                                </div>
                                <h6 class="small font-weight-bold text-dark mb-0">{{ __('Datos de organizador') }}</h6>
                            </div>
                            <div class="row g-3">
                                <div class="col-md-6 mb-3">
                                    <label class="rt-label" for="cu-org">{{ __('Organización') }}</label>
                                    <input type="text" name="organization_name" id="cu-org" class="form-control rt-ios-input @error('organization_name') is-invalid @enderror" value="{{ old('organization_name') }}" maxlength="255">
                                    @error('organization_name')<div class="invalid-feedback d-block">{{ $message }}</div>@enderror
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="rt-label" for="cu-phone">{{ __('Teléfono') }}</label>
                                    <input type="text" name="phone" id="cu-phone" class="form-control rt-ios-input @error('phone') is-invalid @enderror" value="{{ old('phone') }}" maxlength="32">
                                    @error('phone')<div class="invalid-feedback d-block">{{ $message }}</div>@enderror
                                </div>
                            </div>
                            <div class="form-group mb-0">
                                <label class="rt-label" for="cu-event-type">{{ __('Tipo principal de evento') }}</label>
                                <select name="primary_event_type" id="cu-event-type" class="custom-select rt-ios-input @error('primary_event_type') is-invalid @enderror" style="padding-left: 1rem !important;">
                                    <option value="">{{ __('Selecciona…') }}</option>
                                    @foreach (\App\Enums\OrganizerPrimaryEventType::cases() as $pet)
                                        <option value="{{ $pet->value }}" @selected(old('primary_event_type') === $pet->value)>{{ $pet->label() }}</option>
                                    @endforeach
                                </select>
                                @error('primary_event_type')<div class="invalid-feedback d-block">{{ $message }}</div>@enderror
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer border-top-0 bg-white p-4">
                        <button type="button" class="btn btn-light border px-4 py-2" style="border-radius: 12px;" data-dismiss="modal">{{ __('Cancelar') }}</button>
                        <button type="submit" class="btn btn-primary font-weight-bold px-4 py-2 shadow-sm" style="border-radius: 12px;">{{ __('Crear usuario') }}</button>
                    </div>
                </form>
            </div>
        </div>
    @endcan

    @can('manage-organizer-requests')
        <div class="modal fade" id="rejectUserModal" tabindex="-1" role="dialog" aria-labelledby="rejectUserModalLabel" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <form method="post" id="reject-user-form" action="#">
                        @csrf
                        <div class="modal-header">
                            <h5 class="modal-title" id="rejectUserModalLabel">{{ __('Rechazar solicitud') }}</h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="{{ __('Cerrar') }}">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <div class="modal-body">
                            <p class="small text-muted mb-2" id="reject-user-modal-name"></p>
                            <div class="form-group">
                                <label for="reject-user-reason">{{ __('Motivo (obligatorio)') }}</label>
                                <textarea class="form-control" id="reject-user-reason" name="reason" rows="4" required maxlength="2000" placeholder="{{ __('Explica brevemente el motivo del rechazo.') }}"></textarea>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">{{ __('Cancelar') }}</button>
                            <button type="submit" class="btn btn-danger">{{ __('Confirmar rechazo') }}</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    @endcan

    @php
        $rtUsersEditSwalI18n = [
            'intro' => __('Se abrirá el formulario para personalizar nombre, correo, contraseña, rol y datos de organizador si aplica.'),
            'lblName' => __('Nombre'),
            'lblEmail' => __('Correo'),
            'title' => __('Editar usuario'),
            'confirm' => __('Continuar'),
            'cancel' => __('Cancelar'),
        ];
    @endphp
    @push('scripts')
        <script>
            window.rtUsersEditSwalI18n = @json($rtUsersEditSwalI18n);
            document.addEventListener('DOMContentLoaded', function () {
                document.addEventListener('click', function (e) {
                    var btn = e.target.closest('.js-dashboard-user-edit-sw');
                    if (!btn) {
                        return;
                    }
                    e.preventDefault();
                    var href = btn.getAttribute('data-href');
                    var name = btn.getAttribute('data-name') || '';
                    var email = btn.getAttribute('data-email') || '';
                    if (!href) {
                        return;
                    }
                    if (typeof Swal === 'undefined') {
                        window.location.href = href;
                        return;
                    }
                    var t = window.rtUsersEditSwalI18n || {};
                    var swalHtml = '<p class="text-left mb-0">' + (t.intro || '') + '<\/p>' +
                        '<p class="text-left text-muted small mt-2 mb-0"><strong>' + (t.lblName || '') + ':<\/strong> ' + name + '<br><strong>' + (t.lblEmail || '') + ':<\/strong> ' + email + '<\/p>';
                    Swal.fire({
                        icon: 'question',
                        title: t.title || '',
                        html: swalHtml,
                        showCancelButton: true,
                        confirmButtonText: t.confirm || 'OK',
                        cancelButtonText: t.cancel || 'Cancel',
                        confirmButtonColor: '#b91830',
                        cancelButtonColor: '#6c757d',
                        reverseButtons: true,
                        focusCancel: true,
                    }).then(function (r) {
                        if (r.isConfirmed) {
                            window.location.href = href;
                        }
                    });
                });

                function toggleDashboardUserOrganizerFields() {
                    var sel = document.getElementById('dashboard-create-user-role');
                    var wrap = document.querySelector('.js-organizer-fields-dashboard-user');
                    if (!sel || !wrap) {
                        return;
                    }
                    var opt = sel.options[sel.selectedIndex];
                    var slug = opt ? opt.getAttribute('data-slug') : '';
                    wrap.style.display = slug === 'organizador' ? 'block' : 'none';
                }
                var roleSel = document.getElementById('dashboard-create-user-role');
                if (roleSel) {
                    roleSel.addEventListener('change', toggleDashboardUserOrganizerFields);
                    toggleDashboardUserOrganizerFields();
                }
                @if ($errors->any() && !$errors->has('reason'))
                    $('#createUserModal').modal('show');
                @endif

                // Toggle Password Visibility
                document.querySelectorAll('.rt-password-toggle-btn').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const targetId = this.getAttribute('data-target');
                        const input = document.getElementById(targetId);
                        const icon = this.querySelector('i');
                        if (input.type === 'password') {
                            input.type = 'text';
                            icon.classList.replace('fa-eye', 'fa-eye-slash');
                        } else {
                            input.type = 'password';
                            icon.classList.replace('fa-eye-slash', 'fa-eye');
                        }
                    });
                });

                // Generate Secure Password
                document.querySelectorAll('.rt-password-gen-btn').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const targetId = this.getAttribute('data-target');
                        const input = document.getElementById(targetId);
                        const confirmInput = document.getElementById(targetId + '-confirmation');
                        
                        const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+";
                        let pass = "";
                        pass += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[Math.floor(Math.random() * 26)];
                        pass += "0123456789"[Math.floor(Math.random() * 10)];
                        for (let i = 0; i < 10; i++) {
                            pass += chars[Math.floor(Math.random() * chars.length)];
                        }
                        pass = pass.split('').sort(() => 0.5 - Math.random()).join('');
                        
                        input.value = pass;
                        input.type = 'text';
                        if (confirmInput) confirmInput.value = pass;
                        
                        const toggleBtn = this.nextElementSibling;
                        if (toggleBtn) toggleBtn.querySelector('i').classList.replace('fa-eye', 'fa-eye-slash');
                    });
                });

                document.querySelectorAll('form.js-soft-archive').forEach(function (form) {
                    form.addEventListener('submit', function (e) {
                        e.preventDefault();
                        var msg = form.getAttribute('data-confirm') || '';
                        if (!msg) {
                            form.submit();
                            return;
                        }
                        if (typeof Swal === 'undefined') {
                            if (confirm(msg)) {
                                form.submit();
                            }
                            return;
                        }
                        Swal.fire({
                            icon: 'warning',
                            title: @json(__('Confirmar')),
                            text: msg,
                            showCancelButton: true,
                            confirmButtonText: @json(__('Sí, continuar')),
                            cancelButtonText: @json(__('Cancelar')),
                            confirmButtonColor: '#b91830',
                            cancelButtonColor: '#6c757d',
                        }).then(function (r) {
                            if (r.isConfirmed) {
                                form.submit();
                            }
                        });
                    });
                });

                if ($('#rejectUserModal').length) {
                    $('#rejectUserModal').on('show.bs.modal', function (event) {
                        var button = $(event.relatedTarget);
                        var url = button.data('reject-url');
                        var name = button.data('user-name');
                        var form = document.getElementById('reject-user-form');
                        if (form && url) {
                            form.action = url;
                        }
                        var el = document.getElementById('reject-user-modal-name');
                        if (el) {
                            el.textContent = name || '';
                        }
                        var ta = document.getElementById('reject-user-reason');
                        if (ta) {
                            ta.value = '';
                        }
                    });
                }

                function swalConfirm(form, opts) {
                    if (typeof Swal === 'undefined') {
                        form.submit();
                        return;
                    }
                    Swal.fire(opts).then(function (r) {
                        if (r.isConfirmed) {
                            form.submit();
                        }
                    });
                }

                document.querySelectorAll('form.js-organizer-approve-users').forEach(function (form) {
                    form.addEventListener('submit', function (e) {
                        e.preventDefault();
                        swalConfirm(form, {
                            icon: 'question',
                            title: @json(__('¿Aprobar a este organizador?')),
                            showCancelButton: true,
                            confirmButtonText: @json(__('Sí, aprobar')),
                            cancelButtonText: @json(__('Cancelar')),
                            confirmButtonColor: '#38c172',
                            cancelButtonColor: '#6c757d',
                        });
                    });
                });

                document.querySelectorAll('form.js-organizer-activate-users').forEach(function (form) {
                    form.addEventListener('submit', function (e) {
                        e.preventDefault();
                        swalConfirm(form, {
                            icon: 'question',
                            title: @json(__('¿Reactivar esta cuenta (estado aprobado)?')),
                            showCancelButton: true,
                            confirmButtonText: @json(__('Sí, reactivar')),
                            cancelButtonText: @json(__('Cancelar')),
                            confirmButtonColor: '#38c172',
                        });
                    });
                });

                document.querySelectorAll('form.js-organizer-deactivate-users').forEach(function (form) {
                    form.addEventListener('submit', function (e) {
                        e.preventDefault();
                        swalConfirm(form, {
                            icon: 'warning',
                            title: @json(__('Desactivar cuenta')),
                            text: @json(__('¿Marcar la cuenta como inactiva?')),
                            showCancelButton: true,
                            confirmButtonText: @json(__('Sí, desactivar')),
                            cancelButtonText: @json(__('Cancelar')),
                            confirmButtonColor: '#6c757d',
                        });
                    });
                });

                document.querySelectorAll('form.js-organizer-restore-users').forEach(function (form) {
                    form.addEventListener('submit', function (e) {
                        e.preventDefault();
                        swalConfirm(form, {
                            icon: 'question',
                            title: @json(__('¿Reactivar este usuario archivado?')),
                            showCancelButton: true,
                            confirmButtonText: @json(__('Sí, reactivar')),
                            cancelButtonText: @json(__('Cancelar')),
                            confirmButtonColor: '#38c172',
                        });
                    });
                });
            });
        </script>
    @endpush
@endsection
