@php
    use App\Enums\NocTrackingStatus;
    use App\Enums\WorkAssignmentStatus;
    use App\Enums\WorkInternalStatus;
    use App\Enums\WorkPriority;
    use App\Enums\WorkStatus;
@endphp

<div class="flex w-full flex-col gap-6">
    @include('components.catalog.toast', ['showToast' => $showToast, 'toastType' => $toastType, 'toastMessage' => $toastMessage, 'toastSeq' => $toastSeq])

    <div class="relative overflow-hidden rounded-2xl border border-[var(--setel-card-border)] bg-gradient-to-br from-[var(--setel-content-bg)] via-[var(--setel-card)]/30 to-[var(--setel-primary)]/5 p-1 shadow-sm">
        <div class="flex flex-col gap-6 rounded-[0.9rem] bg-[var(--setel-content-bg)] px-5 py-6 sm:flex-row sm:items-stretch sm:justify-between sm:gap-8 sm:px-8 sm:py-7">
            <div class="flex min-w-0 flex-1 items-start gap-5">
                <div class="flex h-24 w-20 shrink-0 flex-col items-center justify-center rounded-xl bg-[var(--setel-primary)]/10 text-[var(--setel-primary)] ring-1 ring-[var(--setel-primary)]/20">
                    <span class="text-[10px] font-semibold uppercase tracking-wider text-[var(--setel-text-muted)]">{{ \Illuminate\Support\Str::ucfirst($this->todayWeekday) }}</span>
                    <span class="text-3xl font-bold tabular-nums leading-none">{{ $this->todayDayNumber }}</span>
                    <span class="mt-1 px-1 text-center text-[11px] font-medium leading-tight text-[var(--setel-text)]">{{ $this->todayMonthYear }}</span>
                </div>
                <div class="min-w-0 flex-1 pt-1">
                    <p class="text-xs font-semibold uppercase tracking-wide text-[var(--setel-text-muted)]">Operación del día</p>
                    <p class="mt-1 text-lg font-semibold capitalize leading-snug text-[var(--setel-text)] sm:text-xl">{{ $this->todayHeading }}</p>
                    <p class="mt-2 text-sm text-[var(--setel-text-muted)]">Fecha calendario: <span class="font-mono text-[var(--setel-text)]">{{ $this->todayIso }}</span></p>
                </div>
            </div>
                <div class="flex shrink-0 flex-col items-stretch justify-center gap-3 sm:items-end">
                @if (! $this->withinOperationsWindow)
                    <span class="setel-badge setel-badge--neutral w-fit text-xs">Fuera de horario</span>
                @elseif ($this->todayHasOpenAssignments)
                    <span class="setel-badge w-fit text-xs bg-emerald-100 text-emerald-900 dark:bg-emerald-950/50 dark:text-emerald-200">Lote abierto</span>
                @else
                    <span class="setel-badge setel-badge--neutral w-fit text-xs">Sin asignaciones activas hoy</span>
                @endif
                <div class="flex flex-wrap items-center gap-2 sm:justify-end">
                    <button
                        type="button"
                        wire:click="openHelpModal"
                        class="inline-flex size-10 items-center justify-center rounded-full border border-[var(--setel-card-border)] bg-[var(--setel-card)] text-base font-bold text-[var(--setel-primary)] shadow-sm hover:bg-[var(--setel-content-bg)]"
                        title="Ayuda"
                        aria-label="Ayuda e instrucciones"
                    >
                        ?
                    </button>
                </div>
            </div>
        </div>
    </div>

    <div class="setel-card overflow-hidden">
        <div class="flex flex-wrap items-center justify-between gap-3 border-b border-[var(--setel-card-border)] px-5 py-4">
            <h2 class="text-lg font-semibold setel-text-primary">Asignaciones</h2>
        </div>

        <div class="flex border-b border-[var(--setel-card-border)] px-5">
            <button
                type="button"
                wire:click="$set('activeTab', 'assign')"
                class="min-w-0 flex-1 border-b-2 px-3 py-3 text-sm font-medium transition-colors sm:flex-none sm:px-5 {{ $activeTab === 'assign' ? 'border-[var(--setel-primary)] text-[var(--setel-primary)]' : 'border-transparent text-[var(--setel-text-muted)] hover:text-[var(--setel-text)]' }}"
            >
                Asignar
            </button>
            <button
                type="button"
                wire:click="$set('activeTab', 'history')"
                class="min-w-0 flex-1 border-b-2 px-3 py-3 text-sm font-medium transition-colors sm:flex-none sm:px-5 {{ $activeTab === 'history' ? 'border-[var(--setel-primary)] text-[var(--setel-primary)]' : 'border-transparent text-[var(--setel-text-muted)] hover:text-[var(--setel-text)]' }}"
            >
                Historial
            </button>
        </div>

        @if ($activeTab === 'assign')
            <div class="space-y-4 border-b border-[var(--setel-card-border)] bg-[var(--setel-content-bg)] px-5 py-4">
                @if (! $this->withinOperationsWindow)
                    <p class="text-sm text-[var(--setel-text)]">
                        <span class="font-semibold text-slate-700 dark:text-slate-300">Fuera de horario</span>
                        · asignar y retirar del día solo entre <strong>{{ config('work_coordination.operations_start') }}</strong> y <strong>{{ config('work_coordination.operations_end') }}</strong> (zona {{ config('app.timezone') }}).
                    </p>
                @elseif ($this->todayHasOpenAssignments)
                    <p class="text-sm text-[var(--setel-text)]">
                        <span class="font-semibold text-emerald-700 dark:text-emerald-400">Lote abierto</span>
                        · hay OT cuya última bitácora del día es <strong>Asignado</strong>. Use <strong>Lotes por asignar</strong> o <strong>Trabajos de hoy</strong> debajo.
                    </p>
                @else
                    <p class="text-sm text-[var(--setel-text-muted)]">
                        Aún no hay OT con asignación activa en la ventana de hoy (00:00–{{ config('work_coordination.operations_end') }}). En horario hábil, abra <strong>Lotes por asignar</strong>, marque OT y asigne técnico.
                    </p>
                @endif
            </div>

            <div class="setel-users-filter-strip border-b border-[var(--setel-card-border)] px-5 py-4">
                <p class="mb-3 text-xs font-semibold uppercase tracking-wide text-[var(--setel-text-muted)]">Filtros (proyecto → tipo)</p>
                <div class="flex flex-col gap-4 sm:flex-row sm:flex-wrap sm:items-end">
                    <div class="setel-users-filter-field min-w-0 w-full sm:max-w-xs">
                        <label class="setel-users-filter-label" for="coord-filter-proj">Proyecto</label>
                        <select id="coord-filter-proj" class="setel-input w-full py-0 pe-8" wire:model.live="filterAssignProjectId">
                            <option value="">Todos los proyectos</option>
                            @foreach ($this->projectsForFilters as $proj)
                                <option value="{{ $proj->id }}">{{ $proj->name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="setel-users-filter-field min-w-0 w-full sm:max-w-xs">
                        <label class="setel-users-filter-label" for="coord-filter-type">Tipo de trabajo</label>
                        <select
                            id="coord-filter-type"
                            class="setel-input w-full py-0 pe-8"
                            wire:model.live="filterAssignWorkTypeId"
                            @disabled(! $filterAssignProjectId)
                        >
                            <option value="">{{ $filterAssignProjectId ? 'Todos los tipos del proyecto' : 'Elija proyecto primero' }}</option>
                            @foreach ($this->assignFilterWorkTypes as $wt)
                                <option value="{{ $wt->id }}">{{ $wt->name }}</option>
                            @endforeach
                        </select>
                    </div>
                </div>
            </div>

            <div class="flex border-b border-[var(--setel-card-border)] bg-[var(--setel-content-bg)] px-5">
                <button
                    type="button"
                    wire:click="$set('assignSubTab', 'lote')"
                    class="min-w-0 flex-1 border-b-2 px-3 py-3 text-sm font-medium transition-colors sm:flex-none sm:px-6 {{ $assignSubTab === 'lote' ? 'border-[var(--setel-primary)] text-[var(--setel-primary)]' : 'border-transparent text-[var(--setel-text-muted)] hover:text-[var(--setel-text)]' }}"
                >
                    Lotes por asignar
                </button>
                <button
                    type="button"
                    wire:click="$set('assignSubTab', 'quitar')"
                    class="min-w-0 flex-1 border-b-2 px-3 py-3 text-sm font-medium transition-colors sm:flex-none sm:px-6 {{ $assignSubTab === 'quitar' ? 'border-[var(--setel-primary)] text-[var(--setel-primary)]' : 'border-transparent text-[var(--setel-text-muted)] hover:text-[var(--setel-text)]' }}"
                >
                    Trabajos de hoy
                </button>
            </div>

            @if ($assignSubTab === 'lote')
                <div class="setel-users-filter-strip border-b border-[var(--setel-card-border)] px-5 py-4">
                    <div class="flex flex-col gap-4 lg:flex-row lg:flex-wrap lg:items-end">
                        <div class="setel-users-filter-field w-full min-w-0 lg:max-w-md lg:flex-1">
                            @include('livewire.works.partials.assignment-day-technician-picker')
                        </div>
                        <div class="setel-users-filter-field flex w-full min-w-0 items-end lg:w-auto">
                            <button
                                type="button"
                                class="setel-btn-primary h-[2.5rem] w-full px-4 text-sm lg:w-auto"
                                wire:click="requestAssignConfirm"
                                wire:loading.attr="disabled"
                                wire:target="requestAssignConfirm,confirmAssignSelection"
                                @disabled(! $this->withinOperationsWindow)
                            >
                                <span wire:loading.remove wire:target="confirmAssignSelection">Asignar selección</span>
                                <span wire:loading wire:target="confirmAssignSelection">Guardando…</span>
                            </button>
                        </div>
                    </div>
                    @error('selectedWorkIds')
                        <p class="mt-2 text-sm text-red-600">{{ $message }}</p>
                    @enderror
                </div>

                <section class="border-b border-[var(--setel-card-border)] px-5 py-6">
                    <div class="flex flex-col gap-2 sm:flex-row sm:items-end sm:justify-between">
                        <div>
                            <h3 class="text-base font-semibold text-[var(--setel-text)]">Sin asignar hoy</h3>
                            <p class="mt-1 text-sm text-[var(--setel-text-muted)]">Solo interno pendiente u observado; sin asignación activa hoy (última bitácora del día distinta de «Asignado»).</p>
                        </div>
                        <span class="setel-badge setel-badge--neutral w-fit text-xs">{{ $this->worksPendingToday->count() }} OT</span>
                    </div>
                    @if ($this->worksPendingToday->count() >= 500)
                        <p class="mt-3 text-xs text-amber-700 dark:text-amber-400">Se muestran como máximo 500 resultados. Use proyecto y tipo para acotar.</p>
                    @endif
                    <div class="setel-table-wrap mt-4 max-w-full overflow-x-auto" wire:loading.class="opacity-60">
                        <table class="setel-table min-w-[1180px]">
                            <thead>
                                <tr>
                                    <th class="w-[44px] text-center"><span class="sr-only">Seleccionar</span></th>
                                    <th>OT</th>
                                    <th>Proyecto</th>
                                    <th>Sitio</th>
                                    <th>Tipo</th>
                                    <th class="text-center">Estado interno</th>
                                    <th class="text-center">Estado externo</th>
                                    <th class="text-center">Bitácora hoy</th>
                                    <th class="w-[52px] text-center">
                                        <span class="sr-only">Resumen</span>
                                        <flux:icon.eye class="mx-auto size-4 text-[var(--setel-text-muted)]" aria-hidden="true" />
                                    </th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse ($this->worksPendingToday as $work)
                                    <tr wire:key="coord-pend-{{ $work->id }}">
                                        <td class="text-center">
                                            <input
                                                type="checkbox"
                                                class="size-4 rounded border-[var(--setel-card-border)]"
                                                wire:model.live="selectedWorkIds"
                                                value="{{ $work->id }}"
                                                @disabled(! $this->withinOperationsWindow)
                                            />
                                        </td>
                                        <td class="font-mono font-semibold text-[var(--setel-text)]">{{ $work->ot }}</td>
                                        <td class="text-sm text-[var(--setel-text-muted)]">{{ $work->site?->project?->name ?? '—' }}</td>
                                        <td class="text-sm">
                                            <span class="font-medium">{{ $work->site?->code }}</span>
                                            <span class="mt-0.5 block truncate text-[var(--setel-text-muted)]">{{ $work->site?->name }}</span>
                                        </td>
                                        <td class="text-sm text-[var(--setel-text)]">{{ $work->workType?->name }}</td>
                                        <td class="text-center">
                                            <span class="{{ WorkInternalStatus::tryFrom($work->internal_status)?->badgeClass() ?? 'setel-badge setel-badge--neutral' }} text-xs">{{ WorkInternalStatus::tryFrom($work->internal_status)?->label() ?? $work->internal_status }}</span>
                                        </td>
                                        <td class="text-center">
                                            <span class="{{ WorkStatus::tryFrom($work->work_status)?->badgeClass() ?? 'setel-badge setel-badge--neutral' }} text-xs">{{ WorkStatus::tryFrom($work->work_status)?->label() ?? $work->work_status }}</span>
                                        </td>
                                        <td class="text-center">
                                            <span class="text-xs text-[var(--setel-text-muted)]" title="No está en el lote activo de hoy">—</span>
                                        </td>
                                        <td class="text-center">
                                            <button
                                                type="button"
                                                class="setel-btn-secondary inline-flex size-9 items-center justify-center p-0 text-xs"
                                                wire:click="openWorkPreview({{ $work->id }})"
                                                title="Resumen"
                                                aria-label="Resumen de la OT"
                                            >
                                                <flux:icon.eye class="size-3.5 shrink-0" />
                                            </button>
                                        </td>
                                    </tr>
                                @empty
                                    <tr>
                                        <td colspan="9" class="py-10 text-center text-sm text-[var(--setel-text-muted)]">No hay OT que coincidan con los filtros.</td>
                                    </tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                </section>
            @else
                <div class="setel-users-filter-strip border-b border-[var(--setel-card-border)] px-5 py-4">
                    <div class="flex flex-col gap-4 lg:flex-row lg:flex-wrap lg:items-end">
                        <div class="setel-users-filter-field w-full min-w-0 lg:max-w-md lg:flex-1">
                            @include('livewire.works.partials.assignment-day-technician-picker')
                        </div>
                        <div class="setel-users-filter-field flex w-full min-w-0 items-end lg:w-auto">
                            <button
                                type="button"
                                class="setel-btn-primary h-[2.5rem] w-full px-4 text-sm lg:w-auto"
                                wire:click="requestAssignConfirm"
                                wire:loading.attr="disabled"
                                wire:target="requestAssignConfirm,confirmAssignSelection"
                                @disabled(! $this->withinOperationsWindow)
                            >
                                <span wire:loading.remove wire:target="confirmAssignSelection">Reasignar selección</span>
                                <span wire:loading wire:target="confirmAssignSelection">Guardando…</span>
                            </button>
                        </div>
                    </div>
                    @error('selectedUnassignWorkIds')
                        <p class="mt-2 text-sm text-red-600">{{ $message }}</p>
                    @enderror
                    <p class="mt-4 text-sm text-[var(--setel-text-muted)]">Marque una o varias OT asignadas hoy y pulse <strong>Retirar del día (selección)</strong> para quitarlas del lote. Para cambiar de técnico, elija técnico arriba y use <strong>Reasignar selección</strong>.</p>
                    <div class="mt-3 flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-end">
                        <button
                            type="button"
                            class="inline-flex min-h-[2.5rem] items-center justify-center gap-2 rounded-lg border-2 border-amber-600 bg-amber-50 px-5 text-sm font-semibold text-amber-950 hover:bg-amber-100 disabled:cursor-not-allowed disabled:opacity-40 dark:border-amber-500 dark:bg-amber-950/40 dark:text-amber-100 dark:hover:bg-amber-950/70"
                            wire:click="requestBulkUnassignConfirm"
                            wire:loading.attr="disabled"
                            wire:target="requestBulkUnassignConfirm,confirmBulkUnassignFromToday"
                            @disabled(! $this->withinOperationsWindow)
                        >
                            <flux:icon.arrow-uturn-left class="size-4 shrink-0" />
                            <span wire:loading.remove wire:target="confirmBulkUnassignFromToday">Retirar del día (selección)</span>
                            <span wire:loading wire:target="confirmBulkUnassignFromToday">Procesando…</span>
                        </button>
                    </div>
                </div>

                <section class="border-b border-[var(--setel-card-border)] px-5 py-6">
                    <div class="flex flex-col gap-2 sm:flex-row sm:items-end sm:justify-between">
                        <div>
                            <h3 class="text-base font-semibold text-[var(--setel-text)]">Asignadas hoy</h3>
                            <p class="mt-1 text-sm text-[var(--setel-text-muted)]">Mismos filtros de proyecto y tipo. Seleccione filas y use <strong>Reasignar selección</strong> o <strong>Retirar del día</strong> arriba.</p>
                        </div>
                        <span class="setel-badge text-xs bg-sky-100 text-sky-900 dark:bg-sky-950/40 dark:text-sky-100">{{ $this->worksAssignedToday->count() }} OT</span>
                    </div>
                    <div class="setel-table-wrap mt-4 max-w-full overflow-x-auto" wire:loading.class="opacity-60">
                        <table class="setel-table min-w-[1280px]">
                            <thead>
                                <tr>
                                    <th class="w-[44px] text-center"><span class="sr-only">Seleccionar</span></th>
                                    <th>OT</th>
                                    <th>Proyecto</th>
                                    <th>Sitio</th>
                                    <th>Tipo</th>
                                    <th class="text-center">Estado interno</th>
                                    <th class="text-center">Estado externo</th>
                                    <th class="text-center">Bitácora hoy</th>
                                    <th>Técnico</th>
                                    <th>Hora</th>
                                    <th class="w-[52px] text-center">
                                        <span class="sr-only">Resumen</span>
                                        <flux:icon.eye class="mx-auto size-4 text-[var(--setel-text-muted)]" aria-hidden="true" />
                                    </th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse ($this->worksAssignedToday as $work)
                                    @php
                                        $a = $work->assignments->first();
                                    @endphp
                                    <tr wire:key="coord-asg-{{ $work->id }}">
                                        <td class="text-center">
                                            <input
                                                type="checkbox"
                                                class="size-4 rounded border-[var(--setel-card-border)]"
                                                wire:model.live="selectedUnassignWorkIds"
                                                value="{{ $work->id }}"
                                                @disabled(! $this->withinOperationsWindow)
                                            />
                                        </td>
                                        <td class="font-mono font-semibold text-[var(--setel-text)]">{{ $work->ot }}</td>
                                        <td class="text-sm text-[var(--setel-text-muted)]">{{ $work->site?->project?->name ?? '—' }}</td>
                                        <td class="text-sm">
                                            <span class="font-medium">{{ $work->site?->code }}</span>
                                            <span class="mt-0.5 block truncate text-[var(--setel-text-muted)]">{{ $work->site?->name }}</span>
                                        </td>
                                        <td class="text-sm text-[var(--setel-text)]">{{ $work->workType?->name }}</td>
                                        <td class="text-center">
                                            <span class="{{ WorkInternalStatus::tryFrom($work->internal_status)?->badgeClass() ?? 'setel-badge setel-badge--neutral' }} text-xs">{{ WorkInternalStatus::tryFrom($work->internal_status)?->label() ?? $work->internal_status }}</span>
                                        </td>
                                        <td class="text-center">
                                            <span class="{{ WorkStatus::tryFrom($work->work_status)?->badgeClass() ?? 'setel-badge setel-badge--neutral' }} text-xs">{{ WorkStatus::tryFrom($work->work_status)?->label() ?? $work->work_status }}</span>
                                        </td>
                                        <td class="text-center">
                                            @if ($a)
                                                <span class="{{ WorkAssignmentStatus::fromDatabase((string) $a->status)?->badgeClass() ?? 'setel-badge setel-badge--neutral' }} text-xs">{{ WorkAssignmentStatus::fromDatabase((string) $a->status)?->label() ?? $a->status }}</span>
                                            @else
                                                <span class="text-xs text-[var(--setel-text-muted)]">—</span>
                                            @endif
                                        </td>
                                        <td class="text-sm font-medium text-[var(--setel-text)]">{{ $a?->technician?->fullName() ?? $work->technician?->fullName() ?? '—' }}</td>
                                        <td class="text-sm tabular-nums text-[var(--setel-text-muted)]">{{ $a?->recorded_at?->format('H:i') ?? '—' }}</td>
                                        <td class="text-center">
                                            <button
                                                type="button"
                                                class="setel-btn-secondary inline-flex size-9 items-center justify-center p-0 text-xs"
                                                wire:click="openWorkPreview({{ $work->id }})"
                                                title="Resumen"
                                                aria-label="Resumen de la OT"
                                            >
                                                <flux:icon.eye class="size-3.5 shrink-0" />
                                            </button>
                                        </td>
                                    </tr>
                                @empty
                                    <tr>
                                        <td colspan="11" class="py-10 text-center text-sm text-[var(--setel-text-muted)]">Ninguna OT asignada hoy con estos filtros.</td>
                                    </tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                </section>
            @endif
        @else
            <div class="border-b border-[var(--setel-card-border)] bg-[var(--setel-content-bg)] px-5 py-3">
                <p class="text-sm text-[var(--setel-text-muted)]">Por defecto solo se listan las asignaciones del <strong>día de hoy</strong>. Amplíe el rango de fechas si necesita otros días.</p>
            </div>
            <div class="setel-users-filter-strip border-b border-[var(--setel-card-border)] px-5 py-4">
                <p class="mb-3 text-xs font-semibold uppercase tracking-wide text-[var(--setel-text-muted)]">Filtros (proyecto → tipo → sitio → fechas)</p>
                <div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-7">
                    <div class="setel-users-filter-field">
                        <label class="setel-users-filter-label" for="hist-proj">Proyecto</label>
                        <select id="hist-proj" class="setel-input w-full py-0 pe-8" wire:model.live="historyProjectId">
                            <option value="">Todos</option>
                            @foreach ($this->projectsForFilters as $proj)
                                <option value="{{ $proj->id }}">{{ $proj->name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="setel-users-filter-field">
                        <label class="setel-users-filter-label" for="hist-type">Tipo de trabajo</label>
                        <select id="hist-type" class="setel-input w-full py-0 pe-8" wire:model.live="historyWorkTypeId" @disabled(! $historyProjectId)>
                            <option value="">{{ $historyProjectId ? 'Todos los tipos' : 'Elija proyecto' }}</option>
                            @foreach ($this->historyFilterWorkTypes as $type)
                                <option value="{{ $type->id }}">{{ $type->name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="setel-users-filter-field sm:col-span-2 lg:col-span-1">
                        <label class="setel-users-filter-label" for="hist-site">Sitio</label>
                        <select id="hist-site" class="setel-input w-full py-0 pe-8" wire:model.live="historySiteId" @disabled(! $historyProjectId)>
                            <option value="">{{ $historyProjectId ? 'Todos los sitios' : 'Elija proyecto' }}</option>
                            @foreach ($this->historyFilterSites as $site)
                                <option value="{{ $site->id }}">{{ $site->code }} · {{ \Illuminate\Support\Str::limit($site->name, 32) }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="setel-users-filter-field">
                        <label class="setel-users-filter-label" for="hist-from">Desde</label>
                        <input id="hist-from" type="date" class="setel-input w-full" wire:model.live="historyDateFrom" />
                    </div>
                    <div class="setel-users-filter-field">
                        <label class="setel-users-filter-label" for="hist-to">Hasta</label>
                        <input id="hist-to" type="date" class="setel-input w-full" wire:model.live="historyDateTo" />
                    </div>
                    <div class="setel-users-filter-field">
                        <label class="setel-users-filter-label" for="hist-status">Estado asignación</label>
                        <select id="hist-status" class="setel-input w-full py-0 pe-8" wire:model.live="historyAssignmentStatus">
                            <option value="">Todos</option>
                            @foreach ($assignmentStatusCases as $case)
                                <option value="{{ $case->value }}">{{ $case->label() }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="setel-users-filter-field flex items-end">
                        <button type="button" class="setel-btn-secondary h-[2.5rem] w-full px-4 text-sm" wire:click="resetHistoryFilters">Limpiar filtros</button>
                    </div>
                    <div class="setel-users-filter-field">
                        <label class="setel-users-filter-label" for="hist-per">Por página</label>
                        <select id="hist-per" class="setel-input w-full py-0 pe-8" wire:model.live="historyPerPage">
                            <option value="15">15</option>
                            <option value="25">25</option>
                            <option value="50">50</option>
                        </select>
                    </div>
                </div>
            </div>

            <div class="setel-table-wrap max-w-full overflow-x-auto px-5 py-4" wire:loading.class="opacity-60">
                <table class="setel-table min-w-[1320px]">
                    <thead>
                        <tr>
                            <th>Registro</th>
                            <th>Proyecto</th>
                            <th>OT</th>
                            <th>Sitio</th>
                            <th>Tipo</th>
                            <th class="text-center">Estado interno</th>
                            <th class="text-center">Estado externo</th>
                            <th class="text-center">Estado bitácora</th>
                            <th>Técnico</th>
                            <th>Coordinador</th>
                            <th class="w-[52px] text-center">
                                <span class="sr-only">Abrir ficha</span>
                                <flux:icon.eye class="mx-auto size-4 text-[var(--setel-text-muted)]" aria-hidden="true" />
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse ($this->assignmentHistory as $row)
                            <tr wire:key="hist-asg-{{ $row->id }}">
                                <td class="text-sm tabular-nums text-[var(--setel-text)]">{{ $row->recorded_at?->format('d/m/Y H:i') ?? '—' }}</td>
                                <td class="text-sm text-[var(--setel-text-muted)]">{{ $row->work?->site?->project?->name ?? '—' }}</td>
                                <td class="font-mono text-sm font-semibold">{{ $row->work?->ot ?? '—' }}</td>
                                <td class="text-sm">{{ $row->work?->site?->code ?? '—' }}</td>
                                <td class="text-sm text-[var(--setel-text-muted)]">{{ \Illuminate\Support\Str::limit((string) ($row->work?->workType?->name ?? ''), 28) }}</td>
                                <td class="text-center">
                                    @if ($row->work)
                                        <span class="{{ WorkInternalStatus::tryFrom($row->work->internal_status)?->badgeClass() ?? 'setel-badge setel-badge--neutral' }} text-xs">{{ WorkInternalStatus::tryFrom($row->work->internal_status)?->label() ?? $row->work->internal_status }}</span>
                                    @else
                                        <span class="text-xs text-[var(--setel-text-muted)]">—</span>
                                    @endif
                                </td>
                                <td class="text-center">
                                    @if ($row->work)
                                        <span class="{{ WorkStatus::tryFrom($row->work->work_status)?->badgeClass() ?? 'setel-badge setel-badge--neutral' }} text-xs">{{ WorkStatus::tryFrom($row->work->work_status)?->label() ?? $row->work->work_status }}</span>
                                    @else
                                        <span class="text-xs text-[var(--setel-text-muted)]">—</span>
                                    @endif
                                </td>
                                <td class="text-center">
                                    <span class="{{ WorkAssignmentStatus::fromDatabase((string) $row->status)?->badgeClass() ?? 'setel-badge setel-badge--neutral' }} text-xs">
                                        {{ WorkAssignmentStatus::fromDatabase((string) $row->status)?->label() ?? $row->status }}
                                    </span>
                                </td>
                                <td class="text-sm">{{ $row->technician?->fullName() ?? '—' }}</td>
                                <td class="text-sm">{{ $row->coordinator?->fullName() ?? '—' }}</td>
                                <td class="text-center">
                                    @if ($row->work)
                                        <button
                                            type="button"
                                            class="setel-btn-secondary inline-flex size-9 items-center justify-center p-0 text-xs"
                                            wire:click="openWorkPreview({{ $row->work->id }})"
                                            title="Abrir ficha"
                                            aria-label="Abrir ficha de la OT"
                                        >
                                            <flux:icon.eye class="size-3.5 shrink-0" />
                                        </button>
                                    @endif
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="11" class="py-12 text-center text-sm text-[var(--setel-text-muted)]">Sin registros para los filtros.</td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>

            @if ($this->assignmentHistory->hasPages())
                <div class="border-t border-[var(--setel-card-border)] px-5 py-4">
                    {{ $this->assignmentHistory->links() }}
                </div>
            @endif
        @endif
    </div>

    <flux:modal wire:model.self="showWorkPreviewModal" wire:close="closeWorkPreview" class="max-w-2xl w-full !max-w-[min(96vw,42rem)]">
        @if ($this->previewWork)
            <div class="flex max-h-[min(85vh,640px)] flex-col gap-4">
                <div class="flex items-start gap-3 pe-10">
                    <span class="setel-modal__icon shrink-0 !static !flex"><flux:icon.eye class="size-5" /></span>
                    <div class="min-w-0">
                        <flux:heading size="lg">Resumen · {{ $this->previewWork->ot }}</flux:heading>
                        <flux:subheading class="mt-1">Vista rápida para decidir asignación. Los datos completos están en la ficha.</flux:subheading>
                    </div>
                </div>

                <div class="min-h-0 flex-1 space-y-4 overflow-y-auto border-t border-[var(--setel-card-border)] pt-4 pe-1">
                    <dl class="grid gap-3 sm:grid-cols-2">
                        <div class="sm:col-span-2">
                            <dt class="text-xs font-semibold uppercase tracking-wide text-[var(--setel-text-muted)]">Sitio</dt>
                            <dd class="mt-1 text-sm text-[var(--setel-text)]">{{ $this->previewWork->site?->code }} · {{ $this->previewWork->site?->name ?? '—' }}</dd>
                        </div>
                        @if ($this->previewWork->site?->project)
                            <div class="sm:col-span-2">
                                <dt class="text-xs font-semibold uppercase tracking-wide text-[var(--setel-text-muted)]">Proyecto</dt>
                                <dd class="mt-1 flex items-center gap-2 text-sm text-[var(--setel-text)]">
                                    <span class="size-3 shrink-0 rounded-full border border-[var(--setel-card-border)]" style="background-color: {{ $this->previewWork->site->project->color ?? '#64748b' }}"></span>
                                    {{ $this->previewWork->site->project->name }}
                                </dd>
                            </div>
                        @endif
                        <div>
                            <dt class="text-xs font-semibold uppercase tracking-wide text-[var(--setel-text-muted)]">Tipo</dt>
                            <dd class="mt-1 text-sm">{{ $this->previewWork->workType?->name ?? '—' }}</dd>
                        </div>
                        <div>
                            <dt class="text-xs font-semibold uppercase tracking-wide text-[var(--setel-text-muted)]">Prioridad</dt>
                            <dd class="mt-1"><span class="{{ WorkPriority::tryFrom($this->previewWork->priority)?->badgeClass() ?? 'setel-badge setel-badge--neutral' }} text-xs">{{ WorkPriority::tryFrom($this->previewWork->priority)?->label() ?? $this->previewWork->priority }}</span></dd>
                        </div>
                        <div>
                            <dt class="text-xs font-semibold uppercase tracking-wide text-[var(--setel-text-muted)]">Estado externo</dt>
                            <dd class="mt-1"><span class="{{ WorkStatus::tryFrom($this->previewWork->work_status)?->badgeClass() ?? 'setel-badge setel-badge--neutral' }} text-xs">{{ WorkStatus::tryFrom($this->previewWork->work_status)?->label() ?? $this->previewWork->work_status }}</span></dd>
                        </div>
                        <div>
                            <dt class="text-xs font-semibold uppercase tracking-wide text-[var(--setel-text-muted)]">Estado interno</dt>
                            <dd class="mt-1"><span class="{{ WorkInternalStatus::tryFrom($this->previewWork->internal_status)?->badgeClass() ?? 'setel-badge setel-badge--neutral' }} text-xs">{{ WorkInternalStatus::tryFrom($this->previewWork->internal_status)?->label() ?? $this->previewWork->internal_status }}</span></dd>
                        </div>
                        <div>
                            <dt class="text-xs font-semibold uppercase tracking-wide text-[var(--setel-text-muted)]">SLA (h)</dt>
                            <dd class="mt-1 text-sm tabular-nums">{{ number_format($this->previewWork->sla_hours) }}</dd>
                        </div>
                        <div>
                            <dt class="text-xs font-semibold uppercase tracking-wide text-[var(--setel-text-muted)]">Escala</dt>
                            <dd class="mt-1 text-sm tabular-nums">{{ $this->previewWork->scale_datetime?->format('d/m/Y H:i') ?? '—' }}</dd>
                        </div>
                        <div>
                            <dt class="text-xs font-semibold uppercase tracking-wide text-[var(--setel-text-muted)]">Programado</dt>
                            <dd class="mt-1 text-sm tabular-nums">{{ $this->previewWork->scheduled_date?->format('d/m/Y H:i') ?? '—' }}</dd>
                        </div>
                        <div class="sm:col-span-2">
                            <dt class="text-xs font-semibold uppercase tracking-wide text-[var(--setel-text-muted)]">Equipo en OT</dt>
                            <dd class="mt-2 grid gap-2 text-sm sm:grid-cols-3">
                                <div><span class="text-[var(--setel-text-muted)]">NOC</span><br /><span class="font-medium">{{ $this->previewWork->noc?->fullName() ?? '—' }}</span></div>
                                <div><span class="text-[var(--setel-text-muted)]">Técnico</span><br /><span class="font-medium">{{ $this->previewWork->technician?->fullName() ?? '—' }}</span></div>
                                <div><span class="text-[var(--setel-text-muted)]">Coord.</span><br /><span class="font-medium">{{ $this->previewWork->coordinator?->fullName() ?? '—' }}</span></div>
                            </dd>
                        </div>
                        <div class="sm:col-span-2">
                            <dt class="text-xs font-semibold uppercase tracking-wide text-[var(--setel-text-muted)]">Seguimiento NOC</dt>
                            <dd class="mt-1 flex flex-wrap items-center gap-2">
                                <span class="{{ NocTrackingStatus::tryFrom((string) ($this->previewWork->noc_tracking_status ?? ''))?->badgeClass() ?? 'setel-badge setel-badge--neutral' }} text-xs">
                                    {{ NocTrackingStatus::tryFrom((string) ($this->previewWork->noc_tracking_status ?? ''))?->label() ?? ($this->previewWork->noc_tracking_status ?? '—') }}
                                </span>
                            </dd>
                            @if ($this->previewWork->noc_comment)
                                <p class="mt-2 text-sm leading-relaxed text-[var(--setel-text-muted)]">{{ $this->previewWork->noc_comment }}</p>
                            @endif
                        </div>
                        @if ($this->previewWork->observation)
                            <div class="sm:col-span-2">
                                <dt class="text-xs font-semibold uppercase tracking-wide text-[var(--setel-text-muted)]">Observaciones</dt>
                                <dd class="mt-1 text-sm leading-relaxed text-[var(--setel-text-muted)]">{{ $this->previewWork->observation }}</dd>
                            </div>
                        @endif
                    </dl>
                </div>

                <div class="flex flex-wrap justify-end gap-2 border-t border-[var(--setel-card-border)] pt-4">
                    <flux:button type="button" variant="ghost" wire:click="closeWorkPreview">Cerrar</flux:button>
                    <a href="{{ route('works.show', $this->previewWork) }}" wire:navigate class="setel-btn-primary inline-flex items-center justify-center gap-2 rounded-md px-4 py-2 text-sm font-medium">Abrir ficha completa</a>
                </div>
            </div>
        @endif
    </flux:modal>

    @php
        $assignConfirmCount = $assignSubTab === 'lote' ? count($selectedWorkIds) : count($selectedUnassignWorkIds);
        $assignConfirmOtWord = $assignConfirmCount === 1 ? 'OT' : 'OTs';
        $assignConfirmTitle = $assignSubTab === 'lote' ? 'Confirmar asignación' : 'Confirmar reasignación';
        $assignConfirmTl = e($this->assignConfirmTechnicianLabel);
        $assignConfirmDay = e($this->todayIso);
        $strongOpen = '<strong class="text-[var(--setel-text)]">';
        $strongClose = '</strong>';
        if ($assignSubTab === 'lote') {
            $assignConfirmBody = 'Se asignará '.$strongOpen.$assignConfirmCount.$strongClose
                .' '.$assignConfirmOtWord.' al técnico '.$strongOpen.$assignConfirmTl.$strongClose
                .' para la fecha <span class="font-mono">'.$assignConfirmDay.'</span>.';
        } else {
            $assignConfirmSuf = $assignConfirmCount === 1 ? '' : 's';
            $assignConfirmBody = 'Se reasignará '.$strongOpen.$assignConfirmCount.$strongClose
                .' '.$assignConfirmOtWord.' seleccionada'.$assignConfirmSuf.' al técnico '.$strongOpen.$assignConfirmTl.$strongClose
                .' para la fecha <span class="font-mono">'.$assignConfirmDay.'</span> (trabajos de hoy).';
        }
    @endphp
    <flux:modal wire:model.self="showAssignConfirmModal" wire:close="cancelAssignConfirm" class="max-w-md w-full !max-w-md">
        <div class="flex flex-col gap-4">
            <flux:heading size="lg">{{ $assignConfirmTitle }}</flux:heading>
            <p class="text-sm text-[var(--setel-text-muted)]">{!! $assignConfirmBody !!}</p>
            <div class="flex flex-wrap justify-end gap-2 border-t border-[var(--setel-card-border)] pt-4">
                <flux:button type="button" variant="ghost" wire:click="cancelAssignConfirm">Cancelar</flux:button>
                <flux:button type="button" variant="primary" wire:click="confirmAssignSelection" wire:loading.attr="disabled" wire:target="confirmAssignSelection">
                    <span wire:loading.remove wire:target="confirmAssignSelection">Confirmar</span>
                    <span wire:loading wire:target="confirmAssignSelection">Guardando…</span>
                </flux:button>
            </div>
        </div>
    </flux:modal>

    <flux:modal wire:model.self="showUnassignConfirmModal" wire:close="cancelUnassignConfirm" class="max-w-md w-full !max-w-md">
        <div class="flex flex-col gap-4">
            <flux:heading size="lg">Retirar del día</flux:heading>
            <p class="text-sm text-[var(--setel-text-muted)]">
                Se retirará la asignación abierta de hoy para <strong class="text-[var(--setel-text)]">{{ $this->bulkUnassignOts->count() }}</strong>
                {{ $this->bulkUnassignOts->count() === 1 ? 'OT' : 'OTs' }}:
            </p>
            <ul class="max-h-40 list-inside list-disc overflow-y-auto text-sm text-[var(--setel-text)]">
                @foreach ($this->bulkUnassignOts as $ot)
                    <li class="font-mono">{{ $ot }}</li>
                @endforeach
            </ul>
            <p class="text-xs text-[var(--setel-text-muted)]">Si el técnico en la ficha coincide con la asignación, se limpiará para poder elegir otro.</p>
            <div class="flex flex-wrap justify-end gap-2 border-t border-[var(--setel-card-border)] pt-4">
                <flux:button type="button" variant="ghost" wire:click="cancelUnassignConfirm">Cancelar</flux:button>
                <flux:button type="button" variant="primary" wire:click="confirmBulkUnassignFromToday" wire:loading.attr="disabled" wire:target="confirmBulkUnassignFromToday">
                    <span wire:loading.remove wire:target="confirmBulkUnassignFromToday">Sí, quitar</span>
                    <span wire:loading wire:target="confirmBulkUnassignFromToday">Quitando…</span>
                </flux:button>
            </div>
        </div>
    </flux:modal>

    <flux:modal wire:model.self="showHelpModal" wire:close="closeHelpModal" class="max-w-lg w-full !max-w-[min(96vw,32rem)]">
        <div class="flex max-h-[min(80vh,520px)] flex-col gap-4">
            <flux:heading size="lg">Cómo usar asignaciones</flux:heading>
            <div class="min-h-0 flex-1 space-y-4 overflow-y-auto text-sm text-[var(--setel-text-muted)]">
                <p><strong class="text-[var(--setel-text)]">Día de operación.</strong> Todas las acciones de la pestaña Asignar aplican a la fecha de hoy que se muestra arriba.</p>
                <p><strong class="text-[var(--setel-text)]">Asignar.</strong> En <em>Lotes por asignar</em> marque OT, elija técnico y confirme. Los filtros van en orden: proyecto y luego tipo de trabajo.</p>
                <p><strong class="text-[var(--setel-text)]">Trabajos de hoy.</strong> Lista de OT ya asignadas hoy; seleccione una o varias y use <em>Reasignar selección</em> para cambiar de técnico o <em>Retirar del día (selección)</em> para quitarlas del lote.</p>
                <p><strong class="text-[var(--setel-text)]">Horario.</strong> Coordinar (asignar / retirar) solo entre <em>{{ config('work_coordination.operations_start') }}</em> y <em>{{ config('work_coordination.operations_end') }}</em> (zona {{ config('app.timezone') }}). Una OT asignada en ese rango no vuelve al lote hasta el día siguiente o hasta que retire la asignación.</p>
                <p><strong class="text-[var(--setel-text)]">Historial.</strong> Por defecto solo hoy; filtre en orden proyecto → tipo → sitio → fechas.</p>
            </div>
            <div class="flex justify-end border-t border-[var(--setel-card-border)] pt-4">
                <flux:button type="button" variant="primary" wire:click="closeHelpModal">Entendido</flux:button>
            </div>
        </div>
    </flux:modal>
</div>
