{{-- resources/views/dashboard.blade.php --}}
@extends('layouts.app')

@section('title', 'Dashboard')

@push('styles')
<style>
    /* Estilos específicos para el dashboard */
    .lote-bar { height: 10px; border-radius: 5px; overflow: hidden; display: flex; }
    .urb-progress { background-color: var(--bs-primary-bg-subtle); border-radius: 6px; }
    .urb-progress-bar { background-color: var(--bs-primary); height: 24px; border-radius: 6px; display: flex; align-items: center; justify-content: flex-end; padding-right: 8px; font-size: 12px; font-weight: 600; color: white; }
    .activity-timeline-item { border-bottom: 1px solid var(--bs-border-color); transition: background 0.2s; }
    .activity-timeline-item:last-child { border-bottom: none; }
    .activity-timeline-item:hover { background-color: var(--bs-gray-100); }
    .stat-icon-wrapper { width: 48px; height: 48px; display: flex; align-items: center; justify-content: center; border-radius: 12px; transition: transform 0.2s; }
    .block-link-shadow:hover .stat-icon-wrapper { transform: scale(1.05); }
    .stat-value { font-size: 28px; font-weight: 700; line-height: 1.2; }
    .stat-trend { font-size: 12px; }
    .quick-action-card { cursor: pointer; transition: all 0.2s; }
    .quick-action-card:hover { transform: translateY(-3px); box-shadow: 0 8px 20px rgba(0,0,0,0.1); }
</style>
@endpush

@section('content')
@php
    $usuario = Auth::user();
    $bd = session('db_connection') === 'tarapaca' ? 'Tarapacá' : 'Cosmos 79';
    $fechaSistema = session('fecha_sistema', \App\Helpers\FechaHelper::hoy());
    $tc = session('tc_sistema', '—');
@endphp

<div class="content">
    {{-- ============================================================ --}}
    {{-- SECCIÓN 1: BIENVENIDA Y CONTEXTO --}}
    {{-- ============================================================ --}}
    <div class="d-flex flex-column flex-sm-row justify-content-between align-items-sm-center mb-4">
        <div>
            <h1 class="fw-bold mb-1">
                <i class="fa fa-tachometer-alt me-2 text-primary"></i>Principal
            </h1>
            <div class="fs-sm text-muted">
                <span><i class="fa fa-user-circle me-1"></i> {{ $usuario->nombre }}</span>
                <span class="mx-2">•</span>
                <span><i class="fa fa-database me-1"></i> {{ $bd }}</span>
                <span class="mx-2">•</span>
                <span><i class="fa fa-calendar-alt me-1"></i> {{ $fechaSistema }}</span>
                <span class="mx-2">•</span>
                <span><i class="fa fa-dollar-sign me-1"></i> TC: <strong class="text-dark">{{ $tc }}</strong></span>
            </div>
        </div>
        <div class="mt-2 mt-sm-0">
            <a href="{{ route('contratos.create') }}" class="btn btn-primary">
                <i class="fa fa-plus me-1"></i> Nuevo Contrato
            </a>
            <a href="{{ route('recibos.create') }}" class="btn btn-alt-success ms-1">
                <i class="fa fa-receipt me-1"></i> Nuevo Recibo
            </a>
        </div>
    </div>

   {{-- ============================================================ --}}
    {{-- SECCIÓN 4: ACCIONES RÁPIDAS (atajos visuales) --}}
    {{-- ============================================================ --}}
    <div class="row g-3 mb-4">
        <div class="col-12">
            <div class="block block-rounded">
                <div class="block-header block-header-default">
                    <h3 class="block-title"><i class="fa fa-bolt me-1 text-warning"></i> Acciones rápidas</h3>
                </div>
                <div class="block-content">
                    <div class="row g-3 text-center">
                        <div class="col-6 col-md-3">
                            <a href="{{ route('contratos.create') }}" class="quick-action-card d-block p-3 rounded bg-body-light">
                                <i class="fa fa-file-contract fa-2x text-primary mb-2"></i>
                                <div class="fw-semibold">Nuevo Contrato</div>
                                <div class="fs-sm text-muted">Registrar venta</div>
                            </a>
                        </div>
                        <div class="col-6 col-md-3">
                            <a href="{{ route('recibos.create') }}" class="quick-action-card d-block p-3 rounded bg-body-light">
                                <i class="fa fa-receipt fa-2x text-success mb-2"></i>
                                <div class="fw-semibold">Nuevo Recibo</div>
                                <div class="fs-sm text-muted">Registrar pago</div>
                            </a>
                        </div>
                        <div class="col-6 col-md-3">
                            <a href="{{ route('clientes.index') }}" class="quick-action-card d-block p-3 rounded bg-body-light">
                                <i class="fa fa-user-plus fa-2x text-info mb-2"></i>
                                <div class="fw-semibold">Nuevo Cliente</div>
                                <div class="fs-sm text-muted">Agregar persona</div>
                            </a>
                        </div>
                        <div class="col-6 col-md-3">
                            <a href="{{ route('extractos.index') }}" class="quick-action-card d-block p-3 rounded bg-body-light">
                                <i class="fa fa-chart-line fa-2x text-warning mb-2"></i>
                                <div class="fw-semibold">Ver Extractos</div>
                                <div class="fs-sm text-muted">Estado de cuentas</div>
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    {{-- ============================================================ --}}
    {{-- SECCIÓN 3: MÉTRICAS CLAVE (KPI Cards) --}}
    {{-- ============================================================ --}}
    <div class="row g-3 mb-4">
        {{-- Clientes Activos --}}
        <div class="col-6 col-md-4 col-xl-2">
            <div class="block block-rounded block-link-shadow text-center">
                <div class="block-content block-content-full">
                    <div class="stat-icon-wrapper bg-primary-light text-primary mx-auto mb-3">
                        <i class="fa fa-users fa-2x"></i>
                    </div>
                    <div class="stat-value">{{ number_format($totalClientes) }}</div>
                    <div class="text-muted mt-1">Clientes</div>
                    <div class="stat-trend text-muted">registrados</div>
                </div>
            </div>
        </div>

        {{-- Contratos Vigentes --}}
        <div class="col-6 col-md-4 col-xl-2">
            <div class="block block-rounded block-link-shadow text-center">
                <div class="block-content block-content-full">
                    <div class="stat-icon-wrapper bg-success-light text-success mx-auto mb-3">
                        <i class="fa fa-file-signature fa-2x"></i>
                    </div>
                    <div class="stat-value">{{ number_format($contratosVigentes) }}</div>
                    <div class="text-muted mt-1">Contratos vigentes</div>
                    <div class="stat-trend text-success">
                        <i class="fa fa-arrow-up"></i> +{{ $contratosEsteMes }} este mes
                    </div>
                </div>
            </div>
        </div>

        {{-- Cobranza del Mes (Bs) --}}
        <div class="col-6 col-md-4 col-xl-2">
            <div class="block block-rounded block-link-shadow text-center">
                <div class="block-content block-content-full">
                    <div class="stat-icon-wrapper bg-warning-light text-warning mx-auto mb-3">
                        <i class="fa fa-money-bill-wave fa-2x"></i>
                    </div>
                    <div class="stat-value fs-1">Bs {{ number_format((float)$cobranzaMes, 0) }}</div>
                    <div class="text-muted mt-1">Cobranza del mes</div>
                    <div class="stat-trend text-muted">≈ $ {{ number_format((float)$cobranzaMesSus, 2) }} USD</div>
                </div>
            </div>
        </div>

        {{-- Lotes Totales --}}
        <div class="col-6 col-md-4 col-xl-2">
            <div class="block block-rounded block-link-shadow text-center">
                <div class="block-content block-content-full">
                    <div class="stat-icon-wrapper bg-info-light text-info mx-auto mb-3">
                        <i class="fa fa-th-large fa-2x"></i>
                    </div>
                    <div class="stat-value">{{ number_format($loteStats['total']) }}</div>
                    <div class="text-muted mt-1">Lotes totales</div>
                    <div class="stat-trend text-success">{{ $loteStats['disponible'] }} disponibles</div>
                </div>
            </div>
        </div>

        {{-- En Trámite --}}
        <div class="col-6 col-md-4 col-xl-2">
            <div class="block block-rounded block-link-shadow text-center">
                <div class="block-content block-content-full">
                    <div class="stat-icon-wrapper bg-secondary-light text-secondary mx-auto mb-3">
                        <i class="fa fa-clipboard-list fa-2x"></i>
                    </div>
                    <div class="stat-value">{{ number_format($loteStats['en_tramite']) }}</div>
                    <div class="text-muted mt-1">En trámite</div>
                    <div class="stat-trend text-muted">{{ $loteStats['consolidado'] }} consolidados</div>
                </div>
            </div>
        </div>

        {{-- Cuotas Vencidas (crítico) --}}
        <div class="col-6 col-md-4 col-xl-2">
            <div class="block block-rounded block-link-shadow text-center {{ $cuotasVencidas > 0 ? 'bg-danger-light' : '' }}">
                <div class="block-content block-content-full">
                    <div class="stat-icon-wrapper bg-danger-light text-danger mx-auto mb-3">
                        <i class="fa fa-exclamation-circle fa-2x"></i>
                    </div>
                    <div class="stat-value {{ $cuotasVencidas > 0 ? 'text-danger' : '' }}">{{ number_format($cuotasVencidas) }}</div>
                    <div class="text-muted mt-1">Cuotas vencidas</div>
                    <div class="stat-trend text-danger">$ {{ number_format((float)$saldoVencido, 0) }} USD</div>
                </div>
            </div>
        </div>
    </div>

    {{-- ============================================================ --}}
    {{-- SECCIÓN 5: ESTADO DE LOTES (panorama general) --}}
    {{-- ============================================================ --}}
    @php
        $total = max($loteStats['total'], 1);
        $loteBars = [
            ['key'=>'disponible',  'label'=>'Disponible',  'color'=>'bg-success', 'icon'=>'fa-check-circle'],
            ['key'=>'reservado',   'label'=>'Reservado',    'color'=>'bg-danger',  'icon'=>'fa-bookmark'],
            ['key'=>'en_proceso',  'label'=>'En Proceso',   'color'=>'bg-warning', 'icon'=>'fa-spinner'],
            ['key'=>'vendido',     'label'=>'Vendido',      'color'=>'bg-primary', 'icon'=>'fa-check-double'],
            ['key'=>'en_tramite',  'label'=>'En Trámite',   'color'=>'bg-info',    'icon'=>'fa-file-alt'],
            ['key'=>'consolidado', 'label'=>'Consolidado',  'color'=>'bg-secondary','icon'=>'fa-check'],
        ];
    @endphp
    <div class="block block-rounded mb-4">
        <div class="block-header block-header-default">
            <h3 class="block-title">
                <i class="fa fa-chart-pie me-1 text-primary"></i> Estado de Lotes
                <span class="fs-sm text-muted ms-2">Total: {{ number_format($loteStats['total']) }} lotes</span>
            </h3>
        </div>
        <div class="block-content">
            <div class="lote-bar mb-4">
                @foreach($loteBars as $b)
                    @php $pct = round($loteStats[$b['key']] * 100 / $total, 1); @endphp
                    @if($pct > 0)
                    <span style="width:{{ $pct }}%;" class="{{ $b['color'] }}" title="{{ $b['label'] }}: {{ $loteStats[$b['key']] }} ({{ $pct }}%)"></span>
                    @endif
                @endforeach
            </div>
            <div class="row g-3">
                @foreach($loteBars as $b)
                <div class="col-6 col-md-4 col-lg-2">
                    <div class="d-flex align-items-center gap-2">
                        <span class="w-12px h-12px rounded {{ $b['color'] }} d-inline-block"></span>
                        <span class="text-muted fs-sm flex-grow-1">{{ $b['label'] }}</span>
                        <strong class="fs-sm">{{ number_format($loteStats[$b['key']]) }}</strong>
                    </div>
                </div>
                @endforeach
            </div>
        </div>
    </div>

    {{-- ============================================================ --}}
    {{-- SECCIÓN 6: TENDENCIAS (Gráficos) --}}
    {{-- ============================================================ --}}
    <div class="row g-3 mb-4">
        <div class="col-lg-7">
            <div class="block block-rounded">
                <div class="block-header block-header-default">
                    <h3 class="block-title">
                        <i class="fa fa-chart-line me-1 text-warning"></i> Evolución de Cobranza
                    </h3>
                    <div class="block-options">
                        <span class="badge bg-success-light text-success">USD</span>
                    </div>
                </div>
                <div class="block-content">
                    <canvas id="chartCobranza" height="140"></canvas>
                </div>
            </div>
        </div>
        <div class="col-lg-5">
            <div class="block block-rounded">
                <div class="block-header block-header-default">
                    <h3 class="block-title">
                        <i class="fa fa-chart-line me-1 text-success"></i> Nuevos Contratos
                    </h3>
                    <div class="block-options">
                        <span class="badge bg-primary-light text-primary">últimos 6 meses</span>
                    </div>
                </div>
                <div class="block-content">
                    <canvas id="chartContratos" height="140"></canvas>
                </div>
            </div>
        </div>
    </div>

    {{-- ============================================================ --}}
    {{-- SECCIÓN 7: ACTIVIDAD RECIENTE (contratos, recibos, movimientos) --}}
    {{-- ============================================================ --}}
    <div class="row g-3 mb-4">
        {{-- Últimos Contratos --}}
        <div class="col-xl-5">
            <div class="block block-rounded">
                <div class="block-header block-header-default">
                    <h3 class="block-title">
                        <i class="fa fa-file-alt me-1 text-primary"></i> Últimos Contratos
                    </h3>
                    <div class="block-options">
                        <a href="{{ route('contratos.index') }}" class="btn btn-sm btn-alt-secondary">
                            Ver todos <i class="fa fa-arrow-right ms-1"></i>
                        </a>
                    </div>
                </div>
                <div class="block-content p-0">
                    <div class="table-responsive">
                        <table class="table table-striped table-vcenter fs-sm mb-0">
                            <thead>
                                <tr class="bg-body-light">
                                    <th style="width: 60px">N°</th>
                                    <th>Cliente</th>
                                    <th style="width: 85px">Fecha</th>
                                    <th style="width: 90px">Total</th>
                                    <th style="width: 80px">Tipo</th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse($ultimosContratos as $c)
                                <tr>
                                    <td class="fw-semibold">
                                        <a href="{{ route('contratos.show', $c->id) }}">#{{ $c->id }}</a>
                                    </td>
                                    <td class="text-truncate" style="max-width: 160px" title="{{ $c->nom_cliente }}">
                                        {{ $c->nom_cliente }}
                                    </td>
                                    <td>{{ $c->fecha_local }}</td>
                                    <td class="fw-semibold">${{ number_format((float)$c->total, 0) }}</td>
                                    <td>
                                        <span class="badge bg-{{ $c->tipo_label === 'CREDITO' ? 'primary' : ($c->tipo_label === 'CONTADO' ? 'success' : 'warning') }}">
                                            {{ $c->tipo_label }}
                                        </span>
                                    </td>
                                </tr>
                                @empty
                                <tr>
                                    <td colspan="5" class="text-center text-muted py-4">
                                        <i class="fa fa-inbox fa-2x mb-2 d-block"></i>
                                        No hay contratos registrados
                                    </td>
                                </tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        {{-- Últimos Recibos --}}
        <div class="col-xl-4">
            <div class="block block-rounded">
                <div class="block-header block-header-default">
                    <h3 class="block-title">
                        <i class="fa fa-receipt me-1 text-success"></i> Últimos Recibos
                    </h3>
                    <div class="block-options">
                        <a href="{{ route('recibos.index') }}" class="btn btn-sm btn-alt-secondary">
                            Ver todos <i class="fa fa-arrow-right ms-1"></i>
                        </a>
                    </div>
                </div>
                <div class="block-content p-0">
                    <div class="table-responsive">
                        <table class="table table-striped table-vcenter fs-sm mb-0">
                            <thead class="bg-body-light">
                                <tr>
                                    <th style="width: 60px">N°</th>
                                    <th>Cliente</th>
                                    <th style="width: 80px">Bs</th>
                                    <th style="width: 80px">USD</th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse($ultimosRecibos as $r)
                                <tr>
                                    <td class="fw-semibold">
                                        <a href="{{ route('recibos.show', $r->id) }}">#{{ $r->id }}</a>
                                    </td>
                                    <td class="text-truncate" style="max-width: 140px" title="{{ $r->nom_cliente }}">
                                        {{ $r->nom_cliente }}
                                    </td>
                                    <td>Bs {{ number_format((float)$r->montocob, 2) }}</td>
                                    <td>$ {{ number_format((float)$r->montocod, 2) }}</td>
                                </tr>
                                @empty
                                <tr>
                                    <td colspan="4" class="text-center text-muted py-4">
                                        <i class="fa fa-inbox fa-2x mb-2 d-block"></i>
                                        No hay recibos registrados
                                    </td>
                                </tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        {{-- Actividad del Sistema --}}
        <div class="col-xl-3">
            <div class="block block-rounded">
                <div class="block-header block-header-default">
                    <h3 class="block-title">
                        <i class="fa fa-history me-1 text-secondary"></i> Actividad Reciente
                    </h3>
                </div>
                <div class="block-content p-0" style="max-height: 380px; overflow-y: auto">
                    @forelse($actividad as $a)
                    @php
                        $badgeClass = match(strtolower($a->tipomov_texto)) {
                            'nuevo'     => 'bg-success',
                            'modificar' => 'bg-primary',
                            'eliminar'  => 'bg-danger',
                            'login', 'logout' => 'bg-info',
                            default     => 'bg-secondary',
                        };
                        $iconMap = [
                            'nuevo' => 'fa-plus',
                            'modificar' => 'fa-edit',
                            'eliminar' => 'fa-trash',
                            'login' => 'fa-sign-in-alt',
                            'logout' => 'fa-sign-out-alt',
                        ];
                        $icon = $iconMap[strtolower($a->tipomov_texto)] ?? 'fa-bell';
                    @endphp
                    <div class="activity-timeline-item d-flex align-items-start p-3">
                        <div class="flex-shrink-0">
                            <span class="badge {{ $badgeClass }} p-2 rounded-circle">
                                <i class="fa {{ $icon }} fa-fw"></i>
                            </span>
                        </div>
                        <div class="flex-grow-1 ms-3">
                            <div class="fw-semibold">{{ $a->tipomov_texto }}</div>
                            <div class="fs-xs text-muted">
                                {{ $a->tipoid_texto ?: 'Registro' }} · ID {{ $a->id }}
                            </div>
                        </div>
                        <div class="text-end text-muted fs-xs">
                            <div>{{ $a->login }}</div>
                            <div>{{ $a->fecha_local }}<br>{{ $a->hora }}</div>
                        </div>
                    </div>
                    @empty
                    <div class="text-center text-muted py-5">
                        <i class="fa fa-inbox fa-3x mb-3 d-block"></i>
                        <p>Sin actividad reciente</p>
                    </div>
                    @endforelse
                </div>
            </div>
        </div>
    </div>

    {{-- ============================================================ --}}
    {{-- SECCIÓN 8: TOP URBANIZACIONES (contexto geográfico) --}}
    {{-- ============================================================ --}}
    @if($topUrbs->count() > 0)
    <div class="block block-rounded mb-4">
        <div class="block-header block-header-default">
            <h3 class="block-title">
                <i class="fa fa-building me-1 text-primary"></i> Top Urbanizaciones
                <span class="fs-sm text-muted ms-2">por cantidad de contratos vigentes</span>
            </h3>
        </div>
        <div class="block-content">
            @php $maxUrb = $topUrbs->max('total'); @endphp
            <div class="row g-4">
                @foreach($topUrbs as $u)
                <div class="col-md-6 col-lg-4">
                    <div class="mb-2 d-flex justify-content-between">
                        <span class="fw-semibold">{{ $u->nombre }}</span>
                        <span class="badge bg-primary rounded-pill">{{ number_format($u->total) }} contratos</span>
                    </div>
                    <div class="progress urb-progress" style="height: 28px;">
                        <div class="progress-bar urb-progress-bar bg-primary" role="progressbar" 
                             style="width: {{ round($u->total * 100 / max($maxUrb,1)) }}%;">
                            {{ $u->total }}
                        </div>
                    </div>
                </div>
                @endforeach
            </div>
        </div>
    </div>
    @endif

    {{-- ============================================================ --}}
    {{-- SECCIÓN 9: FOOTER INFORMATIVO (opcional) --}}
    {{-- ============================================================ --}}
    <div class="text-center text-muted fs-sm py-3">
        <i class="fa fa-sync-alt me-1"></i> Datos actualizados al {{ $fechaSistema }}
        <span class="mx-2">•</span>
        <i class="fa fa-database me-1"></i> Base: {{ $bd }}
    </div>
</div>
@endsection

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Detectar tema OneUI
        const isDarkTheme = document.documentElement.classList.contains('dark');
        const textColor = isDarkTheme ? '#9ca3af' : '#6b7280';
        const gridColor = isDarkTheme ? 'rgba(255,255,255,0.07)' : 'rgba(0,0,0,0.06)';

        const defaultOpts = {
            responsive: true,
            maintainAspectRatio: true,
            plugins: { legend: { display: false } },
            scales: {
                x: { 
                    ticks: { color: textColor, font: { size: 11 } }, 
                    grid: { color: gridColor, display: false }
                },
                y: { 
                    ticks: { color: textColor, font: { size: 11 } }, 
                    grid: { color: gridColor }
                }
            }
        };

        // Gráfico de Cobranza
        const cobranzaData = @json($cobranzaMeses);
        if (cobranzaData.length > 0) {
            new Chart(document.getElementById('chartCobranza'), {
                type: 'bar',
                data: {
                    labels: cobranzaData.map(d => d.label),
                    datasets: [{
                        label: 'Cobranza USD',
                        data: cobranzaData.map(d => d.monto),
                        backgroundColor: isDarkTheme ? 'rgba(59, 130, 246, 0.6)' : '#bfdbfe',
                        borderColor: '#3b82f6',
                        borderWidth: 1.5,
                        borderRadius: 6,
                    }]
                },
                options: {
                    ...defaultOpts,
                    plugins: {
                        tooltip: {
                            callbacks: { 
                                label: ctx => ' $ ' + ctx.raw.toLocaleString('es-BO', {minimumFractionDigits:2}) 
                            }
                        }
                    }
                }
            });
        }

        // Gráfico de Contratos
        const contratosData = @json($contratosMeses);
        if (contratosData.length > 0) {
            new Chart(document.getElementById('chartContratos'), {
                type: 'line',
                data: {
                    labels: contratosData.map(d => d.label),
                    datasets: [{
                        label: 'Contratos nuevos',
                        data: contratosData.map(d => d.cnt),
                        borderColor: '#10b981',
                        backgroundColor: isDarkTheme ? 'rgba(16, 185, 129, 0.1)' : 'rgba(5, 122, 85, 0.08)',
                        borderWidth: 2.5,
                        pointBackgroundColor: '#10b981',
                        pointBorderColor: isDarkTheme ? '#1f2937' : '#fff',
                        pointRadius: 5,
                        pointHoverRadius: 7,
                        fill: true,
                        tension: 0.3,
                    }]
                },
                options: {
                    ...defaultOpts,
                    scales: {
                        ...defaultOpts.scales,
                        y: { 
                            ...defaultOpts.scales.y, 
                            beginAtZero: true, 
                            ticks: { stepSize: 1, precision: 0 }
                        }
                    }
                }
            });
        }
    });
</script>
@endpush