+page.svelte 33.8 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 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
<script>
  import { supabase } from '$lib/supabase';
  import { onMount } from 'svelte';
  import { fade, scale } from 'svelte/transition';
  import { cubicOut } from 'svelte/easing';

  let loading = $state(true);
  let searchQuery = $state('');
  let tipos = $state([]);
  let allItems = $state([]);
  let selectedTipo = $state(null);
  let selectedItem = $state(null);
  let highlightedItem = $state(null);
  let sidebarOpen = $state(false);

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

    const { data, error } = await supabase
      .schema('ppto')
      .from('clas_rubros')
      .select('*')
      .order('rubro');

    if (!error && data) {
      allItems = data;

      // Extraer tipos únicos (nivel más agregado)
      tipos = data
        .filter(item => item.nivel === 'tipo')
        .reduce((acc, item) => {
          if (!acc.find(t => t.rubro === item.rubro)) {
            acc.push(item);
          }
          return acc;
        }, [])
        .sort((a, b) => a.rubro.localeCompare(b.rubro));

      if (tipos.length > 0) {
        selectedTipo = tipos[0];
      }
    }

    loading = false;
  });

  // Helpers para derivar jerarquía desde código rubro
  // Jerarquía: Tipo (XX000) → Clase (XXX00) → Cuenta (XXXX0) → Subcuenta (XXXXX)
  function getTipoFromRubro(rubro) {
    // Tipo = primeros 2 dígitos (XX de XX000)
    return rubro.substring(0, 2);
  }

  function getClaseFromRubro(rubro) {
    // Clase = primeros 3 dígitos (XXX de XXX00)
    return rubro.substring(0, 3);
  }

  function getCuentaFromRubro(rubro) {
    // Cuenta = primeros 4 dígitos (XXXX de XXXX0)
    return rubro.substring(0, 4);
  }

  function getItemsForTipo(tipoCode) {
    if (!tipoCode) return { clases: [] };

    const tipoNum = getTipoFromRubro(tipoCode);

    // Obtener clases únicas de este tipo
    const clasesUnicas = allItems
      .filter(item => item.nivel === 'clase' && getTipoFromRubro(item.rubro) === tipoNum)
      .reduce((acc, item) => {
        if (!acc.find(c => c.rubro === item.rubro)) {
          acc.push(item);
        }
        return acc;
      }, [])
      .sort((a, b) => a.rubro.localeCompare(b.rubro));

    const clases = clasesUnicas.map(clase => {
      const clasePrefix = getClaseFromRubro(clase.rubro);

      // Obtener cuentas de esta clase
      const cuentasUnicas = allItems
        .filter(item => item.nivel === 'cuenta' && getClaseFromRubro(item.rubro) === clasePrefix)
        .reduce((acc, item) => {
          if (!acc.find(c => c.rubro === item.rubro)) {
            acc.push(item);
          }
          return acc;
        }, [])
        .sort((a, b) => a.rubro.localeCompare(b.rubro));

      // Obtener todas las subcuentas de esta clase
      const todasSubcuentas = allItems
        .filter(item => item.nivel === 'sub_cuenta' && getClaseFromRubro(item.rubro) === clasePrefix)
        .reduce((acc, item) => {
          if (!acc.find(sc => sc.rubro === item.rubro)) {
            acc.push(item);
          }
          return acc;
        }, [])
        .sort((a, b) => a.rubro.localeCompare(b.rubro));

      // Set de prefijos de cuenta que existen
      const cuentasExistentes = new Set(cuentasUnicas.map(c => getCuentaFromRubro(c.rubro)));

      // Encontrar subcuentas huérfanas (cuya cuenta no existe)
      const subcuentasHuerfanas = todasSubcuentas.filter(sc => !cuentasExistentes.has(getCuentaFromRubro(sc.rubro)));

      // Agrupar huérfanas por prefijo de cuenta para crear cuentas sintéticas
      const huerfanasPorCuenta = {};
      subcuentasHuerfanas.forEach(sc => {
        const cuentaPrefix = getCuentaFromRubro(sc.rubro);
        if (!huerfanasPorCuenta[cuentaPrefix]) {
          huerfanasPorCuenta[cuentaPrefix] = [];
        }
        huerfanasPorCuenta[cuentaPrefix].push(sc);
      });

      // Crear cuentas sintéticas para las huérfanas
      const cuentasSinteticas = Object.entries(huerfanasPorCuenta).map(([cuentaPrefix, subcuentas]) => {
        const codigoCuenta = `${cuentaPrefix}0`;
        return {
          rubro: codigoCuenta,
          desc_rubro: subcuentas[0]?.desc_rubro?.split(',')[0] || `Cuenta ${codigoCuenta}`,
          nivel: 'cuenta',
          _sintetica: true,
          subcuentas
        };
      });

      // Asignar subcuentas a cuentas existentes
      const cuentas = cuentasUnicas.map(cuenta => {
        const cuentaPrefix = getCuentaFromRubro(cuenta.rubro);
        const subcuentas = todasSubcuentas
          .filter(item => getCuentaFromRubro(item.rubro) === cuentaPrefix)
          .sort((a, b) => a.rubro.localeCompare(b.rubro));

        return { ...cuenta, subcuentas };
      });

      // Combinar cuentas existentes con sintéticas y ordenar
      const todasCuentas = [...cuentas, ...cuentasSinteticas]
        .sort((a, b) => a.rubro.localeCompare(b.rubro));

      return { ...clase, cuentas: todasCuentas };
    });

    return { clases };
  }

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

    return allItems
      .filter(item =>
        item.rubro?.toString().includes(q) ||
        item.desc_rubro?.toLowerCase().includes(q)
      )
      .reduce((acc, item) => {
        if (!acc.find(i => i.rubro === item.rubro)) {
          acc.push(item);
        }
        return acc;
      }, [])
      .slice(0, 20);
  }

  function parseDescripciones(descripcionesStr) {
    if (!descripcionesStr) return [];
    try {
      // Si ya es objeto, usarlo directamente
      const parsed = typeof descripcionesStr === 'string'
        ? JSON.parse(descripcionesStr)
        : descripcionesStr;
      return parsed.sort((a, b) => {
        const maxYearA = getMaxYear(a.rangos);
        const maxYearB = getMaxYear(b.rangos);
        return maxYearB - maxYearA;
      });
    } catch {
      return [];
    }
  }

  function getMaxYear(rangos) {
    if (!rangos) return 0;
    const years = rangos.match(/\d{4}/g);
    if (!years) return 0;
    return Math.max(...years.map(y => parseInt(y)));
  }

  function selectTipo(tipo) {
    selectedTipo = tipo;
    selectedItem = null;
    searchQuery = '';
    highlightedItem = null;
    sidebarOpen = false;
  }

  function openDetail(item) {
    selectedItem = item;
  }

  function closeDetail() {
    selectedItem = null;
  }

  function goToSearchResult(item) {
    const tipoNum = getTipoFromRubro(item.rubro);
    const targetTipo = tipos.find(t => getTipoFromRubro(t.rubro) === tipoNum);

    if (targetTipo) {
      selectedTipo = targetTipo;
      highlightedItem = item.rubro;
      searchQuery = '';
      sidebarOpen = false;

      setTimeout(() => {
        const prefix = item.nivel === 'clase' ? 'cl' : item.nivel === 'cuenta' ? 'cu' : 'sc';
        const element = document.getElementById(`${prefix}-${item.rubro}`);
        if (element) {
          element.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
      }, 100);

      setTimeout(() => {
        highlightedItem = null;
      }, 2000);
    }
  }

  function getNivelLabel(nivel) {
    const labels = { tipo: 'Tipo', clase: 'Clase', cuenta: 'Cuenta', sub_cuenta: 'Subcuenta' };
    return labels[nivel] || nivel;
  }

  let tipoContent = $derived(selectedTipo ? getItemsForTipo(selectedTipo.rubro) : { clases: [] });
  let searchResults = $derived(searchGlobal(searchQuery));
  let isSearching = $derived(searchQuery.length >= 2);

  // Contadores
  let totalItems = $derived(allItems.length);
  let countByNivel = $derived({
    tipos: allItems.filter(i => i.nivel === 'tipo').length,
    clases: allItems.filter(i => i.nivel === 'clase').length,
    cuentas: allItems.filter(i => i.nivel === 'cuenta').length,
    subcuentas: allItems.filter(i => i.nivel === 'sub_cuenta').length
  });
</script>

<svelte:head>
  <title>Rubros | 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);">
          ¿De dónde vienen los ingresos?
        </h1>

        <p class="leading-relaxed mb-3" style="color: var(--theme-texto);">
          Organiza los ingresos del Estado según su <strong style="color: var(--theme-titulo);">origen económico</strong>:
          impuestos, ventas de bienes, regalías, transferencias, créditos.
          Es la forma de entender cómo se financia el presupuesto público.
        </p>

        {#if totalItems > 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;">{totalItems}</span> categorías de ingreso:
            {countByNivel.tipos} tipos, {countByNivel.clases} clases, {countByNivel.cuentas} cuentas, {countByNivel.subcuentas} subcuentas
          </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;">
            Tipo
          </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);">
            Clase
          </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);">
            Cuenta
          </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);">
            Subcuenta
          </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: Tipo → Clase → Cuenta → Subcuenta
        </p>
      </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}
    <!-- 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">{selectedTipo ? selectedTipo.desc_rubro : 'Seleccionar tipo'}</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: Tipos -->
      {#if sidebarOpen}
        <div
          transition:fade={{ duration: 150 }}
          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);">Tipos de ingreso</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..."
              class="w-full px-3 py-2 text-sm rounded-md focus:outline-none focus:ring-2"
              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);">{getNivelLabel(result.nivel)}</span>
                    <span class="font-mono text-xs font-medium" style="color: var(--theme-accent);">{result.rubro}</span>
                    <span class="ml-1">{result.desc_rubro}</span>
                  </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 tipos -->
            <nav>
              <p class="text-xs uppercase tracking-wide mb-3 px-2 hidden lg:block" style="color: var(--theme-texto);">Tipos</p>
              <ul class="space-y-1">
                {#each tipos as tipo}
                  <li>
                    <button
                      class="w-full text-left px-3 py-2 rounded-md text-sm transition-all"
                      style="{selectedTipo?.rubro === tipo.rubro
                        ? `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={() => selectTipo(tipo)}
                    >
                      <span class="font-mono text-xs block" style="color: var(--theme-texto);">{tipo.rubro}</span>
                      {tipo.desc_rubro}
                    </button>
                  </li>
                {/each}
              </ul>
            </nav>
          {/if}
        </div>
      </aside>

      <!-- Contenido principal -->
      <main class="flex-1 min-w-0 lg:border-l xl:border-r" style="border-color: var(--theme-borde);">
        <div class="px-4 sm:px-6 lg:px-10 py-6 lg:py-8">
          {#if selectedTipo}
            {#key selectedTipo.rubro}
            <div in:fade={{ duration: 200, delay: 50 }}>
            <!-- Título del tipo -->
            <div class="mb-8 lg:mb-10 pb-6 lg:pb-8 border-b" style="border-color: var(--theme-borde);">
              <p class="text-sm font-mono mb-1" style="color: var(--theme-texto);">{selectedTipo.rubro}</p>
              <h2 class="text-lg sm:text-xl font-medium mb-2 flex items-center gap-2 sm:gap-3 flex-wrap" style="color: var(--theme-titulo);">
                {selectedTipo.desc_rubro}
                <a
                  href="/rubro/{selectedTipo.rubro}"
                  class="transition-colors hover:text-[var(--theme-accent)]"
                  style="color: var(--theme-texto);"
                  title="Ver detalle"
                >
                  <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="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
                  </svg>
                </a>
              </h2>
              {#if selectedTipo.descripciones}
                {@const tipoDescs = parseDescripciones(selectedTipo.descripciones)}
                {#if tipoDescs.length > 0}
                  <p class="leading-relaxed" style="color: var(--theme-texto);">{tipoDescs[0].descripcion}</p>
                  {#if selectedTipo.n_variaciones > 1}
                    <button
                      class="text-sm text-orange-500 hover:text-orange-700 mt-2 transition-colors underline decoration-dotted decoration-orange-300 hover:decoration-orange-500 cursor-pointer"
                      onclick={() => openDetail(selectedTipo)}
                    >
                      Ver {selectedTipo.n_variaciones} variaciones históricas
                    </button>
                  {/if}
                {/if}
              {/if}
              <!-- Vigencia temporal -->
              {#if selectedTipo.gestiones}
                <p class="text-xs mt-3 font-mono" style="color: var(--theme-texto); opacity: 0.7;">
                  Vigente: {selectedTipo.gestiones}
                </p>
              {/if}
            </div>

            <!-- Clases -->
            <div class="space-y-12">
              {#each tipoContent.clases as clase}
                {@const claseDescs = parseDescripciones(clase.descripciones)}
                <section
                  id="cl-{clase.rubro}"
                  class="scroll-mt-4 {highlightedItem === clase.rubro ? 'highlighted' : ''}"
                >
                  <div class="flex items-start gap-2 sm:gap-4 mb-3">
                    <span class="font-mono text-xs sm:text-sm pt-1" style="color: var(--theme-texto);">{clase.rubro}</span>
                    <div class="flex-1">
                      <h3 class="text-base sm:text-lg font-medium flex items-center gap-2 flex-wrap" style="color: var(--theme-titulo);">
                        <span class="text-left">{clase.desc_rubro}</span>
                        {#if clase.n_variaciones > 1}
                          <button
                            class="text-xs font-normal text-orange-500 hover:text-orange-700 transition-colors underline decoration-dotted decoration-orange-300 hover:decoration-orange-500 cursor-pointer"
                            onclick={() => openDetail(clase)}
                            title="Ver variaciones de descripción"
                          >
                            {clase.n_variaciones} var.
                          </button>
                        {/if}
                        <a
                          href="/rubro/{clase.rubro}"
                          class="transition-colors hover:text-[var(--theme-accent)]"
                          style="color: var(--theme-texto);"
                          title="Ver página de detalle"
                        >
                          <svg class="w-4 h-4" 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>
                        </a>
                      </h3>
                      {#if claseDescs.length > 0}
                        <p class="text-sm mt-1 leading-relaxed" style="color: var(--theme-texto);">{claseDescs[0].descripcion}</p>
                      {/if}
                    </div>
                  </div>

                  <!-- Cuentas -->
                  {#if clase.cuentas?.length > 0}
                    <div class="ml-4 sm:ml-8 lg:ml-16 space-y-5 border-l pl-4 sm:pl-6 lg:pl-8" style="border-color: var(--theme-borde);">
                      {#each clase.cuentas as cuenta}
                        {@const cuentaDescs = parseDescripciones(cuenta.descripciones)}
                        <div
                          id="cu-{cuenta.rubro}"
                          class="scroll-mt-4 {highlightedItem === cuenta.rubro ? 'highlighted-md' : ''}"
                        >
                          <div class="flex items-start gap-2 sm:gap-3">
                            <span class="font-mono text-xs pt-0.5" style="color: var(--theme-texto);">{cuenta.rubro}</span>
                            <div class="flex-1">
                              <h4 class="text-sm font-medium flex items-center gap-2 flex-wrap" style="color: var(--theme-titulo);">
                                <span class="text-left">{cuenta.desc_rubro}</span>
                                {#if cuenta.n_variaciones > 1}
                                  <button
                                    class="text-xs font-normal text-orange-500 hover:text-orange-700 transition-colors underline decoration-dotted decoration-orange-300 hover:decoration-orange-500 cursor-pointer"
                                    onclick={() => openDetail(cuenta)}
                                    title="Ver variaciones de descripción"
                                  >
                                    {cuenta.n_variaciones} var.
                                  </button>
                                {/if}
                                <a
                                  href="/rubro/{cuenta.rubro}"
                                  class="transition-colors hover:text-[var(--theme-accent)]"
                                  style="color: var(--theme-texto);"
                                  title="Ver página de detalle"
                                >
                                  <svg class="w-3.5 h-3.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>
                                </a>
                              </h4>
                              {#if cuentaDescs.length > 0}
                                <p class="text-xs mt-1 leading-relaxed" style="color: var(--theme-texto);">{cuentaDescs[0].descripcion}</p>
                              {/if}
                            </div>
                          </div>

                          <!-- Subcuentas -->
                          {#if cuenta.subcuentas?.length > 0}
                            <div class="ml-8 sm:ml-12 mt-3 space-y-2 border-l pl-4" style="border-color: var(--theme-borde);">
                              {#each cuenta.subcuentas as subcuenta}
                                {@const subcuentaDescs = parseDescripciones(subcuenta.descripciones)}
                                <div
                                  id="sc-{subcuenta.rubro}"
                                  class="scroll-mt-4 {highlightedItem === subcuenta.rubro ? 'highlighted-sm' : ''}"
                                >
                                  <div class="flex items-start gap-2">
                                    <span class="font-mono text-xs" style="color: var(--theme-texto); opacity: 0.7;">{subcuenta.rubro}</span>
                                    <div class="flex-1">
                                      <span class="flex items-center gap-2 flex-wrap">
                                        <span class="text-xs" style="color: var(--theme-titulo);">{subcuenta.desc_rubro}</span>
                                        {#if subcuenta.n_variaciones > 1}
                                          <button
                                            class="text-xs text-orange-500 hover:text-orange-700 transition-colors underline decoration-dotted decoration-orange-300 hover:decoration-orange-500 cursor-pointer"
                                            onclick={() => openDetail(subcuenta)}
                                            title="Ver variaciones de descripción"
                                          >
                                            {subcuenta.n_variaciones} var.
                                          </button>
                                        {/if}
                                        <a
                                          href="/rubro/{subcuenta.rubro}"
                                          class="transition-colors hover:text-[var(--theme-accent)]"
                                          style="color: var(--theme-texto);"
                                          title="Ver página de detalle"
                                        >
                                          <svg class="w-3 h-3" 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>
                                        </a>
                                      </span>
                                      {#if subcuentaDescs.length > 0}
                                        <p class="text-xs mt-0.5" style="color: var(--theme-texto); opacity: 0.8;">{subcuentaDescs[0].descripcion}</p>
                                      {/if}
                                    </div>
                                  </div>
                                </div>
                              {/each}
                            </div>
                          {/if}
                        </div>
                      {/each}
                    </div>
                  {/if}
                </section>
              {/each}
            </div>
            </div>
            {/key}
          {/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 p-4 border-l" style="border-color: var(--theme-borde);">
          <p class="text-xs uppercase tracking-wide mb-3" style="font-family: 'DM Mono', monospace; color: var(--theme-texto);">En esta página</p>
          {#if selectedTipo && !isSearching}
            <nav class="space-y-2">
              {#each tipoContent.clases as clase}
                <div>
                  <a
                    href="#cl-{clase.rubro}"
                    class="block text-sm truncate transition-colors hover:text-[var(--theme-accent)]"
                    style="color: var(--theme-texto);"
                    title="{clase.desc_rubro}"
                  >
                    {clase.desc_rubro}
                  </a>
                  {#if clase.cuentas?.length > 0}
                    <div class="ml-3 mt-1 space-y-1 border-l pl-2" style="border-color: var(--theme-borde);">
                      {#each clase.cuentas.slice(0, 5) as cuenta}
                        <a
                          href="#cu-{cuenta.rubro}"
                          class="block text-xs truncate transition-colors hover:text-[var(--theme-accent)]"
                          style="color: var(--theme-texto); opacity: 0.7;"
                          title="{cuenta.desc_rubro}"
                        >
                          {cuenta.desc_rubro}
                        </a>
                      {/each}
                      {#if clase.cuentas.length > 5}
                        <span class="text-xs" style="color: var(--theme-texto); opacity: 0.5;">+{clase.cuentas.length - 5} más</span>
                      {/if}
                    </div>
                  {/if}
                </div>
              {/each}
            </nav>
          {/if}
        </div>
      </aside>
    </div>
  {/if}
</div>

<!-- Modal de detalle -->
{#if selectedItem}
  <div
    transition:fade={{ duration: 150 }}
    class="fixed inset-0 bg-black/40 flex items-center justify-center p-4 z-50"
    onclick={closeDetail}
  >
    <div
      transition:scale={{ duration: 200, start: 0.95, easing: cubicOut }}
      class="rounded-xl shadow-2xl max-w-2xl w-full max-h-[85vh] overflow-hidden flex flex-col"
      style="background-color: var(--theme-surface);"
      onclick={(e) => e.stopPropagation()}
    >
      <div class="px-6 py-4 border-b flex justify-between items-start" style="background-color: var(--theme-fill); border-color: var(--theme-borde);">
        <div>
          <p class="text-xs uppercase tracking-wide font-medium" style="color: var(--theme-texto);">{getNivelLabel(selectedItem.nivel)}</p>
          <h3 class="text-lg font-medium mt-1" style="color: var(--theme-titulo);">
            <span class="font-mono" style="color: var(--theme-texto);">{selectedItem.rubro}</span>
            <span class="mx-2" style="color: var(--theme-texto); opacity: 0.5;">·</span>
            {selectedItem.desc_rubro}
          </h3>
        </div>
        <button
          onclick={closeDetail}
          class="text-2xl leading-none"
          style="color: var(--theme-texto);"
        >
          &times;
        </button>
      </div>

      <div class="p-6 overflow-y-auto flex-1">
        <h4 class="text-sm font-medium mb-4" style="color: var(--theme-titulo);">
          {#if selectedItem.n_variaciones > 1}
            Descripciones ({selectedItem.n_variaciones} variaciones)
          {:else}
            Descripción
          {/if}
        </h4>

        <div class="space-y-4">
          {#each parseDescripciones(selectedItem.descripciones) as desc, i}
            <div class="border-l-2 pl-4 py-3 rounded-r" style="{i === 0 ? `border-color: var(--theme-accent); background-color: color-mix(in srgb, var(--theme-accent) 10%, transparent);` : `border-color: var(--theme-borde);`}">
              <p class="text-sm mb-2" style="color: var(--theme-texto);">
                {#if i === 0 && selectedItem.n_variaciones > 1}
                  <span class="font-medium" style="color: var(--theme-accent);">Vigente</span>
                  <span class="mx-1" style="opacity: 0.5;">·</span>
                {/if}
                <span class="font-mono">{desc.rangos}</span>
              </p>
              <p class="text-base leading-relaxed" style="color: var(--theme-titulo);">{desc.descripcion}</p>
            </div>
          {/each}
        </div>

        <!-- Vigencia temporal -->
        {#if selectedItem.gestiones}
          <div class="mt-6 pt-4 border-t" style="border-color: var(--theme-borde);">
            <p class="text-xs font-mono" style="color: var(--theme-texto);">
              <span class="font-medium">Años con datos:</span> {selectedItem.gestiones}
            </p>
          </div>
        {/if}
      </div>
    </div>
  </div>
{/if}

<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;
    }
  }

  /* Highlight pulse animation para resultados de búsqueda */
  @keyframes highlight-pulse {
    0%, 100% {
      box-shadow: 0 0 0 2px color-mix(in srgb, var(--theme-accent) 30%, transparent);
    }
    50% {
      box-shadow: 0 0 0 4px color-mix(in srgb, var(--theme-accent) 50%, transparent);
    }
  }

  .highlighted {
    animation: highlight-pulse 0.8s ease-in-out 2;
    border-radius: 0.5rem;
  }

  .highlighted-sm {
    animation: highlight-pulse 0.8s ease-in-out 2;
    border-radius: 0.25rem;
    padding: 0.25rem;
    margin-left: -0.25rem;
  }

  .highlighted-md {
    animation: highlight-pulse 0.8s ease-in-out 2;
    border-radius: 0.5rem;
    padding: 0.5rem;
    margin-left: -0.5rem;
  }

  /* 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>