+page.svelte 83.6 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 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516
<script>
  import { onMount } from 'svelte';
  import { tweened } from 'svelte/motion';
  import { cubicOut } from 'svelte/easing';
  import { goto } from '$app/navigation';
  import { page } from '$app/stores';
  import Spinner from '$lib/components/ui/Spinner.svelte';
  import VistaToggle from '$lib/components/objeto/VistaToggle.svelte';
  import BarChart from '$lib/components/objeto/BarChart.svelte';
  import EntitySelector from '$lib/components/objeto/EntitySelector.svelte';

  let { data } = $props();
  let finfunData = $derived(data.finfun);
  let padres = $derived(data.padres);
  let hijos = $derived(data.hijos);

  let mounted = $state(false);
  let loading = $state(false);
  let hoveredYear = $state(null);
  let lockedYear = $state(null);
  let activeYear = $derived(lockedYear ?? hoveredYear);
  let showDefinicionesModal = $state(false);
  let showMobileSidebar = $state(false);
  let metrica = $state('percapita'); // 'percapita' | 'monto'
  let vista = $state('agregado'); // 'agregado' | 'comparar'
  let linkCopied = $state(false);

  // Inline search state
  let searchQuery = $state('');
  let searchResults = $state([]);
  let searchLoading = $state(false);
  let searchTimeout = null;

  async function doSearch(q) {
    if (!q || q.length < 2) { searchResults = []; return; }
    searchLoading = true;
    try {
      const res = await fetch(`/api/search?q=${encodeURIComponent(q)}&per_page=20&is_class=true&class_=finalidad`);
      const data = await res.json();
      searchResults = (data.hits || []).map(hit => {
        const doc = hit.document || {};
        let meta = {};
        try { meta = typeof doc.metadatos === 'string' ? JSON.parse(doc.metadatos) : (doc.metadatos || {}); } catch {}
        const fin = String(meta.finfun_finalidad ?? '');
        if (!fin) return null;
        let code = fin;
        if (meta.finfun_funcion !== undefined && meta.finfun_grpfuncion !== undefined) {
          code = `${fin}.${meta.finfun_grpfuncion}.${meta.finfun_funcion}`;
        } else if (meta.finfun_grpfuncion !== undefined) {
          code = `${fin}.${meta.finfun_grpfuncion}`;
        }
        return {
          code,
          label: doc.texto || '',
        };
      }).filter(Boolean);
    } catch {
      searchResults = [];
    }
    searchLoading = false;
  }

  function onSearchInput(e) {
    const q = e.target.value;
    searchQuery = q;
    clearTimeout(searchTimeout);
    searchTimeout = setTimeout(() => doSearch(q), 300);
  }

  // Parsear descripciones - la API devuelve array directo con { gestion, descripcion }
  function getMaxYear(str) {
    if (!str) return 0;
    const years = str.match(/\d{4}/g);
    return years ? Math.max(...years.map(Number)) : 0;
  }

  let descripciones = $derived.by(() => {
    const descs = finfunData.descripciones;
    if (!descs) return [];
    let arr;
    if (typeof descs === 'string') {
      try { arr = JSON.parse(descs); } catch { return []; }
    } else {
      arr = Array.isArray(descs) ? descs : [];
    }
    // Ordenar por año más reciente primero
    return [...arr].sort((a, b) => getMaxYear(b.gestion || b.rangos) - getMaxYear(a.gestion || a.rangos));
  });
  let variaciones = $derived(descripciones.map(d => ({ rango: d.gestion || d.rangos || '', texto: d.descripcion })));

  // Estado selector entidad
  let entidades = $state([]);
  let selectedEntity = $state(null);
  let nEntidades = $derived(entidades.length || 0);

  // Datos — inicializar desde estados del server
  function initEstados(obj) {
    const estadosRaw = obj?.estados || [];
    const seen = new Set();
    const estados = estadosRaw.filter(d => { if (seen.has(d.gestion)) return false; seen.add(d.gestion); return true; });
    const hist = estados.find(d => d.gestion === 0) || null;
    const anuales = estados.filter(d => d.gestion >= 2016 && d.gestion > 0);
    const topPorAño = {};
    anuales.forEach(d => {
      topPorAño[d.gestion] = [
        { nombre: d.top1_entidad_desc, porcentaje: d.top1_pct, entidad: d.top1_entidad },
        { nombre: d.top2_entidad_desc, porcentaje: d.top2_pct, entidad: d.top2_entidad },
        { nombre: d.top3_entidad_desc, porcentaje: d.top3_pct, entidad: d.top3_entidad },
      ].filter(e => e.nombre);
    });
    return { hist, anuales, topPorAño };
  }

  let { hist: initHist, anuales: initAnuales, topPorAño: initTop } = initEstados(finfunData);
  let datosAnuales = $state(initAnuales);
  let datosHistorico = $state(initHist);
  let topEntidadesPorAño = $state(initTop);

  const POBLACION = 12000000;
  let finfunCodigo = $derived(finfunData.finfun);
  let finfunNivel = $derived(finfunData.nivel);

  let gastoPerCapita = $derived(
    datosAnuales.map(d => {
      const monto = Number(selectedEntity ? (d.monto ?? d.devengado ?? 0) : (d.total ?? 0)) || 0;
      const perCapita = Number(d.per_capita ?? (d.devengado ? d.devengado / POBLACION : 0)) || 0;
      return {
        año: d.gestion,
        monto,
        perCapita: metrica === 'percapita' ? perCapita : monto
      };
    })
  );

  let primerAño = $derived(gastoPerCapita.length > 0 ? gastoPerCapita[0].año : 2005);
  let ultimoAño = $derived(gastoPerCapita.length > 0 ? gastoPerCapita[gastoPerCapita.length - 1].año : 2025);

  let totalHistorico = $derived(datosHistorico ? (selectedEntity ? (datosHistorico.monto ?? 0) : (datosHistorico.total ?? 0)) : 0);
  let promedioPerCapita = $derived(datosHistorico?.per_capita ?? 0);
  let totalPorcentaje = $derived(datosHistorico?.prop ?? 0);
  let ranking = $derived(datosHistorico?.ranking ?? 0);
  let nPares = $derived(datosHistorico?.n_pares ?? 0);
  let totalGestion = $derived(datosHistorico?.total_gestion ?? 0);

  let currentData = $derived(
    activeYear ? gastoPerCapita.find(g => g.año === activeYear) : null
  );

  // Datos del año activo (fijado o hover) desde datosAnuales
  let currentAnual = $derived(activeYear ? datosAnuales.find(d => d.gestion === activeYear) : null);

  // KPI 1: Monto
  let displayMonto = $derived.by(() => {
    if (selectedEntity) {
      return (currentAnual ? currentAnual.monto : totalHistorico) ?? 0;
    }
    return (currentAnual ? currentAnual.total_gestion : totalGestion) ?? 0;
  });
  let displayMontoLabel = $derived.by(() => {
    if (selectedEntity) {
      return currentAnual ? `gastados en ${currentAnual.gestion}` : `gastados ${primerAño}-${ultimoAño}`;
    }
    return currentAnual ? `gasto total del Estado en ${currentAnual.gestion}` : `gasto total ${primerAño}-${ultimoAño}`;
  });

  // KPI 2: Per cápita
  let displayPerCapita = $derived((currentAnual?.per_capita ?? promedioPerCapita) ?? 0);
  let displayPerCapitaLabel = $derived(currentAnual ? `por cada boliviano en ${currentAnual.gestion}` : 'por cada boliviano (promedio)');

  // KPI 3: Proporción (prop)
  let displayPorcentaje = $derived((currentAnual?.prop ?? totalPorcentaje) ?? 0);
  let displayPorcentajeLabel = $derived.by(() => {
    if (selectedEntity) {
      return currentAnual ? `del total de esta función en ${currentAnual.gestion}` : 'del total de esta función';
    }
    return currentAnual ? `del gasto en ${currentAnual.gestion}` : 'del gasto total';
  });

  let displayPeriodo = $derived(currentData ? currentData.año : `${primerAño}-${ultimoAño}`);
  let displayRanking = $derived(`${currentAnual ? currentAnual.ranking : ranking} de ${selectedEntity ? (datosHistorico?.n_entidades || nEntidades) : (currentAnual ? currentAnual.n_pares : nPares)}`);

  let nivelKey = $derived(finfunData.nivel?.toLowerCase());
  let nivelPlural = $derived({ finalidad: 'finalidades', grpfuncion: 'grupos de función', funcion: 'funciones' }[nivelKey] || 'funciones');
  let nivelLabel = $derived({ finalidad: 'Finalidad', grpfuncion: 'Grupo función', funcion: 'Función' }[nivelKey] || finfunData.nivel);
  let displayRankingLabel = $derived.by(() => {
    if (selectedEntity) {
      return currentAnual ? `entre las que más gastan en ${currentAnual.gestion}` : 'entre las que más gastan';
    }
    return currentData ? `${nivelPlural} más gastadas en ${currentData.año}` : `${nivelPlural} más gastadas`;
  });

  // Top entidades
  let topEntidadesTotal = $derived(
    datosHistorico && !selectedEntity ? [
      { nombre: datosHistorico.top1_entidad_desc, porcentaje: datosHistorico.top1_pct, entidad: datosHistorico.top1_entidad },
      { nombre: datosHistorico.top2_entidad_desc, porcentaje: datosHistorico.top2_pct, entidad: datosHistorico.top2_entidad },
      { nombre: datosHistorico.top3_entidad_desc, porcentaje: datosHistorico.top3_pct, entidad: datosHistorico.top3_entidad },
    ].filter(e => e.nombre) : []
  );
  let displayTopEntidades = $derived(
    activeYear && topEntidadesPorAño[activeYear] ? topEntidadesPorAño[activeYear] : topEntidadesTotal
  );

  // Tweens
  const tw = { duration: 300, easing: cubicOut };
  const twMonto = tweened(0, tw);
  const twPerCapita = tweened(0, tw);
  const twPorcentaje = tweened(0, tw);
  const twTop1 = tweened(0, tw);
  const twTop2 = tweened(0, tw);
  const twTop3 = tweened(0, tw);

  $effect(() => { twMonto.set(typeof displayMonto === 'number' ? displayMonto : 0); });
  $effect(() => { twPerCapita.set(typeof displayPerCapita === 'number' ? displayPerCapita : 0); });
  $effect(() => { twPorcentaje.set(typeof displayPorcentaje === 'number' ? displayPorcentaje : 0); });
  $effect(() => { if (displayTopEntidades[0]) twTop1.set(displayTopEntidades[0].porcentaje); });
  $effect(() => { if (displayTopEntidades[1]) twTop2.set(displayTopEntidades[1].porcentaje); });
  $effect(() => { if (displayTopEntidades[2]) twTop3.set(displayTopEntidades[2].porcentaje); });

  function formatMontoLargo(n) {
    if (n >= 1e9) return `${(n / 1e9).toFixed(1)} mil mill.`;
    if (n >= 1e6) return `${(n / 1e6).toFixed(1)} mill.`;
    if (n >= 1e3) return `${(n / 1e3).toFixed(0)} mil`;
    return n.toLocaleString('es-BO');
  }

  function formatPerCapita(n) {
    return n.toLocaleString('es-BO', { minimumFractionDigits: 0, maximumFractionDigits: 0 });
  }

  async function loadData() {
    if (!selectedEntity) return;
    lockedYear = null;
    loading = true;
    try {
      const res = await fetch(`/api/finfun-data?codigo=${finfunCodigo}&tipo=entidad&entidad=${selectedEntity.entidad}`);
      const raw = await res.json();
      console.log('[loadData] entidad:', selectedEntity.entidad, 'raw rows:', raw?.length);
      if (Array.isArray(raw)) {
        const seen = new Set();
        const data = raw.filter(d => { if (seen.has(d.gestion)) return false; seen.add(d.gestion); return true; });
        datosHistorico = data.find(d => d.gestion === 0) || null;
        datosAnuales = data.filter(d => d.gestion >= 2016);
        topEntidadesPorAño = {};
        console.log('[loadData] historico:', datosHistorico ? { monto: datosHistorico.monto, per_capita: datosHistorico.per_capita, prop: datosHistorico.prop } : null);
        // Forzar tweens directamente
        if (datosHistorico) {
          twMonto.set(datosHistorico.monto || 0);
          twPerCapita.set(datosHistorico.per_capita || 0);
          twPorcentaje.set(datosHistorico.prop || 0);
        }
      }
    } catch (err) {
      console.error('[loadData] Error:', err);
    }
    loading = false;
  }

  async function loadEntidades() {
    try {
      // Usar el último año disponible para filtrar entidades activas
      const añosConDatos = datosAnuales.map(d => d.gestion).sort((a, b) => b - a);
      const año = añosConDatos[0] || 2025;

      const [entRes, clasRes] = await Promise.all([
        fetch(`/api/finfun-data?codigo=${finfunCodigo}&tipo=entidades-año&gestion=${año}`),
        fetch('/api/entidad-clasificador')
      ]);
      const entData = await entRes.json();
      const clasData = await clasRes.json();

      const nombreMap = new Map();
      if (Array.isArray(clasData)) {
        clasData.forEach(e => nombreMap.set(e.entidad, e.desc_entidad));
      }

      if (Array.isArray(entData)) {
        entidades = entData
          .filter(d => d.monto > 0 && d.entidad !== 0)
          .map(d => ({ entidad: d.entidad, entidad_desc: nombreMap.get(d.entidad) || `Entidad ${d.entidad}` }))
          .sort((a, b) => (a.entidad_desc || '').localeCompare(b.entidad_desc || ''));
      }
    } catch {
      entidades = [];
    }
  }

  // ══════════════════════════════════════════════════════════════
  // COMPARACIÓN
  // ══════════════════════════════════════════════════════════════
  const twMontoA = tweened(0, { duration: 300, easing: cubicOut });
  const twMontoB = tweened(0, { duration: 300, easing: cubicOut });
  const twPerCapitaA = tweened(0, { duration: 300, easing: cubicOut });
  const twPerCapitaB = tweened(0, { duration: 300, easing: cubicOut });

  let hoveredYearComparar = $state(null);
  let loadingComparacion = $state(false);
  let isDefaultSelection = $state(false);
  let alertDefaultDismissed = $state(false);
  let alertRangosDismissed = $state(false);

  let entidadCompararA = $state(null);
  let entidadCompararB = $state(null);
  let datosCompararA = $state({ anual: [], historico: null });
  let datosCompararB = $state({ anual: [], historico: null });

  let dropdownAOpen = $state(false);
  let dropdownBOpen = $state(false);
  let searchA = $state('');
  let searchB = $state('');
  let entityLimitA = $state(30);
  let entityLimitB = $state(30);

  let filteredEntidadesA = $derived.by(() => {
    if (!searchA || searchA.length < 2) return entidades.slice(0, entityLimitA);
    const q = searchA.toLowerCase();
    return entidades.filter(e => e.entidad_desc?.toLowerCase().includes(q) || e.entidad?.toString().includes(q)).slice(0, entityLimitA);
  });

  let filteredEntidadesB = $derived.by(() => {
    if (!searchB || searchB.length < 2) return entidades.slice(0, entityLimitB);
    const q = searchB.toLowerCase();
    return entidades.filter(e => e.entidad_desc?.toLowerCase().includes(q) || e.entidad?.toString().includes(q)).slice(0, entityLimitB);
  });

  async function loadDatosEntidad(entidad) {
    try {
      const res = await fetch(`/api/finfun-data?codigo=${finfunCodigo}&tipo=entidad&entidad=${entidad.entidad}`);
      const raw = await res.json();
      if (Array.isArray(raw)) {
        const seen = new Set();
        const data = raw.filter(d => { if (seen.has(d.gestion)) return false; seen.add(d.gestion); return true; });
        return { anual: data.filter(d => d.gestion >= 2016), historico: data.find(d => d.gestion === 0) || null };
      }
    } catch {}
    return { anual: [], historico: null };
  }

  async function initComparacion() {
    if (entidadCompararA || entidadCompararB) return;
    if (selectedEntity) {
      entidadCompararA = selectedEntity;
      loadingComparacion = true;
      datosCompararA = await loadDatosEntidad(selectedEntity);
      loadingComparacion = false;
      isDefaultSelection = false;
    } else if (topEntidadesTotal.length >= 2) {
      const top1 = entidades.find(e => e.entidad_desc === topEntidadesTotal[0].nombre);
      const top2 = entidades.find(e => e.entidad_desc === topEntidadesTotal[1].nombre);
      if (top1 && top2) {
        isDefaultSelection = true;
        loadingComparacion = true;
        entidadCompararA = top1;
        datosCompararA = await loadDatosEntidad(top1);
        entidadCompararB = top2;
        datosCompararB = await loadDatosEntidad(top2);
        loadingComparacion = false;
      }
    }
  }

  async function selectEntidadA(entidad) {
    entidadCompararA = entidad;
    dropdownAOpen = false;
    searchA = '';
    entityLimitA = 30;
    isDefaultSelection = false;
    loadingComparacion = true;
    datosCompararA = await loadDatosEntidad(entidad);
    loadingComparacion = false;
    updateCompararUrl();
  }

  async function selectEntidadB(entidad) {
    entidadCompararB = entidad;
    dropdownBOpen = false;
    searchB = '';
    entityLimitB = 30;
    isDefaultSelection = false;
    loadingComparacion = true;
    datosCompararB = await loadDatosEntidad(entidad);
    loadingComparacion = false;
    updateCompararUrl();
  }

  function handleEntityScroll(event, type) {
    const el = event.target;
    if (el.scrollHeight - el.scrollTop - el.clientHeight < 50) {
      if (type === 'A' && entityLimitA < entidades.length) entityLimitA += 30;
      if (type === 'B' && entityLimitB < entidades.length) entityLimitB += 30;
    }
  }

  let rangoAños = $state('todo');

  let añosComunesTotales = $derived.by(() => {
    const añosA = datosCompararA.anual.map(d => d.gestion);
    const añosB = datosCompararB.anual.map(d => d.gestion);
    if (añosA.length && añosB.length) {
      const setB = new Set(añosB);
      return añosA.filter(a => setB.has(a)).sort((a, b) => a - b);
    }
    if (añosA.length) return [...añosA].sort((a, b) => a - b);
    if (añosB.length) return [...añosB].sort((a, b) => a - b);
    return [];
  });

  let soloUnaEntidad = $derived((entidadCompararA && !entidadCompararB) || (!entidadCompararA && entidadCompararB));

  let rangoInfoA = $derived.by(() => {
    if (!datosCompararA.anual.length) return null;
    const años = datosCompararA.anual.map(d => d.gestion).sort((a, b) => a - b);
    return { desde: años[0], hasta: años[años.length - 1], total: años.length };
  });

  let rangoInfoB = $derived.by(() => {
    if (!datosCompararB.anual.length) return null;
    const años = datosCompararB.anual.map(d => d.gestion).sort((a, b) => a - b);
    return { desde: años[0], hasta: años[años.length - 1], total: años.length };
  });

  let tienenRangosDiferentes = $derived.by(() => {
    if (!rangoInfoA || !rangoInfoB) return false;
    return rangoInfoA.desde !== rangoInfoB.desde || rangoInfoA.hasta !== rangoInfoB.hasta;
  });

  let añosComparacion = $derived.by(() => {
    if (rangoAños === 'todo') return añosComunesTotales;
    return añosComunesTotales.slice(-parseInt(rangoAños));
  });

  let datosGraficoA = $derived.by(() => {
    const map = new Map(datosCompararA.anual.map(d => [d.gestion, d]));
    return añosComparacion.map(año => map.get(año) || { per_capita: 0, monto: 0 });
  });

  let datosGraficoB = $derived.by(() => {
    const map = new Map(datosCompararB.anual.map(d => [d.gestion, d]));
    return añosComparacion.map(año => map.get(año) || { per_capita: 0, monto: 0 });
  });

  // Valor según métrica seleccionada
  function valComparar(d) {
    return metrica === 'percapita' ? (d?.per_capita || 0) : (d?.monto || 0);
  }

  let maxComparacion = $derived.by(() => {
    const all = [...datosGraficoA.map(d => valComparar(d)), ...datosGraficoB.map(d => valComparar(d))];
    return Math.max(...all, 1) * 1.1;
  });

  let displayPeriodoComparar = $derived.by(() => {
    if (hoveredYearComparar) return hoveredYearComparar;
    if (añosComparacion.length > 0) return `${añosComparacion[0]}-${añosComparacion[añosComparacion.length - 1]}`;
    return 'Selecciona entidades';
  });

  let displayPropA = $derived.by(() => {
    if (hoveredYearComparar) { const idx = añosComparacion.indexOf(hoveredYearComparar); if (idx >= 0) return datosGraficoA[idx]?.prop || 0; }
    return datosCompararA.historico?.prop || 0;
  });
  let displayPropB = $derived.by(() => {
    if (hoveredYearComparar) { const idx = añosComparacion.indexOf(hoveredYearComparar); if (idx >= 0) return datosGraficoB[idx]?.prop || 0; }
    return datosCompararB.historico?.prop || 0;
  });
  let displayRankingA = $derived.by(() => {
    if (hoveredYearComparar) { const idx = añosComparacion.indexOf(hoveredYearComparar); if (idx >= 0) return datosGraficoA[idx]?.ranking || '-'; }
    return datosCompararA.historico?.ranking || '-';
  });
  let displayRankingB = $derived.by(() => {
    if (hoveredYearComparar) { const idx = añosComparacion.indexOf(hoveredYearComparar); if (idx >= 0) return datosGraficoB[idx]?.ranking || '-'; }
    return datosCompararB.historico?.ranking || '-';
  });
  let displayNEntidadesA = $derived.by(() => {
    if (hoveredYearComparar) { const idx = añosComparacion.indexOf(hoveredYearComparar); if (idx >= 0) return datosGraficoA[idx]?.n_entidades || '-'; }
    return datosCompararA.historico?.n_entidades || '-';
  });
  let displayNEntidadesB = $derived.by(() => {
    if (hoveredYearComparar) { const idx = añosComparacion.indexOf(hoveredYearComparar); if (idx >= 0) return datosGraficoB[idx]?.n_entidades || '-'; }
    return datosCompararB.historico?.n_entidades || '-';
  });

  let isDarkMode = $state(false);
  $effect(() => {
    if (typeof document !== 'undefined') {
      const checkDark = () => { isDarkMode = document.documentElement.classList.contains('dark'); };
      checkDark();
      const observer = new MutationObserver(checkDark);
      observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] });
      return () => observer.disconnect();
    }
  });

  let colorA = $derived(isDarkMode ? '#7EB8DA' : '#6B8299');
  let colorB = $derived(isDarkMode ? '#D4A574' : '#C4897D');

  function toNumber(v) { return typeof v === 'number' ? v : 0; }

  $effect(() => {
    const year = hoveredYearComparar;
    const idx = year ? añosComparacion.indexOf(year) : -1;
    twMontoA.set(idx >= 0 ? toNumber(datosGraficoA[idx]?.monto) : toNumber(datosCompararA.historico?.monto));
    twMontoB.set(idx >= 0 ? toNumber(datosGraficoB[idx]?.monto) : toNumber(datosCompararB.historico?.monto));
    twPerCapitaA.set(idx >= 0 ? toNumber(datosGraficoA[idx]?.per_capita) : toNumber(datosCompararA.historico?.per_capita));
    twPerCapitaB.set(idx >= 0 ? toNumber(datosGraficoB[idx]?.per_capita) : toNumber(datosCompararB.historico?.per_capita));
  });

  // Actualizar URL para vista comparar
  function updateCompararUrl() {
    if (!mounted) return;
    const url = new URL($page.url);
    url.searchParams.set('vista', 'comparar');
    url.searchParams.delete('entidad');
    if (entidadCompararA) url.searchParams.set('entidadA', entidadCompararA.entidad);
    else url.searchParams.delete('entidadA');
    if (entidadCompararB) url.searchParams.set('entidadB', entidadCompararB.entidad);
    else url.searchParams.delete('entidadB');
    goto(url.toString(), { replaceState: true, noScroll: true });
  }

  // Watch vista changes
  let previousVista = 'agregado';
  let skipPopstate = false;
  $effect(() => {
    if (mounted && vista !== previousVista) {
      previousVista = vista;
      if (!skipPopstate) {
        const url = new URL(window.location.href);
        if (vista === 'comparar') {
          url.searchParams.set('vista', 'comparar');
          url.searchParams.delete('entidad');
        } else {
          url.searchParams.delete('vista');
          url.searchParams.delete('entidadA');
          url.searchParams.delete('entidadB');
        }
        history.pushState({ vista }, '', url.toString());
      }
      skipPopstate = false;
      if (vista === 'comparar') initComparacion();
    }
  });

  function handlePopstate(e) {
    const params = new URL(window.location.href).searchParams;
    const urlVista = params.get('vista') || 'agregado';
    if (urlVista !== vista) {
      skipPopstate = true;
      vista = urlVista;
    }
  }

  function formatMonto(m) {
    if (m >= 1e9) return (m / 1e9).toLocaleString('es-BO', { maximumFractionDigits: 1 }) + ' MM';
    if (m >= 1e6) return (m / 1e6).toLocaleString('es-BO', { maximumFractionDigits: 1 }) + ' M';
    if (m >= 1e3) return Math.round(m / 1e3).toLocaleString('es-BO') + ' K';
    return m?.toLocaleString('es-BO') || '0';
  }

  // ══════════════════════════════════════════════════════════════

  onMount(() => {
    mounted = true;
    loadEntidades().then(async () => {
      // Read URL params after entidades are loaded
      const urlVista = $page.url.searchParams.get('vista');
      const urlEntidad = $page.url.searchParams.get('entidad');
      const urlEntidadA = $page.url.searchParams.get('entidadA');
      const urlEntidadB = $page.url.searchParams.get('entidadB');

      if (urlVista === 'comparar') {
        vista = 'comparar';
        // Precargar entidades de comparación desde URL
        if (urlEntidadA) {
          const entA = entidades.find(e => e.entidad === parseInt(urlEntidadA));
          if (entA) {
            entidadCompararA = entA;
            loadingComparacion = true;
            datosCompararA = await loadDatosEntidad(entA);
          }
        }
        if (urlEntidadB) {
          const entB = entidades.find(e => e.entidad === parseInt(urlEntidadB));
          if (entB) {
            entidadCompararB = entB;
            datosCompararB = await loadDatosEntidad(entB);
          }
        }
        loadingComparacion = false;
        if (!urlEntidadA && !urlEntidadB) initComparacion();
      } else if (urlEntidad && entidades.length > 0) {
        const ent = entidades.find(e => e.entidad === parseInt(urlEntidad));
        if (ent) selectedEntity = ent;
      }
    });
  });

  // Recargar cuando cambia el finfun (navegación entre funciones)
  let prevCodigo = null;
  $effect(() => {
    const code = finfunCodigo;
    if (prevCodigo !== null && code !== prevCodigo) {
      // Reiniciar comparación
      entidadCompararA = null;
      entidadCompararB = null;
      datosCompararA = { anual: [], historico: null };
      datosCompararB = { anual: [], historico: null };

      // Cargar datos del estado desde finfunData.estados
      const { hist, anuales, topPorAño } = initEstados(finfunData);
      datosHistorico = hist;
      datosAnuales = anuales;
      topEntidadesPorAño = topPorAño;
      loading = false;

      // Recargar entidades y mantener la seleccionada si existe en la nueva función
      const prevEntity = selectedEntity;
      loadEntidades().then(() => {
        if (prevEntity) {
          const match = entidades.find(e => e.entidad === prevEntity.entidad);
          if (match) {
            selectedEntity = match;
            loadData();
          } else {
            selectedEntity = null;
          }
        }
      });
    }
    prevCodigo = code;
  });

  // Recargar cuando cambia la entidad seleccionada
  let prevEntity = null;
  $effect(() => {
    const ent = selectedEntity;
    if (ent !== prevEntity) {
      prevEntity = ent;
      if (ent) {
        loadData();
      } else if (prevCodigo) {
        const { hist, anuales, topPorAño } = initEstados(finfunData);
        datosHistorico = hist;
        datosAnuales = anuales;
        topEntidadesPorAño = topPorAño;
        loading = false;
      }
      // Actualizar URL
      if (mounted) {
        const url = new URL($page.url);
        if (ent) {
          url.searchParams.set('entidad', ent.entidad);
        } else {
          url.searchParams.delete('entidad');
        }
        goto(url.toString(), { replaceState: true, noScroll: true });
      }
    }
  });
</script>

<svelte:window on:popstate={handlePopstate} />

<svelte:head>
  <title>{finfunData.desc_finfun} | Presupuesto Abierto</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="page" class:mounted>

  {#if vista === 'agregado'}
  <div class="dashboard-layout">
    <!-- Sidebar -->
    <aside class="dashboard-context" class:mobile-open={showMobileSidebar}>
      <!-- Mobile toggle -->
      <button class="mobile-sidebar-toggle" onclick={() => showMobileSidebar = !showMobileSidebar}>
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/>
        </svg>
        <span>{showMobileSidebar ? 'Ocultar herramientas' : 'Herramientas'}</span>
      </button>

      <div class="context-card">
        <h2 class="context-main-title">Herramientas</h2>

        <!-- Buscar -->
        <div class="context-section">
          <h3 class="context-subtitle">Buscar</h3>
          <div class="inline-search">
            <input
              type="text"
              class="inline-search-input"
              placeholder="Buscar finalidad y función..."
              value={searchQuery}
              oninput={onSearchInput}
            />
            {#if searchLoading}
              <div class="inline-search-loading">Buscando...</div>
            {/if}
            {#if searchResults.length > 0}
              <div class="inline-search-results">
                {#each searchResults as result}
                  <a href="/finfun/{result.code}" class="inline-search-item" onclick={() => { searchQuery = ''; searchResults = []; }}>
                    <span class="inline-search-label">{result.label}</span>
                  </a>
                {/each}
              </div>
            {/if}
          </div>
        </div>

        <div class="context-separator"></div>

        <!-- Navegación -->
        {#if padres.length > 0 || hijos.length > 0}
          <div class="context-section">
            <h3 class="context-subtitle">Navegación</h3>
            <p class="context-hint">Funciones relacionadas. Haz click para explorar.</p>
            <div class="tree">
              {#each padres as padre, i}
                <a href="/finfun/{padre.finfun}" class="tree-node has-tooltip" style="--indent: {i}" data-tooltip="{padre.desc_finfun}">
                  <span class="tree-dot"></span>
                  <span class="tree-code">{padre.finfun}</span>
                  <span class="tree-name">{padre.desc_finfun}</span>
                </a>
              {/each}

              <div class="tree-node tree-node-current has-tooltip" style="--indent: {padres.length}" data-tooltip="{finfunData.desc_finfun}">
                <span class="tree-dot"></span>
                <span class="tree-code">{finfunData.finfun}</span>
                <span class="tree-name">{finfunData.desc_finfun}</span>
              </div>

              {#if hijos.length > 0}
                <div class="tree-children" style="--indent: {padres.length + 1}">
                  {#each hijos as hijo}
                    <a href="/finfun/{hijo.finfun}" class="tree-node tree-node-child has-tooltip" data-tooltip="{hijo.desc_finfun}">
                      <span class="tree-dot"></span>
                      <span class="tree-code">{hijo.finfun}</span>
                      <span class="tree-name">{hijo.desc_finfun}</span>
                    </a>
                  {/each}
                </div>
              {/if}
            </div>
          </div>

          <div class="context-separator"></div>
        {/if}

        <!-- Explorar -->
        <div class="context-section">
          <div class="explore-header">
            <h3 class="context-subtitle">Explorar visualizaciones</h3>
            <span class="explore-count">7 →</span>
          </div>
          <div class="explore-scroll">
            <div class="explore-card" onclick={() => vista = 'comparar'} role="button" tabindex="0">
              <span class="explore-title">Comparar dos entidades</span>
              <span class="explore-desc">¿Quién gasta más en {finfunData.desc_finfun?.toLowerCase()}?</span>
            </div>
            <a href="/finfun/{finfunData.finfun}/entidades" class="explore-card">
              <span class="explore-title">Ranking</span>
              <span class="explore-desc">{nEntidades} entidades que gastan en {finfunData.desc_finfun?.toLowerCase()}</span>
            </a>
            <a href="/ubicacion?clas=finfun&codigo={finfunData.finfun}" class="explore-card">
              <span class="explore-title">Mapa</span>
              <span class="explore-desc">Dónde se concentra el gasto en {finfunData.desc_finfun?.toLowerCase()}</span>
            </a>
            <a href="/clasificadores/funcional?modo=mapa" class="explore-card">
              <span class="explore-title">Peso relativo</span>
              <span class="explore-desc">Cuánto pesa {finfunData.desc_finfun?.toLowerCase()} respecto a otros gastos</span>
            </a>
            <a href="/clasificadores/funcional?modo=comparar{selectedEntity ? `&entidad=${selectedEntity.entidad}` : ''}{activeYear ? `&gestion=${activeYear}` : ''}" class="explore-card">
              <span class="explore-title">Comparar funciones</span>
              <span class="explore-desc">Todas las funciones entre dos momentos o entidades</span>
            </a>
            <a href="/clasificadores/funcional" class="explore-card">
              <span class="explore-title">Clasificador</span>
              <span class="explore-desc">Ver todas las finalidades y funciones y navegar entre ellas</span>
            </a>
          </div>
        </div>

        <div class="context-separator"></div>

        <!-- Comparabilidad -->
        <div class="context-section">
          <h3 class="context-subtitle">Comparabilidad</h3>
          <div class="vigencia-compact">
            <div class="vigencia-status-icon vigencia-full">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/>
                <polyline points="22 4 12 14.01 9 11.01"/>
              </svg>
            </div>
            <div class="vigencia-text">
              <span class="vigencia-main">Comparable en todo el período</span>
            </div>
          </div>
        </div>

        <div class="context-separator"></div>

        <!-- Definición -->
        <div class="context-section">
          <h3 class="context-subtitle">Definición</h3>
          {#if variaciones.length <= 1}
            <p class="context-hint">Definición estable en todo el período</p>
          {:else}
            <p class="context-hint">El significado de esta función ha cambiado {variaciones.length} veces en el período</p>
          {/if}
          <button class="def-link" onclick={() => showDefinicionesModal = true}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/>
            </svg>
            {#if variaciones.length <= 1}
              Ver definición
            {:else}
              Ver variaciones
            {/if}
          </button>
        </div>

        <div class="context-separator"></div>

        <!-- Compartir -->
        <div class="context-section">
          <h3 class="context-subtitle">Compartir</h3>
          <button class="copy-link-btn" onclick={() => {
            navigator.clipboard.writeText(window.location.href);
            linkCopied = true;
            setTimeout(() => linkCopied = false, 2000);
          }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              {#if linkCopied}
                <path d="M20 6L9 17l-5-5"/>
              {:else}
                <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/>
                <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>
              {/if}
            </svg>
            <span>{linkCopied ? 'Link copiado' : 'Copiar link para compartir'}</span>
          </button>
        </div>
      </div>
    </aside>

    <!-- Main -->
    <main class="dashboard-main">
      <div class="chart-protagonista">
        <!-- Header -->
        <div class="chart-top-row">
          <div class="main-title-pills">
            <span class="pill pill-nivel">{nivelLabel}</span>
            <span class="pill pill-codigo">{finfunData.finfun}</span>
          </div>
        </div>

        <h2 class="main-title-name">{finfunData.desc_finfun}</h2>

        <div class="chart-controls">
          <EntitySelector {entidades} bind:selectedEntity {nEntidades} />
          {#if selectedEntity}
            <button class="volver-agregado" onclick={() => { selectedEntity = null; }}>
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M19 12H5M12 19l-7-7 7-7"/>
              </svg>
              Todo el Estado
            </button>
          {/if}
        </div>

        <div class="chart-header">
          <span class="chart-title">
            <button class="metrica-toggle" onclick={() => metrica = metrica === 'percapita' ? 'monto' : 'percapita'}>
              {metrica === 'percapita' ? 'Bs/habitante' : 'Bs (monto total)'}
              <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M7 16V4m0 0L3 8m4-4l4 4M17 8v12m0 0l4-4m-4 4l-4-4"/></svg>
            </button>
            <span class="chart-period">· {displayPeriodo}</span>
          </span>
        </div>

        {#if loading}
          <div class="chart-loading" style="flex: 1; min-height: 100px;">
            <span>Cargando...</span>
          </div>
        {:else if gastoPerCapita.length === 0 && selectedEntity}
          <div class="chart-no-data">
            <p>Esta entidad no tiene registros en {finfunData.desc_finfun?.toLowerCase()} desde 2016</p>
            <button class="volver-agregado" onclick={() => { selectedEntity = null; }}>
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M19 12H5M12 19l-7-7 7-7"/>
              </svg>
              Volver a Todo el Estado
            </button>
          </div>
        {:else}
          <div class="chart-flex-wrapper">
            <BarChart data={gastoPerCapita} bind:hoveredYear bind:lockedYear height={200} fill={true} />
          </div>
        {/if}

        <!-- KPIs -->
        <div class="kpis">
          <div class="kpi">
            <span class="kpi-value">{formatMontoLargo(Math.round($twMonto))}</span>
            <span class="kpi-label">{displayMontoLabel}</span>
          </div>
          <div class="kpi">
            <span class="kpi-value">{formatPerCapita($twPerCapita)} Bs.</span>
            <span class="kpi-label">{displayPerCapitaLabel}</span>
          </div>
          <div class="kpi">
            <span class="kpi-value">{$twPorcentaje.toLocaleString('es-BO', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}%</span>
            <span class="kpi-label">{displayPorcentajeLabel}</span>
          </div>
          <div class="kpi">
            <span class="kpi-value">{displayRanking}</span>
            <span class="kpi-label">{displayRankingLabel}</span>
          </div>
        </div>
      </div>

      {#if !selectedEntity && displayTopEntidades.length > 0}
        <div class="ranking-section">
          <div class="ranking-header">
            <h3 class="ranking-title">Concentración del gasto</h3>
            <div class="ranking-summary">
              <span class="ranking-summary-pct">{($twTop1 + $twTop2 + $twTop3).toFixed(1)}%</span>
              <span class="ranking-summary-text">de {finfunData.desc_finfun?.toLowerCase()} lo gastan estas 3 entidades{activeYear ? ` en ${activeYear}` : ''}</span>
            </div>
          </div>
          <div class="ranking-cards">
            {#each displayTopEntidades as ent, i}
              {@const pct = i === 0 ? $twTop1 : i === 1 ? $twTop2 : $twTop3}
              <button class="ranking-card ranking-card-link" onclick={() => {
                const match = entidades.find(e => e.entidad === ent.entidad);
                selectedEntity = match || { entidad: ent.entidad, entidad_desc: ent.nombre };
              }}>
                <span class="ranking-position">#{i + 1}</span>
                <span class="ranking-name">{ent.nombre}</span>
                <span class="ranking-pct">{pct.toFixed(1)}%</span>
                <svg class="ranking-arrow" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M5 12h14M12 5l7 7-7 7"/></svg>
              </button>
            {/each}
          </div>
        </div>
      {/if}
    </main>
  </div>

  <!-- Modal de definiciones -->
  {#if showDefinicionesModal}
    <div class="modal-overlay" onclick={() => showDefinicionesModal = false}>
      <div class="modal-content" onclick={(e) => e.stopPropagation()}>
        <div class="modal-header">
          <h3>Definiciones de "{finfunData.desc_finfun}"</h3>
          <button class="modal-close" onclick={() => showDefinicionesModal = false}>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
            </svg>
          </button>
        </div>
        <div class="modal-body">
          {#if variaciones.length > 0}
            {#each variaciones as v, i}
              <div class="def-item" class:def-current={i === 0}>
                <div class="def-header">
                  <span class="def-period">{v.rango}</span>
                  {#if i === 0}
                    <span class="def-badge">Vigente</span>
                  {/if}
                </div>
                <p class="def-text">{v.texto}</p>
              </div>
            {/each}
          {:else}
            <div class="def-item def-current">
              <div class="def-header">
                <span class="def-period">{finfunData.gestiones || ''}</span>
                <span class="def-badge">Vigente</span>
              </div>
              <p class="def-text">{finfunData.desc_finfun}</p>
            </div>
          {/if}
        </div>
      </div>
    </div>
  {/if}

  {:else}
    <!-- VISTA COMPARAR -->
    <main class="main-comparar">
      <div class="chart-card-comparar">
        <div class="chart-top-row">
          <div class="main-title-pills">
            <span class="pill pill-nivel">{nivelLabel}</span>
            <span class="pill pill-codigo">{finfunData.finfun}</span>
          </div>
          <VistaToggle bind:vista />
        </div>

        <h2 class="main-title-name">{finfunData.desc_finfun}</h2>

        <div class="comparador-selectors">
          <div class="selector-group comparador-dropdown-container">
            <span class="selector-dot" style="background: {colorA}"></span>
            <div class="relative" style="flex: 1;">
              <button class="selector-btn comparador-btn" onclick={() => { dropdownAOpen = !dropdownAOpen; dropdownBOpen = false; }}>
                <span class="truncate">{entidadCompararA ? entidadCompararA.entidad_desc : 'Seleccionar entidad'}</span>
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 9l6 6 6-6"/></svg>
              </button>
              {#if dropdownAOpen}
                <div class="dropdown-panel comparador-panel">
                  <div class="dropdown-search"><input type="text" bind:value={searchA} placeholder="Buscar entidad..." class="search-input" /></div>
                  <div class="dropdown-list" onscroll={(e) => handleEntityScroll(e, 'A')}>
                    {#each filteredEntidadesA as entity}
                      <button class="dropdown-item" class:active={entidadCompararA?.entidad === entity.entidad} disabled={entidadCompararB?.entidad === entity.entidad} onclick={() => selectEntidadA(entity)}>
                        <span class="truncate">{entity.entidad_desc}</span>
                      </button>
                    {/each}
                  </div>
                </div>
              {/if}
            </div>
          </div>

          <span class="vs">vs</span>

          <div class="selector-group comparador-dropdown-container">
            <span class="selector-dot" style="background: {colorB}"></span>
            <div class="relative" style="flex: 1;">
              <button class="selector-btn comparador-btn" onclick={() => { dropdownBOpen = !dropdownBOpen; dropdownAOpen = false; }}>
                <span class="truncate">{entidadCompararB ? entidadCompararB.entidad_desc : 'Seleccionar entidad'}</span>
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 9l6 6 6-6"/></svg>
              </button>
              {#if dropdownBOpen}
                <div class="dropdown-panel comparador-panel">
                  <div class="dropdown-search"><input type="text" bind:value={searchB} placeholder="Buscar entidad..." class="search-input" /></div>
                  <div class="dropdown-list" onscroll={(e) => handleEntityScroll(e, 'B')}>
                    {#each filteredEntidadesB as entity}
                      <button class="dropdown-item" class:active={entidadCompararB?.entidad === entity.entidad} disabled={entidadCompararA?.entidad === entity.entidad} onclick={() => selectEntidadB(entity)}>
                        <span class="truncate">{entity.entidad_desc}</span>
                      </button>
                    {/each}
                  </div>
                </div>
              {/if}
            </div>
          </div>
        </div>

        {#if isDefaultSelection && entidadCompararA && entidadCompararB && !alertDefaultDismissed}
          <div class="comparador-hint">
            <span>Mostrando las dos entidades con mayor gasto. Puedes cambiar la selección arriba.</span>
            <button class="alert-close" onclick={() => alertDefaultDismissed = true}>✕</button>
          </div>
        {/if}

        {#if tienenRangosDiferentes && entidadCompararA && entidadCompararB && !loadingComparacion && !alertRangosDismissed}
          <div class="comparador-warning">
            <span>Rangos diferentes. Solo se comparan {añosComunesTotales.length} años en común.</span>
            <button class="alert-close" onclick={() => alertRangosDismissed = true}>✕</button>
          </div>
        {/if}

        {#if loadingComparacion}
          <div class="comparador-placeholder"><Spinner size={48} color="var(--theme-texto)" /></div>
        {:else if !entidadCompararA && !entidadCompararB}
          <div class="comparador-placeholder"><p>Selecciona dos entidades para comparar</p></div>
        {:else if añosComparacion.length === 0}
          <div class="comparador-placeholder"><p>No hay datos disponibles para comparar</p></div>
        {:else}
          <div class="chart-header">
            <span class="chart-title">
              <button class="metrica-toggle" onclick={() => metrica = metrica === 'percapita' ? 'monto' : 'percapita'}>
                {metrica === 'percapita' ? 'Bs/habitante' : 'Bs (monto total)'}
                <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M7 16V4m0 0L3 8m4-4l4 4M17 8v12m0 0l4-4m-4 4l-4-4"/></svg>
              </button>
              <span class="chart-period">· {displayPeriodoComparar}</span>
            </span>
            <button class="copy-link-btn" onclick={() => {
              navigator.clipboard.writeText(window.location.href);
              linkCopied = true;
              setTimeout(() => linkCopied = false, 2000);
            }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                {#if linkCopied}
                  <path d="M20 6L9 17l-5-5"/>
                {:else}
                  <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/>
                  <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>
                {/if}
              </svg>
              <span>{linkCopied ? 'Copiado' : 'Compartir'}</span>
            </button>
          </div>

          <div class="chart-comparar-wrapper">
            <div class="chart-comparar-inner">
              <span class="y-label-comparar" style="bottom: 100%">Bs {formatMonto(Math.round(maxComparacion))}</span>
              <span class="y-label-comparar" style="bottom: 50%">Bs {formatMonto(Math.round(maxComparacion / 2))}</span>
              <span class="y-label-comparar" style="bottom: 0%">Bs 0</span>
              <div class="grid-line-comparar" style="bottom: 100%"></div>
              <div class="grid-line-comparar" style="bottom: 50%"></div>
              <div class="grid-line-comparar" style="bottom: 0%"></div>
              <div class="bars-comparar" onmouseleave={() => hoveredYearComparar = null} role="group">
                {#each añosComparacion as año, i}
                  <div class="bar-group-comparar" class:active={hoveredYearComparar === año} onmouseenter={() => hoveredYearComparar = año} role="button" tabindex="0">
                    <div class="bars-pair">
                      <div class="bar-comparar" style="height: {(valComparar(datosGraficoA[i]) / maxComparacion) * 100}%; background: {colorA}"></div>
                      <div class="bar-comparar" style="height: {(valComparar(datosGraficoB[i]) / maxComparacion) * 100}%; background: {colorB}"></div>
                    </div>
                  </div>
                {/each}
              </div>
            </div>
            <div class="x-axis-comparar">
              {#each añosComparacion as año, i}
                {@const show = i === 0 || i === añosComparacion.length - 1 || hoveredYearComparar === año}
                <span class="x-label-comparar" class:visible={show}>{año}</span>
              {/each}
            </div>
          </div>

          <div class="chart-legend">
            {#if entidadCompararA}<span class="legend-item"><span class="legend-dot" style="background: {colorA}"></span>{entidadCompararA.entidad_desc}</span>{/if}
            {#if entidadCompararB}<span class="legend-item"><span class="legend-dot" style="background: {colorB}"></span>{entidadCompararB.entidad_desc}</span>{/if}
          </div>
        {/if}
      </div>

      {#if soloUnaEntidad}
        <div class="comparador-hint comparador-hint-select">
          <span>Selecciona la segunda entidad para ver la comparación completa.</span>
        </div>
      {/if}

      {#if entidadCompararA && entidadCompararB}
        <div class="kpis-card-comparar">
          <div class="tabla-header">
            <span class="tabla-label"></span>
            <span class="tabla-val tabla-entidad" style="color: {colorA}">{entidadCompararA.entidad_desc}</span>
            <span class="tabla-val tabla-entidad" style="color: {colorB}">{entidadCompararB.entidad_desc}</span>
          </div>
          <div class="tabla-row">
            <span class="tabla-label">Gasto</span>
            <span class="tabla-val">Bs {formatMontoLargo(Math.round($twMontoA))}</span>
            <span class="tabla-val">Bs {formatMontoLargo(Math.round($twMontoB))}</span>
          </div>
          <div class="tabla-row">
            <span class="tabla-label">Per cápita</span>
            <span class="tabla-val">Bs {formatPerCapita($twPerCapitaA)}</span>
            <span class="tabla-val">Bs {formatPerCapita($twPerCapitaB)}</span>
          </div>
          <div class="tabla-row">
            <span class="tabla-label">Peso</span>
            <span class="tabla-val">{displayPropA.toLocaleString('es-BO', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}%</span>
            <span class="tabla-val">{displayPropB.toLocaleString('es-BO', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}%</span>
          </div>
          <div class="tabla-row">
            <span class="tabla-label">Ranking</span>
            <span class="tabla-val">#{displayRankingA} de {displayNEntidadesA}</span>
            <span class="tabla-val">#{displayRankingB} de {displayNEntidadesB}</span>
          </div>
        </div>
      {/if}
    </main>
  {/if}
</div>

<style>
  /* ═══════════════════════════════════════════════════════════════
     PAGE
     ═══════════════════════════════════════════════════════════════ */
  .page {
    height: 100dvh;
    width: 100%;
    max-width: 100%;
    overflow: hidden;
    background: var(--theme-body);
    padding-top: 60px;
    box-sizing: border-box;
    color: var(--theme-titulo);
    font-family: var(--font-sans), -apple-system, sans-serif;
    opacity: 0;
    transition: opacity 0.4s ease;
  }
  .page.mounted { opacity: 1; }

  :global(html:not(.dark)) .page {
    background: #f5f5f7;
  }

  /* ═══════════════════════════════════════════════════════════════
     NAV
     ═══════════════════════════════════════════════════════════════ */
  .page-nav {
    padding: 2rem 2rem 0.5rem;
    max-width: 1400px;
    margin: 0 auto;
  }

  .back-link {
    display: inline-flex;
    align-items: center;
    gap: 0.375rem;
    font-family: 'DM Mono', monospace;
    font-size: 0.6875rem;
    color: var(--theme-texto);
    text-decoration: none;
    transition: color 0.2s;
  }
  .back-link:hover { color: var(--theme-accent); }

  /* ═══════════════════════════════════════════════════════════════
     LAYOUT
     ═══════════════════════════════════════════════════════════════ */
  .dashboard-layout {
    display: grid;
    grid-template-columns: minmax(200px, 30%) 1fr;
    gap: 1.5rem;
    max-width: 1400px;
    margin: 0 auto;
    padding: 1rem 2rem 2rem;
    height: 100%;
    overflow: hidden;
  }

  /* ═══════════════════════════════════════════════════════════════
     SIDEBAR
     ═══════════════════════════════════════════════════════════════ */
  .dashboard-context {
    display: flex;
    flex-direction: column;
    min-height: 0;
  }

  .context-card {
    background: var(--theme-surface);
    border-radius: 12px;
    padding: 0.75rem;
    display: flex;
    flex-direction: column;
    gap: 8px;
    flex: 1;
    min-height: 0;
    overflow-y: auto;
    scrollbar-width: thin;
  }

  .context-card::-webkit-scrollbar { width: 4px; }
  .context-card::-webkit-scrollbar-thumb {
    background: rgba(128, 128, 128, 0.3);
    border-radius: 2px;
  }

  .context-main-title {
    font-size: 1rem;
    font-weight: 600;
    color: var(--theme-titulo);
    margin: 0;
    line-height: 1.2;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    opacity: 0.5;
  }

  .context-subtitle {
    font-family: 'Qanelas', var(--font-sans);
    font-size: 0.875rem;
    font-weight: 700;
    color: var(--theme-titulo);
    margin: 0;
  }

  .context-hint {
    font-size: 0.75rem;
    color: var(--theme-texto);
    opacity: 0.7;
    margin: 0;
    line-height: 1.4;
  }

  .context-section {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
  }

  .context-separator {
    border-top: 1px solid var(--theme-borde);
    margin: 0.25rem 0;
  }

  /* ═══════════════════════════════════════════════════════════════
     INLINE SEARCH
     ═══════════════════════════════════════════════════════════════ */
  .inline-search {
    position: relative;
  }

  .inline-search-input {
    width: 100%;
    padding: 0.5rem 0.75rem;
    border: 1px solid var(--theme-borde);
    border-radius: 8px;
    background: var(--theme-body);
    color: var(--theme-titulo);
    font-size: 0.8125rem;
    outline: none;
    font-family: inherit;
    box-sizing: border-box;
  }
  .inline-search-input:focus {
    border-color: var(--theme-accent);
  }
  .inline-search-input::placeholder {
    color: var(--theme-texto);
    opacity: 0.5;
  }

  .inline-search-loading {
    font-size: 0.6875rem;
    color: var(--theme-texto);
    opacity: 0.5;
    padding: 0.25rem 0;
  }

  .inline-search-results {
    position: absolute;
    top: calc(100% + 4px);
    left: 0;
    right: 0;
    background: var(--theme-surface);
    border: 1px solid var(--theme-borde);
    border-radius: 8px;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
    max-height: 240px;
    overflow-y: auto;
    z-index: 100;
  }

  .inline-search-item {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.5rem 0.75rem;
    text-decoration: none;
    color: var(--theme-titulo);
    font-size: 0.8125rem;
    transition: background 0.15s;
  }
  .inline-search-item:hover {
    background: var(--theme-surface-hover, rgba(201, 167, 81, 0.08));
  }

  .inline-search-code {
    font-family: 'DM Mono', monospace;
    font-size: 0.6875rem;
    color: var(--theme-texto);
    opacity: 0.6;
    min-width: 2.5rem;
  }

  .inline-search-label {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  /* ═══════════════════════════════════════════════════════════════
     TREE
     ═══════════════════════════════════════════════════════════════ */
  .tree {
    font-size: 0.75rem;
    line-height: 1.6;
  }

  .tree-node {
    display: flex;
    align-items: center;
    gap: 0.375rem;
    padding: 0.375rem 0.5rem;
    margin-left: calc(var(--indent, 0) * 1rem);
    border-left: 2px solid transparent;
    border-radius: 0 6px 6px 0;
    text-decoration: none;
    color: var(--theme-texto);
    transition: all 0.15s;
  }
  .tree-node:hover { color: var(--theme-accent); }

  .tree-node-current {
    color: var(--theme-titulo);
    font-weight: 600;
    border-left-color: var(--theme-accent);
    background: rgba(201, 167, 81, 0.1);
  }

  .tree-children {
    margin-left: calc(var(--indent, 0) * 1rem);
  }

  .tree-node-child {
    padding-left: 0.75rem;
  }

  .tree-dot {
    width: 4px;
    height: 4px;
    border-radius: 50%;
    background: currentColor;
    flex-shrink: 0;
    opacity: 0.4;
  }

  .tree-code {
    font-family: 'DM Mono', monospace;
    font-size: 0.6875rem;
    min-width: 2.5rem;
    opacity: 0.6;
  }

  .tree-name {
    font-size: 0.6875rem;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  /* ═══════════════════════════════════════════════════════════════
     EXPLORE
     ═══════════════════════════════════════════════════════════════ */
  .explore-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .explore-count {
    font-family: 'DM Mono', monospace;
    font-size: 0.625rem;
    color: var(--theme-accent);
    opacity: 0.7;
    animation: nudgeRight 1.5s ease-in-out infinite;
  }

  @keyframes nudgeRight {
    0%, 100% { transform: translateX(0); }
    50% { transform: translateX(3px); }
  }

  .explore-scroll {
    display: flex;
    gap: 8px;
    overflow-x: auto;
    scrollbar-width: none;
    padding-bottom: 2px;
  }
  .explore-scroll::-webkit-scrollbar { display: none; }

  .explore-scroll {
    -webkit-mask-image: linear-gradient(to right, black 85%, transparent 100%);
    mask-image: linear-gradient(to right, black 85%, transparent 100%);
  }

  .explore-card {
    position: relative;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    padding: 0.375rem 0.5rem;
    width: 120px;
    height: 95px;
    border-radius: 8px;
    background: var(--theme-borde);
    text-decoration: none;
    color: var(--theme-texto);
    cursor: pointer;
    transition: all 0.15s;
    flex-shrink: 0;
    overflow: hidden;
  }
  .explore-card:hover {
    background: rgba(201, 167, 81, 0.15);
    color: var(--theme-accent);
  }
  .explore-card:hover .explore-watermark {
    opacity: 0.18;
    color: var(--theme-accent);
  }
  .explore-card:hover .explore-title {
    color: var(--theme-accent);
  }

  .explore-watermark {
    position: absolute;
    bottom: -4px;
    right: -4px;
    width: 44px;
    height: 44px;
    opacity: 0.15;
    pointer-events: none;
    color: var(--theme-accent, #C9A751);
  }

  .explore-title {
    position: relative;
    font-size: 0.75rem;
    font-weight: 600;
    line-height: 1.3;
    color: var(--theme-titulo);
    z-index: 1;
  }

  .explore-desc {
    position: relative;
    font-size: 0.625rem;
    line-height: 1.35;
    opacity: 0.6;
    margin-top: 3px;
    z-index: 1;
  }

  .explore-card-disabled {
    opacity: 0.3;
    pointer-events: none;
  }

  /* ═══════════════════════════════════════════════════════════════
     VIGENCIA
     ═══════════════════════════════════════════════════════════════ */
  .vigencia-compact {
    display: flex;
    align-items: center;
    gap: 0.75rem;
  }

  .vigencia-status-icon {
    width: 32px;
    height: 32px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
  }

  .vigencia-status-icon.vigencia-full {
    background: rgba(74, 158, 107, 0.15);
    color: #4A9E6B;
  }

  .vigencia-text {
    display: flex;
    flex-direction: column;
    gap: 0.125rem;
  }

  .vigencia-main {
    font-size: 0.75rem;
    font-weight: 500;
    color: var(--theme-titulo);
  }

  .vigencia-sub {
    font-size: 0.625rem;
    color: var(--theme-texto);
    opacity: 0.5;
  }

  /* ═══════════════════════════════════════════════════════════════
     DEFINICIÓN
     ═══════════════════════════════════════════════════════════════ */
  .def-link {
    display: flex;
    align-items: center;
    gap: 0.375rem;
    font-size: 0.75rem;
    color: var(--theme-accent, #C9A751);
    background: none;
    border: none;
    padding: 0;
    cursor: pointer;
    transition: opacity 0.15s;
  }
  .def-link:hover { opacity: 0.7; }
  .def-link svg { flex-shrink: 0; opacity: 0.8; }

  .chart-no-data {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 0.75rem;
    color: var(--theme-texto);
    opacity: 0.7;
    font-size: 0.8125rem;
    text-align: center;
  }

  .chart-no-data p {
    margin: 0;
  }

  .volver-agregado {
    display: inline-flex;
    align-items: center;
    gap: 0.25rem;
    font-size: 0.6875rem;
    color: var(--theme-accent);
    background: none;
    border: none;
    padding: 0;
    cursor: pointer;
    transition: opacity 0.15s;
  }
  .volver-agregado:hover { opacity: 0.7; }

  .copy-link-btn {
    display: flex;
    align-items: center;
    gap: 0.375rem;
    font-size: 0.75rem;
    color: var(--theme-texto);
    opacity: 0.6;
    background: none;
    border: none;
    padding: 0;
    cursor: pointer;
    transition: opacity 0.15s;
  }
  .copy-link-btn:hover { opacity: 1; }
  .copy-link-btn svg { flex-shrink: 0; }

  /* ═══════════════════════════════════════════════════════════════
     MAIN
     ═══════════════════════════════════════════════════════════════ */
  .dashboard-main {
    display: flex;
    flex-direction: column;
    gap: 1.5rem;
    min-height: 0;
    overflow: hidden;
  }

  .chart-protagonista {
    background: var(--theme-surface);
    border-radius: 12px;
    padding: 0.75rem;
    display: flex;
    flex-direction: column;
    min-height: 0;
    flex: 2;
    overflow: hidden;
  }

  .ranking-section {
    background: var(--theme-surface);
    border-radius: 12px;
    padding: 0.75rem;
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0;
  }

  /* ═══════════════════════════════════════════════════════════════
     CHART & KPIs
     ═══════════════════════════════════════════════════════════════ */
  .chart-top-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 0.375rem;
  }

  .main-title-pills {
    display: flex;
    gap: 0.375rem;
  }

  .pill {
    font-family: 'DM Mono', monospace;
    font-size: 0.625rem;
    padding: 0.125rem 0.5rem;
    border-radius: 4px;
    letter-spacing: 0.03em;
  }

  .pill-nivel {
    background: rgba(201, 167, 81, 0.15);
    color: var(--theme-accent);
  }

  .pill-codigo {
    background: var(--theme-borde);
    color: var(--theme-texto);
  }

  .main-title-name {
    font-family: 'DM Serif Display', serif;
    font-size: 2rem;
    font-weight: 400;
    margin: 0 0 0.5rem;
    line-height: 1.15;
    color: var(--theme-titulo);
  }

  .chart-controls {
    margin-bottom: 0.5rem;
  }

  .chart-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 0.25rem;
  }

  .chart-title {
    font-family: 'DM Mono', monospace;
    font-size: 0.6875rem;
    color: var(--theme-texto);
    opacity: 0.7;
  }

  .chart-period {
    opacity: 0.5;
  }

  .metrica-toggle {
    font-family: 'DM Mono', monospace;
    font-size: 0.6875rem;
    color: var(--theme-texto);
    background: rgba(128, 128, 128, 0.08);
    border: 1px solid rgba(128, 128, 128, 0.15);
    padding: 0.125rem 0.375rem;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.15s;
    display: inline-flex;
    align-items: center;
    gap: 0.25rem;
  }

  .metrica-toggle:hover {
    background: rgba(201, 167, 81, 0.12);
    border-color: rgba(201, 167, 81, 0.3);
    color: var(--theme-accent);
  }

  .chart-loading {
    display: flex;
    align-items: center;
    justify-content: center;
    color: var(--theme-texto);
    opacity: 0.5;
  }

  .chart-flex-wrapper {
    flex: 1;
    min-height: 0;
  }

  .kpis {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 0.5rem;
    margin-top: 0.5rem;
    padding-top: 0.75rem;
    border-top: 1px solid var(--theme-borde);
  }

  .kpi {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 0.125rem;
    text-align: center;
  }

  .kpi-value {
    font-family: 'Qanelas', var(--font-sans);
    font-size: 1rem;
    font-weight: 600;
    color: var(--theme-titulo);
  }

  .kpi-label {
    font-size: 0.625rem;
    color: var(--theme-texto);
    opacity: 0.5;
    line-height: 1.35;
  }

  /* ═══════════════════════════════════════════════════════════════
     RANKING
     ═══════════════════════════════════════════════════════════════ */
  .ranking-title {
    font-size: 1rem;
    font-weight: 600;
    color: var(--theme-titulo);
    margin: 0 0 0.25rem;
  }

  .ranking-desc {
    font-size: 0.6875rem;
    color: var(--theme-texto);
    opacity: 0.5;
    margin: 0 0 0.5rem;
  }

  .ranking-cards {
    display: flex;
    flex-direction: column;
    gap: 0.25rem;
  }

  .ranking-card {
    display: flex;
    align-items: center;
    gap: 0.375rem;
    padding: 0.5rem 0.625rem;
    border-radius: 8px;
    background: transparent;
    text-align: left;
  }

  .ranking-card-link {
    text-decoration: none;
    cursor: pointer;
    transition: background 0.15s;
  }

  .ranking-card-link:hover {
    background: rgba(201, 167, 81, 0.05);
  }

  .ranking-card-link:hover .ranking-name {
    color: var(--theme-accent);
    border-bottom-style: solid;
  }

  .ranking-arrow {
    opacity: 0;
    color: var(--theme-accent);
    transition: opacity 0.15s, transform 0.15s;
    flex-shrink: 0;
  }

  .ranking-card-link:hover .ranking-arrow {
    opacity: 1;
    transform: translateX(2px);
  }

  .ranking-header {
    margin-bottom: 0.5rem;
  }

  .ranking-summary {
    display: flex;
    align-items: baseline;
    gap: 0.375rem;
    margin-top: 0.125rem;
  }

  .ranking-summary-pct {
    font-family: 'DM Mono', monospace;
    font-size: 1.25rem;
    font-weight: 700;
    color: var(--theme-titulo);
  }

  .ranking-summary-text {
    font-size: 0.75rem;
    color: var(--theme-texto);
    opacity: 0.7;
  }

  .ranking-position {
    font-family: 'DM Mono', monospace;
    font-size: 0.6875rem;
    color: var(--theme-accent);
    font-weight: 600;
    min-width: 1.5rem;
  }

  .ranking-name {
    font-size: 0.8125rem;
    color: var(--theme-titulo);
    border-bottom: 1px dotted rgba(128, 128, 128, 0.3);
  }

  .ranking-pct {
    font-family: 'DM Mono', monospace;
    font-size: 0.8125rem;
    font-weight: 600;
    color: var(--theme-titulo);
    opacity: 0.7;
  }

  /* ═══════════════════════════════════════════════════════════════
     MODAL
     ═══════════════════════════════════════════════════════════════ */
  .modal-overlay {
    position: fixed;
    inset: 0;
    background: rgba(0, 0, 0, 0.6);
    backdrop-filter: blur(4px);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
    padding: 1rem;
  }

  .modal-content {
    background: var(--theme-surface);
    border-radius: 16px;
    max-width: 560px;
    width: 100%;
    max-height: 80vh;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    box-shadow: 0 24px 48px rgba(0, 0, 0, 0.2);
  }

  .modal-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 1.25rem 1.5rem;
    border-bottom: 1px solid var(--theme-borde);
  }

  .modal-header h3 {
    font-size: 1rem;
    font-weight: 600;
    color: var(--theme-titulo);
    margin: 0;
  }

  .modal-close {
    color: var(--theme-texto);
    background: transparent;
    border: none;
    padding: 0.25rem;
    cursor: pointer;
    border-radius: 6px;
    transition: background 0.2s;
  }

  .modal-close:hover {
    background: var(--theme-borde);
  }

  .modal-body {
    padding: 1.5rem;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    gap: 1rem;
  }

  .def-item {
    padding: 1rem;
    background: var(--theme-body);
    border-radius: 10px;
    border-left: 3px solid var(--theme-borde);
  }

  .def-current {
    border-left-color: #6B9FD4;
  }

  .def-header {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    margin-bottom: 0.5rem;
  }

  .def-period {
    font-family: 'DM Mono', monospace;
    font-size: 0.75rem;
    font-weight: 500;
    color: #6B9FD4;
  }

  .def-badge {
    font-size: 0.625rem;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    color: white;
    background: #4A9E6B;
    padding: 0.125rem 0.5rem;
    border-radius: 4px;
  }

  .def-text {
    font-size: 0.875rem;
    color: var(--theme-texto);
    line-height: 1.6;
    margin: 0;
  }

  :global(html.dark) .def-current {
    border-left-color: var(--theme-accent);
  }

  :global(html.dark) .def-period {
    color: var(--theme-accent);
  }

  /* ═══════════════════════════════════════════════════════════════
     MOBILE SIDEBAR
     ═══════════════════════════════════════════════════════════════ */
  .mobile-sidebar-toggle {
    display: none;
  }

  @media (max-width: 900px) {
    .dashboard-layout {
      grid-template-columns: 1fr;
      gap: 0.5rem;
      height: auto;
      overflow: visible;
      padding: 1.5rem 1rem 2rem;
      align-content: center;
      min-height: calc(100vh - 4rem);
    }

    .dashboard-main {
      overflow: visible;
    }

    .chart-protagonista {
      flex: none;
    }

    .ranking-section {
      flex: none;
    }

    .mobile-sidebar-toggle {
      display: flex;
      align-items: center;
      gap: 0.5rem;
      padding: 0.625rem 1rem;
      background: var(--theme-surface);
      border: 1px solid var(--theme-borde);
      border-radius: 10px;
      color: var(--theme-titulo);
      font-family: 'Qanelas', var(--font-sans);
      font-size: 0.8125rem;
      font-weight: 500;
      cursor: pointer;
      transition: all 0.2s;
      margin-bottom: 0.25rem;
      width: 100%;
    }

    .mobile-sidebar-toggle:hover {
      background: var(--theme-surface-hover);
    }

    .mobile-sidebar-toggle svg {
      color: var(--theme-texto);
      opacity: 0.6;
    }

    .dashboard-context .context-card {
      display: none;
    }

    .dashboard-context.mobile-open .context-card {
      display: flex;
      animation: slideDown 0.25s ease;
    }

    @keyframes slideDown {
      from { opacity: 0; transform: translateY(-8px); }
      to { opacity: 1; transform: translateY(0); }
    }

    .context-card {
      height: auto;
      overflow-y: visible;
    }

    .page-nav {
      padding: 0.75rem 1rem;
    }

    .kpis {
      grid-template-columns: repeat(2, 1fr);
    }
  }

  @media (max-width: 480px) {
    .dashboard-layout {
      padding: 0.5rem;
    }

    .page-nav {
      padding: 0.5rem;
    }

    .chart-protagonista,
    .ranking-section,
    .context-card {
      padding: 0.5rem;
      border-radius: 8px;
    }

    .main-title-name {
      font-size: 1.375rem;
    }

    .chart-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 0.25rem;
    }

    .kpis {
      grid-template-columns: repeat(2, 1fr);
      gap: 0.375rem;
    }

    .kpi-value {
      font-size: 0.8125rem;
    }

    .kpi-label {
      font-size: 0.5625rem;
    }

    .explore-scroll {
      gap: 6px;
    }

    .explore-card {
      width: 100px;
      height: 80px;
    }

    .explore-title {
      font-size: 0.625rem;
    }

    .explore-desc {
      font-size: 0.5rem;
    }

    .ranking-title {
      font-size: 0.875rem;
    }

    .ranking-name {
      font-size: 0.6875rem;
    }

    .ranking-pct {
      font-size: 0.75rem;
    }

    .modal-content {
      margin: 0.5rem;
      max-height: 90vh;
    }

    .tree-name {
      max-width: 150px;
    }
  }

  /* ═══════════════════════════════════════════════════════════════
     DARK MODE
     ═══════════════════════════════════════════════════════════════ */
  :global(html.dark) .context-hint {
    color: rgba(255, 255, 255, 0.5);
  }

  :global(html.dark) .def-link {
    color: var(--theme-accent, #C9A751);
  }

  /* ═══════════════════════════════════════════════════════════════
     COMPARAR VIEW
     ═══════════════════════════════════════════════════════════════ */
  .main-comparar {
    display: flex;
    flex-direction: column;
    gap: 0.75rem;
    padding: 1rem 2rem 2rem;
    width: 100%;
    max-width: 1400px;
    margin: 0 auto;
    height: 100%;
    overflow: hidden;
  }

  .chart-card-comparar {
    background: var(--theme-surface);
    border-radius: 12px;
    padding: 1rem 1.5rem;
    display: flex;
    flex-direction: column;
    flex: 1;
    min-height: 0;
  }

  .comparador-selectors {
    display: flex;
    align-items: center;
    gap: 1rem;
    margin-bottom: 1rem;
  }

  .selector-group { flex: 1; display: flex; align-items: center; gap: 0.5rem; }
  .selector-dot { width: 10px; height: 10px; border-radius: 50%; flex-shrink: 0; }
  .vs { font-family: 'DM Mono', monospace; font-size: 0.75rem; color: var(--theme-texto); flex-shrink: 0; }
  .relative { position: relative; }
  .truncate { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }

  .selector-btn {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.625rem 1rem;
    background: var(--theme-body);
    border: 1px solid var(--theme-borde);
    border-radius: 8px;
    font-size: 0.8125rem;
    color: var(--theme-titulo);
    cursor: pointer;
    transition: border-color 0.2s;
  }
  .selector-btn:hover { border-color: var(--theme-accent); }
  .comparador-btn { width: 100%; justify-content: space-between; }
  .comparador-dropdown-container { position: relative; }

  .dropdown-panel.comparador-panel {
    position: absolute;
    top: calc(100% + 4px);
    left: 0;
    width: 100%;
    min-width: 280px;
    background: var(--theme-surface);
    border: 1px solid var(--theme-borde);
    border-radius: 10px;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
    z-index: 100;
    overflow: hidden;
  }

  .dropdown-search { padding: 0.5rem; border-bottom: 1px solid var(--theme-borde); }
  .search-input {
    width: 100%;
    padding: 0.5rem 0.75rem;
    border: 1px solid var(--theme-borde);
    border-radius: 6px;
    background: var(--theme-body);
    color: var(--theme-titulo);
    font-size: 0.8125rem;
    outline: none;
  }
  .search-input:focus { border-color: var(--theme-accent); }

  .dropdown-item {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    width: 100%;
    padding: 0.625rem 0.75rem;
    border: none;
    background: transparent;
    color: var(--theme-titulo);
    font-size: 0.8125rem;
    text-align: left;
    cursor: pointer;
    transition: background 0.15s;
  }
  .dropdown-item:hover { background: var(--theme-surface-hover); }
  .dropdown-item.active { background: rgba(201, 167, 81, 0.1); color: var(--theme-accent); }
  .dropdown-item:disabled { opacity: 0.4; cursor: not-allowed; }
  .dropdown-list { max-height: 240px; overflow-y: auto; }
  .entity-code { font-family: 'DM Mono', monospace; font-size: 0.6875rem; color: var(--theme-texto); min-width: 2rem; }

  .comparador-placeholder {
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 200px;
    border: 1px dashed var(--theme-borde);
    border-radius: 12px;
    padding: 2rem;
    text-align: center;
  }
  .comparador-placeholder p { color: var(--theme-texto); font-size: 0.875rem; margin: 0; }

  .comparador-hint {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.75rem 1rem;
    background: rgba(107, 159, 212, 0.1);
    border-radius: 8px;
    font-size: 0.8125rem;
    color: #6B9FD4;
  }
  .comparador-hint span { flex: 1; }
  .comparador-hint-select { margin-top: 0.75rem; }

  .comparador-warning {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.75rem 1rem;
    background: rgba(230, 176, 75, 0.1);
    border-radius: 8px;
    font-size: 0.8125rem;
    color: #C9A751;
  }
  .comparador-warning span { flex: 1; }

  .alert-close {
    flex-shrink: 0;
    padding: 0.25rem;
    border: none;
    background: transparent;
    color: inherit;
    opacity: 0.6;
    cursor: pointer;
    border-radius: 4px;
  }
  .alert-close:hover { opacity: 1; }

  .chart-comparar-wrapper {
    position: relative;
    width: 100%;
    flex: 1;
    min-height: 180px;
  }

  .chart-comparar-inner {
    position: absolute;
    top: 10px;
    bottom: 30px;
    left: 50px;
    right: 10px;
  }

  .y-label-comparar {
    position: absolute;
    left: -50px;
    width: 45px;
    text-align: right;
    transform: translateY(50%);
    font-family: 'DM Mono', monospace;
    font-size: 0.6875rem;
    color: var(--theme-texto);
    white-space: nowrap;
  }

  .grid-line-comparar {
    position: absolute;
    left: 0;
    right: 0;
    border-top: 0.5px dotted var(--theme-texto);
    opacity: 0.15;
  }

  .bars-comparar {
    position: absolute;
    inset: 0;
    display: flex;
    align-items: flex-end;
    gap: 3px;
  }

  .bar-group-comparar {
    flex: 1;
    height: 100%;
    display: flex;
    align-items: flex-end;
    justify-content: center;
    cursor: pointer;
  }

  .bars-pair {
    display: flex;
    align-items: flex-end;
    gap: 2px;
    height: 100%;
    width: 100%;
    justify-content: center;
  }

  .bar-comparar {
    flex: 1;
    max-width: 24px;
    border-radius: 3px 3px 0 0;
    min-height: 2px;
    transition: opacity 0.15s;
  }

  .bars-comparar:hover .bar-comparar { opacity: 0.35; }
  .bar-group-comparar.active .bar-comparar { opacity: 1; }

  .x-axis-comparar {
    position: absolute;
    bottom: 0;
    left: 50px;
    right: 10px;
    height: 30px;
    display: flex;
    align-items: center;
  }

  .x-label-comparar {
    flex: 1;
    text-align: center;
    font-family: 'DM Mono', monospace;
    font-size: 0.6875rem;
    color: var(--theme-texto);
    opacity: 0;
    transition: opacity 0.2s;
  }
  .x-label-comparar.visible { opacity: 1; }

  .chart-legend {
    display: flex;
    justify-content: center;
    gap: 2rem;
    margin-top: 0.5rem;
    margin-bottom: 0.75rem;
  }

  .legend-item {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    font-size: 0.75rem;
    color: var(--theme-texto);
  }

  .legend-dot { width: 10px; height: 10px; border-radius: 3px; }

  .kpis-card-comparar {
    background: var(--theme-surface);
    border-radius: 12px;
    padding: 0.75rem 1.25rem;
  }

  .tabla-header {
    display: grid;
    grid-template-columns: 1fr 1.2fr 1.2fr;
    gap: 0.75rem;
    padding-bottom: 0.375rem;
    border-bottom: 1px solid var(--theme-borde);
    margin-bottom: 0.25rem;
  }

  .tabla-header .tabla-val {
    font-size: 0.625rem;
    font-weight: 500;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    text-align: center;
  }

  .tabla-entidad {
    font-size: 0.6875rem;
    line-height: 1.3;
    word-break: break-word;
  }

  .tabla-row {
    display: grid;
    grid-template-columns: 1fr 1.2fr 1.2fr;
    gap: 0.75rem;
    padding: 0.1875rem 0;
  }

  .tabla-label {
    font-size: 0.6875rem;
    font-weight: 500;
    color: var(--theme-texto);
    text-transform: uppercase;
    letter-spacing: 0.05em;
  }

  .tabla-val {
    font-size: 0.875rem;
    font-weight: 500;
    color: var(--theme-titulo);
    text-align: center;
    font-variant-numeric: tabular-nums;
  }

  @media (max-width: 640px) {
    .main-comparar { padding: 0.75rem; }
    .chart-card-comparar, .kpis-card-comparar { padding: 1rem; }
    .comparador-selectors { flex-direction: column; gap: 0.75rem; }
    .vs { display: none; }
  }
</style>