zenit-sdk 0.0.2 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,20 +17,40 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/index.ts
21
31
  var src_exports = {};
22
32
  __export(src_exports, {
33
+ ChevronLeft: () => import_lucide_react.ChevronLeft,
34
+ ChevronRight: () => import_lucide_react.ChevronRight,
23
35
  DEFAULT_MAX_FEATURES_FULL_GEOJSON: () => DEFAULT_MAX_FEATURES_FULL_GEOJSON,
36
+ Eye: () => import_lucide_react.Eye,
37
+ EyeOff: () => import_lucide_react.EyeOff,
24
38
  FilterEngine: () => FilterEngine,
39
+ FloatingChatBox: () => FloatingChatBox,
25
40
  HttpClient: () => HttpClient,
41
+ Layers: () => import_lucide_react.Layers,
42
+ Upload: () => import_lucide_react.Upload,
43
+ X: () => import_lucide_react.X,
26
44
  ZenitAuthClient: () => ZenitAuthClient,
27
45
  ZenitCatalogNotSupportedError: () => ZenitCatalogNotSupportedError,
28
46
  ZenitClient: () => ZenitClient,
47
+ ZenitFeatureFilterPanel: () => ZenitFeatureFilterPanel,
48
+ ZenitLayerManager: () => ZenitLayerManager,
29
49
  ZenitLayersClient: () => ZenitLayersClient,
50
+ ZenitMap: () => ZenitMap,
30
51
  ZenitMapsClient: () => ZenitMapsClient,
31
52
  ZenitSdkAuthClient: () => ZenitSdkAuthClient,
53
+ ZoomIn: () => import_lucide_react.ZoomIn,
32
54
  applyFilteredGeoJSONStrategy: () => applyFilteredGeoJSONStrategy,
33
55
  applyLayerOverrides: () => applyLayerOverrides,
34
56
  applyPrefiltersToFeatureCollection: () => applyPrefiltersToFeatureCollection,
@@ -37,22 +59,34 @@ __export(src_exports, {
37
59
  buildLayerFilters: () => buildLayerFilters,
38
60
  buildLimitedMessage: () => buildLimitedMessage,
39
61
  centroidFromBBox: () => centroidFromBBox,
62
+ clampNumber: () => clampNumber,
63
+ clampOpacity: () => clampOpacity3,
40
64
  computeBBoxFromFeature: () => computeBBoxFromFeature,
41
65
  createChatService: () => createChatService,
42
66
  decorateFeaturesWithLayerId: () => decorateFeaturesWithLayerId,
43
67
  extractMapDto: () => extractMapDto,
44
68
  filterEngine: () => filterEngine,
69
+ getAccentByLayerId: () => getAccentByLayerId,
45
70
  getCatalogSupport: () => getCatalogSupport,
71
+ getEffectiveLayerOpacity: () => getEffectiveLayerOpacity,
72
+ getLayerColor: () => getLayerColor,
73
+ getLayerZoomOpacityFactor: () => getLayerZoomOpacityFactor,
74
+ getStyleByLayerId: () => getStyleByLayerId,
75
+ getZoomOpacityFactor: () => getZoomOpacityFactor,
46
76
  initLayerStates: () => initLayerStates,
77
+ isPolygonLayer: () => isPolygonLayer,
47
78
  normalizeBbox: () => normalizeBbox,
48
79
  normalizeMapCenter: () => normalizeMapCenter,
49
80
  normalizeMapLayers: () => normalizeMapLayers,
50
81
  resetOverrides: () => resetOverrides,
82
+ resolveLayerAccent: () => resolveLayerAccent,
51
83
  resolveLayerStrategy: () => resolveLayerStrategy,
52
84
  sendMessage: () => sendMessage,
53
85
  sendMessageStream: () => sendMessageStream,
54
86
  shouldSkipGeojsonDownload: () => shouldSkipGeojsonDownload,
55
- shouldUseFilterMultiple: () => shouldUseFilterMultiple
87
+ shouldUseFilterMultiple: () => shouldUseFilterMultiple,
88
+ useSendMessage: () => useSendMessage,
89
+ useSendMessageStream: () => useSendMessageStream
56
90
  });
57
91
  module.exports = __toCommonJS(src_exports);
58
92
 
@@ -1367,17 +1401,2733 @@ function normalizeBbox(input) {
1367
1401
  console.warn("[normalizeBbox] Unsupported bbox format:", typeof input);
1368
1402
  return null;
1369
1403
  }
1404
+
1405
+ // src/react/ZenitMap.tsx
1406
+ var import_react = require("react");
1407
+ var import_react_leaflet = require("react-leaflet");
1408
+ var import_leaflet = __toESM(require("leaflet"));
1409
+
1410
+ // src/react/layerStyleHelpers.ts
1411
+ function resolveLayerAccent(style) {
1412
+ if (!style) return null;
1413
+ return style.fillColor ?? style.color ?? null;
1414
+ }
1415
+ function getLayerColor(style, fallback = "#94a3b8") {
1416
+ return resolveLayerAccent(style) ?? fallback;
1417
+ }
1418
+ function getStyleByLayerId(layerId, mapLayers) {
1419
+ if (!mapLayers) return null;
1420
+ const match = mapLayers.find((ml) => String(ml.layerId) === String(layerId));
1421
+ return match?.style ?? null;
1422
+ }
1423
+ function getAccentByLayerId(layerId, mapLayers) {
1424
+ const style = getStyleByLayerId(layerId, mapLayers);
1425
+ return resolveLayerAccent(style);
1426
+ }
1427
+
1428
+ // src/react/zoomOpacity.ts
1429
+ var DEFAULT_OPTIONS = {
1430
+ minZoom: 10,
1431
+ maxZoom: 17,
1432
+ minFactor: 0.6,
1433
+ maxFactor: 1,
1434
+ minOpacity: 0.1,
1435
+ maxOpacity: 0.92
1436
+ };
1437
+ function clampNumber(value, min, max) {
1438
+ return Math.min(max, Math.max(min, value));
1439
+ }
1440
+ function clampOpacity3(value) {
1441
+ return clampNumber(value, 0, 1);
1442
+ }
1443
+ function isPolygonLayer(layerType, geometryType) {
1444
+ const candidate = (layerType ?? geometryType ?? "").toLowerCase();
1445
+ return candidate === "polygon" || candidate === "multipolygon";
1446
+ }
1447
+ function getZoomOpacityFactor(zoom, options) {
1448
+ const settings = { ...DEFAULT_OPTIONS, ...options };
1449
+ const { minZoom, maxZoom, minFactor, maxFactor } = settings;
1450
+ if (maxZoom <= minZoom) return clampNumber(maxFactor, minFactor, maxFactor);
1451
+ const t = clampNumber((zoom - minZoom) / (maxZoom - minZoom), 0, 1);
1452
+ const factor = maxFactor + (minFactor - maxFactor) * t;
1453
+ return clampNumber(factor, minFactor, maxFactor);
1454
+ }
1455
+ function getLayerZoomOpacityFactor(zoom, layerType, geometryType, options) {
1456
+ if (!isPolygonLayer(layerType, geometryType)) return 1;
1457
+ return getZoomOpacityFactor(zoom, options);
1458
+ }
1459
+ function getEffectiveLayerOpacity(baseOpacity, zoom, layerType, geometryType, options) {
1460
+ if (!isPolygonLayer(layerType, geometryType)) {
1461
+ return clampOpacity3(baseOpacity);
1462
+ }
1463
+ const settings = { ...DEFAULT_OPTIONS, ...options };
1464
+ const factor = getZoomOpacityFactor(zoom, options);
1465
+ const effective = clampOpacity3(baseOpacity) * factor;
1466
+ return clampNumber(effective, settings.minOpacity, settings.maxOpacity);
1467
+ }
1468
+
1469
+ // src/react/ZenitMap.tsx
1470
+ var import_jsx_runtime = require("react/jsx-runtime");
1471
+ var DEFAULT_CENTER = [0, 0];
1472
+ var DEFAULT_ZOOM = 3;
1473
+ function computeBBoxFromGeojson(geojson) {
1474
+ if (!geojson) return null;
1475
+ if (!Array.isArray(geojson.features) || geojson.features.length === 0) return null;
1476
+ const coords = [];
1477
+ const collect = (candidate) => {
1478
+ if (!Array.isArray(candidate)) return;
1479
+ if (candidate.length === 2 && typeof candidate[0] === "number" && typeof candidate[1] === "number") {
1480
+ coords.push([candidate[0], candidate[1]]);
1481
+ return;
1482
+ }
1483
+ candidate.forEach((entry) => collect(entry));
1484
+ };
1485
+ geojson.features.forEach((feature) => {
1486
+ collect(feature.geometry?.coordinates);
1487
+ });
1488
+ if (coords.length === 0) return null;
1489
+ const [firstLon, firstLat] = coords[0];
1490
+ const bbox = { minLon: firstLon, minLat: firstLat, maxLon: firstLon, maxLat: firstLat };
1491
+ coords.forEach(([lon, lat]) => {
1492
+ bbox.minLon = Math.min(bbox.minLon, lon);
1493
+ bbox.minLat = Math.min(bbox.minLat, lat);
1494
+ bbox.maxLon = Math.max(bbox.maxLon, lon);
1495
+ bbox.maxLat = Math.max(bbox.maxLat, lat);
1496
+ });
1497
+ return bbox;
1498
+ }
1499
+ function mergeBBoxes(bboxes) {
1500
+ const valid = bboxes.filter((bbox) => !!bbox);
1501
+ if (valid.length === 0) return null;
1502
+ const first = valid[0];
1503
+ return valid.slice(1).reduce(
1504
+ (acc, bbox) => ({
1505
+ minLon: Math.min(acc.minLon, bbox.minLon),
1506
+ minLat: Math.min(acc.minLat, bbox.minLat),
1507
+ maxLon: Math.max(acc.maxLon, bbox.maxLon),
1508
+ maxLat: Math.max(acc.maxLat, bbox.maxLat)
1509
+ }),
1510
+ { ...first }
1511
+ );
1512
+ }
1513
+ function getFeatureLayerId(feature) {
1514
+ const layerId = feature?.properties?.__zenit_layerId ?? feature?.properties?.layerId ?? feature?.properties?.layer_id;
1515
+ if (layerId === void 0 || layerId === null) return null;
1516
+ return layerId;
1517
+ }
1518
+ function escapeHtml(value) {
1519
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
1520
+ }
1521
+ function withAlpha(color, alpha) {
1522
+ const trimmed = color.trim();
1523
+ if (trimmed.startsWith("#")) {
1524
+ const hex = trimmed.replace("#", "");
1525
+ const expanded = hex.length === 3 ? hex.split("").map((char) => `${char}${char}`).join("") : hex;
1526
+ if (expanded.length === 6) {
1527
+ const r = parseInt(expanded.slice(0, 2), 16);
1528
+ const g = parseInt(expanded.slice(2, 4), 16);
1529
+ const b = parseInt(expanded.slice(4, 6), 16);
1530
+ return `rgba(${r}, ${g}, ${b}, ${alpha})`;
1531
+ }
1532
+ }
1533
+ if (trimmed.startsWith("rgb(")) {
1534
+ const inner = trimmed.slice(4, -1);
1535
+ return `rgba(${inner}, ${alpha})`;
1536
+ }
1537
+ if (trimmed.startsWith("rgba(")) {
1538
+ const inner = trimmed.slice(5, -1).split(",").slice(0, 3).map((value) => value.trim());
1539
+ return `rgba(${inner.join(", ")}, ${alpha})`;
1540
+ }
1541
+ return color;
1542
+ }
1543
+ function getRgbFromColor(color) {
1544
+ const trimmed = color.trim();
1545
+ if (trimmed.startsWith("#")) {
1546
+ const hex = trimmed.replace("#", "");
1547
+ const expanded = hex.length === 3 ? hex.split("").map((char) => `${char}${char}`).join("") : hex;
1548
+ if (expanded.length === 6) {
1549
+ const r = parseInt(expanded.slice(0, 2), 16);
1550
+ const g = parseInt(expanded.slice(2, 4), 16);
1551
+ const b = parseInt(expanded.slice(4, 6), 16);
1552
+ return { r, g, b };
1553
+ }
1554
+ }
1555
+ const rgbMatch = trimmed.match(/rgba?\(([^)]+)\)/i);
1556
+ if (rgbMatch) {
1557
+ const [r, g, b] = rgbMatch[1].split(",").map((value) => parseFloat(value.trim())).slice(0, 3);
1558
+ if ([r, g, b].every((value) => Number.isFinite(value))) {
1559
+ return { r, g, b };
1560
+ }
1561
+ }
1562
+ return null;
1563
+ }
1564
+ function getLabelTextStyles(color) {
1565
+ const rgb = getRgbFromColor(color);
1566
+ if (!rgb) {
1567
+ return { color: "#0f172a", shadow: "0 1px 2px rgba(255, 255, 255, 0.6)" };
1568
+ }
1569
+ const luminance = (0.2126 * rgb.r + 0.7152 * rgb.g + 0.0722 * rgb.b) / 255;
1570
+ if (luminance > 0.6) {
1571
+ return { color: "#0f172a", shadow: "0 1px 2px rgba(255, 255, 255, 0.7)" };
1572
+ }
1573
+ return { color: "#ffffff", shadow: "0 1px 2px rgba(0, 0, 0, 0.4)" };
1574
+ }
1575
+ function getFeatureStyleOverrides(feature) {
1576
+ const candidate = feature?.properties?._style;
1577
+ if (!candidate || typeof candidate !== "object" || Array.isArray(candidate)) return null;
1578
+ const styleCandidate = candidate;
1579
+ return {
1580
+ color: styleCandidate.color,
1581
+ weight: styleCandidate.weight,
1582
+ fillColor: styleCandidate.fillColor,
1583
+ fillOpacity: styleCandidate.fillOpacity
1584
+ };
1585
+ }
1586
+ function buildFeaturePopupHtml(feature) {
1587
+ const properties = feature?.properties;
1588
+ if (!properties) return null;
1589
+ const layerName = properties.layerName ?? properties.layer_name ?? properties.name;
1590
+ const descripcion = properties.descripcion ?? properties.description;
1591
+ const reservedKeys = /* @__PURE__ */ new Set([
1592
+ "_style",
1593
+ "layerId",
1594
+ "layer_id",
1595
+ "__zenit_layerId",
1596
+ "layerName",
1597
+ "layer_name",
1598
+ "name",
1599
+ "descripcion",
1600
+ "description"
1601
+ ]);
1602
+ const extraEntries = Object.entries(properties).filter(([key, value]) => {
1603
+ if (reservedKeys.has(key)) return false;
1604
+ return ["string", "number", "boolean"].includes(typeof value);
1605
+ }).slice(0, 5);
1606
+ if (!layerName && !descripcion && extraEntries.length === 0) return null;
1607
+ const parts = [];
1608
+ if (layerName) {
1609
+ parts.push(`<div style="font-weight:600;margin-bottom:4px;">${escapeHtml(layerName)}</div>`);
1610
+ }
1611
+ if (descripcion) {
1612
+ parts.push(`<div style="margin-bottom:6px;">${escapeHtml(descripcion)}</div>`);
1613
+ }
1614
+ if (extraEntries.length > 0) {
1615
+ const rows = extraEntries.map(([key, value]) => {
1616
+ const label = escapeHtml(key.replace(/_/g, " "));
1617
+ const val = escapeHtml(String(value));
1618
+ return `<div><strong>${label}:</strong> ${val}</div>`;
1619
+ }).join("");
1620
+ parts.push(`<div style="font-size:12px;line-height:1.4;">${rows}</div>`);
1621
+ }
1622
+ return `<div>${parts.join("")}</div>`;
1623
+ }
1624
+ function normalizeCenterTuple(center) {
1625
+ if (!center) return null;
1626
+ if (Array.isArray(center) && center.length >= 2) {
1627
+ const lat = center[0];
1628
+ const lon = center[1];
1629
+ if (typeof lat === "number" && typeof lon === "number") return [lat, lon];
1630
+ return null;
1631
+ }
1632
+ const maybeObj = center;
1633
+ if (typeof maybeObj.lat === "number" && typeof maybeObj.lon === "number") {
1634
+ return [maybeObj.lat, maybeObj.lon];
1635
+ }
1636
+ return null;
1637
+ }
1638
+ var FitToBounds = ({ bbox }) => {
1639
+ const mapInstance = (0, import_react_leaflet.useMap)();
1640
+ const lastAppliedBBox = (0, import_react.useRef)(null);
1641
+ (0, import_react.useEffect)(() => {
1642
+ const targetBBox = bbox;
1643
+ if (!targetBBox) return;
1644
+ const serialized = JSON.stringify(targetBBox);
1645
+ if (lastAppliedBBox.current === serialized) return;
1646
+ const bounds = [
1647
+ [targetBBox.minLat, targetBBox.minLon],
1648
+ [targetBBox.maxLat, targetBBox.maxLon]
1649
+ ];
1650
+ mapInstance.fitBounds(bounds, { padding: [12, 12] });
1651
+ lastAppliedBBox.current = serialized;
1652
+ }, [bbox, mapInstance]);
1653
+ return null;
1654
+ };
1655
+ var AutoFitToBounds = ({
1656
+ bbox,
1657
+ enabled = true
1658
+ }) => {
1659
+ const mapInstance = (0, import_react_leaflet.useMap)();
1660
+ const lastAutoBBoxApplied = (0, import_react.useRef)(null);
1661
+ const lastUserInteracted = (0, import_react.useRef)(false);
1662
+ (0, import_react.useEffect)(() => {
1663
+ if (!enabled) return;
1664
+ const handleInteraction = () => {
1665
+ lastUserInteracted.current = true;
1666
+ };
1667
+ mapInstance.on("dragstart", handleInteraction);
1668
+ mapInstance.on("zoomstart", handleInteraction);
1669
+ return () => {
1670
+ mapInstance.off("dragstart", handleInteraction);
1671
+ mapInstance.off("zoomstart", handleInteraction);
1672
+ };
1673
+ }, [enabled, mapInstance]);
1674
+ (0, import_react.useEffect)(() => {
1675
+ if (!enabled) return;
1676
+ if (!bbox) return;
1677
+ const serialized = JSON.stringify(bbox);
1678
+ if (lastAutoBBoxApplied.current === serialized) return;
1679
+ if (lastUserInteracted.current) {
1680
+ lastUserInteracted.current = false;
1681
+ }
1682
+ const bounds = [
1683
+ [bbox.minLat, bbox.minLon],
1684
+ [bbox.maxLat, bbox.maxLon]
1685
+ ];
1686
+ mapInstance.fitBounds(bounds, { padding: [12, 12] });
1687
+ lastAutoBBoxApplied.current = serialized;
1688
+ }, [bbox, enabled, mapInstance]);
1689
+ return null;
1690
+ };
1691
+ var ZoomBasedOpacityHandler = ({ onZoomChange }) => {
1692
+ const mapInstance = (0, import_react_leaflet.useMap)();
1693
+ (0, import_react.useEffect)(() => {
1694
+ const handleZoom = () => {
1695
+ onZoomChange(mapInstance.getZoom());
1696
+ };
1697
+ mapInstance.on("zoomend", handleZoom);
1698
+ handleZoom();
1699
+ return () => {
1700
+ mapInstance.off("zoomend", handleZoom);
1701
+ };
1702
+ }, [mapInstance, onZoomChange]);
1703
+ return null;
1704
+ };
1705
+ var MapInstanceBridge = ({ onReady }) => {
1706
+ const mapInstance = (0, import_react_leaflet.useMap)();
1707
+ (0, import_react.useEffect)(() => {
1708
+ onReady(mapInstance);
1709
+ }, [mapInstance, onReady]);
1710
+ return null;
1711
+ };
1712
+ var ZenitMap = (0, import_react.forwardRef)(({
1713
+ client,
1714
+ mapId,
1715
+ height = "500px",
1716
+ width = "100%",
1717
+ initialZoom,
1718
+ initialCenter,
1719
+ showLayerPanel = true,
1720
+ overlayGeojson,
1721
+ overlayStyle,
1722
+ layerControls,
1723
+ layerStates,
1724
+ layerGeojson,
1725
+ onLayerStateChange,
1726
+ onError,
1727
+ onLoadingChange,
1728
+ onFeatureClick,
1729
+ onFeatureHover,
1730
+ featureInfoMode = "popup",
1731
+ mapLayers,
1732
+ zoomToBbox,
1733
+ zoomToGeojson,
1734
+ onZoomChange,
1735
+ onMapReady
1736
+ }, ref) => {
1737
+ const [map, setMap] = (0, import_react.useState)(null);
1738
+ const [layers, setLayers] = (0, import_react.useState)([]);
1739
+ const [effectiveStates, setEffectiveStates] = (0, import_react.useState)([]);
1740
+ const [loadingMap, setLoadingMap] = (0, import_react.useState)(false);
1741
+ const [mapError, setMapError] = (0, import_react.useState)(null);
1742
+ const [mapInstance, setMapInstance] = (0, import_react.useState)(null);
1743
+ const [currentZoom, setCurrentZoom] = (0, import_react.useState)(initialZoom ?? DEFAULT_ZOOM);
1744
+ const [isMobile, setIsMobile] = (0, import_react.useState)(() => {
1745
+ if (typeof window === "undefined") return false;
1746
+ return window.matchMedia("(max-width: 768px)").matches;
1747
+ });
1748
+ const normalizedLayers = (0, import_react.useMemo)(() => normalizeMapLayers(map), [map]);
1749
+ (0, import_react.useEffect)(() => {
1750
+ if (typeof window === "undefined") return;
1751
+ const mql = window.matchMedia("(max-width: 768px)");
1752
+ const onChange = (e) => {
1753
+ setIsMobile(e.matches);
1754
+ };
1755
+ setIsMobile(mql.matches);
1756
+ if (typeof mql.addEventListener === "function") {
1757
+ mql.addEventListener("change", onChange);
1758
+ return () => mql.removeEventListener("change", onChange);
1759
+ }
1760
+ const legacy = mql;
1761
+ if (typeof legacy.addListener === "function") {
1762
+ legacy.addListener(onChange);
1763
+ return () => legacy.removeListener(onChange);
1764
+ }
1765
+ return;
1766
+ }, []);
1767
+ const layerStyleIndex = (0, import_react.useMemo)(() => {
1768
+ const index = /* @__PURE__ */ new Map();
1769
+ (map?.mapLayers ?? []).forEach((entry) => {
1770
+ const layerStyle = entry.layer?.style ?? entry.mapLayer?.layer?.style ?? entry.style ?? null;
1771
+ const layerId = entry.layerId ?? entry.mapLayer?.layerId ?? entry.mapLayer?.layer?.id ?? entry.layer?.id;
1772
+ if (layerId !== void 0 && layerId !== null && layerStyle) {
1773
+ index.set(String(layerId), layerStyle);
1774
+ }
1775
+ });
1776
+ return index;
1777
+ }, [map]);
1778
+ const labelKeyIndex = (0, import_react.useMemo)(() => {
1779
+ const index = /* @__PURE__ */ new Map();
1780
+ normalizedLayers.forEach((entry) => {
1781
+ const label = entry.layer?.label ?? entry.mapLayer?.label ?? entry.mapLayer.layerConfig?.label;
1782
+ if (typeof label === "string" && label.trim().length > 0) {
1783
+ index.set(String(entry.layerId), label);
1784
+ }
1785
+ });
1786
+ return index;
1787
+ }, [normalizedLayers]);
1788
+ const layerMetaIndex = (0, import_react.useMemo)(() => {
1789
+ const index = /* @__PURE__ */ new Map();
1790
+ normalizedLayers.forEach((entry) => {
1791
+ index.set(String(entry.layerId), {
1792
+ layerType: typeof entry.layer?.layerType === "string" ? entry.layer.layerType : typeof entry.mapLayer.layerType === "string" ? entry.mapLayer.layerType : void 0,
1793
+ geometryType: typeof entry.layer?.geometryType === "string" ? entry.layer.geometryType : typeof entry.mapLayer.layerConfig?.geometryType === "string" ? entry.mapLayer.layerConfig.geometryType : void 0
1794
+ });
1795
+ });
1796
+ return index;
1797
+ }, [normalizedLayers]);
1798
+ const overlayStyleFunction = (0, import_react.useMemo)(() => {
1799
+ return (feature) => {
1800
+ const featureLayerId = getFeatureLayerId(feature);
1801
+ const featureStyleOverrides = getFeatureStyleOverrides(feature);
1802
+ let style = null;
1803
+ if (featureLayerId !== null) {
1804
+ style = getStyleByLayerId(featureLayerId, mapLayers) ?? layerStyleIndex.get(String(featureLayerId)) ?? null;
1805
+ }
1806
+ const resolvedStyle = featureStyleOverrides ? { ...style ?? {}, ...featureStyleOverrides } : style;
1807
+ const defaultOptions = {
1808
+ color: resolvedStyle?.color ?? resolvedStyle?.fillColor ?? "#2563eb",
1809
+ weight: resolvedStyle?.weight ?? 2,
1810
+ fillColor: resolvedStyle?.fillColor ?? resolvedStyle?.color ?? "#2563eb",
1811
+ fillOpacity: resolvedStyle?.fillOpacity ?? 0.15,
1812
+ ...overlayStyle ?? {}
1813
+ };
1814
+ return defaultOptions;
1815
+ };
1816
+ }, [layerStyleIndex, mapLayers, overlayStyle]);
1817
+ const [baseStates, setBaseStates] = (0, import_react.useState)([]);
1818
+ const [mapOverrides, setMapOverrides] = (0, import_react.useState)([]);
1819
+ const [controlOverrides, setControlOverrides] = (0, import_react.useState)([]);
1820
+ const [uiOverrides, setUiOverrides] = (0, import_react.useState)([]);
1821
+ (0, import_react.useEffect)(() => {
1822
+ let isMounted = true;
1823
+ setLoadingMap(true);
1824
+ setMapError(null);
1825
+ onLoadingChange?.("map", true);
1826
+ client.maps.getMap(mapId, true).then((mapResponse) => {
1827
+ if (!isMounted) return;
1828
+ const extracted = extractMapDto(mapResponse);
1829
+ const resolved = extracted ? normalizeMapCenter(extracted) : null;
1830
+ setMap(resolved);
1831
+ }).catch((err) => {
1832
+ if (!isMounted) return;
1833
+ setMapError(err instanceof Error ? err.message : "No se pudo obtener el mapa");
1834
+ onError?.(err, "map");
1835
+ }).finally(() => {
1836
+ if (!isMounted) return;
1837
+ setLoadingMap(false);
1838
+ onLoadingChange?.("map", false);
1839
+ });
1840
+ return () => {
1841
+ isMounted = false;
1842
+ };
1843
+ }, [client.maps, mapId, onError, onLoadingChange]);
1844
+ (0, import_react.useEffect)(() => {
1845
+ if (normalizedLayers.length === 0) {
1846
+ setLayers([]);
1847
+ setBaseStates([]);
1848
+ setMapOverrides([]);
1849
+ setUiOverrides([]);
1850
+ return;
1851
+ }
1852
+ const nextLayers = normalizedLayers.map((entry) => ({
1853
+ mapLayer: { ...entry.mapLayer, layerId: entry.layerId },
1854
+ layer: entry.layer,
1855
+ displayOrder: entry.displayOrder
1856
+ }));
1857
+ const base = initLayerStates(
1858
+ normalizedLayers.map((entry) => ({
1859
+ ...entry.mapLayer,
1860
+ layerId: entry.layerId,
1861
+ opacity: entry.opacity,
1862
+ isVisible: entry.isVisible
1863
+ }))
1864
+ );
1865
+ const initialOverrides = normalizedLayers.map((entry) => ({
1866
+ layerId: entry.layerId,
1867
+ overrideVisible: entry.isVisible,
1868
+ overrideOpacity: entry.opacity
1869
+ }));
1870
+ setLayers(nextLayers);
1871
+ setBaseStates(base);
1872
+ setMapOverrides(initialOverrides);
1873
+ setUiOverrides([]);
1874
+ }, [normalizedLayers]);
1875
+ (0, import_react.useEffect)(() => {
1876
+ if (!layerControls) {
1877
+ setControlOverrides([]);
1878
+ return;
1879
+ }
1880
+ const overrides = layerControls.map((entry) => ({
1881
+ layerId: entry.layerId,
1882
+ overrideVisible: entry.visible,
1883
+ overrideOpacity: entry.opacity
1884
+ }));
1885
+ setControlOverrides(overrides);
1886
+ }, [layerControls]);
1887
+ (0, import_react.useEffect)(() => {
1888
+ if (layerStates) {
1889
+ return;
1890
+ }
1891
+ if (Array.isArray(layerControls) && layerControls.length === 0 && effectiveStates.length > 0) {
1892
+ const reset = resetOverrides(baseStates);
1893
+ setEffectiveStates(reset);
1894
+ onLayerStateChange?.(reset);
1895
+ }
1896
+ }, [baseStates, effectiveStates.length, layerControls, layerStates, onLayerStateChange]);
1897
+ (0, import_react.useEffect)(() => {
1898
+ if (layerStates) {
1899
+ setEffectiveStates(layerStates);
1900
+ }
1901
+ }, [layerStates]);
1902
+ (0, import_react.useEffect)(() => {
1903
+ if (layerStates) {
1904
+ return;
1905
+ }
1906
+ if (mapOverrides.length === 0 && controlOverrides.length === 0 && uiOverrides.length === 0) {
1907
+ setEffectiveStates(baseStates);
1908
+ return;
1909
+ }
1910
+ const combined = [...mapOverrides, ...controlOverrides, ...uiOverrides];
1911
+ const next = applyLayerOverrides(baseStates, combined);
1912
+ setEffectiveStates(next);
1913
+ onLayerStateChange?.(next);
1914
+ }, [baseStates, controlOverrides, layerStates, mapOverrides, onLayerStateChange, uiOverrides]);
1915
+ (0, import_react.useEffect)(() => {
1916
+ if (!Array.isArray(layerControls) || layerControls.length > 0) return;
1917
+ setUiOverrides([]);
1918
+ }, [layerControls]);
1919
+ (0, import_react.useEffect)(() => {
1920
+ if (layerStates) {
1921
+ return;
1922
+ }
1923
+ if (!Array.isArray(layerControls) && effectiveStates.length > 0 && baseStates.length > 0) {
1924
+ const next = resetOverrides(baseStates);
1925
+ setEffectiveStates(next);
1926
+ onLayerStateChange?.(next);
1927
+ }
1928
+ }, [baseStates, effectiveStates.length, layerControls, layerStates, onLayerStateChange]);
1929
+ const upsertUiOverride = (layerId, patch) => {
1930
+ setUiOverrides((prev) => {
1931
+ const filtered = prev.filter((entry) => entry.layerId !== layerId);
1932
+ const nextEntry = {
1933
+ layerId,
1934
+ ...patch
1935
+ };
1936
+ return [...filtered, nextEntry];
1937
+ });
1938
+ };
1939
+ const updateOpacityFromUi = (0, import_react.useCallback)(
1940
+ (layerId, uiOpacity) => {
1941
+ const meta = layerMetaIndex.get(String(layerId));
1942
+ const zoomFactor = getLayerZoomOpacityFactor(
1943
+ currentZoom,
1944
+ meta?.layerType,
1945
+ meta?.geometryType
1946
+ );
1947
+ const baseOpacity = clampOpacity3(uiOpacity / zoomFactor);
1948
+ const effectiveOpacity = getEffectiveLayerOpacity(
1949
+ baseOpacity,
1950
+ currentZoom,
1951
+ meta?.layerType,
1952
+ meta?.geometryType
1953
+ );
1954
+ if (layerStates && onLayerStateChange) {
1955
+ const next = effectiveStates.map(
1956
+ (state) => state.layerId === layerId ? {
1957
+ ...state,
1958
+ baseOpacity,
1959
+ opacity: effectiveOpacity,
1960
+ overrideOpacity: uiOpacity
1961
+ } : state
1962
+ );
1963
+ onLayerStateChange(next);
1964
+ return;
1965
+ }
1966
+ setBaseStates(
1967
+ (prev) => prev.map((state) => state.layerId === layerId ? { ...state, baseOpacity } : state)
1968
+ );
1969
+ setUiOverrides((prev) => {
1970
+ const existing = prev.find((entry) => entry.layerId === layerId);
1971
+ const filtered = prev.filter((entry) => entry.layerId !== layerId);
1972
+ if (existing && existing.overrideVisible !== void 0) {
1973
+ return [
1974
+ ...filtered,
1975
+ { layerId, overrideVisible: existing.overrideVisible }
1976
+ ];
1977
+ }
1978
+ return filtered;
1979
+ });
1980
+ },
1981
+ [currentZoom, effectiveStates, layerMetaIndex, layerStates, onLayerStateChange]
1982
+ );
1983
+ const center = (0, import_react.useMemo)(() => {
1984
+ if (initialCenter) {
1985
+ return initialCenter;
1986
+ }
1987
+ const normalized = normalizeCenterTuple(map?.settings?.center);
1988
+ if (normalized) {
1989
+ return normalized;
1990
+ }
1991
+ return DEFAULT_CENTER;
1992
+ }, [initialCenter, map?.settings?.center]);
1993
+ const zoom = initialZoom ?? map?.settings?.zoom ?? DEFAULT_ZOOM;
1994
+ (0, import_react.useEffect)(() => {
1995
+ setCurrentZoom(zoom);
1996
+ }, [zoom]);
1997
+ const decoratedLayers = (0, import_react.useMemo)(() => {
1998
+ return layers.map((layer) => ({
1999
+ ...layer,
2000
+ effective: effectiveStates.find((state) => state.layerId === layer.mapLayer.layerId),
2001
+ data: layerGeojson?.[layer.mapLayer.layerId] ?? layerGeojson?.[String(layer.mapLayer.layerId)] ?? null
2002
+ }));
2003
+ }, [effectiveStates, layerGeojson, layers]);
2004
+ const orderedLayers = (0, import_react.useMemo)(() => {
2005
+ return [...decoratedLayers].filter((layer) => layer.effective?.visible && layer.data).sort((a, b) => a.displayOrder - b.displayOrder);
2006
+ }, [decoratedLayers]);
2007
+ const explicitZoomBBox = (0, import_react.useMemo)(() => {
2008
+ if (zoomToBbox) return zoomToBbox;
2009
+ if (zoomToGeojson) return computeBBoxFromGeojson(zoomToGeojson);
2010
+ return null;
2011
+ }, [zoomToBbox, zoomToGeojson]);
2012
+ const autoZoomBBox = (0, import_react.useMemo)(() => {
2013
+ if (explicitZoomBBox) return null;
2014
+ const visibleBBoxes = orderedLayers.map((layer) => computeBBoxFromGeojson(layer.data));
2015
+ return mergeBBoxes(visibleBBoxes);
2016
+ }, [explicitZoomBBox, orderedLayers]);
2017
+ const resolveLayerStyle = (0, import_react.useCallback)(
2018
+ (layerId) => {
2019
+ return getStyleByLayerId(layerId, mapLayers) ?? layerStyleIndex.get(String(layerId)) ?? null;
2020
+ },
2021
+ [layerStyleIndex, mapLayers]
2022
+ );
2023
+ const labelMarkers = (0, import_react.useMemo)(() => {
2024
+ const markers = [];
2025
+ decoratedLayers.forEach((layerState) => {
2026
+ if (!layerState.effective?.visible) return;
2027
+ const labelKey = labelKeyIndex.get(String(layerState.mapLayer.layerId));
2028
+ if (!labelKey) return;
2029
+ const data = layerState.data;
2030
+ if (!data) return;
2031
+ const resolvedStyle = resolveLayerStyle(layerState.mapLayer.layerId);
2032
+ const layerColor = resolvedStyle?.fillColor ?? resolvedStyle?.color ?? "rgba(37, 99, 235, 1)";
2033
+ const opacity = layerState.effective?.opacity ?? 1;
2034
+ data.features.forEach((feature, index) => {
2035
+ const properties = feature.properties;
2036
+ const value = properties?.[labelKey];
2037
+ if (value === void 0 || value === null || value === "") return;
2038
+ const bbox = computeBBoxFromFeature(feature);
2039
+ if (!bbox) return;
2040
+ const [lat, lng] = centroidFromBBox(bbox);
2041
+ markers.push({
2042
+ key: `${layerState.mapLayer.layerId}-label-${index}`,
2043
+ position: [lat, lng],
2044
+ label: String(value),
2045
+ opacity,
2046
+ layerId: layerState.mapLayer.layerId,
2047
+ color: layerColor
2048
+ });
2049
+ });
2050
+ });
2051
+ return markers;
2052
+ }, [decoratedLayers, labelKeyIndex, resolveLayerStyle]);
2053
+ const ensureLayerPanes = (0, import_react.useCallback)(
2054
+ (targetMap, targetLayers) => {
2055
+ const baseZIndex = 400;
2056
+ targetLayers.forEach((layer) => {
2057
+ const paneName = `zenit-layer-${layer.layerId}`;
2058
+ const pane = targetMap.getPane(paneName) ?? targetMap.createPane(paneName);
2059
+ const order = Number.isFinite(layer.displayOrder) ? layer.displayOrder : 0;
2060
+ pane.style.zIndex = String(baseZIndex + order);
2061
+ });
2062
+ },
2063
+ []
2064
+ );
2065
+ const handleMapReady = (0, import_react.useCallback)(
2066
+ (instance) => {
2067
+ setMapInstance(instance);
2068
+ onMapReady?.(instance);
2069
+ },
2070
+ [onMapReady]
2071
+ );
2072
+ (0, import_react.useEffect)(() => {
2073
+ if (!mapInstance) {
2074
+ return;
2075
+ }
2076
+ if (orderedLayers.length === 0) {
2077
+ return;
2078
+ }
2079
+ const layerTargets = orderedLayers.map((layer) => ({
2080
+ layerId: layer.mapLayer.layerId,
2081
+ displayOrder: layer.displayOrder
2082
+ }));
2083
+ ensureLayerPanes(mapInstance, layerTargets);
2084
+ }, [mapInstance, orderedLayers, ensureLayerPanes]);
2085
+ const overlayOnEachFeature = (0, import_react.useMemo)(() => {
2086
+ return (feature, layer) => {
2087
+ const layerId = getFeatureLayerId(feature) ?? void 0;
2088
+ const geometryType = feature?.geometry?.type;
2089
+ const isPointFeature = geometryType === "Point" || geometryType === "MultiPoint" || layer instanceof import_leaflet.default.CircleMarker;
2090
+ const originalStyle = layer instanceof import_leaflet.default.Path ? {
2091
+ color: layer.options.color,
2092
+ weight: layer.options.weight,
2093
+ fillColor: layer.options.fillColor,
2094
+ opacity: layer.options.opacity,
2095
+ fillOpacity: layer.options.fillOpacity
2096
+ } : null;
2097
+ const originalRadius = layer instanceof import_leaflet.default.CircleMarker ? layer.getRadius() : null;
2098
+ if (featureInfoMode === "popup") {
2099
+ const content = buildFeaturePopupHtml(feature);
2100
+ if (content) {
2101
+ layer.bindPopup(content, { maxWidth: 320 });
2102
+ }
2103
+ }
2104
+ if (isPointFeature && layer.bindTooltip) {
2105
+ layer.bindTooltip("Click para ver detalle", {
2106
+ sticky: true,
2107
+ direction: "top",
2108
+ opacity: 0.9,
2109
+ className: "zenit-map-tooltip"
2110
+ });
2111
+ }
2112
+ layer.on("click", () => onFeatureClick?.(feature, layerId));
2113
+ layer.on("mouseover", () => {
2114
+ if (layer instanceof import_leaflet.default.Path && originalStyle) {
2115
+ layer.setStyle({
2116
+ ...originalStyle,
2117
+ weight: (originalStyle.weight ?? 2) + 1,
2118
+ opacity: Math.min(1, (originalStyle.opacity ?? 1) + 0.2),
2119
+ fillOpacity: Math.min(1, (originalStyle.fillOpacity ?? 0.8) + 0.1)
2120
+ });
2121
+ }
2122
+ if (layer instanceof import_leaflet.default.CircleMarker && typeof originalRadius === "number") {
2123
+ layer.setRadius(originalRadius + 1);
2124
+ }
2125
+ onFeatureHover?.(feature, layerId);
2126
+ });
2127
+ layer.on("mouseout", () => {
2128
+ if (layer instanceof import_leaflet.default.Path && originalStyle) {
2129
+ layer.setStyle(originalStyle);
2130
+ }
2131
+ if (layer instanceof import_leaflet.default.CircleMarker && typeof originalRadius === "number") {
2132
+ layer.setRadius(originalRadius);
2133
+ }
2134
+ });
2135
+ };
2136
+ }, [featureInfoMode, onFeatureClick, onFeatureHover]);
2137
+ const buildLayerStyle = (layerId, baseOpacity, feature, layerType) => {
2138
+ const style = resolveLayerStyle(layerId);
2139
+ const featureStyleOverrides = getFeatureStyleOverrides(feature);
2140
+ const resolvedStyle = featureStyleOverrides ? { ...style ?? {}, ...featureStyleOverrides } : style;
2141
+ const geometryType = feature?.geometry?.type;
2142
+ const resolvedLayerType = layerType ?? geometryType;
2143
+ const sanitizedBaseOpacity = clampOpacity3(baseOpacity);
2144
+ const normalizedStyleFill = typeof resolvedStyle?.fillOpacity === "number" ? clampOpacity3(resolvedStyle.fillOpacity) : 0.8;
2145
+ const effectiveOpacity = getEffectiveLayerOpacity(
2146
+ sanitizedBaseOpacity,
2147
+ currentZoom,
2148
+ resolvedLayerType,
2149
+ geometryType
2150
+ );
2151
+ const fillOpacity = clampOpacity3(effectiveOpacity * normalizedStyleFill);
2152
+ const strokeOpacity = clampOpacity3(Math.max(0.35, effectiveOpacity * 0.9));
2153
+ return {
2154
+ color: resolvedStyle?.color ?? resolvedStyle?.fillColor ?? "#2563eb",
2155
+ weight: resolvedStyle?.weight ?? 2,
2156
+ fillColor: resolvedStyle?.fillColor ?? resolvedStyle?.color ?? "#2563eb",
2157
+ opacity: strokeOpacity,
2158
+ fillOpacity
2159
+ };
2160
+ };
2161
+ const buildLabelIcon = (0, import_react.useCallback)((label, opacity, color) => {
2162
+ const size = 60;
2163
+ const innerSize = 44;
2164
+ const textStyles = getLabelTextStyles(color);
2165
+ const safeLabel = escapeHtml(label);
2166
+ const clampedOpacity = Math.min(1, Math.max(0.92, opacity));
2167
+ const innerBackground = withAlpha(color, 0.9);
2168
+ return import_leaflet.default.divIcon({
2169
+ className: "zenit-label-marker",
2170
+ iconSize: [size, size],
2171
+ iconAnchor: [size / 2, size / 2],
2172
+ html: `
2173
+ <div
2174
+ title="${safeLabel}"
2175
+ style="
2176
+ width:${size}px;
2177
+ height:${size}px;
2178
+ border-radius:9999px;
2179
+ background:rgba(255, 255, 255, 0.95);
2180
+ border:3px solid rgba(255, 255, 255, 1);
2181
+ display:flex;
2182
+ align-items:center;
2183
+ justify-content:center;
2184
+ opacity:${clampedOpacity};
2185
+ box-shadow:0 2px 6px rgba(0, 0, 0, 0.25);
2186
+ pointer-events:none;
2187
+ "
2188
+ >
2189
+ <div
2190
+ style="
2191
+ width:${innerSize}px;
2192
+ height:${innerSize}px;
2193
+ border-radius:9999px;
2194
+ background:${innerBackground};
2195
+ display:flex;
2196
+ align-items:center;
2197
+ justify-content:center;
2198
+ box-shadow:inset 0 0 0 1px rgba(15, 23, 42, 0.12);
2199
+ "
2200
+ >
2201
+ <span
2202
+ style="
2203
+ color:${textStyles.color};
2204
+ font-size:20px;
2205
+ font-weight:800;
2206
+ text-shadow:${textStyles.shadow};
2207
+ "
2208
+ >
2209
+ ${safeLabel}
2210
+ </span>
2211
+ </div>
2212
+ </div>
2213
+ `
2214
+ });
2215
+ }, []);
2216
+ (0, import_react.useImperativeHandle)(ref, () => ({
2217
+ setLayerOpacity: (layerId, opacity) => {
2218
+ upsertUiOverride(layerId, { overrideOpacity: opacity });
2219
+ },
2220
+ setLayerVisibility: (layerId, visible) => {
2221
+ upsertUiOverride(layerId, { overrideVisible: visible });
2222
+ },
2223
+ fitBounds: (bbox, options) => {
2224
+ if (!mapInstance) return;
2225
+ if (typeof bbox.minLat !== "number" || typeof bbox.minLon !== "number" || typeof bbox.maxLat !== "number" || typeof bbox.maxLon !== "number" || !Number.isFinite(bbox.minLat) || !Number.isFinite(bbox.minLon) || !Number.isFinite(bbox.maxLat) || !Number.isFinite(bbox.maxLon)) {
2226
+ console.warn("[ZenitMap.fitBounds] Invalid bbox: missing or non-finite coordinates", bbox);
2227
+ return;
2228
+ }
2229
+ const bounds = [
2230
+ [bbox.minLat, bbox.minLon],
2231
+ [bbox.maxLat, bbox.maxLon]
2232
+ ];
2233
+ const fitOptions = {
2234
+ padding: options?.padding ?? [12, 12],
2235
+ animate: options?.animate ?? true
2236
+ };
2237
+ mapInstance.fitBounds(bounds, fitOptions);
2238
+ },
2239
+ setView: (coordinates, zoom2) => {
2240
+ if (!mapInstance) return;
2241
+ mapInstance.setView([coordinates.lat, coordinates.lon], zoom2 ?? mapInstance.getZoom(), {
2242
+ animate: true
2243
+ });
2244
+ },
2245
+ getLayerSnapshot: () => {
2246
+ return effectiveStates.map((state) => ({
2247
+ layerId: state.layerId,
2248
+ visible: state.visible,
2249
+ opacity: state.opacity
2250
+ }));
2251
+ },
2252
+ restoreLayerSnapshot: (snapshot) => {
2253
+ const overrides = snapshot.map((s) => ({
2254
+ layerId: s.layerId,
2255
+ overrideVisible: s.visible,
2256
+ overrideOpacity: s.opacity
2257
+ }));
2258
+ setUiOverrides(overrides);
2259
+ },
2260
+ highlightFeature: (layerId, featureId) => {
2261
+ upsertUiOverride(layerId, { overrideVisible: true, overrideOpacity: 1 });
2262
+ },
2263
+ getMapInstance: () => mapInstance
2264
+ }), [effectiveStates, mapInstance]);
2265
+ if (loadingMap) {
2266
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { style: { padding: 16, height, width }, children: "Cargando mapa..." });
2267
+ }
2268
+ if (mapError) {
2269
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { style: { padding: 16, height, width, color: "red" }, children: [
2270
+ "Error al cargar mapa: ",
2271
+ mapError
2272
+ ] });
2273
+ }
2274
+ if (!map) {
2275
+ return null;
2276
+ }
2277
+ const handleZoomChange = (zoomValue) => {
2278
+ setCurrentZoom(zoomValue);
2279
+ onZoomChange?.(zoomValue);
2280
+ };
2281
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
2282
+ "div",
2283
+ {
2284
+ style: {
2285
+ display: "flex",
2286
+ height,
2287
+ width,
2288
+ border: "1px solid #e2e8f0",
2289
+ borderRadius: 4,
2290
+ overflow: "hidden",
2291
+ boxSizing: "border-box"
2292
+ },
2293
+ children: [
2294
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { style: { flex: 1, position: "relative" }, children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
2295
+ import_react_leaflet.MapContainer,
2296
+ {
2297
+ center,
2298
+ zoom,
2299
+ style: { height: "100%", width: "100%" },
2300
+ scrollWheelZoom: true,
2301
+ zoomControl: false,
2302
+ children: [
2303
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
2304
+ import_react_leaflet.TileLayer,
2305
+ {
2306
+ url: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
2307
+ attribution: "\xA9 OpenStreetMap contributors"
2308
+ }
2309
+ ),
2310
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_leaflet.ZoomControl, { position: "topright" }),
2311
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(MapInstanceBridge, { onReady: handleMapReady }),
2312
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(FitToBounds, { bbox: explicitZoomBBox ?? void 0 }),
2313
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AutoFitToBounds, { bbox: autoZoomBBox ?? void 0, enabled: !explicitZoomBBox }),
2314
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ZoomBasedOpacityHandler, { onZoomChange: handleZoomChange }),
2315
+ orderedLayers.map((layerState) => {
2316
+ const baseOpacity = layerState.effective?.baseOpacity ?? layerState.effective?.opacity ?? 1;
2317
+ const paneName = `zenit-layer-${layerState.mapLayer.layerId}`;
2318
+ const layerType = layerState.layer?.layerType ?? layerState.mapLayer.layerType ?? void 0;
2319
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
2320
+ import_react_leaflet.GeoJSON,
2321
+ {
2322
+ data: layerState.data,
2323
+ pane: mapInstance?.getPane(paneName) ? paneName : void 0,
2324
+ style: (feature) => buildLayerStyle(layerState.mapLayer.layerId, baseOpacity, feature, layerType),
2325
+ pointToLayer: (feature, latlng) => import_leaflet.default.circleMarker(latlng, {
2326
+ radius: isMobile ? 8 : 6,
2327
+ ...buildLayerStyle(layerState.mapLayer.layerId, baseOpacity, feature, layerType)
2328
+ }),
2329
+ onEachFeature: overlayOnEachFeature
2330
+ },
2331
+ layerState.mapLayer.layerId.toString()
2332
+ );
2333
+ }),
2334
+ overlayGeojson && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
2335
+ import_react_leaflet.GeoJSON,
2336
+ {
2337
+ data: overlayGeojson,
2338
+ style: overlayStyleFunction,
2339
+ onEachFeature: overlayOnEachFeature
2340
+ },
2341
+ "zenit-overlay-geojson"
2342
+ ),
2343
+ labelMarkers.map((marker) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
2344
+ import_react_leaflet.Marker,
2345
+ {
2346
+ position: marker.position,
2347
+ icon: buildLabelIcon(marker.label, marker.opacity, marker.color),
2348
+ interactive: false
2349
+ },
2350
+ marker.key
2351
+ ))
2352
+ ]
2353
+ },
2354
+ String(mapId)
2355
+ ) }),
2356
+ showLayerPanel && decoratedLayers.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
2357
+ "div",
2358
+ {
2359
+ style: {
2360
+ width: 260,
2361
+ borderLeft: "1px solid #e2e8f0",
2362
+ padding: "12px 16px",
2363
+ background: "#fafafa",
2364
+ fontFamily: 'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
2365
+ fontSize: 14,
2366
+ overflowY: "auto"
2367
+ },
2368
+ children: [
2369
+ overlayGeojson && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
2370
+ "div",
2371
+ {
2372
+ style: {
2373
+ border: "1px solid #bfdbfe",
2374
+ background: "#eff6ff",
2375
+ color: "#1e40af",
2376
+ padding: "8px 10px",
2377
+ borderRadius: 8,
2378
+ marginBottom: 12
2379
+ },
2380
+ children: [
2381
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { style: { fontWeight: 600, marginBottom: 4 }, children: "Overlay activo" }),
2382
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { style: { fontSize: 13 }, children: [
2383
+ "GeoJSON externo con ",
2384
+ (overlayGeojson.features?.length ?? 0).toLocaleString(),
2385
+ " elementos."
2386
+ ] })
2387
+ ]
2388
+ }
2389
+ ),
2390
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { style: { fontWeight: 600, marginBottom: 12 }, children: "Capas" }),
2391
+ decoratedLayers.map((layerState) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
2392
+ "div",
2393
+ {
2394
+ style: { borderBottom: "1px solid #e5e7eb", paddingBottom: 10, marginBottom: 10 },
2395
+ children: [
2396
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("label", { style: { display: "flex", gap: 8, alignItems: "center" }, children: [
2397
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
2398
+ "input",
2399
+ {
2400
+ type: "checkbox",
2401
+ checked: layerState.effective?.visible ?? false,
2402
+ onChange: (e) => {
2403
+ const visible = e.target.checked;
2404
+ upsertUiOverride(layerState.mapLayer.layerId, { overrideVisible: visible });
2405
+ }
2406
+ }
2407
+ ),
2408
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: layerState.layer?.name ?? `Capa ${layerState.mapLayer.layerId}` })
2409
+ ] }),
2410
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { style: { marginTop: 8 }, children: [
2411
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { style: { display: "flex", justifyContent: "space-between", marginBottom: 4 }, children: [
2412
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { style: { color: "#4a5568" }, children: "Opacidad" }),
2413
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { children: [
2414
+ Math.round((layerState.effective?.opacity ?? 1) * 100),
2415
+ "%"
2416
+ ] })
2417
+ ] }),
2418
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
2419
+ "input",
2420
+ {
2421
+ type: "range",
2422
+ min: 0,
2423
+ max: 1,
2424
+ step: 0.05,
2425
+ value: layerState.effective?.opacity ?? 1,
2426
+ onChange: (e) => {
2427
+ const value = Number(e.target.value);
2428
+ updateOpacityFromUi(layerState.mapLayer.layerId, value);
2429
+ },
2430
+ style: { width: "100%" }
2431
+ }
2432
+ )
2433
+ ] })
2434
+ ]
2435
+ },
2436
+ layerState.mapLayer.layerId.toString()
2437
+ ))
2438
+ ]
2439
+ }
2440
+ )
2441
+ ]
2442
+ }
2443
+ );
2444
+ });
2445
+ ZenitMap.displayName = "ZenitMap";
2446
+
2447
+ // src/react/ZenitLayerManager.tsx
2448
+ var import_react2 = __toESM(require("react"));
2449
+
2450
+ // src/react/icons.tsx
2451
+ var import_lucide_react = require("lucide-react");
2452
+
2453
+ // src/react/ZenitLayerManager.tsx
2454
+ var import_jsx_runtime2 = require("react/jsx-runtime");
2455
+ var FLOAT_TOLERANCE = 1e-3;
2456
+ function areEffectiveStatesEqual(a, b) {
2457
+ if (a.length !== b.length) return false;
2458
+ return a.every((state, index) => {
2459
+ const other = b[index];
2460
+ if (!other) return false;
2461
+ const opacityDiff = Math.abs((state.opacity ?? 1) - (other.opacity ?? 1));
2462
+ return String(state.layerId) === String(other.layerId) && (state.visible ?? false) === (other.visible ?? false) && opacityDiff <= FLOAT_TOLERANCE;
2463
+ });
2464
+ }
2465
+ function getLayerColor2(style) {
2466
+ if (!style) return "#94a3b8";
2467
+ return style.fillColor ?? style.color ?? "#94a3b8";
2468
+ }
2469
+ function resolveDisplayOrder(value) {
2470
+ if (typeof value === "number" && Number.isFinite(value)) return value;
2471
+ if (typeof value === "string") {
2472
+ const parsed = Number.parseFloat(value);
2473
+ if (Number.isFinite(parsed)) return parsed;
2474
+ }
2475
+ return 0;
2476
+ }
2477
+ var ZenitLayerManager = ({
2478
+ client,
2479
+ mapId,
2480
+ side = "right",
2481
+ className,
2482
+ style,
2483
+ height,
2484
+ layerStates,
2485
+ onLayerStatesChange,
2486
+ mapZoom,
2487
+ autoOpacityOnZoom = false,
2488
+ autoOpacityConfig,
2489
+ showUploadTab = true,
2490
+ showLayerVisibilityIcon = true,
2491
+ layerFeatureCounts,
2492
+ mapLayers
2493
+ }) => {
2494
+ const [map, setMap] = (0, import_react2.useState)(null);
2495
+ const [loadingMap, setLoadingMap] = (0, import_react2.useState)(false);
2496
+ const [mapError, setMapError] = (0, import_react2.useState)(null);
2497
+ const [layers, setLayers] = (0, import_react2.useState)([]);
2498
+ const [activeTab, setActiveTab] = (0, import_react2.useState)("layers");
2499
+ const [panelVisible, setPanelVisible] = (0, import_react2.useState)(true);
2500
+ const lastEmittedStatesRef = (0, import_react2.useRef)(null);
2501
+ const isControlled = Array.isArray(layerStates) && typeof onLayerStatesChange === "function";
2502
+ const baseStates = (0, import_react2.useMemo)(
2503
+ () => initLayerStates(
2504
+ layers.map((entry) => ({
2505
+ ...entry.mapLayer,
2506
+ layerId: entry.mapLayer.layerId,
2507
+ isVisible: entry.visible,
2508
+ opacity: entry.opacity
2509
+ }))
2510
+ ),
2511
+ [layers]
2512
+ );
2513
+ const overrideStates = (0, import_react2.useMemo)(
2514
+ () => layers.map(
2515
+ (entry) => ({
2516
+ layerId: entry.mapLayer.layerId,
2517
+ overrideVisible: entry.visible,
2518
+ overrideOpacity: entry.opacity
2519
+ })
2520
+ ),
2521
+ [layers]
2522
+ );
2523
+ const effectiveStates = (0, import_react2.useMemo)(
2524
+ () => layerStates ?? applyLayerOverrides(baseStates, overrideStates),
2525
+ [baseStates, layerStates, overrideStates]
2526
+ );
2527
+ const layerMetaIndex = (0, import_react2.useMemo)(() => {
2528
+ const index = /* @__PURE__ */ new Map();
2529
+ mapLayers?.forEach((entry) => {
2530
+ const key = String(entry.layerId);
2531
+ index.set(key, { layerType: entry.layerType ?? void 0, geometryType: entry.geometryType ?? void 0 });
2532
+ });
2533
+ map?.mapLayers?.forEach((entry) => {
2534
+ const key = String(entry.layerId);
2535
+ if (!index.has(key)) {
2536
+ index.set(key, { layerType: entry.layerType ?? void 0, geometryType: entry.geometryType ?? void 0 });
2537
+ }
2538
+ });
2539
+ return index;
2540
+ }, [map, mapLayers]);
2541
+ const resolveUserOpacity = import_react2.default.useCallback((state) => {
2542
+ if (typeof state.overrideOpacity === "number") return state.overrideOpacity;
2543
+ if (typeof state.overrideOpacity === "string") {
2544
+ const parsed = Number.parseFloat(state.overrideOpacity);
2545
+ if (Number.isFinite(parsed)) return parsed;
2546
+ }
2547
+ return state.opacity ?? 1;
2548
+ }, []);
2549
+ const resolveEffectiveOpacity = import_react2.default.useCallback(
2550
+ (layerId, userOpacity) => {
2551
+ if (!autoOpacityOnZoom || typeof mapZoom !== "number") {
2552
+ return userOpacity;
2553
+ }
2554
+ const meta = layerMetaIndex.get(String(layerId));
2555
+ return getEffectiveLayerOpacity(
2556
+ userOpacity,
2557
+ mapZoom,
2558
+ meta?.layerType,
2559
+ meta?.geometryType,
2560
+ autoOpacityConfig
2561
+ );
2562
+ },
2563
+ [autoOpacityConfig, autoOpacityOnZoom, layerMetaIndex, mapZoom]
2564
+ );
2565
+ const effectiveStatesWithZoom = (0, import_react2.useMemo)(() => {
2566
+ if (!autoOpacityOnZoom || typeof mapZoom !== "number") {
2567
+ return effectiveStates;
2568
+ }
2569
+ return effectiveStates.map((state) => {
2570
+ const userOpacity = resolveUserOpacity(state);
2571
+ const adjustedOpacity = resolveEffectiveOpacity(state.layerId, userOpacity);
2572
+ return {
2573
+ ...state,
2574
+ opacity: adjustedOpacity,
2575
+ overrideOpacity: userOpacity
2576
+ };
2577
+ });
2578
+ }, [autoOpacityOnZoom, effectiveStates, mapZoom, resolveEffectiveOpacity, resolveUserOpacity]);
2579
+ (0, import_react2.useEffect)(() => {
2580
+ let cancelled = false;
2581
+ setLoadingMap(true);
2582
+ setMapError(null);
2583
+ setLayers([]);
2584
+ client.maps.getMap(mapId, true).then((mapResponse) => {
2585
+ if (cancelled) return;
2586
+ const extractedMap = extractMapDto(mapResponse);
2587
+ const resolvedMap = extractedMap ? normalizeMapCenter(extractedMap) : null;
2588
+ setMap(resolvedMap);
2589
+ const normalizedLayers = normalizeMapLayers(resolvedMap);
2590
+ setLayers(
2591
+ normalizedLayers.map((entry, index) => ({
2592
+ mapLayer: { ...entry.mapLayer, layerId: entry.layerId },
2593
+ layer: entry.layer,
2594
+ visible: entry.isVisible,
2595
+ opacity: entry.opacity,
2596
+ displayOrder: entry.displayOrder,
2597
+ initialIndex: index
2598
+ }))
2599
+ );
2600
+ }).catch((err) => {
2601
+ if (cancelled) return;
2602
+ const message = err instanceof Error ? err.message : "No se pudo cargar el mapa";
2603
+ setMapError(message);
2604
+ }).finally(() => {
2605
+ if (!cancelled) setLoadingMap(false);
2606
+ });
2607
+ return () => {
2608
+ cancelled = true;
2609
+ };
2610
+ }, [client.maps, mapId]);
2611
+ (0, import_react2.useEffect)(() => {
2612
+ if (!showUploadTab && activeTab === "upload") {
2613
+ setActiveTab("layers");
2614
+ }
2615
+ }, [activeTab, showUploadTab]);
2616
+ (0, import_react2.useEffect)(() => {
2617
+ if (isControlled) return;
2618
+ if (!onLayerStatesChange) return;
2619
+ const emitStates = autoOpacityOnZoom && typeof mapZoom === "number" ? effectiveStatesWithZoom : effectiveStates;
2620
+ const previous = lastEmittedStatesRef.current;
2621
+ if (previous && areEffectiveStatesEqual(previous, emitStates)) {
2622
+ return;
2623
+ }
2624
+ lastEmittedStatesRef.current = emitStates;
2625
+ onLayerStatesChange(emitStates);
2626
+ }, [
2627
+ autoOpacityOnZoom,
2628
+ effectiveStates,
2629
+ effectiveStatesWithZoom,
2630
+ isControlled,
2631
+ mapZoom,
2632
+ onLayerStatesChange
2633
+ ]);
2634
+ const updateLayerVisible = import_react2.default.useCallback(
2635
+ (layerId, visible) => {
2636
+ if (!onLayerStatesChange) return;
2637
+ const next = effectiveStates.map(
2638
+ (state) => state.layerId === layerId ? { ...state, visible, overrideVisible: visible } : state
2639
+ );
2640
+ onLayerStatesChange(next);
2641
+ },
2642
+ [effectiveStates, onLayerStatesChange]
2643
+ );
2644
+ const updateLayerOpacity = import_react2.default.useCallback(
2645
+ (layerId, opacity) => {
2646
+ if (!onLayerStatesChange) return;
2647
+ const adjustedOpacity = resolveEffectiveOpacity(layerId, opacity);
2648
+ const next = effectiveStates.map(
2649
+ (state) => state.layerId === layerId ? { ...state, opacity: adjustedOpacity, overrideOpacity: opacity } : state
2650
+ );
2651
+ onLayerStatesChange(next);
2652
+ },
2653
+ [effectiveStates, onLayerStatesChange, resolveEffectiveOpacity]
2654
+ );
2655
+ const resolveFeatureCount = import_react2.default.useCallback(
2656
+ (layerId, layer) => {
2657
+ const resolvedFeatureCount = layerFeatureCounts?.[layerId] ?? layerFeatureCounts?.[String(layerId)];
2658
+ if (typeof resolvedFeatureCount === "number") return resolvedFeatureCount;
2659
+ const featureCount = layer?.featuresCount ?? layer?.featureCount ?? layer?.totalFeatures;
2660
+ return typeof featureCount === "number" ? featureCount : null;
2661
+ },
2662
+ [layerFeatureCounts]
2663
+ );
2664
+ const decoratedLayers = (0, import_react2.useMemo)(() => {
2665
+ return layers.map((entry) => ({
2666
+ ...entry,
2667
+ effective: effectiveStates.find((state) => state.layerId === entry.mapLayer.layerId),
2668
+ featureCount: resolveFeatureCount(entry.mapLayer.layerId, entry.layer),
2669
+ layerName: entry.layer?.name ?? entry.mapLayer.name ?? `Capa ${entry.mapLayer.layerId}`
2670
+ })).sort((a, b) => {
2671
+ const aOrder = resolveDisplayOrder(
2672
+ a.displayOrder ?? a.mapLayer.displayOrder ?? a.mapLayer.order
2673
+ );
2674
+ const bOrder = resolveDisplayOrder(
2675
+ b.displayOrder ?? b.mapLayer.displayOrder ?? b.mapLayer.order
2676
+ );
2677
+ const aHasOrder = a.displayOrder ?? a.mapLayer.displayOrder ?? a.mapLayer.order ?? null;
2678
+ const bHasOrder = b.displayOrder ?? b.mapLayer.displayOrder ?? b.mapLayer.order ?? null;
2679
+ if (aHasOrder !== null && bHasOrder !== null) {
2680
+ const orderCompare = aOrder - bOrder;
2681
+ if (orderCompare !== 0) return orderCompare;
2682
+ }
2683
+ const aInitial = a.initialIndex ?? 0;
2684
+ const bInitial = b.initialIndex ?? 0;
2685
+ if (aInitial !== bInitial) return aInitial - bInitial;
2686
+ const aName = a.layerName ?? String(a.mapLayer.layerId);
2687
+ const bName = b.layerName ?? String(b.mapLayer.layerId);
2688
+ const nameCompare = aName.localeCompare(bName, void 0, { sensitivity: "base" });
2689
+ if (nameCompare !== 0) return nameCompare;
2690
+ return String(a.mapLayer.layerId).localeCompare(String(b.mapLayer.layerId));
2691
+ });
2692
+ }, [effectiveStates, layers, resolveFeatureCount]);
2693
+ const resolveLayerStyle = import_react2.default.useCallback(
2694
+ (layerId) => {
2695
+ const layerKey = String(layerId);
2696
+ const fromProp = mapLayers?.find((entry) => String(entry.layerId) === layerKey)?.style;
2697
+ if (fromProp) return fromProp;
2698
+ const fromMapDto = map?.mapLayers?.find((entry) => String(entry.layerId) === layerKey);
2699
+ if (fromMapDto?.layer) {
2700
+ const layer = fromMapDto.layer;
2701
+ if (layer.style) return layer.style;
2702
+ }
2703
+ return void 0;
2704
+ },
2705
+ [map, mapLayers]
2706
+ );
2707
+ const panelStyle = {
2708
+ width: 360,
2709
+ borderLeft: side === "right" ? "1px solid #e2e8f0" : void 0,
2710
+ borderRight: side === "left" ? "1px solid #e2e8f0" : void 0,
2711
+ background: "#f1f5f9",
2712
+ fontFamily: 'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
2713
+ fontSize: 14,
2714
+ boxSizing: "border-box",
2715
+ height: height ?? "100%",
2716
+ display: "flex",
2717
+ flexDirection: "column",
2718
+ boxShadow: "0 12px 28px rgba(15, 23, 42, 0.08)",
2719
+ ...style,
2720
+ ...height ? { height } : {}
2721
+ };
2722
+ if (loadingMap) {
2723
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { className, style: panelStyle, children: "Cargando capas\u2026" });
2724
+ }
2725
+ if (mapError) {
2726
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className, style: { ...panelStyle, color: "#c53030" }, children: [
2727
+ "Error al cargar mapa: ",
2728
+ mapError
2729
+ ] });
2730
+ }
2731
+ if (!map) {
2732
+ return null;
2733
+ }
2734
+ const headerStyle = {
2735
+ padding: "14px 16px",
2736
+ borderBottom: "1px solid #e2e8f0",
2737
+ background: "#fff",
2738
+ position: "sticky",
2739
+ top: 0,
2740
+ zIndex: 2,
2741
+ boxShadow: "0 1px 0 rgba(148, 163, 184, 0.25)"
2742
+ };
2743
+ const renderLayerCards = () => {
2744
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { style: { display: "flex", flexDirection: "column", gap: 12 }, children: decoratedLayers.map((layerState) => {
2745
+ const layerId = layerState.mapLayer.layerId;
2746
+ const layerName = layerState.layerName ?? `Capa ${layerId}`;
2747
+ const visible = layerState.effective?.visible ?? false;
2748
+ const userOpacity = layerState.effective ? resolveUserOpacity(layerState.effective) : 1;
2749
+ const featureCount = layerState.featureCount;
2750
+ const layerColor = getLayerColor2(resolveLayerStyle(layerId));
2751
+ const muted = !visible;
2752
+ const opacityPercent = Math.round(userOpacity * 100);
2753
+ const sliderBackground = `linear-gradient(to right, ${layerColor} 0%, ${layerColor} ${opacityPercent}%, #e5e7eb ${opacityPercent}%, #e5e7eb 100%)`;
2754
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
2755
+ "div",
2756
+ {
2757
+ className: `zlm-card${muted ? " is-muted" : ""}`,
2758
+ style: {
2759
+ border: "1px solid #e2e8f0",
2760
+ borderRadius: 12,
2761
+ padding: 12,
2762
+ background: "#fff",
2763
+ display: "flex",
2764
+ flexDirection: "column",
2765
+ gap: 10,
2766
+ width: "100%"
2767
+ },
2768
+ children: [
2769
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { style: { display: "flex", justifyContent: "space-between", gap: 12 }, children: [
2770
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { style: { display: "flex", gap: 10, alignItems: "flex-start", minWidth: 0, flex: 1 }, children: [
2771
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2772
+ "div",
2773
+ {
2774
+ style: {
2775
+ width: 14,
2776
+ height: 14,
2777
+ borderRadius: "50%",
2778
+ backgroundColor: layerColor,
2779
+ border: "2px solid #e2e8f0",
2780
+ flexShrink: 0,
2781
+ marginTop: 4
2782
+ },
2783
+ title: "Color de la capa"
2784
+ }
2785
+ ),
2786
+ showLayerVisibilityIcon && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2787
+ "button",
2788
+ {
2789
+ type: "button",
2790
+ className: `zlm-icon-button${visible ? " is-active" : ""}`,
2791
+ onClick: () => isControlled ? updateLayerVisible(layerId, !visible) : setLayers(
2792
+ (prev) => prev.map(
2793
+ (entry) => entry.mapLayer.layerId === layerId ? { ...entry, visible: !visible } : entry
2794
+ )
2795
+ ),
2796
+ "aria-label": visible ? "Ocultar capa" : "Mostrar capa",
2797
+ children: visible ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_lucide_react.Eye, { size: 16 }) : /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_lucide_react.EyeOff, { size: 16 })
2798
+ }
2799
+ ),
2800
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { style: { minWidth: 0, flex: 1 }, children: [
2801
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2802
+ "div",
2803
+ {
2804
+ className: "zlm-layer-name",
2805
+ style: {
2806
+ fontWeight: 700,
2807
+ display: "-webkit-box",
2808
+ WebkitLineClamp: 2,
2809
+ WebkitBoxOrient: "vertical",
2810
+ overflow: "hidden",
2811
+ overflowWrap: "anywhere",
2812
+ lineHeight: 1.2,
2813
+ color: muted ? "#64748b" : "#0f172a"
2814
+ },
2815
+ title: layerName,
2816
+ children: layerName
2817
+ }
2818
+ ),
2819
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { style: { color: muted ? "#94a3b8" : "#64748b", fontSize: 12 }, children: [
2820
+ "ID ",
2821
+ layerId
2822
+ ] })
2823
+ ] })
2824
+ ] }),
2825
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { style: { display: "flex", alignItems: "flex-start", gap: 6, flexShrink: 0 }, children: typeof featureCount === "number" && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("span", { className: "zlm-badge", children: [
2826
+ featureCount.toLocaleString(),
2827
+ " features"
2828
+ ] }) })
2829
+ ] }),
2830
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { style: { display: "flex", gap: 10, alignItems: "center" }, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { style: { flex: 1 }, children: [
2831
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { style: { display: "flex", justifyContent: "space-between", marginBottom: 6, color: "#64748b", fontSize: 12 }, children: [
2832
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { children: "Opacidad" }),
2833
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("span", { children: [
2834
+ opacityPercent,
2835
+ "%"
2836
+ ] })
2837
+ ] }),
2838
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2839
+ "input",
2840
+ {
2841
+ className: "zlm-range",
2842
+ type: "range",
2843
+ min: 0,
2844
+ max: 1,
2845
+ step: 0.05,
2846
+ value: userOpacity,
2847
+ style: {
2848
+ width: "100%",
2849
+ accentColor: layerColor,
2850
+ background: sliderBackground,
2851
+ height: 6,
2852
+ borderRadius: 999
2853
+ },
2854
+ onChange: (e) => {
2855
+ const value = Number(e.target.value);
2856
+ if (isControlled) {
2857
+ updateLayerOpacity(layerId, value);
2858
+ return;
2859
+ }
2860
+ setLayers(
2861
+ (prev) => prev.map(
2862
+ (entry) => entry.mapLayer.layerId === layerId ? { ...entry, opacity: value } : entry
2863
+ )
2864
+ );
2865
+ },
2866
+ "aria-label": `Opacidad de la capa ${layerName}`
2867
+ }
2868
+ )
2869
+ ] }) })
2870
+ ]
2871
+ },
2872
+ layerId.toString()
2873
+ );
2874
+ }) });
2875
+ };
2876
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: ["zenit-layer-manager", className].filter(Boolean).join(" "), style: panelStyle, children: [
2877
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("style", { children: `
2878
+ .zenit-layer-manager .zlm-card {
2879
+ transition: box-shadow 0.2s ease, transform 0.2s ease, opacity 0.2s ease;
2880
+ box-shadow: 0 6px 16px rgba(15, 23, 42, 0.08);
2881
+ }
2882
+ .zenit-layer-manager .zlm-card.is-muted {
2883
+ opacity: 0.7;
2884
+ }
2885
+ .zenit-layer-manager .zlm-badge {
2886
+ display: inline-flex;
2887
+ align-items: center;
2888
+ gap: 4px;
2889
+ margin-top: 6px;
2890
+ padding: 2px 8px;
2891
+ border-radius: 999px;
2892
+ background: #f1f5f9;
2893
+ color: #475569;
2894
+ font-size: 11px;
2895
+ font-weight: 600;
2896
+ }
2897
+ .zenit-layer-manager .zlm-icon-button {
2898
+ border: 1px solid #e2e8f0;
2899
+ background: #f8fafc;
2900
+ color: #475569;
2901
+ border-radius: 8px;
2902
+ width: 34px;
2903
+ height: 34px;
2904
+ display: inline-flex;
2905
+ align-items: center;
2906
+ justify-content: center;
2907
+ cursor: pointer;
2908
+ transition: all 0.15s ease;
2909
+ }
2910
+ .zenit-layer-manager .zlm-icon-button.is-active {
2911
+ background: #0f172a;
2912
+ color: #fff;
2913
+ border-color: #0f172a;
2914
+ }
2915
+ .zenit-layer-manager .zlm-icon-button:hover {
2916
+ box-shadow: 0 4px 10px rgba(15, 23, 42, 0.12);
2917
+ }
2918
+ .zenit-layer-manager .zlm-icon-button:focus-visible {
2919
+ outline: 2px solid #60a5fa;
2920
+ outline-offset: 2px;
2921
+ }
2922
+ .zenit-layer-manager .zlm-range {
2923
+ width: 100%;
2924
+ accent-color: #0f172a;
2925
+ }
2926
+ .zenit-layer-manager .zlm-tab {
2927
+ flex: 1;
2928
+ padding: 8px 12px;
2929
+ border: none;
2930
+ background: transparent;
2931
+ color: #475569;
2932
+ font-weight: 600;
2933
+ cursor: pointer;
2934
+ display: inline-flex;
2935
+ align-items: center;
2936
+ justify-content: center;
2937
+ gap: 6px;
2938
+ font-size: 13px;
2939
+ }
2940
+ .zenit-layer-manager .zlm-tab.is-active {
2941
+ background: #fff;
2942
+ color: #0f172a;
2943
+ box-shadow: 0 4px 10px rgba(15, 23, 42, 0.08);
2944
+ border-radius: 10px;
2945
+ }
2946
+ .zenit-layer-manager .zlm-tab:focus-visible {
2947
+ outline: 2px solid #60a5fa;
2948
+ outline-offset: 2px;
2949
+ }
2950
+ .zenit-layer-manager .zlm-panel-toggle {
2951
+ border: 1px solid #e2e8f0;
2952
+ background: #fff;
2953
+ color: #0f172a;
2954
+ border-radius: 10px;
2955
+ padding: 6px 10px;
2956
+ display: inline-flex;
2957
+ align-items: center;
2958
+ gap: 6px;
2959
+ font-size: 12px;
2960
+ font-weight: 600;
2961
+ cursor: pointer;
2962
+ transition: all 0.15s ease;
2963
+ }
2964
+ .zenit-layer-manager .zlm-panel-toggle:hover {
2965
+ box-shadow: 0 4px 10px rgba(15, 23, 42, 0.12);
2966
+ }
2967
+ .zenit-layer-manager .zlm-panel-toggle:focus-visible {
2968
+ outline: 2px solid #60a5fa;
2969
+ outline-offset: 2px;
2970
+ }
2971
+ ` }),
2972
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { style: headerStyle, children: [
2973
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "center" }, children: [
2974
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { children: [
2975
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { style: { fontWeight: 800, fontSize: 16, color: "#0f172a" }, children: "Gesti\xF3n de Capas" }),
2976
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { style: { color: "#64748b", fontSize: 12 }, children: [
2977
+ "Mapa #",
2978
+ map.id
2979
+ ] })
2980
+ ] }),
2981
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
2982
+ "button",
2983
+ {
2984
+ type: "button",
2985
+ onClick: () => setPanelVisible((prev) => !prev),
2986
+ className: "zlm-panel-toggle",
2987
+ "aria-label": panelVisible ? "Ocultar panel de capas" : "Mostrar panel de capas",
2988
+ children: [
2989
+ panelVisible ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_lucide_react.Eye, { size: 16 }) : /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_lucide_react.EyeOff, { size: 16 }),
2990
+ panelVisible ? "Ocultar" : "Mostrar"
2991
+ ]
2992
+ }
2993
+ )
2994
+ ] }),
2995
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
2996
+ "div",
2997
+ {
2998
+ style: {
2999
+ display: "flex",
3000
+ gap: 6,
3001
+ marginTop: 12,
3002
+ padding: 4,
3003
+ border: "1px solid #e2e8f0",
3004
+ borderRadius: 12,
3005
+ background: "#f1f5f9"
3006
+ },
3007
+ children: [
3008
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
3009
+ "button",
3010
+ {
3011
+ type: "button",
3012
+ className: `zlm-tab${activeTab === "layers" ? " is-active" : ""}`,
3013
+ onClick: () => setActiveTab("layers"),
3014
+ children: [
3015
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_lucide_react.Layers, { size: 16 }),
3016
+ "Capas"
3017
+ ]
3018
+ }
3019
+ ),
3020
+ showUploadTab && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
3021
+ "button",
3022
+ {
3023
+ type: "button",
3024
+ className: `zlm-tab${activeTab === "upload" ? " is-active" : ""}`,
3025
+ onClick: () => setActiveTab("upload"),
3026
+ children: [
3027
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_lucide_react.Upload, { size: 16 }),
3028
+ "Subir"
3029
+ ]
3030
+ }
3031
+ )
3032
+ ]
3033
+ }
3034
+ )
3035
+ ] }),
3036
+ panelVisible && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { style: { padding: "12px 10px 18px", overflowY: "auto", flex: 1, minHeight: 0 }, children: [
3037
+ activeTab === "layers" && renderLayerCards(),
3038
+ showUploadTab && activeTab === "upload" && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { style: { color: "#475569", fontSize: 13 }, children: "Pr\xF3ximamente podr\xE1s subir capas desde este panel." })
3039
+ ] })
3040
+ ] });
3041
+ };
3042
+
3043
+ // src/react/ZenitFeatureFilterPanel.tsx
3044
+ var import_jsx_runtime3 = require("react/jsx-runtime");
3045
+ var ZenitFeatureFilterPanel = ({
3046
+ title = "Filtros",
3047
+ description,
3048
+ className,
3049
+ style,
3050
+ children
3051
+ }) => {
3052
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
3053
+ "section",
3054
+ {
3055
+ className,
3056
+ style: {
3057
+ border: "1px solid #e2e8f0",
3058
+ borderRadius: 12,
3059
+ padding: 16,
3060
+ background: "#fff",
3061
+ fontFamily: 'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
3062
+ ...style
3063
+ },
3064
+ children: [
3065
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("header", { style: { marginBottom: 12 }, children: [
3066
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("h3", { style: { margin: 0, fontSize: 16 }, children: title }),
3067
+ description && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("p", { style: { margin: "6px 0 0", color: "#475569", fontSize: 13 }, children: description })
3068
+ ] }),
3069
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { children })
3070
+ ]
3071
+ }
3072
+ );
3073
+ };
3074
+
3075
+ // src/react/ai/FloatingChatBox.tsx
3076
+ var import_react4 = require("react");
3077
+ var import_react_dom = require("react-dom");
3078
+
3079
+ // src/react/hooks/use-chat.ts
3080
+ var import_react3 = require("react");
3081
+ var useSendMessage = (config) => {
3082
+ const [isLoading, setIsLoading] = (0, import_react3.useState)(false);
3083
+ const [error, setError] = (0, import_react3.useState)(null);
3084
+ const send = (0, import_react3.useCallback)(
3085
+ async (mapId, request, options) => {
3086
+ setIsLoading(true);
3087
+ setError(null);
3088
+ try {
3089
+ return await sendMessage(mapId, request, options, config);
3090
+ } catch (err) {
3091
+ setError(err);
3092
+ throw err;
3093
+ } finally {
3094
+ setIsLoading(false);
3095
+ }
3096
+ },
3097
+ [config]
3098
+ );
3099
+ return { sendMessage: send, isLoading, error };
3100
+ };
3101
+ var useSendMessageStream = (config) => {
3102
+ const [isStreaming, setIsStreaming] = (0, import_react3.useState)(false);
3103
+ const [streamingText, setStreamingText] = (0, import_react3.useState)("");
3104
+ const [completeResponse, setCompleteResponse] = (0, import_react3.useState)(null);
3105
+ const [error, setError] = (0, import_react3.useState)(null);
3106
+ const requestIdRef = (0, import_react3.useRef)(0);
3107
+ const reset = (0, import_react3.useCallback)(() => {
3108
+ setIsStreaming(false);
3109
+ setStreamingText("");
3110
+ setCompleteResponse(null);
3111
+ setError(null);
3112
+ }, []);
3113
+ const send = (0, import_react3.useCallback)(
3114
+ async (mapId, request, options) => {
3115
+ const requestId = requestIdRef.current + 1;
3116
+ requestIdRef.current = requestId;
3117
+ setIsStreaming(true);
3118
+ setStreamingText("");
3119
+ setCompleteResponse(null);
3120
+ setError(null);
3121
+ try {
3122
+ const response = await sendMessageStream(
3123
+ mapId,
3124
+ request,
3125
+ {
3126
+ onChunk: (_chunk, aggregated) => {
3127
+ if (requestIdRef.current !== requestId) return;
3128
+ setStreamingText(aggregated);
3129
+ },
3130
+ onError: (err) => {
3131
+ if (requestIdRef.current !== requestId) return;
3132
+ setError(err);
3133
+ },
3134
+ onComplete: (finalResponse) => {
3135
+ if (requestIdRef.current !== requestId) return;
3136
+ setCompleteResponse(finalResponse);
3137
+ }
3138
+ },
3139
+ options,
3140
+ config
3141
+ );
3142
+ return response;
3143
+ } catch (err) {
3144
+ setError(err);
3145
+ throw err;
3146
+ } finally {
3147
+ if (requestIdRef.current === requestId) {
3148
+ setIsStreaming(false);
3149
+ }
3150
+ }
3151
+ },
3152
+ [config]
3153
+ );
3154
+ return {
3155
+ sendMessage: send,
3156
+ isStreaming,
3157
+ streamingText,
3158
+ completeResponse,
3159
+ error,
3160
+ reset
3161
+ };
3162
+ };
3163
+
3164
+ // src/react/components/MarkdownRenderer.tsx
3165
+ var import_react_markdown = __toESM(require("react-markdown"));
3166
+ var import_remark_gfm = __toESM(require("remark-gfm"));
3167
+ var import_jsx_runtime4 = require("react/jsx-runtime");
3168
+ function normalizeAssistantMarkdown(text) {
3169
+ if (!text || typeof text !== "string") return "";
3170
+ let normalized = text;
3171
+ normalized = normalized.replace(/\r\n/g, "\n");
3172
+ normalized = normalized.replace(/^\s*#{1,6}\s*$/gm, "");
3173
+ normalized = normalized.replace(/\n{3,}/g, "\n\n");
3174
+ normalized = normalized.split("\n").map((line) => line.trimEnd()).join("\n");
3175
+ normalized = normalized.trim();
3176
+ return normalized;
3177
+ }
3178
+ var MarkdownRenderer = ({ content, className }) => {
3179
+ const normalizedContent = normalizeAssistantMarkdown(content);
3180
+ if (!normalizedContent) {
3181
+ return null;
3182
+ }
3183
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className, style: { wordBreak: "break-word" }, children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
3184
+ import_react_markdown.default,
3185
+ {
3186
+ remarkPlugins: [import_remark_gfm.default],
3187
+ components: {
3188
+ // Headings with proper spacing
3189
+ h1: ({ children, ...props }) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("h1", { style: { fontSize: "1.5em", fontWeight: 700, marginTop: "1em", marginBottom: "0.5em" }, ...props, children }),
3190
+ h2: ({ children, ...props }) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("h2", { style: { fontSize: "1.3em", fontWeight: 700, marginTop: "0.9em", marginBottom: "0.45em" }, ...props, children }),
3191
+ h3: ({ children, ...props }) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("h3", { style: { fontSize: "1.15em", fontWeight: 600, marginTop: "0.75em", marginBottom: "0.4em" }, ...props, children }),
3192
+ h4: ({ children, ...props }) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("h4", { style: { fontSize: "1.05em", fontWeight: 600, marginTop: "0.6em", marginBottom: "0.35em" }, ...props, children }),
3193
+ h5: ({ children, ...props }) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("h5", { style: { fontSize: "1em", fontWeight: 600, marginTop: "0.5em", marginBottom: "0.3em" }, ...props, children }),
3194
+ h6: ({ children, ...props }) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("h6", { style: { fontSize: "0.95em", fontWeight: 600, marginTop: "0.5em", marginBottom: "0.3em" }, ...props, children }),
3195
+ // Paragraphs with comfortable line height
3196
+ p: ({ children, ...props }) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("p", { style: { marginTop: "0.5em", marginBottom: "0.5em", lineHeight: 1.6 }, ...props, children }),
3197
+ // Lists with proper indentation
3198
+ ul: ({ children, ...props }) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("ul", { style: { paddingLeft: "1.5em", marginTop: "0.5em", marginBottom: "0.5em" }, ...props, children }),
3199
+ ol: ({ children, ...props }) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("ol", { style: { paddingLeft: "1.5em", marginTop: "0.5em", marginBottom: "0.5em" }, ...props, children }),
3200
+ li: ({ children, ...props }) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("li", { style: { marginTop: "0.25em", marginBottom: "0.25em" }, ...props, children }),
3201
+ // Code blocks
3202
+ code: ({ inline, children, ...props }) => {
3203
+ if (inline) {
3204
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
3205
+ "code",
3206
+ {
3207
+ style: {
3208
+ backgroundColor: "rgba(0, 0, 0, 0.08)",
3209
+ padding: "0.15em 0.4em",
3210
+ borderRadius: "4px",
3211
+ fontSize: "0.9em",
3212
+ fontFamily: "monospace"
3213
+ },
3214
+ ...props,
3215
+ children
3216
+ }
3217
+ );
3218
+ }
3219
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
3220
+ "code",
3221
+ {
3222
+ style: {
3223
+ display: "block",
3224
+ backgroundColor: "rgba(0, 0, 0, 0.08)",
3225
+ padding: "0.75em",
3226
+ borderRadius: "6px",
3227
+ fontSize: "0.9em",
3228
+ fontFamily: "monospace",
3229
+ overflowX: "auto",
3230
+ marginTop: "0.5em",
3231
+ marginBottom: "0.5em"
3232
+ },
3233
+ ...props,
3234
+ children
3235
+ }
3236
+ );
3237
+ },
3238
+ // Pre (code block wrapper)
3239
+ pre: ({ children, ...props }) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("pre", { style: { margin: 0 }, ...props, children }),
3240
+ // Blockquotes
3241
+ blockquote: ({ children, ...props }) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
3242
+ "blockquote",
3243
+ {
3244
+ style: {
3245
+ borderLeft: "4px solid rgba(0, 0, 0, 0.2)",
3246
+ paddingLeft: "1em",
3247
+ marginLeft: 0,
3248
+ marginTop: "0.5em",
3249
+ marginBottom: "0.5em",
3250
+ color: "rgba(0, 0, 0, 0.7)"
3251
+ },
3252
+ ...props,
3253
+ children
3254
+ }
3255
+ ),
3256
+ // Strong/bold
3257
+ strong: ({ children, ...props }) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("strong", { style: { fontWeight: 600 }, ...props, children }),
3258
+ // Emphasis/italic
3259
+ em: ({ children, ...props }) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("em", { style: { fontStyle: "italic" }, ...props, children }),
3260
+ // Horizontal rule
3261
+ hr: (props) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
3262
+ "hr",
3263
+ {
3264
+ style: {
3265
+ border: "none",
3266
+ borderTop: "1px solid rgba(0, 0, 0, 0.1)",
3267
+ marginTop: "1em",
3268
+ marginBottom: "1em"
3269
+ },
3270
+ ...props
3271
+ }
3272
+ ),
3273
+ // Tables (GFM)
3274
+ table: ({ children, ...props }) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { style: { overflowX: "auto", marginTop: "0.5em", marginBottom: "0.5em" }, children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
3275
+ "table",
3276
+ {
3277
+ style: {
3278
+ borderCollapse: "collapse",
3279
+ width: "100%",
3280
+ fontSize: "0.9em"
3281
+ },
3282
+ ...props,
3283
+ children
3284
+ }
3285
+ ) }),
3286
+ th: ({ children, ...props }) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
3287
+ "th",
3288
+ {
3289
+ style: {
3290
+ border: "1px solid rgba(0, 0, 0, 0.2)",
3291
+ padding: "0.5em",
3292
+ backgroundColor: "rgba(0, 0, 0, 0.05)",
3293
+ fontWeight: 600,
3294
+ textAlign: "left"
3295
+ },
3296
+ ...props,
3297
+ children
3298
+ }
3299
+ ),
3300
+ td: ({ children, ...props }) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
3301
+ "td",
3302
+ {
3303
+ style: {
3304
+ border: "1px solid rgba(0, 0, 0, 0.2)",
3305
+ padding: "0.5em"
3306
+ },
3307
+ ...props,
3308
+ children
3309
+ }
3310
+ )
3311
+ },
3312
+ children: normalizedContent
3313
+ }
3314
+ ) });
3315
+ };
3316
+
3317
+ // src/react/ai/FloatingChatBox.tsx
3318
+ var import_jsx_runtime5 = require("react/jsx-runtime");
3319
+ var ChatIcon = () => /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("svg", { width: "20", height: "20", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("path", { d: "M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" }) });
3320
+ var CloseIcon = () => /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("svg", { width: "20", height: "20", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", children: [
3321
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("line", { x1: "18", y1: "6", x2: "6", y2: "18" }),
3322
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("line", { x1: "6", y1: "6", x2: "18", y2: "18" })
3323
+ ] });
3324
+ var ExpandIcon = () => /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("svg", { width: "18", height: "18", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", children: [
3325
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("polyline", { points: "15 3 21 3 21 9" }),
3326
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("polyline", { points: "9 21 3 21 3 15" }),
3327
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("line", { x1: "21", y1: "3", x2: "14", y2: "10" }),
3328
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("line", { x1: "3", y1: "21", x2: "10", y2: "14" })
3329
+ ] });
3330
+ var CollapseIcon = () => /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("svg", { width: "18", height: "18", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", children: [
3331
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("polyline", { points: "4 14 10 14 10 20" }),
3332
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("polyline", { points: "20 10 14 10 14 4" }),
3333
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("line", { x1: "14", y1: "10", x2: "21", y2: "3" }),
3334
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("line", { x1: "3", y1: "21", x2: "10", y2: "14" })
3335
+ ] });
3336
+ var SendIcon = () => /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", children: [
3337
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("line", { x1: "22", y1: "2", x2: "11", y2: "13" }),
3338
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("polygon", { points: "22 2 15 22 11 13 2 9 22 2" })
3339
+ ] });
3340
+ var LayersIcon = () => /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("svg", { width: "14", height: "14", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", children: [
3341
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("polygon", { points: "12 2 2 7 12 12 22 7 12 2" }),
3342
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("polyline", { points: "2 17 12 22 22 17" }),
3343
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("polyline", { points: "2 12 12 17 22 12" })
3344
+ ] });
3345
+ var styles = {
3346
+ root: {
3347
+ fontFamily: 'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'
3348
+ },
3349
+ // Floating button (closed state - wide with text, open state - circular with X)
3350
+ floatingButton: {
3351
+ position: "fixed",
3352
+ bottom: 24,
3353
+ right: 24,
3354
+ borderRadius: "999px",
3355
+ border: "none",
3356
+ cursor: "pointer",
3357
+ background: "linear-gradient(135deg, #10b981, #059669)",
3358
+ color: "#fff",
3359
+ boxShadow: "0 12px 28px rgba(16, 185, 129, 0.4)",
3360
+ display: "flex",
3361
+ alignItems: "center",
3362
+ justifyContent: "center",
3363
+ fontSize: 15,
3364
+ fontWeight: 600,
3365
+ zIndex: 99999,
3366
+ transition: "all 0.3s cubic-bezier(0.4, 0, 0.2, 1)"
3367
+ },
3368
+ floatingButtonClosed: {
3369
+ padding: "14px 24px",
3370
+ gap: 8
3371
+ },
3372
+ floatingButtonOpen: {
3373
+ width: 56,
3374
+ height: 56,
3375
+ padding: 0
3376
+ },
3377
+ floatingButtonMobile: {
3378
+ width: 56,
3379
+ height: 56,
3380
+ padding: 0
3381
+ },
3382
+ // Panel (expandable)
3383
+ panel: {
3384
+ position: "fixed",
3385
+ bottom: 92,
3386
+ right: 24,
3387
+ background: "#fff",
3388
+ borderRadius: 16,
3389
+ boxShadow: "0 20px 60px rgba(15, 23, 42, 0.3), 0 0 0 1px rgba(15, 23, 42, 0.05)",
3390
+ display: "flex",
3391
+ flexDirection: "column",
3392
+ overflow: "hidden",
3393
+ zIndex: 99999,
3394
+ transition: "all 0.3s cubic-bezier(0.4, 0, 0.2, 1)"
3395
+ },
3396
+ panelNormal: {
3397
+ width: 400,
3398
+ height: 550
3399
+ },
3400
+ panelExpanded: {
3401
+ width: 520,
3402
+ height: 700
3403
+ },
3404
+ // Header with green gradient
3405
+ header: {
3406
+ padding: "16px 18px",
3407
+ background: "linear-gradient(135deg, #10b981, #059669)",
3408
+ color: "#fff",
3409
+ display: "flex",
3410
+ alignItems: "center",
3411
+ justifyContent: "space-between"
3412
+ },
3413
+ title: {
3414
+ margin: 0,
3415
+ fontSize: 16,
3416
+ fontWeight: 600,
3417
+ letterSpacing: "-0.01em"
3418
+ },
3419
+ headerButtons: {
3420
+ display: "flex",
3421
+ alignItems: "center",
3422
+ gap: 8
3423
+ },
3424
+ headerButton: {
3425
+ border: "none",
3426
+ background: "rgba(255, 255, 255, 0.15)",
3427
+ color: "#fff",
3428
+ width: 32,
3429
+ height: 32,
3430
+ borderRadius: 8,
3431
+ cursor: "pointer",
3432
+ display: "flex",
3433
+ alignItems: "center",
3434
+ justifyContent: "center",
3435
+ transition: "background 0.2s"
3436
+ },
3437
+ // Messages area
3438
+ messages: {
3439
+ flex: 1,
3440
+ padding: "20px 18px",
3441
+ overflowY: "auto",
3442
+ background: "#f8fafc",
3443
+ display: "flex",
3444
+ flexDirection: "column",
3445
+ gap: 16
3446
+ },
3447
+ // Message bubbles
3448
+ messageWrapper: {
3449
+ display: "flex",
3450
+ flexDirection: "column",
3451
+ gap: 8
3452
+ },
3453
+ messageBubble: {
3454
+ maxWidth: "85%",
3455
+ padding: "12px 14px",
3456
+ borderRadius: 16,
3457
+ lineHeight: 1.5,
3458
+ fontSize: 14,
3459
+ whiteSpace: "pre-wrap",
3460
+ wordBreak: "break-word"
3461
+ },
3462
+ userMessage: {
3463
+ alignSelf: "flex-end",
3464
+ background: "linear-gradient(135deg, #10b981, #059669)",
3465
+ color: "#fff",
3466
+ borderBottomRightRadius: 4
3467
+ },
3468
+ assistantMessage: {
3469
+ alignSelf: "flex-start",
3470
+ background: "#e2e8f0",
3471
+ color: "#0f172a",
3472
+ borderBottomLeftRadius: 4
3473
+ },
3474
+ // Streaming cursor
3475
+ cursor: {
3476
+ display: "inline-block",
3477
+ width: 2,
3478
+ height: 16,
3479
+ background: "#0f172a",
3480
+ marginLeft: 2,
3481
+ animation: "zenitBlink 1s infinite",
3482
+ verticalAlign: "text-bottom"
3483
+ },
3484
+ thinkingText: {
3485
+ fontStyle: "italic",
3486
+ opacity: 0.7,
3487
+ display: "flex",
3488
+ alignItems: "center",
3489
+ gap: 8
3490
+ },
3491
+ typingIndicator: {
3492
+ display: "flex",
3493
+ gap: 4,
3494
+ alignItems: "center"
3495
+ },
3496
+ typingDot: {
3497
+ width: 8,
3498
+ height: 8,
3499
+ borderRadius: "50%",
3500
+ backgroundColor: "#059669",
3501
+ animation: "typingDotBounce 1.4s infinite ease-in-out"
3502
+ },
3503
+ // Metadata section (Referenced Layers)
3504
+ metadataSection: {
3505
+ marginTop: 12,
3506
+ padding: "10px 12px",
3507
+ background: "rgba(255, 255, 255, 0.5)",
3508
+ borderRadius: 10,
3509
+ fontSize: 12
3510
+ },
3511
+ metadataTitle: {
3512
+ fontWeight: 600,
3513
+ color: "#059669",
3514
+ marginBottom: 6,
3515
+ display: "flex",
3516
+ alignItems: "center",
3517
+ gap: 6
3518
+ },
3519
+ metadataList: {
3520
+ margin: 0,
3521
+ paddingLeft: 18,
3522
+ color: "#475569"
3523
+ },
3524
+ metadataItem: {
3525
+ marginBottom: 2
3526
+ },
3527
+ // Suggested actions
3528
+ actionsSection: {
3529
+ marginTop: 12
3530
+ },
3531
+ sectionLabel: {
3532
+ fontSize: 11,
3533
+ fontWeight: 600,
3534
+ color: "#64748b",
3535
+ marginBottom: 8,
3536
+ textTransform: "uppercase",
3537
+ letterSpacing: "0.05em"
3538
+ },
3539
+ actionsGrid: {
3540
+ display: "flex",
3541
+ flexWrap: "wrap",
3542
+ gap: 6
3543
+ },
3544
+ actionButton: {
3545
+ border: "1px solid #d1fae5",
3546
+ background: "#d1fae5",
3547
+ color: "#065f46",
3548
+ borderRadius: 999,
3549
+ padding: "6px 12px",
3550
+ fontSize: 12,
3551
+ fontWeight: 500,
3552
+ cursor: "pointer",
3553
+ transition: "all 0.2s"
3554
+ },
3555
+ // Follow-up questions
3556
+ followUpButton: {
3557
+ border: "1px solid #cbd5e1",
3558
+ background: "#fff",
3559
+ color: "#475569",
3560
+ borderRadius: 10,
3561
+ padding: "8px 12px",
3562
+ fontSize: 12,
3563
+ fontWeight: 500,
3564
+ cursor: "pointer",
3565
+ textAlign: "left",
3566
+ width: "100%",
3567
+ transition: "all 0.2s"
3568
+ },
3569
+ // Input area
3570
+ inputWrapper: {
3571
+ borderTop: "1px solid #e2e8f0",
3572
+ padding: "14px 16px",
3573
+ display: "flex",
3574
+ gap: 10,
3575
+ alignItems: "flex-end",
3576
+ background: "#fff"
3577
+ },
3578
+ textarea: {
3579
+ flex: 1,
3580
+ resize: "none",
3581
+ borderRadius: 12,
3582
+ border: "1.5px solid #cbd5e1",
3583
+ padding: "10px 12px",
3584
+ fontSize: 14,
3585
+ fontFamily: "inherit",
3586
+ lineHeight: 1.4,
3587
+ transition: "border-color 0.2s"
3588
+ },
3589
+ textareaFocus: {
3590
+ borderColor: "#10b981",
3591
+ outline: "none"
3592
+ },
3593
+ sendButton: {
3594
+ borderRadius: 12,
3595
+ border: "none",
3596
+ padding: "10px 14px",
3597
+ background: "linear-gradient(135deg, #10b981, #059669)",
3598
+ color: "#fff",
3599
+ cursor: "pointer",
3600
+ fontSize: 14,
3601
+ fontWeight: 600,
3602
+ display: "flex",
3603
+ alignItems: "center",
3604
+ justifyContent: "center",
3605
+ transition: "opacity 0.2s, transform 0.2s",
3606
+ minWidth: 44,
3607
+ height: 44
3608
+ },
3609
+ // Status messages
3610
+ statusNote: {
3611
+ padding: "0 16px 14px",
3612
+ fontSize: 12,
3613
+ color: "#64748b",
3614
+ textAlign: "center"
3615
+ },
3616
+ errorText: {
3617
+ padding: "0 16px 14px",
3618
+ fontSize: 12,
3619
+ color: "#dc2626",
3620
+ textAlign: "center"
3621
+ }
3622
+ };
3623
+ var FloatingChatBox = ({
3624
+ mapId,
3625
+ filteredLayerIds,
3626
+ filters,
3627
+ userId,
3628
+ baseUrl,
3629
+ accessToken,
3630
+ getAccessToken,
3631
+ onActionClick,
3632
+ onOpenChange,
3633
+ hideButton
3634
+ }) => {
3635
+ const [open, setOpen] = (0, import_react4.useState)(false);
3636
+ const [expanded, setExpanded] = (0, import_react4.useState)(false);
3637
+ const [messages, setMessages] = (0, import_react4.useState)([]);
3638
+ const [inputValue, setInputValue] = (0, import_react4.useState)("");
3639
+ const [conversationId, setConversationId] = (0, import_react4.useState)();
3640
+ const [errorMessage, setErrorMessage] = (0, import_react4.useState)(null);
3641
+ const [isFocused, setIsFocused] = (0, import_react4.useState)(false);
3642
+ const [isMobile, setIsMobile] = (0, import_react4.useState)(false);
3643
+ const messagesEndRef = (0, import_react4.useRef)(null);
3644
+ const messagesContainerRef = (0, import_react4.useRef)(null);
3645
+ const chatBoxRef = (0, import_react4.useRef)(null);
3646
+ const chatConfig = (0, import_react4.useMemo)(() => {
3647
+ if (!baseUrl) return void 0;
3648
+ return { baseUrl, accessToken, getAccessToken };
3649
+ }, [accessToken, baseUrl, getAccessToken]);
3650
+ const { sendMessage: sendMessage2, isStreaming, streamingText, completeResponse } = useSendMessageStream(chatConfig);
3651
+ const canSend = Boolean(mapId) && Boolean(baseUrl) && inputValue.trim().length > 0 && !isStreaming;
3652
+ (0, import_react4.useEffect)(() => {
3653
+ onOpenChange?.(open);
3654
+ }, [open, onOpenChange]);
3655
+ (0, import_react4.useEffect)(() => {
3656
+ if (open && isMobile) {
3657
+ setExpanded(true);
3658
+ }
3659
+ }, [open, isMobile]);
3660
+ const scrollToBottom = (0, import_react4.useCallback)(() => {
3661
+ if (messagesEndRef.current) {
3662
+ messagesEndRef.current.scrollIntoView({ behavior: "smooth" });
3663
+ }
3664
+ }, []);
3665
+ (0, import_react4.useEffect)(() => {
3666
+ if (open && messages.length === 0) {
3667
+ setMessages([
3668
+ {
3669
+ id: "welcome",
3670
+ role: "assistant",
3671
+ content: "Hola, soy el asistente de IA de ZENIT. Estoy aqu\xED para ayudarte a analizar tu mapa y responder tus preguntas sobre las capas y datos. \xBFEn qu\xE9 puedo ayudarte hoy?"
3672
+ }
3673
+ ]);
3674
+ }
3675
+ }, [open, messages.length]);
3676
+ (0, import_react4.useEffect)(() => {
3677
+ scrollToBottom();
3678
+ }, [messages, streamingText, scrollToBottom]);
3679
+ (0, import_react4.useEffect)(() => {
3680
+ if (!open) return;
3681
+ if (isMobile && expanded) return;
3682
+ const handleClickOutside = (event) => {
3683
+ if (chatBoxRef.current && !chatBoxRef.current.contains(event.target)) {
3684
+ setOpen(false);
3685
+ }
3686
+ };
3687
+ document.addEventListener("mousedown", handleClickOutside);
3688
+ return () => {
3689
+ document.removeEventListener("mousedown", handleClickOutside);
3690
+ };
3691
+ }, [open, isMobile, expanded]);
3692
+ (0, import_react4.useEffect)(() => {
3693
+ if (typeof window === "undefined") return;
3694
+ const mediaQuery = window.matchMedia("(max-width: 768px)");
3695
+ const updateMobile = () => setIsMobile(mediaQuery.matches);
3696
+ updateMobile();
3697
+ if (mediaQuery.addEventListener) {
3698
+ mediaQuery.addEventListener("change", updateMobile);
3699
+ } else {
3700
+ mediaQuery.addListener(updateMobile);
3701
+ }
3702
+ return () => {
3703
+ if (mediaQuery.removeEventListener) {
3704
+ mediaQuery.removeEventListener("change", updateMobile);
3705
+ } else {
3706
+ mediaQuery.removeListener(updateMobile);
3707
+ }
3708
+ };
3709
+ }, []);
3710
+ (0, import_react4.useEffect)(() => {
3711
+ if (typeof document === "undefined") return;
3712
+ if (!open || !isMobile) return;
3713
+ document.body.style.overflow = "hidden";
3714
+ return () => {
3715
+ document.body.style.overflow = "";
3716
+ };
3717
+ }, [open, isMobile]);
3718
+ const addMessage = (0, import_react4.useCallback)((message) => {
3719
+ setMessages((prev) => [...prev, message]);
3720
+ }, []);
3721
+ const handleSend = (0, import_react4.useCallback)(async () => {
3722
+ if (!mapId) {
3723
+ setErrorMessage("Selecciona un mapa para usar el asistente.");
3724
+ return;
3725
+ }
3726
+ if (!baseUrl) {
3727
+ setErrorMessage("Configura la baseUrl del SDK para usar Zenit AI.");
3728
+ return;
3729
+ }
3730
+ if (!inputValue.trim()) return;
3731
+ const messageText = inputValue.trim();
3732
+ setInputValue("");
3733
+ setErrorMessage(null);
3734
+ addMessage({
3735
+ id: `user-${Date.now()}`,
3736
+ role: "user",
3737
+ content: messageText
3738
+ });
3739
+ const request = {
3740
+ message: messageText,
3741
+ conversationId,
3742
+ filteredLayerIds,
3743
+ filters,
3744
+ userId
3745
+ };
3746
+ try {
3747
+ const response = await sendMessage2(mapId, request);
3748
+ setConversationId(response.conversationId ?? conversationId);
3749
+ addMessage({
3750
+ id: `assistant-${Date.now()}`,
3751
+ role: "assistant",
3752
+ content: response.answer,
3753
+ response
3754
+ });
3755
+ } catch (error) {
3756
+ setErrorMessage(error instanceof Error ? error.message : "Ocurri\xF3 un error inesperado.");
3757
+ addMessage({
3758
+ id: `error-${Date.now()}`,
3759
+ role: "assistant",
3760
+ content: `\u274C Error: ${error instanceof Error ? error.message : "Ocurri\xF3 un error inesperado."}`
3761
+ });
3762
+ }
3763
+ }, [
3764
+ addMessage,
3765
+ baseUrl,
3766
+ conversationId,
3767
+ filteredLayerIds,
3768
+ filters,
3769
+ inputValue,
3770
+ mapId,
3771
+ sendMessage2,
3772
+ userId
3773
+ ]);
3774
+ const handleKeyDown = (0, import_react4.useCallback)(
3775
+ (event) => {
3776
+ if (event.key === "Enter" && !event.shiftKey) {
3777
+ event.preventDefault();
3778
+ if (canSend) {
3779
+ void handleSend();
3780
+ }
3781
+ }
3782
+ },
3783
+ [canSend, handleSend]
3784
+ );
3785
+ const handleFollowUpClick = (0, import_react4.useCallback)((question) => {
3786
+ setInputValue(question);
3787
+ }, []);
3788
+ const renderMetadata = (response) => {
3789
+ if (!response?.metadata) return null;
3790
+ const referencedLayers = response.metadata.referencedLayers;
3791
+ if (!referencedLayers || referencedLayers.length === 0) return null;
3792
+ return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { style: styles.metadataSection, children: [
3793
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { style: styles.metadataTitle, children: [
3794
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(LayersIcon, {}),
3795
+ "Capas Analizadas"
3796
+ ] }),
3797
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("ul", { style: styles.metadataList, children: referencedLayers.map((layer, index) => /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("li", { style: styles.metadataItem, children: [
3798
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("strong", { children: layer.layerName }),
3799
+ " (",
3800
+ layer.featureCount,
3801
+ " ",
3802
+ layer.featureCount === 1 ? "elemento" : "elementos",
3803
+ ")"
3804
+ ] }, index)) })
3805
+ ] });
3806
+ };
3807
+ const renderActions = (response) => {
3808
+ if (!response?.suggestedActions?.length) return null;
3809
+ return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { style: styles.actionsSection, children: [
3810
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { style: styles.sectionLabel, children: "Acciones Sugeridas" }),
3811
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { style: styles.actionsGrid, children: response.suggestedActions.map((action, index) => /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
3812
+ "button",
3813
+ {
3814
+ type: "button",
3815
+ style: {
3816
+ ...styles.actionButton,
3817
+ opacity: isStreaming ? 0.5 : 1,
3818
+ cursor: isStreaming ? "not-allowed" : "pointer"
3819
+ },
3820
+ onClick: () => !isStreaming && onActionClick?.(action),
3821
+ disabled: isStreaming,
3822
+ onMouseEnter: (e) => {
3823
+ if (!isStreaming) {
3824
+ e.currentTarget.style.background = "#a7f3d0";
3825
+ e.currentTarget.style.borderColor = "#a7f3d0";
3826
+ }
3827
+ },
3828
+ onMouseLeave: (e) => {
3829
+ if (!isStreaming) {
3830
+ e.currentTarget.style.background = "#d1fae5";
3831
+ e.currentTarget.style.borderColor = "#d1fae5";
3832
+ }
3833
+ },
3834
+ children: action.label ?? action.action ?? "Acci\xF3n"
3835
+ },
3836
+ `${action.label ?? action.action ?? "action"}-${index}`
3837
+ )) })
3838
+ ] });
3839
+ };
3840
+ const renderFollowUps = (response) => {
3841
+ if (!response?.followUpQuestions?.length) return null;
3842
+ return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { style: styles.actionsSection, children: [
3843
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { style: styles.sectionLabel, children: "Preguntas Relacionadas" }),
3844
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { style: { display: "flex", flexDirection: "column", gap: 6 }, children: response.followUpQuestions.map((question, index) => /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
3845
+ "button",
3846
+ {
3847
+ type: "button",
3848
+ style: {
3849
+ ...styles.followUpButton,
3850
+ opacity: isStreaming ? 0.5 : 1,
3851
+ cursor: isStreaming ? "not-allowed" : "pointer"
3852
+ },
3853
+ onClick: () => !isStreaming && handleFollowUpClick(question),
3854
+ disabled: isStreaming,
3855
+ onMouseEnter: (e) => {
3856
+ if (!isStreaming) {
3857
+ e.currentTarget.style.background = "#f8fafc";
3858
+ e.currentTarget.style.borderColor = "#10b981";
3859
+ }
3860
+ },
3861
+ onMouseLeave: (e) => {
3862
+ if (!isStreaming) {
3863
+ e.currentTarget.style.background = "#fff";
3864
+ e.currentTarget.style.borderColor = "#cbd5e1";
3865
+ }
3866
+ },
3867
+ children: question
3868
+ },
3869
+ `followup-${index}`
3870
+ )) })
3871
+ ] });
3872
+ };
3873
+ const chatContent = /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { style: styles.root, children: [
3874
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("style", { children: `
3875
+ @keyframes zenitBlink {
3876
+ 0%, 49% { opacity: 1; }
3877
+ 50%, 100% { opacity: 0; }
3878
+ }
3879
+ @keyframes zenitPulse {
3880
+ 0% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.7); }
3881
+ 70% { box-shadow: 0 0 0 14px rgba(16, 185, 129, 0); }
3882
+ 100% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0); }
3883
+ }
3884
+ @keyframes typingDotBounce {
3885
+ 0%, 60%, 100% { transform: translateY(0); }
3886
+ 30% { transform: translateY(-8px); }
3887
+ }
3888
+ .zenit-typing-dot:nth-child(1) { animation-delay: 0s; }
3889
+ .zenit-typing-dot:nth-child(2) { animation-delay: 0.2s; }
3890
+ .zenit-typing-dot:nth-child(3) { animation-delay: 0.4s; }
3891
+ .zenit-ai-button:not(.open) {
3892
+ animation: zenitPulse 2.5s infinite;
3893
+ }
3894
+ .zenit-ai-button:hover {
3895
+ transform: scale(1.05);
3896
+ }
3897
+ .zenit-ai-button:active {
3898
+ transform: scale(0.95);
3899
+ }
3900
+ .zenit-send-button:disabled {
3901
+ opacity: 0.5;
3902
+ cursor: not-allowed;
3903
+ }
3904
+ .zenit-send-button:not(:disabled):hover {
3905
+ opacity: 0.9;
3906
+ transform: translateY(-1px);
3907
+ }
3908
+ .zenit-send-button:not(:disabled):active {
3909
+ transform: translateY(0);
3910
+ }
3911
+ .zenit-chat-panel {
3912
+ box-sizing: border-box;
3913
+ }
3914
+ @media (max-width: 768px) {
3915
+ .zenit-chat-panel.zenit-chat-panel--fullscreen {
3916
+ position: fixed !important;
3917
+ inset: 0 !important;
3918
+ width: 100vw !important;
3919
+ max-width: 100vw !important;
3920
+ height: 100vh !important;
3921
+ height: 100dvh !important;
3922
+ border-radius: 0 !important;
3923
+ display: flex !important;
3924
+ flex-direction: column !important;
3925
+ overflow: hidden !important;
3926
+ z-index: 100000 !important;
3927
+ padding-top: env(safe-area-inset-top);
3928
+ }
3929
+ .zenit-chat-panel.zenit-chat-panel--fullscreen .zenit-ai-body {
3930
+ flex: 1;
3931
+ min-height: 0;
3932
+ overflow-y: auto;
3933
+ -webkit-overflow-scrolling: touch;
3934
+ }
3935
+ .zenit-chat-panel.zenit-chat-panel--fullscreen .zenit-ai-input-area {
3936
+ flex-shrink: 0;
3937
+ padding-bottom: max(14px, env(safe-area-inset-bottom));
3938
+ }
3939
+ .zenit-ai-button.zenit-ai-button--hidden-mobile {
3940
+ display: none !important;
3941
+ }
3942
+ }
3943
+ ` }),
3944
+ open && /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
3945
+ "div",
3946
+ {
3947
+ ref: chatBoxRef,
3948
+ className: `zenit-chat-panel${expanded ? " zenit-chat-panel--expanded" : ""}${isMobile ? " zenit-chat-panel--fullscreen" : ""}`,
3949
+ style: {
3950
+ ...styles.panel,
3951
+ ...expanded ? styles.panelExpanded : styles.panelNormal
3952
+ },
3953
+ children: [
3954
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("header", { style: styles.header, children: [
3955
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("h3", { style: styles.title, children: "Asistente Zenit AI" }),
3956
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { style: styles.headerButtons, children: [
3957
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
3958
+ "button",
3959
+ {
3960
+ type: "button",
3961
+ style: styles.headerButton,
3962
+ onClick: () => setExpanded(!expanded),
3963
+ onMouseEnter: (e) => {
3964
+ e.currentTarget.style.background = "rgba(255, 255, 255, 0.25)";
3965
+ },
3966
+ onMouseLeave: (e) => {
3967
+ e.currentTarget.style.background = "rgba(255, 255, 255, 0.15)";
3968
+ },
3969
+ "aria-label": expanded ? "Contraer" : "Expandir",
3970
+ children: expanded ? /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(CollapseIcon, {}) : /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(ExpandIcon, {})
3971
+ }
3972
+ ),
3973
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
3974
+ "button",
3975
+ {
3976
+ type: "button",
3977
+ style: styles.headerButton,
3978
+ onClick: () => setOpen(false),
3979
+ onMouseEnter: (e) => {
3980
+ e.currentTarget.style.background = "rgba(255, 255, 255, 0.25)";
3981
+ },
3982
+ onMouseLeave: (e) => {
3983
+ e.currentTarget.style.background = "rgba(255, 255, 255, 0.15)";
3984
+ },
3985
+ "aria-label": "Cerrar",
3986
+ children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(CloseIcon, {})
3987
+ }
3988
+ )
3989
+ ] })
3990
+ ] }),
3991
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { ref: messagesContainerRef, className: "zenit-ai-body", style: styles.messages, children: [
3992
+ messages.map((message) => /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
3993
+ "div",
3994
+ {
3995
+ style: {
3996
+ ...styles.messageWrapper,
3997
+ alignItems: message.role === "user" ? "flex-end" : "flex-start"
3998
+ },
3999
+ children: /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
4000
+ "div",
4001
+ {
4002
+ style: {
4003
+ ...styles.messageBubble,
4004
+ ...message.role === "user" ? styles.userMessage : styles.assistantMessage
4005
+ },
4006
+ children: [
4007
+ message.role === "assistant" ? /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(MarkdownRenderer, { content: message.content }) : message.content,
4008
+ message.role === "assistant" && renderMetadata(message.response),
4009
+ message.role === "assistant" && renderActions(message.response),
4010
+ message.role === "assistant" && renderFollowUps(message.response)
4011
+ ]
4012
+ }
4013
+ )
4014
+ },
4015
+ message.id
4016
+ )),
4017
+ isStreaming && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
4018
+ "div",
4019
+ {
4020
+ style: {
4021
+ ...styles.messageWrapper,
4022
+ alignItems: "flex-start"
4023
+ },
4024
+ children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
4025
+ "div",
4026
+ {
4027
+ style: {
4028
+ ...styles.messageBubble,
4029
+ ...styles.assistantMessage
4030
+ },
4031
+ children: streamingText ? /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(import_jsx_runtime5.Fragment, { children: [
4032
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(MarkdownRenderer, { content: streamingText }),
4033
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { style: styles.cursor })
4034
+ ] }) : /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { style: styles.thinkingText, children: [
4035
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { children: "Analizando" }),
4036
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { style: styles.typingIndicator, children: [
4037
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { className: "zenit-typing-dot", style: styles.typingDot }),
4038
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { className: "zenit-typing-dot", style: styles.typingDot }),
4039
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { className: "zenit-typing-dot", style: styles.typingDot })
4040
+ ] })
4041
+ ] })
4042
+ }
4043
+ )
4044
+ }
4045
+ ),
4046
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { ref: messagesEndRef })
4047
+ ] }),
4048
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "zenit-ai-input-area", style: styles.inputWrapper, children: [
4049
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
4050
+ "textarea",
4051
+ {
4052
+ style: {
4053
+ ...styles.textarea,
4054
+ ...isFocused ? styles.textareaFocus : {}
4055
+ },
4056
+ rows: 2,
4057
+ value: inputValue,
4058
+ onChange: (event) => setInputValue(event.target.value),
4059
+ onKeyDown: handleKeyDown,
4060
+ onFocus: () => setIsFocused(true),
4061
+ onBlur: () => setIsFocused(false),
4062
+ placeholder: !mapId ? "Selecciona un mapa para comenzar" : isStreaming ? "Esperando respuesta..." : "Escribe tu pregunta...",
4063
+ disabled: !mapId || !baseUrl || isStreaming
4064
+ }
4065
+ ),
4066
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
4067
+ "button",
4068
+ {
4069
+ type: "button",
4070
+ className: "zenit-send-button",
4071
+ style: styles.sendButton,
4072
+ onClick: () => void handleSend(),
4073
+ disabled: !canSend,
4074
+ "aria-label": "Enviar mensaje",
4075
+ children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(SendIcon, {})
4076
+ }
4077
+ )
4078
+ ] }),
4079
+ errorMessage && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { style: styles.errorText, children: errorMessage }),
4080
+ !mapId && !errorMessage && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { style: styles.statusNote, children: "Selecciona un mapa para usar el asistente" }),
4081
+ !baseUrl && !errorMessage && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { style: styles.statusNote, children: "Configura la baseUrl del SDK" })
4082
+ ]
4083
+ }
4084
+ ),
4085
+ !(hideButton && !open) && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
4086
+ "button",
4087
+ {
4088
+ type: "button",
4089
+ className: `zenit-ai-button ${open ? "open" : ""}${open && isMobile ? " zenit-ai-button--hidden-mobile" : ""}`,
4090
+ style: {
4091
+ ...styles.floatingButton,
4092
+ ...open ? styles.floatingButtonOpen : isMobile ? styles.floatingButtonMobile : styles.floatingButtonClosed
4093
+ },
4094
+ onClick: () => setOpen((prev) => !prev),
4095
+ "aria-label": open ? "Cerrar asistente" : "Abrir asistente Zenit AI",
4096
+ children: open ? /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(CloseIcon, {}) : /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(import_jsx_runtime5.Fragment, { children: [
4097
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(ChatIcon, {}),
4098
+ !isMobile && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { children: "Asistente IA" })
4099
+ ] })
4100
+ }
4101
+ )
4102
+ ] });
4103
+ if (typeof document !== "undefined") {
4104
+ return (0, import_react_dom.createPortal)(chatContent, document.body);
4105
+ }
4106
+ return chatContent;
4107
+ };
1370
4108
  // Annotate the CommonJS export names for ESM import in node:
1371
4109
  0 && (module.exports = {
4110
+ ChevronLeft,
4111
+ ChevronRight,
1372
4112
  DEFAULT_MAX_FEATURES_FULL_GEOJSON,
4113
+ Eye,
4114
+ EyeOff,
1373
4115
  FilterEngine,
4116
+ FloatingChatBox,
1374
4117
  HttpClient,
4118
+ Layers,
4119
+ Upload,
4120
+ X,
1375
4121
  ZenitAuthClient,
1376
4122
  ZenitCatalogNotSupportedError,
1377
4123
  ZenitClient,
4124
+ ZenitFeatureFilterPanel,
4125
+ ZenitLayerManager,
1378
4126
  ZenitLayersClient,
4127
+ ZenitMap,
1379
4128
  ZenitMapsClient,
1380
4129
  ZenitSdkAuthClient,
4130
+ ZoomIn,
1381
4131
  applyFilteredGeoJSONStrategy,
1382
4132
  applyLayerOverrides,
1383
4133
  applyPrefiltersToFeatureCollection,
@@ -1386,21 +4136,33 @@ function normalizeBbox(input) {
1386
4136
  buildLayerFilters,
1387
4137
  buildLimitedMessage,
1388
4138
  centroidFromBBox,
4139
+ clampNumber,
4140
+ clampOpacity,
1389
4141
  computeBBoxFromFeature,
1390
4142
  createChatService,
1391
4143
  decorateFeaturesWithLayerId,
1392
4144
  extractMapDto,
1393
4145
  filterEngine,
4146
+ getAccentByLayerId,
1394
4147
  getCatalogSupport,
4148
+ getEffectiveLayerOpacity,
4149
+ getLayerColor,
4150
+ getLayerZoomOpacityFactor,
4151
+ getStyleByLayerId,
4152
+ getZoomOpacityFactor,
1395
4153
  initLayerStates,
4154
+ isPolygonLayer,
1396
4155
  normalizeBbox,
1397
4156
  normalizeMapCenter,
1398
4157
  normalizeMapLayers,
1399
4158
  resetOverrides,
4159
+ resolveLayerAccent,
1400
4160
  resolveLayerStrategy,
1401
4161
  sendMessage,
1402
4162
  sendMessageStream,
1403
4163
  shouldSkipGeojsonDownload,
1404
- shouldUseFilterMultiple
4164
+ shouldUseFilterMultiple,
4165
+ useSendMessage,
4166
+ useSendMessageStream
1405
4167
  });
1406
4168
  //# sourceMappingURL=index.js.map