+page.svelte 28.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
<script>
  import { onMount } from 'svelte';
  import { page } from '$app/stores';
  import { goto } from '$app/navigation';

  let loading = $state(true);
  let searchQuery = $state('');
  let areas = $state([]);
  let allEntidades = $state([]);
  let selectedArea = $state(null);
  let highlightedEntidad = $state(null);
  let sidebarOpen = $state(false);

  // Modo de visualización desde URL
  let viewMode = $derived($page.url.searchParams.get('modo') || 'lista');

  // Función para cambiar de modo preservando otros parámetros
  function setMode(mode) {
    const params = new URLSearchParams($page.url.searchParams);
    if (mode === 'lista') {
      params.delete('modo');
    } else {
      params.set('modo', mode);
    }
    const query = params.toString();
    goto(`?${query}`, { replaceState: true, noScroll: true });
  }

  onMount(async () => {
    // Forzar recálculo de layout para navegación cliente
    requestAnimationFrame(() => {
      document.body.offsetHeight; // Force reflow
    });

    try {
    const res = await fetch('/api/entidad-clasificador');
    const data = await res.json();

    if (Array.isArray(data)) {
      allEntidades = data.sort((a, b) => (a.desc_area || '').localeCompare(b.desc_area || '') || (a.desc_entidad || '').localeCompare(b.desc_entidad || ''));

      // Agrupar por área (segundo nivel)
      const areasMap = {};

      data.forEach(item => {
        const areaKey = item.area;

        if (!areasMap[areaKey]) {
          areasMap[areaKey] = {
            codigo: item.area,
            nombre: item.desc_area,
            sector: item.desc_sector,
            entidades: []
          };
        }

        areasMap[areaKey].entidades.push({
          codigo: item.entidad,
          nombre: item.desc_entidad,
          sigla: item.sigla_entidad,
          años: item.n_gestiones,
          gestiones: item.gestiones,
          subarea: item.desc_subarea
        });
      });

      areas = Object.values(areasMap).sort((a, b) => a.nombre.localeCompare(b.nombre));

      if (areas.length > 0) {
        selectedArea = areas[0];
      }
    }
    } catch (err) {
      console.error('Error loading clasificador:', err);
    }

    loading = false;
  });

  // Agrupar entidades por subárea dentro del área seleccionada
  function getSubareasForArea(areaEntidades) {
    if (!areaEntidades) return [];

    const subareasMap = {};

    areaEntidades.forEach(ent => {
      const subareaKey = ent.subarea || 'Sin subárea';

      if (!subareasMap[subareaKey]) {
        subareasMap[subareaKey] = {
          nombre: subareaKey,
          entidades: []
        };
      }

      subareasMap[subareaKey].entidades.push(ent);
    });

    return Object.values(subareasMap).sort((a, b) => a.nombre.localeCompare(b.nombre));
  }

  // Búsqueda global
  function searchGlobal(query) {
    if (!query || query.length < 2) return [];
    const q = query.toLowerCase();

    return allEntidades
      .filter(item =>
        item.entidad?.toString().includes(q) ||
        item.desc_entidad?.toLowerCase().includes(q) ||
        item.sigla_entidad?.toLowerCase().includes(q)
      )
      .slice(0, 20);
  }

  function selectArea(area) {
    selectedArea = area;
    searchQuery = '';
    highlightedEntidad = null;
    sidebarOpen = false;
  }

  function goToSearchResult(item) {
    const targetArea = areas.find(a => a.codigo === item.area);

    if (targetArea) {
      selectedArea = targetArea;
      highlightedEntidad = item.entidad;
      searchQuery = '';
      sidebarOpen = false;

      setTimeout(() => {
        const element = document.getElementById(`ent-${item.entidad}`);
        if (element) {
          element.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
      }, 100);
    }
  }

  // Convertir lista de años a rangos legibles
  function formatGestiones(gestiones) {
    if (!gestiones) return '';

    const years = gestiones.split(',').map(y => parseInt(y.trim())).sort((a, b) => a - b);
    if (years.length === 0) return '';
    if (years.length === 1) return years[0].toString();

    const ranges = [];
    let start = years[0];
    let end = years[0];

    for (let i = 1; i < years.length; i++) {
      if (years[i] === end + 1) {
        end = years[i];
      } else {
        ranges.push(start === end ? `${start}` : `${start}-${end}`);
        start = years[i];
        end = years[i];
      }
    }
    ranges.push(start === end ? `${start}` : `${start}-${end}`);

    return ranges.join(', ');
  }

  let areaSubareas = $derived(selectedArea ? getSubareasForArea(selectedArea.entidades) : []);
  let searchResults = $derived(searchGlobal(searchQuery));
  let isSearching = $derived(searchQuery.length >= 2);
  let totalEntidades = $derived(allEntidades.length);
  let totalAreas = $derived(areas.length);
</script>

<svelte:head>
  <title>Institucional | Presupuesto Público</title>
  <link rel="preconnect" href="https://fonts.googleapis.com" />
  <link href="https://fonts.googleapis.com/css2?family=DM+Serif+Display:ital@0;1&family=DM+Mono:wght@400;500&family=Instrument+Sans:wght@400;500;600&display=swap" rel="stylesheet" />
</svelte:head>

<div class="min-h-screen" style="font-family: 'Instrument Sans', sans-serif; background-color: var(--theme-body); color: var(--theme-titulo); transition: background-color 0.2s, color 0.2s;">
  <!-- Header pedagógico -->
  <header class="border-b" style="border-color: var(--theme-borde); background-color: var(--theme-body);">
    <div class="max-w-screen-xl mx-auto px-4 sm:px-6 py-6">
      <!-- Breadcrumb: responsive -->
      <nav class="mb-4" style="font-family: 'DM Mono', monospace; font-size: 0.75rem;">
        <!-- Móvil: solo padre -->
        <a href="/clasificadores" class="sm:hidden transition-colors" style="color: var(--theme-texto);">
          ← Clasificadores
        </a>
        <!-- Desktop: ruta completa -->
        <div class="hidden sm:flex items-center gap-2" style="color: var(--theme-texto);">
          <a href="/" class="transition-colors hover:opacity-80">Inicio</a>
          <span style="opacity: 0.5;">/</span>
          <a href="/clasificadores" class="transition-colors hover:opacity-80">Clasificadores</a>
        </div>
      </nav>

      <div class="max-w-3xl">
        <p class="text-xs uppercase tracking-widest mb-2" style="font-family: 'DM Mono', monospace; color: var(--theme-texto);">
          Clasificador 01
        </p>
        <h1 class="text-3xl mb-3" style="font-family: 'DM Serif Display', serif; color: var(--theme-titulo);">
          ¿Quién gasta?
        </h1>
        <p class="leading-relaxed mb-3" style="color: var(--theme-texto);">
          Este clasificador identifica a las <strong style="color: var(--theme-titulo);">instituciones del Estado</strong>
          que administran y ejecutan el presupuesto público: ministerios, empresas estatales,
          gobiernos locales y entidades descentralizadas.
        </p>

        {#if totalEntidades > 0}
          <p class="text-sm mb-5" style="font-family: 'DM Mono', monospace; color: var(--theme-texto);">
            <span style="color: var(--theme-titulo); font-weight: 500;">{totalEntidades}</span> entidades públicas en
            <span style="color: var(--theme-titulo); font-weight: 500;">{totalAreas}</span> áreas institucionales
          </p>
        {/if}

        <!-- Jerarquía -->
        <div class="hidden sm:flex flex-wrap items-center gap-2 sm:gap-3 text-xs mb-6" style="font-family: 'DM Mono', monospace;">
          <span class="px-2.5 py-1 rounded-full font-medium" style="background-color: var(--theme-accent); color: var(--theme-body); opacity: 0.9;">
            Área
          </span>
          <span style="color: var(--theme-texto);">→</span>
          <span class="px-2.5 py-1 rounded-full" style="background-color: var(--theme-fill); color: var(--theme-titulo); border: 1px solid var(--theme-borde);">
            Subárea
          </span>
          <span style="color: var(--theme-texto);">→</span>
          <span class="px-2.5 py-1 rounded-full" style="background-color: var(--theme-fill); color: var(--theme-titulo); border: 1px solid var(--theme-borde);">
            Entidad
          </span>
        </div>
        <!-- Versión móvil simplificada -->
        <p class="sm:hidden text-sm mb-4" style="font-family: 'DM Mono', monospace; color: var(--theme-texto);">
          Jerarquía: Área → Subárea → Entidad
        </p>
      </div>

      <!-- Controles de visualización -->
      <div class="mt-8">
      </div>
    </div>
  </header>

  {#if loading}
    <div class="flex items-center justify-center py-20">
      <p style="color: var(--theme-texto);">Cargando clasificador...</p>
    </div>
  {:else}
    {#if viewMode === 'lista'}
    <!-- ═══════════════════════════════════════════════════════════ -->
    <!-- MODO LISTA: Navegación jerárquica de entidades              -->
    <!-- ═══════════════════════════════════════════════════════════ -->

    <!-- Botón móvil para abrir sidebar -->
    <div class="lg:hidden px-4 py-3 border-b" style="border-color: var(--theme-borde); background-color: var(--theme-fill);">
      <button
        onclick={() => sidebarOpen = !sidebarOpen}
        class="flex items-center gap-2 text-sm"
        style="color: var(--theme-texto);"
      >
        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" />
        </svg>
        <span class="font-medium">{selectedArea?.nombre || 'Seleccionar área'}</span>
        <svg class="w-4 h-4 ml-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
        </svg>
      </button>
    </div>

    <div class="clasificador-layout max-w-screen-xl mx-auto flex px-4" style="display: flex !important; flex-direction: row;">
      <!-- Sidebar izquierda: Áreas -->
      <!-- En móvil: overlay, en desktop: sidebar fijo -->
      {#if sidebarOpen}
        <div class="fixed inset-0 bg-black/30 z-40 lg:hidden" onclick={() => sidebarOpen = false}></div>
      {/if}
      <aside class="
        {sidebarOpen ? 'translate-x-0' : '-translate-x-full'}
        lg:translate-x-0
        fixed lg:relative
        inset-y-0 left-0
        w-72 lg:w-64
        z-50 lg:z-auto
        transition-transform duration-200 ease-in-out
        lg:flex-shrink-0
        shadow-xl lg:shadow-none
        sidebar-left
      ">
        <div class="h-full lg:h-screen lg:sticky lg:top-0 overflow-y-auto py-6 px-4 lg:px-0 lg:pr-6">
          <!-- Cerrar en móvil -->
          <div class="flex justify-between items-center mb-4 lg:hidden">
            <span class="text-sm font-medium" style="color: var(--theme-titulo);">Áreas institucionales</span>
            <button onclick={() => sidebarOpen = false} style="color: var(--theme-texto);">
              <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>

          <!-- Buscador -->
          <div class="mb-6">
            <input
              type="text"
              bind:value={searchQuery}
              placeholder="Buscar entidad..."
              class="w-full px-3 py-2 text-sm rounded-md focus:outline-none focus:ring-2 focus:ring-offset-0"
              style="border: 1px solid var(--theme-borde); background-color: var(--theme-surface); color: var(--theme-titulo);"
            />
          </div>

          <!-- Resultados de búsqueda -->
          {#if isSearching}
            <div class="mb-4">
              <p class="text-xs uppercase tracking-wide mb-2" style="color: var(--theme-texto);">
                {searchResults.length} resultados
              </p>
              <div class="space-y-1">
                {#each searchResults as result}
                  <button
                    class="w-full text-left px-2 py-2 text-sm rounded transition-all"
                    style="color: var(--theme-titulo);"
                    onclick={() => goToSearchResult(result)}
                  >
                    <span class="text-xs block" style="color: var(--theme-texto);">{result.desc_area}</span>
                    <span>{result.desc_entidad}</span>
                    {#if result.sigla_entidad}
                      <span class="text-xs ml-1" style="color: var(--theme-texto); opacity: 0.7;">({result.sigla_entidad})</span>
                    {/if}
                  </button>
                {/each}
                {#if searchResults.length === 0}
                  <p class="text-sm px-2" style="color: var(--theme-texto);">Sin resultados</p>
                {/if}
              </div>
            </div>
          {:else}
            <!-- Lista de áreas -->
            <nav>
              <p class="text-xs uppercase tracking-wide mb-3 px-2 hidden lg:block" style="color: var(--theme-texto);">Áreas</p>
              <ul class="space-y-1">
                {#each areas as area}
                  <li>
                    <button
                      class="w-full text-left px-3 py-2 rounded-md text-sm transition-all"
                      style="{selectedArea?.codigo === area.codigo
                        ? `background-color: color-mix(in srgb, var(--theme-accent) 15%, transparent); color: var(--theme-titulo); font-weight: 500; border-left: 2px solid var(--theme-accent);`
                        : `color: var(--theme-texto);`}"
                      onclick={() => selectArea(area)}
                    >
                      <span class="flex justify-between items-center">
                        <span class="truncate">{area.nombre}</span>
                        <span class="text-xs ml-2 flex-shrink-0" style="color: var(--theme-texto); opacity: 0.7;">{area.entidades.length}</span>
                      </span>
                    </button>
                  </li>
                {/each}
              </ul>
            </nav>
          {/if}
        </div>
      </aside>

      <!-- Contenido principal -->
      <main class="flex-1 min-w-0 lg:border-l" style="border-color: var(--theme-borde);">
        <div class="px-4 sm:px-6 lg:px-10 py-6 lg:py-8">
          {#if selectedArea}
            <!-- Título del área -->
            <div class="mb-8 lg:mb-10 pb-6 lg:pb-8 border-b" style="border-color: var(--theme-borde);">
              <p class="text-sm mb-1" style="font-family: 'DM Mono', monospace; color: var(--theme-texto);">Área {selectedArea.codigo}</p>
              <h2 class="text-lg sm:text-xl font-medium mb-2 flex items-center gap-2 sm:gap-3 flex-wrap" style="font-family: 'DM Serif Display', serif; color: var(--theme-titulo);">
                {selectedArea.nombre}
              </h2>
              <p class="text-sm" style="color: var(--theme-texto);">{selectedArea.entidades.length} entidades en esta área</p>
            </div>

            <!-- Subáreas y entidades -->
            <div class="space-y-10">
              {#each areaSubareas as subarea}
                <section id="subarea-{subarea.nombre.replace(/\s+/g, '-')}" class="scroll-mt-4">
                  {#if areaSubareas.length > 1 || subarea.nombre !== selectedArea.nombre}
                    <div class="flex items-start gap-2 sm:gap-4 mb-4">
                      <div class="flex-1">
                        <h3 class="text-base sm:text-lg font-medium" style="color: var(--theme-titulo);">{subarea.nombre}</h3>
                        <p class="text-sm" style="color: var(--theme-texto);">{subarea.entidades.length} entidades</p>
                      </div>
                    </div>
                  {/if}

                  <!-- Entidades -->
                  <div class="ml-0 sm:ml-4 lg:ml-8 space-y-2 border-l-2 pl-4 sm:pl-6 lg:pl-8" style="border-color: var(--theme-borde);">
                    {#each subarea.entidades as entidad}
                      <div
                        id="ent-{entidad.codigo}"
                        class="scroll-mt-4"
                        style="{highlightedEntidad === entidad.codigo ? `box-shadow: 0 0 0 2px color-mix(in srgb, var(--theme-accent) 30%, transparent); border-radius: 0.5rem;` : ''}"
                      >
                        <a
                          href="/entidad/{entidad.codigo}"
                          class="block px-4 py-3 rounded-lg border transition-all group"
                          style="background-color: var(--theme-surface); border-color: var(--theme-borde);"
                        >
                          <div class="flex items-start justify-between gap-3">
                            <div class="flex-1 min-w-0">
                              <div class="flex items-center gap-2 flex-wrap">
                                <span class="font-mono text-xs" style="color: var(--theme-texto);">{entidad.codigo}</span>
                                <span class="font-medium" style="color: var(--theme-titulo);">{entidad.nombre}</span>
                                {#if entidad.sigla}
                                  <span class="text-sm" style="color: var(--theme-texto); opacity: 0.7;">({entidad.sigla})</span>
                                {/if}
                              </div>
                              <p class="text-xs mt-1" style="font-family: 'DM Mono', monospace; color: var(--theme-texto);">
                                {formatGestiones(entidad.gestiones)}
                              </p>
                            </div>
                            <svg class="w-4 h-4 flex-shrink-0 mt-1 transition-colors group-hover:text-[var(--theme-accent)]" style="color: var(--theme-texto); opacity: 0.5;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
                            </svg>
                          </div>
                        </a>
                      </div>
                    {/each}
                  </div>
                </section>
              {/each}
            </div>
          {/if}
        </div>
      </main>

      <!-- Sidebar derecha: En esta página -->
      <aside class="w-56 flex-shrink-0 hidden xl:block">
        <div class="sticky top-0 h-screen overflow-y-auto py-8 pl-6 border-l" style="border-color: var(--theme-borde);">
          <p class="text-xs uppercase tracking-wide mb-3" style="color: var(--theme-texto);">En esta página</p>
          {#if selectedArea && !isSearching}
            <nav class="space-y-3">
              {#each areaSubareas as subarea}
                {#if areaSubareas.length > 1 || subarea.nombre !== selectedArea.nombre}
                  <a
                    href="#subarea-{subarea.nombre.replace(/\s+/g, '-')}"
                    class="block text-sm leading-snug transition-colors hover:opacity-80"
                    style="color: var(--theme-titulo);"
                    title={subarea.nombre}
                  >
                    {subarea.nombre}
                    <span class="text-xs ml-1" style="color: var(--theme-texto);">({subarea.entidades.length})</span>
                  </a>
                {/if}
              {/each}
              {#if areaSubareas.length === 1 && areaSubareas[0].nombre === selectedArea.nombre}
                <p class="text-sm" style="color: var(--theme-texto);">{selectedArea.entidades.length} entidades</p>
              {/if}
            </nav>
          {/if}
        </div>
      </aside>
    </div>

    {:else if viewMode === 'mapa'}
    <!-- ═══════════════════════════════════════════════════════════ -->
    <!-- MODO MAPA: Visualización geográfica del presupuesto         -->
    <!-- ═══════════════════════════════════════════════════════════ -->

    <div class="max-w-screen-xl mx-auto px-4 sm:px-6 py-8">
      <div class="border-2 border-dashed rounded-2xl min-h-[500px] flex flex-col items-center justify-center p-8" style="background-color: var(--theme-fill); border-color: var(--theme-borde);">
        <svg class="w-16 h-16 mb-4" style="color: var(--theme-texto); opacity: 0.5;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 20l-5.447-2.724A1 1 0 013 16.382V5.618a1 1 0 011.447-.894L9 7m0 13l6-3m-6 3V7m6 10l4.553 2.276A1 1 0 0021 18.382V7.618a1 1 0 00-.553-.894L15 4m0 13V4m0 0L9 7" />
        </svg>
        <h3 class="text-lg font-medium mb-2" style="font-family: 'DM Serif Display', serif; color: var(--theme-titulo);">
          Mapa de Bolivia
        </h3>
        <p class="text-center max-w-md mb-4" style="color: var(--theme-texto);">
          Visualización geográfica del presupuesto por departamento y municipio.
          El color indica el monto ejecutado por cada entidad territorial.
        </p>
        <div class="flex flex-wrap gap-2 justify-center text-xs" style="font-family: 'DM Mono', monospace; color: var(--theme-texto);">
          <span class="px-2 py-1 rounded border" style="background-color: var(--theme-surface); border-color: var(--theme-borde);">9 departamentos</span>
          <span class="px-2 py-1 rounded border" style="background-color: var(--theme-surface); border-color: var(--theme-borde);">340 municipios</span>
          <span class="px-2 py-1 rounded border" style="background-color: var(--theme-surface); border-color: var(--theme-borde);">TopoJSON + D3.js</span>
        </div>
      </div>

      <div class="mt-6 p-4 rounded-lg border" style="background-color: color-mix(in srgb, var(--theme-accent) 10%, transparent); border-color: color-mix(in srgb, var(--theme-accent) 30%, transparent);">
        <div class="flex items-start gap-3">
          <svg class="w-5 h-5 shrink-0 mt-0.5" style="color: var(--theme-accent);" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
          <div>
            <p class="text-sm font-medium" style="color: var(--theme-titulo);">Próximamente</p>
            <p class="text-sm mt-1" style="color: var(--theme-texto);">
              Esta visualización mostrará el presupuesto ejecutado en cada territorio de Bolivia.
              Podrás explorar por departamento, provincia y municipio.
            </p>
          </div>
        </div>
      </div>
    </div>

    {:else if viewMode === 'comparar'}
    <!-- ═══════════════════════════════════════════════════════════ -->
    <!-- MODO COMPARAR: Dos entidades lado a lado                    -->
    <!-- ═══════════════════════════════════════════════════════════ -->

    <div class="max-w-screen-xl mx-auto px-4 sm:px-6 py-8">
      <div class="flex flex-col lg:flex-row gap-6 lg:gap-8 mb-8">
        <!-- Lado A -->
        <div class="flex-1">
          <div class="flex items-center gap-3 mb-4">
            <span class="w-8 h-8 rounded-full flex items-center justify-center font-semibold text-sm" style="background-color: color-mix(in srgb, var(--theme-accent) 20%, transparent); color: var(--theme-accent);">A</span>
            <span class="font-medium" style="color: var(--theme-titulo);">Selecciona una entidad</span>
          </div>
          <div class="border-2 border-dashed rounded-xl min-h-[350px] flex flex-col items-center justify-center p-6" style="background-color: color-mix(in srgb, var(--theme-accent) 5%, transparent); border-color: color-mix(in srgb, var(--theme-accent) 30%, transparent);">
            <svg class="w-12 h-12 mb-3" style="color: var(--theme-accent); opacity: 0.5;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
            </svg>
            <p class="font-medium" style="color: var(--theme-accent);">Entidad A</p>
            <p class="text-sm mt-1" style="color: var(--theme-texto);">Evolución presupuestaria</p>
          </div>
        </div>

        <!-- Separador -->
        <div class="flex lg:flex-col items-center justify-center gap-2">
          <span class="font-medium text-sm" style="color: var(--theme-texto);">vs</span>
        </div>

        <!-- Lado B -->
        <div class="flex-1">
          <div class="flex items-center gap-3 mb-4">
            <span class="w-8 h-8 rounded-full flex items-center justify-center font-semibold text-sm" style="background-color: color-mix(in srgb, #8b5cf6 20%, transparent); color: #8b5cf6;">B</span>
            <span class="font-medium" style="color: var(--theme-titulo);">Selecciona otra entidad</span>
          </div>
          <div class="border-2 border-dashed rounded-xl min-h-[350px] flex flex-col items-center justify-center p-6" style="background-color: color-mix(in srgb, #8b5cf6 5%, transparent); border-color: color-mix(in srgb, #8b5cf6 30%, transparent);">
            <svg class="w-12 h-12 mb-3" style="color: #8b5cf6; opacity: 0.5;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
            </svg>
            <p class="font-medium" style="color: #8b5cf6;">Entidad B</p>
            <p class="text-sm mt-1" style="color: var(--theme-texto);">Evolución presupuestaria</p>
          </div>
        </div>
      </div>

      <div class="border rounded-xl p-6" style="background-color: var(--theme-fill); border-color: var(--theme-borde);">
        <h3 class="text-sm font-medium uppercase tracking-wide mb-4" style="font-family: 'DM Mono', monospace; color: var(--theme-titulo);">
          Comparación
        </h3>
        <div class="grid sm:grid-cols-3 gap-4 text-center">
          <div class="p-4 rounded-lg border" style="background-color: var(--theme-surface); border-color: var(--theme-borde);">
            <p class="text-xs uppercase tracking-wide mb-1" style="color: var(--theme-texto);">Presupuesto total</p>
            <p class="text-sm italic" style="color: var(--theme-texto);">Selecciona entidades</p>
          </div>
          <div class="p-4 rounded-lg border" style="background-color: var(--theme-surface); border-color: var(--theme-borde);">
            <p class="text-xs uppercase tracking-wide mb-1" style="color: var(--theme-texto);">Diferencia</p>
            <p class="text-sm italic" style="color: var(--theme-texto);">Selecciona entidades</p>
          </div>
          <div class="p-4 rounded-lg border" style="background-color: var(--theme-surface); border-color: var(--theme-borde);">
            <p class="text-xs uppercase tracking-wide mb-1" style="color: var(--theme-texto);">Tendencia</p>
            <p class="text-sm italic" style="color: var(--theme-texto);">Selecciona entidades</p>
          </div>
        </div>
      </div>
    </div>
    {/if}
  {/if}
</div>

<style>
  /* Sidebar izquierdo: con fondo en móvil, transparente en desktop */
  .sidebar-left {
    background-color: var(--theme-surface);
  }
  @media (min-width: 1024px) {
    .sidebar-left {
      background-color: transparent;
    }
  }

  /* Layout principal - fallback nativo */
  .clasificador-layout {
    display: flex !important;
    flex-direction: row !important;
  }

  /* Sidebar - fallback para responsive */
  .sidebar-left {
    position: fixed;
    transform: translateX(-100%);
  }

  @media (min-width: 1024px) {
    .sidebar-left {
      position: relative !important;
      transform: translateX(0) !important;
      flex-shrink: 0;
      width: 16rem;
      z-index: auto !important;
      box-shadow: none !important;
    }
  }

  @media (max-width: 1023px) {
    .clasificador-layout {
      display: block !important;
    }
  }
</style>