@php
    $editableColumns = isset($editableColumns) && is_array($editableColumns) ? $editableColumns : [];
    $detailEntities = ['bienes', 'registros-stock'];
    $highlightColumnsByEntity = [
        'sitios' => ['responsable'],
        'embarcaciones' => ['responsable'],
        'tallas-uniformes' => ['cedula_usuario'],
        'registros-stock' => ['cedulaResponsable', 'codigo'],
    ];
    $resolvePhotoUrl = static function (string $directory, ?string $identifier): ?string {
        $identifier = trim((string) $identifier);
        if ($identifier === '') {
            return null;
        }

        foreach (['jpg', 'png', 'webp'] as $ext) {
            $relativePath = $directory . '/' . $identifier . '.' . $ext;
            if (is_file(public_path($relativePath))) {
                return asset($relativePath);
            }
        }

        return null;
    };
    $extractTooltipLabel = static function ($label): ?string {
        if (! is_string($label) || $label === '') {
            return null;
        }

        $parts = explode(' - ', $label, 2);

        return $parts[1] ?? $label;
    };
    $resolveOperationRoute = static function ($value): ?string {
        return match ((int) $value) {
            1 => 'alimentos',
            2 => 'dotacion',
            3 => 'transferencia',
            5 => 'devolucion-prestamo',
            6 => 'devolucion-transferencia',
            default => null,
        };
    };
    $entityKey = is_string($entity ?? null) ? $entity : '';
    $formatKg = static function ($value): string {
        $numericValue = is_numeric($value) ? (float) $value : 0.0;
        $formatted = number_format($numericValue, 3, '.', '');
        $formatted = rtrim(rtrim($formatted, '0'), '.');

        return ($formatted === '' ? '0' : $formatted) . ' kg';
    };
    $hasDetailAction = in_array($entityKey, $detailEntities, true);
    $hasReadOnlyActions = $hasDetailAction || $entityKey === 'operaciones';
    $showActionsColumn = ! ($isReadOnly ?? false) || $hasReadOnlyActions;
    $entityHighlightColumns = $highlightColumnsByEntity[$entityKey] ?? [];
@endphp

<div class="crud-card p-3" style="width: 100%; max-width: 100vw;">
    @if (method_exists($rows, 'links'))
        <div class="mb-2">
            {{ $rows->links() }}
        </div>
    @endif
    <div class="crud-table-wrap">
        <div>
            <table class="table table-sm align-middle mb-0" style="width:100%; table-layout:auto; overflow:visible;">
                <thead>
                    <tr>
                        @if (!empty($showRowNumber))
                            <th>#</th>
                        @endif
                        @foreach ($columns as $column)
                            <th class="{{ $entity === 'embarcaciones' && $column === 'observacion' ? 'obs-col' : '' }}">{{ $columnLabels[$column] ?? $column }}</th>
                        @endforeach
                        @if ($showActionsColumn)
                            <th>Acciones</th>
                        @endif
                    </tr>
                </thead>
                <tbody>
                    @forelse ($rows as $row)
                        @php
                            $usuarioPhotoUrl = $resolvePhotoUrl('foto_usuarios', data_get($row, 'cedula'));
                            $bienPhotoUrl = $entity === 'bienes'
                                ? $resolvePhotoUrl('foto_bienes', data_get($row, 'codigo'))
                                : null;
                            $rowRecord = collect($editableColumns)->mapWithKeys(fn ($col) => [$col => data_get($row, $col)]);
                            $tipoOperacionRoute = $entity === 'operaciones'
                                ? $resolveOperationRoute(data_get($row, 'tipo'))
                                : null;
                        @endphp
                        <tr>
                            @if (!empty($showRowNumber))
                                <td>{{ ($rows->firstItem() ?? 1) + $loop->index }}</td>
                            @endif
                            @foreach ($columns as $column)
                                @php
                                    $cellValue = data_get($row, $column);
                                    $rawCellValue = $cellValue;
                                    $cellTooltip = null;
                                    $isEmbarcacionObservation = $entity === 'embarcaciones' && $column === 'observacion';

                                    if ($column === 'activo') {
                                        $cellValue = (string) $cellValue === '1' ? 'Activo' : 'Inactivo';
                                    }

                                    if ($entity === 'bienes' && $column === 'tipo') {
                                        $cellValue = data_get($row, 'tipo_nombre') ?? $cellValue;
                                    } elseif ($entity === 'bienes' && $column === 'pesoTotal') {
                                        $cellValue = data_get($row, 'pesoTotal');
                                    } elseif ($entity === 'registros-stock' && $column === 'objetivo') {
                                        $cellValue = match ((int) $cellValue) {
                                            1 => 'Almacenado',
                                            2 => 'En stock',
                                            default => $cellValue,
                                        };
                                    } elseif ($entity === 'operaciones' && $column === 'tipo') {
                                        $cellValue = $fieldOptions['tipo'][(int) $rawCellValue] ?? $rawCellValue;
                                    }

                                    if (($entity === 'sitios' || $entity === 'embarcaciones') && $column === 'responsable') {
                                        $cellTooltip = $extractTooltipLabel($fieldOptions['responsable'][$cellValue] ?? null);
                                    } elseif ($entity === 'tallas-uniformes' && $column === 'cedula_usuario') {
                                        $cellTooltip = $extractTooltipLabel($fieldOptions['cedula_usuario'][$cellValue] ?? null);
                                    } elseif (in_array($column, ['cedulaEditor', 'cedula_usuario'], true) && isset($fieldOptions[$column])) {
                                        $cellTooltip = $extractTooltipLabel($fieldOptions[$column][$cellValue] ?? null);
                                        $cellValue = $fieldOptions[$column][$cellValue] ?? $cellValue;
                                    } elseif ($entity === 'registros-stock' && $column === 'cedulaResponsable') {
                                        $cellTooltip = $extractTooltipLabel($fieldOptions['cedulaResponsable'][$cellValue] ?? null);
                                    } elseif ($entity === 'registros-stock' && $column === 'codigo') {
                                        $bienDescripcion = $bienLabels[$cellValue] ?? null;
                                        $cellTooltip = is_string($bienDescripcion) && trim($bienDescripcion) !== ''
                                            ? $bienDescripcion
                                            : null;
                                    }

                                    $isHighlightedCell = in_array($column, $entityHighlightColumns, true) && filled($cellValue);
                                @endphp
                                <td class="{{ $isEmbarcacionObservation ? 'obs-col' : '' }}">
                                    @if ($isHighlightedCell)
                                        <span
                                            class="responsable-highlight"
                                            @if ($cellTooltip)
                                                data-bs-toggle="tooltip"
                                                data-bs-placement="top"
                                                data-bs-title="{{ $cellTooltip }}"
                                            @endif
                                        >{{ $cellValue }}</span>
                                    @elseif ($isEmbarcacionObservation)
                                        <div class="observation-cell">
                                            <button
                                                type="button"
                                                class="observation-indicator action-icon-btn {{ filled($cellValue) ? '' : 'd-none' }}"
                                                data-bs-toggle="tooltip"
                                                data-bs-placement="top"
                                                data-bs-title="{{ $cellValue ?? '' }}"
                                                aria-label="Ver observacion"
                                            >💬</button>
                                        </div>
                                    @elseif ($entity === 'precios-por-bien' && in_array($column, ['precio', 'precio_final'], true))
                                        {{ number_format((float) ($cellValue ?? 0), 2, ',', '.') }}
                                    @elseif ($entity === 'precios-por-bien' && $column === 'porcentaje_utilidad')
                                        {{ number_format((float) ($cellValue ?? 0), 2, ',', '.') }}%
                                    @elseif ($entity === 'bienes' && $column === 'precioUnitario')
                                        @php
                                            $ultimaFechaPrecio = data_get($row, 'ultimoPrecioPorBien.fecha_registro');
                                            $establecerPrecioUrl = route('administracion.crud.index', [
                                                'entity' => 'precios-por-bien',
                                                'bien_id' => data_get($row, 'id'),
                                                'open_modal' => 'create',
                                                'selected_bien_id' => data_get($row, 'id'),
                                            ]);
                                        @endphp
                                        @if ($cellValue === null)
                                            @if (! ($isReadOnly ?? false))
                                                <a class="btn btn-sm btn-outline-primary" href="{{ $establecerPrecioUrl }}">Establecer precio</a>
                                            @else
                                                -
                                            @endif
                                        @else
                                            <div>{{ number_format((float) $cellValue, 2, ',', '.') }}</div>
                                            @if (filled($ultimaFechaPrecio))
                                                <div class="small text-muted">({{ $ultimaFechaPrecio }})</div>
                                            @endif
                                        @endif
                                    @elseif ($entity === 'bienes' && in_array($column, ['peso', 'pesoTotal'], true))
                                        {{ $formatKg($cellValue) }}
                                    @elseif ($entity === 'bienes' && $column === 'relacionUnidades')
                                        {{ (int) ($cellValue ?? 0) }}
                                    @else
                                        {{ $cellValue }}
                                    @endif
                                </td>
                            @endforeach
                            @if ($showActionsColumn)
                                <td class="text-nowrap">
                                    <div class="actions-cell">
                                        @if ($hasDetailAction)
                                            <button
                                                class="btn btn-sm action-icon-btn detail-row-btn"
                                                type="button"
                                                data-bs-toggle="tooltip"
                                                data-bs-placement="top"
                                                data-bs-title="Ver detalle"
                                                aria-label="Ver detalle"
                                                data-detail-record='@json($rowRecord)'
                                                @if ($entity === 'bienes')
                                                    data-foto-bien-url="{{ $bienPhotoUrl ?? '' }}"
                                                @endif
                                            >👁</button>
                                        @endif
                                        @if ($entity === 'operaciones' && $tipoOperacionRoute !== null)
                                            <a
                                                class="btn btn-sm btn-outline-primary"
                                                href="{{ route('administracion.comprobante.show', ['id' => data_get($row, $primaryKey)]) }}"
                                                aria-label="Ver comprobante"
                                            >Ver comprobante</a>
                                            <a
                                                class="btn btn-sm btn-excel"
                                                href="{{ route('asignacion.operacion.export', ['tipo' => $tipoOperacionRoute, 'numero' => data_get($row, 'numero')]) }}"
                                                aria-label="Exportar Excel"
                                            >Exportar Excel</a>
                                        @elseif ($entity === 'operaciones')
                                            <span class="text-muted small">Sin comprobante</span>
                                        @endif
                                        @if (! ($isReadOnly ?? false))
                                            <button
                                                class="btn btn-sm action-icon-btn edit-row-btn"
                                                type="button"
                                                data-bs-toggle="tooltip"
                                                data-bs-placement="top"
                                                data-bs-title="Editar"
                                                aria-label="Editar"
                                                data-update-url="{{ route('administracion.crud.update', ['entity' => $entity, 'id' => data_get($row, $primaryKey)]) }}"
                                                data-record='@json($rowRecord)'
                                                data-foto-usuario-url="{{ $usuarioPhotoUrl ?? '' }}"
                                                @if ($entity === 'bienes')
                                                    data-foto-bien-url="{{ $bienPhotoUrl ?? '' }}"
                                                @endif
                                            >✏️</button>
                                            <form method="POST" class="d-inline" action="{{ route('administracion.crud.destroy', ['entity' => $entity, 'id' => data_get($row, $primaryKey)]) }}" onsubmit="return confirm('Eliminar registro?');">
                                                @csrf
                                                @method('DELETE')
                                                <button class="btn btn-sm action-icon-btn" type="submit" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Eliminar" aria-label="Eliminar">🚫</button>
                                            </form>
                                        @endif
                                    </div>
                                </td>
                            @endif
                        </tr>
                    @empty
                        <tr>
                            <td class="text-secondary" colspan="{{ count($columns) + ($showActionsColumn ? 1 : 0) + (!empty($showRowNumber) ? 1 : 0) }}">Sin registros.</td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
    </div>

    @if (method_exists($rows, 'links'))
        <div class="mt-3">
            {{ $rows->links() }}
        </div>
    @endif
</div>
