<!DOCTYPE html>
<html lang="es">

<head>
    <meta charset="UTF-8">
    <title>Estadi­sticas</title>
    @vite(["resources/css/layout.css"])
    <!-- CDN Tailwind (Ãºtil en dev). En prod compÃ­lalo con Vite/PostCSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tom-select/dist/css/tom-select.css">
    <script src="https://cdn.jsdelivr.net/npm/tom-select/dist/js/tom-select.complete.min.js"></script>

    <style>
        :root {
            --bg: #f5f7fb;
            --surface: #ffffff;
            --text: #1f2937;
            --muted: #6b7280;
            --border: #e5e7eb;

            --primary: #2155CD;
            /* azul corporativo */
            --primary-600: #1b47ab;
            /* hover */
            --primary-50: #edf2ff;

            --accent: #2155CD;
            /* verde acción */
            --accent-600: #1b47ab;
        }

        .tab-panel {
            display: none;
        }

        .tab-panel.active {
            display: block;
        }

        /* ===== Header ===== */
        /* ===== Header (gradiente global) ===== */
        .app-header {
            position: flex;
            top: 0;
            z-index: 50;
            background: linear-gradient(180deg, #2e43a7 0%, #3256b0 35%, #3b7cbd 100%);
            color: #fff;
            box-shadow: 0 2px 10px rgba(0, 0, 0, .08);
        }

        .app-header .inner {
            max-width: 1200px;
            margin: 0 auto;
            display: flex;
            align-items: center;
            gap: 16px;
            padding: 14px 20px;
        }

        .app-header .btn-ghost {
            background: transparent;
            border: 1px solid rgba(255, 255, 255, .35);
            color: #fff;
        }

        .app-header .btn-ghost:hover {
            background: rgba(255, 255, 255, .08);
        }

        .brand {
            display: flex;
            align-items: center;
            gap: 10px;
            font-weight: 700;
            letter-spacing: .2px;
        }

        .brand .logo {
            width: 258px;
            height: 80px;
            display: grid;
            place-items: center;
            background: linear-gradient(180deg, #2e43a7 0%, #3256b0 35%, #3b7cbd 100%);
            color: #fff;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 800;
        }

        .brand .logo img {
            width: 100%;
            height: 100%;
            object-fit: contain;
            display: block;
        }

        .btn {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            border-radius: 10px;
            padding: 10px 16px;
            font-weight: 700;
            border: 1px solid transparent;
            cursor: pointer;
        }

        .btn-primary {
            background: var(--primary);
            color: #fff;
        }

        .btn-primary:hover {
            background: var(--primary-600);
        }

        .btn-accent {
            background: var(--accent);
            color: #fff;
            margin-top: 10px;
        }

        .btn-accent:hover {
            background: var(--accent-600);
        }

        .btn-ghost {
            background: #fff;
            border: 1px solid var(--border);
            color: var(--text);
        }

        .chart-wrap {
            position: relative;
            height: 360px;
            /* o el alto que uses */
            overflow: visible;
            /* NO hidden, para que no recorte labels */
        }
    </style>
</head>

<body class="bg-gray-100">
    <div class="area">
        <header class="app-header">
            <div class="inner">
                <div class="brand">
                    <div class="logo">
                        <img src="{{ asset('img/logo.png') }}" alt="Logo">
                    </div>
                    <div>Seguimiento contractual capitas</div>
                </div>
                <div style="margin-left:auto; display:flex; gap:10px">
                    <a href="{{ url('/auditoria_capita') }}" class="btn btn-ghost">Inicio</a>
                </div>
            </div>
        </header>
        <!-- Fondo decorativo igual que Home/Layout -->
        <ul class="circles">
            <li></li>
            <li></li>
            <li></li>
            <li></li>
            <li></li>
            <li></li>
            <li></li>
            <li></li>
            <li></li>
            <li></li>
        </ul>
        <div class="layout-content">

            @php
                // KPIs simples desde lo que ya llega a la vista
                $roundPercent = function ($v) {
                    $floor = floor($v);
                    return $floor + (($v - $floor) > 0.6 ? 1 : 0);
                };
                $avg = function ($col) use ($chartRegionalMulti, $roundPercent) {
                    $vals = collect($chartRegionalMulti ?? [])->pluck($col)->filter(fn($v) => $v !== null)->values();
                    return $vals->count() ? $roundPercent($vals->avg()) : 0;
                };
                $kpiResultado = $avg('resultado');
                $kpiEjecucion = $avg('ejecucion');
                $kpiSalud = $avg('salud');
                $kpiGeneralidades = $avg('generalidades');

                // Opciones para filtros desde colecciones ya agregadas (sin nuevas consultas)
                $optsRegional = collect($chartRegionalMulti)->pluck('etiqueta')->unique()->values();
                $optsDepto = collect($chartDeptoMulti)->pluck('etiqueta')->unique()->values();
                $optsRazon = collect($chartRazonMulti)->pluck('etiqueta')->unique()->values();
                $optsSede = collect($chartSedeMulti)->pluck('etiqueta')->unique()->values();
            @endphp


            

                <h1 style="font-size:20px; font-weight:700; margin:0 0 16px;">Aplicativo Auditoria Capita > Home >
                    Estadisticas </h1>

                <div class="grid grid-cols-12 gap-6">
                    <!-- ================== IZQUIERDA: FILTROS + KPIs ================== -->
                    <aside class="col-span-12 md:col-span-3 space-y-6">

                        <!-- KPIs -->
                        <section class="border rounded-2xl p-5 shadow bg-white">
                            <h3 class="font-semibold mb-4">Resumen</h3>
                            <div class="space-y-3">
                                <div class="flex items-center justify-between"><span
                                        class="text-sm text-gray-600">Resultado
                                        global</span><span class="font-semibold">{{ $kpiResultado }}%</span></div>
                                <div class="flex items-center justify-between"><span
                                        class="text-sm text-gray-600">Ejecucion</span><span
                                        class="font-semibold">{{ $kpiEjecucion }}%</span></div>
                                <div class="flex items-center justify-between"><span
                                        class="text-sm text-gray-600">Resultados en salud</span><span
                                        class="font-semibold">{{ $kpiSalud }}%</span></div>
                                <div class="flex items-center justify-between"><span
                                        class="text-sm text-gray-600">Generalidades</span><span
                                        class="font-semibold">{{ $kpiGeneralidades }}%</span></div>
                            </div>

                            @if(request()->hasAny(['regional', 'departamento', 'razon_social', 'sede', 'tipo_red', 'trimestre_evaluado', 'anio_vigencia']))
                                <div class="mt-4">
                                    <p class="text-xs text-gray-500 mb-2">Filtros activos:</p>
                                    <div class="flex flex-wrap gap-2">
                                        @foreach(['regional', 'departamento', 'razon_social', 'sede', 'tipo_red', 'trimestre_evaluado', 'anio_vigencia'] as $f)
                                            @if(request($f))
                                                <span
                                                    class="text-xs bg-indigo-50 text-indigo-700 px-2 py-1 rounded">{{ ucfirst(str_replace('_', ' ', $f)) }}:
                                                    {{ request($f) }}</span>
                                            @endif
                                        @endforeach
                                    </div>
                                </div>
                            @endif
                        </section>

                        <!-- Filtros (GET) -->
                        <section class="border rounded-2xl p-5 shadow bg-white">
                            <h3 class="font-semibold mb-4">Filtros</h3>
                            <form method="GET" action="{{ url()->current() }}" class="space-y-4">
                                <div>
                                    <label class="text-sm font-medium">Regional</label>
                                    <select name="regional" class="mt-1 w-full border rounded p-2">
                                        <option value="">â€” Todas â€”</option>
                                        @foreach($optsRegional as $opt)
                                            <option value="{{ $opt }}" @selected(request('regional') == $opt)>{{ $opt }}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>
                                <div>
                                    <label class="text-sm font-medium">Departamento</label>
                                    <select name="departamento" class="mt-1 w-full border rounded p-2">
                                        <option value="">â€” Todos â€”</option>
                                        @foreach($optsDepto as $opt)
                                            <option value="{{ $opt }}" @selected(request('departamento') == $opt)>{{ $opt }}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>
                                <div>
                                    <label class="text-sm font-medium">RazÃ³n social</label>
                                    <select name="razon_social" class="mt-1 w-full border rounded p-2">
                                        <option value="">â€” Todas â€”</option>
                                        @foreach($optsRazon as $opt)
                                            <option value="{{ $opt }}" @selected(request('razon_social') == $opt)>{{ $opt }}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>
                                <div>
                                    <label class="text-sm font-medium">Sede</label>
                                    <select name="sede" class="mt-1 w-full border rounded p-2">
                                        <option value="">â€” Todas â€”</option>
                                        @foreach($optsSede as $opt)
                                            <option value="{{ $opt }}" @selected(request('sede') == $opt)>{{ $opt }}</option>
                                        @endforeach
                                    </select>
                                </div>
                                <div>
                                    <label class="text-sm font-medium">Tipo de red</label>
                                    <select name="tipo_red" class="mt-1 w-full border rounded p-2">
                                        <option value="">â€” Todos â€”</option>
                                        @foreach($optsTipoRed as $opt)
                                            <option value="{{ $opt }}" @selected(request('tipo_red') == $opt)>{{ $opt }}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>
                                <div>
                                    <label class="text-sm font-medium">Trimestre evaluado</label>
                                    <select name="trimestre_evaluado" class="mt-1 w-full border rounded p-2">
                                        <option value="">â€” Todos â€”</option>
                                        @foreach($optsTrimestre as $opt)
                                            <option value="{{ $opt }}" @selected(request('trimestre_evaluado') == $opt)>
                                                {{ $opt }}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>
                                <div>
                                    <label class="text-sm font-medium">Año vigencia</label>
                                    <select name="anio_vigencia" class="mt-1 w-full border rounded p-2">
                                        <option value="">â€” Todos â€”</option>
                                        @foreach($optsAnioVigencia as $opt)
                                            <option value="{{ $opt }}" @selected(request('anio_vigencia') == $opt)>{{ $opt }}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>

                                <div class="flex gap-2 pt-2">
                                    <button class="px-4 py-2 rounded bg-indigo-600 text-white hover:bg-indigo-700"
                                        type="submit">
                                        Aplicar
                                    </button>
                                    <a href="{{ url()->current() }}"
                                        class="px-4 py-2 rounded bg-gray-200 hover:bg-gray-300">
                                        Limpiar
                                    </a>
                                </div>
                            </form>
                        </section>

                    </aside>


                    <!-- ================== DERECHA: TABS + GRÃFICAS ================== -->
                    <main class="col-span-12 md:col-span-9">
                        <section class="border rounded-2xl p-8 width-100% shadow bg-white">
                            <!-- Tabs -->
                            <div class="flex gap-4 border-b">
                                <button id="tab-general" class="px-4 py-2 border-b-2 border-indigo-600 font-semibold"
                                    onclick="showTab('general')">General</button>
                                <button id="tab-salud" class="px-4 py-2" onclick="showTab('salud')">Resultados en
                                    Salud</button>
                                <button id="tab-ejecucion" class="px-4 py-2" onclick="showTab('ejecucion')">Ejecucion
                                    del
                                    contrato</button>
                                <button id="tab-ajustes" class="px-4 py-2" onclick="showTab('ajustes')">Ajustes</button>
                            </div>

                            <!-- Panel: General (multi) -->
                            <div id="panel-general" class="tab-panel active">
                                <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mt-6">

                                    <!-- ðŸ“Š EJECUCIÃ“N -->
                                    <div class="bg-white border rounded-2xl shadow p-6 chart-box">
                                        <h3 class="text-lg font-bold text-indigo-600 border-b pb-2 mb-4">Ejecucion</h3>
                                        <ul class="space-y-2 text-gray-700 font-medium">
                                            <li>Ejec I: {{ $trimestres->ejecucion_i ?? 0 }}%</li>
                                            <li>Ejec II: {{ $trimestres->ejecucion_ii ?? 0 }}%</li>
                                            <li>Ejec III: {{ $trimestres->ejecucion_iii ?? 0 }}%</li>
                                            <li>Ejec IV: {{ $trimestres->ejecucion_iv ?? 0 }}%</li>
                                        </ul>
                                    </div>

                                    <!-- ðŸ¥ SALUD -->
                                    <div class="bg-white border rounded-2xl shadow p-6 chart-box">
                                        <h3 class="text-lg font-bold text-green-600 border-b pb-2 mb-4">Salud</h3>
                                        <ul class="space-y-2 text-gray-700 font-medium">
                                            <li>Salud I-II: {{ $trimestres->salud_i_ii ?? 0 }}%</li>
                                            <li>Salud III: {{ $trimestres->salud_iii ?? 0 }}%</li>
                                            <li>Salud IV: {{ $trimestres->salud_iv ?? 0 }}%</li>
                                        </ul>
                                    </div>

                                    <!-- ðŸ“‘ GENERALIDADES -->
                                    <div class="bg-white border rounded-2xl shadow p-6 chart-box">
                                        <h3 class="text-lg font-bold text-blue-600 border-b pb-2 mb-4">Generalidades
                                        </h3>
                                        <ul class="space-y-2 text-gray-700 font-medium">
                                            <li>Gen I-II: {{ $trimestres->generalidades_i_ii ?? 0 }}%</li>
                                            <li>Gen III: {{ $trimestres->generalidades_iii ?? 0 }}%</li>
                                            <li>Gen IV: {{ $trimestres->generalidades_iv ?? 0 }}%</li>
                                        </ul>
                                    </div>

                                </div>


                                <div class="flex flex-col gap-8 mt-6">
                                    <div class="border rounded-xl p-4 bg-white shadow h-[500px]">
                                        <h3 class="font-semibold mb-3">Por Regional</h3>
                                        <canvas id="grafico_regional"></canvas>
                                    </div>
                                    <div class="border rounded-xl p-4 bg-white shadow h-[500px]">
                                        <h3 class="font-semibold mb-3">Por Departamento</h3>
                                        <canvas id="grafico_departamento"></canvas>
                                    </div>
                                    <div class="border rounded-xl p-4 bg-white shadow h-[500px] overflow-x-auto">
                                        <h3 class="font-semibold mb-3">Por Razon Social</h3>
                                        <canvas id="grafico_razon"></canvas>
                                    </div>
                                    <div class="border rounded-xl p-4 bg-white shadow h-[500px] overflow-x-auto">
                                        <h3 class="font-semibold mb-3">Por Sede</h3>
                                        <canvas id="grafico_sede"></canvas>
                                    </div>
                                </div>
                            </div>

                            <!-- Panel: Salud (detalle) -->
                            <div id="panel-salud" class="tab-panel">
                                <div class="bg-white border rounded-2xl shadow p-6 chart-box mt-6">
                                    <h3 class="text-lg font-bold text-green-600 border-b pb-2 mb-4">Salud</h3>
                                    <div class="flex flex-wrap gap-4">
                                        <span class="text-gray-700 font-medium">
                                            I-II: {{ $roundPercent($trimestres->salud_i_ii ?? 0) }}%
                                        </span>
                                        <span class="text-gray-700 font-medium">
                                            III: {{ $roundPercent($trimestres->salud_iii ?? 0) }}%
                                        </span>
                                        <span class="text-gray-700 font-medium">
                                            IV: {{ $roundPercent($trimestres->salud_iv ?? 0) }}%
                                        </span>
                                    </div>
                                </div>


                                <div class="flex flex-col gap-8 mt-6">
                                    <div class="border rounded-xl p-4 bg-white shadow h-[500px]">
                                        <h3 class="font-semibold mb-3">Por Regional</h3>
                                        <canvas id="grafico_regional_salud"></canvas>
                                    </div>
                                    <div class="border rounded-xl p-4 bg-white shadow h-[500px]">
                                        <h3 class="font-semibold mb-3">Por Departamento</h3>
                                        <canvas id="grafico_departamento_salud"></canvas>
                                    </div>
                                    <div class="border rounded-xl p-4 bg-white shadow h-[500px] overflow-x-auto">
                                        <h3 class="font-semibold mb-3">Por Razon Social</h3>
                                        <canvas id="grafico_razon_salud"></canvas>
                                    </div>
                                    <div class="border rounded-xl p-4 bg-white shadow h-[500px] overflow-x-auto">
                                        <h3 class="font-semibold mb-3">Por Sede</h3>
                                        <canvas id="grafico_sede_salud"></canvas>
                                    </div>
                                </div>
                            </div>

                            <!-- Panel: EjecuciÃ³n (detalle) -->
                            <div id="panel-ejecucion" class="tab-panel">
                                <div class="bg-white border rounded-2xl shadow p-6 chart-box mt-6">
                                    <h3 class="text-lg font-bold text-indigo-600 border-b pb-2 mb-4">Ejecucion</h3>
                                    <div class="flex flex-wrap gap-4">
                                        <span class="text-gray-700 font-medium">
                                            I: {{ $roundPercent($trimestres->ejecucion_i ?? 0) }}%
                                        </span>
                                        <span class="text-gray-700 font-medium">
                                            II: {{ $roundPercent($trimestres->ejecucion_ii ?? 0) }}%
                                        </span>
                                        <span class="text-gray-700 font-medium">
                                            III: {{ $roundPercent($trimestres->ejecucion_iii ?? 0) }}%
                                        </span>
                                        <span class="text-gray-700 font-medium">
                                            IV: {{ $roundPercent($trimestres->ejecucion_iv ?? 0) }}%
                                        </span>
                                    </div>
                                </div>

                                <div class="flex flex-col gap-8 mt-6">
                                    <div class="border rounded-xl p-4 bg-white shadow h-[500px]">
                                        <h3 class="font-semibold mb-3">Por Regional</h3>
                                        <canvas id="grafico_regional_ejecucion"></canvas>
                                    </div>
                                    <div class="border rounded-xl p-4 bg-white shadow h-[500px]">
                                        <h3 class="font-semibold mb-3">Por Departamento</h3>
                                        <canvas id="grafico_departamento_ejecucion"></canvas>
                                    </div>
                                    <div class="border rounded-xl p-4 bg-white shadow h-[500px] overflow-x-auto">
                                        <h3 class="font-semibold mb-3">Por RazÃ³n Social</h3>
                                        <canvas id="grafico_razon_ejecucion"></canvas>
                                    </div>
                                    <div class="border rounded-xl p-4 bg-white shadow h-[500px] overflow-x-auto">
                                        <h3 class="font-semibold mb-3">Por Sede</h3>
                                        <canvas id="grafico_sede_ejecucion"></canvas>
                                    </div>
                                </div>
                            </div>
                            <!-- Panel: Ajustes -->
                            <div id="panel-ajustes" class="tab-panel">
                                <div class="bg-white border rounded-2xl shadow p-6 chart-box mt-6">
                                    <h3 class="text-lg font-bold text-amber-600 border-b pb-2 mb-4">Ajustes</h3>
                                    <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                                        <div class="bg-white border rounded-2xl shadow p-6 chart-box">
                                            <div class="text-sm text-gray-600 mb-1">Total Ajustes</div>
                                            <div class="text-2xl font-bold">$
                                                {{ number_format(($ajustes->ajuste_total ?? 0), 2, ',', '.') }}
                                            </div>
                                        </div>
                                        <div class="bg-white border rounded-2xl shadow p-6 chart-box">
                                            <div class="text-sm text-gray-600 mb-1">Detalle por trimestre</div>
                                            <ul class="space-y-1 text-gray-700 font-medium">
                                                <li>I: $ {{ number_format(($ajustes->ajuste_i ?? 0), 2, ',', '.') }}
                                                </li>
                                                <li>II: $ {{ number_format(($ajustes->ajuste_ii ?? 0), 2, ',', '.') }}
                                                </li>
                                                <li>III: $ {{ number_format(($ajustes->ajuste_iii ?? 0), 2, ',', '.') }}
                                                </li>
                                                <li>IV: $ {{ number_format(($ajustes->ajuste_iv ?? 0), 2, ',', '.') }}
                                                </li>
                                            </ul>
                                        </div>
                                        <div class="border rounded-xl p-4 bg-white shadow">
                                            <h4 class="font-semibold mb-2">Distribucion</h4>
                                            <div class="chart-wrap">
                                                <canvas id="grafico_ajustes_pie"></canvas>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                        </section>
                    </main>
                </div>
            

            <!-- Modal para ver grÃ¡ficos en grande -->
            <div id="chartModal" class="fixed inset-0 bg-black bg-opacity-50 hidden items-center justify-center z-50">
                <div class="bg-white p-4 rounded shadow-lg relative max-w-4xl w-11/12">
                    <button class="absolute top-2 right-2 text-gray-600" onclick="closeChartModal()">&times;</button>
                    <img id="chartModalImg" class="w-full h-auto" alt="GrÃ¡fico ampliado" />
                </div>
            </div>

            <script>
                const FILTER_MATRIX = @json($filterMatrix);
                document.addEventListener('DOMContentLoaded', () => {
                    const selects = {
                        regional: new TomSelect('select[name="regional"]', { allowEmptyOption: true, sortField: { field: 'text', direction: 'asc' } }),
                        departamento: new TomSelect('select[name="departamento"]', { allowEmptyOption: true, sortField: { field: 'text', direction: 'asc' } }),
                        razon_social: new TomSelect('select[name="razon_social"]', { allowEmptyOption: true, sortField: { field: 'text', direction: 'asc' } }),
                        sede: new TomSelect('select[name="sede"]', { allowEmptyOption: true, sortField: { field: 'text', direction: 'asc' } }),
                        tipo_red: new TomSelect('select[name="tipo_red"]', { allowEmptyOption: true, sortField: { field: 'text', direction: 'asc' } }),
                        trimestre_evaluado: new TomSelect('select[name="trimestre_evaluado"]', { allowEmptyOption: true, sortField: { field: 'text', direction: 'asc' } }),
                        anio_vigencia: new TomSelect('select[name="anio_vigencia"]', { allowEmptyOption: true, sortField: { field: 'text', direction: 'asc' } })
                    };

                    function recompute(changed) {
                        const current = {};
                        Object.keys(selects).forEach(k => current[k] = selects[k].getValue());
                        Object.keys(selects).forEach(key => {
                            if (key === changed) return;
                            const sel = selects[key];
                            const options = new Set();
                            FILTER_MATRIX.forEach(row => {
                                let match = true;
                                for (const [k, v] of Object.entries(current)) {
                                    if (k === key) continue;
                                    if (v && row[k] !== v) { match = false; break; }
                                }
                                if (match && row[key]) options.add(row[key]);
                            });
                            const value = current[key];
                            sel.clearOptions();
                            sel.addOption({ value: '', text: 'â€” Todos â€”' });
                            Array.from(options).sort().forEach(opt => sel.addOption({ value: opt, text: opt }));
                            sel.refreshOptions(false);
                            if (value && options.has(value)) {
                                sel.setValue(value, false);
                            } else {
                                sel.clear(true);
                            }
                        });
                    }

                    Object.keys(selects).forEach(key => {
                        selects[key].on('change', () => recompute(key));
                    });

                    recompute(null);
                });
            </script>

            <script>

                Chart.register(ChartDataLabels);

                // ===== Datos enviados por tu controlador (tal cual) =====
                const REGIONAL = @json($chartRegionalMulti);
                const DEPARTAMENTO = @json($chartDeptoMulti);
                const RAZON = @json($chartRazonMulti);
                const SEDE = @json($chartSedeMulti);
                // Fallback array para posibles claves trimestrales que puedan quedar referenciadas
                const GEN_KEYS = ['resultado', 'ejecucion', 'salud', 'generalidades'];

                // Control de renderizado por pestaÃ±a (evita re-dibujar innecesariamente)
                const painted = { salud: false, ejecucion: false };

                // ===== Store de instancias Chart para destruir antes de repintar =====
                const charts = {};
                function destroyChart(id) { if (charts[id]) { try { charts[id].destroy(); } catch (_) { } charts[id] = null; } }

                // ===== Utilidades de ejes y opciones =====
                // Trunca etiquetas largas del eje X (tooltip nativo mantiene el texto completo)
                function xTickFormatter() {
                    return function (value) {
                        const full = this.getLabelForValue ? this.getLabelForValue(value) : String(value ?? '');
                        return full.length > 14 ? (full.slice(0, 14) + 'â€¦') : full;
                    };
                }

                // Opciones de barras en %, con X opcional vertical y truncado
                // Opciones de barras en %, con X opcional vertical y truncado
                function barOptionsPercent({ verticalX = false, truncateX = false, labels = [], maxY = 100 } = {}, caso = '') {
                    const max = Math.max(100, maxY);
                    return {
                        responsive: true,
                        maintainAspectRatio: false,
                        interaction: { mode: 'index', intersect: false },
                        layout: { padding: { left: 12, right: 12, top: 12, bottom: 8 } }, // un poco mÃ¡s arriba para el label
                        plugins: {
                            legend: { display: true },
                            tooltip: {
                                callbacks: {
                                    label: ctx => `${ctx.dataset.label}: ${ctx.parsed.y}%`
                                }
                            },
                            // â¬‡ï¸ Etiquetas sobre cada barra
                            datalabels: {
                                formatter: (v, ctx) => (v == null ? '' : `${v}%`),
                                color: '#111827',         // gris-900
                                font: { size: 10, weight: '600' },
                                anchor: 'end',            // ancla al final de la barra
                                align: 'end',             // coloca el texto arriba de la barra
                                offset: -2,               // pequeÃ±o ajuste vertical
                                clip: false,              // no recortar el texto
                                clamp: true,              // si se sale, lo â€œpegaâ€ al borde
                                display: (ctx) => {
                                    const v = ctx.dataset.data?.[ctx.dataIndex];
                                    // oculta si es 0 o null (ajusta a tu gusto)
                                    return v != null && v !== 0;
                                }
                            }
                        },
                        scales: {
                            x: {
                                offset: Array.isArray(labels) && labels.length > 0,
                                ticks: Object.assign(
                                    { autoSkip: false, font: { size: 10 }, padding: 6 },
                                    verticalX ? { minRotation: 45, maxRotation: 45 } : { minRotation: 90, maxRotation: 90 },
                                    truncateX ? { callback: xTickFormatter() } : {}
                                )
                            },
                            y: {
                                min: 0,
                                max,
                                grace: '10%', // mÃ¡s â€œaireâ€ arriba para que quepan los labels
                                ticks: { callback: v => v + '%' }
                            }
                        }
                    };
                }

                // ===== Scroll dentro de la grÃ¡fica (wrapper dinÃ¡mico) =====
                function makeScrollable(canvasId, { axis = 'x', labels = [], perPx = 50, minPx = 900 } = {}) {
                    const canvas = document.getElementById(canvasId);
                    if (!canvas) return;

                    const card = canvas.parentElement; // card contenedor
                    if (!card) return;

                    // crea/reusa un wrapper interno
                    const wrapId = canvasId + '-wrap';
                    let wrap = document.getElementById(wrapId);
                    if (!wrap) {
                        wrap = document.createElement('div');
                        wrap.id = wrapId;
                        wrap.style.height = '100%';
                        wrap.style.display = 'block';
                        card.insertBefore(wrap, canvas);
                        wrap.appendChild(canvas);
                    }

                    const count = Array.isArray(labels) ? labels.length : 0;
                    const sizePx = Math.max(minPx, count * perPx);

                    if (axis === 'x') {
                        card.style.overflowX = 'auto';
                        card.style.overflowY = 'hidden';
                        wrap.style.width = sizePx + 'px';
                        wrap.style.height = '100%';
                    } else {
                        card.style.overflowY = 'auto';
                        card.style.overflowX = 'hidden';
                        wrap.style.height = sizePx + 'px';
                        wrap.style.width = '100%';
                    }
                }

                // ===== Dibujo de grÃ¡ficos =====
                function drawMulti(canvasId, arr, opts = {}) {
                    const el = document.getElementById(canvasId); if (!el) return;
                    destroyChart(canvasId);

                    const L = (arr ?? []).map(x => x?.etiqueta ?? '');
                    const datasets = [
                        { label: 'Resultado', data: (arr ?? []).map(x => Number(x?.resultado ?? 0)) },
                        { label: 'EjecuciÃ³n', data: (arr ?? []).map(x => Number(x?.ejecucion ?? 0)) },
                        { label: 'Salud', data: (arr ?? []).map(x => Number(x?.salud ?? 0)) },
                        { label: 'Generalidades', data: (arr ?? []).map(x => Number(x?.generalidades ?? 0)) },
                    ];
                    const maxY = Math.max(0, ...datasets.flatMap(d => d.data));

                    charts[canvasId] = new Chart(el.getContext('2d'), {
                        type: 'line',
                        data: { labels: L, datasets },
                        options: barOptionsPercent(Object.assign({}, opts, { labels: L, maxY }))
                    });
                }

                function drawSingle(canvasId, arr, key, label, opts = {}) {
                    const el = document.getElementById(canvasId); if (!el) return;
                    destroyChart(canvasId);

                    const L = (arr ?? []).map(x => x?.etiqueta ?? '');
                    const data = (arr ?? []).map(x => Number(x?.[key] ?? 0));
                    const maxY = Math.max(0, ...data);
                    charts[canvasId] = new Chart(el.getContext('2d'), {
                        type: 'line',
                        data: { labels: L, datasets: [{ label, data }] },
                        options: barOptionsPercent(Object.assign({}, opts, { labels: L, maxY }))
                    });
                }

                function drawTrimestres(canvasId, arr, keys = [], labels = [], opts = {}) {
                    const el = document.getElementById(canvasId); if (!el) return;
                    destroyChart(canvasId);

                    const L = (arr ?? []).map(x => x?.etiqueta ?? '');
                    const datasets = keys.map((k, i) => ({ label: labels[i] || k, data: (arr ?? []).map(x => Number(x?.[k] ?? 0)) }));
                    const maxY = Math.max(0, ...datasets.flatMap(d => d.data));

                    charts[canvasId] = new Chart(el.getContext('2d'), {
                        type: 'bar',
                        data: { labels: L, datasets },
                        options: barOptionsPercent(Object.assign({}, opts, { labels: L, maxY }))
                    });
                }

                // ===== Render inicial: General =====



                // RazÃ³n/Sede con scroll horizontal, X vertical + truncado
                (function () {
                    // Regional/Depto normal
                    drawMulti('grafico_regional', REGIONAL, { verticalX: true });

                    const L_departamento = (DEPARTAMENTO ?? []).map(x => x?.etiqueta ?? '');
                    makeScrollable('grafico_razon', { axis: 'x', labels: L_departamento, perPx: 50, minPx: 900 });
                    drawMulti('grafico_departamento', DEPARTAMENTO, { verticalX: true });

                    const L_razon = (RAZON ?? []).map(x => x?.etiqueta ?? '');
                    makeScrollable('grafico_razon', { axis: 'x', labels: L_razon, perPx: 50, minPx: 900 });
                    drawMulti('grafico_razon', RAZON, { verticalX: false });

                    const L_sede = (SEDE ?? []).map(x => x?.etiqueta ?? '');
                    makeScrollable('grafico_sede', { axis: 'x', labels: L_sede, perPx: 50, minPx: 900 });
                    drawMulti('grafico_sede', SEDE, { verticalX: true });
                })();

                // ===== Tabs con render "lazy" =====
                function showTab(name) {
                    document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
                    document.getElementById('panel-' + name).classList.add('active');

                    document.querySelectorAll('[id^=tab-]').forEach(b => b.classList.remove('border-b-2', 'border-indigo-600', 'font-semibold'));
                    document.getElementById('tab-' + name).classList.add('border-b-2', 'border-indigo-600', 'font-semibold');

                    if (name === 'salud' && !painted.salud) {
                        renderSalud();
                        painted.salud = true;
                    }
                    if (name === 'ejecucion' && !painted.ejecucion) {
                        renderEjecucion();
                        painted.ejecucion = true;
                    }
                    if (name === 'ajustes' && !painted.ajustes) {
                        renderAjustes();
                        painted.ajustes = true;
                    }
                }

                function renderSalud() {
                    // Regional/Depto normal
                    drawTrimestres('grafico_regional_salud', REGIONAL, ['salud_i_ii', 'salud_iii', 'salud_iv'], ['I-II', 'III', 'IV'], { verticalX: true });
                    drawTrimestres('grafico_departamento_salud', DEPARTAMENTO, ['salud_i_ii', 'salud_iii', 'salud_iv'], ['I-II', 'III', 'IV'], { verticalX: true });

                    console.log('RAZON', RAZON);
                    // RazÃ³n/Sede con scroll horizontal
                    const L_razon = (RAZON ?? []).map(x => x?.etiqueta ?? '');
                    makeScrollable('grafico_razon_salud', { axis: 'x', labels: L_razon, perPx: 50, minPx: 900 });
                    drawTrimestres('grafico_razon_salud', RAZON, ['salud_i_ii', 'salud_iii', 'salud_iv'], ['I-II', 'III', 'IV'], { verticalX: true, truncateX: true });

                    console.log('SEDE', SEDE);
                    const L_sede = (SEDE ?? []).map(x => x?.etiqueta ?? '');
                    makeScrollable('grafico_sede_salud', { axis: 'x', labels: L_sede, perPx: 50, minPx: 900 });
                    drawTrimestres('grafico_sede_salud', SEDE, ['salud_i_ii', 'salud_iii', 'salud_iv'], ['I-II', 'III', 'IV'], { verticalX: true, truncateX: true });
                }

                function renderEjecucion() {
                    // Regional/Depto normal
                    drawTrimestres('grafico_regional_ejecucion', REGIONAL, ['ejecucion_i', 'ejecucion_ii', 'ejecucion_iii', 'ejecucion_iv'], ['I', 'II', 'III', 'IV'], { verticalX: true });
                    drawTrimestres('grafico_departamento_ejecucion', DEPARTAMENTO, ['ejecucion_i', 'ejecucion_ii', 'ejecucion_iii', 'ejecucion_iv'], ['I', 'II', 'III', 'IV'], { verticalX: true });

                    // RazÃ³n/Sede con scroll horizontal
                    const L_razon = (RAZON ?? []).map(x => x?.etiqueta ?? '');
                    makeScrollable('grafico_razon_ejecucion', { axis: 'x', labels: L_razon, perPx: 50, minPx: 900 });
                    drawTrimestres('grafico_razon_ejecucion', RAZON, ['ejecucion_i', 'ejecucion_ii', 'ejecucion_iii', 'ejecucion_iv'], ['I', 'II', 'III', 'IV'], { verticalX: true, truncateX: true });

                    const L_sede = (SEDE ?? []).map(x => x?.etiqueta ?? '');
                    makeScrollable('grafico_sede_ejecucion', { axis: 'x', labels: L_sede, perPx: 50, minPx: 900 });
                    drawTrimestres('grafico_sede_ejecucion', SEDE, ['ejecucion_i', 'ejecucion_ii', 'ejecucion_iii', 'ejecucion_iv'], ['I', 'II', 'III', 'IV'], { verticalX: true, truncateX: true });
                }

                // ===== Modal de ampliaciÃ³n de grÃ¡ficas =====
                function enlargeChart(id) {
                    const canvas = document.getElementById(id);
                    if (!canvas) return;
                    const modal = document.getElementById('chartModal');
                    const img = document.getElementById('chartModalImg');
                    img.src = canvas.toDataURL('image/png');
                    modal.classList.remove('hidden');
                }

                function closeChartModal() {
                    document.getElementById('chartModal').classList.add('hidden');
                }

                document.querySelectorAll('canvas').forEach(c => {
                    c.style.cursor = 'pointer';
                    c.addEventListener('click', () => enlargeChart(c.id));
                });

                // ===== Ajustes (pie) =====
                const AJUSTES = {
                    i:  {{ (float) ($ajustes->ajuste_i ?? 0) }},
                    ii: {{ (float) ($ajustes->ajuste_ii ?? 0) }},
                    iii: {{ (float) ($ajustes->ajuste_iii ?? 0) }},
                    iv: {{ (float) ($ajustes->ajuste_iv ?? 0) }}
        };
                function renderAjustes() {
                    const el = document.getElementById('grafico_ajustes_pie'); if (!el) return;
                    const data = [AJUSTES.i, AJUSTES.ii, AJUSTES.iii, AJUSTES.iv];
                    new Chart(el.getContext('2d'), {
                        type: 'pie',
                        data: {
                            labels: ['I', 'II', 'III', 'IV'],
                            datasets: [{ data, backgroundColor: ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728'] }]
                        },
                        options: {
                            responsive: true,
                            plugins: { legend: { position: 'bottom' }, datalabels: { color: '#111', formatter: (v) => '$ ' + v.toLocaleString() } }
                        }
                    });
                }
            </script>

        </div>
    </div>
</body>

</html>