@thibezer/ui-components-kit 2.3.0 → 2.4.1

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/canvas.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Qi=Object.defineProperty;var tn=(n,t,e)=>t in n?Qi(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var p=(n,t,e)=>tn(n,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});;/* empty css */const y=require("leaflet"),S=require("./leaflet-DcO7uRC-.cjs"),ve=require("./listener-bag-D5omxZ9h.cjs"),Mo=require("./ssr-safe-CiHD1adl.cjs"),ye={perimetroWeight:1,fechamentoWeight:1,vizinhoWeight:1,bancoWeight:1,markerSizeBase:10,markerStyleM:"circle-dot",markerSizeM:14,markerStyleP:"circle",markerSizeP:10,markerStyleV:"cross",markerSizeV:8,enableAnimations:!1,preferCanvas:!0,crosshair:!1,satOpacity:1,magnetSnap:!1},ht=class ht{constructor(){p(this,"config");this.config=this.loadConfig()}static getInstance(){return ht.instance||(ht.instance=new ht),ht.instance}loadConfig(){try{const t=typeof localStorage<"u"?localStorage.getItem("gerencigeo_mapa_config"):null;if(t)return{...ye,...JSON.parse(t)}}catch(t){console.error("Erro ao carregar configurações do mapa",t)}return{...ye}}saveConfig(t){this.config={...this.config,...t},typeof localStorage<"u"&&localStorage.setItem("gerencigeo_mapa_config",JSON.stringify(this.config))}getConfig(){return this.config=this.loadConfig(),{...this.config}}};p(ht,"instance");let jt=ht;async function en(n,t,e,o){const i=n.getSize(),a=n.getBounds(),s=a.getSouthWest(),r=a.getNorthEast(),c=`${s.lng},${s.lat},${r.lng},${r.lat}`;let l=0,d=0;try{if(t.containerPoint)l=Math.round(t.containerPoint.x),d=Math.round(t.containerPoint.y);else if(t.layerPoint){const x=n.layerPointToContainerPoint(t.layerPoint);l=Math.round(x.x),d=Math.round(x.y)}}catch{l=0,d=0}const h=`https://acervofundiario.incra.gov.br/i3geo/ogc.php?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetFeatureInfo&FORMAT=image/png&TRANSPARENT=true&QUERY_LAYERS=certificada_sigef_particular_pr&LAYERS=certificada_sigef_particular_pr&INFO_FORMAT=application/json&X=${l}&Y=${d}&WIDTH=${i.x}&HEIGHT=${i.y}&SRS=EPSG:4326&BBOX=${c}`,u=n.getContainer();u.style.cursor="wait";const m=y.popup({className:"compact-sigef-popup",maxWidth:250}).setLatLng(t.latlng).setContent(`
1
+ "use strict";var oa=Object.defineProperty;var ia=(a,t,e)=>t in a?oa(a,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[t]=e;var p=(a,t,e)=>ia(a,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});;/* empty css */const y=require("leaflet"),S=require("./leaflet-DcO7uRC-.cjs"),Le=require("./listener-bag-D5omxZ9h.cjs"),ko=require("./ssr-safe-CiHD1adl.cjs"),Se={perimetroWeight:1,fechamentoWeight:1,vizinhoWeight:1,bancoWeight:1,markerSizeBase:10,markerStyleM:"circle-dot",markerSizeM:14,markerStyleP:"circle",markerSizeP:10,markerStyleV:"cross",markerSizeV:8,enableAnimations:!1,preferCanvas:!0,crosshair:!1,satOpacity:1,magnetSnap:!1},ut=class ut{constructor(){p(this,"config");this.config=this.loadConfig()}static getInstance(){return ut.instance||(ut.instance=new ut),ut.instance}loadConfig(){try{const t=typeof localStorage<"u"?localStorage.getItem("gerencigeo_mapa_config"):null;if(t)return{...Se,...JSON.parse(t)}}catch(t){console.error("Erro ao carregar configurações do mapa",t)}return{...Se}}saveConfig(t){this.config={...this.config,...t},typeof localStorage<"u"&&localStorage.setItem("gerencigeo_mapa_config",JSON.stringify(this.config))}getConfig(){return this.config=this.loadConfig(),{...this.config}}};p(ut,"instance");let Yt=ut;async function aa(a,t,e,o){const i=a.getSize(),n=a.getBounds(),s=n.getSouthWest(),r=n.getNorthEast(),c=`${s.lng},${s.lat},${r.lng},${r.lat}`;let l=0,d=0;try{if(t.containerPoint)l=Math.round(t.containerPoint.x),d=Math.round(t.containerPoint.y);else if(t.layerPoint){const x=a.layerPointToContainerPoint(t.layerPoint);l=Math.round(x.x),d=Math.round(x.y)}}catch{l=0,d=0}const h=`https://acervofundiario.incra.gov.br/i3geo/ogc.php?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetFeatureInfo&FORMAT=image/png&TRANSPARENT=true&QUERY_LAYERS=certificada_sigef_particular_pr&LAYERS=certificada_sigef_particular_pr&INFO_FORMAT=application/json&X=${l}&Y=${d}&WIDTH=${i.x}&HEIGHT=${i.y}&SRS=EPSG:4326&BBOX=${c}`,u=a.getContainer();u.style.cursor="wait";const g=y.popup({className:"compact-sigef-popup",maxWidth:250}).setLatLng(t.latlng).setContent(`
2
2
  <div style="font-family:var(--ui-fonte-base, sans-serif); display:flex; align-items:center; gap:8px; color:rgba(255,255,255,0.9); font-size:12px;">
3
3
  <svg style="animation:spin 1s linear infinite; width:14px; height:14px; flex-shrink:0;" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
4
4
  <circle cx="12" cy="12" r="10" stroke="rgba(255,255,255,0.2)" stroke-width="4" fill="none"></circle>
@@ -6,19 +6,19 @@
6
6
  </svg>
7
7
  Consultando...
8
8
  </div>
9
- `).openOn(n);o.currentAbortController&&o.currentAbortController.abort(),o.currentAbortController=new AbortController;const f=o.currentAbortController.signal,g=setTimeout(()=>{o.currentAbortController&&o.currentAbortController.abort()},8e3);try{const A=typeof window<"u"&&(window.location.origin.includes("localhost")||window.location.origin.includes("127.0.0.1")||window.location.origin.includes("[::1]"))?`${e}/proxy/sigef?url=${encodeURIComponent(h)}`:`${window.location.origin}/api.php?action=proxy_sigef&url=${encodeURIComponent(h)}`,M=await fetch(A,{signal:f});clearTimeout(g);let C=null;if(M.ok){const z=await M.text();try{C=JSON.parse(z)}catch{C=null}}if(C&&C.features&&C.features.length>0){const z=C.features[0],P=z.properties||{},v=String(z.id||P.parcela_codigo||P.co_parcela||P.id_parcela||""),b=String(P.nome_area||P.nome_imovel||"Imóvel Sem Nome");if(v){const k=encodeURIComponent(v),E=`https://sigef.incra.gov.br/geo/exportar/parcela/shp/${k}/`,L=`https://sigef.incra.gov.br/geo/parcela/detalhe/${k}/`,w=document.createElement("div");w.style.cssText="font-family:var(--ui-fonte-base, sans-serif); color:rgba(255, 255, 255, 0.9); line-height:1.4; min-width:180px;",w.innerHTML=`
9
+ `).openOn(a);o.currentAbortController&&o.currentAbortController.abort(),o.currentAbortController=new AbortController;const m=o.currentAbortController.signal,f=setTimeout(()=>{o.currentAbortController&&o.currentAbortController.abort()},8e3);try{const E=typeof window<"u"&&(window.location.origin.includes("localhost")||window.location.origin.includes("127.0.0.1")||window.location.origin.includes("[::1]"))?`${e}/proxy/sigef?url=${encodeURIComponent(h)}`:`${window.location.origin}/api.php?action=proxy_sigef&url=${encodeURIComponent(h)}`,M=await fetch(E,{signal:m});clearTimeout(f);let A=null;if(M.ok){const C=await M.text();try{A=JSON.parse(C)}catch{A=null}}if(A&&A.features&&A.features.length>0){const C=A.features[0],b=C.properties||{},v=String(C.id||b.parcela_codigo||b.co_parcela||b.id_parcela||""),P=String(b.nome_area||b.nome_imovel||"Imóvel Sem Nome");if(v){const w=encodeURIComponent(v),k=`https://sigef.incra.gov.br/geo/exportar/parcela/shp/${w}/`,L=`https://sigef.incra.gov.br/geo/parcela/detalhe/${w}/`,z=document.createElement("div");z.style.cssText="font-family:var(--ui-fonte-base, sans-serif); color:rgba(255, 255, 255, 0.9); line-height:1.4; min-width:180px;",z.innerHTML=`
10
10
  <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:6px; padding-bottom:5px; border-bottom:1px solid rgba(255, 255, 255, 0.1);">
11
11
  <span style="font-weight:700; font-size:11px; color:#10b981; text-transform:uppercase; letter-spacing:0.5px;">SIGEF</span>
12
- <span style="font-size:10px; color:rgba(255, 255, 255, 0.5);">${S.escapeHtml(P.situacao_informada||P.status||"Certificada")}</span>
12
+ <span style="font-size:10px; color:rgba(255, 255, 255, 0.5);">${S.escapeHtml(b.situacao_informada||b.status||"Certificada")}</span>
13
13
  </div>
14
- <div style="font-weight:700; font-size:12px; margin-bottom:4px; color:#ffffff; word-break:break-word;">${S.escapeHtml(b)}</div>
15
- <div style="font-size:11px; color:rgba(255, 255, 255, 0.7); margin-bottom:2px;">Cód: <span style="font-family:var(--ui-fonte-codigo, monospace);">${S.escapeHtml(P.codigo_imovel||"N/A")}</span></div>
14
+ <div style="font-weight:700; font-size:12px; margin-bottom:4px; color:#ffffff; word-break:break-word;">${S.escapeHtml(P)}</div>
15
+ <div style="font-size:11px; color:rgba(255, 255, 255, 0.7); margin-bottom:2px;">Cód: <span style="font-family:var(--ui-fonte-codigo, monospace);">${S.escapeHtml(b.codigo_imovel||"N/A")}</span></div>
16
16
  <div style="display:flex; gap:12px; font-size:11px; color:rgba(255, 255, 255, 0.7); margin-bottom:6px;">
17
- <span>Mat: <strong style="color:#ffffff;">${S.escapeHtml(P.registro_matricula||P.matricula||"N/A")}</strong></span>
18
- <span>${S.escapeHtml(P.data_submissao||"")}</span>
17
+ <span>Mat: <strong style="color:#ffffff;">${S.escapeHtml(b.registro_matricula||b.matricula||"N/A")}</strong></span>
18
+ <span>${S.escapeHtml(b.data_submissao||"")}</span>
19
19
  </div>
20
20
  <div style="display:flex; flex-direction:column; gap:5px; padding-top:6px; border-top:1px solid rgba(255, 255, 255, 0.1);">
21
- <a href="${E}" target="_blank" rel="noopener noreferrer" style="display:flex; align-items:center; justify-content:center; gap:5px; padding:5px 8px; background:rgba(16, 185, 129, 0.15); border:1px solid rgba(16, 185, 129, 0.3); color:#34d399; font-size:11px; font-weight:700; border-radius:5px; text-decoration:none; cursor:pointer;">
21
+ <a href="${k}" target="_blank" rel="noopener noreferrer" style="display:flex; align-items:center; justify-content:center; gap:5px; padding:5px 8px; background:rgba(16, 185, 129, 0.15); border:1px solid rgba(16, 185, 129, 0.3); color:#34d399; font-size:11px; font-weight:700; border-radius:5px; text-decoration:none; cursor:pointer;">
22
22
  <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
23
23
  Baixar Shapefile
24
24
  </a>
@@ -31,107 +31,107 @@
31
31
  Abrir no SIGEF
32
32
  </a>
33
33
  </div>
34
- `;const I=w.querySelector(".btn-importar-confrontante-sigef");I&&I.addEventListener("click",()=>{window.dispatchEvent(new CustomEvent("gerencigeo:importar_vizinho_sigef",{detail:{uuid:v,nome:b}}))}),m.setContent(w)}else m.setContent(`
34
+ `;const I=z.querySelector(".btn-importar-confrontante-sigef");I&&I.addEventListener("click",()=>{window.dispatchEvent(new CustomEvent("gerencigeo:importar_vizinho_sigef",{detail:{uuid:v,nome:P}}))}),g.setContent(z)}else g.setContent(`
35
35
  <div style="font-family:var(--ui-fonte-base, sans-serif); font-size:12px; color:#b45309; padding:2px 0;">
36
36
  Lote identificado, mas código da parcela indisponível.
37
37
  </div>
38
- `)}else m.setContent(`
38
+ `)}else g.setContent(`
39
39
  <div style="font-family:var(--ui-fonte-base, sans-serif); font-size:12px; color:rgba(255, 255, 255, 0.7); padding:2px 0;">
40
40
  Nenhum imóvel SIGEF certificado neste ponto.
41
41
  </div>
42
- `)}catch(x){x.name==="AbortError"?m.setContent(`
42
+ `)}catch(x){x.name==="AbortError"?g.setContent(`
43
43
  <div style="font-family:var(--ui-fonte-base, sans-serif); font-size:12px; color:#f59e0b; padding:2px 0;">
44
44
  Consulta cancelada ou tempo limite de resposta esgotado.
45
45
  </div>
46
- `):(console.warn("Erro ao consultar SIGEF:",x),m.setContent(`
46
+ `):(console.warn("Erro ao consultar SIGEF:",x),g.setContent(`
47
47
  <div style="font-family:var(--ui-fonte-base, sans-serif); font-size:12px; color:#f59e0b; padding:2px 0;">
48
48
  Serviço de consulta SIGEF indisponível nesta área.
49
49
  </div>
50
- `))}finally{u.style.cursor=""}}function on(n,t){if(!n)return;const e=Math.floor(n.getZoom()),o=Math.max(e,12),i=Math.min(e+1,19),a=t.pad(.2),s=["mt0","mt1","mt2","mt3"];let r=0;const c=32;for(let l=o;l<=i&&r<c;l++){const d=a.getNorthWest(),h=a.getSouthEast(),u=We(d.lng,l),m=We(h.lng,l),f=Xe(d.lat,l),g=Xe(h.lat,l);for(let x=u;x<=m&&r<c;x++)for(let A=f;A<=g&&r<c;A++){const C=`https://${s[(x+A)%s.length]}.google.com/vt/lyrs=s,h&x=${x}&y=${A}&z=${l}`,z=new Image;z.src=C,r++}}}function We(n,t){return Math.floor((n+180)/360*Math.pow(2,t))}function Xe(n,t){const e=n*Math.PI/180;return Math.floor((1-Math.log(Math.tan(e)+1/Math.cos(e))/Math.PI)/2*Math.pow(2,t))}class Ao{constructor(t){p(this,"map",null);p(this,"configManager",jt.getInstance());p(this,"config",this.configManager.getConfig());p(this,"apiBaseUrl","/api");p(this,"bancoPontosGroup",y.layerGroup());p(this,"pontosVizinhosGroup",y.layerGroup());p(this,"controller");p(this,"containerElement",null);p(this,"bc");p(this,"sigefState",{});this.controller=t}init(t){if(this.map)try{this.map.off(),this.map.remove()}catch{}finally{this.map=null}const e=typeof t=="string"?document.getElementById(t):t;if(!e)return null;if(this.containerElement=e,e._leaflet_id)try{delete e._leaflet_id}catch{e._leaflet_id=void 0}if(this.map=y.map(e,{maxZoom:24,scrollWheelZoom:!0,preferCanvas:this.config.preferCanvas!==void 0?this.config.preferCanvas:!0,zoomControl:!1}).setView([-23.7661,-53.3204],14),this.listenConfigBroadcast(),this.applyMapStyles(),!this.map.getPane("sigefPane")){const o=this.map.createPane("sigefPane");o.style.zIndex="390"}if(!this.map.getPane("perimetroPane")){const o=this.map.createPane("perimetroPane");o.style.zIndex="520"}if(!this.map.getPane("verticesPane")){const o=this.map.createPane("verticesPane");o.style.zIndex="650"}return y.control.scale({metric:!0,imperial:!1,position:"bottomleft"}).addTo(this.map),this.map.on("click",o=>{if(this.controller.modoCliqueSequencialAtivo||this.controller.canvasInteracao&&this.controller.canvasInteracao.selectionHappened)return;(this.controller.layerManager?this.controller.layerManager.isLayerActiveAndSelectable("sigef"):!1)&&this.consultarSigef(o)}),setTimeout(()=>{this.invalidateSize()},250),this.map}invalidateSize(t=!1){var e,o;if(this.map)try{const i=(o=(e=this.map).getContainer)==null?void 0:o.call(e);if(!i||!i.parentNode)return;this.map.invalidateSize({animate:t,pan:!1})}catch{}}applyMapStyles(){const t=this.containerElement||document.getElementById("mapa-triagem");t&&(t.style.cursor=this.config.crosshair?"crosshair":"")}listenConfigBroadcast(){if(!(typeof BroadcastChannel>"u"))try{this.bc=new BroadcastChannel("gerencigeo_map_config"),this.bc.onmessage=t=>{t.data==="RELOAD_REQUIRED"&&(this.config=this.configManager.getConfig(),this.applyMapStyles(),window.dispatchEvent(new CustomEvent("gerencigeo:map_config_changed",{detail:this.config})))}}catch{}}destroy(){if(this.sigefState.currentAbortController&&(this.sigefState.currentAbortController.abort(),this.sigefState.currentAbortController=void 0),this.bc){try{this.bc.close()}catch{}this.bc=void 0}if(this.map)try{this.map.off(),this.map.remove()}catch{}finally{this.map=null}if(this.containerElement&&this.containerElement._leaflet_id)try{delete this.containerElement._leaflet_id}catch{this.containerElement._leaflet_id=void 0}}preCarregarTilesRegiao(t){on(this.map,t)}async consultarSigef(t){this.map&&await en(this.map,t,this.apiBaseUrl,this.sigefState)}}function Ze(n){if(!n)return!1;const t=n;return t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.tagName==="SELECT"||t.isContentEditable===!0}function Ie(n){var o,i;const t=(o=n==null?void 0:n.composedPath)==null?void 0:o.call(n)[0];if(t instanceof Element)return Ze(t);let e=typeof document>"u"?null:document.activeElement;for(;(i=e==null?void 0:e.shadowRoot)!=null&&i.activeElement;)e=e.shadowRoot.activeElement;return Ze(e)}const wo=["verticesPane","perimetroPane","overlayPane","markerPane","pane-vertices","pane-perimetro","pane-vizinhos","pane-homologados","pane-homologados-pontos"];class nn{constructor(t,e,o){p(this,"map");p(this,"mapContainer");p(this,"ctx");p(this,"selectionDiv",null);p(this,"isSelecting",!1);p(this,"selectStartPos",{x:0,y:0});p(this,"selectStartPoint",null);this.map=t,this.mapContainer=e,this.ctx=o,this.criarDivSelecao()}criarDivSelecao(){this.selectionDiv||(this.selectionDiv=document.createElement("div"),this.selectionDiv.className="cad-selection-box",this.selectionDiv.style.position="absolute",this.selectionDiv.style.zIndex="9999",this.selectionDiv.style.pointerEvents="none",this.selectionDiv.style.display="none",this.selectionDiv.style.borderRadius="2px",this.mapContainer.style.position="relative",this.mapContainer.appendChild(this.selectionDiv))}setPanesPointerEvents(t){wo.forEach(e=>{const o=this.map.getPane(e);o&&(o.style.pointerEvents=t)})}iniciarSelecao(t){const e=this.mapContainer.getBoundingClientRect(),o=t.clientX-e.left,i=t.clientY-e.top;this.isSelecting=!0,this.selectStartPos={x:o,y:i},this.selectStartPoint=this.map.mouseEventToContainerPoint(t),this.selectionDiv&&(this.selectionDiv.style.left=`${o}px`,this.selectionDiv.style.top=`${i}px`,this.selectionDiv.style.width="0px",this.selectionDiv.style.height="0px",this.selectionDiv.style.display="block"),this.setPanesPointerEvents("none")}atualizarSelecao(t){if(!this.isSelecting||!this.selectionDiv)return;const e=this.mapContainer.getBoundingClientRect(),o=t.clientX-e.left,i=t.clientY-e.top,a=Math.abs(o-this.selectStartPos.x),s=Math.abs(i-this.selectStartPos.y),r=Math.min(o,this.selectStartPos.x),c=Math.min(i,this.selectStartPos.y);this.selectionDiv.style.left=`${Math.round(r)}px`,this.selectionDiv.style.top=`${Math.round(c)}px`,this.selectionDiv.style.width=`${Math.round(a)}px`,this.selectionDiv.style.height=`${Math.round(s)}px`,o>=this.selectStartPos.x?(this.selectionDiv.style.background="rgba(14, 116, 144, 0.22)",this.selectionDiv.style.border="1px solid #06b6d4"):(this.selectionDiv.style.background="rgba(16, 185, 129, 0.22)",this.selectionDiv.style.border="1px dashed #10b981")}finalizarSelecao(t,e,o){var M,C,z,P,v,b,k,E,L;if(!this.isSelecting)return!1;this.isSelecting=!1,this.selectionDiv&&(this.selectionDiv.style.display="none"),this.map.closePopup();try{this.setPanesPointerEvents("auto"),(M=this.ctx.layerManager)==null||M.ensurePanes()}catch{}const i=this.mapContainer.getBoundingClientRect(),a=t.clientX-i.left,s=t.clientY-i.top,r=this.map.mouseEventToContainerPoint(t),c=Math.abs(a-this.selectStartPos.x),l=Math.abs(s-this.selectStartPos.y);if(c<4&&l<4){const w=t.target;if(w&&((C=w.classList)!=null&&C.contains("leaflet-container")||w.id==="mapa-triagem"||(z=w.closest)!=null&&z.call(w,".leaflet-pane"))){const I=((P=w.closest)==null?void 0:P.call(w,".custom-leaflet-marker"))||((v=w.closest)==null?void 0:v.call(w,".custom-div-icon")),_=t.ctrlKey||t.metaKey||t.shiftKey;!I&&!_&&o()}return!1}if(!this.selectStartPoint)return!1;const d={x1:Math.min(this.selectStartPoint.x,r.x),y1:Math.min(this.selectStartPoint.y,r.y),x2:Math.max(this.selectStartPoint.x,r.x),y2:Math.max(this.selectStartPoint.y,r.y)},h=r.x>=this.selectStartPoint.x?"window":"crossing";(k=(b=this.ctx).selecionarFeicoesNaCaixa)==null||k.call(b,d,h,t.ctrlKey||t.metaKey);const u=((E=this.ctx.mapaController)==null?void 0:E.getMarkers())||[],m=((L=this.ctx.mapaController)==null?void 0:L.getVizinhosMarkers())||[],f=[],g=[],x=!this.ctx.layerManager||this.ctx.layerManager.isLayerActiveAndSelectable("vertices"),A=!this.ctx.layerManager||this.ctx.layerManager.isLayerActiveAndSelectable("vizinhos");return x&&u.forEach(w=>{const I=w.pontoId;if(!I)return;const _=this.map.latLngToContainerPoint(w.getLatLng());_.x>=d.x1&&_.x<=d.x2&&_.y>=d.y1&&_.y<=d.y2&&f.push(I)}),A&&m.forEach(w=>{const I=w.pontoId;if(!I)return;const _=this.map.latLngToContainerPoint(w.getLatLng());_.x>=d.x1&&_.x<=d.x2&&_.y>=d.y1&&_.y<=d.y2&&g.push(I)}),t.ctrlKey||t.metaKey?(f.forEach(w=>{this.ctx.selectedPontoIds.includes(w)?this.ctx.selectedPontoIds=this.ctx.selectedPontoIds.filter(I=>I!==w):this.ctx.selectedPontoIds.push(w)}),g.forEach(w=>{this.ctx.selectedVizinhoPontoIds.includes(w)?this.ctx.selectedVizinhoPontoIds=this.ctx.selectedVizinhoPontoIds.filter(I=>I!==w):this.ctx.selectedVizinhoPontoIds.push(w)})):(this.ctx.selectedPontoIds=f,this.ctx.selectedVizinhoPontoIds=g),this.ctx.selectedPontoIds.length>0&&(this.ctx.lastSelectedPontoId=this.ctx.selectedPontoIds[this.ctx.selectedPontoIds.length-1]),e(),!0}cancelarSelecao(){this.isSelecting&&(this.isSelecting=!1,this.selectionDiv&&(this.selectionDiv.style.display="none"),this.setPanesPointerEvents("auto"),this.ctx.layerManager&&this.ctx.layerManager.ensurePanes())}destruir(){this.selectionDiv&&this.selectionDiv.parentNode&&(this.selectionDiv.parentNode.removeChild(this.selectionDiv),this.selectionDiv=null),this.setPanesPointerEvents("auto")}}function xe(n){return`pane-${n}`}const ko=["poligono","linha","ponto","texto"];function zo(n,t){return`${xe(n)}-${t}`}function at(n,t,e){const o=n.getPane(xe(t))??n.createPane(xe(t)),i=zo(t,e);if(!n.getPane(i)){const a=n.createPane(i,o);a.style.zIndex=String((ko.indexOf(e)+1)*100)}return i}const Ye="ui-canvas-hit-test-estilo",Ot=6,Eo=4,an=4,Dt={poligono:1,linha:2,ponto:3,texto:3};function Io(n){var i;const t=n.getRootNode(),e=t instanceof ShadowRoot?t:document.head;if((i=e.querySelector)!=null&&i.call(e,`#${Ye}`))return;const o=document.createElement("style");o.id=Ye,o.textContent=".leaflet-pane > canvas { pointer-events: none !important; }",e.appendChild(o)}function ne(n,t){var e,o;return t+(((e=n.options)==null?void 0:e.stroke)===!1?0:(((o=n.options)==null?void 0:o.weight)??0)/2)}function sn(n,t,e){let o=1/0;for(const i of n){for(let a=1;a<i.length;a++)o=Math.min(o,y.LineUtil.pointToSegmentDistance(t,i[a-1],i[a]));e&&i.length>2&&(o=Math.min(o,y.LineUtil.pointToSegmentDistance(t,i[i.length-1],i[0])))}return o}function rn(n){const t=n._pxBounds;return t?(t.max.x-t.min.x)*(t.max.y-t.min.y):0}function cn(n,t,e){var o,i,a;if(!((o=n.options)!=null&&o.interactive))return null;if(n._point&&n._radius!==void 0){const s=n._radius,r=n._radiusY??n._radius,c=n._point.distanceTo(t),l=(s+r)/2,d=e==="ponto"?Eo:ne(n,Ot);return n.options.fill!==!1&&e==="poligono"?c<=l+1?0:null:e==="ponto"?c<=l+d?c:null:Math.abs(c-l)<=d?Math.abs(c-l):null}if(n._parts){const s=n instanceof y.Polygon,r=sn(n._parts,t,s);return e==="linha"?r<=ne(n,Ot)?r:null:s&&((i=n._containsPoint)!=null&&i.call(n,t))?0:r<=ne(n,Ot)?r:null}return(a=n._containsPoint)!=null&&a.call(n,t)?0:null}function ln(n){const t=[];for(let e=n._drawFirst;e;e=e.next)t.push(e.layer);return t}function _e(n,t,e){const o=n._paneRenderers;if(!o)return[];const i=t.filter(s=>s.visivel&&s.interativo&&!s.bloqueada).sort((s,r)=>r.zIndex-s.zIndex),a=[];for(const s of i)for(const r of ko){const c=o[zo(s.id,r)];if(c)for(const l of ln(c).reverse()){const d=cn(l,e,r);d!==null&&a.push({camada:s,tipo:r,alvo:l,distancia:d,area:rn(l)})}}return a.sort((s,r)=>Dt[s.tipo]!==Dt[r.tipo]?Dt[r.tipo]-Dt[s.tipo]:s.camada.zIndex!==r.camada.zIndex?r.camada.zIndex-s.camada.zIndex:s.tipo==="poligono"&&s.area!==r.area?s.area-r.area:0)}const be=new WeakMap;function dn(n,t,e){const o=e.map(s=>y.Util.stamp(s.alvo)),i=be.get(n);let a=0;return i&&Math.hypot(i.x-t.x,i.y-t.y)<=an&&i.ids.length===o.length&&i.ids.every((s,r)=>s===o[r])&&(a=(i.indice+1)%e.length),be.set(n,{x:t.x,y:t.y,ids:o,indice:a}),e[a]}function _o(n,t,e){const o=n.mouseEventToLayerPoint(e),i=_e(n,t,o);return i.length===0?(be.delete(n),!1):(dn(n,o,i).alvo.fire(e.type,{originalEvent:e,latlng:n.mouseEventToLatLng(e),layerPoint:o,containerPoint:n.mouseEventToContainerPoint(e)},!0),!0)}function hn(n,t,e){return _e(n,t,n.mouseEventToLayerPoint(e))[0]??null}class To{constructor(t){p(this,"ctx");p(this,"map",null);p(this,"mapContainer",null);p(this,"selecaoBox",null);p(this,"isPanning",!1);p(this,"lastMousePos",{x:0,y:0});p(this,"lastMiddleClickTime",0);p(this,"touchStartPos",{x:0,y:0});p(this,"touchStartDist",0);p(this,"isTouchPanning",!1);p(this,"removerSupressao",null);p(this,"selectionHappened",!1);p(this,"panHappened",!1);p(this,"handleTouchStart",t=>{if(!(!this.map||!this.mapContainer)){if(t.touches.length===1)this.isTouchPanning=!0,this.touchStartPos={x:t.touches[0].clientX,y:t.touches[0].clientY};else if(t.touches.length===2){this.isTouchPanning=!1;const e=t.touches[0].clientX-t.touches[1].clientX,o=t.touches[0].clientY-t.touches[1].clientY;this.touchStartDist=Math.hypot(e,o)}}});p(this,"handleTouchMove",t=>{if(!(!this.map||!this.mapContainer)){if(t.touches.length===1&&this.isTouchPanning){t.preventDefault(),this.panHappened=!0;const e=this.touchStartPos.x-t.touches[0].clientX,o=this.touchStartPos.y-t.touches[0].clientY;this.map.panBy([e,o],{animate:!1}),this.touchStartPos={x:t.touches[0].clientX,y:t.touches[0].clientY}}else if(t.touches.length===2&&this.touchStartDist>0){t.preventDefault(),this.panHappened=!0;const e=t.touches[0].clientX-t.touches[1].clientX,o=t.touches[0].clientY-t.touches[1].clientY,i=Math.hypot(e,o);Math.abs(i-this.touchStartDist)>25&&(i>this.touchStartDist?this.map.zoomIn(1):this.map.zoomOut(1),this.touchStartDist=i)}}});p(this,"handleTouchEnd",()=>{this.isTouchPanning=!1,this.touchStartDist=0,setTimeout(()=>{this.panHappened=!1},120)});p(this,"handleContextMenu",t=>{var e,o;t.preventDefault(),(o=(e=this.ctx).aoMenuContexto)==null||o.call(e,t)});p(this,"handleClick",t=>{var e,o,i,a;!this.map||!this.ctx.layerManager||(o=(e=this.ctx).ferramentaAtiva)!=null&&o.call(e)||(a=(i=t.target)==null?void 0:i.closest)!=null&&a.call(i,".leaflet-marker-icon")||_o(this.map,this.ctx.layerManager.getLayers(),t)});p(this,"handleMouseDown",t=>{var e,o,i,a,s;if(!(!this.map||!this.mapContainer)){if(this.cancelarSupressaoClique(),t.button===1){t.preventDefault();const r=Date.now();if(r-this.lastMiddleClickTime<300){this.zoomExtents();return}this.lastMiddleClickTime=r,this.isPanning=!0,this.panHappened=!1,this.lastMousePos={x:t.clientX,y:t.clientY},this.mapContainer.style.cursor="grabbing";return}if(t.button===0){if((o=(e=t.target)==null?void 0:e.closest)!=null&&o.call(e,".cad-vertex-handle, .cad-vertex-ghost, #cm-vertex-edit-hud, #cm-draw-hud")||(a=(i=this.ctx).ferramentaAtiva)!=null&&a.call(i)||(this.selectionHappened=!1,this.ctx.mapaController&&this.ctx.mapaController.modoCliqueSequencialAtivo))return;(s=this.selecaoBox)==null||s.iniciarSelecao(t)}}});p(this,"handleMouseMove",t=>{var e;if(!(!this.map||!this.mapContainer)){if(this.isPanning){const o=this.lastMousePos.x-t.clientX,i=this.lastMousePos.y-t.clientY;(Math.abs(o)>1||Math.abs(i)>1)&&(this.panHappened=!0),this.map.panBy([o,i],{animate:!1}),this.lastMousePos={x:t.clientX,y:t.clientY};return}(e=this.selecaoBox)==null||e.atualizarSelecao(t)}});p(this,"handleMouseUp",t=>{this.isPanning&&(this.isPanning=!1,this.mapContainer&&(this.mapContainer.style.cursor="grab"),setTimeout(()=>{this.panHappened=!1},120)),this.selecaoBox&&this.selecaoBox.isSelecting&&this.selecaoBox.finalizarSelecao(t,()=>this.notificarSelecao(),()=>this.limparSelecao())&&(this.selectionHappened=!0,this.suprimirProximoClique())});p(this,"handleKeyDown",t=>{var e;if(t.key==="Escape"){if(Ie(t))return;(e=this.selecaoBox)==null||e.cancelarSelecao(),this.limparSelecao()}});this.ctx={selectedPontoIds:[],selectedVizinhoPontoIds:[],lastSelectedPontoId:null,pontosList:[],...t}}ativar(t,e){this.ctx.mapaController=t,e&&(this.ctx.containerHost=e),this.map=t.getMap(),this.map&&(this.mapContainer=this.map.getContainer(),this.mapContainer&&(this.map.dragging.disable(),this.map.doubleClickZoom.disable(),this.selecaoBox=new nn(this.map,this.mapContainer,this.ctx),Io(this.mapContainer),this.mapContainer.addEventListener("click",this.handleClick),this.mapContainer.addEventListener("mousedown",this.handleMouseDown),this.mapContainer.addEventListener("mousemove",this.handleMouseMove),window.addEventListener("mouseup",this.handleMouseUp),this.mapContainer.addEventListener("contextmenu",this.handleContextMenu),window.addEventListener("keydown",this.handleKeyDown),this.mapContainer.addEventListener("touchstart",this.handleTouchStart,{passive:!1}),this.mapContainer.addEventListener("touchmove",this.handleTouchMove,{passive:!1}),this.mapContainer.addEventListener("touchend",this.handleTouchEnd),this.mapContainer.addEventListener("touchcancel",this.handleTouchEnd)))}desativar(){this.mapContainer&&(this.mapContainer.removeEventListener("click",this.handleClick),this.mapContainer.removeEventListener("mousedown",this.handleMouseDown),this.mapContainer.removeEventListener("mousemove",this.handleMouseMove),this.mapContainer.removeEventListener("contextmenu",this.handleContextMenu),this.mapContainer.removeEventListener("touchstart",this.handleTouchStart),this.mapContainer.removeEventListener("touchmove",this.handleTouchMove),this.mapContainer.removeEventListener("touchend",this.handleTouchEnd),this.mapContainer.removeEventListener("touchcancel",this.handleTouchEnd)),window.removeEventListener("mouseup",this.handleMouseUp),window.removeEventListener("keydown",this.handleKeyDown),this.cancelarSupressaoClique(),this.selecaoBox&&(this.selecaoBox.destruir(),this.selecaoBox=null),this.map&&(this.map.dragging.enable(),this.map.doubleClickZoom.enable())}suprimirProximoClique(){this.cancelarSupressaoClique(),this.removerSupressao=()=>window.removeEventListener("click",t,!0);const t=e=>{e.stopImmediatePropagation(),e.preventDefault(),this.cancelarSupressaoClique()};window.addEventListener("click",t,!0)}cancelarSupressaoClique(){var t;(t=this.removerSupressao)==null||t.call(this),this.removerSupressao=null}limparSelecao(){var t,e,o,i;(e=(t=this.ctx).aoLimparSelecao)==null||e.call(t),this.ctx.mapaController&&this.ctx.mapaController.context.selectedSegmentoId&&this.ctx.mapaController.selectSegmento(null),(this.ctx.selectedPontoIds.length>0||this.ctx.selectedVizinhoPontoIds.length>0)&&(this.ctx.selectedPontoIds=[],this.ctx.selectedVizinhoPontoIds=[],this.ctx.lastSelectedPontoId=null,this.ctx.mapaController&&(this.ctx.mapaController.context.selectedPontoIds=[],(i=(o=this.ctx.mapaController).atualizarDestaqueMarcadores)==null||i.call(o)),this.notificarSelecao())}notificarSelecao(){var t,e;this.ctx.mapaController&&(this.ctx.mapaController.context.selectedPontoIds=[...this.ctx.selectedPontoIds],(e=(t=this.ctx.mapaController).atualizarDestaqueMarcadores)==null||e.call(t)),this.ctx.atualizarDestaqueLinhasTabela&&this.ctx.atualizarDestaqueLinhasTabela(),this.ctx.onSelectionChange&&this.ctx.onSelectionChange(this.ctx.selectedPontoIds,this.ctx.selectedVizinhoPontoIds),window.dispatchEvent(new CustomEvent("gerencigeo:ponto-selecionado",{detail:{selectedPontoIds:this.ctx.selectedPontoIds,selectedVizinhoPontoIds:this.ctx.selectedVizinhoPontoIds,lastSelectedPontoId:this.ctx.lastSelectedPontoId}}))}zoomExtents(){if(!this.ctx.pontosList||this.ctx.pontosList.length===0)return;const t=this.ctx.pontosList.filter(e=>e.tipo_ponto!=="B"&&e.tipo!=="B");t.length>0&&this.ctx.mapaController&&this.ctx.mapaController.fitBounds(t)}destroy(){this.desativar()}}class F{static register(t,e){this.renderers.set(t.toLowerCase(),e)}static get(t){return this.renderers.get(t.toLowerCase())}static has(t){return this.renderers.has(t.toLowerCase())}static getRegisteredTypes(){return Array.from(this.renderers.keys())}}p(F,"renderers",new Map);class Do{render(t,e,o){var c,l,d;const i=((c=t.dados)==null?void 0:c.url)||"https://{s}.google.com/vt/lyrs=s,h&x={x}&y={y}&z={z}",a=((l=t.dados)==null?void 0:l.subdomains)||["mt0","mt1","mt2","mt3"],s=((d=t.dados)==null?void 0:d.attribution)||"Google Satélite";return y.tileLayer(i,{maxZoom:24,maxNativeZoom:20,subdomains:a,attribution:s,keepBuffer:16,updateWhenZooming:!1,updateWhenIdle:!0,className:"smooth-zoom-layer",opacity:t.opacidade!==void 0?t.opacidade:1,pane:`pane-${t.id}`})}update(t,e,o){e instanceof y.TileLayer&&o.opacidade!==void 0&&e.setOpacity(o.opacidade)}destroy(t,e){e.hasLayer(t)&&e.removeLayer(t)}}class $o{render(t,e,o){var l,d,h,u;const i=((l=t.dados)==null?void 0:l.url)||"https://acervofundiario.incra.gov.br/i3geo/ogc.php",a=((d=t.dados)==null?void 0:d.layers)||"certificada_sigef_particular_pr",s=((h=t.dados)==null?void 0:h.format)||"image/png",r=((u=t.dados)==null?void 0:u.attribution)||"INCRA/SIGEF";return y.tileLayer.wms(i,{layers:a,format:s,transparent:!0,version:"1.1.1",pane:`pane-${t.id}`,attribution:r,className:"sigef-wms-layer",keepBuffer:8,updateWhenZooming:!1,updateWhenIdle:!0,opacity:t.opacidade!==void 0?t.opacidade:.85})}update(t,e,o){e instanceof y.TileLayer.WMS&&o.opacidade!==void 0&&e.setOpacity(o.opacidade)}destroy(t,e){e.hasLayer(t)&&e.removeLayer(t)}}function qo(n,t,e){const o=n.estilo.espessuraLinha||e.config.perimetroWeight||2,i=e.graphicScale.lineScaleMultiplier||1;if(n.estilo.scaleMode==="world"){const a=n.estilo.dimensaoMetros||.3,s=t.getCenter(),r=t.getZoom(),c=40075016686e-3*Math.abs(Math.cos(s.lat*Math.PI/180))/Math.pow(2,r+8),l=a/(c>0?c:1);return Math.max(1,Math.round(l*i))}return Math.max(1,Math.round(o*i))}function ut(n,t,e,o,i){const a=Math.max(Math.round(e+3),4);y.polyline(t,{color:"#080d0a",weight:a,opacity:.85,lineCap:"round",lineJoin:"round",dashArray:i,pane:o,interactive:!1}).addTo(n)}function Ke(n,t,e,o,i){var f,g,x,A,M,C,z,P;const a=n.id==="homologados",s=((f=n.dados)==null?void 0:f.conexoes)??(Array.isArray(n.dados)&&n.dados.length>0&&"origemId"in n.dados[0]?n.dados:null),r=((g=n.dados)==null?void 0:g.segmentos)||o.segmentos||[],c=((x=n.dados)==null?void 0:x.pontos)||(a?o.bancoPontos||[]:o.pontos)||[],l=qo(n,e,o),d=n.opacidade!==void 0?n.opacidade:1,h=n.interativo&&!n.bloqueada,u=[];c.forEach(v=>{const b=S.parseCoordenada(v.lat??v.latitude??v.y,v.lon??v.lng??v.longitude??v.x);b&&u.push({...v,lat:b.lat,lon:b.lon})});const m=v=>{const b=u.find(k=>String(k.id)===String(v));if(b)return b;if(o.pontos){const k=o.pontos.find(E=>String(E.id)===String(v));if(k){const E=S.parseCoordenada(k.lat,k.lon);if(E)return{...k,lat:E.lat,lon:E.lon}}}return null};if(s&&Array.isArray(s)){s.forEach(v=>{var E,L,w,I,_,O,T;const b=m(v.origemId),k=m(v.destinoId);if(b&&k&&b.lat&&b.lon&&k.lat&&k.lon){const W=v.tipoLinha==="tracejada"||((E=v.estilo)==null?void 0:E.tipoLinha)==="tracejada",D=((L=v.estilo)==null?void 0:L.cor)||((w=v.estilo)==null?void 0:w.color)||n.estilo.corPrimaria||"#00f5a0",N=((I=v.estilo)==null?void 0:I.espessura)||((_=v.estilo)==null?void 0:_.weight)||l,$=[[b.lat,b.lon],[k.lat,k.lon]],R=W?"6, 6":n.estilo.dashArray;ut(t,$,N,i,R);const q=y.polyline($,{color:D,weight:N,opacity:((O=v.estilo)==null?void 0:O.opacidade)??d,dashArray:R,pane:i,interactive:h});if(h){const B=v.acoes||n.acoes||((T=n.dados)==null?void 0:T.acoes)||[],V=`${v.origemId}-${v.destinoId}`,J=S.renderPopupAcoesHtml(B,V);q.bindPopup(`
50
+ `))}finally{u.style.cursor=""}}function na(a,t){if(!a)return;const e=Math.floor(a.getZoom()),o=Math.max(e,12),i=Math.min(e+1,19),n=t.pad(.2),s=["mt0","mt1","mt2","mt3"];let r=0;const c=32;for(let l=o;l<=i&&r<c;l++){const d=n.getNorthWest(),h=n.getSouthEast(),u=Je(d.lng,l),g=Je(h.lng,l),m=Qe(d.lat,l),f=Qe(h.lat,l);for(let x=u;x<=g&&r<c;x++)for(let E=m;E<=f&&r<c;E++){const A=`https://${s[(x+E)%s.length]}.google.com/vt/lyrs=s,h&x=${x}&y=${E}&z=${l}`,C=new Image;C.src=A,r++}}}function Je(a,t){return Math.floor((a+180)/360*Math.pow(2,t))}function Qe(a,t){const e=a*Math.PI/180;return Math.floor((1-Math.log(Math.tan(e)+1/Math.cos(e))/Math.PI)/2*Math.pow(2,t))}class Io{constructor(t){p(this,"map",null);p(this,"configManager",Yt.getInstance());p(this,"config",this.configManager.getConfig());p(this,"apiBaseUrl","/api");p(this,"bancoPontosGroup",y.layerGroup());p(this,"pontosVizinhosGroup",y.layerGroup());p(this,"controller");p(this,"containerElement",null);p(this,"bc");p(this,"sigefState",{});this.controller=t}init(t){if(this.map)try{this.map.off(),this.map.remove()}catch{}finally{this.map=null}const e=typeof t=="string"?document.getElementById(t):t;if(!e)return null;if(this.containerElement=e,e._leaflet_id)try{delete e._leaflet_id}catch{e._leaflet_id=void 0}if(this.map=y.map(e,{maxZoom:24,scrollWheelZoom:!0,preferCanvas:this.config.preferCanvas!==void 0?this.config.preferCanvas:!0,zoomControl:!1}).setView([-23.7661,-53.3204],14),this.listenConfigBroadcast(),this.applyMapStyles(),!this.map.getPane("sigefPane")){const o=this.map.createPane("sigefPane");o.style.zIndex="390"}if(!this.map.getPane("perimetroPane")){const o=this.map.createPane("perimetroPane");o.style.zIndex="520"}if(!this.map.getPane("verticesPane")){const o=this.map.createPane("verticesPane");o.style.zIndex="650"}return y.control.scale({metric:!0,imperial:!1,position:"bottomleft"}).addTo(this.map),this.map.on("click",o=>{if(this.controller.modoCliqueSequencialAtivo||this.controller.canvasInteracao&&this.controller.canvasInteracao.selectionHappened)return;(this.controller.layerManager?this.controller.layerManager.isLayerActiveAndSelectable("sigef"):!1)&&this.consultarSigef(o)}),setTimeout(()=>{this.invalidateSize()},250),this.map}invalidateSize(t=!1){var e,o;if(this.map)try{const i=(o=(e=this.map).getContainer)==null?void 0:o.call(e);if(!i||!i.parentNode)return;this.map.invalidateSize({animate:t,pan:!1})}catch{}}applyMapStyles(){const t=this.containerElement||document.getElementById("mapa-triagem");t&&(t.style.cursor=this.config.crosshair?"crosshair":"")}listenConfigBroadcast(){if(!(typeof BroadcastChannel>"u"))try{this.bc=new BroadcastChannel("gerencigeo_map_config"),this.bc.onmessage=t=>{t.data==="RELOAD_REQUIRED"&&(this.config=this.configManager.getConfig(),this.applyMapStyles(),window.dispatchEvent(new CustomEvent("gerencigeo:map_config_changed",{detail:this.config})))}}catch{}}destroy(){if(this.sigefState.currentAbortController&&(this.sigefState.currentAbortController.abort(),this.sigefState.currentAbortController=void 0),this.bc){try{this.bc.close()}catch{}this.bc=void 0}if(this.map)try{this.map.off(),this.map.remove()}catch{}finally{this.map=null}if(this.containerElement&&this.containerElement._leaflet_id)try{delete this.containerElement._leaflet_id}catch{this.containerElement._leaflet_id=void 0}}preCarregarTilesRegiao(t){na(this.map,t)}async consultarSigef(t){this.map&&await aa(this.map,t,this.apiBaseUrl,this.sigefState)}}function to(a){if(!a)return!1;const t=a;return t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.tagName==="SELECT"||t.isContentEditable===!0}function Dt(a){var o,i;const t=(o=a==null?void 0:a.composedPath)==null?void 0:o.call(a)[0];if(t instanceof Element)return to(t);let e=typeof document>"u"?null:document.activeElement;for(;(i=e==null?void 0:e.shadowRoot)!=null&&i.activeElement;)e=e.shadowRoot.activeElement;return to(e)}const _o=["verticesPane","perimetroPane","overlayPane","markerPane","pane-vertices","pane-perimetro","pane-vizinhos","pane-homologados","pane-homologados-pontos"];class sa{constructor(t,e,o){p(this,"map");p(this,"mapContainer");p(this,"ctx");p(this,"selectionDiv",null);p(this,"isSelecting",!1);p(this,"selectStartPos",{x:0,y:0});p(this,"selectStartPoint",null);this.map=t,this.mapContainer=e,this.ctx=o,this.criarDivSelecao()}criarDivSelecao(){this.selectionDiv||(this.selectionDiv=document.createElement("div"),this.selectionDiv.className="cad-selection-box",this.selectionDiv.style.position="absolute",this.selectionDiv.style.zIndex="9999",this.selectionDiv.style.pointerEvents="none",this.selectionDiv.style.display="none",this.selectionDiv.style.borderRadius="2px",this.mapContainer.style.position="relative",this.mapContainer.appendChild(this.selectionDiv))}setPanesPointerEvents(t){_o.forEach(e=>{const o=this.map.getPane(e);o&&(o.style.pointerEvents=t)})}iniciarSelecao(t){const e=this.mapContainer.getBoundingClientRect(),o=t.clientX-e.left,i=t.clientY-e.top;this.isSelecting=!0,this.selectStartPos={x:o,y:i},this.selectStartPoint=this.map.mouseEventToContainerPoint(t),this.selectionDiv&&(this.selectionDiv.style.left=`${o}px`,this.selectionDiv.style.top=`${i}px`,this.selectionDiv.style.width="0px",this.selectionDiv.style.height="0px",this.selectionDiv.style.display="block"),this.setPanesPointerEvents("none")}atualizarSelecao(t){if(!this.isSelecting||!this.selectionDiv)return;const e=this.mapContainer.getBoundingClientRect(),o=t.clientX-e.left,i=t.clientY-e.top,n=Math.abs(o-this.selectStartPos.x),s=Math.abs(i-this.selectStartPos.y),r=Math.min(o,this.selectStartPos.x),c=Math.min(i,this.selectStartPos.y);this.selectionDiv.style.left=`${Math.round(r)}px`,this.selectionDiv.style.top=`${Math.round(c)}px`,this.selectionDiv.style.width=`${Math.round(n)}px`,this.selectionDiv.style.height=`${Math.round(s)}px`,o>=this.selectStartPos.x?(this.selectionDiv.style.background="rgba(14, 116, 144, 0.22)",this.selectionDiv.style.border="1px solid #06b6d4"):(this.selectionDiv.style.background="rgba(16, 185, 129, 0.22)",this.selectionDiv.style.border="1px dashed #10b981")}finalizarSelecao(t,e,o){var M,A,C,b,v,P,w,k,L;if(!this.isSelecting)return!1;this.isSelecting=!1,this.selectionDiv&&(this.selectionDiv.style.display="none"),this.map.closePopup();try{this.setPanesPointerEvents("auto"),(M=this.ctx.layerManager)==null||M.ensurePanes()}catch{}const i=this.mapContainer.getBoundingClientRect(),n=t.clientX-i.left,s=t.clientY-i.top,r=this.map.mouseEventToContainerPoint(t),c=Math.abs(n-this.selectStartPos.x),l=Math.abs(s-this.selectStartPos.y);if(c<4&&l<4){const z=t.target;if(z&&((A=z.classList)!=null&&A.contains("leaflet-container")||z.id==="mapa-triagem"||(C=z.closest)!=null&&C.call(z,".leaflet-pane"))){const I=((b=z.closest)==null?void 0:b.call(z,".custom-leaflet-marker"))||((v=z.closest)==null?void 0:v.call(z,".custom-div-icon")),_=t.ctrlKey||t.metaKey||t.shiftKey;!I&&!_&&o()}return!1}if(!this.selectStartPoint)return!1;const d={x1:Math.min(this.selectStartPoint.x,r.x),y1:Math.min(this.selectStartPoint.y,r.y),x2:Math.max(this.selectStartPoint.x,r.x),y2:Math.max(this.selectStartPoint.y,r.y)},h=r.x>=this.selectStartPoint.x?"window":"crossing";(w=(P=this.ctx).selecionarFeicoesNaCaixa)==null||w.call(P,d,h,t.ctrlKey||t.metaKey);const u=((k=this.ctx.mapaController)==null?void 0:k.getMarkers())||[],g=((L=this.ctx.mapaController)==null?void 0:L.getVizinhosMarkers())||[],m=[],f=[],x=!this.ctx.layerManager||this.ctx.layerManager.isLayerActiveAndSelectable("vertices"),E=!this.ctx.layerManager||this.ctx.layerManager.isLayerActiveAndSelectable("vizinhos");return x&&u.forEach(z=>{const I=z.pontoId;if(!I)return;const _=this.map.latLngToContainerPoint(z.getLatLng());_.x>=d.x1&&_.x<=d.x2&&_.y>=d.y1&&_.y<=d.y2&&m.push(I)}),E&&g.forEach(z=>{const I=z.pontoId;if(!I)return;const _=this.map.latLngToContainerPoint(z.getLatLng());_.x>=d.x1&&_.x<=d.x2&&_.y>=d.y1&&_.y<=d.y2&&f.push(I)}),t.ctrlKey||t.metaKey?(m.forEach(z=>{this.ctx.selectedPontoIds.includes(z)?this.ctx.selectedPontoIds=this.ctx.selectedPontoIds.filter(I=>I!==z):this.ctx.selectedPontoIds.push(z)}),f.forEach(z=>{this.ctx.selectedVizinhoPontoIds.includes(z)?this.ctx.selectedVizinhoPontoIds=this.ctx.selectedVizinhoPontoIds.filter(I=>I!==z):this.ctx.selectedVizinhoPontoIds.push(z)})):(this.ctx.selectedPontoIds=m,this.ctx.selectedVizinhoPontoIds=f),this.ctx.selectedPontoIds.length>0&&(this.ctx.lastSelectedPontoId=this.ctx.selectedPontoIds[this.ctx.selectedPontoIds.length-1]),e(),!0}cancelarSelecao(){this.isSelecting&&(this.isSelecting=!1,this.selectionDiv&&(this.selectionDiv.style.display="none"),this.setPanesPointerEvents("auto"),this.ctx.layerManager&&this.ctx.layerManager.ensurePanes())}destruir(){this.selectionDiv&&this.selectionDiv.parentNode&&(this.selectionDiv.parentNode.removeChild(this.selectionDiv),this.selectionDiv=null),this.setPanesPointerEvents("auto")}}function Me(a){return`pane-${a}`}const To=["poligono","linha","ponto","texto"];function Do(a,t){return`${Me(a)}-${t}`}function st(a,t,e){const o=a.getPane(Me(t))??a.createPane(Me(t)),i=Do(t,e);if(!a.getPane(i)){const n=a.createPane(i,o);n.style.zIndex=String((To.indexOf(e)+1)*100)}return i}const eo="ui-canvas-hit-test-estilo",Vt=6,$o=4,qo=4,Nt={poligono:1,linha:2,ponto:3,texto:3};function No(a){var i;const t=a.getRootNode(),e=t instanceof ShadowRoot?t:document.head;if((i=e.querySelector)!=null&&i.call(e,`#${eo}`))return;const o=document.createElement("style");o.id=eo,o.textContent=".leaflet-pane > canvas { pointer-events: none !important; }",e.appendChild(o)}function de(a,t){var e,o;return t+(((e=a.options)==null?void 0:e.stroke)===!1?0:(((o=a.options)==null?void 0:o.weight)??0)/2)}function ra(a,t,e){let o=1/0;for(const i of a){for(let n=1;n<i.length;n++)o=Math.min(o,y.LineUtil.pointToSegmentDistance(t,i[n-1],i[n]));e&&i.length>2&&(o=Math.min(o,y.LineUtil.pointToSegmentDistance(t,i[i.length-1],i[0])))}return o}function ca(a){const t=a._pxBounds;return t?(t.max.x-t.min.x)*(t.max.y-t.min.y):0}function la(a,t,e){var o,i,n;if(!((o=a.options)!=null&&o.interactive))return null;if(a._point&&a._radius!==void 0){const s=a._radius,r=a._radiusY??a._radius,c=a._point.distanceTo(t),l=(s+r)/2,d=e==="ponto"?$o:de(a,Vt);return a.options.fill!==!1&&e==="poligono"?c<=l+1?0:null:e==="ponto"?c<=l+d?c:null:Math.abs(c-l)<=d?Math.abs(c-l):null}if(a._parts){const s=a instanceof y.Polygon,r=ra(a._parts,t,s);return e==="linha"?r<=de(a,Vt)?r:null:s&&((i=a._containsPoint)!=null&&i.call(a,t))?0:r<=de(a,Vt)?r:null}return(n=a._containsPoint)!=null&&n.call(a,t)?0:null}function da(a){const t=[];for(let e=a._drawFirst;e;e=e.next)t.push(e.layer);return t}function qe(a,t,e){const o=a._paneRenderers;if(!o)return[];const i=t.filter(s=>s.visivel&&s.interativo&&!s.bloqueada).sort((s,r)=>r.zIndex-s.zIndex),n=[];for(const s of i)for(const r of To){const c=o[Do(s.id,r)];if(c)for(const l of da(c).reverse()){const d=la(l,e,r);d!==null&&n.push({camada:s,tipo:r,alvo:l,distancia:d,area:ca(l)})}}return n.sort((s,r)=>Nt[s.tipo]!==Nt[r.tipo]?Nt[r.tipo]-Nt[s.tipo]:s.camada.zIndex!==r.camada.zIndex?r.camada.zIndex-s.camada.zIndex:s.tipo==="poligono"&&s.area!==r.area?s.area-r.area:0)}const Kt=new WeakMap;function ha(a,t,e){const o=e.map(s=>y.Util.stamp(s.alvo)),i=Kt.get(a);let n=0;return i&&Math.hypot(i.x-t.x,i.y-t.y)<=qo&&i.ids.length===o.length&&i.ids.every((s,r)=>s===o[r])&&(n=(i.indice+1)%e.length),Kt.set(a,{x:t.x,y:t.y,ids:o,indice:n}),e[n]}function ua(a,t,e){const o=Kt.get(a),i=!!o&&Math.hypot(o.x-t.x,o.y-t.y)<=qo&&o.ids.length===e.length;return e[i?o.indice:0]??e[0]}function Ae(a,t,e){const o=a.mouseEventToLayerPoint(e),i=qe(a,t,o);return i.length===0?(Kt.delete(a),!1):((e.type==="dblclick"?ua(a,o,i).alvo:ha(a,o,i).alvo).fire(e.type,{originalEvent:e,latlng:a.mouseEventToLatLng(e),layerPoint:o,containerPoint:a.mouseEventToContainerPoint(e)},!0),!0)}function pa(a,t,e){return qe(a,t,a.mouseEventToLayerPoint(e))[0]??null}const he=".cad-vertex-handle, .cad-vertex-ghost, .cad-bezier-handle, #cm-vertex-edit-hud, #cm-draw-hud";class Oo{constructor(t){p(this,"ctx");p(this,"map",null);p(this,"mapContainer",null);p(this,"selecaoBox",null);p(this,"isPanning",!1);p(this,"lastMousePos",{x:0,y:0});p(this,"lastMiddleClickTime",0);p(this,"touchStartPos",{x:0,y:0});p(this,"touchStartDist",0);p(this,"isTouchPanning",!1);p(this,"removerSupressao",null);p(this,"selectionHappened",!1);p(this,"panHappened",!1);p(this,"handleTouchStart",t=>{var e,o;if(!(!this.map||!this.mapContainer)){if(t.touches.length===1)this.isTouchPanning=!((o=(e=t.target)==null?void 0:e.closest)!=null&&o.call(e,he)),this.touchStartPos={x:t.touches[0].clientX,y:t.touches[0].clientY};else if(t.touches.length===2){this.isTouchPanning=!1;const i=t.touches[0].clientX-t.touches[1].clientX,n=t.touches[0].clientY-t.touches[1].clientY;this.touchStartDist=Math.hypot(i,n)}}});p(this,"handleTouchMove",t=>{if(!(!this.map||!this.mapContainer)){if(t.touches.length===1&&this.isTouchPanning){t.preventDefault(),this.panHappened=!0;const e=this.touchStartPos.x-t.touches[0].clientX,o=this.touchStartPos.y-t.touches[0].clientY;this.map.panBy([e,o],{animate:!1}),this.touchStartPos={x:t.touches[0].clientX,y:t.touches[0].clientY}}else if(t.touches.length===2&&this.touchStartDist>0){t.preventDefault(),this.panHappened=!0;const e=t.touches[0].clientX-t.touches[1].clientX,o=t.touches[0].clientY-t.touches[1].clientY,i=Math.hypot(e,o);Math.abs(i-this.touchStartDist)>25&&(i>this.touchStartDist?this.map.zoomIn(1):this.map.zoomOut(1),this.touchStartDist=i)}}});p(this,"handleTouchEnd",()=>{this.isTouchPanning=!1,this.touchStartDist=0,setTimeout(()=>{this.panHappened=!1},120)});p(this,"handleContextMenu",t=>{var e,o;t.preventDefault(),(o=(e=this.ctx).aoMenuContexto)==null||o.call(e,t)});p(this,"handleClick",t=>{var e,o,i,n;!this.map||!this.ctx.layerManager||(o=(e=this.ctx).ferramentaAtiva)!=null&&o.call(e)||(n=(i=t.target)==null?void 0:i.closest)!=null&&n.call(i,".leaflet-marker-icon")||Ae(this.map,this.ctx.layerManager.getLayers(),t)});p(this,"handleDblClick",t=>{var e,o,i,n;!this.map||!this.ctx.layerManager||(o=(e=this.ctx).ferramentaAtiva)!=null&&o.call(e)||(n=(i=t.target)==null?void 0:i.closest)!=null&&n.call(i,`.leaflet-marker-icon, ${he}`)||Ae(this.map,this.ctx.layerManager.getLayers(),t)});p(this,"handleMouseDown",t=>{var e,o,i,n,s;if(!(!this.map||!this.mapContainer)){if(this.cancelarSupressaoClique(),t.button===1){t.preventDefault();const r=Date.now();if(r-this.lastMiddleClickTime<300){this.zoomExtents();return}this.lastMiddleClickTime=r,this.isPanning=!0,this.panHappened=!1,this.lastMousePos={x:t.clientX,y:t.clientY},this.mapContainer.style.cursor="grabbing";return}if(t.button===0){if((o=(e=t.target)==null?void 0:e.closest)!=null&&o.call(e,he)||(n=(i=this.ctx).ferramentaAtiva)!=null&&n.call(i)||(this.selectionHappened=!1,this.ctx.mapaController&&this.ctx.mapaController.modoCliqueSequencialAtivo))return;(s=this.selecaoBox)==null||s.iniciarSelecao(t)}}});p(this,"handleMouseMove",t=>{var e;if(!(!this.map||!this.mapContainer)){if(this.isPanning){const o=this.lastMousePos.x-t.clientX,i=this.lastMousePos.y-t.clientY;(Math.abs(o)>1||Math.abs(i)>1)&&(this.panHappened=!0),this.map.panBy([o,i],{animate:!1}),this.lastMousePos={x:t.clientX,y:t.clientY};return}(e=this.selecaoBox)==null||e.atualizarSelecao(t)}});p(this,"handleMouseUp",t=>{this.isPanning&&(this.isPanning=!1,this.mapContainer&&(this.mapContainer.style.cursor="grab"),setTimeout(()=>{this.panHappened=!1},120)),this.selecaoBox&&this.selecaoBox.isSelecting&&this.selecaoBox.finalizarSelecao(t,()=>this.notificarSelecao(),()=>this.limparSelecao())&&(this.selectionHappened=!0,this.suprimirProximoClique())});p(this,"handleKeyDown",t=>{var e;if(t.key==="Escape"){if(Dt(t))return;(e=this.selecaoBox)==null||e.cancelarSelecao(),this.limparSelecao()}});this.ctx={selectedPontoIds:[],selectedVizinhoPontoIds:[],lastSelectedPontoId:null,pontosList:[],...t}}ativar(t,e){this.ctx.mapaController=t,e&&(this.ctx.containerHost=e),this.map=t.getMap(),this.map&&(this.mapContainer=this.map.getContainer(),this.mapContainer&&(this.map.dragging.disable(),this.map.doubleClickZoom.disable(),this.selecaoBox=new sa(this.map,this.mapContainer,this.ctx),No(this.mapContainer),this.mapContainer.addEventListener("click",this.handleClick),this.mapContainer.addEventListener("dblclick",this.handleDblClick),this.mapContainer.addEventListener("mousedown",this.handleMouseDown),this.mapContainer.addEventListener("mousemove",this.handleMouseMove),window.addEventListener("mouseup",this.handleMouseUp),this.mapContainer.addEventListener("contextmenu",this.handleContextMenu),window.addEventListener("keydown",this.handleKeyDown),this.mapContainer.addEventListener("touchstart",this.handleTouchStart,{passive:!1}),this.mapContainer.addEventListener("touchmove",this.handleTouchMove,{passive:!1}),this.mapContainer.addEventListener("touchend",this.handleTouchEnd),this.mapContainer.addEventListener("touchcancel",this.handleTouchEnd)))}desativar(){this.mapContainer&&(this.mapContainer.removeEventListener("click",this.handleClick),this.mapContainer.removeEventListener("dblclick",this.handleDblClick),this.mapContainer.removeEventListener("mousedown",this.handleMouseDown),this.mapContainer.removeEventListener("mousemove",this.handleMouseMove),this.mapContainer.removeEventListener("contextmenu",this.handleContextMenu),this.mapContainer.removeEventListener("touchstart",this.handleTouchStart),this.mapContainer.removeEventListener("touchmove",this.handleTouchMove),this.mapContainer.removeEventListener("touchend",this.handleTouchEnd),this.mapContainer.removeEventListener("touchcancel",this.handleTouchEnd)),window.removeEventListener("mouseup",this.handleMouseUp),window.removeEventListener("keydown",this.handleKeyDown),this.cancelarSupressaoClique(),this.selecaoBox&&(this.selecaoBox.destruir(),this.selecaoBox=null),this.map&&(this.map.dragging.enable(),this.map.doubleClickZoom.enable())}suprimirProximoClique(){this.cancelarSupressaoClique(),this.removerSupressao=()=>window.removeEventListener("click",t,!0);const t=e=>{e.stopImmediatePropagation(),e.preventDefault(),this.cancelarSupressaoClique()};window.addEventListener("click",t,!0)}cancelarSupressaoClique(){var t;(t=this.removerSupressao)==null||t.call(this),this.removerSupressao=null}limparSelecao(){var t,e,o,i;(e=(t=this.ctx).aoLimparSelecao)==null||e.call(t),this.ctx.mapaController&&this.ctx.mapaController.context.selectedSegmentoId&&this.ctx.mapaController.selectSegmento(null),(this.ctx.selectedPontoIds.length>0||this.ctx.selectedVizinhoPontoIds.length>0)&&(this.ctx.selectedPontoIds=[],this.ctx.selectedVizinhoPontoIds=[],this.ctx.lastSelectedPontoId=null,this.ctx.mapaController&&(this.ctx.mapaController.context.selectedPontoIds=[],(i=(o=this.ctx.mapaController).atualizarDestaqueMarcadores)==null||i.call(o)),this.notificarSelecao())}notificarSelecao(){var t,e;this.ctx.mapaController&&(this.ctx.mapaController.context.selectedPontoIds=[...this.ctx.selectedPontoIds],(e=(t=this.ctx.mapaController).atualizarDestaqueMarcadores)==null||e.call(t)),this.ctx.atualizarDestaqueLinhasTabela&&this.ctx.atualizarDestaqueLinhasTabela(),this.ctx.onSelectionChange&&this.ctx.onSelectionChange(this.ctx.selectedPontoIds,this.ctx.selectedVizinhoPontoIds),window.dispatchEvent(new CustomEvent("gerencigeo:ponto-selecionado",{detail:{selectedPontoIds:this.ctx.selectedPontoIds,selectedVizinhoPontoIds:this.ctx.selectedVizinhoPontoIds,lastSelectedPontoId:this.ctx.lastSelectedPontoId}}))}zoomExtents(){if(!this.ctx.pontosList||this.ctx.pontosList.length===0)return;const t=this.ctx.pontosList.filter(e=>e.tipo_ponto!=="B"&&e.tipo!=="B");t.length>0&&this.ctx.mapaController&&this.ctx.mapaController.fitBounds(t)}destroy(){this.desativar()}}class R{static register(t,e){this.renderers.set(t.toLowerCase(),e)}static get(t){return this.renderers.get(t.toLowerCase())}static has(t){return this.renderers.has(t.toLowerCase())}static getRegisteredTypes(){return Array.from(this.renderers.keys())}}p(R,"renderers",new Map);class Ro{render(t,e,o){var c,l,d;const i=((c=t.dados)==null?void 0:c.url)||"https://{s}.google.com/vt/lyrs=s,h&x={x}&y={y}&z={z}",n=((l=t.dados)==null?void 0:l.subdomains)||["mt0","mt1","mt2","mt3"],s=((d=t.dados)==null?void 0:d.attribution)||"Google Satélite";return y.tileLayer(i,{maxZoom:24,maxNativeZoom:20,subdomains:n,attribution:s,keepBuffer:16,updateWhenZooming:!1,updateWhenIdle:!0,className:"smooth-zoom-layer",opacity:t.opacidade!==void 0?t.opacidade:1,pane:`pane-${t.id}`})}update(t,e,o){e instanceof y.TileLayer&&o.opacidade!==void 0&&e.setOpacity(o.opacidade)}destroy(t,e){e.hasLayer(t)&&e.removeLayer(t)}}class Fo{render(t,e,o){var l,d,h,u;const i=((l=t.dados)==null?void 0:l.url)||"https://acervofundiario.incra.gov.br/i3geo/ogc.php",n=((d=t.dados)==null?void 0:d.layers)||"certificada_sigef_particular_pr",s=((h=t.dados)==null?void 0:h.format)||"image/png",r=((u=t.dados)==null?void 0:u.attribution)||"INCRA/SIGEF";return y.tileLayer.wms(i,{layers:n,format:s,transparent:!0,version:"1.1.1",pane:`pane-${t.id}`,attribution:r,className:"sigef-wms-layer",keepBuffer:8,updateWhenZooming:!1,updateWhenIdle:!0,opacity:t.opacidade!==void 0?t.opacidade:.85})}update(t,e,o){e instanceof y.TileLayer.WMS&&o.opacidade!==void 0&&e.setOpacity(o.opacidade)}destroy(t,e){e.hasLayer(t)&&e.removeLayer(t)}}function Bo(a,t,e){const o=a.estilo.espessuraLinha||e.config.perimetroWeight||2,i=e.graphicScale.lineScaleMultiplier||1;if(a.estilo.scaleMode==="world"){const n=a.estilo.dimensaoMetros||.3,s=t.getCenter(),r=t.getZoom(),c=40075016686e-3*Math.abs(Math.cos(s.lat*Math.PI/180))/Math.pow(2,r+8),l=n/(c>0?c:1);return Math.max(1,Math.round(l*i))}return Math.max(1,Math.round(o*i))}function pt(a,t,e,o,i){const n=Math.max(Math.round(e+3),4);y.polyline(t,{color:"#080d0a",weight:n,opacity:.85,lineCap:"round",lineJoin:"round",dashArray:i,pane:o,interactive:!1}).addTo(a)}function oo(a,t,e,o,i){var m,f,x,E,M,A,C,b;const n=a.id==="homologados",s=((m=a.dados)==null?void 0:m.conexoes)??(Array.isArray(a.dados)&&a.dados.length>0&&"origemId"in a.dados[0]?a.dados:null),r=((f=a.dados)==null?void 0:f.segmentos)||o.segmentos||[],c=((x=a.dados)==null?void 0:x.pontos)||(n?o.bancoPontos||[]:o.pontos)||[],l=Bo(a,e,o),d=a.opacidade!==void 0?a.opacidade:1,h=a.interativo&&!a.bloqueada,u=[];c.forEach(v=>{const P=S.parseCoordenada(v.lat??v.latitude??v.y,v.lon??v.lng??v.longitude??v.x);P&&u.push({...v,lat:P.lat,lon:P.lon})});const g=v=>{const P=u.find(w=>String(w.id)===String(v));if(P)return P;if(o.pontos){const w=o.pontos.find(k=>String(k.id)===String(v));if(w){const k=S.parseCoordenada(w.lat,w.lon);if(k)return{...w,lat:k.lat,lon:k.lon}}}return null};if(s&&Array.isArray(s)){s.forEach(v=>{var k,L,z,I,_,O,T;const P=g(v.origemId),w=g(v.destinoId);if(P&&w&&P.lat&&P.lon&&w.lat&&w.lon){const W=v.tipoLinha==="tracejada"||((k=v.estilo)==null?void 0:k.tipoLinha)==="tracejada",D=((L=v.estilo)==null?void 0:L.cor)||((z=v.estilo)==null?void 0:z.color)||a.estilo.corPrimaria||"#00f5a0",N=((I=v.estilo)==null?void 0:I.espessura)||((_=v.estilo)==null?void 0:_.weight)||l,$=[[P.lat,P.lon],[w.lat,w.lon]],F=W?"6, 6":a.estilo.dashArray;pt(t,$,N,i,F);const q=y.polyline($,{color:D,weight:N,opacity:((O=v.estilo)==null?void 0:O.opacidade)??d,dashArray:F,pane:i,interactive:h});if(h){const B=v.acoes||a.acoes||((T=a.dados)==null?void 0:T.acoes)||[],H=`${v.origemId}-${v.destinoId}`,J=S.renderPopupAcoesHtml(B,H);q.bindPopup(`
51
51
  <div style="font-family:sans-serif; color:rgba(255, 255, 255, 0.9); line-height:1.3;">
52
52
  <div style="font-weight:700; font-size:12px; margin-bottom:3px; color:#ffffff;">Conexão ${S.escapeHtml(String(v.origemId))} ↔ ${S.escapeHtml(String(v.destinoId))}</div>
53
53
  <div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">Tipo: ${S.escapeHtml(v.tipoLinha||"contínua")}</div>
54
54
  ${J}
55
55
  </div>
56
- `,{className:"compact-popup",maxWidth:220}),q.on("popupopen",ct=>{if(o.modoSequencial){q.closePopup();return}S.bindPopupAcoesEvents(ct.popup,v,o,q)})}q.addTo(t)}});return}if((A=n.dados)!=null&&A.polilinhaSequencial||((M=n.dados)==null?void 0:M.fechar)!==void 0&&u.length>=2){const v=((C=n.dados)==null?void 0:C.chaveGrupo)||o.chaveGrupo,b=S.agruparPontosPorChave(u,v),k=((z=n.dados)==null?void 0:z.fechar)!==!1,E=n.estilo.corPrimaria||"#00f5a0";Object.entries(b).forEach(([L,w])=>{const I=S.ordenarPontosPorSequencia(w);if(I.length<2)return;const _=I.map(T=>[T.lat,T.lon]);ut(t,_,l,i,n.estilo.dashArray);const O=y.polyline(_,{color:E,weight:l,opacity:d,dashArray:n.estilo.dashArray,pane:i,interactive:h});if(h&&O.bindPopup(`
56
+ `,{className:"compact-popup",maxWidth:220}),q.on("popupopen",ct=>{if(o.modoSequencial){q.closePopup();return}S.bindPopupAcoesEvents(ct.popup,v,o,q)})}q.addTo(t)}});return}if((E=a.dados)!=null&&E.polilinhaSequencial||((M=a.dados)==null?void 0:M.fechar)!==void 0&&u.length>=2){const v=((A=a.dados)==null?void 0:A.chaveGrupo)||o.chaveGrupo,P=S.agruparPontosPorChave(u,v),w=((C=a.dados)==null?void 0:C.fechar)!==!1,k=a.estilo.corPrimaria||"#00f5a0";Object.entries(P).forEach(([L,z])=>{const I=S.ordenarPontosPorSequencia(z);if(I.length<2)return;const _=I.map(T=>[T.lat,T.lon]);pt(t,_,l,i,a.estilo.dashArray);const O=y.polyline(_,{color:k,weight:l,opacity:d,dashArray:a.estilo.dashArray,pane:i,interactive:h});if(h&&O.bindPopup(`
57
57
  <div style="font-family:sans-serif; color:rgba(255, 255, 255, 0.9); line-height:1.3;">
58
58
  <div style="font-weight:700; font-size:12px; margin-bottom:3px; color:#ffffff;">Polilinha: Grupo ${S.escapeHtml(L)}</div>
59
59
  <div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">Vértices: ${I.length}</div>
60
60
  </div>
61
- `,{className:"compact-popup",maxWidth:220}),O.addTo(t),k&&_.length>=3){const T=_[_.length-1],W=_[0],D=[T,W];ut(t,D,l,i,"4, 4"),y.polyline(D,{color:E,weight:l,opacity:d,dashArray:"4, 4",pane:i,interactive:h}).addTo(t)}});return}if(!a&&r&&r.length>0)r.forEach(v=>{var E;const b=u.find(L=>String(L.id)===String(v.ponto_inicio_id)),k=u.find(L=>String(L.id)===String(v.ponto_fim_id));if(b&&k&&b.lat&&b.lon&&k.lat&&k.lon){const L=v.tipo_limite_sigef||v.tipo_limite||"",w=v.metodo_posicionamento_sigef||v.metodo_posicionamento||"",I=L==="LA1"?"#10b981":L==="LN1"?"#3b82f6":"#00f5a0",_=v.id!=null?v.id:`${v.ponto_inicio_id}-${v.ponto_fim_id}`,O=o.selectedSegmentoId!=null&&(String(o.selectedSegmentoId)===String(v.id)||String(o.selectedSegmentoId)===String(_)),T=O?"#facc15":n.estilo.corPrimaria||I,W=[[b.lat,b.lon],[k.lat,k.lon]],D=O?l+3:l,N=L==="LN1"?"6, 6":n.estilo.dashArray;ut(t,W,O?D+2:D,i,N);const $=y.polyline(W,{color:T,weight:D,opacity:O?1:d,dashArray:N,pane:i,interactive:h});if($.segmentoId=_,$.segmento=v,h){$.on("click",V=>{V&&V.originalEvent&&V.originalEvent.stopPropagation(),o.onSegmentoClick&&o.onSegmentoClick(_,v,{lat:(b.lat+k.lat)/2,lon:(b.lon+k.lon)/2})});const R=v.acoes||n.acoes||((E=n.dados)==null?void 0:E.acoes)||[],q=`${v.ponto_inicio_id}-${v.ponto_fim_id}`,B=S.renderPopupAcoesHtml(R,q);$.bindPopup(`
61
+ `,{className:"compact-popup",maxWidth:220}),O.addTo(t),w&&_.length>=3){const T=_[_.length-1],W=_[0],D=[T,W];pt(t,D,l,i,"4, 4"),y.polyline(D,{color:k,weight:l,opacity:d,dashArray:"4, 4",pane:i,interactive:h}).addTo(t)}});return}if(!n&&r&&r.length>0)r.forEach(v=>{var k;const P=u.find(L=>String(L.id)===String(v.ponto_inicio_id)),w=u.find(L=>String(L.id)===String(v.ponto_fim_id));if(P&&w&&P.lat&&P.lon&&w.lat&&w.lon){const L=v.tipo_limite_sigef||v.tipo_limite||"",z=v.metodo_posicionamento_sigef||v.metodo_posicionamento||"",I=L==="LA1"?"#10b981":L==="LN1"?"#3b82f6":"#00f5a0",_=v.id!=null?v.id:`${v.ponto_inicio_id}-${v.ponto_fim_id}`,O=o.selectedSegmentoId!=null&&(String(o.selectedSegmentoId)===String(v.id)||String(o.selectedSegmentoId)===String(_)),T=O?"#facc15":a.estilo.corPrimaria||I,W=[[P.lat,P.lon],[w.lat,w.lon]],D=O?l+3:l,N=L==="LN1"?"6, 6":a.estilo.dashArray;pt(t,W,O?D+2:D,i,N);const $=y.polyline(W,{color:T,weight:D,opacity:O?1:d,dashArray:N,pane:i,interactive:h});if($.segmentoId=_,$.segmento=v,h){$.on("click",H=>{H&&H.originalEvent&&H.originalEvent.stopPropagation(),o.onSegmentoClick&&o.onSegmentoClick(_,v,{lat:(P.lat+w.lat)/2,lon:(P.lon+w.lon)/2})});const F=v.acoes||a.acoes||((k=a.dados)==null?void 0:k.acoes)||[],q=`${v.ponto_inicio_id}-${v.ponto_fim_id}`,B=S.renderPopupAcoesHtml(F,q);$.bindPopup(`
62
62
  <div style="font-family:sans-serif; color:rgba(255, 255, 255, 0.9); line-height:1.3;">
63
- <div style="font-weight:700; font-size:12px; margin-bottom:3px; color:#ffffff;">${S.escapeHtml(b.nome_vertice)} ↔ ${S.escapeHtml(k.nome_vertice)}</div>
64
- <div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">Limite: ${S.escapeHtml(L||"N/A")} · ${S.escapeHtml(w||"N/A")}</div>
63
+ <div style="font-weight:700; font-size:12px; margin-bottom:3px; color:#ffffff;">${S.escapeHtml(P.nome_vertice)} ↔ ${S.escapeHtml(w.nome_vertice)}</div>
64
+ <div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">Limite: ${S.escapeHtml(L||"N/A")} · ${S.escapeHtml(z||"N/A")}</div>
65
65
  ${B}
66
66
  </div>
67
- `,{className:"compact-popup",maxWidth:220}),$.on("popupopen",V=>{if(o.modoSequencial){$.closePopup();return}S.bindPopupAcoesEvents(V.popup,v,o,$)})}$.addTo(t)}});else if(u&&u.length>=2){const v=u.filter(w=>w.lat&&w.lon&&w.tipo_ponto!=="B"&&w.tipo!=="B"&&w.ignorar_poligono!==1),b=((P=n.dados)==null?void 0:P.chaveGrupo)||o.chaveGrupo,k=S.agruparPontosPorChave(v,b),E=n.estilo.corPrimaria||(a?"#f59e0b":"#10b981"),L=n.estilo.dashArray||(a?"6, 8":void 0);Object.values(k).forEach(w=>{const I=S.ordenarPontosPorSequencia(w);if(I.length<2)return;const _=I.map(T=>[T.lat,T.lon]);if(ut(t,_,l,i,L),y.polyline(_,{color:E,weight:l,opacity:d,dashArray:L,pane:i,interactive:h}).addTo(t),_.length>=3){const T=_[_.length-1],W=_[0],D=a?"6, 8":"4, 4",N=[T,W];ut(t,N,l,i,D),y.polyline(N,{color:E,weight:l,opacity:d,dashArray:D,pane:i,interactive:h}).addTo(t)}})}}class No{constructor(){p(this,"zoomListenerMap",new WeakMap)}render(t,e,o){const i=y.layerGroup(),a=at(e,t.id,"linha");Ke(t,i,e,o,a);const s=()=>{if(t.estilo.scaleMode==="world"){const r=qo(t,e,o);i.eachLayer(c=>{c.setStyle&&c.setStyle({weight:r})})}};return e.on("zoomend",s),this.zoomListenerMap.set(i,s),i}update(t,e,o,i,a){(o.opacidade!==void 0||o.estilo!==void 0||o.dados!==void 0||o.interativo!==void 0||o.bloqueada!==void 0)&&(e.clearLayers(),Ke(t,e,a,i,at(a,t.id,"linha")))}destroy(t,e){const o=this.zoomListenerMap.get(t);o&&(e.off("zoomend",o),this.zoomListenerMap.delete(t)),t.clearLayers(),e.hasLayer(t)&&e.removeLayer(t)}}const Ut=300;function Wt(n){return n>Ut?"compacta":"normal"}function Te(n,t){if(n<=Ut)return 1;const e=Math.max(.7,1-.3*Math.log10(n/Ut)),o=t>=18?1:t>=16?.92:t>=14?.82:.72;return Math.max(.6,e*o)}function Oo(n){if(!n)return"#00f5a0";const t=n.trim();if(t.startsWith("#")||t.startsWith("rgb")||t.startsWith("hsl")||t.startsWith("var("))return t;if(t.includes("bg-[#")&&t.includes("]")){const o=t.match(/bg-\[(#[a-fA-F0-9]+)\]/);if(o)return o[1]}const e={"bg-mint-vibrant":"#00f5a0","bg-indigo-500":"#6366f1","bg-rose-500":"#f43f5e","bg-amber-500":"#f59e0b","bg-forest-deep":"#06130b","bg-purple-500":"#a855f7","bg-blue-500":"#3b82f6","bg-emerald-500":"#10b981"};for(const[o,i]of Object.entries(e))if(t.includes(o))return i;return"#00f5a0"}function Je(n){return n.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}const ae={diamond:"6,0.8 11.2,6 6,11.2 0.8,6",triangle:"6,1 11.4,10.6 0.6,10.6"},se={cross:["M6 1.2V10.8","M1.2 6H10.8"],x:["M2 2L10 10","M10 2L2 10"]};function At(n,t,e,o="",i="",a=!1,s={}){const r=a||o.includes("ponto-selecionado")||o.includes("cad-marker-selected"),c=s.densidade==="compacta",l=Je(Oo(e)),d=t+6,h=r?`color-mix(in srgb, ${l} 38%, #000000)`:l,u=r?1:c?.72:.9,m=r?"rgba(255,255,255,0.95)":c?"rgba(0,0,0,0.55)":"rgba(0,0,0,0.7)",f=r?1.3:c?.8:1,g=r?"rgba(255,255,255,0.9)":"rgba(0,0,0,0.6)",x=(b,k,E,L="")=>`class="${b}" stroke="${k}" stroke-width="${E}" vector-effect="non-scaling-stroke" ${L}`,A=n in ae?`<polygon points="${ae[n]}" style="fill:${h}" fill-opacity="${u}" stroke-linejoin="round" ${x("cad-pt-contorno",m,f)} />`:n in se?se[n].map(b=>`<path d="${b}" fill="none" stroke-linecap="round" ${x("cad-pt-halo",g,c?2.6:3.4)} /><path d="${b}" fill="none" stroke-linecap="round" ${x("cad-pt-traco",r?h:l,c?1.3:1.8,`stroke-opacity="${r?1:c?.9:1}"`)} />`).join(""):n==="square"?`<rect x="1.2" y="1.2" width="9.6" height="9.6" rx="1.4" style="fill:${h}" fill-opacity="${u}" ${x("cad-pt-contorno",m,f)} />`:`<circle cx="6" cy="6" r="5.2" style="fill:${h}" fill-opacity="${u}" ${x("cad-pt-contorno",m,f)} />`,M=!c&&!r&&!(n in se)?n in ae?"":n==="square"?'<rect x="2.2" y="2.2" width="7.6" height="7.6" rx="0.9" fill="none" stroke="rgba(255,255,255,0.45)" stroke-width="0.8" vector-effect="non-scaling-stroke" />':'<circle cx="6" cy="6" r="4.3" fill="none" stroke="rgba(255,255,255,0.45)" stroke-width="0.8" vector-effect="non-scaling-stroke" />':"",C=n==="circle-dot"?'<circle cx="6" cy="6" r="1.7" fill="#ffffff" stroke="rgba(0,0,0,0.45)" stroke-width="0.6" vector-effect="non-scaling-stroke" />':"",z=`cad-pt ${c?"cad-pt-compacto":""} ${e} ${o} ${r?"ponto-selecionado":""}`.replace(/\s+/g," ").trim(),P=t;return`
68
- <div ${i?`id="${Je(i)}"`:""} class="${z}" style="display:flex; align-items:center; justify-content:center; width:${d}px; height:${d}px; position:relative; pointer-events:auto; background:none !important;">
69
- <svg width="${P}" height="${P}" viewBox="0 0 12 12" xmlns="http://www.w3.org/2000/svg" style="overflow:visible; display:block;">
70
- ${A}${M}${C}
67
+ `,{className:"compact-popup",maxWidth:220}),$.on("popupopen",H=>{if(o.modoSequencial){$.closePopup();return}S.bindPopupAcoesEvents(H.popup,v,o,$)})}$.addTo(t)}});else if(u&&u.length>=2){const v=u.filter(z=>z.lat&&z.lon&&z.tipo_ponto!=="B"&&z.tipo!=="B"&&z.ignorar_poligono!==1),P=((b=a.dados)==null?void 0:b.chaveGrupo)||o.chaveGrupo,w=S.agruparPontosPorChave(v,P),k=a.estilo.corPrimaria||(n?"#f59e0b":"#10b981"),L=a.estilo.dashArray||(n?"6, 8":void 0);Object.values(w).forEach(z=>{const I=S.ordenarPontosPorSequencia(z);if(I.length<2)return;const _=I.map(T=>[T.lat,T.lon]);if(pt(t,_,l,i,L),y.polyline(_,{color:k,weight:l,opacity:d,dashArray:L,pane:i,interactive:h}).addTo(t),_.length>=3){const T=_[_.length-1],W=_[0],D=n?"6, 8":"4, 4",N=[T,W];pt(t,N,l,i,D),y.polyline(N,{color:k,weight:l,opacity:d,dashArray:D,pane:i,interactive:h}).addTo(t)}})}}class Vo{constructor(){p(this,"zoomListenerMap",new WeakMap)}render(t,e,o){const i=y.layerGroup(),n=st(e,t.id,"linha");oo(t,i,e,o,n);const s=()=>{if(t.estilo.scaleMode==="world"){const r=Bo(t,e,o);i.eachLayer(c=>{c.setStyle&&c.setStyle({weight:r})})}};return e.on("zoomend",s),this.zoomListenerMap.set(i,s),i}update(t,e,o,i,n){(o.opacidade!==void 0||o.estilo!==void 0||o.dados!==void 0||o.interativo!==void 0||o.bloqueada!==void 0)&&(e.clearLayers(),oo(t,e,n,i,st(n,t.id,"linha")))}destroy(t,e){const o=this.zoomListenerMap.get(t);o&&(e.off("zoomend",o),this.zoomListenerMap.delete(t)),t.clearLayers(),e.hasLayer(t)&&e.removeLayer(t)}}const Jt=300;function Qt(a){return a>Jt?"compacta":"normal"}function Ne(a,t){if(a<=Jt)return 1;const e=Math.max(.7,1-.3*Math.log10(a/Jt)),o=t>=18?1:t>=16?.92:t>=14?.82:.72;return Math.max(.6,e*o)}function Ho(a){if(!a)return"#00f5a0";const t=a.trim();if(t.startsWith("#")||t.startsWith("rgb")||t.startsWith("hsl")||t.startsWith("var("))return t;if(t.includes("bg-[#")&&t.includes("]")){const o=t.match(/bg-\[(#[a-fA-F0-9]+)\]/);if(o)return o[1]}const e={"bg-mint-vibrant":"#00f5a0","bg-indigo-500":"#6366f1","bg-rose-500":"#f43f5e","bg-amber-500":"#f59e0b","bg-forest-deep":"#06130b","bg-purple-500":"#a855f7","bg-blue-500":"#3b82f6","bg-emerald-500":"#10b981"};for(const[o,i]of Object.entries(e))if(t.includes(o))return i;return"#00f5a0"}function io(a){return a.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}const ue={diamond:"6,0.8 11.2,6 6,11.2 0.8,6",triangle:"6,1 11.4,10.6 0.6,10.6"},pe={cross:["M6 1.2V10.8","M1.2 6H10.8"],x:["M2 2L10 10","M10 2L2 10"]};function zt(a,t,e,o="",i="",n=!1,s={}){const r=n||o.includes("ponto-selecionado")||o.includes("cad-marker-selected"),c=s.densidade==="compacta",l=io(Ho(e)),d=t+6,h=r?`color-mix(in srgb, ${l} 38%, #000000)`:l,u=r?1:c?.72:.9,g=r?"rgba(255,255,255,0.95)":c?"rgba(0,0,0,0.55)":"rgba(0,0,0,0.7)",m=r?1.3:c?.8:1,f=r?"rgba(255,255,255,0.9)":"rgba(0,0,0,0.6)",x=(P,w,k,L="")=>`class="${P}" stroke="${w}" stroke-width="${k}" vector-effect="non-scaling-stroke" ${L}`,E=a in ue?`<polygon points="${ue[a]}" style="fill:${h}" fill-opacity="${u}" stroke-linejoin="round" ${x("cad-pt-contorno",g,m)} />`:a in pe?pe[a].map(P=>`<path d="${P}" fill="none" stroke-linecap="round" ${x("cad-pt-halo",f,c?2.6:3.4)} /><path d="${P}" fill="none" stroke-linecap="round" ${x("cad-pt-traco",r?h:l,c?1.3:1.8,`stroke-opacity="${r?1:c?.9:1}"`)} />`).join(""):a==="square"?`<rect x="1.2" y="1.2" width="9.6" height="9.6" rx="1.4" style="fill:${h}" fill-opacity="${u}" ${x("cad-pt-contorno",g,m)} />`:`<circle cx="6" cy="6" r="5.2" style="fill:${h}" fill-opacity="${u}" ${x("cad-pt-contorno",g,m)} />`,M=!c&&!r&&!(a in pe)?a in ue?"":a==="square"?'<rect x="2.2" y="2.2" width="7.6" height="7.6" rx="0.9" fill="none" stroke="rgba(255,255,255,0.45)" stroke-width="0.8" vector-effect="non-scaling-stroke" />':'<circle cx="6" cy="6" r="4.3" fill="none" stroke="rgba(255,255,255,0.45)" stroke-width="0.8" vector-effect="non-scaling-stroke" />':"",A=a==="circle-dot"?'<circle cx="6" cy="6" r="1.7" fill="#ffffff" stroke="rgba(0,0,0,0.45)" stroke-width="0.6" vector-effect="non-scaling-stroke" />':"",C=`cad-pt ${c?"cad-pt-compacto":""} ${e} ${o} ${r?"ponto-selecionado":""}`.replace(/\s+/g," ").trim(),b=t;return`
68
+ <div ${i?`id="${io(i)}"`:""} class="${C}" style="display:flex; align-items:center; justify-content:center; width:${d}px; height:${d}px; position:relative; pointer-events:auto; background:none !important;">
69
+ <svg width="${b}" height="${b}" viewBox="0 0 12 12" xmlns="http://www.w3.org/2000/svg" style="overflow:visible; display:block;">
70
+ ${E}${M}${A}
71
71
  </svg>
72
72
  </div>
73
- `}class Fo{constructor(){p(this,"zoomListenerMap",new WeakMap)}render(t,e,o){const i=y.layerGroup(),a=at(e,t.id,"ponto");this.rebuildPoints(t,i,e,o,a);const s=()=>{i.eachLayer(r=>{if(!(r.setIcon&&r.baseSize&&r.shapeStyle&&r.markerBg&&r.pontoId!==void 0))return;const c=r.densTotal||0;if(t.estilo.scaleMode!=="world"&&Wt(c)!=="compacta")return;const l=this.calculateSize(t,e,o,r.baseSize,c);l!==r.tamanhoPx&&(r.tamanhoPx=l,r.setIcon(this.criarIcone(t,o,r.shapeStyle,l,r.markerBg,r.pontoId,!!r.isSelected,c)))})};return e.on("zoomend",s),this.zoomListenerMap.set(i,s),i}criarIcone(t,e,o,i,a,s,r,c){const l=e.config.enableAnimations?"cad-pt-anim":"",d=At(o,i,a,l,`map-marker-${t.id}-${s}`,r,{densidade:Wt(c)});return y.divIcon({html:d,className:`custom-leaflet-marker ${r?"cad-marker-selected":""}`.trim(),iconSize:[i+6,i+6]})}calculateSize(t,e,o,i,a=0){const s=o.graphicScale.markerScaleMultiplier||1;if(t.estilo.scaleMode==="world"){const c=t.estilo.dimensaoMetros||.25,l=e.getCenter(),d=e.getZoom(),h=40075016686e-3*Math.abs(Math.cos(l.lat*Math.PI/180))/Math.pow(2,d+8),u=c/(h>0?h:1);return Math.max(3,Math.round(u*s))}const r=Te(a,e.getZoom());return Math.max(r<1?5:4,Math.round(i*s*r))}rebuildPoints(t,e,o,i,a){var m;const r=t.id==="homologados-pontos"?i.bancoPontos||[]:((m=t.dados)==null?void 0:m.pontos)||i.pontos||[],c=t.interativo&&!t.bloqueada,l=t.id==="vizinhos",d=t.id==="homologados"||t.id==="homologados-pontos",h=i.selectedPontoIds||[],u=r.length;r.forEach(f=>{var A;const g=f.lat??f.latitude,x=f.lon??f.lng??f.longitude;if(g!==void 0&&x!==void 0&&g!==0&&x!==0&&!isNaN(Number(g))&&!isNaN(Number(x))){const M=f.tipo_ponto==="B"||f.tipo==="B",C=f.tipo_ponto==="M"||f.tipo==="M";let z=t.estilo.estiloMarcador||"x",P=t.estilo.corPrimaria||"bg-mint-vibrant",v=t.estilo.tamanhoMarcador||7;d?(z="circle",P=t.estilo.corPrimaria||"#f59e0b",v=8):l?(z=C?"circle-dot":t.estilo.estiloMarcador||"cross",P=t.estilo.corPrimaria||"#a855f7",v=C?10:8):C?(P="#6366f1",z="circle-dot",v=10):M&&(P="#f43f5e",z="square",v=9);const b=!!(f.selecionado||h.length>0&&(h.includes(f.id)||h.includes(String(f.id))||h.includes(Number(f.id)))),k=this.calculateSize(t,o,i,v,u),E=this.criarIcone(t,i,z,k,P,f.id,b,u),L=y.marker([Number(g),Number(x)],{icon:E,pane:a,interactive:c});if(b&&L.setZIndexOffset(2e3),L.pontoId=f.id,L.layerId=t.id,L.isVizinho=l,L.baseSize=v,L.shapeStyle=z,L.markerBg=P,L.isSelected=b,L.densTotal=u,L.tamanhoPx=k,c){const w=d?"Vértice Homologado SIGEF":l?"Confrontante (Importado)":C?"Base Homologada PPP":M?"Base de Campo (Translação)":"Vértice de Perímetro",I=f.acoes||t.acoes||((A=t.dados)==null?void 0:A.acoes)||[],_=S.renderPopupAcoesHtml(I,f.id);L.bindPopup(`
73
+ `}class Go{constructor(){p(this,"zoomListenerMap",new WeakMap)}render(t,e,o){const i=y.layerGroup(),n=st(e,t.id,"ponto");this.rebuildPoints(t,i,e,o,n);const s=()=>{i.eachLayer(r=>{if(!(r.setIcon&&r.baseSize&&r.shapeStyle&&r.markerBg&&r.pontoId!==void 0))return;const c=r.densTotal||0;if(t.estilo.scaleMode!=="world"&&Qt(c)!=="compacta")return;const l=this.calculateSize(t,e,o,r.baseSize,c);l!==r.tamanhoPx&&(r.tamanhoPx=l,r.setIcon(this.criarIcone(t,o,r.shapeStyle,l,r.markerBg,r.pontoId,!!r.isSelected,c)))})};return e.on("zoomend",s),this.zoomListenerMap.set(i,s),i}criarIcone(t,e,o,i,n,s,r,c){const l=e.config.enableAnimations?"cad-pt-anim":"",d=zt(o,i,n,l,`map-marker-${t.id}-${s}`,r,{densidade:Qt(c)});return y.divIcon({html:d,className:`custom-leaflet-marker ${r?"cad-marker-selected":""}`.trim(),iconSize:[i+6,i+6]})}calculateSize(t,e,o,i,n=0){const s=o.graphicScale.markerScaleMultiplier||1;if(t.estilo.scaleMode==="world"){const c=t.estilo.dimensaoMetros||.25,l=e.getCenter(),d=e.getZoom(),h=40075016686e-3*Math.abs(Math.cos(l.lat*Math.PI/180))/Math.pow(2,d+8),u=c/(h>0?h:1);return Math.max(3,Math.round(u*s))}const r=Ne(n,e.getZoom());return Math.max(r<1?5:4,Math.round(i*s*r))}rebuildPoints(t,e,o,i,n){var g;const r=t.id==="homologados-pontos"?i.bancoPontos||[]:((g=t.dados)==null?void 0:g.pontos)||i.pontos||[],c=t.interativo&&!t.bloqueada,l=t.id==="vizinhos",d=t.id==="homologados"||t.id==="homologados-pontos",h=i.selectedPontoIds||[],u=r.length;r.forEach(m=>{var E;const f=m.lat??m.latitude,x=m.lon??m.lng??m.longitude;if(f!==void 0&&x!==void 0&&f!==0&&x!==0&&!isNaN(Number(f))&&!isNaN(Number(x))){const M=m.tipo_ponto==="B"||m.tipo==="B",A=m.tipo_ponto==="M"||m.tipo==="M";let C=t.estilo.estiloMarcador||"x",b=t.estilo.corPrimaria||"bg-mint-vibrant",v=t.estilo.tamanhoMarcador||7;d?(C="circle",b=t.estilo.corPrimaria||"#f59e0b",v=8):l?(C=A?"circle-dot":t.estilo.estiloMarcador||"cross",b=t.estilo.corPrimaria||"#a855f7",v=A?10:8):A?(b="#6366f1",C="circle-dot",v=10):M&&(b="#f43f5e",C="square",v=9);const P=!!(m.selecionado||h.length>0&&(h.includes(m.id)||h.includes(String(m.id))||h.includes(Number(m.id)))),w=this.calculateSize(t,o,i,v,u),k=this.criarIcone(t,i,C,w,b,m.id,P,u),L=y.marker([Number(f),Number(x)],{icon:k,pane:n,interactive:c});if(P&&L.setZIndexOffset(2e3),L.pontoId=m.id,L.layerId=t.id,L.isVizinho=l,L.baseSize=v,L.shapeStyle=C,L.markerBg=b,L.isSelected=P,L.densTotal=u,L.tamanhoPx=w,c){const z=d?"Vértice Homologado SIGEF":l?"Confrontante (Importado)":A?"Base Homologada PPP":M?"Base de Campo (Translação)":"Vértice de Perímetro",I=m.acoes||t.acoes||((E=t.dados)==null?void 0:E.acoes)||[],_=S.renderPopupAcoesHtml(I,m.id);L.bindPopup(`
74
74
  <div style="font-family:var(--ui-fonte-base, sans-serif); color:rgba(255, 255, 255, 0.9); line-height:1.3;">
75
- <div style="font-weight:700; font-size:13px; margin-bottom:4px; color:#ffffff;">${S.escapeHtml(f.nome_vertice||String(f.id))}</div>
76
- <div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">${S.escapeHtml(w)} · ${S.escapeHtml(f.tipo_ponto||f.tipo||"Vértice")}</div>
77
- <div style="font-size:11px; color:rgba(255, 255, 255, 0.45); font-family:var(--ui-fonte-codigo, monospace); margin-top:4px;">Lat ${Number(g).toFixed(6)} &nbsp; Lon ${Number(x).toFixed(6)}</div>
75
+ <div style="font-weight:700; font-size:13px; margin-bottom:4px; color:#ffffff;">${S.escapeHtml(m.nome_vertice||String(m.id))}</div>
76
+ <div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">${S.escapeHtml(z)} · ${S.escapeHtml(m.tipo_ponto||m.tipo||"Vértice")}</div>
77
+ <div style="font-size:11px; color:rgba(255, 255, 255, 0.45); font-family:var(--ui-fonte-codigo, monospace); margin-top:4px;">Lat ${Number(f).toFixed(6)} &nbsp; Lon ${Number(x).toFixed(6)}</div>
78
78
  ${_}
79
79
  </div>
80
- `,{className:"compact-popup",maxWidth:240}),I&&I.length>0&&L.on("popupopen",O=>{S.bindPopupAcoesEvents(O.popup,f,i,L)}),L.on("click",()=>{i.onMarkerClick&&i.onMarkerClick(f.id,l,f,{lat:Number(g),lon:Number(x)})})}L.addTo(e)}})}update(t,e,o,i,a){(o.opacidade!==void 0||o.estilo!==void 0||o.dados!==void 0||o.interativo!==void 0||o.bloqueada!==void 0)&&(e.clearLayers(),this.rebuildPoints(t,e,a,i,at(a,t.id,"ponto")))}destroy(t,e){const o=this.zoomListenerMap.get(t);o&&(e.off("zoomend",o),this.zoomListenerMap.delete(t)),t.clearLayers(),e.hasLayer(t)&&e.removeLayer(t)}}class Ro{render(t,e,o){const i=y.layerGroup();return this.rebuildPolygons(t,i,o,e),i}rebuildPolygons(t,e,o,i){var m,f;const a=at(i,t.id,"poligono"),s=at(i,t.id,"ponto"),c=(((m=t.dados)==null?void 0:m.poligonos)??(Array.isArray(t.dados)?t.dados:null))||((f=t.dados)==null?void 0:f.confrontantes)||o.confrontantes||[],l=t.interativo&&!t.bloqueada,d=t.estilo.corPrimaria||"#a855f7",h=t.estilo.espessuraLinha||1,u=t.opacidade!==void 0?t.opacidade:.8;c.forEach(g=>{var b,k,E,L,w,I,_,O,T,W;if(!g)return;const x=((b=g.estilo)==null?void 0:b.cor)||((k=g.estilo)==null?void 0:k.color)||d,A=((E=g.estilo)==null?void 0:E.espessura)||((L=g.estilo)==null?void 0:L.weight)||h,M=((w=g.estilo)==null?void 0:w.opacidade)??u,C=((I=g.estilo)==null?void 0:I.fillColor)||x,z=((_=g.estilo)==null?void 0:_.fillOpacity)??Math.min(.14,M*.1),P=((O=g.estilo)==null?void 0:O.dashArray)||t.estilo.dashArray||"4, 6";if(g.coordenadas&&Array.isArray(g.coordenadas)&&g.coordenadas.length>=3){const D=Array.isArray(g.coordenadas[0])&&Array.isArray(g.coordenadas[0][0]);let N;if(D?N=g.coordenadas.map($=>$.map(R=>{const q=S.parseCoordenada(R[0],R[1]);return q?[q.lat,q.lon]:null}).filter(Boolean)):N=g.coordenadas.map($=>{const R=S.parseCoordenada($[0],$[1]);return R?[R.lat,R.lon]:null}).filter(Boolean),N&&(D?((T=N[0])==null?void 0:T.length)>=3:N.length>=3)){const $=y.polygon(N,{color:x,weight:A,opacity:M,dashArray:P,fillColor:C,fillOpacity:z,lineJoin:"round",pane:a,interactive:l});if($.poligonoId=g.id,$.layerId=t.id,l){let R="";g.metadados&&Object.keys(g.metadados).length>0&&(R=Object.entries(g.metadados).map(([q,B])=>`<div style="font-size:11px;"><strong>${S.escapeHtml(q)}:</strong> ${S.escapeHtml(String(B))}</div>`).join("")),$.bindPopup(`
80
+ `,{className:"compact-popup",maxWidth:240}),I&&I.length>0&&L.on("popupopen",O=>{S.bindPopupAcoesEvents(O.popup,m,i,L)}),L.on("click",()=>{i.onMarkerClick&&i.onMarkerClick(m.id,l,m,{lat:Number(f),lon:Number(x)})})}L.addTo(e)}})}update(t,e,o,i,n){(o.opacidade!==void 0||o.estilo!==void 0||o.dados!==void 0||o.interativo!==void 0||o.bloqueada!==void 0)&&(e.clearLayers(),this.rebuildPoints(t,e,n,i,st(n,t.id,"ponto")))}destroy(t,e){const o=this.zoomListenerMap.get(t);o&&(e.off("zoomend",o),this.zoomListenerMap.delete(t)),t.clearLayers(),e.hasLayer(t)&&e.removeLayer(t)}}class jo{render(t,e,o){const i=y.layerGroup();return this.rebuildPolygons(t,i,o,e),i}rebuildPolygons(t,e,o,i){var g,m;const n=st(i,t.id,"poligono"),s=st(i,t.id,"ponto"),c=(((g=t.dados)==null?void 0:g.poligonos)??(Array.isArray(t.dados)?t.dados:null))||((m=t.dados)==null?void 0:m.confrontantes)||o.confrontantes||[],l=t.interativo&&!t.bloqueada,d=t.estilo.corPrimaria||"#a855f7",h=t.estilo.espessuraLinha||1,u=t.opacidade!==void 0?t.opacidade:.8;c.forEach(f=>{var P,w,k,L,z,I,_,O,T,W;if(!f)return;const x=((P=f.estilo)==null?void 0:P.cor)||((w=f.estilo)==null?void 0:w.color)||d,E=((k=f.estilo)==null?void 0:k.espessura)||((L=f.estilo)==null?void 0:L.weight)||h,M=((z=f.estilo)==null?void 0:z.opacidade)??u,A=((I=f.estilo)==null?void 0:I.fillColor)||x,C=((_=f.estilo)==null?void 0:_.fillOpacity)??Math.min(.14,M*.1),b=((O=f.estilo)==null?void 0:O.dashArray)||t.estilo.dashArray||"4, 6";if(f.coordenadas&&Array.isArray(f.coordenadas)&&f.coordenadas.length>=3){const D=Array.isArray(f.coordenadas[0])&&Array.isArray(f.coordenadas[0][0]);let N;if(D?N=f.coordenadas.map($=>$.map(F=>{const q=S.parseCoordenada(F[0],F[1]);return q?[q.lat,q.lon]:null}).filter(Boolean)):N=f.coordenadas.map($=>{const F=S.parseCoordenada($[0],$[1]);return F?[F.lat,F.lon]:null}).filter(Boolean),N&&(D?((T=N[0])==null?void 0:T.length)>=3:N.length>=3)){const $=y.polygon(N,{color:x,weight:E,opacity:M,dashArray:b,fillColor:A,fillOpacity:C,lineJoin:"round",pane:n,interactive:l});if($.poligonoId=f.id,$.layerId=t.id,l){let F="";f.metadados&&Object.keys(f.metadados).length>0&&(F=Object.entries(f.metadados).map(([q,B])=>`<div style="font-size:11px;"><strong>${S.escapeHtml(q)}:</strong> ${S.escapeHtml(String(B))}</div>`).join("")),$.bindPopup(`
81
81
  <div style="font-family:var(--ui-fonte-base, sans-serif); color:rgba(255, 255, 255, 0.9); line-height:1.3; min-width:180px;">
82
- <div style="font-weight:700; font-size:12px; color:#c084fc; margin-bottom:3px; border-bottom:1px solid rgba(255,255,255,0.1); padding-bottom:3px;">Polígono ${S.escapeHtml(String(g.id??""))}</div>
83
- ${R||`<div style="font-size:11px;">Área vetorial definida por ${g.coordenadas.length} vértices</div>`}
82
+ <div style="font-weight:700; font-size:12px; color:#c084fc; margin-bottom:3px; border-bottom:1px solid rgba(255,255,255,0.1); padding-bottom:3px;">Polígono ${S.escapeHtml(String(f.id??""))}</div>
83
+ ${F||`<div style="font-size:11px;">Área vetorial definida por ${f.coordenadas.length} vértices</div>`}
84
84
  </div>
85
- `,{className:"compact-popup",maxWidth:220}),$.on("popupopen",()=>{o.modoSequencial&&$.closePopup()})}$.addTo(e);return}}const v=g.wkt||g.poligono_wkt;if(v){const D=[...v.matchAll(/\(([^()]+)\)/g)];if(D.length>0){const N=S.escapeHtml(g.nome_propriedade||`Polígono ${String(g.id||"")}`),$=S.escapeHtml(g.nome||"Proprietário"),R=[];if(D.forEach(q=>{const B=q[1].split(",").map(V=>{const J=V.trim().split(/\s+/);if(J.length<2)return null;const ct=S.parseCoordenada(J[1],J[0]);return ct?[ct.lat,ct.lon]:null}).filter(V=>V!==null);B.length>=3&&R.push(B)}),R.length>0){const q=R.length===1?R[0]:R,B=y.polygon(q,{color:x,weight:A,opacity:M,dashArray:P,fillColor:C,fillOpacity:z,lineJoin:"round",pane:a,interactive:l});if(B.poligonoId=g.id,B.layerId=t.id,l){const V=g.acoes||t.acoes||((W=t.dados)==null?void 0:W.acoes)||[],J=S.renderPopupAcoesHtml(V,g.id);B.bindPopup(`
85
+ `,{className:"compact-popup",maxWidth:220}),$.on("popupopen",()=>{o.modoSequencial&&$.closePopup()})}$.addTo(e);return}}const v=f.wkt||f.poligono_wkt;if(v){const D=[...v.matchAll(/\(([^()]+)\)/g)];if(D.length>0){const N=S.escapeHtml(f.nome_propriedade||`Polígono ${String(f.id||"")}`),$=S.escapeHtml(f.nome||"Proprietário"),F=[];if(D.forEach(q=>{const B=q[1].split(",").map(H=>{const J=H.trim().split(/\s+/);if(J.length<2)return null;const ct=S.parseCoordenada(J[1],J[0]);return ct?[ct.lat,ct.lon]:null}).filter(H=>H!==null);B.length>=3&&F.push(B)}),F.length>0){const q=F.length===1?F[0]:F,B=y.polygon(q,{color:x,weight:E,opacity:M,dashArray:b,fillColor:A,fillOpacity:C,lineJoin:"round",pane:n,interactive:l});if(B.poligonoId=f.id,B.layerId=t.id,l){const H=f.acoes||t.acoes||((W=t.dados)==null?void 0:W.acoes)||[],J=S.renderPopupAcoesHtml(H,f.id);B.bindPopup(`
86
86
  <div style="font-family:var(--ui-fonte-base, sans-serif); color:rgba(255, 255, 255, 0.9); line-height:1.3; min-width:180px;">
87
87
  <div style="font-weight:700; font-size:12px; color:#c084fc; margin-bottom:3px; border-bottom:1px solid rgba(255,255,255,0.1); padding-bottom:3px;">${N}</div>
88
- <div style="font-size:11px; margin-bottom:2px;"><strong>Identificador:</strong> ${S.escapeHtml(String(g.id??""))}</div>
89
- ${g.nome?`<div style="font-size:11px;"><strong>Proprietário:</strong> ${$}</div>`:""}
88
+ <div style="font-size:11px; margin-bottom:2px;"><strong>Identificador:</strong> ${S.escapeHtml(String(f.id??""))}</div>
89
+ ${f.nome?`<div style="font-size:11px;"><strong>Proprietário:</strong> ${$}</div>`:""}
90
90
  ${J}
91
91
  </div>
92
- `,{className:"compact-popup",maxWidth:220}),B.on("popupopen",ct=>{if(o.modoSequencial){B.closePopup();return}S.bindPopupAcoesEvents(ct.popup,g,o,B)})}B.addTo(e)}}}g.pontos&&g.pontos.length>0&&g.pontos.forEach(D=>{var $;const N=S.parseCoordenada(D.lat??D.latitude??D.y,D.lon??D.lng??D.longitude??D.x);if(N){const R=y.divIcon({html:'<div class="cad-pt" style="width:12px; height:12px; display:flex; align-items:center; justify-content:center;"><svg width="8" height="8" viewBox="0 0 12 12" style="overflow:visible; display:block;"><circle cx="6" cy="6" r="5.2" fill="#a855f7" fill-opacity="0.85" stroke="rgba(0,0,0,0.65)" stroke-width="1" vector-effect="non-scaling-stroke" /><circle cx="6" cy="6" r="4.3" fill="none" stroke="rgba(255,255,255,0.5)" stroke-width="0.8" vector-effect="non-scaling-stroke" /></svg></div>',className:"custom-leaflet-marker",iconSize:[12,12]}),q=y.marker([N.lat,N.lon],{icon:R,pane:s,interactive:l});if(q.pontoId=D.id,q.isVizinho=!0,q.layerId=t.id,l){const B=D.acoes||g.acoes||t.acoes||(($=t.dados)==null?void 0:$.acoes)||[],V=S.renderPopupAcoesHtml(B,D.id);q.bindPopup(`
92
+ `,{className:"compact-popup",maxWidth:220}),B.on("popupopen",ct=>{if(o.modoSequencial){B.closePopup();return}S.bindPopupAcoesEvents(ct.popup,f,o,B)})}B.addTo(e)}}}f.pontos&&f.pontos.length>0&&f.pontos.forEach(D=>{var $;const N=S.parseCoordenada(D.lat??D.latitude??D.y,D.lon??D.lng??D.longitude??D.x);if(N){const F=y.divIcon({html:'<div class="cad-pt" style="width:12px; height:12px; display:flex; align-items:center; justify-content:center;"><svg width="8" height="8" viewBox="0 0 12 12" style="overflow:visible; display:block;"><circle cx="6" cy="6" r="5.2" fill="#a855f7" fill-opacity="0.85" stroke="rgba(0,0,0,0.65)" stroke-width="1" vector-effect="non-scaling-stroke" /><circle cx="6" cy="6" r="4.3" fill="none" stroke="rgba(255,255,255,0.5)" stroke-width="0.8" vector-effect="non-scaling-stroke" /></svg></div>',className:"custom-leaflet-marker",iconSize:[12,12]}),q=y.marker([N.lat,N.lon],{icon:F,pane:s,interactive:l});if(q.pontoId=D.id,q.isVizinho=!0,q.layerId=t.id,l){const B=D.acoes||f.acoes||t.acoes||(($=t.dados)==null?void 0:$.acoes)||[],H=S.renderPopupAcoesHtml(B,D.id);q.bindPopup(`
93
93
  <div style="font-family:var(--ui-fonte-base, sans-serif); color:rgba(255, 255, 255, 0.9); line-height:1.3; min-width:170px;">
94
94
  <div style="font-weight:700; font-size:12px; color:#c084fc; margin-bottom:3px;">${S.escapeHtml(D.nome_vertice||String(D.id))}</div>
95
- <div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">Confrontante: ${S.escapeHtml(g.nome||"Desconhecido")}</div>
95
+ <div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">Confrontante: ${S.escapeHtml(f.nome||"Desconhecido")}</div>
96
96
  <div style="font-size:10px; color:rgba(255, 255, 255, 0.45); font-family:var(--ui-fonte-codigo, monospace); margin-top:3px;">Lat ${N.lat.toFixed(6)} &nbsp; Lon ${N.lon.toFixed(6)}</div>
97
- ${V}
97
+ ${H}
98
98
  </div>
99
- `,{className:"compact-popup",maxWidth:220}),q.on("click",()=>{o.modoSequencial&&q.closePopup(),o.onMarkerClick&&o.onMarkerClick(D.id,!0,D,{lat:N.lat,lon:N.lon})}),q.on("popupopen",J=>{if(o.modoSequencial){q.closePopup();return}S.bindPopupAcoesEvents(J.popup,D,o,q)})}q.addTo(e)}})})}update(t,e,o,i,a){o.opacidade!==void 0&&o.estilo===void 0&&o.dados===void 0&&o.interativo===void 0&&o.bloqueada===void 0||(o.opacidade!==void 0||o.estilo!==void 0||o.dados!==void 0||o.interativo!==void 0||o.bloqueada!==void 0)&&(e.clearLayers(),this.rebuildPolygons(t,e,i,a))}destroy(t,e){t.clearLayers(),e.hasLayer(t)&&e.removeLayer(t)}}class Bo{constructor(){p(this,"moveListenerMap",new WeakMap)}render(t,e,o){const i=y.layerGroup(),a=`pane-${t.id}`,s=()=>{if(i.clearLayers(),!t.visivel)return;if(e.getZoom()>20){const c=e.getBounds(),l=c.getSouth(),d=c.getNorth(),h=c.getWest(),u=c.getEast(),m=e.getCenter(),f=8999e-9,g=Math.cos(m.lat*Math.PI/180),x=f/(g>.1?g:1),A=Math.floor((d-l)/f),M=Math.floor((u-h)/x);if(A<200&&M<200){const C=Math.ceil(l/f)*f;for(let P=C;P<=d;P+=f)y.polyline([[P,h],[P,u]],{color:t.estilo.corPrimaria||"rgba(0, 245, 160, 0.18)",weight:t.estilo.espessuraLinha||.6,interactive:!1,pane:a}).addTo(i);const z=Math.ceil(h/x)*x;for(let P=z;P<=u;P+=x)y.polyline([[l,P],[d,P]],{color:t.estilo.corPrimaria||"rgba(0, 245, 160, 0.18)",weight:t.estilo.espessuraLinha||.6,interactive:!1,pane:a}).addTo(i)}}};return s(),e.on("zoomend moveend",s),this.moveListenerMap.set(i,s),i}update(t,e){t.visivel||e.clearLayers()}destroy(t,e){const o=this.moveListenerMap.get(t);o&&(e.off("zoomend moveend",o),this.moveListenerMap.delete(t)),t.clearLayers(),e.hasLayer(t)&&e.removeLayer(t)}}function j(n){return n.partes&&n.partes.length>1?n.partes:[n.coordenadas]}function wt(n){return n.tipo==="LineString"&&!!n.partes&&n.partes.length>1}function yt(n){return n.length>1?{tipo:"LineString",coordenadas:n[0],partes:n}:{tipo:"LineString",coordenadas:n[0]}}const Pe=63710088e-1,it=n=>n*Math.PI/180;function st(n,t){const e=it(t[0]-n[0]),o=it(t[1]-n[1]),i=Math.sin(e/2)**2+Math.cos(it(n[0]))*Math.cos(it(t[0]))*Math.sin(o/2)**2;return 2*Pe*Math.asin(Math.min(1,Math.sqrt(i)))}function kt(n,t=!1){let e=0;for(let o=1;o<n.length;o++)e+=st(n[o-1],n[o]);return t&&n.length>2&&(e+=st(n[n.length-1],n[0])),e}function Qe(n){const t=it(n.reduce((i,a)=>i+a[0],0)/n.length),e=n.map(i=>[it(i[1])*Math.cos(t)*Pe,it(i[0])*Pe]);let o=0;for(let i=0;i<e.length;i++){const[a,s]=e[i],[r,c]=e[(i+1)%e.length];o+=a*c-r*s}return Math.abs(o)/2}function Ho(n){const[t,...e]=n;return t?Math.max(0,Qe(t)-e.reduce((o,i)=>o+Qe(i),0)):0}const un=new Intl.NumberFormat("pt-BR",{minimumFractionDigits:4,maximumFractionDigits:4}),to=new Intl.NumberFormat("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2});function rt(n){return`${un.format(n/1e4)} ha`}function G(n){return n>=1e3?`${to.format(n/1e3)} km`:`${to.format(n)} m`}function Q(n){return n.tipo==="Polygon"?Ho(n.aneis):n.tipo==="Circle"?Math.PI*n.raioMetros**2:null}function tt(n){return n.tipo==="LineString"?j(n).reduce((t,e)=>t+kt(e),0):n.tipo==="Polygon"?kt(n.aneis[0]??[],!0):n.tipo==="Circle"?2*Math.PI*n.raioMetros:null}function Vo(n,t){var i;const e=t??"name";if(e==="area"){const a=Q(n.geometria);return a===null?"":rt(a)}if(e==="extensao"){const a=tt(n.geometria);return a===null?"":G(a)}if(e==="id")return n.id;const o=(i=n.propriedades)==null?void 0:i[e];return o!=null&&o!==""?String(o):t?"":n.id}function De(n){let t;switch(n.tipo){case"Point":case"Text":t=[n.coordenada];break;case"LineString":t=j(n).flat();break;case"Polygon":t=n.aneis.flat();break;case"Circle":{const i=n.raioMetros/111320,a=i/Math.max(.01,Math.cos(it(n.centro[0])));t=[[n.centro[0]-i,n.centro[1]-a],[n.centro[0]+i,n.centro[1]+a]];break}}const e=t.map(i=>i[0]),o=t.map(i=>i[1]);return[[Math.min(...e),Math.min(...o)],[Math.max(...e),Math.max(...o)]]}const $t=16,pn=256;function Ce(n){const[[t,e],[o,i]]=De(n.geometria);return{minLon:e,minLat:t,maxLon:i,maxLat:o}}function mt(n,t){return n.minLon<=t.maxLon&&n.maxLon>=t.minLon&&n.minLat<=t.maxLat&&n.maxLat>=t.minLat}function eo(n){let t=1/0,e=1/0,o=-1/0,i=-1/0;for(const a of n)a.minLon<t&&(t=a.minLon),a.minLat<e&&(e=a.minLat),a.maxLon>o&&(o=a.maxLon),a.maxLat>i&&(i=a.maxLat);return{minLon:t,minLat:e,maxLon:o,maxLat:i}}function oo(n){const t=n.length,e=Math.ceil(t/$t),i=Math.ceil(Math.sqrt(e))*$t,a=[...n].sort((r,c)=>r.minLon+r.maxLon-(c.minLon+c.maxLon)),s=[];for(let r=0;r<t;r+=i){const c=a.slice(r,r+i).sort((l,d)=>l.minLat+l.maxLat-(d.minLat+d.maxLat));for(let l=0;l<c.length;l+=$t)s.push(c.slice(l,l+$t))}return s}function fn(n){if(n.length===0)return null;let t=oo(n).map(e=>({...eo(e),folhas:e}));for(;t.length>1;)t=oo(t).map(e=>({...eo(e),filhos:e}));return t[0]}class Go{constructor(){p(this,"raiz",null);p(this,"itens",new Map);p(this,"delta",new Map);p(this,"obsoletos",new Set)}get tamanho(){return this.itens.size}construir(t){this.itens.clear();for(const e of t)e.excluida||this.itens.set(e.id,{id:e.id,...Ce(e)});this.remontar()}inserir(t){this.atualizar(t)}atualizar(t){if(t.excluida){this.remover(t.id);return}const e={id:t.id,...Ce(t)};this.itens.has(t.id)&&this.obsoletos.add(t.id),this.itens.set(t.id,e),this.delta.set(t.id,e),this.compactarSeNecessario()}remover(t){this.itens.delete(t)&&(this.obsoletos.add(t),this.delta.delete(t),this.compactarSeNecessario())}limpar(){this.itens.clear(),this.remontar()}consultar(t){const e=[],o=this.raiz?[this.raiz]:[];for(;o.length>0;){const i=o.pop();if(mt(i,t))if(i.folhas)for(const a of i.folhas)!this.obsoletos.has(a.id)&&mt(a,t)&&e.push(a.id);else i.filhos&&o.push(...i.filhos)}for(const i of this.delta.values())mt(i,t)&&e.push(i.id);return e}intersecta(t){return this.consultar(t).length>0}caixaDe(t){return this.itens.get(t)}compactarSeNecessario(){this.delta.size+this.obsoletos.size>Math.max(pn,this.itens.size*.1)&&this.remontar()}remontar(){this.raiz=fn([...this.itens.values()]),this.delta.clear(),this.obsoletos.clear()}}const Xt=12,$e=40,mn=1.2;function jo(n){return n>=Xt?0:360/(256*2**n)*mn}function gn(n,t,e){const o=e[1]-t[1],i=e[0]-t[0],a=o*o+i*i;let s=a===0?0:((n[1]-t[1])*o+(n[0]-t[0])*i)/a;return s=Math.max(0,Math.min(1,s)),Math.hypot(n[1]-(t[1]+s*o),n[0]-(t[0]+s*i))}function qe(n,t){if(t<=0||n.length<3)return n;const e=new Uint8Array(n.length);e[0]=1,e[n.length-1]=1;const o=[[0,n.length-1]];for(;o.length>0;){const[i,a]=o.pop();let s=0,r=-1;for(let c=i+1;c<a;c++){const l=gn(n[c],n[i],n[a]);l>s&&(s=l,r=c)}r!==-1&&s>t&&(e[r]=1,o.push([i,r],[r,a]))}return n.filter((i,a)=>e[a]===1)}function Uo(n,t){if(t<=0||n.length<4)return n;const e=[...n,n[0]],o=qe(e,t);return o.pop(),o.length>=3?o:n}function Ne(n){return(n.tipo==="LineString"||n.tipo==="Polygon")&&n.curva?0:n.tipo==="LineString"?j(n).reduce((t,e)=>t+e.length,0):n.tipo==="Polygon"?n.aneis.reduce((t,e)=>t+e.length,0):0}function Wo(n,t){const e=jo(t);return e===0||Ne(n)<$e?n:n.tipo==="LineString"?yt(j(n).map(o=>qe(o,e))):n.tipo==="Polygon"?{tipo:"Polygon",aneis:n.aneis.map(o=>Uo(o,e))}:n}const vn=new Set(["previa","prévia","preview","rascunho","draft","proposta"]);function Y(n){var e,o;const t=[n.status,(e=n.propriedades)==null?void 0:e.status,(o=n.propriedades)==null?void 0:o.tipo_geometria];for(const i of t)if(typeof i=="string"&&vn.has(i.trim().toLowerCase()))return"previa";return"oficial"}function nt(n){var e;const t=n.entidadeId??((e=n.propriedades)==null?void 0:e.entidadeId);return typeof t=="string"||typeof t=="number"?String(t):n.id}const re=(n,t)=>`${n}\0${t}`;class Zt{constructor(){p(this,"global",!1);p(this,"individuais",new Set)}alternarIndividual(t,e){const o=re(t,e);return this.individuais.has(o)?this.individuais.delete(o):this.individuais.add(o),this.individuais.has(o)}definirIndividual(t,e,o){const i=re(t,e);o?this.individuais.add(i):this.individuais.delete(i)}individualAtiva(t,e){return this.individuais.has(re(t,e))}static oficiais(t){const e=new Set;for(const o of t)!o.excluida&&Y(o)==="oficial"&&e.add(nt(o));return e}visivel(t,e){if(Y(t)==="oficial")return!0;const o=nt(t);return this.global||!e.has(o)||this.individualAtiva(t.camadaId,o)}previaSolicitada(t){return this.global||this.individualAtiva(t.camadaId,nt(t))}}const yn=24,xn=2,io=n=>typeof n=="number"&&Number.isFinite(n),ce=n=>Array.isArray(n)&&n.length===2&&io(n[0])&&io(n[1]);function Oe(n,t){return[2*n[0]-t[0],2*n[1]-t[1]]}function Xo(n){return n.some(t=>t.entrada!==void 0||t.saida!==void 0)}function It(n,t){return[n.saida??n.ponto,t.entrada??t.ponto]}function Zo(n,t){const e=[];for(let o=0;o<n-1;o++)e.push([o,o+1]);return t&&n>2&&e.push([n-1,0]),e}function Fe(n,t,e,o,i){const a=1-i,s=a*a*a,r=3*a*a*i,c=3*a*i*i,l=i*i*i;return[s*n[0]+r*t[0]+c*e[0]+l*o[0],s*n[1]+r*t[1]+c*e[1]+l*o[1]]}function xt(n,t=!1,e=yn){if(n.length===0)return[];const o=[[n[0].ponto[0],n[0].ponto[1]]];for(const[i,a]of Zo(n.length,t)){const s=n[i],r=n[a];if(!(s.saida===void 0&&r.entrada===void 0)){const[l,d]=It(s,r);for(let h=1;h<e;h++)o.push(Fe(s.ponto,l,d,r.ponto,h/e))}a!==0&&o.push([r.ponto[0],r.ponto[1]])}return o}function Yo(n,t){if(n.length===0)return[];const e=[{cmd:"M",pts:[n[0].ponto]}];for(const[o,i]of Zo(n.length,t)){const a=n[o],s=n[i];if(a.saida===void 0&&s.entrada===void 0)e.push({cmd:"L",pts:[s.ponto]});else{const[r,c]=It(a,s);e.push({cmd:"C",pts:[r,c,s.ponto]})}}return e}function bn(n,t,e){const o=a=>String(Math.round(a*100)/100),i=Yo(n,t).map(a=>a.cmd+a.pts.map(s=>{const r=e(s);return`${o(r.x)} ${o(r.y)}`}).join(" ")).join("");return i&&t?`${i}Z`:i}function Pn(n,t=xn){if(!Array.isArray(n)||n.length<t)return null;const e=[];for(const o of n){if(!o||typeof o!="object"||!ce(o.ponto))return null;const i=o,a={ponto:[i.ponto[0],i.ponto[1]]};ce(i.entrada)&&(a.entrada=[i.entrada[0],i.entrada[1]]),ce(i.saida)&&(a.saida=[i.saida[0],i.saida[1]]),e.push(a)}return Xo(e)?e:null}function no(n,t){return n.map(e=>{const o={ponto:t(e.ponto)};return e.entrada&&(o.entrada=t(e.entrada)),e.saida&&(o.saida=t(e.saida)),o})}function Ko(n,t){var s,r;const e=n._nosCurva,o=n._renderer,i=n._map;if(!e||e.length<2||!o||!i)return!1;const a=c=>i.latLngToLayerPoint([c[0],c[1]]);if(o._ctx&&o._fillStroke){if(!o._drawing||!((s=n._parts)!=null&&s.length))return!0;const c=o._ctx;c.beginPath();for(const l of Yo(e,t)){const d=l.pts.map(a);l.cmd==="M"?c.moveTo(d[0].x,d[0].y):l.cmd==="L"?c.lineTo(d[0].x,d[0].y):c.bezierCurveTo(d[0].x,d[0].y,d[1].x,d[1].y,d[2].x,d[2].y)}return t&&c.closePath(),o._fillStroke(c,n),!0}return o._setPath?(o._setPath(n,(r=n._parts)!=null&&r.length?bn(e,t,a):"M0 0"),!0):!1}class Jo extends y.Polyline{constructor(){super(...arguments);p(this,"_nosCurva",null)}definirCurva(e){this._nosCurva=e}_updatePath(){Ko(this,!1)||y.Polyline.prototype._updatePath.call(this)}}class Qo extends y.Polygon{constructor(){super(...arguments);p(this,"_nosCurva",null)}definirCurva(e){this._nosCurva=e}_updatePath(){Ko(this,!0)||y.Polygon.prototype._updatePath.call(this)}}function Yt(n){return n.tipo==="LineString"?n.curva&&n.curva.length>=2&&!(n.partes&&n.partes.length>1)?n.curva:null:n.tipo==="Polygon"&&n.curva&&n.curva.length>=3&&n.aneis.length===1?n.curva:null}function ti(n,t){const e=Yt(n);if(!e)return null;const o=n.tipo==="Polygon"?new Qo(n.aneis[0],t):new Jo(n.coordenadas,t);return o.definirCurva(e),o}function Cn(n,t){n.definirCurva(Yt(t)),n.setLatLngs(t.tipo==="Polygon"?t.aneis[0]:t.coordenadas)}const zt=55,ei=17,oi=8;function Kt(n,t){return t<ei&&n>oi}function ii(n){let t=0,e=0;for(const o of n)t+=o.coordenada[0],e+=o.coordenada[1];return[t/n.length,e/n.length]}function Ln(n,t,e){if(!Kt(n.length,t))return{clusters:[],isolados:n};const o=new Map;for(const s of n){const{x:r,y:c}=e(s.coordenada),l=`${t}:${Math.floor(r/zt)}:${Math.floor(c/zt)}`,d=o.get(l);d?d.push(s):o.set(l,[s])}const i=[],a=[];for(const[s,r]of o)r.length===1?a.push(r[0]):i.push({chave:s,coordenada:ii(r),membros:r});return{clusters:i,isolados:a}}class ni{constructor(t,e){p(this,"celulas",new Map);p(this,"celulaDe",new Map);p(this,"multiplas",new Set);this.zoom=t,this.projetar=e}get total(){return this.celulaDe.size}chaveDoPonto(t){return this.celulaDe.get(t)}celula(t){return this.celulas.get(t)}*celulasAgrupadas(){for(const t of this.multiplas){const e=this.celulas.get(t);e&&(yield[t,e])}}emCluster(t){var o;const e=this.celulaDe.get(t);return e!==void 0&&(((o=this.celulas.get(e))==null?void 0:o.membros.size)??0)>=2}inserir(t){this.remover(t.id);const{x:e,y:o}=this.projetar(t.coordenada),i=`${this.zoom}:${Math.floor(e/zt)}:${Math.floor(o/zt)}`;let a=this.celulas.get(i);return a||(a={membros:new Map,somaLat:0,somaLon:0},this.celulas.set(i,a)),a.membros.set(t.id,t),a.somaLat+=t.coordenada[0],a.somaLon+=t.coordenada[1],a.membros.size>=2&&this.multiplas.add(i),this.celulaDe.set(t.id,i),i}remover(t){const e=this.celulaDe.get(t);if(e===void 0)return;this.celulaDe.delete(t);const o=this.celulas.get(e),i=o==null?void 0:o.membros.get(t);return o&&i&&(o.membros.delete(t),o.somaLat-=i.coordenada[0],o.somaLon-=i.coordenada[1],o.membros.size<2&&this.multiplas.delete(e),o.membros.size===0&&this.celulas.delete(e)),e}}const Ft={tower:'<path d="M12 2 L8 22 M12 2 L16 22 M9.5 12 H14.5 M8.7 17 H15.3 M12 2 L9.5 12 L14.5 12 Z" />',tree:'<path d="M12 22 V14 M12 3 L5 14 H19 Z" />',warning:'<path d="M12 3 L22 20 H2 Z M12 9 V14 M12 17 V17.5" />',water:'<path d="M12 3 C12 3 5 11 5 15.5 A7 7 0 0 0 19 15.5 C19 11 12 3 12 3 Z" />',boundary:'<path d="M12 2 L22 12 L12 22 L2 12 Z" />'},le="#38bdf8",Sn=/^(#[0-9a-f]{3,8}|(rgb|hsl)a?\([0-9.,%\s\/-]+\)|[a-z]{3,20})$/i;function Z(n,t){return n&&Sn.test(n.trim())?n.trim():t}const ft="#38bdf8",Mn=150,An=100,Le=300,ao=.75,wn=.3,de=typeof requestAnimationFrame=="function"?n=>{requestAnimationFrame(n)}:n=>{setTimeout(n,16)};class ai{constructor(){p(this,"estados",new WeakMap);p(this,"selecionadas",new WeakMap);p(this,"tokenLote",new WeakMap)}render(t,e,o){const i=y.layerGroup();return this.sincronizar(t,i,e,o,!0),i}update(t,e,o,i,a){if(o.dados===void 0&&o.estilo===void 0&&o.interativo===void 0&&o.bloqueada===void 0)return;const s=o.estilo!==void 0||o.interativo!==void 0||o.bloqueada!==void 0;this.sincronizar(t,e,a,i,s)}destroy(t,e){const o=this.estados.get(t);o&&(o.vivo=!1,e.off("moveend zoomend",o.aoMover)),t.clearLayers(),this.estados.delete(t),this.tokenLote.set(t,(this.tokenLote.get(t)??0)+1),e.hasLayer(t)&&e.removeLayer(t)}reavaliarVersoes(t){const e=this.estados.get(t);e&&(e.revisao++,e.revisaoBase++,this.reconciliar(t,e,!1,null))}feicaoVisivel(t,e){const o=this.estados.get(t),i=o==null?void 0:o.context.regraVersoes;return!o||!i||i.visivel(e,o.oficiais)}consultarProximas(t,e){const o=this.estados.get(t);if(!o)return[];const i=[];for(const a of o.indice.consultar(e)){const s=o.loja.get(a);s&&!s.oculta&&i.push(s)}return i}previsualizar(t,e){var s;const o=this.estados.get(t),i=o==null?void 0:o.entradas.get(e.id);if(!o||!i)return;const a=o.map._loaded?o.map.getZoom():0;this.remendar(i.layer,this.paraDesenho(e,a),o.layerDef,o.interativo,!!((s=this.selecionadas.get(o.layerDef))!=null&&s.has(e.id)))}estatisticas(t){const e=this.estados.get(t);return e?{total:e.loja.size,materializadas:e.entradas.size,clusters:e.clusters.size}:null}feicoesDe(t){const e=t.dados,o=Array.isArray(e)?e:e==null?void 0:e.feicoes;return Array.isArray(o)?o:[]}obterEstado(t,e,o,i){let a=this.estados.get(t);if(!a){const s={layerDef:e,interativo:!1,map:o,context:i,loja:new Map,indice:new Go,revisao:0,revisaoBase:0,listaSincronizada:null,oficiais:new Set,contOficiais:new Map,nPrevias:0,entradas:new Map,clusters:new Map,nPontos:0,nPontosRev:-1,agrupador:null,agrupadorRev:-1,culling:!1,agendado:!1,vivo:!0,aoMover:()=>{s.agendado||!s.vivo||(s.agendado=!0,de(()=>{s.agendado=!1,s.vivo&&this.reconciliar(t,s,!1,null)}))}};o.on("moveend zoomend",s.aoMover),this.estados.set(t,s),a=s}return a.layerDef=e,a.map=o,a.context=i,a.interativo=e.interativo&&!e.bloqueada,a}sincronizar(t,e,o,i,a){var f;const s=this.obterEstado(e,t,o,i),r=this.feicoesDe(t),c=(f=t.dados)==null?void 0:f.delta;if(!a&&this.aplicarDelta(e,s,r,c))return;const l=r.filter(g=>!g.excluida),d=new Set,h=new Set;for(const g of l)h.add(g.id),s.loja.get(g.id)!==g&&d.add(g.id);const u=[...s.loja.keys()].filter(g=>!h.has(g));if(d.size>0||u.length>0){if(s.revisao++,s.revisaoBase++,s.loja.size===0||d.size+u.length>l.length*wn)s.indice.construir(l);else{for(const g of l)d.has(g.id)&&s.indice.atualizar(g);for(const g of u)s.indice.remover(g)}s.loja=new Map(l.map(g=>[g.id,g])),this.recontarOficiais(s,l)}s.listaSincronizada=r;const m=this.selecionadas.get(t);if(m)for(const g of[...m])h.has(g)||m.delete(g);this.reconciliar(e,s,a,d)}recontarOficiais(t,e){t.contOficiais=new Map,t.nPrevias=0;for(const o of e){if(o.excluida)continue;if(Y(o)!=="oficial"){t.nPrevias++;continue}const i=nt(o);t.contOficiais.set(i,(t.contOficiais.get(i)??0)+1)}t.oficiais=new Set(t.contOficiais.keys())}aplicarDelta(t,e,o,i){if(!i||i.base!==e.listaSincronizada)return!1;const{loja:a}=e,s=this.selecionadas.get(e.layerDef),r=f=>f.geometria.tipo==="Point"&&this.desenhavel(e,f),c=new Map,l=(f,g)=>{if(!f||f.excluida||Y(f)!=="oficial")return;const x=nt(f);c.has(x)||c.set(x,e.oficiais.has(x));const A=(e.contOficiais.get(x)??0)+g;A<=0?(e.contOficiais.delete(x),e.oficiais.delete(x)):(e.contOficiais.set(x,A),e.oficiais.add(x))},d=[],h=[],u=f=>{const g=a.get(f);g&&(Y(g)==="previa"&&e.nPrevias--,l(g,-1),r(g)&&e.nPontos--,a.delete(f),e.indice.remover(f),s==null||s.delete(f),h.push(f))};for(const f of i.removidas)u(f);for(const f of i.mudadas){if(f.excluida){u(f.id);continue}const g=a.get(f.id);Y(f)==="previa"&&e.nPrevias++,g&&(Y(g)==="previa"&&e.nPrevias--,l(g,-1),r(g)&&e.nPontos--),a.set(f.id,f),e.indice.atualizar(f),l(f,1),r(f)&&e.nPontos++,d.push(f.id)}let m=!1;if(e.nPrevias>0)for(const[f,g]of c)g!==e.oficiais.has(f)&&(m=!0);return e.listaSincronizada=o,e.revisao++,m&&e.revisaoBase++,this.reconciliarParcial(t,e,d,h,m),!0}ressimplificar(t,e){return t.zoomDesenho===e||Ne(t.feicao.geometria)<$e?!1:e<Xt||t.zoomDesenho<Xt}paraDesenho(t,e){const o=Wo(t.geometria,e);return o===t.geometria?t:{...t,geometria:o}}desenhavel(t,e){if(e.oculta)return!1;const o=t.context.regraVersoes;return!o||o.visivel(e,t.oficiais)}estaCarregado(t){return!!t._loaded}caixaDe(t){return{minLon:t.getWest(),minLat:t.getSouth(),maxLon:t.getEast(),maxLat:t.getNorth()}}materializar(t,e,o,i,a,s){const r=this.formaDe(o),c=e.entradas.get(o.id),l=this.paraDesenho(o,i);if(c&&c.forma===r){(s||c.feicao!==o||this.ressimplificar(c,i))&&(this.remendar(c.layer,l,e.layerDef,e.interativo,a),c.feicao=o,c.zoomDesenho=i);return}c&&t.removeLayer(c.layer);const d=this.criar(l,e.layerDef,e.map,e.interativo,a);this.ligarEventos(d,o.id,e.layerDef,e.entradas,e.context),this.aplicarRotulo(d,o),t.addLayer(d),e.entradas.set(o.id,{layer:d,forma:r,feicao:o,zoomDesenho:i})}tirarEntrada(t,e,o){const i=e.entradas.get(o);i&&(t.removeLayer(i.layer),e.entradas.delete(o))}colocarCluster(t,e,o,i){const a=e.clusters.get(o);if((a==null?void 0:a.assinatura)===i.assinatura)return;a&&t.removeLayer(a.marker);const s=this.criarMarcadorCluster(i.coordenada,i.total,()=>{var r,c;return Array.from(((c=(r=e.agrupador)==null?void 0:r.celula(o))==null?void 0:c.membros.values())??[])},e);t.addLayer(s),e.clusters.set(o,{marker:s,assinatura:i.assinatura})}tirarCluster(t,e,o){const i=e.clusters.get(o);i&&(t.removeLayer(i.marker),e.clusters.delete(o))}agrupadorAtivo(t,e){const o=s=>this.desenhavel(t,s);if(t.nPontosRev!==t.revisaoBase){let s=0;for(const r of t.loja.values())r.geometria.tipo==="Point"&&o(r)&&s++;t.nPontos=s,t.nPontosRev=t.revisaoBase}if(!Kt(t.nPontos,e))return t.agrupador=null,null;const i=t.agrupador;if(i&&i.zoom===e&&t.agrupadorRev===t.revisaoBase)return i;const a=new ni(e,s=>t.map.project(y.latLng(s[0],s[1]),e));for(const s of t.loja.values())s.geometria.tipo==="Point"&&o(s)&&a.inserir({id:s.id,coordenada:s.geometria.coordenada});return t.agrupador=a,t.agrupadorRev=t.revisaoBase,a}reconciliar(t,e,o,i){var A;const{map:a,layerDef:s,loja:r}=e,c=this.selecionadas.get(s),l=this.estaCarregado(a),d=l?a.getZoom():0,h=l&&r.size>Le?a.getBounds().pad(ao):null,u=h?this.caixaDe(h):null;e.culling=h!==null;const m=u?e.indice.consultar(u):r.keys(),f=new Set(m);if(c)for(const M of c)r.has(M)&&f.add(M);for(const M of[...f]){const C=r.get(M);C&&!this.desenhavel(e,C)&&f.delete(M)}const g=new Map,x=l?this.agrupadorAtivo(e,d):null;if(x||(e.agrupador=null),x){for(const C of[...f])x.emCluster(C)&&f.delete(C);const M=new Map;if(c)for(const C of c){const z=x.chaveDoPonto(C),P=z===void 0||(A=x.celula(z))==null?void 0:A.membros.get(C);if(z!==void 0&&P){const v=M.get(z);v?v.push(P):M.set(z,[P])}}for(const[C,z]of x.celulasAgrupadas()){const P=M.get(C);if(P)for(const k of P)f.add(k.id);const v=z.membros.size,b=v-((P==null?void 0:P.length)??0);if(b===1)for(const k of z.membros.values()){if(c!=null&&c.has(k.id))continue;const E=e.indice.caixaDe(k.id);(!u||E&&mt(E,u))&&f.add(k.id);break}if(!(h&&!h.contains([z.somaLat/v,z.somaLon/v]))&&b>=2){let k=z.somaLat,E=z.somaLon;if(P)for(const w of P)k-=w.coordenada[0],E-=w.coordenada[1];const L=[k/b,E/b];g.set(C,{coordenada:L,total:v,assinatura:`${C}:${v}:${b}:${L[0].toFixed(7)}:${L[1].toFixed(7)}`})}}}for(const M of f){const C=r.get(M);C&&this.materializar(t,e,C,d,!!(c!=null&&c.has(M)),o||!!(i!=null&&i.has(M)))}for(const M of[...e.entradas.keys()])f.has(M)&&r.has(M)||this.tirarEntrada(t,e,M);for(const[M,C]of g)this.colocarCluster(t,e,M,C);for(const M of[...e.clusters.keys()])g.has(M)||this.tirarCluster(t,e,M)}reconciliarParcial(t,e,o,i,a){const{map:s,layerDef:r,loja:c}=e,l=this.estaCarregado(s),d=l?s.getZoom():0,h=l&&c.size>Le,u=l&&Kt(e.nPontos,d),m=e.agrupador;if(a||h!==e.culling||u!==(m!==null)||m!==null&&(m.zoom!==d||e.agrupadorRev!==e.revisaoBase)){this.reconciliar(t,e,!1,new Set(o));return}const f=this.selecionadas.get(r),g=v=>this.desenhavel(e,v),x=h?s.getBounds().pad(ao):null,A=x?this.caixaDe(x):null,M=(v,b)=>{const k=c.get(v);if(!k||!g(k)){this.tirarEntrada(t,e,v);return}const E=!!(f!=null&&f.has(v));if(!E&&A){const L=e.indice.caixaDe(v);if(!L||!mt(L,A)){this.tirarEntrada(t,e,v);return}}this.materializar(t,e,k,d,E,b)},C=new Set,z=[];for(const v of i){this.tirarEntrada(t,e,v);const b=m==null?void 0:m.remover(v);b!==void 0&&C.add(b)}for(const v of o){const b=c.get(v);if(!b)continue;const k=m==null?void 0:m.remover(v);k!==void 0&&C.add(k),m&&b.geometria.tipo==="Point"&&g(b)?C.add(m.inserir({id:v,coordenada:b.geometria.coordenada})):z.push(v)}for(const v of z)M(v,!0);if(!m)return;const P=new Set(o);for(const v of C){const b=m.celula(v);if(!b||b.membros.size<2){if(this.tirarCluster(t,e,v),b)for(const T of b.membros.keys())M(T,P.has(T));continue}const k=b.membros.size;let E=b.somaLat,L=b.somaLon,w=0;for(const T of b.membros.values())f!=null&&f.has(T.id)&&(w++,E-=T.coordenada[0],L-=T.coordenada[1]);const I=k-w;for(const T of b.membros.values())f!=null&&f.has(T.id)||I===1?M(T.id,P.has(T.id)):this.tirarEntrada(t,e,T.id);const _=[b.somaLat/k,b.somaLon/k];if(x&&!x.contains(_)||I<2){this.tirarCluster(t,e,v);continue}const O=[E/I,L/I];this.colocarCluster(t,e,v,{coordenada:O,total:k,assinatura:`${v}:${k}:${I}:${O[0].toFixed(7)}:${O[1].toFixed(7)}`})}}criarMarcadorCluster(t,e,o,i){const a=e<10?30:e<100?38:46,s=Z(i.layerDef.estilo.corPrimaria,le),r=y.divIcon({className:"custom-leaflet-marker cad-feicao-cluster",iconSize:[a,a],html:`<div style="width:${a}px;height:${a}px;border-radius:50%;background:${s};opacity:.9;border:2px solid rgba(255,255,255,.85);display:flex;align-items:center;justify-content:center;color:#fff;font:700 12px sans-serif;text-shadow:0 0 2px #000">${e}</div>`}),c=y.marker(t,{icon:r,pane:at(i.map,i.layerDef.id,"ponto"),keyboard:!1});return c.bindTooltip(`${e} feições agrupadas`,{direction:"top"}),c.on("click",()=>{const l=o();l.length>0&&i.map.fitBounds(y.latLngBounds(l.map(d=>d.coordenada)),{padding:[60,60],maxZoom:18})}),c}aplicarSelecao(t,e){const o=this.estados.get(t);if(!o)return;const i=this.selecionadas.get(o.layerDef)??new Set,a=new Set(e);this.selecionadas.set(o.layerDef,a);const s=[];for(const d of a)i.has(d)||s.push(d);for(const d of i)a.has(d)||s.push(d);if(s.length===0)return;const r=o.entradas,c=d=>{const h=r.get(d);if(!h)return;const u=a.has(d);this.remendar(h.layer,this.paraDesenho(h.feicao,h.zoomDesenho),o.layerDef,o.interativo,u),u&&"bringToFront"in h.layer&&h.layer.bringToFront()},l=(this.tokenLote.get(t)??0)+1;if(this.tokenLote.set(t,l),s.length<=Mn)s.forEach(c);else{const h=!!o.map._loaded?o.map.getBounds():null,u=x=>{var M;const A=(M=r.get(x))==null?void 0:M.layer;return h?A!=null&&A.getBounds?h.intersects(A.getBounds()):A!=null&&A.getLatLng?h.contains(A.getLatLng()):!0:!0},m=s.filter(u),f=s.filter(x=>!u(x));m.forEach(c);const g=()=>{this.tokenLote.get(t)===l&&(f.splice(0,An).forEach(c),f.length>0&&de(g))};f.length>0&&de(g)}this.reconciliar(t,o,!1,null)}formaDe(t){var o;const e=t.geometria;return e.tipo==="Point"?`Point:${(o=t.estilo)!=null&&o.icone&&Ft[t.estilo.icone]?t.estilo.icone:""}`:Yt(e)?`${e.tipo}:curva`:e.tipo}paneDe(t){switch(t.geometria.tipo){case"Polygon":case"Circle":return"poligono";case"LineString":return"linha";case"Point":return"ponto";default:return"texto"}}estiloVetor(t,e,o,i=!1){const a=t.estilo??{},s=Z(a.corTraco??e.estilo.corPrimaria,le),r=t.geometria.tipo==="Polygon"||t.geometria.tipo==="Circle",c=t.geometria.tipo==="Point",l=c&&Z(a.corContorno,"")||s,d=c&&typeof a.espessuraContorno=="number"&&Number.isFinite(a.espessuraContorno)&&a.espessuraContorno>=0?a.espessuraContorno:void 0,h=d??a.espessuraTraco??e.estilo.espessuraLinha??2,u=a.opacidadePreenchimento??(r?.2:.85);return{color:i?ft:l,stroke:!(d===0&&!i),weight:i?h+2:h,dashArray:a.dashArray??(Y(t)==="previa"?"6 4":e.estilo.dashArray),fill:r||t.geometria.tipo==="Point",fillColor:Z(a.corPreenchimento,s),fillOpacity:i?Math.min(1,u+.18):u,lineJoin:"round",interactive:o}}criar(t,e,o,i,a){var d,h;const s=at(o,e.id,this.paneDe(t)),r=t.geometria,c=this.estiloVetor(t,e,i,a),l=ti(r,{...c,pane:s});if(l)return l;switch(r.tipo){case"Polygon":return y.polygon(r.aneis.length===1?r.aneis[0]:r.aneis,{...c,pane:s});case"Circle":return y.circle(r.centro,{...c,radius:r.raioMetros,pane:s});case"LineString":return y.polyline(r.partes&&r.partes.length>1?j(r):r.coordenadas,{...c,pane:s});case"Point":{const u=(d=t.estilo)==null?void 0:d.icone;return u&&Ft[u]?y.marker(r.coordenada,{icon:this.iconeSvg(t,e,a),pane:s,interactive:i}):y.circleMarker(r.coordenada,{...c,radius:(((h=t.estilo)==null?void 0:h.tamanhoIcone)??e.estilo.tamanhoMarcador??8)/2,pane:s})}default:return y.marker(r.coordenada,{icon:this.iconeTexto(t,e,a),pane:s,interactive:i,draggable:i&&!t.bloqueada})}}remendar(t,e,o,i,a){var c,l,d;const s=e.geometria,r=this.estiloVetor(e,o,i,a);(t instanceof Jo||t instanceof Qo)&&Yt(s)?(Cn(t,s),t.setStyle(r)):s.tipo==="Polygon"?(t.setLatLngs(s.aneis.length===1?s.aneis[0]:s.aneis),t.setStyle(r)):s.tipo==="LineString"?(t.setLatLngs(s.partes&&s.partes.length>1?j(s):s.coordenadas),t.setStyle(r)):s.tipo==="Circle"?(t.setLatLng(s.centro),t.setRadius(s.raioMetros),t.setStyle(r)):s.tipo==="Point"&&t instanceof y.CircleMarker?(t.setLatLng(s.coordenada),t.setRadius((((c=e.estilo)==null?void 0:c.tamanhoIcone)??o.estilo.tamanhoMarcador??8)/2),t.setStyle(r)):t instanceof y.Marker&&(t.setLatLng(s.tipo==="Point"||s.tipo==="Text"?s.coordenada:t.getLatLng()),t.setIcon(s.tipo==="Text"?this.iconeTexto(e,o,a):this.iconeSvg(e,o,a)),s.tipo==="Text"&&(i&&!e.bloqueada?(l=t.dragging)==null||l.enable():(d=t.dragging)==null||d.disable())),this.aplicarRotulo(t,e)}iconeSvg(t,e,o=!1){const i=t.estilo??{},a=i.tamanhoIcone??e.estilo.tamanhoMarcador,s=typeof a=="number"&&Number.isFinite(a)&&a>0?a:22,r=o?ft:Z(i.corTraco??i.corPreenchimento??e.estilo.corPrimaria,le),c=Number.isFinite(i.rotacaoIcone)?i.rotacaoIcone:0,l=Ft[i.icone??""]??"";return y.divIcon({className:`custom-leaflet-marker${o?" cad-feicao-selecionada":""}`,iconSize:[s,s],html:`<svg width="${s}" height="${s}" viewBox="0 0 24 24" fill="${r}" fill-opacity="0.25" stroke="${r}" stroke-width="1.6" stroke-linejoin="round" stroke-linecap="round" style="transform:rotate(${c}deg);overflow:visible;display:block${o?`;filter:drop-shadow(0 0 3px ${ft})`:""}">${l}</svg>`})}iconeTexto(t,e,o=!1){const i=t.estilo??{},a=t.geometria.tipo==="Text"?t.geometria.texto:"",s=o?ft:Z(i.corTraco??e.estilo.corPrimaria,"#ffffff"),r=Number.isFinite(i.tamanhoFonte)?i.tamanhoFonte:13,l=`display:inline-block;white-space:nowrap;transform:translate(-50%,-50%) rotate(${Number.isFinite(i.rotacaoIcone)?i.rotacaoIcone:0}deg);color:${s};font-size:${r}px;font-weight:600;`,d=Z(i.corFundo,"");if(d){const u=Z(i.corBorda,""),m=typeof i.opacidadeFundo=="number"&&Number.isFinite(i.opacidadeFundo)?Math.min(1,Math.max(0,i.opacidadeFundo)):.85,f=typeof i.raioBorda=="number"&&Number.isFinite(i.raioBorda)?Math.min(50,Math.max(0,i.raioBorda)):4,g=o?`1px solid ${ft}`:u?`1px solid ${u}`:"none";return y.divIcon({className:`custom-leaflet-marker cad-feicao-texto cad-feicao-selo${o?" cad-feicao-selecionada":""}`,iconSize:void 0,html:`<span style="${l}position:relative;padding:2px 6px;border-radius:${f}px;border:${g}"><span style="position:absolute;top:0;right:0;bottom:0;left:0;border-radius:inherit;background:${d};opacity:${m}"></span><span style="position:relative">${S.escapeHtml(a)}</span></span>`})}const h=i.halo?"text-shadow:-1px -1px 0 #000,1px -1px 0 #000,-1px 1px 0 #000,1px 1px 0 #000;":"";return y.divIcon({className:`custom-leaflet-marker cad-feicao-texto${o?" cad-feicao-selecionada":""}`,iconSize:void 0,html:`<span style="${l}${h}">${S.escapeHtml(a)}</span>`})}aplicarRotulo(t,e){const o=e.estilo;if(!(o!=null&&o.mostrarRotulo)||e.geometria.tipo==="Text"){t.unbindTooltip();return}const i=Vo(e,o.campoRotulo);if(!i){t.unbindTooltip();return}const a=document.createElement("span");a.textContent=i,t.getTooltip()?t.setTooltipContent(a):t.bindTooltip(a,{permanent:!0,direction:"center",className:"cad-feicao-rotulo",interactive:!1})}ligarEventos(t,e,o,i,a){t.on("click",s=>{var l;const r=i.get(e);if(!r)return;const c=s==null?void 0:s.originalEvent;(l=a.onLayerAction)==null||l.call(a,"feicao-clique",{camadaId:o.id,feicao:r.feicao,aditivo:!!(c&&(c.ctrlKey||c.metaKey||c.shiftKey))})}),t instanceof y.Marker&&t.on("dragend",()=>{var l;const s=i.get(e);if(!s||s.feicao.geometria.tipo!=="Text")return;const{lat:r,lng:c}=t.getLatLng();s.feicao={...s.feicao,geometria:{...s.feicao.geometria,coordenada:[r,c]}},(l=a.onLayerAction)==null||l.call(a,"feicao-movida",{camadaId:o.id,feicao:s.feicao})})}}F.register("tile",new Do);F.register("wms",new $o);F.register("vetorial-linhas",new No);F.register("vetorial-pontos",new Fo);F.register("vetorial-poligonos",new Ro);F.register("grid",new Bo);F.register("feicoes",new ai);const Se=[{id:"satelite",nome:"Satélite Google Híbrido",categoria:"base",tipo:"tile",visivel:!0,opacidade:1,zIndex:200,interativo:!1,bloqueada:!1,estilo:{scaleMode:"screen"}},{id:"sigef",nome:"Acervo Fundiário SIGEF (INCRA)",categoria:"wms",tipo:"wms",visivel:!0,opacidade:.85,zIndex:390,interativo:!0,bloqueada:!1,estilo:{scaleMode:"screen"}},{id:"homologados",nome:"Poligonal Homologada (Banco)",categoria:"referencia",tipo:"vetorial-linhas",visivel:!0,opacidade:.9,zIndex:420,interativo:!0,bloqueada:!1,estilo:{corPrimaria:"#f59e0b",espessuraLinha:1,dashArray:"6, 8",scaleMode:"screen"}},{id:"homologados-pontos",nome:"Marcos Homologados (Banco)",categoria:"referencia",tipo:"vetorial-pontos",visivel:!0,opacidade:1,zIndex:430,interativo:!0,bloqueada:!1,estilo:{tamanhoMarcador:8,estiloMarcador:"circle",scaleMode:"screen"}},{id:"perimetro",nome:"Divisas e Poligonal do Imóvel",categoria:"levantamento",tipo:"vetorial-linhas",visivel:!0,opacidade:1,zIndex:520,interativo:!0,bloqueada:!1,estilo:{corPrimaria:"#00f5a0",espessuraLinha:1,scaleMode:"screen",dimensaoMetros:.3}},{id:"vizinhos",nome:"Imóveis Confrontantes (WKT/CSV)",categoria:"referencia",tipo:"vetorial-poligonos",visivel:!0,opacidade:.8,zIndex:440,interativo:!0,bloqueada:!1,estilo:{corPrimaria:"#a855f7",espessuraLinha:1,dashArray:"4, 6",scaleMode:"screen"}},{id:"vertices",nome:"Vértices e Marcos do Levantamento",categoria:"levantamento",tipo:"vetorial-pontos",visivel:!0,opacidade:1,zIndex:650,interativo:!0,bloqueada:!1,estilo:{tamanhoMarcador:8,scaleMode:"screen",dimensaoMetros:.25}},{id:"grade",nome:"Grade de Coordenadas UTM",categoria:"referencia",tipo:"grid",visivel:!0,opacidade:.5,zIndex:700,interativo:!1,bloqueada:!1,estilo:{corPrimaria:"rgba(0, 245, 160, 0.18)",espessuraLinha:.6,scaleMode:"screen"}}],kn=new Set(["tile","wms","grid"]);class si{constructor(t){p(this,"layers",[]);p(this,"layerInstances",new Map);p(this,"map",null);p(this,"context",null);p(this,"listeners",[]);p(this,"renderPendente",!1);this.layers=(t||Se).map(e=>({...e,estilo:{...e.estilo}}))}descartarCamadasPadrao(){if(this.map)return;const t=new Set(Se.map(e=>e.id));this.layers=this.layers.filter(e=>!t.has(e.id)||e.tipo==="feicoes")}attachMap(t,e){this.map=t,this.context=e,this.ensurePanes(),this.renderAllLayers()}ensurePanes(){this.map&&this.layers.forEach(t=>{const e=`pane-${t.id}`;let o=this.map.getPane(e);o||(o=this.map.createPane(e)),o&&(o.style.zIndex=String(t.zIndex),o.style.pointerEvents=t.interativo&&!t.bloqueada&&t.visivel?"auto":"none")})}renderAllLayers(t=!1){this.renderPendente=!1,!(!this.map||!this.context)&&(this.layers.forEach(e=>{if(!(t&&kn.has(e.tipo)&&e.visivel&&this.layerInstances.has(e.id))){if(this.layerInstances.has(e.id)){const o=this.layerInstances.get(e.id),i=F.get(e.tipo);i&&i.destroy(o,this.map),this.layerInstances.delete(e.id)}if(e.visivel){const o=F.get(e.tipo);if(o){const i=o.render(e,this.map,this.context);i&&(i.addTo(this.map),this.layerInstances.set(e.id,i))}}}}),this.notifyChange())}flushRender(){this.renderPendente&&this.renderAllLayers(!0)}agendarRender(){this.renderPendente||(this.renderPendente=!0,queueMicrotask(()=>this.flushRender()))}setLayerVisibility(t,e){this.flushRender();const o=this.layers.find(s=>s.id===t);if(!o||o.visivel===e||(o.visivel=e,!this.map||!this.context))return;const i=`pane-${o.id}`,a=this.map.getPane(i);if(a&&(a.style.display=e?"":"none",a.style.pointerEvents=o.visivel&&o.interativo&&!o.bloqueada?"auto":"none"),e){if(!this.layerInstances.has(t)){const s=F.get(o.tipo);if(s){const r=s.render(o,this.map,this.context);r&&(r.addTo(this.map),this.layerInstances.set(t,r))}}}else if(this.layerInstances.has(t)){const s=this.layerInstances.get(t),r=F.get(o.tipo);r&&r.destroy(s,this.map),this.layerInstances.delete(t)}this.notifyChange()}setLayerOpacity(t,e){this.flushRender();const o=this.layers.find(a=>a.id===t);if(!o)return;if(o.opacidade=Math.max(0,Math.min(1,e)),this.map){const a=this.map.getPane(`pane-${t}`);a&&(a.style.opacity=String(o.opacidade))}const i=this.layerInstances.get(t);if(i&&this.map&&this.context){const a=F.get(o.tipo);a&&a.update(o,i,{opacidade:o.opacidade},this.context,this.map)}this.notifyChange()}setLayerZIndex(t,e){const o=this.layers.find(i=>i.id===t);if(o){if(o.zIndex=e,this.map){const i=this.map.getPane(`pane-${t}`);i&&(i.style.zIndex=String(e))}this.notifyChange()}}setLayerBlocked(t,e){const o=this.layers.find(i=>i.id===t);if(o){if(o.bloqueada=e,this.map){const i=this.map.getPane(`pane-${t}`);i&&(i.style.pointerEvents=o.visivel&&o.interativo&&!e?"auto":"none")}this.notifyChange()}}setLayerScaleMode(t,e){this.flushRender();const o=this.layers.find(a=>a.id===t);if(!o)return;o.estilo.scaleMode=e;const i=this.layerInstances.get(t);if(i&&this.map&&this.context){const a=F.get(o.tipo);a&&a.update(o,i,{estilo:o.estilo},this.context,this.map)}this.notifyChange()}setGraphicScale(t){this.context&&(this.context.graphicScale={...this.context.graphicScale,...t},this.agendarRender())}updateContext(t){this.context&&(this.context={...this.context,...t},this.agendarRender())}getLayers(){return[...this.layers]}getActiveSelectableLayers(){return this.layers.filter(t=>t.visivel&&t.interativo&&!t.bloqueada)}isLayerActiveAndSelectable(t){const e=this.layers.find(o=>o.id===t);return!!(e&&e.visivel&&e.interativo&&!e.bloqueada)}exportState(){return this.layers.map(t=>({id:t.id,visivel:t.visivel,opacidade:t.opacidade,zIndex:t.zIndex,bloqueada:t.bloqueada,estilo:{...t.estilo}}))}importState(t){!t||!Array.isArray(t)||(t.forEach(e=>{const o=this.layers.find(i=>i.id===e.id);o&&(e.visivel!==void 0&&(o.visivel=e.visivel),e.opacidade!==void 0&&(o.opacidade=e.opacidade),e.zIndex!==void 0&&(o.zIndex=e.zIndex),e.bloqueada!==void 0&&(o.bloqueada=e.bloqueada),e.estilo&&(o.estilo={...o.estilo,...e.estilo}))}),this.ensurePanes(),this.renderAllLayers())}onChange(t){return this.listeners.push(t),()=>{this.listeners=this.listeners.filter(e=>e!==t)}}notifyChange(){const t=this.getLayers();this.listeners.forEach(e=>{try{e(t)}catch(o){console.error("Erro no listener de camadas:",o)}})}getAllLayerInstances(){return this.flushRender(),Array.from(this.layerInstances.values())}getLayerInstance(t){return this.flushRender(),this.layerInstances.get(t)}getLayer(t){return this.layers.find(e=>e.id===t)}getLayerDef(t){return this.layers.find(e=>e.id===t)}getOrCreateLayer(t,e,o){let i=this.layers.find(a=>a.id===t);return i||(i={id:t,nome:o,categoria:"custom",tipo:e,visivel:!0,opacidade:1,zIndex:600,interativo:!0,bloqueada:!1,estilo:{scaleMode:"screen"}},this.layers.push(i),this.ensurePanes()),i}setLayerData(t,e){this.flushRender();const o=this.layers.find(a=>a.id===t);if(!o)return;o.dados=e;const i=this.layerInstances.get(t);if(i&&this.map&&this.context){const a=F.get(o.tipo);a&&a.update(o,i,{dados:e},this.context,this.map)}else if(o.visivel&&this.map&&this.context){const a=F.get(o.tipo);if(a){const s=a.render(o,this.map,this.context);s&&(s.addTo(this.map),this.layerInstances.set(t,s))}}this.notifyChange()}clearLayers(t){this.flushRender(),(t&&t.length>0?t:Array.from(this.layerInstances.keys())).forEach(o=>{if(this.layerInstances.has(o)){const i=this.layerInstances.get(o),a=this.layers.find(s=>s.id===o);if(a){const s=F.get(a.tipo);s&&s.destroy(i,this.map)}this.layerInstances.delete(o)}}),this.notifyChange()}destroy(){this.renderPendente=!1,this.map&&(this.layerInstances.forEach((t,e)=>{const o=this.layers.find(i=>i.id===e);if(o){const i=F.get(o.tipo);i&&i.destroy(t,this.map)}}),this.layerInstances.clear()),this.listeners=[]}}function ri(n,t){var s,r;if(t==null)return null;const e=String(t).trim(),o=c=>c?(c.lon=c.lng,c):null,a=n.getMarkers().find(c=>{var m,f,g,x;const l=c.pontoId,d=c.elementoId??c.id??((m=c.options)==null?void 0:m.pontoId)??((f=c.options)==null?void 0:f.id),h=(g=c.elemento)==null?void 0:g.nome_vertice,u=(x=c.elemento)==null?void 0:x.codigo_completo;return String(l)===e||String(d)===e||h&&String(h).toLowerCase()===e.toLowerCase()||u&&String(u).toLowerCase()===e.toLowerCase()});if(a&&typeof a.getLatLng=="function")return o(a.getLatLng());if(n.layerManager)for(const c of n.layerManager.getAllLayerInstances()){let l=null;const d=h=>{var f,g,x,A,M;if(l)return;const u=h.pontoId??h.elementoId??h.id??((f=h.options)==null?void 0:f.id)??((g=h.options)==null?void 0:g.pontoId),m=((x=h.elemento)==null?void 0:x.nome)??((A=h.elemento)==null?void 0:A.nome_vertice)??((M=h.options)==null?void 0:M.nome);(String(u)===e||m&&String(m).toLowerCase()===e.toLowerCase())&&(typeof h.getLatLng=="function"?l=h.getLatLng():typeof h.getBounds=="function"&&(l=h.getBounds().getCenter()))};if(d(c),typeof c.eachLayer=="function"&&c.eachLayer(d),l)return o(l)}if(n.context.pontos&&n.context.pontos.length>0){const c=n.context.pontos.find(l=>String(l.id)===e||l.nome_vertice&&String(l.nome_vertice).toLowerCase()===e.toLowerCase());if(c){const l=c.lat??c.latitude??c.y,d=c.lon??c.lng??c.longitude??c.x,h=S.parseCoordenada(l,d);if(h)return o(y.latLng(h.lat,h.lon))}}if(n.context.bancoPontos&&n.context.bancoPontos.length>0){const c=n.context.bancoPontos.find(l=>String(l.id)===e||l.codigo_completo&&String(l.codigo_completo).toLowerCase()===e.toLowerCase()||l.nome_vertice&&String(l.nome_vertice).toLowerCase()===e.toLowerCase());if(c){const l=c.lat??c.latitude??c.y,d=c.lon??c.lng??c.longitude??c.x,h=S.parseCoordenada(l,d);if(h)return o(y.latLng(h.lat,h.lon))}}if(n.context.confrontantes&&n.context.confrontantes.length>0){const c=n.context.confrontantes.find(l=>String(l.id)===e||l.nome&&String(l.nome).toLowerCase()===e.toLowerCase()||l.nome_propriedade&&String(l.nome_propriedade).toLowerCase()===e.toLowerCase());if(c){if(c.pontos&&c.pontos.length>0){let l=0,d=0,h=0;for(const u of c.pontos){const m=u.lat??u.latitude??u.y,f=u.lon??u.lng??u.longitude??u.x,g=S.parseCoordenada(m,f);g&&(l+=g.lat,d+=g.lon,h++)}if(h>0)return o(y.latLng(l/h,d/h))}if(c.poligono_wkt){const l=S.extrairCentroDeWkt(c.poligono_wkt);if(l)return o(y.latLng(l.lat,l.lon))}}}if(n.context.segmentos&&n.context.segmentos.length>0){const c=n.context.segmentos.find(l=>String(l.id)===e||`${l.ponto_inicio_id}-${l.ponto_fim_id}`===e);if(c){const l=(s=n.context.pontos)==null?void 0:s.find(h=>String(h.id)===String(c.ponto_inicio_id)),d=(r=n.context.pontos)==null?void 0:r.find(h=>String(h.id)===String(c.ponto_fim_id));if(l&&d){const h=S.parseCoordenada(l.lat??l.latitude,l.lon??l.longitude),u=S.parseCoordenada(d.lat??d.latitude,d.lon??d.longitude);if(h&&u)return o(y.latLng((h.lat+u.lat)/2,(h.lon+u.lon)/2))}}}if(n.layerManager){for(const c of n.layerManager.getLayers())if(c.dados){if(Array.isArray(c.dados.pontos)){const l=c.dados.pontos.find(d=>String(d.id)===e||d.nome_vertice&&String(d.nome_vertice)===e);if(l){const d=S.parseCoordenada(l.lat,l.lon);if(d)return o(y.latLng(d.lat,d.lon))}}if(Array.isArray(c.dados.poligonos)){const l=c.dados.poligonos.find(d=>String(d.id)===e);if(l){if(l.wkt){const d=S.extrairCentroDeWkt(l.wkt);if(d)return o(y.latLng(d.lat,d.lon))}if(Array.isArray(l.coordenadas)&&l.coordenadas.length>0){let d=0,h=0,u=0;for(const m of l.coordenadas){const f=S.parseCoordenada(m[0],m[1])||S.parseCoordenada(m[1],m[0]);f&&(d+=f.lat,h+=f.lon,u++)}if(u>0)return o(y.latLng(d/u,h/u))}}}}}return null}function zn(n,t,e,o){var m,f;Me(t,n.getMap());const i=n.getMap();if(!i)return;const a=ri(n,e);if(!a){console.warn(`[ui-canvas-cad] Elemento com identificador "${e}" não encontrado para destaque.`);return}const s=(o==null?void 0:o.pan)===!0,r=o==null?void 0:o.zoom;s?r!==void 0?typeof i.flyTo=="function"?i.flyTo(a,r,{animate:!0}):i.setView(a,r,{animate:!0}):typeof i.panTo=="function"?i.panTo(a,{animate:!0}):i.setView(a,i.getZoom(),{animate:!0}):r!==void 0&&i.setZoom(r,{animate:!0});const c=(o==null?void 0:o.cor)||"#00f5a0",l="pane-destaque";let d=i.getPane(l);d||(d=i.createPane(l)),d&&(d.style.zIndex="850",d.style.pointerEvents="none");const h=y.divIcon({className:"cad-destaque-marker-container",html:`
99
+ `,{className:"compact-popup",maxWidth:220}),q.on("click",()=>{o.modoSequencial&&q.closePopup(),o.onMarkerClick&&o.onMarkerClick(D.id,!0,D,{lat:N.lat,lon:N.lon})}),q.on("popupopen",J=>{if(o.modoSequencial){q.closePopup();return}S.bindPopupAcoesEvents(J.popup,D,o,q)})}q.addTo(e)}})})}update(t,e,o,i,n){o.opacidade!==void 0&&o.estilo===void 0&&o.dados===void 0&&o.interativo===void 0&&o.bloqueada===void 0||(o.opacidade!==void 0||o.estilo!==void 0||o.dados!==void 0||o.interativo!==void 0||o.bloqueada!==void 0)&&(e.clearLayers(),this.rebuildPolygons(t,e,i,n))}destroy(t,e){t.clearLayers(),e.hasLayer(t)&&e.removeLayer(t)}}class Uo{constructor(){p(this,"moveListenerMap",new WeakMap)}render(t,e,o){const i=y.layerGroup(),n=`pane-${t.id}`,s=()=>{if(i.clearLayers(),!t.visivel)return;if(e.getZoom()>20){const c=e.getBounds(),l=c.getSouth(),d=c.getNorth(),h=c.getWest(),u=c.getEast(),g=e.getCenter(),m=8999e-9,f=Math.cos(g.lat*Math.PI/180),x=m/(f>.1?f:1),E=Math.floor((d-l)/m),M=Math.floor((u-h)/x);if(E<200&&M<200){const A=Math.ceil(l/m)*m;for(let b=A;b<=d;b+=m)y.polyline([[b,h],[b,u]],{color:t.estilo.corPrimaria||"rgba(0, 245, 160, 0.18)",weight:t.estilo.espessuraLinha||.6,interactive:!1,pane:n}).addTo(i);const C=Math.ceil(h/x)*x;for(let b=C;b<=u;b+=x)y.polyline([[l,b],[d,b]],{color:t.estilo.corPrimaria||"rgba(0, 245, 160, 0.18)",weight:t.estilo.espessuraLinha||.6,interactive:!1,pane:n}).addTo(i)}}};return s(),e.on("zoomend moveend",s),this.moveListenerMap.set(i,s),i}update(t,e){t.visivel||e.clearLayers()}destroy(t,e){const o=this.moveListenerMap.get(t);o&&(e.off("zoomend moveend",o),this.moveListenerMap.delete(t)),t.clearLayers(),e.hasLayer(t)&&e.removeLayer(t)}}function U(a){return a.partes&&a.partes.length>1?a.partes:[a.coordenadas]}function kt(a){return a.tipo==="LineString"&&!!a.partes&&a.partes.length>1}function bt(a){return a.length>1?{tipo:"LineString",coordenadas:a[0],partes:a}:{tipo:"LineString",coordenadas:a[0]}}const we=63710088e-1,at=a=>a*Math.PI/180;function et(a,t){const e=at(t[0]-a[0]),o=at(t[1]-a[1]),i=Math.sin(e/2)**2+Math.cos(at(a[0]))*Math.cos(at(t[0]))*Math.sin(o/2)**2;return 2*we*Math.asin(Math.min(1,Math.sqrt(i)))}function It(a,t=!1){let e=0;for(let o=1;o<a.length;o++)e+=et(a[o-1],a[o]);return t&&a.length>2&&(e+=et(a[a.length-1],a[0])),e}function ao(a){const t=at(a.reduce((i,n)=>i+n[0],0)/a.length),e=a.map(i=>[at(i[1])*Math.cos(t)*we,at(i[0])*we]);let o=0;for(let i=0;i<e.length;i++){const[n,s]=e[i],[r,c]=e[(i+1)%e.length];o+=n*c-r*s}return Math.abs(o)/2}function Wo(a){const[t,...e]=a;return t?Math.max(0,ao(t)-e.reduce((o,i)=>o+ao(i),0)):0}const fa=new Intl.NumberFormat("pt-BR",{minimumFractionDigits:4,maximumFractionDigits:4}),no=new Intl.NumberFormat("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2});function rt(a){return`${fa.format(a/1e4)} ha`}function G(a){return a>=1e3?`${no.format(a/1e3)} km`:`${no.format(a)} m`}function Q(a){return a.tipo==="Polygon"?Wo(a.aneis):a.tipo==="Circle"?Math.PI*a.raioMetros**2:null}function tt(a){return a.tipo==="LineString"?U(a).reduce((t,e)=>t+It(e),0):a.tipo==="Polygon"?It(a.aneis[0]??[],!0):a.tipo==="Circle"?2*Math.PI*a.raioMetros:null}function Xo(a,t){var i;const e=t??"name";if(e==="area"){const n=Q(a.geometria);return n===null?"":rt(n)}if(e==="extensao"){const n=tt(a.geometria);return n===null?"":G(n)}if(e==="id")return a.id;const o=(i=a.propriedades)==null?void 0:i[e];return o!=null&&o!==""?String(o):t?"":a.id}function Oe(a){let t;switch(a.tipo){case"Point":case"Text":t=[a.coordenada];break;case"LineString":t=U(a).flat();break;case"Polygon":t=a.aneis.flat();break;case"Circle":{const i=a.raioMetros/111320,n=i/Math.max(.01,Math.cos(at(a.centro[0])));t=[[a.centro[0]-i,a.centro[1]-n],[a.centro[0]+i,a.centro[1]+n]];break}}const e=t.map(i=>i[0]),o=t.map(i=>i[1]);return[[Math.min(...e),Math.min(...o)],[Math.max(...e),Math.max(...o)]]}const Ot=16,ma=256;function Ee(a){const[[t,e],[o,i]]=Oe(a.geometria);return{minLon:e,minLat:t,maxLon:i,maxLat:o}}function vt(a,t){return a.minLon<=t.maxLon&&a.maxLon>=t.minLon&&a.minLat<=t.maxLat&&a.maxLat>=t.minLat}function so(a){let t=1/0,e=1/0,o=-1/0,i=-1/0;for(const n of a)n.minLon<t&&(t=n.minLon),n.minLat<e&&(e=n.minLat),n.maxLon>o&&(o=n.maxLon),n.maxLat>i&&(i=n.maxLat);return{minLon:t,minLat:e,maxLon:o,maxLat:i}}function ro(a){const t=a.length,e=Math.ceil(t/Ot),i=Math.ceil(Math.sqrt(e))*Ot,n=[...a].sort((r,c)=>r.minLon+r.maxLon-(c.minLon+c.maxLon)),s=[];for(let r=0;r<t;r+=i){const c=n.slice(r,r+i).sort((l,d)=>l.minLat+l.maxLat-(d.minLat+d.maxLat));for(let l=0;l<c.length;l+=Ot)s.push(c.slice(l,l+Ot))}return s}function ga(a){if(a.length===0)return null;let t=ro(a).map(e=>({...so(e),folhas:e}));for(;t.length>1;)t=ro(t).map(e=>({...so(e),filhos:e}));return t[0]}class Zo{constructor(){p(this,"raiz",null);p(this,"itens",new Map);p(this,"delta",new Map);p(this,"obsoletos",new Set)}get tamanho(){return this.itens.size}construir(t){this.itens.clear();for(const e of t)e.excluida||this.itens.set(e.id,{id:e.id,...Ee(e)});this.remontar()}inserir(t){this.atualizar(t)}atualizar(t){if(t.excluida){this.remover(t.id);return}const e={id:t.id,...Ee(t)};this.itens.has(t.id)&&this.obsoletos.add(t.id),this.itens.set(t.id,e),this.delta.set(t.id,e),this.compactarSeNecessario()}remover(t){this.itens.delete(t)&&(this.obsoletos.add(t),this.delta.delete(t),this.compactarSeNecessario())}limpar(){this.itens.clear(),this.remontar()}consultar(t){const e=[],o=this.raiz?[this.raiz]:[];for(;o.length>0;){const i=o.pop();if(vt(i,t))if(i.folhas)for(const n of i.folhas)!this.obsoletos.has(n.id)&&vt(n,t)&&e.push(n.id);else i.filhos&&o.push(...i.filhos)}for(const i of this.delta.values())vt(i,t)&&e.push(i.id);return e}intersecta(t){return this.consultar(t).length>0}caixaDe(t){return this.itens.get(t)}compactarSeNecessario(){this.delta.size+this.obsoletos.size>Math.max(ma,this.itens.size*.1)&&this.remontar()}remontar(){this.raiz=ga([...this.itens.values()]),this.delta.clear(),this.obsoletos.clear()}}const te=12,Re=40,va=1.2;function Yo(a){return a>=te?0:360/(256*2**a)*va}function ya(a,t,e){const o=e[1]-t[1],i=e[0]-t[0],n=o*o+i*i;let s=n===0?0:((a[1]-t[1])*o+(a[0]-t[0])*i)/n;return s=Math.max(0,Math.min(1,s)),Math.hypot(a[1]-(t[1]+s*o),a[0]-(t[0]+s*i))}function Fe(a,t){if(t<=0||a.length<3)return a;const e=new Uint8Array(a.length);e[0]=1,e[a.length-1]=1;const o=[[0,a.length-1]];for(;o.length>0;){const[i,n]=o.pop();let s=0,r=-1;for(let c=i+1;c<n;c++){const l=ya(a[c],a[i],a[n]);l>s&&(s=l,r=c)}r!==-1&&s>t&&(e[r]=1,o.push([i,r],[r,n]))}return a.filter((i,n)=>e[n]===1)}function Ko(a,t){if(t<=0||a.length<4)return a;const e=[...a,a[0]],o=Fe(e,t);return o.pop(),o.length>=3?o:a}function Be(a){return(a.tipo==="LineString"||a.tipo==="Polygon")&&a.curva?0:a.tipo==="LineString"?U(a).reduce((t,e)=>t+e.length,0):a.tipo==="Polygon"?a.aneis.reduce((t,e)=>t+e.length,0):0}function Jo(a,t){const e=Yo(t);return e===0||Be(a)<Re?a:a.tipo==="LineString"?bt(U(a).map(o=>Fe(o,e))):a.tipo==="Polygon"?{tipo:"Polygon",aneis:a.aneis.map(o=>Ko(o,e))}:a}const xa=new Set(["previa","prévia","preview","rascunho","draft","proposta"]);function K(a){var e,o;const t=[a.status,(e=a.propriedades)==null?void 0:e.status,(o=a.propriedades)==null?void 0:o.tipo_geometria];for(const i of t)if(typeof i=="string"&&xa.has(i.trim().toLowerCase()))return"previa";return"oficial"}function nt(a){var e;const t=a.entidadeId??((e=a.propriedades)==null?void 0:e.entidadeId);return typeof t=="string"||typeof t=="number"?String(t):a.id}const fe=(a,t)=>`${a}\0${t}`;class ee{constructor(){p(this,"global",!1);p(this,"individuais",new Set)}alternarIndividual(t,e){const o=fe(t,e);return this.individuais.has(o)?this.individuais.delete(o):this.individuais.add(o),this.individuais.has(o)}definirIndividual(t,e,o){const i=fe(t,e);o?this.individuais.add(i):this.individuais.delete(i)}individualAtiva(t,e){return this.individuais.has(fe(t,e))}static oficiais(t){const e=new Set;for(const o of t)!o.excluida&&K(o)==="oficial"&&e.add(nt(o));return e}visivel(t,e){if(K(t)==="oficial")return!0;const o=nt(t);return this.global||!e.has(o)||this.individualAtiva(t.camadaId,o)}previaSolicitada(t){return this.global||this.individualAtiva(t.camadaId,nt(t))}}const ba=24,Pa=2,co=a=>typeof a=="number"&&Number.isFinite(a),me=a=>Array.isArray(a)&&a.length===2&&co(a[0])&&co(a[1]);function Ve(a,t){return[2*a[0]-t[0],2*a[1]-t[1]]}function Qo(a){return a.some(t=>t.entrada!==void 0||t.saida!==void 0)}function $t(a,t){return[a.saida??a.ponto,t.entrada??t.ponto]}function ti(a,t){const e=[];for(let o=0;o<a-1;o++)e.push([o,o+1]);return t&&a>2&&e.push([a-1,0]),e}function He(a,t,e,o,i){const n=1-i,s=n*n*n,r=3*n*n*i,c=3*n*i*i,l=i*i*i;return[s*a[0]+r*t[0]+c*e[0]+l*o[0],s*a[1]+r*t[1]+c*e[1]+l*o[1]]}function Pt(a,t=!1,e=ba){if(a.length===0)return[];const o=[[a[0].ponto[0],a[0].ponto[1]]];for(const[i,n]of ti(a.length,t)){const s=a[i],r=a[n];if(!(s.saida===void 0&&r.entrada===void 0)){const[l,d]=$t(s,r);for(let h=1;h<e;h++)o.push(He(s.ponto,l,d,r.ponto,h/e))}n!==0&&o.push([r.ponto[0],r.ponto[1]])}return o}function ei(a,t){if(a.length===0)return[];const e=[{cmd:"M",pts:[a[0].ponto]}];for(const[o,i]of ti(a.length,t)){const n=a[o],s=a[i];if(n.saida===void 0&&s.entrada===void 0)e.push({cmd:"L",pts:[s.ponto]});else{const[r,c]=$t(n,s);e.push({cmd:"C",pts:[r,c,s.ponto]})}}return e}function Ca(a,t,e){const o=n=>String(Math.round(n*100)/100),i=ei(a,t).map(n=>n.cmd+n.pts.map(s=>{const r=e(s);return`${o(r.x)} ${o(r.y)}`}).join(" ")).join("");return i&&t?`${i}Z`:i}function La(a,t=Pa){if(!Array.isArray(a)||a.length<t)return null;const e=[];for(const o of a){if(!o||typeof o!="object"||!me(o.ponto))return null;const i=o,n={ponto:[i.ponto[0],i.ponto[1]]};me(i.entrada)&&(n.entrada=[i.entrada[0],i.entrada[1]]),me(i.saida)&&(n.saida=[i.saida[0],i.saida[1]]),e.push(n)}return Qo(e)?e:null}function lo(a,t){return a.map(e=>{const o={ponto:t(e.ponto)};return e.entrada&&(o.entrada=t(e.entrada)),e.saida&&(o.saida=t(e.saida)),o})}function oi(a,t){var s,r;const e=a._nosCurva,o=a._renderer,i=a._map;if(!e||e.length<2||!o||!i)return!1;const n=c=>i.latLngToLayerPoint([c[0],c[1]]);if(o._ctx&&o._fillStroke){if(!o._drawing||!((s=a._parts)!=null&&s.length))return!0;const c=o._ctx;c.beginPath();for(const l of ei(e,t)){const d=l.pts.map(n);l.cmd==="M"?c.moveTo(d[0].x,d[0].y):l.cmd==="L"?c.lineTo(d[0].x,d[0].y):c.bezierCurveTo(d[0].x,d[0].y,d[1].x,d[1].y,d[2].x,d[2].y)}return t&&c.closePath(),o._fillStroke(c,a),!0}return o._setPath?(o._setPath(a,(r=a._parts)!=null&&r.length?Ca(e,t,n):"M0 0"),!0):!1}class ii extends y.Polyline{constructor(){super(...arguments);p(this,"_nosCurva",null)}definirCurva(e){this._nosCurva=e}_updatePath(){oi(this,!1)||y.Polyline.prototype._updatePath.call(this)}}class ai extends y.Polygon{constructor(){super(...arguments);p(this,"_nosCurva",null)}definirCurva(e){this._nosCurva=e}_updatePath(){oi(this,!0)||y.Polygon.prototype._updatePath.call(this)}}function oe(a){return a.tipo==="LineString"?a.curva&&a.curva.length>=2&&!(a.partes&&a.partes.length>1)?a.curva:null:a.tipo==="Polygon"&&a.curva&&a.curva.length>=3&&a.aneis.length===1?a.curva:null}function ni(a,t){const e=oe(a);if(!e)return null;const o=a.tipo==="Polygon"?new ai(a.aneis[0],t):new ii(a.coordenadas,t);return o.definirCurva(e),o}function Sa(a,t){a.definirCurva(oe(t)),a.setLatLngs(t.tipo==="Polygon"?t.aneis[0]:t.coordenadas)}const _t=55,si=17,ri=8;function ie(a,t){return t<si&&a>ri}function ci(a){let t=0,e=0;for(const o of a)t+=o.coordenada[0],e+=o.coordenada[1];return[t/a.length,e/a.length]}function Ma(a,t,e){if(!ie(a.length,t))return{clusters:[],isolados:a};const o=new Map;for(const s of a){const{x:r,y:c}=e(s.coordenada),l=`${t}:${Math.floor(r/_t)}:${Math.floor(c/_t)}`,d=o.get(l);d?d.push(s):o.set(l,[s])}const i=[],n=[];for(const[s,r]of o)r.length===1?n.push(r[0]):i.push({chave:s,coordenada:ci(r),membros:r});return{clusters:i,isolados:n}}class li{constructor(t,e){p(this,"celulas",new Map);p(this,"celulaDe",new Map);p(this,"multiplas",new Set);this.zoom=t,this.projetar=e}get total(){return this.celulaDe.size}chaveDoPonto(t){return this.celulaDe.get(t)}celula(t){return this.celulas.get(t)}*celulasAgrupadas(){for(const t of this.multiplas){const e=this.celulas.get(t);e&&(yield[t,e])}}emCluster(t){var o;const e=this.celulaDe.get(t);return e!==void 0&&(((o=this.celulas.get(e))==null?void 0:o.membros.size)??0)>=2}inserir(t){this.remover(t.id);const{x:e,y:o}=this.projetar(t.coordenada),i=`${this.zoom}:${Math.floor(e/_t)}:${Math.floor(o/_t)}`;let n=this.celulas.get(i);return n||(n={membros:new Map,somaLat:0,somaLon:0},this.celulas.set(i,n)),n.membros.set(t.id,t),n.somaLat+=t.coordenada[0],n.somaLon+=t.coordenada[1],n.membros.size>=2&&this.multiplas.add(i),this.celulaDe.set(t.id,i),i}remover(t){const e=this.celulaDe.get(t);if(e===void 0)return;this.celulaDe.delete(t);const o=this.celulas.get(e),i=o==null?void 0:o.membros.get(t);return o&&i&&(o.membros.delete(t),o.somaLat-=i.coordenada[0],o.somaLon-=i.coordenada[1],o.membros.size<2&&this.multiplas.delete(e),o.membros.size===0&&this.celulas.delete(e)),e}}const Ht={tower:'<path d="M12 2 L8 22 M12 2 L16 22 M9.5 12 H14.5 M8.7 17 H15.3 M12 2 L9.5 12 L14.5 12 Z" />',tree:'<path d="M12 22 V14 M12 3 L5 14 H19 Z" />',warning:'<path d="M12 3 L22 20 H2 Z M12 9 V14 M12 17 V17.5" />',water:'<path d="M12 3 C12 3 5 11 5 15.5 A7 7 0 0 0 19 15.5 C19 11 12 3 12 3 Z" />',boundary:'<path d="M12 2 L22 12 L12 22 L2 12 Z" />'},ge="#38bdf8",Aa=/^(#[0-9a-f]{3,8}|(rgb|hsl)a?\([0-9.,%\s\/-]+\)|[a-z]{3,20})$/i;function Y(a,t){return a&&Aa.test(a.trim())?a.trim():t}const mt="#38bdf8",wa=150,Ea=100,ze=300,ho=.75,za=.3,ve=typeof requestAnimationFrame=="function"?a=>{requestAnimationFrame(a)}:a=>{setTimeout(a,16)};class di{constructor(){p(this,"estados",new WeakMap);p(this,"selecionadas",new WeakMap);p(this,"tokenLote",new WeakMap)}render(t,e,o){const i=y.layerGroup();return this.sincronizar(t,i,e,o,!0),i}update(t,e,o,i,n){if(o.dados===void 0&&o.estilo===void 0&&o.interativo===void 0&&o.bloqueada===void 0)return;const s=o.estilo!==void 0||o.interativo!==void 0||o.bloqueada!==void 0;this.sincronizar(t,e,n,i,s)}destroy(t,e){const o=this.estados.get(t);o&&(o.vivo=!1,e.off("moveend zoomend",o.aoMover)),t.clearLayers(),this.estados.delete(t),this.tokenLote.set(t,(this.tokenLote.get(t)??0)+1),e.hasLayer(t)&&e.removeLayer(t)}reavaliarVersoes(t){const e=this.estados.get(t);e&&(e.revisao++,e.revisaoBase++,this.reconciliar(t,e,!1,null))}feicaoVisivel(t,e){const o=this.estados.get(t),i=o==null?void 0:o.context.regraVersoes;return!o||!i||i.visivel(e,o.oficiais)}consultarProximas(t,e){const o=this.estados.get(t);if(!o)return[];const i=[];for(const n of o.indice.consultar(e)){const s=o.loja.get(n);s&&!s.oculta&&i.push(s)}return i}previsualizar(t,e){var s;const o=this.estados.get(t),i=o==null?void 0:o.entradas.get(e.id);if(!o||!i)return;const n=o.map._loaded?o.map.getZoom():0;this.remendar(i.layer,this.paraDesenho(e,n),o.layerDef,o.interativo,!!((s=this.selecionadas.get(o.layerDef))!=null&&s.has(e.id)))}estatisticas(t){const e=this.estados.get(t);return e?{total:e.loja.size,materializadas:e.entradas.size,clusters:e.clusters.size}:null}feicoesDe(t){const e=t.dados,o=Array.isArray(e)?e:e==null?void 0:e.feicoes;return Array.isArray(o)?o:[]}obterEstado(t,e,o,i){let n=this.estados.get(t);if(!n){const s={layerDef:e,interativo:!1,map:o,context:i,loja:new Map,indice:new Zo,revisao:0,revisaoBase:0,listaSincronizada:null,oficiais:new Set,contOficiais:new Map,nPrevias:0,entradas:new Map,clusters:new Map,nPontos:0,nPontosRev:-1,agrupador:null,agrupadorRev:-1,culling:!1,agendado:!1,vivo:!0,aoMover:()=>{s.agendado||!s.vivo||(s.agendado=!0,ve(()=>{s.agendado=!1,s.vivo&&this.reconciliar(t,s,!1,null)}))}};o.on("moveend zoomend",s.aoMover),this.estados.set(t,s),n=s}return n.layerDef=e,n.map=o,n.context=i,n.interativo=e.interativo&&!e.bloqueada,n}sincronizar(t,e,o,i,n){var m;const s=this.obterEstado(e,t,o,i),r=this.feicoesDe(t),c=(m=t.dados)==null?void 0:m.delta;if(!n&&this.aplicarDelta(e,s,r,c))return;const l=r.filter(f=>!f.excluida),d=new Set,h=new Set;for(const f of l)h.add(f.id),s.loja.get(f.id)!==f&&d.add(f.id);const u=[...s.loja.keys()].filter(f=>!h.has(f));if(d.size>0||u.length>0){if(s.revisao++,s.revisaoBase++,s.loja.size===0||d.size+u.length>l.length*za)s.indice.construir(l);else{for(const f of l)d.has(f.id)&&s.indice.atualizar(f);for(const f of u)s.indice.remover(f)}s.loja=new Map(l.map(f=>[f.id,f])),this.recontarOficiais(s,l)}s.listaSincronizada=r;const g=this.selecionadas.get(t);if(g)for(const f of[...g])h.has(f)||g.delete(f);this.reconciliar(e,s,n,d)}recontarOficiais(t,e){t.contOficiais=new Map,t.nPrevias=0;for(const o of e){if(o.excluida)continue;if(K(o)!=="oficial"){t.nPrevias++;continue}const i=nt(o);t.contOficiais.set(i,(t.contOficiais.get(i)??0)+1)}t.oficiais=new Set(t.contOficiais.keys())}aplicarDelta(t,e,o,i){if(!i||i.base!==e.listaSincronizada)return!1;const{loja:n}=e,s=this.selecionadas.get(e.layerDef),r=m=>m.geometria.tipo==="Point"&&this.desenhavel(e,m),c=new Map,l=(m,f)=>{if(!m||m.excluida||K(m)!=="oficial")return;const x=nt(m);c.has(x)||c.set(x,e.oficiais.has(x));const E=(e.contOficiais.get(x)??0)+f;E<=0?(e.contOficiais.delete(x),e.oficiais.delete(x)):(e.contOficiais.set(x,E),e.oficiais.add(x))},d=[],h=[],u=m=>{const f=n.get(m);f&&(K(f)==="previa"&&e.nPrevias--,l(f,-1),r(f)&&e.nPontos--,n.delete(m),e.indice.remover(m),s==null||s.delete(m),h.push(m))};for(const m of i.removidas)u(m);for(const m of i.mudadas){if(m.excluida){u(m.id);continue}const f=n.get(m.id);K(m)==="previa"&&e.nPrevias++,f&&(K(f)==="previa"&&e.nPrevias--,l(f,-1),r(f)&&e.nPontos--),n.set(m.id,m),e.indice.atualizar(m),l(m,1),r(m)&&e.nPontos++,d.push(m.id)}let g=!1;if(e.nPrevias>0)for(const[m,f]of c)f!==e.oficiais.has(m)&&(g=!0);return e.listaSincronizada=o,e.revisao++,g&&e.revisaoBase++,this.reconciliarParcial(t,e,d,h,g),!0}ressimplificar(t,e){return t.zoomDesenho===e||Be(t.feicao.geometria)<Re?!1:e<te||t.zoomDesenho<te}paraDesenho(t,e){const o=Jo(t.geometria,e);return o===t.geometria?t:{...t,geometria:o}}desenhavel(t,e){if(e.oculta)return!1;const o=t.context.regraVersoes;return!o||o.visivel(e,t.oficiais)}estaCarregado(t){return!!t._loaded}caixaDe(t){return{minLon:t.getWest(),minLat:t.getSouth(),maxLon:t.getEast(),maxLat:t.getNorth()}}materializar(t,e,o,i,n,s){const r=this.formaDe(o),c=e.entradas.get(o.id),l=this.paraDesenho(o,i);if(c&&c.forma===r){(s||c.feicao!==o||this.ressimplificar(c,i))&&(this.remendar(c.layer,l,e.layerDef,e.interativo,n),c.feicao=o,c.zoomDesenho=i);return}c&&t.removeLayer(c.layer);const d=this.criar(l,e.layerDef,e.map,e.interativo,n);this.ligarEventos(d,o.id,e.layerDef,e.entradas,e.context),this.aplicarRotulo(d,o),t.addLayer(d),e.entradas.set(o.id,{layer:d,forma:r,feicao:o,zoomDesenho:i})}tirarEntrada(t,e,o){const i=e.entradas.get(o);i&&(t.removeLayer(i.layer),e.entradas.delete(o))}colocarCluster(t,e,o,i){const n=e.clusters.get(o);if((n==null?void 0:n.assinatura)===i.assinatura)return;n&&t.removeLayer(n.marker);const s=this.criarMarcadorCluster(i.coordenada,i.total,()=>{var r,c;return Array.from(((c=(r=e.agrupador)==null?void 0:r.celula(o))==null?void 0:c.membros.values())??[])},e);t.addLayer(s),e.clusters.set(o,{marker:s,assinatura:i.assinatura})}tirarCluster(t,e,o){const i=e.clusters.get(o);i&&(t.removeLayer(i.marker),e.clusters.delete(o))}agrupadorAtivo(t,e){const o=s=>this.desenhavel(t,s);if(t.nPontosRev!==t.revisaoBase){let s=0;for(const r of t.loja.values())r.geometria.tipo==="Point"&&o(r)&&s++;t.nPontos=s,t.nPontosRev=t.revisaoBase}if(!ie(t.nPontos,e))return t.agrupador=null,null;const i=t.agrupador;if(i&&i.zoom===e&&t.agrupadorRev===t.revisaoBase)return i;const n=new li(e,s=>t.map.project(y.latLng(s[0],s[1]),e));for(const s of t.loja.values())s.geometria.tipo==="Point"&&o(s)&&n.inserir({id:s.id,coordenada:s.geometria.coordenada});return t.agrupador=n,t.agrupadorRev=t.revisaoBase,n}reconciliar(t,e,o,i){var E;const{map:n,layerDef:s,loja:r}=e,c=this.selecionadas.get(s),l=this.estaCarregado(n),d=l?n.getZoom():0,h=l&&r.size>ze?n.getBounds().pad(ho):null,u=h?this.caixaDe(h):null;e.culling=h!==null;const g=u?e.indice.consultar(u):r.keys(),m=new Set(g);if(c)for(const M of c)r.has(M)&&m.add(M);for(const M of[...m]){const A=r.get(M);A&&!this.desenhavel(e,A)&&m.delete(M)}const f=new Map,x=l?this.agrupadorAtivo(e,d):null;if(x||(e.agrupador=null),x){for(const A of[...m])x.emCluster(A)&&m.delete(A);const M=new Map;if(c)for(const A of c){const C=x.chaveDoPonto(A),b=C===void 0||(E=x.celula(C))==null?void 0:E.membros.get(A);if(C!==void 0&&b){const v=M.get(C);v?v.push(b):M.set(C,[b])}}for(const[A,C]of x.celulasAgrupadas()){const b=M.get(A);if(b)for(const w of b)m.add(w.id);const v=C.membros.size,P=v-((b==null?void 0:b.length)??0);if(P===1)for(const w of C.membros.values()){if(c!=null&&c.has(w.id))continue;const k=e.indice.caixaDe(w.id);(!u||k&&vt(k,u))&&m.add(w.id);break}if(!(h&&!h.contains([C.somaLat/v,C.somaLon/v]))&&P>=2){let w=C.somaLat,k=C.somaLon;if(b)for(const z of b)w-=z.coordenada[0],k-=z.coordenada[1];const L=[w/P,k/P];f.set(A,{coordenada:L,total:v,assinatura:`${A}:${v}:${P}:${L[0].toFixed(7)}:${L[1].toFixed(7)}`})}}}for(const M of m){const A=r.get(M);A&&this.materializar(t,e,A,d,!!(c!=null&&c.has(M)),o||!!(i!=null&&i.has(M)))}for(const M of[...e.entradas.keys()])m.has(M)&&r.has(M)||this.tirarEntrada(t,e,M);for(const[M,A]of f)this.colocarCluster(t,e,M,A);for(const M of[...e.clusters.keys()])f.has(M)||this.tirarCluster(t,e,M)}reconciliarParcial(t,e,o,i,n){const{map:s,layerDef:r,loja:c}=e,l=this.estaCarregado(s),d=l?s.getZoom():0,h=l&&c.size>ze,u=l&&ie(e.nPontos,d),g=e.agrupador;if(n||h!==e.culling||u!==(g!==null)||g!==null&&(g.zoom!==d||e.agrupadorRev!==e.revisaoBase)){this.reconciliar(t,e,!1,new Set(o));return}const m=this.selecionadas.get(r),f=v=>this.desenhavel(e,v),x=h?s.getBounds().pad(ho):null,E=x?this.caixaDe(x):null,M=(v,P)=>{const w=c.get(v);if(!w||!f(w)){this.tirarEntrada(t,e,v);return}const k=!!(m!=null&&m.has(v));if(!k&&E){const L=e.indice.caixaDe(v);if(!L||!vt(L,E)){this.tirarEntrada(t,e,v);return}}this.materializar(t,e,w,d,k,P)},A=new Set,C=[];for(const v of i){this.tirarEntrada(t,e,v);const P=g==null?void 0:g.remover(v);P!==void 0&&A.add(P)}for(const v of o){const P=c.get(v);if(!P)continue;const w=g==null?void 0:g.remover(v);w!==void 0&&A.add(w),g&&P.geometria.tipo==="Point"&&f(P)?A.add(g.inserir({id:v,coordenada:P.geometria.coordenada})):C.push(v)}for(const v of C)M(v,!0);if(!g)return;const b=new Set(o);for(const v of A){const P=g.celula(v);if(!P||P.membros.size<2){if(this.tirarCluster(t,e,v),P)for(const T of P.membros.keys())M(T,b.has(T));continue}const w=P.membros.size;let k=P.somaLat,L=P.somaLon,z=0;for(const T of P.membros.values())m!=null&&m.has(T.id)&&(z++,k-=T.coordenada[0],L-=T.coordenada[1]);const I=w-z;for(const T of P.membros.values())m!=null&&m.has(T.id)||I===1?M(T.id,b.has(T.id)):this.tirarEntrada(t,e,T.id);const _=[P.somaLat/w,P.somaLon/w];if(x&&!x.contains(_)||I<2){this.tirarCluster(t,e,v);continue}const O=[k/I,L/I];this.colocarCluster(t,e,v,{coordenada:O,total:w,assinatura:`${v}:${w}:${I}:${O[0].toFixed(7)}:${O[1].toFixed(7)}`})}}criarMarcadorCluster(t,e,o,i){const n=e<10?30:e<100?38:46,s=Y(i.layerDef.estilo.corPrimaria,ge),r=y.divIcon({className:"custom-leaflet-marker cad-feicao-cluster",iconSize:[n,n],html:`<div style="width:${n}px;height:${n}px;border-radius:50%;background:${s};opacity:.9;border:2px solid rgba(255,255,255,.85);display:flex;align-items:center;justify-content:center;color:#fff;font:700 12px sans-serif;text-shadow:0 0 2px #000">${e}</div>`}),c=y.marker(t,{icon:r,pane:st(i.map,i.layerDef.id,"ponto"),keyboard:!1});return c.bindTooltip(`${e} feições agrupadas`,{direction:"top"}),c.on("click",()=>{const l=o();l.length>0&&i.map.fitBounds(y.latLngBounds(l.map(d=>d.coordenada)),{padding:[60,60],maxZoom:18})}),c}aplicarSelecao(t,e){const o=this.estados.get(t);if(!o)return;const i=this.selecionadas.get(o.layerDef)??new Set,n=new Set(e);this.selecionadas.set(o.layerDef,n);const s=[];for(const d of n)i.has(d)||s.push(d);for(const d of i)n.has(d)||s.push(d);if(s.length===0)return;const r=o.entradas,c=d=>{const h=r.get(d);if(!h)return;const u=n.has(d);this.remendar(h.layer,this.paraDesenho(h.feicao,h.zoomDesenho),o.layerDef,o.interativo,u),u&&"bringToFront"in h.layer&&h.layer.bringToFront()},l=(this.tokenLote.get(t)??0)+1;if(this.tokenLote.set(t,l),s.length<=wa)s.forEach(c);else{const h=!!o.map._loaded?o.map.getBounds():null,u=x=>{var M;const E=(M=r.get(x))==null?void 0:M.layer;return h?E!=null&&E.getBounds?h.intersects(E.getBounds()):E!=null&&E.getLatLng?h.contains(E.getLatLng()):!0:!0},g=s.filter(u),m=s.filter(x=>!u(x));g.forEach(c);const f=()=>{this.tokenLote.get(t)===l&&(m.splice(0,Ea).forEach(c),m.length>0&&ve(f))};m.length>0&&ve(f)}this.reconciliar(t,o,!1,null)}formaDe(t){var o;const e=t.geometria;return e.tipo==="Point"?`Point:${(o=t.estilo)!=null&&o.icone&&Ht[t.estilo.icone]?t.estilo.icone:""}`:oe(e)?`${e.tipo}:curva`:e.tipo}paneDe(t){switch(t.geometria.tipo){case"Polygon":case"Circle":return"poligono";case"LineString":return"linha";case"Point":return"ponto";default:return"texto"}}estiloVetor(t,e,o,i=!1){const n=t.estilo??{},s=Y(n.corTraco??e.estilo.corPrimaria,ge),r=t.geometria.tipo==="Polygon"||t.geometria.tipo==="Circle",c=t.geometria.tipo==="Point",l=c&&Y(n.corContorno,"")||s,d=c&&typeof n.espessuraContorno=="number"&&Number.isFinite(n.espessuraContorno)&&n.espessuraContorno>=0?n.espessuraContorno:void 0,h=d??n.espessuraTraco??e.estilo.espessuraLinha??2,u=n.opacidadePreenchimento??(r?.2:.85);return{color:i?mt:l,stroke:!(d===0&&!i),weight:i?h+2:h,dashArray:n.dashArray??(K(t)==="previa"?"6 4":e.estilo.dashArray),fill:r||t.geometria.tipo==="Point",fillColor:Y(n.corPreenchimento,s),fillOpacity:i?Math.min(1,u+.18):u,lineJoin:"round",interactive:o}}criar(t,e,o,i,n){var d,h;const s=st(o,e.id,this.paneDe(t)),r=t.geometria,c=this.estiloVetor(t,e,i,n),l=ni(r,{...c,pane:s});if(l)return l;switch(r.tipo){case"Polygon":return y.polygon(r.aneis.length===1?r.aneis[0]:r.aneis,{...c,pane:s});case"Circle":return y.circle(r.centro,{...c,radius:r.raioMetros,pane:s});case"LineString":return y.polyline(r.partes&&r.partes.length>1?U(r):r.coordenadas,{...c,pane:s});case"Point":{const u=(d=t.estilo)==null?void 0:d.icone;return u&&Ht[u]?y.marker(r.coordenada,{icon:this.iconeSvg(t,e,n),pane:s,interactive:i}):y.circleMarker(r.coordenada,{...c,radius:(((h=t.estilo)==null?void 0:h.tamanhoIcone)??e.estilo.tamanhoMarcador??8)/2,pane:s})}default:return y.marker(r.coordenada,{icon:this.iconeTexto(t,e,n),pane:s,interactive:i,draggable:i&&!t.bloqueada})}}remendar(t,e,o,i,n){var c,l,d;const s=e.geometria,r=this.estiloVetor(e,o,i,n);(t instanceof ii||t instanceof ai)&&oe(s)?(Sa(t,s),t.setStyle(r)):s.tipo==="Polygon"?(t.setLatLngs(s.aneis.length===1?s.aneis[0]:s.aneis),t.setStyle(r)):s.tipo==="LineString"?(t.setLatLngs(s.partes&&s.partes.length>1?U(s):s.coordenadas),t.setStyle(r)):s.tipo==="Circle"?(t.setLatLng(s.centro),t.setRadius(s.raioMetros),t.setStyle(r)):s.tipo==="Point"&&t instanceof y.CircleMarker?(t.setLatLng(s.coordenada),t.setRadius((((c=e.estilo)==null?void 0:c.tamanhoIcone)??o.estilo.tamanhoMarcador??8)/2),t.setStyle(r)):t instanceof y.Marker&&(t.setLatLng(s.tipo==="Point"||s.tipo==="Text"?s.coordenada:t.getLatLng()),t.setIcon(s.tipo==="Text"?this.iconeTexto(e,o,n):this.iconeSvg(e,o,n)),s.tipo==="Text"&&(i&&!e.bloqueada?(l=t.dragging)==null||l.enable():(d=t.dragging)==null||d.disable())),this.aplicarRotulo(t,e)}iconeSvg(t,e,o=!1){const i=t.estilo??{},n=i.tamanhoIcone??e.estilo.tamanhoMarcador,s=typeof n=="number"&&Number.isFinite(n)&&n>0?n:22,r=o?mt:Y(i.corTraco??i.corPreenchimento??e.estilo.corPrimaria,ge),c=Number.isFinite(i.rotacaoIcone)?i.rotacaoIcone:0,l=Ht[i.icone??""]??"";return y.divIcon({className:`custom-leaflet-marker${o?" cad-feicao-selecionada":""}`,iconSize:[s,s],html:`<svg width="${s}" height="${s}" viewBox="0 0 24 24" fill="${r}" fill-opacity="0.25" stroke="${r}" stroke-width="1.6" stroke-linejoin="round" stroke-linecap="round" style="transform:rotate(${c}deg);overflow:visible;display:block${o?`;filter:drop-shadow(0 0 3px ${mt})`:""}">${l}</svg>`})}iconeTexto(t,e,o=!1){const i=t.estilo??{},n=t.geometria.tipo==="Text"?t.geometria.texto:"",s=o?mt:Y(i.corTraco??e.estilo.corPrimaria,"#ffffff"),r=Number.isFinite(i.tamanhoFonte)?i.tamanhoFonte:13,l=`display:inline-block;white-space:nowrap;transform:translate(-50%,-50%) rotate(${Number.isFinite(i.rotacaoIcone)?i.rotacaoIcone:0}deg);color:${s};font-size:${r}px;font-weight:600;`,d=Y(i.corFundo,"");if(d){const u=Y(i.corBorda,""),g=typeof i.opacidadeFundo=="number"&&Number.isFinite(i.opacidadeFundo)?Math.min(1,Math.max(0,i.opacidadeFundo)):.85,m=typeof i.raioBorda=="number"&&Number.isFinite(i.raioBorda)?Math.min(50,Math.max(0,i.raioBorda)):4,f=o?`1px solid ${mt}`:u?`1px solid ${u}`:"none";return y.divIcon({className:`custom-leaflet-marker cad-feicao-texto cad-feicao-selo${o?" cad-feicao-selecionada":""}`,iconSize:void 0,html:`<span style="${l}position:relative;padding:2px 6px;border-radius:${m}px;border:${f}"><span style="position:absolute;top:0;right:0;bottom:0;left:0;border-radius:inherit;background:${d};opacity:${g}"></span><span style="position:relative">${S.escapeHtml(n)}</span></span>`})}const h=i.halo?"text-shadow:-1px -1px 0 #000,1px -1px 0 #000,-1px 1px 0 #000,1px 1px 0 #000;":"";return y.divIcon({className:`custom-leaflet-marker cad-feicao-texto${o?" cad-feicao-selecionada":""}`,iconSize:void 0,html:`<span style="${l}${h}">${S.escapeHtml(n)}</span>`})}aplicarRotulo(t,e){const o=e.estilo;if(!(o!=null&&o.mostrarRotulo)||e.geometria.tipo==="Text"){t.unbindTooltip();return}const i=Xo(e,o.campoRotulo);if(!i){t.unbindTooltip();return}const n=document.createElement("span");n.textContent=i,t.getTooltip()?t.setTooltipContent(n):t.bindTooltip(n,{permanent:!0,direction:"center",className:"cad-feicao-rotulo",interactive:!1})}ligarEventos(t,e,o,i,n){t.on("click",s=>{var l;const r=i.get(e);if(!r)return;const c=s==null?void 0:s.originalEvent;(l=n.onLayerAction)==null||l.call(n,"feicao-clique",{camadaId:o.id,feicao:r.feicao,aditivo:!!(c&&(c.ctrlKey||c.metaKey||c.shiftKey))})}),t.on("dblclick",()=>{var r;const s=i.get(e);s&&((r=n.onLayerAction)==null||r.call(n,"feicao-duplo-clique",{camadaId:o.id,feicao:s.feicao}))}),t instanceof y.Marker&&t.on("dragend",()=>{var l;const s=i.get(e);if(!s||s.feicao.geometria.tipo!=="Text")return;const{lat:r,lng:c}=t.getLatLng();s.feicao={...s.feicao,geometria:{...s.feicao.geometria,coordenada:[r,c]}},(l=n.onLayerAction)==null||l.call(n,"feicao-movida",{camadaId:o.id,feicao:s.feicao})})}}R.register("tile",new Ro);R.register("wms",new Fo);R.register("vetorial-linhas",new Vo);R.register("vetorial-pontos",new Go);R.register("vetorial-poligonos",new jo);R.register("grid",new Uo);R.register("feicoes",new di);const ke=[{id:"satelite",nome:"Satélite Google Híbrido",categoria:"base",tipo:"tile",visivel:!0,opacidade:1,zIndex:200,interativo:!1,bloqueada:!1,estilo:{scaleMode:"screen"}},{id:"sigef",nome:"Acervo Fundiário SIGEF (INCRA)",categoria:"wms",tipo:"wms",visivel:!0,opacidade:.85,zIndex:390,interativo:!0,bloqueada:!1,estilo:{scaleMode:"screen"}},{id:"homologados",nome:"Poligonal Homologada (Banco)",categoria:"referencia",tipo:"vetorial-linhas",visivel:!0,opacidade:.9,zIndex:420,interativo:!0,bloqueada:!1,estilo:{corPrimaria:"#f59e0b",espessuraLinha:1,dashArray:"6, 8",scaleMode:"screen"}},{id:"homologados-pontos",nome:"Marcos Homologados (Banco)",categoria:"referencia",tipo:"vetorial-pontos",visivel:!0,opacidade:1,zIndex:430,interativo:!0,bloqueada:!1,estilo:{tamanhoMarcador:8,estiloMarcador:"circle",scaleMode:"screen"}},{id:"perimetro",nome:"Divisas e Poligonal do Imóvel",categoria:"levantamento",tipo:"vetorial-linhas",visivel:!0,opacidade:1,zIndex:520,interativo:!0,bloqueada:!1,estilo:{corPrimaria:"#00f5a0",espessuraLinha:1,scaleMode:"screen",dimensaoMetros:.3}},{id:"vizinhos",nome:"Imóveis Confrontantes (WKT/CSV)",categoria:"referencia",tipo:"vetorial-poligonos",visivel:!0,opacidade:.8,zIndex:440,interativo:!0,bloqueada:!1,estilo:{corPrimaria:"#a855f7",espessuraLinha:1,dashArray:"4, 6",scaleMode:"screen"}},{id:"vertices",nome:"Vértices e Marcos do Levantamento",categoria:"levantamento",tipo:"vetorial-pontos",visivel:!0,opacidade:1,zIndex:650,interativo:!0,bloqueada:!1,estilo:{tamanhoMarcador:8,scaleMode:"screen",dimensaoMetros:.25}},{id:"grade",nome:"Grade de Coordenadas UTM",categoria:"referencia",tipo:"grid",visivel:!0,opacidade:.5,zIndex:700,interativo:!1,bloqueada:!1,estilo:{corPrimaria:"rgba(0, 245, 160, 0.18)",espessuraLinha:.6,scaleMode:"screen"}}],ka=new Set(["tile","wms","grid"]);class hi{constructor(t){p(this,"layers",[]);p(this,"layerInstances",new Map);p(this,"map",null);p(this,"context",null);p(this,"listeners",[]);p(this,"renderPendente",!1);this.layers=(t||ke).map(e=>({...e,estilo:{...e.estilo}}))}descartarCamadasPadrao(){if(this.map)return;const t=new Set(ke.map(e=>e.id));this.layers=this.layers.filter(e=>!t.has(e.id)||e.tipo==="feicoes")}attachMap(t,e){this.map=t,this.context=e,this.ensurePanes(),this.renderAllLayers()}ensurePanes(){this.map&&this.layers.forEach(t=>{const e=`pane-${t.id}`;let o=this.map.getPane(e);o||(o=this.map.createPane(e)),o&&(o.style.zIndex=String(t.zIndex),o.style.pointerEvents=t.interativo&&!t.bloqueada&&t.visivel?"auto":"none")})}renderAllLayers(t=!1){this.renderPendente=!1,!(!this.map||!this.context)&&(this.layers.forEach(e=>{if(!(t&&ka.has(e.tipo)&&e.visivel&&this.layerInstances.has(e.id))){if(this.layerInstances.has(e.id)){const o=this.layerInstances.get(e.id),i=R.get(e.tipo);i&&i.destroy(o,this.map),this.layerInstances.delete(e.id)}if(e.visivel){const o=R.get(e.tipo);if(o){const i=o.render(e,this.map,this.context);i&&(i.addTo(this.map),this.layerInstances.set(e.id,i))}}}}),this.notifyChange())}flushRender(){this.renderPendente&&this.renderAllLayers(!0)}agendarRender(){this.renderPendente||(this.renderPendente=!0,queueMicrotask(()=>this.flushRender()))}setLayerVisibility(t,e){this.flushRender();const o=this.layers.find(s=>s.id===t);if(!o||o.visivel===e||(o.visivel=e,!this.map||!this.context))return;const i=`pane-${o.id}`,n=this.map.getPane(i);if(n&&(n.style.display=e?"":"none",n.style.pointerEvents=o.visivel&&o.interativo&&!o.bloqueada?"auto":"none"),e){if(!this.layerInstances.has(t)){const s=R.get(o.tipo);if(s){const r=s.render(o,this.map,this.context);r&&(r.addTo(this.map),this.layerInstances.set(t,r))}}}else if(this.layerInstances.has(t)){const s=this.layerInstances.get(t),r=R.get(o.tipo);r&&r.destroy(s,this.map),this.layerInstances.delete(t)}this.notifyChange()}setLayerOpacity(t,e){this.flushRender();const o=this.layers.find(n=>n.id===t);if(!o)return;if(o.opacidade=Math.max(0,Math.min(1,e)),this.map){const n=this.map.getPane(`pane-${t}`);n&&(n.style.opacity=String(o.opacidade))}const i=this.layerInstances.get(t);if(i&&this.map&&this.context){const n=R.get(o.tipo);n&&n.update(o,i,{opacidade:o.opacidade},this.context,this.map)}this.notifyChange()}setLayerZIndex(t,e){const o=this.layers.find(i=>i.id===t);if(o){if(o.zIndex=e,this.map){const i=this.map.getPane(`pane-${t}`);i&&(i.style.zIndex=String(e))}this.notifyChange()}}setLayerBlocked(t,e){const o=this.layers.find(i=>i.id===t);if(o){if(o.bloqueada=e,this.map){const i=this.map.getPane(`pane-${t}`);i&&(i.style.pointerEvents=o.visivel&&o.interativo&&!e?"auto":"none")}this.notifyChange()}}setLayerScaleMode(t,e){this.flushRender();const o=this.layers.find(n=>n.id===t);if(!o)return;o.estilo.scaleMode=e;const i=this.layerInstances.get(t);if(i&&this.map&&this.context){const n=R.get(o.tipo);n&&n.update(o,i,{estilo:o.estilo},this.context,this.map)}this.notifyChange()}setGraphicScale(t){this.context&&(this.context.graphicScale={...this.context.graphicScale,...t},this.agendarRender())}updateContext(t){this.context&&(this.context={...this.context,...t},this.agendarRender())}getLayers(){return[...this.layers]}getActiveSelectableLayers(){return this.layers.filter(t=>t.visivel&&t.interativo&&!t.bloqueada)}isLayerActiveAndSelectable(t){const e=this.layers.find(o=>o.id===t);return!!(e&&e.visivel&&e.interativo&&!e.bloqueada)}exportState(){return this.layers.map(t=>({id:t.id,visivel:t.visivel,opacidade:t.opacidade,zIndex:t.zIndex,bloqueada:t.bloqueada,estilo:{...t.estilo}}))}importState(t){!t||!Array.isArray(t)||(t.forEach(e=>{const o=this.layers.find(i=>i.id===e.id);o&&(e.visivel!==void 0&&(o.visivel=e.visivel),e.opacidade!==void 0&&(o.opacidade=e.opacidade),e.zIndex!==void 0&&(o.zIndex=e.zIndex),e.bloqueada!==void 0&&(o.bloqueada=e.bloqueada),e.estilo&&(o.estilo={...o.estilo,...e.estilo}))}),this.ensurePanes(),this.renderAllLayers())}onChange(t){return this.listeners.push(t),()=>{this.listeners=this.listeners.filter(e=>e!==t)}}notifyChange(){const t=this.getLayers();this.listeners.forEach(e=>{try{e(t)}catch(o){console.error("Erro no listener de camadas:",o)}})}getAllLayerInstances(){return this.flushRender(),Array.from(this.layerInstances.values())}getLayerInstance(t){return this.flushRender(),this.layerInstances.get(t)}getLayer(t){return this.layers.find(e=>e.id===t)}getLayerDef(t){return this.layers.find(e=>e.id===t)}getOrCreateLayer(t,e,o){let i=this.layers.find(n=>n.id===t);return i||(i={id:t,nome:o,categoria:"custom",tipo:e,visivel:!0,opacidade:1,zIndex:600,interativo:!0,bloqueada:!1,estilo:{scaleMode:"screen"}},this.layers.push(i),this.ensurePanes()),i}setLayerData(t,e){this.flushRender();const o=this.layers.find(n=>n.id===t);if(!o)return;o.dados=e;const i=this.layerInstances.get(t);if(i&&this.map&&this.context){const n=R.get(o.tipo);n&&n.update(o,i,{dados:e},this.context,this.map)}else if(o.visivel&&this.map&&this.context){const n=R.get(o.tipo);if(n){const s=n.render(o,this.map,this.context);s&&(s.addTo(this.map),this.layerInstances.set(t,s))}}this.notifyChange()}clearLayers(t){this.flushRender(),(t&&t.length>0?t:Array.from(this.layerInstances.keys())).forEach(o=>{if(this.layerInstances.has(o)){const i=this.layerInstances.get(o),n=this.layers.find(s=>s.id===o);if(n){const s=R.get(n.tipo);s&&s.destroy(i,this.map)}this.layerInstances.delete(o)}}),this.notifyChange()}destroy(){this.renderPendente=!1,this.map&&(this.layerInstances.forEach((t,e)=>{const o=this.layers.find(i=>i.id===e);if(o){const i=R.get(o.tipo);i&&i.destroy(t,this.map)}}),this.layerInstances.clear()),this.listeners=[]}}function ui(a,t){var s,r;if(t==null)return null;const e=String(t).trim(),o=c=>c?(c.lon=c.lng,c):null,n=a.getMarkers().find(c=>{var g,m,f,x;const l=c.pontoId,d=c.elementoId??c.id??((g=c.options)==null?void 0:g.pontoId)??((m=c.options)==null?void 0:m.id),h=(f=c.elemento)==null?void 0:f.nome_vertice,u=(x=c.elemento)==null?void 0:x.codigo_completo;return String(l)===e||String(d)===e||h&&String(h).toLowerCase()===e.toLowerCase()||u&&String(u).toLowerCase()===e.toLowerCase()});if(n&&typeof n.getLatLng=="function")return o(n.getLatLng());if(a.layerManager)for(const c of a.layerManager.getAllLayerInstances()){let l=null;const d=h=>{var m,f,x,E,M;if(l)return;const u=h.pontoId??h.elementoId??h.id??((m=h.options)==null?void 0:m.id)??((f=h.options)==null?void 0:f.pontoId),g=((x=h.elemento)==null?void 0:x.nome)??((E=h.elemento)==null?void 0:E.nome_vertice)??((M=h.options)==null?void 0:M.nome);(String(u)===e||g&&String(g).toLowerCase()===e.toLowerCase())&&(typeof h.getLatLng=="function"?l=h.getLatLng():typeof h.getBounds=="function"&&(l=h.getBounds().getCenter()))};if(d(c),typeof c.eachLayer=="function"&&c.eachLayer(d),l)return o(l)}if(a.context.pontos&&a.context.pontos.length>0){const c=a.context.pontos.find(l=>String(l.id)===e||l.nome_vertice&&String(l.nome_vertice).toLowerCase()===e.toLowerCase());if(c){const l=c.lat??c.latitude??c.y,d=c.lon??c.lng??c.longitude??c.x,h=S.parseCoordenada(l,d);if(h)return o(y.latLng(h.lat,h.lon))}}if(a.context.bancoPontos&&a.context.bancoPontos.length>0){const c=a.context.bancoPontos.find(l=>String(l.id)===e||l.codigo_completo&&String(l.codigo_completo).toLowerCase()===e.toLowerCase()||l.nome_vertice&&String(l.nome_vertice).toLowerCase()===e.toLowerCase());if(c){const l=c.lat??c.latitude??c.y,d=c.lon??c.lng??c.longitude??c.x,h=S.parseCoordenada(l,d);if(h)return o(y.latLng(h.lat,h.lon))}}if(a.context.confrontantes&&a.context.confrontantes.length>0){const c=a.context.confrontantes.find(l=>String(l.id)===e||l.nome&&String(l.nome).toLowerCase()===e.toLowerCase()||l.nome_propriedade&&String(l.nome_propriedade).toLowerCase()===e.toLowerCase());if(c){if(c.pontos&&c.pontos.length>0){let l=0,d=0,h=0;for(const u of c.pontos){const g=u.lat??u.latitude??u.y,m=u.lon??u.lng??u.longitude??u.x,f=S.parseCoordenada(g,m);f&&(l+=f.lat,d+=f.lon,h++)}if(h>0)return o(y.latLng(l/h,d/h))}if(c.poligono_wkt){const l=S.extrairCentroDeWkt(c.poligono_wkt);if(l)return o(y.latLng(l.lat,l.lon))}}}if(a.context.segmentos&&a.context.segmentos.length>0){const c=a.context.segmentos.find(l=>String(l.id)===e||`${l.ponto_inicio_id}-${l.ponto_fim_id}`===e);if(c){const l=(s=a.context.pontos)==null?void 0:s.find(h=>String(h.id)===String(c.ponto_inicio_id)),d=(r=a.context.pontos)==null?void 0:r.find(h=>String(h.id)===String(c.ponto_fim_id));if(l&&d){const h=S.parseCoordenada(l.lat??l.latitude,l.lon??l.longitude),u=S.parseCoordenada(d.lat??d.latitude,d.lon??d.longitude);if(h&&u)return o(y.latLng((h.lat+u.lat)/2,(h.lon+u.lon)/2))}}}if(a.layerManager){for(const c of a.layerManager.getLayers())if(c.dados){if(Array.isArray(c.dados.pontos)){const l=c.dados.pontos.find(d=>String(d.id)===e||d.nome_vertice&&String(d.nome_vertice)===e);if(l){const d=S.parseCoordenada(l.lat,l.lon);if(d)return o(y.latLng(d.lat,d.lon))}}if(Array.isArray(c.dados.poligonos)){const l=c.dados.poligonos.find(d=>String(d.id)===e);if(l){if(l.wkt){const d=S.extrairCentroDeWkt(l.wkt);if(d)return o(y.latLng(d.lat,d.lon))}if(Array.isArray(l.coordenadas)&&l.coordenadas.length>0){let d=0,h=0,u=0;for(const g of l.coordenadas){const m=S.parseCoordenada(g[0],g[1])||S.parseCoordenada(g[1],g[0]);m&&(d+=m.lat,h+=m.lon,u++)}if(u>0)return o(y.latLng(d/u,h/u))}}}}}return null}function Ia(a,t,e,o){var g,m;Ie(t,a.getMap());const i=a.getMap();if(!i)return;const n=ui(a,e);if(!n){console.warn(`[ui-canvas-cad] Elemento com identificador "${e}" não encontrado para destaque.`);return}const s=(o==null?void 0:o.pan)===!0,r=o==null?void 0:o.zoom;s?r!==void 0?typeof i.flyTo=="function"?i.flyTo(n,r,{animate:!0}):i.setView(n,r,{animate:!0}):typeof i.panTo=="function"?i.panTo(n,{animate:!0}):i.setView(n,i.getZoom(),{animate:!0}):r!==void 0&&i.setZoom(r,{animate:!0});const c=(o==null?void 0:o.cor)||"#00f5a0",l="pane-destaque";let d=i.getPane(l);d||(d=i.createPane(l)),d&&(d.style.zIndex="850",d.style.pointerEvents="none");const h=y.divIcon({className:"cad-destaque-marker-container",html:`
100
100
  <div class="cad-pulse-highlight" style="--cad-pulse-cor: ${S.escapeHtml(c)};">
101
101
  <div class="cad-pulse-core"></div>
102
102
  <div class="cad-pulse-ring ring-1"></div>
103
103
  <div class="cad-pulse-ring ring-2"></div>
104
104
  </div>
105
- `,iconSize:[52,52],iconAnchor:[26,26]});t.destaqueMarker=y.marker(a,{icon:h,pane:l,interactive:!1,keyboard:!1}),t.destaqueMarker.addTo(i);const u=(f=(m=t.destaqueMarker).getElement)==null?void 0:f.call(m);u&&(u.style.pointerEvents="none"),o!=null&&o.duracaoMs&&o.duracaoMs>0&&(t.destaqueTimeoutId=window.setTimeout(()=>{Me(t,i)},o.duracaoMs))}function Me(n,t){n.destaqueTimeoutId!==null&&(window.clearTimeout(n.destaqueTimeoutId),n.destaqueTimeoutId=null),n.destaqueMarker&&(t&&t.hasLayer(n.destaqueMarker)?t.removeLayer(n.destaqueMarker):typeof n.destaqueMarker.remove=="function"&&n.destaqueMarker.remove(),n.destaqueMarker=null)}function En(n,t){const e=new Map;n.forEach(i=>{const a=i.lat??i.latitude??i.y,s=i.lon??i.lng??i.longitude??i.x,r=S.parseCoordenada(a,s);r&&(i.lat=r.lat,i.lon=r.lon);const c=i.confrontante_id??i.id_confrontante??0;e.has(c)||e.set(c,[]),e.get(c).push(i)});const o=new Map;return t.forEach(i=>{const a=i.id!==void 0&&i.id!==null?i.id:0;o.set(a,{...i,pontos:[]})}),e.forEach((i,a)=>{var s,r;if(o.has(a)){const c=o.get(a);c.pontos=i}else o.set(a,{id:a,nome:((s=i[0])==null?void 0:s.nome_confrontante)||"Confrontante",nome_propriedade:((r=i[0])==null?void 0:r.nome_propriedade)||"",pontos:i})}),Array.from(o.values()).filter(i=>i.pontos&&i.pontos.length>0||!!i.poligono_wkt)}function In(n,t){const e=new Map;return t.forEach(o=>{o.id!==void 0&&o.id!==null&&o.pontos&&o.pontos.length>0&&e.set(o.id,o.pontos)}),n.map(o=>{const i=o.id!==void 0&&o.id!==null?o.id:void 0;return i!==void 0&&(!o.pontos||o.pontos.length===0)&&e.has(i)?{...o,pontos:e.get(i)}:{...o}})}function _n(n,t,e=!1){let o=[...n];e&&t&&t.forEach(a=>{a.pontos&&o.push(...a.pontos)});const i=o.map(a=>{const s=a.lat??a.latitude??a.y,r=a.lon??a.lng??a.longitude??a.x,c=S.parseCoordenada(s,r);return c?y.latLng(c.lat,c.lon):null}).filter(a=>a!==null);return i.length===1?{single:i[0]}:i.length>1?{bounds:y.latLngBounds(i)}:null}function Tn(n,t){var a;(a=t==null?void 0:t.flushRender)==null||a.call(t);const e=[],o=new Set,i=s=>{s instanceof y.Marker&&s.pontoId!==void 0&&!o.has(s)&&(o.add(s),e.push(s))};return n&&n.eachLayer(s=>{i(s),typeof s.eachLayer=="function"&&s.eachLayer(i)}),t&&t.getAllLayerInstances().forEach(s=>{i(s),typeof s.eachLayer=="function"&&s.eachLayer(i)}),e}function Dn(n,t,e="vertices",o){const i=t||[];n.layerManager.getOrCreateLayer(e,"vetorial-pontos","Pontos / Vértices"),e==="vertices"&&(n.context.pontos=i,n.canvasInteracao.ctx.pontosList=i,o&&(n.customMarkerClickCallback=a=>{const s=i.find(r=>String(r.id)===String(a))||{id:a,lat:0,lon:0};o(s)})),n.layerManager.setLayerData(e,{pontos:i,onClique:o}),n.layerManager.setLayerVisibility(e,!0)}function $n(n,t,e="linhas"){const o=t||[];n.layerManager.getOrCreateLayer(e,"vetorial-linhas","Conexões / Linhas"),(e==="linhas"||e==="perimetro")&&(n.context.segmentos=o.map(i=>({ponto_inicio_id:Number(i.origemId)||0,ponto_fim_id:Number(i.destinoId)||0,tipo_limite_sigef:i.tipoLinha==="tracejada"?"LN1":"LA1"}))),n.layerManager.setLayerData(e,{conexoes:o}),n.layerManager.setLayerVisibility(e,!0)}function qn(n,t,e=!0,o="polilinha",i){const a=t||[];n.layerManager.getOrCreateLayer(o,"vetorial-linhas","Polilinhas"),(o==="polilinha"||o==="perimetro")&&(n.context.pontos=a,n.context.segmentos=[],n.canvasInteracao.ctx.pontosList=a);const s=i||n.chaveGrupo||n.context.chaveGrupo;n.layerManager.setLayerData(o,{pontos:a,fechar:e!==!1,polilinhaSequencial:!0,chaveGrupo:s}),n.layerManager.setLayerVisibility(o,!0)}function Nn(n,t,e="poligonos"){const o=t||[];n.layerManager.getOrCreateLayer(e,"vetorial-poligonos","Polígonos"),n.layerManager.setLayerData(e,{poligonos:o}),n.layerManager.setLayerVisibility(e,!0)}function On(n,t,e){const o=t||[];if(e!=null){const i=e||[];n.context.pontos=i,n.canvasInteracao.ctx.pontosList=i}n.context.segmentos=o,n.layerManager.updateContext({segmentos:o,...e!=null?{pontos:n.context.pontos}:{}})}function Fn(n,t=!1){n.context.pontos=[],n.context.segmentos=[],n.context.confrontantes=[],n.canvasInteracao.ctx.pontosList=[],n.canvasInteracao.limparSelecao();const e={pontos:[],segmentos:[],confrontantes:[]};t||(n.context.bancoPontos=[],e.bancoPontos=[]),n.layerManager.updateContext(e)}function so(n){return n!=null&&!isNaN(Number(n))&&String(n).trim()!==""?Number(n):n}function Rn(n,t){var r,c;const e=n.core.map,o=n.layerManager.getLayerDef(t.layerId),i=t.baseSize||8,a=((r=n.context.graphicScale)==null?void 0:r.markerScaleMultiplier)||1;if(e&&((c=o==null?void 0:o.estilo)==null?void 0:c.scaleMode)==="world"){const l=o.estilo.dimensaoMetros||.25,d=e.getCenter(),h=e.getZoom(),u=40075016686e-3*Math.abs(Math.cos(d.lat*Math.PI/180))/Math.pow(2,h+8),m=l/(u>0?u:1);return Math.max(3,Math.round(m*a))}const s=Te(t.densTotal||0,(e==null?void 0:e.getZoom())??18);return Math.max(s<1?5:4,Math.round(i*a*s))}function Bn(n,t,e,o,i){const a=Rn(n,e),s=n.context.config.enableAnimations?"cad-pt-anim":"",r=At(e.shapeStyle,a,e.markerBg,s,`map-marker-${e.layerId||"pts"}-${o}`,i,{densidade:Wt(e.densTotal||0)});e.tamanhoPx=a,t.setIcon(y.divIcon({html:r,className:`custom-leaflet-marker ${i?"cad-marker-selected ponto-selecionado":""}`,iconSize:[a+6,a+6]}))}function Hn(n){const t=n.context.selectedPontoIds||[],e=n.canvasInteracao.ctx.selectedVizinhoPontoIds||[],o=new Set([...t.map(String),...e.map(String)]);for(const i of n.getMarkers()){const a=i,s=a.pontoId;if(s==null)continue;const r=o.has(String(s));if(a.isSelected===r)continue;a.isSelected=r,i.setZIndexOffset(r?2e3:0),a.shapeStyle&&a.baseSize&&a.markerBg&&Bn(n,i,a,s,r);const c=i.getElement();c&&(r?c.classList.add("cad-marker-selected","ponto-selecionado"):c.classList.remove("cad-marker-selected","ponto-selecionado"))}}class ie{constructor(t){p(this,"core");p(this,"layerManager");p(this,"canvasInteracao");p(this,"context");p(this,"modoCliqueSequencialAtivo",!1);p(this,"chaveGrupo");p(this,"zonaProjecao",22);p(this,"levantamentoId",null);p(this,"customMarkerClickCallback");p(this,"customPopupActionCallback");p(this,"destaqueState",{destaqueMarker:null,destaqueTimeoutId:null});this.core=new Ao(this),this.layerManager=new si(t),this.canvasInteracao=new To({mapaController:this,layerManager:this.layerManager}),this.context={pontos:[],segmentos:[],bancoPontos:[],confrontantes:[],zonaProjecao:22,config:this.core.config,graphicScale:{markerScaleMultiplier:1,lineScaleMultiplier:1,scaleModeGlobal:"screen"},onMarkerClick:(e,o)=>{if(this.modoCliqueSequencialAtivo||this.context.modoSequencial)return;const i=so(e);if(this.customMarkerClickCallback)try{this.customMarkerClickCallback(i,o)}catch(a){console.error("Erro no customMarkerClickCallback:",a)}o?this.canvasInteracao.ctx.selectedVizinhoPontoIds=[i]:(this.canvasInteracao.ctx.selectedPontoIds=[i],this.canvasInteracao.ctx.lastSelectedPontoId=i),this.context.selectedPontoIds=[...this.canvasInteracao.ctx.selectedPontoIds],this.atualizarDestaqueMarcadores(),window.dispatchEvent(new CustomEvent("gerencigeo:ponto-selecionado",{detail:{selectedPontoIds:[i],lastSelectedPontoId:i,isVizinho:o}}))},onPopupAcao:(e,o,i)=>{if(this.customPopupActionCallback)try{this.customPopupActionCallback(e,o,i)}catch(a){console.error("Erro no customPopupActionCallback:",a)}}}}init(t,e){const o=this.core.init(t);return o&&(this.layerManager.attachMap(o,this.context),this.canvasInteracao.ativar(this,e)),o}invalidateSize(){try{this.core&&(typeof this.core.invalidateSize=="function"?this.core.invalidateSize():this.core.map&&typeof this.core.map.invalidateSize=="function"&&this.core.map.invalidateSize())}catch{}}setPontos(t){const e=t||[];this.context.pontos=e,this.canvasInteracao.ctx.pontosList=e,this.layerManager.updateContext({pontos:e})}setSegmentos(t){const e=t||[];this.context.segmentos=e,this.layerManager.updateContext({segmentos:e})}setBancoPontos(t){const e=t||[];this.context.bancoPontos=e,this.layerManager.updateContext({bancoPontos:e})}setConfrontantes(t){const e=t||[];this.context.confrontantes=e,this.layerManager.updateContext({confrontantes:e})}plotarPontos(t,e="vertices",o){Dn(this,t,e,o)}plotarConexoes(t,e="linhas"){$n(this,t,e)}plotarPolilinhaSequencial(t,e=!0,o="polilinha",i){qn(this,t,e,o,i)}plotarPoligonos(t,e="poligonos"){Nn(this,t,e)}limparCamadas(t){this.layerManager.clearLayers(t),(!t||t.length===0)&&this.canvasInteracao.limparSelecao()}obterMarcadores(t){if(t){const e=[],o=this.layerManager.getLayerInstance(t);if(o){const i=a=>{a instanceof y.Marker&&e.push(a)};i(o),typeof o.eachLayer=="function"&&o.eachLayer(i)}return e}return this.getMarkers()}plotPontos(t,e){e&&(this.customMarkerClickCallback=e),this.setPontos(t||[])}plotSegmentos(t,e){On(this,t,e)}plotPolilinhaTemporaria(t){const e=t||[];this.context.pontos=e,this.context.segmentos=[],this.canvasInteracao.ctx.pontosList=e,this.layerManager.updateContext({pontos:e,segmentos:[]})}plotPoligonalHomologada(t){const e=t||[];this.setBancoPontos(e),this.layerManager.setLayerVisibility("homologados",!0),this.layerManager.setLayerVisibility("homologados-pontos",!0)}plotPontosVizinhos(t){const e=En(t||[],this.context.confrontantes||[]);this.setConfrontantes(e),this.layerManager.setLayerVisibility("vizinhos",!0)}plotPoligonosVizinhos(t){const e=In(t||[],this.context.confrontantes||[]);this.setConfrontantes(e),this.layerManager.setLayerVisibility("vizinhos",!0)}clearOverlays(t=!1){Fn(this,t)}setGraphicScale(t){this.layerManager.setGraphicScale(t)}exportState(){return this.layerManager.exportState()}importState(t){this.layerManager.importState(t)}selectPonto(t,e){if(!this.core.map)return;const o=String(t),i=this.getMarkers().find(s=>String(s.pontoId)===o);if(i){const s=e!==void 0?e:this.core.map.getZoom();this.core.map.setView(i.getLatLng(),s),i.openPopup()}const a=so(t);this.canvasInteracao.ctx.selectedPontoIds=[a],this.canvasInteracao.ctx.lastSelectedPontoId=a,this.context.selectedPontoIds=[a],this.atualizarDestaqueMarcadores()}atualizarDestaqueMarcadores(){Hn(this)}selectSegmento(t){const e=t!=null?String(t):null;(this.context.selectedSegmentoId??null)!==e&&(this.context.selectedSegmentoId=e,this.layerManager.updateContext({selectedSegmentoId:e}))}fitBounds(t,e=[40,40],o=!1){if(!this.core.map)return;const i=_n(t||this.context.pontos||[],this.context.confrontantes,o);if(i){i.single?this.core.map.setView(i.single,18):i.bounds&&(this.core.map.fitBounds(i.bounds,{padding:e}),this.core.map.once("moveend",()=>{this.core.preCarregarTilesRegiao(i.bounds)}));try{this.core.map.invalidateSize()}catch{}}}getMarkers(){return Tn(this.core.map,this.layerManager)}getVizinhosMarkers(){return this.getMarkers().filter(t=>!!t.isVizinho)}get destaqueAtivo(){return this.destaqueState.destaqueMarker!==null}localizarCoordenadasElemento(t){return ri(this,t)}destacarElemento(t,e){zn(this,this.destaqueState,t,e)}limparDestaque(){Me(this.destaqueState,this.getMap())}destroy(){if(this.limparDestaque(),this.canvasInteracao.desativar(),this.layerManager.destroy(),this.core.destroy(),this.core.map)try{this.core.map.off(),this.core.map.remove()}catch{}finally{this.core.map=null}}getMap(){return this.core.map}}function ci(n,t,e,o){if(!n)return;if(n.querySelectorAll(".layer-item").length===t.length){t.forEach(a=>{var r,c;const s=n.querySelector(`.layer-item[data-layer-id="${a.id}"]`);if(s){const l=s.querySelector(".layer-chk-visibility");l&&l.checked!==a.visivel&&(l.checked=a.visivel);const d=s.querySelector(".layer-opacity-slider"),h=s.querySelector(".opacity-percent-label"),u=Math.round(a.opacidade*100);d&&parseInt(d.value,10)!==u&&(d.value=String(u)),h&&(h.textContent=`${u}%`);const m=s.querySelector(".btn-lock-layer");m&&(m.classList.toggle("active",!!a.bloqueada),m.title=a.bloqueada?"Desbloquear Camada":"Bloquear Camada");const f=s.querySelector(".btn-toggle-scale-mode");f&&((r=a.estilo)!=null&&r.scaleMode)&&(f.textContent=((c=a.estilo)==null?void 0:c.scaleMode)==="world"?"Métrico":"Tela")}});return}n.innerHTML=`
106
- ${t.map(a=>{var s,r;return`
107
- <div class="layer-item" data-layer-id="${a.id}">
105
+ `,iconSize:[52,52],iconAnchor:[26,26]});t.destaqueMarker=y.marker(n,{icon:h,pane:l,interactive:!1,keyboard:!1}),t.destaqueMarker.addTo(i);const u=(m=(g=t.destaqueMarker).getElement)==null?void 0:m.call(g);u&&(u.style.pointerEvents="none"),o!=null&&o.duracaoMs&&o.duracaoMs>0&&(t.destaqueTimeoutId=window.setTimeout(()=>{Ie(t,i)},o.duracaoMs))}function Ie(a,t){a.destaqueTimeoutId!==null&&(window.clearTimeout(a.destaqueTimeoutId),a.destaqueTimeoutId=null),a.destaqueMarker&&(t&&t.hasLayer(a.destaqueMarker)?t.removeLayer(a.destaqueMarker):typeof a.destaqueMarker.remove=="function"&&a.destaqueMarker.remove(),a.destaqueMarker=null)}function _a(a,t){const e=new Map;a.forEach(i=>{const n=i.lat??i.latitude??i.y,s=i.lon??i.lng??i.longitude??i.x,r=S.parseCoordenada(n,s);r&&(i.lat=r.lat,i.lon=r.lon);const c=i.confrontante_id??i.id_confrontante??0;e.has(c)||e.set(c,[]),e.get(c).push(i)});const o=new Map;return t.forEach(i=>{const n=i.id!==void 0&&i.id!==null?i.id:0;o.set(n,{...i,pontos:[]})}),e.forEach((i,n)=>{var s,r;if(o.has(n)){const c=o.get(n);c.pontos=i}else o.set(n,{id:n,nome:((s=i[0])==null?void 0:s.nome_confrontante)||"Confrontante",nome_propriedade:((r=i[0])==null?void 0:r.nome_propriedade)||"",pontos:i})}),Array.from(o.values()).filter(i=>i.pontos&&i.pontos.length>0||!!i.poligono_wkt)}function Ta(a,t){const e=new Map;return t.forEach(o=>{o.id!==void 0&&o.id!==null&&o.pontos&&o.pontos.length>0&&e.set(o.id,o.pontos)}),a.map(o=>{const i=o.id!==void 0&&o.id!==null?o.id:void 0;return i!==void 0&&(!o.pontos||o.pontos.length===0)&&e.has(i)?{...o,pontos:e.get(i)}:{...o}})}function Da(a,t,e=!1){let o=[...a];e&&t&&t.forEach(n=>{n.pontos&&o.push(...n.pontos)});const i=o.map(n=>{const s=n.lat??n.latitude??n.y,r=n.lon??n.lng??n.longitude??n.x,c=S.parseCoordenada(s,r);return c?y.latLng(c.lat,c.lon):null}).filter(n=>n!==null);return i.length===1?{single:i[0]}:i.length>1?{bounds:y.latLngBounds(i)}:null}function $a(a,t){var n;(n=t==null?void 0:t.flushRender)==null||n.call(t);const e=[],o=new Set,i=s=>{s instanceof y.Marker&&s.pontoId!==void 0&&!o.has(s)&&(o.add(s),e.push(s))};return a&&a.eachLayer(s=>{i(s),typeof s.eachLayer=="function"&&s.eachLayer(i)}),t&&t.getAllLayerInstances().forEach(s=>{i(s),typeof s.eachLayer=="function"&&s.eachLayer(i)}),e}function qa(a,t,e="vertices",o){const i=t||[];a.layerManager.getOrCreateLayer(e,"vetorial-pontos","Pontos / Vértices"),e==="vertices"&&(a.context.pontos=i,a.canvasInteracao.ctx.pontosList=i,o&&(a.customMarkerClickCallback=n=>{const s=i.find(r=>String(r.id)===String(n))||{id:n,lat:0,lon:0};o(s)})),a.layerManager.setLayerData(e,{pontos:i,onClique:o}),a.layerManager.setLayerVisibility(e,!0)}function Na(a,t,e="linhas"){const o=t||[];a.layerManager.getOrCreateLayer(e,"vetorial-linhas","Conexões / Linhas"),(e==="linhas"||e==="perimetro")&&(a.context.segmentos=o.map(i=>({ponto_inicio_id:Number(i.origemId)||0,ponto_fim_id:Number(i.destinoId)||0,tipo_limite_sigef:i.tipoLinha==="tracejada"?"LN1":"LA1"}))),a.layerManager.setLayerData(e,{conexoes:o}),a.layerManager.setLayerVisibility(e,!0)}function Oa(a,t,e=!0,o="polilinha",i){const n=t||[];a.layerManager.getOrCreateLayer(o,"vetorial-linhas","Polilinhas"),(o==="polilinha"||o==="perimetro")&&(a.context.pontos=n,a.context.segmentos=[],a.canvasInteracao.ctx.pontosList=n);const s=i||a.chaveGrupo||a.context.chaveGrupo;a.layerManager.setLayerData(o,{pontos:n,fechar:e!==!1,polilinhaSequencial:!0,chaveGrupo:s}),a.layerManager.setLayerVisibility(o,!0)}function Ra(a,t,e="poligonos"){const o=t||[];a.layerManager.getOrCreateLayer(e,"vetorial-poligonos","Polígonos"),a.layerManager.setLayerData(e,{poligonos:o}),a.layerManager.setLayerVisibility(e,!0)}function Fa(a,t,e){const o=t||[];if(e!=null){const i=e||[];a.context.pontos=i,a.canvasInteracao.ctx.pontosList=i}a.context.segmentos=o,a.layerManager.updateContext({segmentos:o,...e!=null?{pontos:a.context.pontos}:{}})}function Ba(a,t=!1){a.context.pontos=[],a.context.segmentos=[],a.context.confrontantes=[],a.canvasInteracao.ctx.pontosList=[],a.canvasInteracao.limparSelecao();const e={pontos:[],segmentos:[],confrontantes:[]};t||(a.context.bancoPontos=[],e.bancoPontos=[]),a.layerManager.updateContext(e)}function uo(a){return a!=null&&!isNaN(Number(a))&&String(a).trim()!==""?Number(a):a}function Va(a,t){var r,c;const e=a.core.map,o=a.layerManager.getLayerDef(t.layerId),i=t.baseSize||8,n=((r=a.context.graphicScale)==null?void 0:r.markerScaleMultiplier)||1;if(e&&((c=o==null?void 0:o.estilo)==null?void 0:c.scaleMode)==="world"){const l=o.estilo.dimensaoMetros||.25,d=e.getCenter(),h=e.getZoom(),u=40075016686e-3*Math.abs(Math.cos(d.lat*Math.PI/180))/Math.pow(2,h+8),g=l/(u>0?u:1);return Math.max(3,Math.round(g*n))}const s=Ne(t.densTotal||0,(e==null?void 0:e.getZoom())??18);return Math.max(s<1?5:4,Math.round(i*n*s))}function Ha(a,t,e,o,i){const n=Va(a,e),s=a.context.config.enableAnimations?"cad-pt-anim":"",r=zt(e.shapeStyle,n,e.markerBg,s,`map-marker-${e.layerId||"pts"}-${o}`,i,{densidade:Qt(e.densTotal||0)});e.tamanhoPx=n,t.setIcon(y.divIcon({html:r,className:`custom-leaflet-marker ${i?"cad-marker-selected ponto-selecionado":""}`,iconSize:[n+6,n+6]}))}function Ga(a){const t=a.context.selectedPontoIds||[],e=a.canvasInteracao.ctx.selectedVizinhoPontoIds||[],o=new Set([...t.map(String),...e.map(String)]);for(const i of a.getMarkers()){const n=i,s=n.pontoId;if(s==null)continue;const r=o.has(String(s));if(n.isSelected===r)continue;n.isSelected=r,i.setZIndexOffset(r?2e3:0),n.shapeStyle&&n.baseSize&&n.markerBg&&Ha(a,i,n,s,r);const c=i.getElement();c&&(r?c.classList.add("cad-marker-selected","ponto-selecionado"):c.classList.remove("cad-marker-selected","ponto-selecionado"))}}class le{constructor(t){p(this,"core");p(this,"layerManager");p(this,"canvasInteracao");p(this,"context");p(this,"modoCliqueSequencialAtivo",!1);p(this,"chaveGrupo");p(this,"zonaProjecao",22);p(this,"levantamentoId",null);p(this,"customMarkerClickCallback");p(this,"customPopupActionCallback");p(this,"destaqueState",{destaqueMarker:null,destaqueTimeoutId:null});this.core=new Io(this),this.layerManager=new hi(t),this.canvasInteracao=new Oo({mapaController:this,layerManager:this.layerManager}),this.context={pontos:[],segmentos:[],bancoPontos:[],confrontantes:[],zonaProjecao:22,config:this.core.config,graphicScale:{markerScaleMultiplier:1,lineScaleMultiplier:1,scaleModeGlobal:"screen"},onMarkerClick:(e,o)=>{if(this.modoCliqueSequencialAtivo||this.context.modoSequencial)return;const i=uo(e);if(this.customMarkerClickCallback)try{this.customMarkerClickCallback(i,o)}catch(n){console.error("Erro no customMarkerClickCallback:",n)}o?this.canvasInteracao.ctx.selectedVizinhoPontoIds=[i]:(this.canvasInteracao.ctx.selectedPontoIds=[i],this.canvasInteracao.ctx.lastSelectedPontoId=i),this.context.selectedPontoIds=[...this.canvasInteracao.ctx.selectedPontoIds],this.atualizarDestaqueMarcadores(),window.dispatchEvent(new CustomEvent("gerencigeo:ponto-selecionado",{detail:{selectedPontoIds:[i],lastSelectedPontoId:i,isVizinho:o}}))},onPopupAcao:(e,o,i)=>{if(this.customPopupActionCallback)try{this.customPopupActionCallback(e,o,i)}catch(n){console.error("Erro no customPopupActionCallback:",n)}}}}init(t,e){const o=this.core.init(t);return o&&(this.layerManager.attachMap(o,this.context),this.canvasInteracao.ativar(this,e)),o}invalidateSize(){try{this.core&&(typeof this.core.invalidateSize=="function"?this.core.invalidateSize():this.core.map&&typeof this.core.map.invalidateSize=="function"&&this.core.map.invalidateSize())}catch{}}setPontos(t){const e=t||[];this.context.pontos=e,this.canvasInteracao.ctx.pontosList=e,this.layerManager.updateContext({pontos:e})}setSegmentos(t){const e=t||[];this.context.segmentos=e,this.layerManager.updateContext({segmentos:e})}setBancoPontos(t){const e=t||[];this.context.bancoPontos=e,this.layerManager.updateContext({bancoPontos:e})}setConfrontantes(t){const e=t||[];this.context.confrontantes=e,this.layerManager.updateContext({confrontantes:e})}plotarPontos(t,e="vertices",o){qa(this,t,e,o)}plotarConexoes(t,e="linhas"){Na(this,t,e)}plotarPolilinhaSequencial(t,e=!0,o="polilinha",i){Oa(this,t,e,o,i)}plotarPoligonos(t,e="poligonos"){Ra(this,t,e)}limparCamadas(t){this.layerManager.clearLayers(t),(!t||t.length===0)&&this.canvasInteracao.limparSelecao()}obterMarcadores(t){if(t){const e=[],o=this.layerManager.getLayerInstance(t);if(o){const i=n=>{n instanceof y.Marker&&e.push(n)};i(o),typeof o.eachLayer=="function"&&o.eachLayer(i)}return e}return this.getMarkers()}plotPontos(t,e){e&&(this.customMarkerClickCallback=e),this.setPontos(t||[])}plotSegmentos(t,e){Fa(this,t,e)}plotPolilinhaTemporaria(t){const e=t||[];this.context.pontos=e,this.context.segmentos=[],this.canvasInteracao.ctx.pontosList=e,this.layerManager.updateContext({pontos:e,segmentos:[]})}plotPoligonalHomologada(t){const e=t||[];this.setBancoPontos(e),this.layerManager.setLayerVisibility("homologados",!0),this.layerManager.setLayerVisibility("homologados-pontos",!0)}plotPontosVizinhos(t){const e=_a(t||[],this.context.confrontantes||[]);this.setConfrontantes(e),this.layerManager.setLayerVisibility("vizinhos",!0)}plotPoligonosVizinhos(t){const e=Ta(t||[],this.context.confrontantes||[]);this.setConfrontantes(e),this.layerManager.setLayerVisibility("vizinhos",!0)}clearOverlays(t=!1){Ba(this,t)}setGraphicScale(t){this.layerManager.setGraphicScale(t)}exportState(){return this.layerManager.exportState()}importState(t){this.layerManager.importState(t)}selectPonto(t,e){if(!this.core.map)return;const o=String(t),i=this.getMarkers().find(s=>String(s.pontoId)===o);if(i){const s=e!==void 0?e:this.core.map.getZoom();this.core.map.setView(i.getLatLng(),s),i.openPopup()}const n=uo(t);this.canvasInteracao.ctx.selectedPontoIds=[n],this.canvasInteracao.ctx.lastSelectedPontoId=n,this.context.selectedPontoIds=[n],this.atualizarDestaqueMarcadores()}atualizarDestaqueMarcadores(){Ga(this)}selectSegmento(t){const e=t!=null?String(t):null;(this.context.selectedSegmentoId??null)!==e&&(this.context.selectedSegmentoId=e,this.layerManager.updateContext({selectedSegmentoId:e}))}fitBounds(t,e=[40,40],o=!1){if(!this.core.map)return;const i=Da(t||this.context.pontos||[],this.context.confrontantes,o);if(i){i.single?this.core.map.setView(i.single,18):i.bounds&&(this.core.map.fitBounds(i.bounds,{padding:e}),this.core.map.once("moveend",()=>{this.core.preCarregarTilesRegiao(i.bounds)}));try{this.core.map.invalidateSize()}catch{}}}getMarkers(){return $a(this.core.map,this.layerManager)}getVizinhosMarkers(){return this.getMarkers().filter(t=>!!t.isVizinho)}get destaqueAtivo(){return this.destaqueState.destaqueMarker!==null}localizarCoordenadasElemento(t){return ui(this,t)}destacarElemento(t,e){Ia(this,this.destaqueState,t,e)}limparDestaque(){Ie(this.destaqueState,this.getMap())}destroy(){if(this.limparDestaque(),this.canvasInteracao.desativar(),this.layerManager.destroy(),this.core.destroy(),this.core.map)try{this.core.map.off(),this.core.map.remove()}catch{}finally{this.core.map=null}}getMap(){return this.core.map}}function pi(a,t,e,o){if(!a)return;if(a.querySelectorAll(".layer-item").length===t.length){t.forEach(n=>{var r,c;const s=a.querySelector(`.layer-item[data-layer-id="${n.id}"]`);if(s){const l=s.querySelector(".layer-chk-visibility");l&&l.checked!==n.visivel&&(l.checked=n.visivel);const d=s.querySelector(".layer-opacity-slider"),h=s.querySelector(".opacity-percent-label"),u=Math.round(n.opacidade*100);d&&parseInt(d.value,10)!==u&&(d.value=String(u)),h&&(h.textContent=`${u}%`);const g=s.querySelector(".btn-lock-layer");g&&(g.classList.toggle("active",!!n.bloqueada),g.title=n.bloqueada?"Desbloquear Camada":"Bloquear Camada");const m=s.querySelector(".btn-toggle-scale-mode");m&&((r=n.estilo)!=null&&r.scaleMode)&&(m.textContent=((c=n.estilo)==null?void 0:c.scaleMode)==="world"?"Métrico":"Tela")}});return}a.innerHTML=`
106
+ ${t.map(n=>{var s,r;return`
107
+ <div class="layer-item" data-layer-id="${n.id}">
108
108
  <div class="layer-item-row">
109
109
  <label class="layer-item-label">
110
- <input type="checkbox" class="layer-chk-visibility" data-layer-id="${a.id}" ${a.visivel?"checked":""} />
111
- <span>${a.nome}</span>
110
+ <input type="checkbox" class="layer-chk-visibility" data-layer-id="${n.id}" ${n.visivel?"checked":""} />
111
+ <span>${n.nome}</span>
112
112
  </label>
113
113
  <div class="layer-item-actions">
114
- <button class="btn-layer-action btn-lock-layer ${a.bloqueada?"active":""}" data-layer-id="${a.id}" type="button" title="${a.bloqueada?"Desbloquear Camada":"Bloquear Camada"}">
115
- ${a.bloqueada?'<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>':'<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 9.9-1"/></svg>'}
114
+ <button class="btn-layer-action btn-lock-layer ${n.bloqueada?"active":""}" data-layer-id="${n.id}" type="button" title="${n.bloqueada?"Desbloquear Camada":"Bloquear Camada"}">
115
+ ${n.bloqueada?'<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>':'<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 9.9-1"/></svg>'}
116
116
  </button>
117
- ${(s=a.estilo)!=null&&s.scaleMode?`
118
- <span class="scale-mode-pill btn-toggle-scale-mode" data-layer-id="${a.id}" title="Alternar modo de escala">
119
- ${((r=a.estilo)==null?void 0:r.scaleMode)==="world"?"Métrico":"Tela"}
117
+ ${(s=n.estilo)!=null&&s.scaleMode?`
118
+ <span class="scale-mode-pill btn-toggle-scale-mode" data-layer-id="${n.id}" title="Alternar modo de escala">
119
+ ${((r=n.estilo)==null?void 0:r.scaleMode)==="world"?"Métrico":"Tela"}
120
120
  </span>
121
121
  `:""}
122
122
  </div>
123
123
  </div>
124
124
  <div class="layer-controls-row">
125
125
  <span>Opacidade</span>
126
- <input type="range" min="0" max="100" value="${Math.round(a.opacidade*100)}" class="layer-opacity-slider" data-layer-id="${a.id}" />
127
- <span class="opacity-percent-label" style="font-family:var(--ui-fonte-codigo, monospace); font-size:9px; width:28px; text-align:right;">${Math.round(a.opacidade*100)}%</span>
126
+ <input type="range" min="0" max="100" value="${Math.round(n.opacidade*100)}" class="layer-opacity-slider" data-layer-id="${n.id}" />
127
+ <span class="opacity-percent-label" style="font-family:var(--ui-fonte-codigo, monospace); font-size:9px; width:28px; text-align:right;">${Math.round(n.opacidade*100)}%</span>
128
128
  </div>
129
129
  </div>
130
130
  `}).join("")}
131
- `,e.cleanup(),n.querySelectorAll(".layer-chk-visibility").forEach(a=>{e.add(a,"change",s=>{const r=s.target.getAttribute("data-layer-id"),c=s.target.checked;r&&o.setLayerVisibility(r,c)})}),n.querySelectorAll(".layer-opacity-slider").forEach(a=>{e.add(a,"input",s=>{const r=s.target.getAttribute("data-layer-id"),c=parseInt(s.target.value,10),l=c/100,d=s.target.closest(".layer-item"),h=d==null?void 0:d.querySelector(".opacity-percent-label");h&&(h.textContent=`${c}%`),r&&o.setLayerOpacity(r,l)})}),n.querySelectorAll(".btn-lock-layer").forEach(a=>{e.add(a,"click",s=>{const r=s.currentTarget.getAttribute("data-layer-id");if(r){const c=t.find(l=>l.id===r);c&&o.setLayerBlocked(r,!c.bloqueada)}})}),n.querySelectorAll(".btn-toggle-scale-mode").forEach(a=>{e.add(a,"click",s=>{var c;const r=s.currentTarget.getAttribute("data-layer-id");if(r){const l=t.find(d=>d.id===r);if(l){const d=((c=l.estilo)==null?void 0:c.scaleMode)==="world"?"screen":"world";o.setLayerScaleMode(r,d)}}})})}function li(n,t,e,o){var x,A,M,C,z,P;if(n.modoSequencial||n.controller.canvasInteracao.selectionHappened||n.controller.canvasInteracao.panHappened||n.mouseMovedSinceDown)return!1;const i=(t==null?void 0:t.originalEvent)||t,a=typeof(i==null?void 0:i.composedPath)=="function"?i.composedPath():[],s=a.length>0?a[0]:(i==null?void 0:i.target)||(t==null?void 0:t.target);if(s){const v='.custom-leaflet-marker, .leaflet-marker-icon, .leaflet-interactive, .compact-popup, .leaflet-popup, .ui-popup-btn, .cad-btn-tool, .qgis-layer-panel, [class*="leaflet-marker"], [class*="leaflet-popup"]';if(((x=s.matches)==null?void 0:x.call(s,v))||((A=s.closest)==null?void 0:A.call(s,v)))return!1}const r=n.controller.getMap();if(!r||!n.mapContainer)return!1;let c,l;if(o)c=Math.round(o.x),l=Math.round(o.y);else if(t!=null&&t.containerPoint||t!=null&&t.layerPoint)c=Math.round(((M=t.containerPoint)==null?void 0:M.x)??((C=t.layerPoint)==null?void 0:C.x)??0),l=Math.round(((z=t.containerPoint)==null?void 0:z.y)??((P=t.layerPoint)==null?void 0:P.y)??0);else{const v=n.mapContainer.getBoundingClientRect(),b=(i==null?void 0:i.clientX)??0,k=(i==null?void 0:i.clientY)??0;c=Math.round(b-v.left),l=Math.round(k-v.top)}const d={x:c,y:l};let h,u;const m=e||(t==null?void 0:t.latlng);if(m&&typeof m.lat=="number")h=m.lat,u=m.lng??m.lon??0;else{const v=r.containerPointToLatLng(y.point(d.x,d.y));h=v.lat,u=v.lng}const f=n.controller.layerManager?n.controller.layerManager.getLayers().filter(v=>v.visivel).map(v=>v.id):[],g=i;return n.host.dispatchEvent(new CustomEvent("ui-canvas-clique",{detail:{coordenadas:{lat:h,lng:u},pontoPixel:d,eventoOriginal:g,lat:h,lon:u,lng:u,camadasAtivas:f},bubbles:!0,composed:!0})),!0}function di(n,t,e,o){const i=o||n.obterElementoPorId(e);n.host.dispatchEvent(new CustomEvent("ui-acao-popup",{detail:{acaoId:t,elementoId:e,elemento:i??{id:e}},bubbles:!0,composed:!0})),n.fecharPopup()}function hi(n,t,e,o,i,a,s){let r=o||n.obterElementoPorId(t),c=i;if(!c&&r){const l=r.lat??r.latitude??0,d=r.lon??r.lng??r.longitude??0;c={lat:Number(l),lon:Number(d)}}if(c||(c={lat:0,lon:0}),n.modoSequencial){n.fecharPopup(),n.host.dispatchEvent(new CustomEvent("ui-clique-sequencial",{detail:{id:t,elemento:r??{id:t,lat:c.lat,lon:c.lon},coordenadas:c},bubbles:!0,composed:!0}));return}if(s)try{const l=t!=null&&!isNaN(Number(t))&&String(t).trim()!==""?Number(t):t;s(l,e)}catch(l){console.error("Erro no callback de clique de marcador:",l)}if(a)try{a(t,e,r,c)}catch(l){console.error("Erro no handler anterior de marker click:",l)}n.controller.context.selectedSegmentoId&&n.controller.selectSegmento(null),n.host.dispatchEvent(new CustomEvent("ui-ponto-selecionado",{detail:{selectedIds:[t],lastSelectedId:t,isVizinho:e},bubbles:!0,composed:!0})),n.host.dispatchEvent(new CustomEvent("ui-elemento-selecionado",{detail:{id:t,elemento:r,tipo:e?"vizinho":"vertice",coordenadas:c},bubbles:!0,composed:!0}))}function ui(n,t,e,o,i){if(n.modoSequencial){n.fecharPopup();return}if(n.controller.canvasInteracao.ctx.selectedPontoIds=[],n.controller.canvasInteracao.ctx.selectedVizinhoPontoIds=[],n.controller.canvasInteracao.ctx.lastSelectedPontoId=null,n.controller.context.selectedPontoIds=[],n.controller.atualizarDestaqueMarcadores(),n.controller.selectSegmento(t),i)try{i(t,e)}catch(a){console.error("Erro no callback de clique de segmento:",a)}n.host.dispatchEvent(new CustomEvent("ui-segmento-selecionado",{detail:{segmentoId:t,segmento:e,pontoInicioId:e==null?void 0:e.ponto_inicio_id,pontoFimId:e==null?void 0:e.ponto_fim_id,coordenadas:o},bubbles:!0,composed:!0})),n.host.dispatchEvent(new CustomEvent("ui-elemento-selecionado",{detail:{id:t,elemento:e,tipo:"segmento",coordenadas:o},bubbles:!0,composed:!0}))}function pi(n,t){let e=null,o=null,i=0,a=0;function s(){var d;try{if(!n.isConnected)return;const h=t.getMap();if(!h)return;const u=(d=h.getContainer)==null?void 0:d.call(h);if(!u||!u.parentNode)return;t.invalidateSize()}catch{}}function r(d=25){o!==null&&(window.clearTimeout(o),o=null),o=window.setTimeout(()=>{o=null,s()},d)}function c(){l(),!(typeof ResizeObserver>"u")&&(e=new ResizeObserver(d=>{for(const h of d){let u=0,m=0;h.contentRect?(u=h.contentRect.width,m=h.contentRect.height):h.borderBoxSize&&h.borderBoxSize.length>0?(u=h.borderBoxSize[0].inlineSize,m=h.borderBoxSize[0].blockSize):(u=n.clientWidth||n.offsetWidth,m=n.clientHeight||n.offsetHeight),u>0&&m>0&&(Math.abs(u-i)>=.5||Math.abs(m-a)>=.5)&&(i=u,a=m,r(25))}}),e.observe(n))}function l(){e&&(e.disconnect(),e=null),o!==null&&(window.clearTimeout(o),o=null)}return{observe:c,disconnect:l,invalidateSizeSafely:s}}class Vn{constructor(t){p(this,"canal",null);p(this,"contexto");this.contexto=t}conectar(t){this.desconectar();const e=t!==void 0?t:this.contexto.host.getAttribute("canal-configuracao");if(!(!e||typeof BroadcastChannel>"u"))try{this.canal=new BroadcastChannel(e),this.canal.onmessage=o=>{this.processarMensagem(o.data)}}catch(o){console.warn(`[ui-canvas-cad] Erro ao conectar ao BroadcastChannel "${e}":`,o)}}processarMensagem(t){if(!t||typeof t!="object")return;const e=t.tipo||"ESTILOS_ALTERADOS",o=t.configuracoes||t;if(o.crosshair!==void 0){const i=!!o.crosshair;this.contexto.mapContainer&&(this.contexto.mapContainer.style.cursor=i?"crosshair":"");const a=this.contexto.controller.getMap();if(a){const s=a.getContainer();s&&(s.style.cursor=i?"crosshair":"")}this.contexto.controller.core.config.crosshair=i}if(o.opacidadeBase!==void 0){const i=parseFloat(o.opacidadeBase);isNaN(i)||this.contexto.setLayerOpacity("satelite",i)}if(o.satOpacity!==void 0){const i=parseFloat(o.satOpacity);isNaN(i)||this.contexto.setLayerOpacity("satelite",i)}o.opacidades&&typeof o.opacidades=="object"&&Object.entries(o.opacidades).forEach(([i,a])=>{const s=parseFloat(a);isNaN(s)||this.contexto.setLayerOpacity(i,s)}),this.contexto.host.dispatchEvent(new CustomEvent("ui-config-aplicada",{detail:{tipo:e,configuracoes:o},bubbles:!0,composed:!0}))}desconectar(){if(this.canal){try{this.canal.close()}catch{}this.canal=null}}}class Gn{constructor(t){p(this,"contexto");p(this,"uiListeners",new ve.ListenerBag);p(this,"isLayersPanelOpen",!1);p(this,"mouseMovedSinceDown",!1);p(this,"mouseDownPos",{x:0,y:0});this.contexto=t}get estaPainelAberto(){return this.isLayersPanelOpen}get houveMovimentoMouse(){return this.mouseMovedSinceDown}toggleLayersPanel(){this.isLayersPanelOpen=!this.isLayersPanelOpen,this.contexto.layersPanel&&(this.isLayersPanelOpen?this.contexto.layersPanel.classList.remove("collapsed"):this.contexto.layersPanel.classList.add("collapsed"));const t=this.contexto.shadow.getElementById("btn-toggle-layers");t==null||t.classList.toggle("active",this.isLayersPanelOpen)}closeLayersPanel(){var e;this.isLayersPanelOpen=!1,(e=this.contexto.layersPanel)==null||e.classList.add("collapsed");const t=this.contexto.shadow.getElementById("btn-toggle-layers");t==null||t.classList.remove("active")}vincularEventos(){this.uiListeners.cleanup();const t=this.contexto.shadow.getElementById("btn-toggle-layers"),e=this.contexto.shadow.getElementById("btn-close-layers"),o=this.contexto.shadow.getElementById("btn-zoom-extents"),i=this.contexto.shadow.getElementById("btn-clear-selection"),a=this.contexto.shadow.getElementById("btn-toggle-snap");this.uiListeners.add(t,"click",()=>{this.contexto.onToggleCamadas?this.contexto.onToggleCamadas():this.toggleLayersPanel()}),this.uiListeners.add(e,"click",()=>{this.contexto.onCloseCamadas?this.contexto.onCloseCamadas():this.closeLayersPanel()}),this.uiListeners.add(o,"click",()=>{var s,r;(r=(s=this.contexto).onZoomExtents)==null||r.call(s)}),this.uiListeners.add(i,"click",()=>{var s,r;(r=(s=this.contexto).onLimparSelecao)==null||r.call(s)}),this.uiListeners.add(a,"click",()=>{var s,r;(r=(s=this.contexto).onToggleSnap)==null||r.call(s)}),this.contexto.mapContainer&&(this.uiListeners.add(this.contexto.mapContainer,"mousedown",s=>{s.button===0&&(this.mouseDownPos={x:s.clientX,y:s.clientY},this.mouseMovedSinceDown=!1)}),this.uiListeners.add(this.contexto.mapContainer,"mousemove",s=>{Math.hypot(s.clientX-this.mouseDownPos.x,s.clientY-this.mouseDownPos.y)>=4&&(this.mouseMovedSinceDown=!0)}),this.uiListeners.add(this.contexto.mapContainer,"click",s=>{var r,c;s.button===0&&(this.mouseMovedSinceDown||(c=(r=this.contexto).onTratarCliqueCanvas)==null||c.call(r,s))})),this.uiListeners.add(this.contexto.shadow,"click",s=>{var l,d,h;const r=s.composedPath?s.composedPath()[0]:s.target,c=(l=r==null?void 0:r.closest)==null?void 0:l.call(r,".ui-popup-btn");if(c){s.preventDefault(),s.stopPropagation();const u=c.getAttribute("data-acao-id"),m=c.getAttribute("data-elemento-id");u&&m!==null&&((h=(d=this.contexto).onDispararAcaoPopup)==null||h.call(d,u,m))}})}limpar(){this.uiListeners.cleanup()}}class jn{constructor(t){p(this,"contexto");p(this,"_pontos",[]);p(this,"_segmentos",[]);p(this,"_bancoPontos",[]);p(this,"_confrontantes",[]);p(this,"customMarkerClickHandler");this.contexto=t}get pontos(){return this._pontos}set pontos(t){this._pontos=t||[],this.contexto.obterController().setPontos(this._pontos)}get segmentos(){return this._segmentos}set segmentos(t){this._segmentos=t||[],this.contexto.obterController().setSegmentos(this._segmentos)}get bancoPontos(){return this._bancoPontos}set bancoPontos(t){this._bancoPontos=t||[],this.contexto.obterController().setBancoPontos(this._bancoPontos)}get confrontantes(){return this._confrontantes}set confrontantes(t){this._confrontantes=t||[],this.contexto.obterController().setConfrontantes(this._confrontantes)}sincronizarInicial(){const t=this.contexto.obterController();this._pontos.length>0&&t.setPontos(this._pontos),this._segmentos.length>0&&t.setSegmentos(this._segmentos),this._bancoPontos.length>0&&t.setBancoPontos(this._bancoPontos),this._confrontantes.length>0&&t.setConfrontantes(this._confrontantes)}obterElementoPorId(t){return this._pontos.find(e=>String(e.id)===String(t))||this._bancoPontos.find(e=>String(e.id)===String(t))||this._confrontantes.find(e=>String(e.id)===String(t))}plotarPontos(t,e="vertices",o){const i=t||[];e==="vertices"&&(this._pontos=i),this.contexto.obterController().plotarPontos(i,e,o)}plotarConexoes(t,e="linhas"){const o=t||[];this.contexto.obterController().plotarConexoes(o,e)}plotarPolilinhaSequencial(t,e=!0,o="polilinha",i){const a=t||[];(o==="polilinha"||o==="perimetro")&&(this._pontos=a,this._segmentos=[]);const s=i??this.contexto.obterChaveGrupo();this.contexto.obterController().plotarPolilinhaSequencial(a,e,o,s)}plotarPoligonos(t,e="poligonos"){const o=t||[];this.contexto.obterController().plotarPoligonos(o,e)}limparCamadas(t){!t||t.length===0?(this._pontos=[],this._segmentos=[],this._confrontantes=[]):(t.includes("vertices")&&(this._pontos=[]),(t.includes("linhas")||t.includes("perimetro")||t.includes("polilinha"))&&(this._segmentos=[]),(t.includes("poligonos")||t.includes("vizinhos"))&&(this._confrontantes=[])),this.contexto.obterController().limparCamadas(t)}obterMarcadores(t){return this.contexto.obterController().obterMarcadores(t)}plotPontos(t,e){e&&(this.customMarkerClickHandler=e);const o=t||[];this._pontos=o,this.contexto.obterController().plotPontos(o,e)}plotSegmentos(t,e){const o=t||[];e!=null&&(this._pontos=e||[]),this._segmentos=o,this.contexto.obterController().plotSegmentos(o,e)}plotPolilinhaTemporaria(t){const e=t||[];this._pontos=e,this._segmentos=[],this.contexto.obterController().plotPolilinhaTemporaria(e)}plotPoligonalHomologada(t){const e=t||[];this._bancoPontos=e,this.contexto.obterController().plotPoligonalHomologada(e),this.contexto.setLayerVisibility("homologados",!0),this.contexto.setLayerVisibility("homologados-pontos",!0)}plotPontosVizinhos(t){const e=t||[],o=this.contexto.obterController();o.plotPontosVizinhos(e),this._confrontantes=o.context.confrontantes||[]}plotPoligonosVizinhos(t){const e=t||[],o=this.contexto.obterController();o.plotPoligonosVizinhos(e),this._confrontantes=o.context.confrontantes||[]}clearOverlays(t=!1){this._pontos=[],this._segmentos=[],this._confrontantes=[],t||(this._bancoPontos=[]),this.contexto.obterController().clearOverlays(t)}getMarkers(){return this.contexto.obterController().getMarkers()}getVizinhosMarkers(){return this.contexto.obterController().getVizinhosMarkers()}}const Un=':host{display:block;width:100%;height:520px;position:relative;border-radius:var(--ui-raio-lg, 10px);overflow:hidden;box-shadow:0 10px 30px -5px #0009;border:1px solid rgba(255,255,255,.1);background:#080d0a;color:#fff;font-family:var(--ui-fonte-base, "Inter", sans-serif);user-select:none;-webkit-user-select:none}*,*:before,*:after{box-sizing:border-box}.cad-root{position:relative;width:100%;height:100%;display:flex;overflow:hidden}.cad-map-container{width:100%;height:100%;background:#080d0a;z-index:1}.qgis-layer-panel{position:absolute;top:12px;left:12px;z-index:var(--ui-z-workspace-hud, 500);width:290px;max-height:calc(100% - 24px);background:#0a120eeb;backdrop-filter:blur(16px);-webkit-backdrop-filter:blur(16px);border:1px solid rgba(255,255,255,.15);border-radius:8px;box-shadow:0 20px 40px #000000b3;display:flex;flex-direction:column;transition:transform .25s cubic-bezier(.16,1,.3,1),opacity .25s ease;overflow:hidden}.qgis-layer-panel.collapsed{transform:translate(-310px);opacity:0;pointer-events:none}.layer-panel-header{padding:10px 14px;background:#ffffff08;border-bottom:1px solid rgba(255,255,255,.08);display:flex;align-items:center;justify-content:space-between}.layer-panel-title{font-size:12px;font-weight:700;letter-spacing:.5px;color:#00f5a0;display:flex;align-items:center;gap:6px;text-transform:uppercase}.layer-panel-close{background:transparent;border:none;color:#ffffff80;cursor:pointer;padding:2px;border-radius:var(--ui-raio-sm, 4px);display:flex;align-items:center;justify-content:center;transition:all .15s}.layer-panel-close:hover{color:#fff;background:#ffffff1a}.layer-panel-body{padding:8px 10px;overflow-y:auto;display:flex;flex-direction:column;gap:2px;max-height:400px}.layer-panel-body::-webkit-scrollbar{width:5px}.layer-panel-body::-webkit-scrollbar-track{background:transparent}.layer-panel-body::-webkit-scrollbar-thumb{background:#fff3;border-radius:var(--ui-raio-sm, 4px)}.layer-panel-body::-webkit-scrollbar-thumb:hover{background:#00f5a066}.layer-item{background:transparent;border:none;border-bottom:1px solid rgba(255,255,255,.08);border-radius:0;padding:4px;display:flex;flex-direction:column;gap:3px;transition:background .15s ease}.layer-item:last-child{border-bottom:none}.layer-item:hover{background:#ffffff08;border-radius:var(--ui-raio-sm, 4px)}.layer-item-row{display:flex;align-items:center;justify-content:space-between;min-height:18px}.layer-item-label{display:flex;align-items:center;gap:7px;font-size:11px;font-weight:600;line-height:1.2;color:#ffffffe6;cursor:pointer;-webkit-user-select:none;user-select:none}.layer-chk-visibility{-moz-appearance:none;appearance:none;-webkit-appearance:none;width:14px;height:14px;border:1px solid rgba(255,255,255,.4);border-radius:3px;background:#0006;cursor:pointer;display:inline-flex;align-items:center;justify-content:center;position:relative;transition:all .15s ease;flex-shrink:0;margin:0}.layer-chk-visibility:hover{border-color:#00f5a0}.layer-chk-visibility:checked{background:#00f5a0;border-color:#00f5a0}.layer-chk-visibility:checked:after{content:"";width:3.5px;height:7px;border:solid #04150c;border-width:0 1.5px 1.5px 0;transform:rotate(45deg) translateY(-.5px);display:block}.layer-item-actions{display:flex;align-items:center;gap:4px}.btn-layer-action{background:transparent;border:none;color:#fff6;cursor:pointer;padding:2px;border-radius:3px;display:flex;align-items:center;justify-content:center;transition:all .15s}.btn-layer-action:hover{color:#00f5a0;background:#ffffff14}.btn-layer-action.active{color:#f43f5e;background:#f43f5e26}.layer-controls-row{display:flex;align-items:center;justify-content:space-between;gap:8px;font-size:9.5px;line-height:1;color:#ffffff80;padding-left:21px}.layer-opacity-slider{flex:1;height:3px;margin:0;border-radius:2px;background:#ffffff26;accent-color:#00f5a0;cursor:pointer}.scale-mode-pill{font-size:8.5px;font-weight:600;padding:1px 6px;border-radius:6px;background:#ffffff0f;color:#ffffffb3;cursor:pointer;border:1px solid rgba(255,255,255,.1);transition:all .15s;line-height:1.2}.scale-mode-pill:hover{border-color:#00f5a0;color:#00f5a0;background:#00f5a01a}:host([sem-painel-camadas]) .qgis-layer-panel,:host([sem-painel-camadas]) #btn-toggle-layers,:host([sem-barra-rapida]) .cad-quick-toolbar{display:none!important}.cad-quick-toolbar{position:absolute;top:12px;right:12px;z-index:var(--ui-z-workspace-hud, 500);display:flex;flex-direction:column;gap:6px;background:#0c1510eb;backdrop-filter:blur(14px);-webkit-backdrop-filter:blur(14px);border:1px solid rgba(255,255,255,.15);border-radius:8px;padding:5px;box-shadow:0 10px 25px -5px #0009}.cad-btn-tool{background:transparent;border:none;color:#fff9;cursor:pointer;padding:7px;border-radius:5px;display:flex;align-items:center;justify-content:center;transition:all .15s}.cad-btn-tool:hover{background:#ffffff1a;color:#fff}.cad-btn-tool.active{background:#00f5a026;color:#00f5a0;border:1px solid rgba(0,245,160,.3)}.cad-selection-box{pointer-events:none;box-sizing:border-box}.custom-leaflet-marker{cursor:pointer}.custom-leaflet-marker:hover{z-index:1800!important}.custom-leaflet-marker .cad-pt svg{transition:transform .12s ease-out}.custom-leaflet-marker:hover .cad-pt svg{transform:scale(1.3)}.leaflet-popup-content-wrapper{background:#0f1712!important;color:#f8fafc!important;border:1px solid rgba(255,255,255,.15)!important;border-radius:8px!important;box-shadow:0 10px 25px #0009!important;padding:0!important;backdrop-filter:blur(16px)!important;-webkit-backdrop-filter:blur(16px)!important}.leaflet-popup-tip{background:#0f1712!important;border:1px solid rgba(255,255,255,.15)!important;box-shadow:none!important}.leaflet-popup-close-button{color:#fff9!important;padding:6px!important;transition:color .15s ease}.leaflet-popup-close-button:hover{color:#fff!important}.leaflet-popup-content{margin:12px 14px!important;line-height:1.4;font-family:inherit;color:#f8fafc}.compact-popup .leaflet-popup-content{margin:10px 12px!important}.ui-popup-actions-footer{display:flex;gap:6px;margin-top:8px;padding-top:8px;border-top:1px solid rgba(255,255,255,.1);justify-content:flex-end;align-items:center;flex-wrap:wrap}.ui-popup-btn{display:inline-flex;align-items:center;justify-content:center;font-family:inherit;font-size:11px;font-weight:500;padding:4px 9px;border-radius:var(--ui-raio-borda, 6px);cursor:pointer;transition:all .15s ease;border:1px solid transparent;outline:none;line-height:1.25;-webkit-user-select:none;user-select:none}.ui-popup-btn-primary{background:var(--ui-cor-primaria, #00f5a0);color:#080d0a;font-weight:600;border-color:var(--ui-cor-primaria, #00f5a0)}.ui-popup-btn-primary:hover{filter:brightness(1.1);box-shadow:0 0 10px #00f5a059}.ui-popup-btn-secondary{background:#ffffff14;color:#fff;border-color:#ffffff2e}.ui-popup-btn-secondary:hover{background:#ffffff29;border-color:#ffffff4d}.ui-popup-btn-destrutivo{background:#ef444426;color:#f87171;border-color:#ef444459}.ui-popup-btn-destrutivo:hover{background:#ef444440;border-color:#ef444499;color:#fff}@media (max-width: 520px){.qgis-layer-panel{top:8px;left:8px;right:8px;width:auto;max-height:calc(100% - 16px)}.qgis-layer-panel.collapsed{transform:translateY(-115%)}.layer-panel-close{min-width:36px;min-height:36px;font-size:16px}.layer-action-btn{min-width:32px;min-height:32px}}.cad-destaque-marker-container{pointer-events:none!important;background:transparent!important;border:none!important;overflow:visible!important}.cad-destaque-marker-container *{pointer-events:none!important}.cad-pulse-highlight{position:relative;width:52px;height:52px;display:flex;align-items:center;justify-content:center;pointer-events:none!important;user-select:none;-webkit-user-select:none}.cad-pulse-core{position:absolute;width:12px;height:12px;border-radius:50%;background-color:var(--cad-pulse-cor, #00f5a0);border:2px solid #ffffff;box-sizing:border-box;pointer-events:none!important}.cad-pulse-ring{position:absolute;width:100%;height:100%;border-radius:50%;border:2px solid var(--cad-pulse-cor, #00f5a0);background-color:color-mix(in srgb,var(--cad-pulse-cor, #00f5a0) 14%,transparent);box-sizing:border-box;pointer-events:none!important;opacity:0;animation:cad-pulse-ping 1.8s cubic-bezier(0,0,.2,1) infinite}.cad-pulse-ring.ring-2{animation-delay:.9s}@keyframes cad-pulse-ping{0%{transform:scale(.3);opacity:.9}70%{opacity:.35}to{transform:scale(1);opacity:0}}@media (prefers-reduced-motion: reduce){.cad-pulse-ring{animation:none;opacity:.6;transform:scale(.6)}}.cad-marker-selected,.ponto-selecionado{z-index:2000!important}@media (prefers-reduced-motion: reduce){.custom-leaflet-marker .cad-pt svg{transition:none}}.ui-popup-actions-footer{margin-top:8px;padding-top:6px;border-top:1px solid rgba(255,255,255,.12);display:flex;gap:6px;flex-wrap:wrap}.ui-popup-btn{display:inline-flex;align-items:center;justify-content:center;padding:4px 8px;font-size:11px;font-weight:600;border-radius:var(--ui-raio-sm, 4px);border:1px solid rgba(255,255,255,.15);background:#ffffff14;color:#fff;cursor:pointer;line-height:1.2;transition:all .15s ease;-webkit-user-select:none;user-select:none}.ui-popup-btn:hover{background:#ffffff2e;border-color:#ffffff4d}.ui-popup-btn-primary{background:#00f5a0;color:#06130b;border-color:#00f5a0}.ui-popup-btn-primary:hover{background:#10ffad;box-shadow:0 0 8px #00f5a066}.ui-popup-btn-danger{background:#f43f5e33;color:#f43f5e;border-color:#f43f5e66}.ui-popup-btn-danger:hover{background:#f43f5e59;color:#fff}.cad-draw-toolbar{right:auto;left:12px;max-height:calc(100% - 24px);overflow-y:auto}.cad-draw-btn{font:600 11px var(--ui-fonte-base, sans-serif);padding:5px 9px;white-space:nowrap;justify-content:flex-start}.cad-ferramenta-ativa .leaflet-marker-icon{pointer-events:none!important}';function Wn(){return`
131
+ `,e.cleanup(),a.querySelectorAll(".layer-chk-visibility").forEach(n=>{e.add(n,"change",s=>{const r=s.target.getAttribute("data-layer-id"),c=s.target.checked;r&&o.setLayerVisibility(r,c)})}),a.querySelectorAll(".layer-opacity-slider").forEach(n=>{e.add(n,"input",s=>{const r=s.target.getAttribute("data-layer-id"),c=parseInt(s.target.value,10),l=c/100,d=s.target.closest(".layer-item"),h=d==null?void 0:d.querySelector(".opacity-percent-label");h&&(h.textContent=`${c}%`),r&&o.setLayerOpacity(r,l)})}),a.querySelectorAll(".btn-lock-layer").forEach(n=>{e.add(n,"click",s=>{const r=s.currentTarget.getAttribute("data-layer-id");if(r){const c=t.find(l=>l.id===r);c&&o.setLayerBlocked(r,!c.bloqueada)}})}),a.querySelectorAll(".btn-toggle-scale-mode").forEach(n=>{e.add(n,"click",s=>{var c;const r=s.currentTarget.getAttribute("data-layer-id");if(r){const l=t.find(d=>d.id===r);if(l){const d=((c=l.estilo)==null?void 0:c.scaleMode)==="world"?"screen":"world";o.setLayerScaleMode(r,d)}}})})}function fi(a,t,e,o){var x,E,M,A,C,b;if(a.modoSequencial||a.controller.canvasInteracao.selectionHappened||a.controller.canvasInteracao.panHappened||a.mouseMovedSinceDown)return!1;const i=(t==null?void 0:t.originalEvent)||t,n=typeof(i==null?void 0:i.composedPath)=="function"?i.composedPath():[],s=n.length>0?n[0]:(i==null?void 0:i.target)||(t==null?void 0:t.target);if(s){const v='.custom-leaflet-marker, .leaflet-marker-icon, .leaflet-interactive, .compact-popup, .leaflet-popup, .ui-popup-btn, .cad-btn-tool, .qgis-layer-panel, [class*="leaflet-marker"], [class*="leaflet-popup"]';if(((x=s.matches)==null?void 0:x.call(s,v))||((E=s.closest)==null?void 0:E.call(s,v)))return!1}const r=a.controller.getMap();if(!r||!a.mapContainer)return!1;let c,l;if(o)c=Math.round(o.x),l=Math.round(o.y);else if(t!=null&&t.containerPoint||t!=null&&t.layerPoint)c=Math.round(((M=t.containerPoint)==null?void 0:M.x)??((A=t.layerPoint)==null?void 0:A.x)??0),l=Math.round(((C=t.containerPoint)==null?void 0:C.y)??((b=t.layerPoint)==null?void 0:b.y)??0);else{const v=a.mapContainer.getBoundingClientRect(),P=(i==null?void 0:i.clientX)??0,w=(i==null?void 0:i.clientY)??0;c=Math.round(P-v.left),l=Math.round(w-v.top)}const d={x:c,y:l};let h,u;const g=e||(t==null?void 0:t.latlng);if(g&&typeof g.lat=="number")h=g.lat,u=g.lng??g.lon??0;else{const v=r.containerPointToLatLng(y.point(d.x,d.y));h=v.lat,u=v.lng}const m=a.controller.layerManager?a.controller.layerManager.getLayers().filter(v=>v.visivel).map(v=>v.id):[],f=i;return a.host.dispatchEvent(new CustomEvent("ui-canvas-clique",{detail:{coordenadas:{lat:h,lng:u},pontoPixel:d,eventoOriginal:f,lat:h,lon:u,lng:u,camadasAtivas:m},bubbles:!0,composed:!0})),!0}function mi(a,t,e,o){const i=o||a.obterElementoPorId(e);a.host.dispatchEvent(new CustomEvent("ui-acao-popup",{detail:{acaoId:t,elementoId:e,elemento:i??{id:e}},bubbles:!0,composed:!0})),a.fecharPopup()}function gi(a,t,e,o,i,n,s){let r=o||a.obterElementoPorId(t),c=i;if(!c&&r){const l=r.lat??r.latitude??0,d=r.lon??r.lng??r.longitude??0;c={lat:Number(l),lon:Number(d)}}if(c||(c={lat:0,lon:0}),a.modoSequencial){a.fecharPopup(),a.host.dispatchEvent(new CustomEvent("ui-clique-sequencial",{detail:{id:t,elemento:r??{id:t,lat:c.lat,lon:c.lon},coordenadas:c},bubbles:!0,composed:!0}));return}if(s)try{const l=t!=null&&!isNaN(Number(t))&&String(t).trim()!==""?Number(t):t;s(l,e)}catch(l){console.error("Erro no callback de clique de marcador:",l)}if(n)try{n(t,e,r,c)}catch(l){console.error("Erro no handler anterior de marker click:",l)}a.controller.context.selectedSegmentoId&&a.controller.selectSegmento(null),a.host.dispatchEvent(new CustomEvent("ui-ponto-selecionado",{detail:{selectedIds:[t],lastSelectedId:t,isVizinho:e},bubbles:!0,composed:!0})),a.host.dispatchEvent(new CustomEvent("ui-elemento-selecionado",{detail:{id:t,elemento:r,tipo:e?"vizinho":"vertice",coordenadas:c},bubbles:!0,composed:!0}))}function vi(a,t,e,o,i){if(a.modoSequencial){a.fecharPopup();return}if(a.controller.canvasInteracao.ctx.selectedPontoIds=[],a.controller.canvasInteracao.ctx.selectedVizinhoPontoIds=[],a.controller.canvasInteracao.ctx.lastSelectedPontoId=null,a.controller.context.selectedPontoIds=[],a.controller.atualizarDestaqueMarcadores(),a.controller.selectSegmento(t),i)try{i(t,e)}catch(n){console.error("Erro no callback de clique de segmento:",n)}a.host.dispatchEvent(new CustomEvent("ui-segmento-selecionado",{detail:{segmentoId:t,segmento:e,pontoInicioId:e==null?void 0:e.ponto_inicio_id,pontoFimId:e==null?void 0:e.ponto_fim_id,coordenadas:o},bubbles:!0,composed:!0})),a.host.dispatchEvent(new CustomEvent("ui-elemento-selecionado",{detail:{id:t,elemento:e,tipo:"segmento",coordenadas:o},bubbles:!0,composed:!0}))}function yi(a,t){let e=null,o=null,i=0,n=0;function s(){var d;try{if(!a.isConnected)return;const h=t.getMap();if(!h)return;const u=(d=h.getContainer)==null?void 0:d.call(h);if(!u||!u.parentNode)return;t.invalidateSize()}catch{}}function r(d=25){o!==null&&(window.clearTimeout(o),o=null),o=window.setTimeout(()=>{o=null,s()},d)}function c(){l(),!(typeof ResizeObserver>"u")&&(e=new ResizeObserver(d=>{for(const h of d){let u=0,g=0;h.contentRect?(u=h.contentRect.width,g=h.contentRect.height):h.borderBoxSize&&h.borderBoxSize.length>0?(u=h.borderBoxSize[0].inlineSize,g=h.borderBoxSize[0].blockSize):(u=a.clientWidth||a.offsetWidth,g=a.clientHeight||a.offsetHeight),u>0&&g>0&&(Math.abs(u-i)>=.5||Math.abs(g-n)>=.5)&&(i=u,n=g,r(25))}}),e.observe(a))}function l(){e&&(e.disconnect(),e=null),o!==null&&(window.clearTimeout(o),o=null)}return{observe:c,disconnect:l,invalidateSizeSafely:s}}class ja{constructor(t){p(this,"canal",null);p(this,"contexto");this.contexto=t}conectar(t){this.desconectar();const e=t!==void 0?t:this.contexto.host.getAttribute("canal-configuracao");if(!(!e||typeof BroadcastChannel>"u"))try{this.canal=new BroadcastChannel(e),this.canal.onmessage=o=>{this.processarMensagem(o.data)}}catch(o){console.warn(`[ui-canvas-cad] Erro ao conectar ao BroadcastChannel "${e}":`,o)}}processarMensagem(t){if(!t||typeof t!="object")return;const e=t.tipo||"ESTILOS_ALTERADOS",o=t.configuracoes||t;if(o.crosshair!==void 0){const i=!!o.crosshair;this.contexto.mapContainer&&(this.contexto.mapContainer.style.cursor=i?"crosshair":"");const n=this.contexto.controller.getMap();if(n){const s=n.getContainer();s&&(s.style.cursor=i?"crosshair":"")}this.contexto.controller.core.config.crosshair=i}if(o.opacidadeBase!==void 0){const i=parseFloat(o.opacidadeBase);isNaN(i)||this.contexto.setLayerOpacity("satelite",i)}if(o.satOpacity!==void 0){const i=parseFloat(o.satOpacity);isNaN(i)||this.contexto.setLayerOpacity("satelite",i)}o.opacidades&&typeof o.opacidades=="object"&&Object.entries(o.opacidades).forEach(([i,n])=>{const s=parseFloat(n);isNaN(s)||this.contexto.setLayerOpacity(i,s)}),this.contexto.host.dispatchEvent(new CustomEvent("ui-config-aplicada",{detail:{tipo:e,configuracoes:o},bubbles:!0,composed:!0}))}desconectar(){if(this.canal){try{this.canal.close()}catch{}this.canal=null}}}class Ua{constructor(t){p(this,"contexto");p(this,"uiListeners",new Le.ListenerBag);p(this,"isLayersPanelOpen",!1);p(this,"mouseMovedSinceDown",!1);p(this,"mouseDownPos",{x:0,y:0});this.contexto=t}get estaPainelAberto(){return this.isLayersPanelOpen}get houveMovimentoMouse(){return this.mouseMovedSinceDown}toggleLayersPanel(){this.isLayersPanelOpen=!this.isLayersPanelOpen,this.contexto.layersPanel&&(this.isLayersPanelOpen?this.contexto.layersPanel.classList.remove("collapsed"):this.contexto.layersPanel.classList.add("collapsed"));const t=this.contexto.shadow.getElementById("btn-toggle-layers");t==null||t.classList.toggle("active",this.isLayersPanelOpen)}closeLayersPanel(){var e;this.isLayersPanelOpen=!1,(e=this.contexto.layersPanel)==null||e.classList.add("collapsed");const t=this.contexto.shadow.getElementById("btn-toggle-layers");t==null||t.classList.remove("active")}vincularEventos(){this.uiListeners.cleanup();const t=this.contexto.shadow.getElementById("btn-toggle-layers"),e=this.contexto.shadow.getElementById("btn-close-layers"),o=this.contexto.shadow.getElementById("btn-zoom-extents"),i=this.contexto.shadow.getElementById("btn-clear-selection"),n=this.contexto.shadow.getElementById("btn-toggle-snap");this.uiListeners.add(t,"click",()=>{this.contexto.onToggleCamadas?this.contexto.onToggleCamadas():this.toggleLayersPanel()}),this.uiListeners.add(e,"click",()=>{this.contexto.onCloseCamadas?this.contexto.onCloseCamadas():this.closeLayersPanel()}),this.uiListeners.add(o,"click",()=>{var s,r;(r=(s=this.contexto).onZoomExtents)==null||r.call(s)}),this.uiListeners.add(i,"click",()=>{var s,r;(r=(s=this.contexto).onLimparSelecao)==null||r.call(s)}),this.uiListeners.add(n,"click",()=>{var s,r;(r=(s=this.contexto).onToggleSnap)==null||r.call(s)}),this.contexto.mapContainer&&(this.uiListeners.add(this.contexto.mapContainer,"mousedown",s=>{s.button===0&&(this.mouseDownPos={x:s.clientX,y:s.clientY},this.mouseMovedSinceDown=!1)}),this.uiListeners.add(this.contexto.mapContainer,"mousemove",s=>{Math.hypot(s.clientX-this.mouseDownPos.x,s.clientY-this.mouseDownPos.y)>=4&&(this.mouseMovedSinceDown=!0)}),this.uiListeners.add(this.contexto.mapContainer,"click",s=>{var r,c;s.button===0&&(this.mouseMovedSinceDown||(c=(r=this.contexto).onTratarCliqueCanvas)==null||c.call(r,s))})),this.uiListeners.add(this.contexto.shadow,"click",s=>{var l,d,h;const r=s.composedPath?s.composedPath()[0]:s.target,c=(l=r==null?void 0:r.closest)==null?void 0:l.call(r,".ui-popup-btn");if(c){s.preventDefault(),s.stopPropagation();const u=c.getAttribute("data-acao-id"),g=c.getAttribute("data-elemento-id");u&&g!==null&&((h=(d=this.contexto).onDispararAcaoPopup)==null||h.call(d,u,g))}})}limpar(){this.uiListeners.cleanup()}}class Wa{constructor(t){p(this,"contexto");p(this,"_pontos",[]);p(this,"_segmentos",[]);p(this,"_bancoPontos",[]);p(this,"_confrontantes",[]);p(this,"customMarkerClickHandler");this.contexto=t}get pontos(){return this._pontos}set pontos(t){this._pontos=t||[],this.contexto.obterController().setPontos(this._pontos)}get segmentos(){return this._segmentos}set segmentos(t){this._segmentos=t||[],this.contexto.obterController().setSegmentos(this._segmentos)}get bancoPontos(){return this._bancoPontos}set bancoPontos(t){this._bancoPontos=t||[],this.contexto.obterController().setBancoPontos(this._bancoPontos)}get confrontantes(){return this._confrontantes}set confrontantes(t){this._confrontantes=t||[],this.contexto.obterController().setConfrontantes(this._confrontantes)}sincronizarInicial(){const t=this.contexto.obterController();this._pontos.length>0&&t.setPontos(this._pontos),this._segmentos.length>0&&t.setSegmentos(this._segmentos),this._bancoPontos.length>0&&t.setBancoPontos(this._bancoPontos),this._confrontantes.length>0&&t.setConfrontantes(this._confrontantes)}obterElementoPorId(t){return this._pontos.find(e=>String(e.id)===String(t))||this._bancoPontos.find(e=>String(e.id)===String(t))||this._confrontantes.find(e=>String(e.id)===String(t))}plotarPontos(t,e="vertices",o){const i=t||[];e==="vertices"&&(this._pontos=i),this.contexto.obterController().plotarPontos(i,e,o)}plotarConexoes(t,e="linhas"){const o=t||[];this.contexto.obterController().plotarConexoes(o,e)}plotarPolilinhaSequencial(t,e=!0,o="polilinha",i){const n=t||[];(o==="polilinha"||o==="perimetro")&&(this._pontos=n,this._segmentos=[]);const s=i??this.contexto.obterChaveGrupo();this.contexto.obterController().plotarPolilinhaSequencial(n,e,o,s)}plotarPoligonos(t,e="poligonos"){const o=t||[];this.contexto.obterController().plotarPoligonos(o,e)}limparCamadas(t){!t||t.length===0?(this._pontos=[],this._segmentos=[],this._confrontantes=[]):(t.includes("vertices")&&(this._pontos=[]),(t.includes("linhas")||t.includes("perimetro")||t.includes("polilinha"))&&(this._segmentos=[]),(t.includes("poligonos")||t.includes("vizinhos"))&&(this._confrontantes=[])),this.contexto.obterController().limparCamadas(t)}obterMarcadores(t){return this.contexto.obterController().obterMarcadores(t)}plotPontos(t,e){e&&(this.customMarkerClickHandler=e);const o=t||[];this._pontos=o,this.contexto.obterController().plotPontos(o,e)}plotSegmentos(t,e){const o=t||[];e!=null&&(this._pontos=e||[]),this._segmentos=o,this.contexto.obterController().plotSegmentos(o,e)}plotPolilinhaTemporaria(t){const e=t||[];this._pontos=e,this._segmentos=[],this.contexto.obterController().plotPolilinhaTemporaria(e)}plotPoligonalHomologada(t){const e=t||[];this._bancoPontos=e,this.contexto.obterController().plotPoligonalHomologada(e),this.contexto.setLayerVisibility("homologados",!0),this.contexto.setLayerVisibility("homologados-pontos",!0)}plotPontosVizinhos(t){const e=t||[],o=this.contexto.obterController();o.plotPontosVizinhos(e),this._confrontantes=o.context.confrontantes||[]}plotPoligonosVizinhos(t){const e=t||[],o=this.contexto.obterController();o.plotPoligonosVizinhos(e),this._confrontantes=o.context.confrontantes||[]}clearOverlays(t=!1){this._pontos=[],this._segmentos=[],this._confrontantes=[],t||(this._bancoPontos=[]),this.contexto.obterController().clearOverlays(t)}getMarkers(){return this.contexto.obterController().getMarkers()}getVizinhosMarkers(){return this.contexto.obterController().getVizinhosMarkers()}}const Xa=':host{display:block;width:100%;height:520px;position:relative;border-radius:var(--ui-raio-lg, 10px);overflow:hidden;box-shadow:0 10px 30px -5px #0009;border:1px solid rgba(255,255,255,.1);background:#080d0a;color:#fff;font-family:var(--ui-fonte-base, "Inter", sans-serif);user-select:none;-webkit-user-select:none}*,*:before,*:after{box-sizing:border-box}.cad-root{position:relative;width:100%;height:100%;display:flex;overflow:hidden}.cad-map-container{width:100%;height:100%;background:#080d0a;z-index:1}.qgis-layer-panel{position:absolute;top:12px;left:12px;z-index:var(--ui-z-workspace-hud, 500);width:290px;max-height:calc(100% - 24px);background:#0a120eeb;backdrop-filter:blur(16px);-webkit-backdrop-filter:blur(16px);border:1px solid rgba(255,255,255,.15);border-radius:8px;box-shadow:0 20px 40px #000000b3;display:flex;flex-direction:column;transition:transform .25s cubic-bezier(.16,1,.3,1),opacity .25s ease;overflow:hidden}.qgis-layer-panel.collapsed{transform:translate(-310px);opacity:0;pointer-events:none}.layer-panel-header{padding:10px 14px;background:#ffffff08;border-bottom:1px solid rgba(255,255,255,.08);display:flex;align-items:center;justify-content:space-between}.layer-panel-title{font-size:12px;font-weight:700;letter-spacing:.5px;color:#00f5a0;display:flex;align-items:center;gap:6px;text-transform:uppercase}.layer-panel-close{background:transparent;border:none;color:#ffffff80;cursor:pointer;padding:2px;border-radius:var(--ui-raio-sm, 4px);display:flex;align-items:center;justify-content:center;transition:all .15s}.layer-panel-close:hover{color:#fff;background:#ffffff1a}.layer-panel-body{padding:8px 10px;overflow-y:auto;display:flex;flex-direction:column;gap:2px;max-height:400px}.layer-panel-body::-webkit-scrollbar{width:5px}.layer-panel-body::-webkit-scrollbar-track{background:transparent}.layer-panel-body::-webkit-scrollbar-thumb{background:#fff3;border-radius:var(--ui-raio-sm, 4px)}.layer-panel-body::-webkit-scrollbar-thumb:hover{background:#00f5a066}.layer-item{background:transparent;border:none;border-bottom:1px solid rgba(255,255,255,.08);border-radius:0;padding:4px;display:flex;flex-direction:column;gap:3px;transition:background .15s ease}.layer-item:last-child{border-bottom:none}.layer-item:hover{background:#ffffff08;border-radius:var(--ui-raio-sm, 4px)}.layer-item-row{display:flex;align-items:center;justify-content:space-between;min-height:18px}.layer-item-label{display:flex;align-items:center;gap:7px;font-size:11px;font-weight:600;line-height:1.2;color:#ffffffe6;cursor:pointer;-webkit-user-select:none;user-select:none}.layer-chk-visibility{-moz-appearance:none;appearance:none;-webkit-appearance:none;width:14px;height:14px;border:1px solid rgba(255,255,255,.4);border-radius:3px;background:#0006;cursor:pointer;display:inline-flex;align-items:center;justify-content:center;position:relative;transition:all .15s ease;flex-shrink:0;margin:0}.layer-chk-visibility:hover{border-color:#00f5a0}.layer-chk-visibility:checked{background:#00f5a0;border-color:#00f5a0}.layer-chk-visibility:checked:after{content:"";width:3.5px;height:7px;border:solid #04150c;border-width:0 1.5px 1.5px 0;transform:rotate(45deg) translateY(-.5px);display:block}.layer-item-actions{display:flex;align-items:center;gap:4px}.btn-layer-action{background:transparent;border:none;color:#fff6;cursor:pointer;padding:2px;border-radius:3px;display:flex;align-items:center;justify-content:center;transition:all .15s}.btn-layer-action:hover{color:#00f5a0;background:#ffffff14}.btn-layer-action.active{color:#f43f5e;background:#f43f5e26}.layer-controls-row{display:flex;align-items:center;justify-content:space-between;gap:8px;font-size:9.5px;line-height:1;color:#ffffff80;padding-left:21px}.layer-opacity-slider{flex:1;height:3px;margin:0;border-radius:2px;background:#ffffff26;accent-color:#00f5a0;cursor:pointer}.scale-mode-pill{font-size:8.5px;font-weight:600;padding:1px 6px;border-radius:6px;background:#ffffff0f;color:#ffffffb3;cursor:pointer;border:1px solid rgba(255,255,255,.1);transition:all .15s;line-height:1.2}.scale-mode-pill:hover{border-color:#00f5a0;color:#00f5a0;background:#00f5a01a}:host([sem-painel-camadas]) .qgis-layer-panel,:host([sem-painel-camadas]) #btn-toggle-layers,:host([sem-barra-rapida]) .cad-quick-toolbar{display:none!important}.cad-quick-toolbar{position:absolute;top:12px;right:12px;z-index:var(--ui-z-workspace-hud, 500);display:flex;flex-direction:column;gap:6px;background:#0c1510eb;backdrop-filter:blur(14px);-webkit-backdrop-filter:blur(14px);border:1px solid rgba(255,255,255,.15);border-radius:8px;padding:5px;box-shadow:0 10px 25px -5px #0009}.cad-btn-tool{background:transparent;border:none;color:#fff9;cursor:pointer;padding:7px;border-radius:5px;display:flex;align-items:center;justify-content:center;transition:all .15s}.cad-btn-tool:hover{background:#ffffff1a;color:#fff}.cad-btn-tool.active{background:#00f5a026;color:#00f5a0;border:1px solid rgba(0,245,160,.3)}.cad-selection-box{pointer-events:none;box-sizing:border-box}.custom-leaflet-marker{cursor:pointer}.custom-leaflet-marker:hover{z-index:1800!important}.custom-leaflet-marker .cad-pt svg{transition:transform .12s ease-out}.custom-leaflet-marker:hover .cad-pt svg{transform:scale(1.3)}.leaflet-popup-content-wrapper{background:#0f1712!important;color:#f8fafc!important;border:1px solid rgba(255,255,255,.15)!important;border-radius:8px!important;box-shadow:0 10px 25px #0009!important;padding:0!important;backdrop-filter:blur(16px)!important;-webkit-backdrop-filter:blur(16px)!important}.leaflet-popup-tip{background:#0f1712!important;border:1px solid rgba(255,255,255,.15)!important;box-shadow:none!important}.leaflet-popup-close-button{color:#fff9!important;padding:6px!important;transition:color .15s ease}.leaflet-popup-close-button:hover{color:#fff!important}.leaflet-popup-content{margin:12px 14px!important;line-height:1.4;font-family:inherit;color:#f8fafc}.compact-popup .leaflet-popup-content{margin:10px 12px!important}.ui-popup-actions-footer{display:flex;gap:6px;margin-top:8px;padding-top:8px;border-top:1px solid rgba(255,255,255,.1);justify-content:flex-end;align-items:center;flex-wrap:wrap}.ui-popup-btn{display:inline-flex;align-items:center;justify-content:center;font-family:inherit;font-size:11px;font-weight:500;padding:4px 9px;border-radius:var(--ui-raio-borda, 6px);cursor:pointer;transition:all .15s ease;border:1px solid transparent;outline:none;line-height:1.25;-webkit-user-select:none;user-select:none}.ui-popup-btn-primary{background:var(--ui-cor-primaria, #00f5a0);color:#080d0a;font-weight:600;border-color:var(--ui-cor-primaria, #00f5a0)}.ui-popup-btn-primary:hover{filter:brightness(1.1);box-shadow:0 0 10px #00f5a059}.ui-popup-btn-secondary{background:#ffffff14;color:#fff;border-color:#ffffff2e}.ui-popup-btn-secondary:hover{background:#ffffff29;border-color:#ffffff4d}.ui-popup-btn-destrutivo{background:#ef444426;color:#f87171;border-color:#ef444459}.ui-popup-btn-destrutivo:hover{background:#ef444440;border-color:#ef444499;color:#fff}@media (max-width: 520px){.qgis-layer-panel{top:8px;left:8px;right:8px;width:auto;max-height:calc(100% - 16px)}.qgis-layer-panel.collapsed{transform:translateY(-115%)}.layer-panel-close{min-width:36px;min-height:36px;font-size:16px}.layer-action-btn{min-width:32px;min-height:32px}}.cad-destaque-marker-container{pointer-events:none!important;background:transparent!important;border:none!important;overflow:visible!important}.cad-destaque-marker-container *{pointer-events:none!important}.cad-pulse-highlight{position:relative;width:52px;height:52px;display:flex;align-items:center;justify-content:center;pointer-events:none!important;user-select:none;-webkit-user-select:none}.cad-pulse-core{position:absolute;width:12px;height:12px;border-radius:50%;background-color:var(--cad-pulse-cor, #00f5a0);border:2px solid #ffffff;box-sizing:border-box;pointer-events:none!important}.cad-pulse-ring{position:absolute;width:100%;height:100%;border-radius:50%;border:2px solid var(--cad-pulse-cor, #00f5a0);background-color:color-mix(in srgb,var(--cad-pulse-cor, #00f5a0) 14%,transparent);box-sizing:border-box;pointer-events:none!important;opacity:0;animation:cad-pulse-ping 1.8s cubic-bezier(0,0,.2,1) infinite}.cad-pulse-ring.ring-2{animation-delay:.9s}@keyframes cad-pulse-ping{0%{transform:scale(.3);opacity:.9}70%{opacity:.35}to{transform:scale(1);opacity:0}}@media (prefers-reduced-motion: reduce){.cad-pulse-ring{animation:none;opacity:.6;transform:scale(.6)}}.cad-marker-selected,.ponto-selecionado{z-index:2000!important}@media (prefers-reduced-motion: reduce){.custom-leaflet-marker .cad-pt svg{transition:none}}.ui-popup-actions-footer{margin-top:8px;padding-top:6px;border-top:1px solid rgba(255,255,255,.12);display:flex;gap:6px;flex-wrap:wrap}.ui-popup-btn{display:inline-flex;align-items:center;justify-content:center;padding:4px 8px;font-size:11px;font-weight:600;border-radius:var(--ui-raio-sm, 4px);border:1px solid rgba(255,255,255,.15);background:#ffffff14;color:#fff;cursor:pointer;line-height:1.2;transition:all .15s ease;-webkit-user-select:none;user-select:none}.ui-popup-btn:hover{background:#ffffff2e;border-color:#ffffff4d}.ui-popup-btn-primary{background:#00f5a0;color:#06130b;border-color:#00f5a0}.ui-popup-btn-primary:hover{background:#10ffad;box-shadow:0 0 8px #00f5a066}.ui-popup-btn-danger{background:#f43f5e33;color:#f43f5e;border-color:#f43f5e66}.ui-popup-btn-danger:hover{background:#f43f5e59;color:#fff}.cad-draw-toolbar{right:auto;left:12px;max-height:calc(100% - 24px);overflow-y:auto}.cad-draw-btn{font:600 11px var(--ui-fonte-base, sans-serif);padding:5px 9px;white-space:nowrap;justify-content:flex-start}.cad-ferramenta-ativa .leaflet-marker-icon{pointer-events:none!important}';function Za(){return`
132
132
  <style>
133
133
  ${S.leafletCss}
134
- ${Un}
134
+ ${Xa}
135
135
  </style>
136
136
  <div class="cad-root" id="cad-root">
137
137
  <div class="cad-map-container" id="cad-map-container"></div>
@@ -162,14 +162,14 @@
162
162
  </button>
163
163
  </div>
164
164
  </div>
165
- `}function Xn(n,t,e,o){if(e!==o){if(t==="sat-opacity"){const i=parseFloat(o);isNaN(i)||n.setLayerOpacity("satelite",i)}else if(t==="scale-mode")(o==="world"||o==="screen")&&(n.setLayerScaleMode("perimetro",o),n.setLayerScaleMode("vertices",o));else if(t==="modo-sequencial")n.host.modoSequencial=o!==null&&o!=="false";else if(t==="chave-grupo")n.host.chaveGrupo=o||void 0;else if(t==="zona-projecao"||t==="fuso"){const i=parseInt(o,10);!isNaN(i)&&i>0&&(n.atualizarZonaProjecao(i),t==="fuso"&&n.host.getAttribute("zona-projecao")!==o?n.host.setAttribute("zona-projecao",o):t==="zona-projecao"&&n.host.hasAttribute("fuso")&&n.host.getAttribute("fuso")!==o&&n.host.setAttribute("fuso",o),n.controller.zonaProjecao=i,n.controller.context.zonaProjecao=i)}else if(t==="canal-configuracao")n.broadcastConfig.conectar(o);else if(t==="crosshair"){const i=o!==null&&o!=="false";n.mapContainer&&(n.mapContainer.style.cursor=i?"crosshair":"");const a=n.controller.getMap();if(a){const s=a.getContainer();s&&(s.style.cursor=i?"crosshair":"")}n.controller.core.config.crosshair=i}}}function Zn(n){if(!n.mapContainer)return;if(n.mapContainer._leaflet_id&&!n.controller.getMap())try{delete n.mapContainer._leaflet_id}catch{n.mapContainer._leaflet_id=void 0}if(n.controller.init(n.mapContainer,n.shadow),n.toolbarPainel.vincularEventos(),n.renderLayersUI(),n.host.hasAttribute("modo-sequencial")&&(n.controller.modoCliqueSequencialAtivo=!0,n.controller.context.modoSequencial=!0),n.host.hasAttribute("chave-grupo")){const o=n.host.getAttribute("chave-grupo");o&&(n.host.chaveGrupo=o)}if(n.host.hasAttribute("zona-projecao")||n.host.hasAttribute("fuso")){const o=n.host.zonaProjecao;n.controller.zonaProjecao=o,n.controller.context.zonaProjecao=o}if(n.host.hasAttribute("crosshair")){const o=n.host.getAttribute("crosshair")!=="false";n.mapContainer&&(n.mapContainer.style.cursor=o?"crosshair":""),n.controller.core.config.crosshair=o}n.colecoesDados.sincronizarInicial(),n.controller.layerManager.onChange(o=>{n.renderLayersUI(),n.host.dispatchEvent(new CustomEvent("ui-camadas-alteradas",{detail:{layers:o},bubbles:!0,composed:!0}))});const t=n.controller.context.onMarkerClick;n.controller.context.onMarkerClick=(o,i,a,s)=>{hi(n.obterContextoEventos(),o,i,a,s,t,n.colecoesDados.customMarkerClickHandler)},n.controller.context.onSegmentoClick=(o,i,a)=>{ui(n.obterContextoEventos(),o,i,a)},n.controller.context.onPopupAcao=(o,i,a)=>{n.dispararAcaoPopup(o,i,a)};const e=n.controller.getMap();e&&e.on("click",o=>{n.toolbarPainel.houveMovimentoMouse||n.tratarCliqueLivreCanvas(o,o.latlng,o.containerPoint)}),setTimeout(()=>{n.invalidateSizeSafely()},150)}function X(n,t){let e,o;if(Array.isArray(n))[e,o]=n;else if(n&&typeof n=="object"){const a=n;e=a.lat??a.latitude,o=a.lng??a.lon??a.longitude}else return null;const i=S.parseCoordenada(e,o,t);return!i||!Number.isFinite(i.lat)||!Number.isFinite(i.lon)?null:[i.lat,i.lon]}function Yn(n,t){return n[0]===t[0]&&n[1]===t[1]}function Re(n,t){const e=n.map(o=>X(o,t)).filter(o=>o!==null);return e.length>1&&Yn(e[0],e[e.length-1])&&e.pop(),e.length>=3?e:null}function Ae(n,t){const e=n.map(o=>X(o,t)).filter(o=>o!==null);return e.length>=2?e:null}function fi(n,t){if(!Array.isArray(n)||n.length===0)return null;const o=(Array.isArray(n[0])&&Array.isArray(n[0][0])?n:[n]).map(i=>Re(i,t));return o.some(i=>i===null)?null:o}function Kn(n,t){const e=S.parseCoordenada(n.lat,n.lon);return e?{id:String(n.id),camadaId:t,geometria:{tipo:"Point",coordenada:[e.lat,e.lon]},propriedades:{...n}}:null}function Jn(n,t,e){const o=t.get(String(n.ponto_inicio_id)),i=t.get(String(n.ponto_fim_id));if(!o||!i)return null;const a=S.parseCoordenada(o.lat,o.lon),s=S.parseCoordenada(i.lat,i.lon);if(!a||!s)return null;const r=(n.tipo_limite_sigef??n.tipo_limite)==="LN1";return{id:String(n.id??`${n.ponto_inicio_id}-${n.ponto_fim_id}`),camadaId:e,geometria:{tipo:"LineString",coordenadas:[[a.lat,a.lon],[s.lat,s.lon]]},estilo:r?{dashArray:"6, 6"}:void 0,propriedades:{...n}}}function Qn(n,t){if(!n.poligono_wkt)return null;const e=/POLYGON\s*\(\s*\(\s*(.*?)\s*\)\s*\)/i.exec(n.poligono_wkt);if(!e)return null;const o=e[1].split(",").map(a=>{const[s,r]=a.trim().split(/\s+/);return[r,s]}),i=Re(o);return i?{id:String(n.id??n.nome??""),camadaId:t,geometria:{tipo:"Polygon",aneis:[i]},propriedades:{nome:n.nome,nome_propriedade:n.nome_propriedade}}:null}function ro(n,t){const e=Pn(n);if(!e)return null;const o=[];for(const i of e){const a=X(i.ponto,t);if(!a)return null;const s={ponto:a},r=i.entrada&&X(i.entrada,{...t,aceitarOrigem:!0}),c=i.saida&&X(i.saida,{...t,aceitarOrigem:!0});r&&(s.entrada=r),c&&(s.saida=c),o.push(s)}return o}const ta=new Set(["Point","LineString","Polygon","Circle","Text"]);function Rt(n,t,e){if(!n||typeof n!="object")return null;const o=n,i=o.geometria;if(!i||!ta.has(i.tipo)||o.id===void 0||o.id===null||o.id==="")return null;let a=null;switch(i.tipo){case"Point":{const r=X(i.coordenada,e);r&&(a={tipo:"Point",coordenada:r});break}case"Text":{const r=X(i.coordenada,e);r&&typeof i.texto=="string"&&i.texto&&(a={tipo:"Text",coordenada:r,texto:i.texto});break}case"LineString":{const r=Array.isArray(i.partes)?i.partes.map(l=>Array.isArray(l)?Ae(l,e):null).filter(l=>l!==null):[];if(r.length>0)a=yt(r);else{const l=Array.isArray(i.coordenadas)?Ae(i.coordenadas,e):null;l&&(a=yt([l]))}const c=r.length<=1?ro(i.curva,e):null;a&&a.tipo==="LineString"&&c&&c.length>=2&&(a={tipo:"LineString",coordenadas:xt(c,!1),curva:c});break}case"Polygon":{const r=Array.isArray(i.aneis)?fi(i.aneis,e):null;r&&(a={tipo:"Polygon",aneis:r});const c=r&&r.length===1?ro(i.curva,e):null;a&&c&&c.length>=3&&(a={tipo:"Polygon",aneis:[xt(c,!0)],curva:c});break}case"Circle":{const r=X(i.centro,e),c=Number(i.raioMetros);r&&Number.isFinite(c)&&c>0&&(a={tipo:"Circle",centro:r,raioMetros:c});break}}if(!a)return null;const s={id:String(o.id),camadaId:t,geometria:a,estilo:o.estilo&&typeof o.estilo=="object"?{...o.estilo}:void 0,propriedades:o.propriedades&&typeof o.propriedades=="object"?{...o.propriedades}:{},bloqueada:!!o.bloqueada,status:"oficial",excluida:!!o.excluida};return o.oculta&&(s.oculta=!0),(typeof o.entidadeId=="string"||typeof o.entidadeId=="number")&&(s.entidadeId=String(o.entidadeId)),s.status=Y({...s,status:o.status}),s}const he="cad-cursores",ea=/^#[0-9a-f]{3,8}$/i,oa="#94a3b8";function Jt(n){return typeof n=="string"&&ea.test(n.trim())?n.trim():oa}const ia='<svg width="18" height="18" viewBox="0 0 24 24" style="display:block;filter:drop-shadow(0 1px 1px rgba(0,0,0,.6))"><path d="M3 2 L3 19 L8 14.5 L11.5 22 L14.5 20.5 L11 13.5 L18 13 Z" fill="currentColor" stroke="#fff" stroke-width="1.2" stroke-linejoin="round"/></svg>';function co(n){const t=document.createElement("div");t.style.cssText=`color:${Jt(n.cor)};position:relative;pointer-events:none`,t.innerHTML=ia;const e=document.createElement("span");return e.textContent=String(n.nome??n.id),e.style.cssText=`position:absolute;left:16px;top:14px;white-space:nowrap;font:600 11px sans-serif;color:#fff;background:${Jt(n.cor)};padding:1px 5px;border-radius:3px;max-width:160px;overflow:hidden;text-overflow:ellipsis`,t.appendChild(e),y.divIcon({className:"custom-leaflet-marker cad-cursor-remoto",iconSize:[18,18],iconAnchor:[3,2],html:t})}class mi{constructor(t){p(this,"marcadores",new Map);this.obterMapa=t}get quantidade(){return this.marcadores.size}atualizar(t,e){const o=this.obterMapa();if(!o||!t||t.id===void 0||t.id===null||t.id===""||!Number.isFinite(e==null?void 0:e[0])||!Number.isFinite(e==null?void 0:e[1]))return!1;const i=String(t.id),a=`${t.nome??""}\0${Jt(t.cor)}`,s=this.marcadores.get(i);if(s)return s.marker.setLatLng(e),s.assinatura!==a&&(s.marker.setIcon(co(t)),s.assinatura=a),!0;o.getPane(he)||(o.createPane(he).style.zIndex="9500");const r=y.marker(e,{icon:co(t),pane:he,interactive:!1,keyboard:!1}).addTo(o);return this.marcadores.set(i,{marker:r,assinatura:a}),!0}remover(t){const e=this.marcadores.get(String(t));return e?(e.marker.remove(),this.marcadores.delete(String(t)),!0):!1}limpar(){for(const t of this.marcadores.values())t.marker.remove();this.marcadores.clear()}}const qt=n=>`${n.camadaId}\0${n.id}`;class gi{constructor(t){p(this,"itens",new Map);this.dep=t}get quantidade(){return this.itens.size}contem(t){return this.itens.has(qt(t))}obter(){const t=[];for(const e of this.itens.values()){const o=this.dep.obterFeicao(e);o&&t.push(o)}return t}selecionar(t,e=!1){const o=this.assinatura(),i=new Set;e||this.itens.forEach(a=>i.add(a.camadaId)),e||this.itens.clear();for(const a of t)this.alcancavel(a)&&(this.itens.set(qt(a),{camadaId:a.camadaId,id:a.id}),i.add(a.camadaId));this.finalizar(o,i)}alternar(t){const e=this.assinatura(),o=qt(t);this.itens.has(o)?this.itens.delete(o):this.alcancavel(t)&&this.itens.set(o,{camadaId:t.camadaId,id:t.id}),this.finalizar(e,new Set([t.camadaId]))}alternarVarias(t){const e=this.assinatura(),o=new Set;for(const i of t){const a=qt(i);this.itens.has(a)?this.itens.delete(a):this.alcancavel(i)&&this.itens.set(a,{camadaId:i.camadaId,id:i.id}),o.add(i.camadaId)}this.finalizar(e,o)}alcancavel(t){const e=this.dep.obterFeicao(t);return!!e&&(!this.dep.selecionavel||this.dep.selecionavel(e))}limpar(){if(this.itens.size===0)return;const t=this.assinatura(),e=new Set([...this.itens.values()].map(o=>o.camadaId));this.itens.clear(),this.finalizar(t,e)}reconciliar(){const t=this.assinatura(),e=new Set;for(const[o,i]of this.itens){const a=this.dep.obterFeicao(i);(!a||a.excluida||this.dep.visivel&&!this.dep.visivel(a))&&(this.itens.delete(o),e.add(i.camadaId))}e.size!==0&&this.finalizar(t,e)}assinatura(){return[...this.itens.keys()].join("|")}finalizar(t,e){for(const i of e){const a=new Set;for(const s of this.itens.values())s.camadaId===i&&a.add(s.id);this.dep.aplicarVisual(i,a)}if(this.assinatura()===t)return;const o=this.obter();this.dep.aoSelecionar(o),o.length<=1&&this.dep.aoSelecionarUma(o[0]??null)}}const Qt=63710088e-1,lo=111320,te=n=>n*Math.PI/180;function gt(n){return{lat0:n[0],lon0:n[1],cos0:Math.cos(te(n[0]))}}function we(n,t){return[te(n[1]-t.lon0)*t.cos0*Qt,te(n[0]-t.lat0)*Qt]}function vt(n,t){return[t.lat0+n[1]/Qt*(180/Math.PI),t.lon0+n[0]/(Qt*t.cos0)*(180/Math.PI)]}function Be(n,t){const e=o=>{let i=!1;for(let a=0,s=o.length-1;a<o.length;s=a++){const[r,c]=o[a],[l,d]=o[s];r>n[0]!=l>n[0]&&n[1]<(d-c)*(n[0]-r)/(l-r)+c&&(i=!i)}return i};return!t[0]||!e(t[0])?!1:!t.slice(1).some(e)}function vi(n,t,e,o){const i=t[0]-n[0],a=t[1]-n[1],s=o[0]-e[0],r=o[1]-e[1],c=i*r-a*s;if(Math.abs(c)<1e-12)return null;const l=((e[0]-n[0])*r-(e[1]-n[1])*s)/c,d=((e[0]-n[0])*a-(e[1]-n[1])*i)/c;return l<0||l>1||d<0||d>=1?null:{t:l,u:d}}function ee(n){let t=0;for(let e=0;e<n.length;e++){const[o,i]=n[e],[a,s]=n[(e+1)%n.length];t+=o*s-a*i}return Math.abs(t)/2}function yi(n,t){if(n.length<3||t.length<2)return null;const e=gt(n[0]),o=n.map(s=>we(s,e)),i=t.map(s=>we(s,e)),a=xi(o,i,0);return a&&a.length>=2?a.map(s=>s.map(r=>vt(r,e))):null}function xi(n,t,e){if(e>8)return null;const o=n.length,i=[];for(let P=0;P<t.length-1;P++)for(let v=0;v<o;v++){const b=vi(t[P],t[P+1],n[v],n[(v+1)%o]);b&&i.push({tLinha:P+b.t,tAnel:v+b.u,ponto:[t[P][0]+b.t*(t[P+1][0]-t[P][0]),t[P][1]+b.t*(t[P+1][1]-t[P][1])]})}if(i.sort((P,v)=>P.tLinha-v.tLinha),i.length<2)return null;const[a,s]=i,r=[];for(let P=Math.floor(a.tLinha)+1;P<=Math.floor(s.tLinha);P++)P>a.tLinha&&P<s.tLinha&&r.push(t[P]);const c=[a.ponto,...r,s.ponto];let l=a,d=s,h=c;a.tAnel>s.tAnel&&(l=s,d=a,h=[...c].reverse());const u=Math.floor(l.tAnel),m=Math.floor(d.tAnel),f=h.slice(1,-1),g=[l.ponto];for(let P=u+1;P<=m;P++)g.push(n[P%o]);g.push(d.ponto,...[...f].reverse());const x=[d.ponto];for(let P=m+1;P<=u+o;P++)x.push(n[P%o]);x.push(l.ponto,...f);const M=ee(n)*1e-9,C=[g,x].filter(P=>P.length>=3&&ee(P)>M);if(C.length<2)return null;const z=[s.ponto,...t.slice(Math.floor(s.tLinha)+1)];if(i.length>2&&z.length>=2){const P=[];for(const v of C){const b=xi(v,z,e+1);b?P.push(...b):P.push(v)}return P}return C}function bt(n,t){return n.map(e=>we(e,t))}const ot=(n,t)=>Math.hypot(n[0]-t[0],n[1]-t[1]);function bi(n,t=0){if(n.length===0||n.some(a=>a.length<2))return null;const e=gt(n[0][0]),o=n.slice(1).map(a=>bt(a,e));let i=bt(n[0],e);for(;o.length>0;){let a=null;if(o.forEach((d,h)=>{const u=i[0],m=i[i.length-1],f=[{inverter:!1,noFim:!0,d:ot(m,d[0])},{inverter:!0,noFim:!0,d:ot(m,d[d.length-1])},{inverter:!1,noFim:!1,d:ot(u,d[d.length-1])},{inverter:!0,noFim:!1,d:ot(u,d[0])}];for(const g of f)(!a||g.d<a.d)&&(a={idx:h,...g})}),!a||a.d>t)return null;const{idx:s,inverter:r,noFim:c}=a;let l=o.splice(s,1)[0];r&&(l=[...l].reverse()),i=c?[...i,...ot(i[i.length-1],l[0])>0?l:l.slice(1)]:[...l,...ot(l[l.length-1],i[0])>0?i:i.slice(1)]}return i.map(a=>vt(a,e))}function na(n,t,e,o){const i=vi(n,t,e,o);return!!i&&i.t>1e-9&&i.t<1-1e-9&&i.u>1e-9}function aa(n,t){for(let e=0;e<n.length;e++)for(let o=0;o<t.length;o++)if(na(n[e],n[(e+1)%n.length],t[o],t[(o+1)%t.length]))return!0;return!1}function Pi(n,t,e=0){if(n.length<3||t.length<3)return null;const o=gt(n[0]),i=bt(n,o),a=bt(t,o);if(aa(i,a))return null;let s={i:0,j:0,d:1/0};for(let d=0;d<i.length;d++)for(let h=0;h<a.length;h++){const u=ot(i[d],a[h]);u<s.d&&(s={i:d,j:h,d:u})}if(s.d>e)return null;const{i:r,j:c}=s,l=[];for(let d=0;d<=i.length;d++)l.push(i[(r+d)%i.length]);for(let d=0;d<=a.length;d++)l.push(a[(c+d)%a.length]);return l.map(d=>vt(d,o))}const ho=16;function uo(n,t,e,o){const i=[];for(let a=0;a<=ho;a++){const s=e+(o-e)*a/ho;i.push([n[0]+t*Math.cos(s),n[1]+t*Math.sin(s)])}return i}function Nt(n,t){const e=ot(n,t)||1;return[-(t[1]-n[1])/e,(t[0]-n[0])/e]}function ue(n,t,e){const o=n.length,i=[],a=o;for(let s=0;s<a;s++){const r=e?n[(s-1+o)%o]:n[Math.max(0,s-1)],c=n[s],l=e?n[(s+1)%o]:n[Math.min(o-1,s+1)],d=s===0&&!e?Nt(c,l):Nt(r,c),h=s===o-1&&!e?Nt(r,c):Nt(c,l);let u=d[0]+h[0],m=d[1]+h[1];const f=Math.hypot(u,m);if(f<1e-9){i.push([c[0]+d[0]*t,c[1]+d[1]*t]);continue}u/=f,m/=f;const g=u*d[0]+m*d[1],x=Math.min(1/Math.max(g,.5),2);i.push([c[0]+u*t*x,c[1]+m*t*x])}return i}function sa(n){let t=0;for(let e=0;e<n.length;e++){const[o,i]=n[e],[a,s]=n[(e+1)%n.length];t+=(a-o)*(s+i)}return t>0}function Ci(n,t){if(!Number.isFinite(t)||t===0)return null;if(n.tipo==="Point"||n.tipo==="Text"||n.tipo==="Circle"){const e=n.tipo==="Circle"?n.centro:n.coordenada,o=n.tipo==="Circle"?n.raioMetros+t:t;if(o<=0)return null;const i=gt(e),a=64;return Array.from({length:a},(s,r)=>[o*Math.cos(2*Math.PI*r/a),o*Math.sin(2*Math.PI*r/a)]).map(s=>vt(s,i))}if(n.tipo==="LineString"){if(t<0||n.coordenadas.length<2||wt(n))return null;const e=gt(n.coordenadas[0]),o=bt(n.coordenadas,e),i=ue(o,t,!1),a=ue([...o].reverse(),t,!1),s=o[o.length-1],r=o[0],c=Math.atan2(s[1]-o[o.length-2][1],s[0]-o[o.length-2][0]),l=Math.atan2(r[1]-o[1][1],r[0]-o[1][0]),d=uo(s,t,c+Math.PI/2,c-Math.PI/2),h=uo(r,t,l+Math.PI/2,l-Math.PI/2);return[...i,...d,...a,...h].map(u=>vt(u,e))}if(n.tipo==="Polygon"){const e=n.aneis[0];if(!e||e.length<3)return null;const o=gt(e[0]);let i=bt(e,o);sa(i)&&(i=[...i].reverse());const s=ue(i,-t,!0);return s.length<3||t<0&&ee(s)>=ee(i)?null:s.map(r=>vt(r,o))}return null}function Li(n,t,e){const o=i=>{const a=e/lo,s=t/(lo*Math.max(.01,Math.cos(te(i[0]))));return[i[0]+a,i[1]+s]};switch(n.tipo){case"Point":return{tipo:"Point",coordenada:o(n.coordenada)};case"Text":return{...n,coordenada:o(n.coordenada)};case"Circle":return{...n,centro:o(n.centro)};case"LineString":{const i=yt(j(n).map(a=>a.map(o)));return n.curva?{...i,curva:no(n.curva,o)}:i}case"Polygon":{const i={tipo:"Polygon",aneis:n.aneis.map(a=>a.map(o))};return n.curva?{...i,curva:no(n.curva,o)}:i}}}const po={m:1,km:1e3,ft:.3048,mi:1609.344},fo={m2:1,ha:1e4,km2:1e6,ac:4046.8564224,alqueire:24200};function ra(n,t,e){return n*po[t]/po[e]}function ca(n,t,e){return n*fo[t]/fo[e]}function la(n,t,e=2){const o=t==="lat"?n<0?"S":"N":n<0?"O":"L",i=Math.abs(n);let a=Math.floor(i),s=Math.floor((i-a)*60),r=Number(((i-a-s/60)*3600).toFixed(e));r>=60&&(r=0,s+=1),s>=60&&(s=0,a+=1);const c=r.toFixed(e).padStart(e?e+3:2,"0");return`${a}°${String(s).padStart(2,"0")}'${c}"${o}`}function da(n){var u;if(typeof n!="string")return null;const t=n.trim().toUpperCase().replace(",","."),e=(u=/[NSLEOW]$/.exec(t))==null?void 0:u[0],o=t.replace(/[NSLEOW]$/,"").trim(),i=o.match(/-?\d+(?:\.\d+)?/g);if(!i||i.length===0||i.length>3||!/^[-\d\s°'"′″.]+$/.test(o))return null;const[a,s="0",r="0"]=i,c=Math.abs(Number(a)),l=Number(s),d=Number(r);if(l<0||l>=60||d<0||d>=60)return null;let h=c+l/60+d/3600;return(a.startsWith("-")||e==="S"||e==="O"||e==="W")&&(h=-h),h}function ha(n,t){return st(n,t)}function Bt(n,t,e){return{...n,id:t,geometria:e??JSON.parse(JSON.stringify(n.geometria)),estilo:n.estilo?{...n.estilo}:void 0,propriedades:{...n.propriedades}}}const ua=111320;function Ct(n,t){return n.x>=t.x1&&n.x<=t.x2&&n.y>=t.y1&&n.y<=t.y2}function mo(n,t,e){let o=0,i=1;const a=t.x-n.x,s=t.y-n.y,r=[-a,a,-s,s],c=[n.x-e.x1,e.x2-n.x,n.y-e.y1,e.y2-n.y];for(let l=0;l<4;l++)if(r[l]===0){if(c[l]<0)return!1}else{const d=c[l]/r[l];if(r[l]<0){if(d>i)return!1;d>o&&(o=d)}else{if(d<o)return!1;d<i&&(i=d)}}return!0}function go(n,t){let e=!1;for(let o=0,i=t.length-1;o<t.length;i=o++){const a=t[o],s=t[i];a.y>n.y!=s.y>n.y&&n.x<(s.x-a.x)*(n.y-a.y)/(s.y-a.y)+a.x&&(e=!e)}return e}function vo(n,t,e){for(let o=1;o<n.length;o++)if(mo(n[o-1],n[o],t))return!0;return e&&n.length>2&&mo(n[n.length-1],n[0],t)}function pa(n,t,e){const o=e(n),i=e([n[0]+t/ua,n[1]]);return Math.hypot(i.x-o.x,i.y-o.y)}function Si(n,t,e,o){if(n.oculta)return!1;const i=n.geometria,a=o==="window";switch(i.tipo){case"Point":case"Text":return Ct(e(i.coordenada),t);case"LineString":{const s=j(i).map(r=>r.map(e));return a?s.every(r=>r.every(c=>Ct(c,t))):s.some(r=>r.some(c=>Ct(c,t))||vo(r,t,!1))}case"Polygon":{const s=i.aneis.map(l=>l.map(e)),r=s[0];if(!r)return!1;if(a)return r.every(l=>Ct(l,t));if(s.some(l=>l.some(d=>Ct(d,t))||vo(l,t,!0)))return!0;const c={x:t.x1,y:t.y1};return go(c,r)&&!s.slice(1).some(l=>go(c,l))}case"Circle":{const s=e(i.centro),r=pa(i.centro,i.raioMetros,e);if(a)return s.x-r>=t.x1&&s.x+r<=t.x2&&s.y-r>=t.y1&&s.y+r<=t.y2;const c=Math.max(t.x1,Math.min(s.x,t.x2)),l=Math.max(t.y1,Math.min(s.y,t.y2));return Math.hypot(s.x-c,s.y-l)<=r}}}function Mi(n,t){if(t.length<3||n.oculta)return!1;const e=i=>Be(i,[t]),o=n.geometria;switch(o.tipo){case"Point":case"Text":return e(o.coordenada);case"Circle":return e(o.centro);case"LineString":return j(o).some(i=>i.some(e));case"Polygon":{const i=o.aneis[0]??[];if(i.some(e))return!0;if(i.length<3)return!1;const a=i.reduce((s,r)=>[s[0]+r[0],s[1]+r[1]],[0,0]);return e([a[0]/i.length,a[1]/i.length])}}}const fa={Point:"Ponto",LineString:"Linha",Polygon:"Polígono",Circle:"Círculo",Text:"Texto"},ma=new Set(["name","nome","category","categoria","description","descricao","author","autor","date","data","created_at","criadoEm"]),yo=6;function Lt(n,t){var e;for(const o of t){const i=(e=n.propriedades)==null?void 0:e[o];if(i!=null&&String(i)!=="")return String(i)}return""}function ga(n){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(n),e=t?new Date(Number(t[1]),Number(t[2])-1,Number(t[3])):new Date(n);return Number.isNaN(e.getTime())?n:e.toLocaleDateString("pt-BR")}function va(n){const t=typeof n=="object"?JSON.stringify(n):String(n);return t.length>80?`${t.slice(0,77)}...`:t}function Et(n){const t=n.geometria;switch(t.tipo){case"Point":case"Text":return t.coordenada;case"Circle":return t.centro;case"LineString":return t.coordenadas[Math.floor(t.coordenadas.length/2)];case"Polygon":{const e=t.aneis[0],o=e.reduce((a,s)=>a+s[0],0)/e.length,i=e.reduce((a,s)=>a+s[1],0)/e.length;return[o,i]}}}function ya(n){const t=n.geometria,e=[],o=Q(t),i=tt(t);if(t.tipo==="Polygon")e.push(["Área",rt(o??0)],["Perímetro",G(i??0)]),e.push(["Vértices",String(t.aneis.reduce((r,c)=>r+c.length,0))]);else if(t.tipo==="LineString"){const r=j(t);e.push(["Extensão",G(i??0)],["Vértices",String(r.reduce((c,l)=>c+l.length,0))]),r.length>1&&e.push(["Partes",String(r.length)])}else t.tipo==="Circle"&&e.push(["Raio",G(t.raioMetros)],["Área",rt(o??0)]);const[a,s]=Et(n);return e.push(["Coordenadas",`${a.toFixed(6)}, ${s.toFixed(6)}`]),e}class Ai{constructor(t){p(this,"popup",null);p(this,"feicaoAtual",null);p(this,"margens",{topo:20,base:20,esquerda:20,direita:20});this.dep=t}definirMargens(t){this.margens={...this.margens,...t}}get aberto(){return this.feicaoAtual}abrir(t){const e=this.dep.obterMapa();e&&(this.fechar(),this.feicaoAtual=t,this.popup=y.popup({className:"compact-popup",maxWidth:280,closeOnClick:!1,autoClose:!1,autoPanPaddingTopLeft:y.point(this.margens.esquerda,this.margens.topo),autoPanPaddingBottomRight:y.point(this.margens.direita,this.margens.base)}).setLatLng(Et(t)).setContent(this.montar(t)),this.popup.openOn(e))}atualizar(t){var e;!this.popup||((e=this.feicaoAtual)==null?void 0:e.id)!==t.id||this.feicaoAtual.camadaId!==t.camadaId||(this.feicaoAtual=t,this.popup.setLatLng(Et(t)).setContent(this.montar(t)))}fechar(){const t=this.popup;this.popup=null,this.feicaoAtual=null,t==null||t.close()}montar(t){var g;const e=this.dep.obterCamada(t.camadaId),o=Z(((g=t.estilo)==null?void 0:g.corTraco)??(e==null?void 0:e.estilo.corPrimaria),"#38bdf8"),i=(x,A="",M)=>{const C=document.createElement(x);return A&&(C.style.cssText=A),M!==void 0&&(C.textContent=M),C},a=i("div","font-family:var(--ui-fonte-base,sans-serif);color:rgba(255,255,255,.9);line-height:1.35;min-width:200px;border-left:3px solid "+o+";padding-left:8px");a.className="cad-feicao-popup",a.appendChild(i("div","font-weight:700;font-size:13px;margin-bottom:1px",Lt(t,["name","nome"])||t.id));const s=Lt(t,["category","categoria"]),r=[fa[t.geometria.tipo],(e==null?void 0:e.nome)??t.camadaId,s].filter(Boolean).join(" · ");a.appendChild(i("div","font-size:11px;color:rgba(255,255,255,.6);margin-bottom:4px",r));const c=Lt(t,["description","descricao"]);c&&a.appendChild(i("div","font-size:11px;margin-bottom:4px",c));const l=x=>{const A=i("div","font-size:11px;margin-bottom:4px");for(const[M,C]of x){const z=i("div");z.appendChild(i("strong","",`${M}: `)),z.appendChild(document.createTextNode(C)),A.appendChild(z)}return A};a.appendChild(l(ya(t)));const d=Object.entries(t.propriedades??{}).filter(([x,A])=>!ma.has(x)&&A!==void 0&&A!==null&&A!=="");d.length>0&&(a.appendChild(l(d.slice(0,yo).map(([x,A])=>[x,va(A)]))),d.length>yo&&a.appendChild(i("div","font-size:10px;color:rgba(255,255,255,.55);margin-bottom:4px",`${d.length} atributos`)));const h=Lt(t,["author","autor"]),u=Lt(t,["date","data","created_at","criadoEm"]);if(h||u){const x=[h,u?ga(u):""].filter(Boolean).join(" · ");a.appendChild(i("div","font-size:10px;color:rgba(255,255,255,.55);margin-bottom:4px",x))}const m=i("div","display:flex;gap:4px;flex-wrap:wrap;margin-top:6px"),f=[["inspecionar","Inspecionar"],["zoom","Zoom"]];(t.geometria.tipo==="LineString"||t.geometria.tipo==="Polygon"||t.geometria.tipo==="Point")&&f.push(["vertices","Vértices"]),t.geometria.tipo==="Point"&&f.push(["copiar","Copiar"]);for(const[x,A]of f){const M=i("button","font-size:11px;padding:2px 8px;border-radius:4px;border:1px solid rgba(255,255,255,.25);background:rgba(255,255,255,.08);color:inherit;cursor:pointer",A);M.type="button",M.dataset.acao=x,M.addEventListener("click",C=>{C.stopPropagation(),this.dep.aoAcao(x,this.feicaoAtual??t)}),m.appendChild(M)}return a.appendChild(m),a}}const wi=5e3;function _t(n){return n.tipo==="Polygon"?3:n.tipo==="LineString"?2:1}function ki(n,t=!1){if(n.bloqueada||t)return"bloqueada";const e=n.geometria;return e.tipo!=="Point"&&e.tipo!=="LineString"&&e.tipo!=="Polygon"&&e.tipo!=="Circle"?"tipo-nao-suportado":e.tipo==="Polygon"&&e.aneis.length!==1?"poligono-com-furos":wt(e)?"multiparte":K(e).length>wi?"muitos-vertices":null}function K(n){return n.tipo==="Point"?[n.coordenada]:n.tipo==="LineString"?n.coordenadas:n.tipo==="Polygon"?n.aneis[0]??[]:[]}function Tt(n,t){return n.tipo==="Point"?{tipo:"Point",coordenada:t[0]}:n.tipo==="LineString"?{tipo:"LineString",coordenadas:t}:n.tipo==="Polygon"?{tipo:"Polygon",aneis:[t]}:n}function xa(n,t,e){const o=K(n).slice();return t<0||t>=o.length?n:(o[t]=e,Tt(n,o))}function zi(n,t,e){if(n.tipo!=="LineString"&&n.tipo!=="Polygon")return n;const o=K(n).slice();return t<0||t>=o.length?n:(o.splice(t+1,0,e),Tt(n,o))}function Ei(n,t){if(n.tipo!=="LineString"&&n.tipo!=="Polygon")return null;const e=K(n);return t<0||t>=e.length||e.length<=_t(n)?null:Tt(n,e.filter((o,i)=>i!==t))}function He(n,t){return[(n[0]+t[0])/2,(n[1]+t[1])/2]}function Ve(n){const t=K(n).length,e=[];if(n.tipo!=="LineString"&&n.tipo!=="Polygon")return e;for(let o=0;o<t-1;o++)e.push([o,o+1]);return n.tipo==="Polygon"&&t>2&&e.push([t-1,0]),e}function U(n){return(n.tipo==="LineString"||n.tipo==="Polygon")&&n.curva&&n.curva.length>=_t(n)?n.curva:null}const ba=63710088e-1*Math.PI/180,Ii=.5;function _i(n,t){const e=Math.max(.01,Math.cos(n[0]*Math.PI/180));return[n[0],n[1]+t/(ba*e)]}function St(n){var t;return n.tipo==="Circle"?[n.centro,_i(n.centro,n.raioMetros)]:((t=U(n))==null?void 0:t.map(e=>e.ponto))??K(n)}function Pt(n,t){const e=n.tipo==="Polygon",o=xt(t,e);return e?{tipo:"Polygon",aneis:[o],curva:t}:{tipo:"LineString",coordenadas:o,curva:t}}function Ti(n,t){if(n.tipo==="Circle")return t.length<2?n:{...n,centro:t[0],raioMetros:Math.max(Ii,st(t[0],t[1]))};const e=U(n);if(!e||e.length!==t.length)return Tt(n,t);const o=e.map((i,a)=>{const s=t[a][0]-i.ponto[0],r=t[a][1]-i.ponto[1],c=d=>[d[0]+s,d[1]+r],l={ponto:t[a]};return i.entrada&&(l.entrada=c(i.entrada)),i.saida&&(l.saida=c(i.saida)),l});return Pt(n,o)}function pt(n,t,e){return[n[0]+(t[0]-n[0])*e,n[1]+(t[1]-n[1])*e]}function Pa(n,t,e){const[o,i]=It(n,t);let a=.5,s=1/0;for(let r=1;r<64;r++){const c=r/64,l=Fe(n.ponto,o,i,t.ponto,c),d=(l[0]-e[0])**2+(l[1]-e[1])**2;d<s&&(s=d,a=c)}return a}function Ht(n,t,e){const o=U(n);if(!o){const s=K(n);return He(s[t],s[e])}const[i,a]=It(o[t],o[e]);return Fe(o[t].ponto,i,a,o[e].ponto,.5)}function Di(n){const t=U(n);if(!t)return Ve(n);const e=[];for(let o=0;o<t.length-1;o++)e.push([o,o+1]);return n.tipo==="Polygon"&&t.length>2&&e.push([t.length-1,0]),e}function $i(n,t,e){const o=U(n);if(!o)return zi(n,t,e);if(t<0||t>=o.length)return n;const i=(t+1)%o.length,a=o[t],s=o[i],r=a.saida===void 0&&s.entrada===void 0;let c,l=a,d=s;if(r)c={ponto:e};else{const u=Pa(a,s,e),[m,f]=It(a,s),g=pt(a.ponto,m,u),x=pt(m,f,u),A=pt(f,s.ponto,u),M=pt(g,x,u),C=pt(x,A,u);c={ponto:pt(M,C,u),entrada:M,saida:C},l={...a,saida:g},d={...s,entrada:A}}const h=o.slice();return h[t]=l,h[i]=d,h.splice(t+1,0,c),Pt(n,h)}function qi(n,t){const e=U(n);return e?t<0||t>=e.length||e.length<=_t(n)?null:Pt(n,e.filter((o,i)=>i!==t)):Ei(n,t)}function Ni(n){return n.tipo!=="LineString"&&n.tipo!=="Polygon"?null:U(n)??K(n).map(t=>({ponto:[t[0],t[1]]}))}function Oi(n,t,e,o,i=!0){const a=Ni(n);if(!a||t<0||t>=a.length)return n;const s={...a[t],[e]:o};i&&(s[e==="saida"?"entrada":"saida"]=Oe(s.ponto,o));const r=a.slice();return r[t]=s,Pt(n,r)}function Fi(n,t){const e=Ni(n);if(!e||t<0||t>=e.length)return n;const o=e[t],i=e.slice();if(o.entrada||o.saida)return i[t]={ponto:o.ponto},Pt(n,i);const a=n.tipo==="Polygon",s=e.length,r=t>0?e[t-1]:a?e[s-1]:null,c=t<s-1?e[t+1]:a?e[0]:null;if(!r&&!c)return n;const l=o.ponto;let d,h;if(r&&c)d=(c.ponto[0]-r.ponto[0])/6,h=(c.ponto[1]-r.ponto[1])/6;else{const u=(c??r).ponto,m=c?1:-1;d=(u[0]-l[0])/3*m,h=(u[1]-l[1])/3*m}return i[t]={ponto:l,saida:[l[0]+d,l[1]+h],entrada:[l[0]-d,l[1]-h]},Pt(n,i)}const Ri={topo:0,base:16,esquerda:0,direita:0},Bi=16,Hi=.92,Vt={topo:"--cad-hud-topo",base:"--cad-hud-base",esquerda:"--cad-hud-esquerda",direita:"--cad-hud-direita"},Ge="position:absolute;box-sizing:border-box;z-index:10000;left:calc(var(--cad-hud-esquerda,0px) + (100% - var(--cad-hud-esquerda,0px) - var(--cad-hud-direita,0px)) / 2);bottom:var(--cad-hud-base,16px);transform:translateX(-50%);width:max-content;max-width:min(92%, calc(100% - var(--cad-hud-esquerda,0px) - var(--cad-hud-direita,0px) - 16px));max-height:calc(100% - var(--cad-hud-topo,0px) - var(--cad-hud-base,16px) - 8px);overflow:hidden;display:flex;flex-wrap:wrap;";function Ca(n,t,e={}){const o={...Ri,...e},i=Math.max(0,n-o.esquerda-o.direita);return{centroX:o.esquerda+i/2,base:o.base,larguraMax:Math.max(0,Math.min(n*Hi,i-Bi)),alturaMax:Math.max(0,t-o.topo-o.base-8)}}function Vi(n,t){for(const e of Object.keys(Vt)){const o=t[e];typeof o=="number"&&Number.isFinite(o)&&o>=0?n.style.setProperty(Vt[e],`${o}px`):n.style.removeProperty(Vt[e])}}const Gi="cm-vertex-edit-hud",lt="cad-edicao-vertices",xo="#facc15",bo="#f472b6";class ji{constructor(t){p(this,"feicaoAtual",null);p(this,"pts",[]);p(this,"alcas",[]);p(this,"fantasmas",[]);p(this,"alcasBezier",[]);p(this,"marcadorSnap",null);p(this,"hud",null);p(this,"grupo",null);this.dep=t}get ativo(){return this.feicaoAtual!==null}get ehCirculo(){var t;return((t=this.feicaoAtual)==null?void 0:t.geometria.tipo)==="Circle"}get feicao(){return this.feicaoAtual}iniciar(t){this.parar(),this.feicaoAtual=t,this.pts=St(t.geometria).map(o=>[o[0],o[1]]);const e=this.dep.map;if(!e.getPane(lt)){const o=e.createPane(lt);o.style.zIndex="9000"}this.grupo=y.layerGroup().addTo(e),this.montarHud(),this.reconstruir()}parar(){var e,o;const t=this.feicaoAtual;t&&(this.feicaoAtual=null,this.alcas=[],this.fantasmas=[],this.alcasBezier=[],(e=this.grupo)==null||e.remove(),this.grupo=null,this.marcadorSnap=null,(o=this.hud)==null||o.remove(),this.hud=null,this.dep.aoEncerrar(t))}sincronizar(t){!this.feicaoAtual||this.feicaoAtual.id!==t.id||(this.feicaoAtual=t,this.pts=St(t.geometria).map(e=>[e[0],e[1]]),this.reconstruir())}atualizarSnapNoHud(){var e;const t=(e=this.hud)==null?void 0:e.querySelector('[data-campo="snap"]');t&&(t.textContent=`Snap: ${this.dep.snapLigado()?"ligado":"desligado"} (S)`)}geometriaAtual(){return Ti(this.feicaoAtual.geometria,this.pts)}feicaoComPontos(){return{...this.feicaoAtual,geometria:this.geometriaAtual()}}reconstruir(){var e;if((e=this.grupo)==null||e.clearLayers(),this.alcas=[],this.fantasmas=[],this.alcasBezier=[],!this.feicaoAtual||!this.grupo)return;const t=this.feicaoAtual.geometria;if(this.pts.forEach((o,i)=>{const a=this.criarAlca(o,i);this.alcas.push(a),this.grupo.addLayer(a)}),this.criarAlcasBezier(),t.tipo!=="Point")for(const[o,i]of Di(this.geometriaAtual())){const a=this.criarFantasma(o,i);this.fantasmas.push(a),this.grupo.addLayer(a.marker)}this.atualizarHud()}icone(t,e,o){return y.divIcon({className:`custom-leaflet-marker ${t}`,iconSize:[e,e],html:`<div style="width:${e}px;height:${e}px;box-sizing:border-box;${o}"></div>`})}criarAlca(t,e){const o=y.marker(t,{icon:this.icone("cad-vertex-handle",12,`background:${xo};border:2px solid #111;border-radius:${this.ehCirculo&&e===1?"50%":"2px"};cursor:${this.ehCirculo&&e===1?"ew-resize":"move"}`),draggable:!0,pane:lt,keyboard:!1});return o.on("drag",()=>this.aoArrastar(o,e)),o.on("dragend",()=>{this.esconderSnap(),this.confirmar(this.feicaoComPontos())}),o.on("contextmenu",i=>{y.DomEvent.preventDefault(i.originalEvent),y.DomEvent.stopPropagation(i.originalEvent),this.excluir(e)}),o.on("dblclick",i=>{y.DomEvent.stopPropagation(i.originalEvent),this.alternarSuave(e)}),o}criarAlcasBezier(){const t=this.feicaoAtual&&U(this.feicaoAtual.geometria);t&&t.forEach((e,o)=>this.completarAlcasDoNo(o))}completarAlcasDoNo(t){var o;const e=this.feicaoAtual&&((o=U(this.feicaoAtual.geometria))==null?void 0:o[t]);if(!(!e||!this.grupo))for(const i of["entrada","saida"]){const a=e[i];if(!a||this.alcasBezier.some(l=>l.i===t&&l.qual===i))continue;const s=y.polyline([e.ponto,a],{pane:lt,color:bo,weight:1,opacity:.8,interactive:!1}),r=y.marker(a,{icon:this.icone("cad-bezier-handle",10,`background:#fff;border:2px solid ${bo};border-radius:50%;cursor:move`),draggable:!0,pane:lt,keyboard:!1}),c={marker:r,haste:s,i:t,qual:i};r.on("drag",l=>{const d=l.originalEvent;this.aoArrastarAlca(c,!(d!=null&&d.shiftKey))}),r.on("dragend",()=>this.confirmar(this.feicaoAtual)),this.alcasBezier.push(c),this.grupo.addLayer(s),this.grupo.addLayer(r)}}sincronizarAlcasBezier(){var e;const t=this.feicaoAtual&&U(this.feicaoAtual.geometria);if(t)for(const o of this.alcasBezier){const i=(e=t[o.i])==null?void 0:e[o.qual];i&&((o.marker.getLatLng().lat!==i[0]||o.marker.getLatLng().lng!==i[1])&&o.marker.setLatLng(i),o.haste.setLatLngs([t[o.i].ponto,i]))}}aoArrastarAlca(t,e){const o=this.feicaoAtual;if(!o)return;const{lat:i,lng:a}=t.marker.getLatLng(),s=Oi(o.geometria,t.i,t.qual,[i,a],e);this.feicaoAtual={...o,geometria:s},this.completarAlcasDoNo(t.i),this.sincronizarAlcasBezier(),this.dep.previsualizar(this.feicaoAtual),this.atualizarHud()}alternarSuave(t){const e=this.feicaoAtual;if(!e)return;const o=Fi(e.geometria,t);o!==e.geometria&&(this.feicaoAtual={...e,geometria:o},this.reconstruir(),this.dep.previsualizar(this.feicaoAtual),this.confirmar(this.feicaoAtual))}criarFantasma(t,e){const o=y.marker(Ht(this.geometriaAtual(),t,e),{icon:this.icone("cad-vertex-ghost",9,`background:${xo};opacity:.45;border:1px solid #111;border-radius:50%;cursor:copy`),pane:lt,keyboard:!1});return o.on("click",i=>{y.DomEvent.stopPropagation(i.originalEvent),this.inserir(t,o.getLatLng())}),{marker:o,i:t,j:e}}aoArrastar(t,e){var s;const o=this.feicaoAtual;if(!o)return;let i=[t.getLatLng().lat,t.getLatLng().lng];const a=this.dep.snapLigado()?this.dep.buscarSnap(i,{feicaoId:o.id,camadaId:o.camadaId,vertice:e}):null;if(a?(i=a.coordenada,t.setLatLng(i),this.mostrarSnap(i)):this.esconderSnap(),o.geometria.tipo==="Circle"&&e===0){const r=i[0]-this.pts[0][0],c=i[1]-this.pts[0][1];this.pts[1]=[this.pts[1][0]+r,this.pts[1][1]+c],(s=this.alcas[1])==null||s.setLatLng(this.pts[1])}this.pts[e]=i;for(const r of this.fantasmas)(r.i===e||r.j===e)&&r.marker.setLatLng(Ht(this.geometriaAtual(),r.i,r.j));this.dep.previsualizar(this.feicaoComPontos()),this.atualizarAlcasDoNo(e),this.atualizarHud()}atualizarAlcasDoNo(t){const e=U(this.geometriaAtual());if(e)for(const o of this.alcasBezier){if(o.i!==t)continue;const i=e[t][o.qual];i&&(o.marker.setLatLng(i),o.haste.setLatLngs([e[t].ponto,i]))}}inserir(t,e){if(!this.feicaoAtual)return;const i=$i(this.geometriaAtual(),t,[e.lat,e.lng]);this.pts=St(i).map(s=>[s[0],s[1]]),this.reconstruir();const a=this.feicaoComPontos();this.dep.previsualizar(a),this.confirmar(a)}confirmar(t){this.feicaoAtual=t,this.dep.aoGesto(t)}excluir(t){if(!this.feicaoAtual)return;const o=qi(this.geometriaAtual(),t);if(!o)return;this.pts=St(o).map(a=>[a[0],a[1]]),this.reconstruir();const i=this.feicaoComPontos();this.dep.previsualizar(i),this.confirmar(i)}excluirVertice(t){const e=this.pts.length;return this.excluir(t),this.pts.length<e}inserirVerticeApos(t){if(t<0||t>=this.pts.length)return;const e=(t+1)%this.pts.length,o=Ht(this.geometriaAtual(),t,e);this.inserir(t,y.latLng(o[0],o[1]))}mostrarSnap(t){this.grupo&&(this.marcadorSnap?this.marcadorSnap.setLatLng(t):this.marcadorSnap=y.marker(t,{icon:y.divIcon({className:"custom-leaflet-marker cm-snap",iconSize:[18,18],html:'<div style="width:18px;height:18px;box-sizing:border-box;border:2px solid #22d3ee;transform:rotate(45deg);border-radius:2px"></div>'}),interactive:!1,pane:lt,keyboard:!1}).addTo(this.grupo))}esconderSnap(){var t;this.marcadorSnap&&((t=this.grupo)==null||t.removeLayer(this.marcadorSnap),this.marcadorSnap=null)}montarHud(){const t=this.dep.map.getContainer(),e=document.createElement("div");e.id=Gi,e.style.cssText=Ge+"gap:12px;align-items:center;padding:6px 12px;border-radius:8px;background:rgba(15,23,42,.92);color:#fff;font:12px var(--ui-fonte-base,sans-serif);border:1px solid rgba(255,255,255,.2);pointer-events:auto";const o=c=>{const l=document.createElement("span");return l.dataset.campo=c,l},i=document.createElement("strong");i.textContent=this.ehCirculo?"Editando círculo":"Editando vértices";const a=o("snap");a.style.cursor="pointer",a.title="Alternar snap (S). Alt desliga temporariamente.",a.addEventListener("click",()=>this.dep.alternarSnap());const s=document.createElement("button");s.type="button",s.textContent="Concluir",s.style.cssText="padding:3px 10px;border-radius:4px;border:1px solid #facc15;background:#facc15;color:#111;font-weight:600;cursor:pointer",s.addEventListener("click",()=>this.parar());const r=o("dica");r.style.opacity=".7",r.textContent="Duplo clique no nó: curva ↔ canto · Alças: Shift solta a simetria",e.append(i,o("nos"),o("medida"),a,r,s),y.DomEvent.disableClickPropagation(e),y.DomEvent.disableScrollPropagation(e),t.appendChild(e),this.hud=e,this.atualizarSnapNoHud()}atualizarHud(){if(!this.hud||!this.feicaoAtual)return;const t=this.geometriaAtual(),e=this.hud.querySelector('[data-campo="nos"]'),o=this.hud.querySelector('[data-campo="medida"]');e&&(e.textContent=t.tipo==="Circle"?"Centro move · borda muda o raio":`Nós: ${this.pts.length} (mín. ${_t(t)})`),o&&(t.tipo==="Polygon"?o.textContent=`Área: ${rt(Q(t)??0)} · Perímetro: ${G(tt(t)??0)}`:t.tipo==="LineString"?o.textContent=`Extensão: ${G(tt(t)??0)}`:t.tipo==="Point"?o.textContent=`${t.coordenada[0].toFixed(6)}, ${t.coordenada[1].toFixed(6)}`:t.tipo==="Circle"&&(o.textContent=`Raio: ${G(t.raioMetros)} · Área: ${rt(Q(t)??0)}`))}vertices(){return this.pts.map(t=>[t[0],t[1]])}get totalAlcasBezier(){return this.alcasBezier.length}arrastarAlcaPara(t,e,o,i=!1){const a=this.alcasBezier.find(s=>s.i===t&&s.qual===e);a&&(a.marker.setLatLng(o),this.aoArrastarAlca(a,!i),this.confirmar(this.feicaoAtual))}alternarSuavidadeDoNo(t){this.alternarSuave(t)}arrastarPara(t,e){const o=this.alcas[t];o&&(o.setLatLng(e),this.aoArrastar(o,t),o.fire("dragend"))}}const je=10,pe=(n,t)=>Math.hypot(n.x-t.x,n.y-t.y);function La(n,t,e){const o=e.x-t.x,i=e.y-t.y,a=o*o+i*i,s=a===0?0:Math.max(0,Math.min(1,((n.x-t.x)*o+(n.y-t.y)*i)/a));return{t:s,d:Math.hypot(n.x-(t.x+s*o),n.y-(t.y+s*i))}}function Ui(n,t,e,o={},i){const a=o.toleranciaPx??je,s=o.vertice!==!1,r=o.meio!==!1,c=o.aresta!==!1;let l=null,d=null,h=null;const u=(m,f)=>!m||f.distanciaPx<m.distanciaPx?f:m;for(const m of t){if(m.excluida||m.oculta)continue;const f=!!i&&i.feicaoId===m.id&&(i.camadaId===void 0||i.camadaId===m.camadaId),g=m.geometria,x={feicaoId:m.id,camadaId:m.camadaId};if(g.tipo==="Point"||g.tipo==="Text"||g.tipo==="Circle"){if(!s||f)continue;const C=g.tipo==="Circle"?g.centro:g.coordenada,z=pe(n,e(C));z<=a&&(l=u(l,{tipo:"vertice",coordenada:C,distanciaPx:z,...x}));continue}if(f&&(g.tipo==="LineString"||g.tipo==="Polygon")&&g.curva)continue;const A=g.tipo==="LineString"?j(g).map(C=>({pts:C,fechado:!1})):[{pts:K(g),fechado:g.tipo==="Polygon"}],M=f?i.vertice:void 0;for(const{pts:C,fechado:z}of A){const P=C.map(e);if(s)for(let b=0;b<C.length;b++){if(b===M)continue;const k=pe(n,P[b]);k<=a&&(l=u(l,{tipo:"vertice",coordenada:C[b],distanciaPx:k,...x}))}if(!r&&!c)continue;const v=[];for(let b=0;b<C.length-1;b++)v.push([b,b+1]);z&&C.length>2&&v.push([C.length-1,0]);for(const[b,k]of v)if(!(M!==void 0&&(b===M||k===M))&&!(f&&M===void 0)){if(r){const E=He(C[b],C[k]),L=pe(n,e(E));L<=a&&(d=u(d,{tipo:"meio",coordenada:E,distanciaPx:L,...x}))}if(c){const{t:E,d:L}=La(n,P[b],P[k]);if(L<=a){const w=[C[b][0]+E*(C[k][0]-C[b][0]),C[b][1]+E*(C[k][1]-C[b][1])];h=u(h,{tipo:"aresta",coordenada:w,distanciaPx:L,...x})}}}}}return l??d??h}class Sa{constructor(t){p(this,"_ligado",!0);p(this,"_altSegurado",!1);p(this,"atalhoS",!0);p(this,"conectado",!1);p(this,"aoTeclaBaixo",t=>{if(t.key==="Alt"){this.definirAlt(!0);return}this.atalhoS&&(t.key==="s"||t.key==="S")&&!t.ctrlKey&&!t.metaKey&&!t.altKey&&!Ie(t)&&this.alternar()});p(this,"aoTeclaCima",t=>{t.key==="Alt"&&this.definirAlt(!1)});p(this,"aoPerderFoco",()=>{this.definirAlt(!1)});this.contexto=t}get ativo(){return this._ligado&&!this._altSegurado}get ligado(){return this._ligado}definir(t){this._ligado!==t&&(this._ligado=t,this.notificar())}alternar(){this.definir(!this._ligado)}conectar(){if(this.conectado)return;this.conectado=!0;const t=this.contexto.alvo??window;t.addEventListener("keydown",this.aoTeclaBaixo),t.addEventListener("keyup",this.aoTeclaCima),t.addEventListener("blur",this.aoPerderFoco)}desconectar(){if(!this.conectado)return;this.conectado=!1;const t=this.contexto.alvo??window;t.removeEventListener("keydown",this.aoTeclaBaixo),t.removeEventListener("keyup",this.aoTeclaCima),t.removeEventListener("blur",this.aoPerderFoco),this._altSegurado=!1}definirAlt(t){this._altSegurado!==t&&(this._altSegurado=t,this.notificar())}notificar(){this.contexto.aoMudar({ativo:this.ativo,ligado:this._ligado,temporario:this._altSegurado})}}const Po=36,Ma=.45;function Aa(n,t){const e=Math.abs(t[0]-n[0]),o=Math.abs(t[1]-n[1]);if(e===0&&o===0)return null;const i=[];for(let a=0;a<Po;a++){const s=a*2*Math.PI/Po;i.push([n[0]+e*Math.sin(s),n[1]+o*Math.cos(s)])}return i}function Wi(n,t){const e=Math.cos(n[0]*Math.PI/180)||1,o=t[0]-n[0],i=(t[1]-n[1])*e,a=Math.hypot(o,i);return a===0?null:{raio:a,inicio:Math.atan2(o,i),cosLat:e}}function wa(n,t,e=6){const o=Wi(n,t);if(!o||e<3)return null;const i=[];for(let a=0;a<e;a++){const s=o.inicio+a*2*Math.PI/e;i.push([n[0]+o.raio*Math.sin(s),n[1]+o.raio*Math.cos(s)/o.cosLat])}return i}function ka(n,t,e=5){const o=Wi(n,t);if(!o||e<3)return null;const i=e*2,a=[];for(let s=0;s<i;s++){const r=s%2===0?o.raio:o.raio*Ma,c=o.inicio+s*2*Math.PI/i;a.push([n[0]+r*Math.sin(c),n[1]+r*Math.cos(c)/o.cosLat])}return a}const oe=["ponto","linha","poligono","retangulo","elipse","poligono-regular","estrela","circulo","texto","caneta","medir-distancia","medir-area","dividir","selecao-laco","conta-gotas"],ke=2;function Ue(n){return typeof n=="string"&&oe.includes(n)}function Mt(n){return n.map(t=>{const e={ponto:t.ponto};return t.alca&&(e.saida=t.alca,e.entrada=Oe(t.ponto,t.alca)),e})}function Xi(n){return xt(Mt(n),!1)}function fe(n,t){const e=Xo(n);if(t){const i=e?xt(n,!0):n.map(a=>a.ponto);return e?{tipo:"Polygon",aneis:[i],curva:n}:{tipo:"Polygon",aneis:[i]}}const o=e?xt(n,!1):n.map(i=>i.ponto);return e?{tipo:"LineString",coordenadas:o,curva:n}:{tipo:"LineString",coordenadas:o}}const za=(n,t)=>n[0]===t[0]&&n[1]===t[1],Co={elipse:Aa,"poligono-regular":(n,t)=>wa(n,t,6),estrela:(n,t)=>ka(n,t,5)};class Gt{constructor(t,e=!1){p(this,"pontos",[]);p(this,"cursor",null);p(this,"ancoras",[]);this.ferramenta=t,this.fechar=e}get nos(){return this.ferramenta==="caneta"?this.ancoras.length:this.pontos.length}get ehSequencial(){return["linha","poligono","caneta","medir-distancia","medir-area","dividir","selecao-laco"].includes(this.ferramenta)}get ehArea(){return this.ferramenta==="poligono"||this.ferramenta==="medir-area"||this.ferramenta==="selecao-laco"||this.ferramenta==="caneta"&&this.fechar}get fechaNoPrimeiro(){return this.nos>=3&&(this.ehArea||this.ferramenta==="caneta")}get primeiro(){var t;return(this.ferramenta==="caneta"?(t=this.ancoras[0])==null?void 0:t.ponto:this.pontos[0])??null}get minimo(){return this.ehArea?3:2}get podeConcluir(){return this.ehSequencial&&this.nos>=this.minimo}mover(t){this.cursor=t}clicar(t){switch(this.ferramenta){case"ponto":return{concluida:{tipo:"Point",coordenada:t}};case"texto":return{concluida:{tipo:"Text",coordenada:t,texto:""}};case"retangulo":return this.pontos.length===0?(this.pontos.push(t),{}):{concluida:this.retangulo(this.pontos[0],t)??void 0};case"circulo":if(this.pontos.length===0)return this.pontos.push(t),{};{const e=st(this.pontos[0],t);return e>=ke?{concluida:{tipo:"Circle",centro:this.pontos[0],raioMetros:e}}:{}}case"elipse":case"poligono-regular":case"estrela":{if(this.pontos.length===0)return this.pontos.push(t),{};const e=Co[this.ferramenta](this.pontos[0],t);return e?{concluida:{tipo:"Polygon",aneis:[e]}}:{}}case"caneta":return this.ancoras.push({ponto:t}),{};case"conta-gotas":return{};default:return this.pontos.length>0&&za(this.pontos[this.pontos.length-1],t)?{}:(this.pontos.push(t),{})}}definirAlca(t){const e=this.ancoras[this.ancoras.length-1];this.ferramenta==="caneta"&&e&&(e.alca=t)}desfazer(){const t=this.ferramenta==="caneta"?this.ancoras:this.pontos;return t.length===0?!1:(t.pop(),!0)}vertices(){return this.ferramenta==="caneta"?Xi(this.ancoras):this.pontos}retangulo(t,e){return t[0]===e[0]||t[1]===e[1]?null:{tipo:"Polygon",aneis:[[[t[0],t[1]],[t[0],e[1]],[e[0],e[1]],[e[0],t[1]]]]}}previa(){const t=this.cursor;switch(this.ferramenta){case"retangulo":return this.pontos.length===1&&t?this.retangulo(this.pontos[0],t):null;case"circulo":{if(this.pontos.length!==1||!t)return null;const e=st(this.pontos[0],t);return e>=ke?{tipo:"Circle",centro:this.pontos[0],raioMetros:e}:null}case"caneta":{if(this.ancoras.length===0)return null;const e=Mt(t?[...this.ancoras,{ponto:t}]:this.ancoras);return e.length<2?null:fe(e,this.ehArea&&e.length>=3)}case"elipse":case"poligono-regular":case"estrela":{if(this.pontos.length!==1||!t)return null;const e=Co[this.ferramenta](this.pontos[0],t);return e?{tipo:"Polygon",aneis:[e]}:null}case"ponto":case"texto":case"conta-gotas":return null;default:{const e=t?[...this.pontos,t]:[...this.pontos];return e.length<2?null:this.ehArea&&e.length>=3?{tipo:"Polygon",aneis:[e]}:{tipo:"LineString",coordenadas:e}}}}concluir(){if(!this.podeConcluir)return null;if(this.ferramenta==="caneta")return fe(Mt(this.ancoras),this.ehArea);const t=this.vertices();return this.ehArea?{tipo:"Polygon",aneis:[t]}:{tipo:"LineString",coordenadas:t}}concluirFechando(){return this.fechaNoPrimeiro?this.ferramenta==="caneta"?fe(Mt(this.ancoras),!0):{tipo:"Polygon",aneis:[this.vertices()]}:null}comprimentoMetros(){const t=this.cursor&&this.nos>0?[...this.vertices(),this.cursor]:this.vertices();return kt(t,!1)}}const Zi="cm-draw-hud",ze="cad-ferramenta-ativa",et="cad-desenho",dt="#22d3ee",Ea=4,Ia=450,_a=10,Ta={ponto:"Ponto",linha:"Linha",poligono:"Polígono",retangulo:"Retângulo",elipse:"Elipse","poligono-regular":"Polígono regular (hexágono)",estrela:"Estrela",circulo:"Círculo",texto:"Texto",caneta:"Caneta (Bézier)","medir-distancia":"Medir distância","medir-area":"Medir área",dividir:"Dividir polígono","selecao-laco":"Seleção por laço","conta-gotas":"Conta-gotas"},Da={ponto:"Clique para colocar",linha:"Clique nos vértices · Enter ou duplo clique conclui",poligono:"Clique nos vértices · Enter ou duplo clique conclui",retangulo:"Clique nos dois cantos",elipse:"Clique no centro e depois no canto da caixa","poligono-regular":"Clique no centro e depois num vértice",estrela:"Clique no centro e depois numa ponta",circulo:"Clique no centro e depois num ponto da borda",texto:"Clique onde o texto vai",caneta:"Clique e arraste para curvar · Enter conclui · 1º ponto fecha","medir-distancia":"Clique nos pontos · Enter conclui","medir-area":"Clique nos vértices · Enter conclui",dividir:"Desenhe a linha de corte · Enter aplica","selecao-laco":"Desenhe o laço · Enter ou 1º ponto fecha e seleciona","conta-gotas":"Clique numa feição para copiar o estilo"};class Yi{constructor(t){p(this,"sessao",null);p(this,"fechar",!1);p(this,"grupo",null);p(this,"previa",null);p(this,"marcas",null);p(this,"medicao",null);p(this,"marcadorSnap",null);p(this,"hud",null);p(this,"campoTexto",null);p(this,"arrastando",!1);p(this,"ultimoClique",null);p(this,"aoClicar",t=>{var a;const e=this.sessao;if(!e||e.ferramenta==="caneta"||this.campoTexto||((a=t.originalEvent)==null?void 0:a.button)!==void 0&&t.originalEvent.button!==0)return;const o=this.coordenada(t);if(e.ferramenta==="conta-gotas"){this.dep.aoAmostrar(o,t.originalEvent);return}if(e.ehSequencial&&this.repetido(t)||this.fechaNoPrimeiroVertice(t))return;const i=e.clicar(o);if(i.concluida){i.concluida.tipo==="Text"?this.pedirTexto(o):this.finalizar(i.concluida);return}this.atualizar()});p(this,"aoPressionar",t=>{var o;const e=this.sessao;!e||e.ferramenta!=="caneta"||((o=t.originalEvent)==null?void 0:o.button)!==0||this.repetido(t)||this.fechaNoPrimeiroVertice(t)||(e.clicar(this.coordenada(t)),this.arrastando=!0,this.atualizar())});p(this,"aoSoltar",()=>{this.arrastando=!1});p(this,"aoMover",t=>{const e=this.sessao;if(!e)return;const o=this.coordenada(t);e.mover(o),this.arrastando&&e.definirAlca(o),this.atualizar()});p(this,"aoDuploClique",()=>{this.concluir()});p(this,"aoTecla",t=>{const e=this.sessao;if(!e)return;const o=Ie(t);if(t.key==="Escape"){if(o&&!this.campoTexto)return;this.campoTexto?this.cancelarTexto():e.nos>0?this.reiniciar():this.desativar(),t.preventDefault();return}o||(t.key==="Enter"?(this.concluir(),t.preventDefault()):(t.key==="Backspace"||(t.ctrlKey||t.metaKey)&&t.key.toLowerCase()==="z")&&(e.desfazer()&&this.atualizar(),t.preventDefault()))});this.dep=t}get ferramenta(){var t;return((t=this.sessao)==null?void 0:t.ferramenta)??null}get ativo(){return this.sessao!==null}get nos(){var t;return((t=this.sessao)==null?void 0:t.nos)??0}desfazerVertice(){var t;return(t=this.sessao)!=null&&t.desfazer()?(this.atualizar(),!0):!1}ativar(t,e={}){var s;const o=(s=this.sessao)==null?void 0:s.ferramenta;this.desligar(),o&&this.dep.aoDesativar(o),this.limparMedicao();const i=this.dep.map;this.fechar=!!e.fechar,this.sessao=new Gt(t,this.fechar),i.getPane(et)||(i.createPane(et).style.zIndex="8500"),this.grupo=y.layerGroup().addTo(i),this.marcas=y.layerGroup().addTo(this.grupo);const a=i.getContainer();a.classList.add(ze),a.style.cursor=t==="conta-gotas"?"copy":"crosshair",i.on("click",this.aoClicar),i.on("dblclick",this.aoDuploClique),i.on("mousemove",this.aoMover),i.on("mousedown",this.aoPressionar),i.on("mouseup",this.aoSoltar),window.addEventListener("keydown",this.aoTecla),this.montarHud(),this.atualizar()}desativar(){var e;const t=(e=this.sessao)==null?void 0:e.ferramenta;t&&(this.desligar(),this.dep.aoDesativar(t))}limparMedicao(){var t;(t=this.medicao)==null||t.remove(),this.medicao=null}desligar(){var o,i;const t=this.dep.map;t.off("click",this.aoClicar),t.off("dblclick",this.aoDuploClique),t.off("mousemove",this.aoMover),t.off("mousedown",this.aoPressionar),t.off("mouseup",this.aoSoltar),window.removeEventListener("keydown",this.aoTecla);const e=t.getContainer();e.classList.remove(ze),e.style.cursor="",(o=this.grupo)==null||o.remove(),this.grupo=null,this.previa=null,this.marcas=null,this.marcadorSnap=null,(i=this.hud)==null||i.remove(),this.hud=null,this.campoTexto=null,this.sessao=null,this.arrastando=!1,this.ultimoClique=null}coordenada(t){const e=[t.latlng.lat,t.latlng.lng];if(!this.dep.snapAtivo())return this.esconderSnap(),e;const o=this.dep.buscarSnap(e);return o?(this.mostrarSnap(o.coordenada),o.coordenada):(this.esconderSnap(),e)}repetido(t){const e=this.ultimoClique,o=Date.now(),i=t.containerPoint,a=!!e&&Math.hypot(e.x-i.x,e.y-i.y)<=Ea&&o-e.t<=Ia;return this.ultimoClique={x:i.x,y:i.y,t:o},a}fechaNoPrimeiroVertice(t){const e=this.sessao,o=e==null?void 0:e.primeiro;if(!e||!o||!e.fechaNoPrimeiro)return!1;const i=this.dep.map.latLngToContainerPoint(o);if(Math.hypot(i.x-t.containerPoint.x,i.y-t.containerPoint.y)>_a)return!1;const a=e.concluirFechando();return a&&this.finalizar(a),!!a}concluir(){const t=this.sessao;if(!t)return;const e=t.concluir();e&&this.finalizar(e)}botaoDireito(){const t=this.sessao;if(t){if(this.campoTexto){this.cancelarTexto();return}t.podeConcluir?this.concluir():t.nos>0&&t.desfazer()?this.atualizar():this.desativar()}}reiniciar(){var e;const t=(e=this.sessao)==null?void 0:e.ferramenta;t&&(this.sessao=new Gt(t,this.fechar),this.ultimoClique=null,this.arrastando=!1,this.atualizar())}finalizar(t){const e=this.sessao.ferramenta,o=e==="medir-distancia"||e==="medir-area"?this.mostrarMedicao(t,e):null;this.sessao=new Gt(e,this.fechar),this.ultimoClique=null,this.atualizar(),o&&this.dep.aoMedir(o),this.dep.aoGeometria(e,t)}pedirTexto(t){var o,i;if(!this.hud||(i=(o=this.dep).aoSolicitarTexto)!=null&&i.call(o,t)||!this.hud)return;const e=document.createElement("input");e.type="text",e.placeholder="Texto…",e.style.cssText="padding:3px 6px;border-radius:4px;border:1px solid #475569;background:#0f172a;color:#fff;min-width:160px",e.addEventListener("keydown",a=>{if(a.stopPropagation(),a.key==="Enter"){const s=e.value.trim();this.cancelarTexto(),s&&this.finalizar({tipo:"Text",coordenada:t,texto:s})}else a.key==="Escape"&&this.cancelarTexto()}),this.campoTexto=e,this.hud.insertBefore(e,this.hud.querySelector('[data-campo="dica"]')),e.focus()}cancelarTexto(){var t;(t=this.campoTexto)==null||t.remove(),this.campoTexto=null}atualizar(){const t=this.sessao;if(!t||!this.grupo||!this.marcas)return;this.previa&&(this.grupo.removeLayer(this.previa),this.previa=null);const e=t.previa();e&&(this.previa=this.desenharGeometria(e,!0),this.grupo.addLayer(this.previa)),this.marcas.clearLayers();const o=t.ferramenta==="caneta"?t.ancoras.map(i=>i.ponto):t.pontos;if(t.ferramenta==="caneta")for(const i of t.ancoras){if(!i.alca)continue;const a=Oe(i.ponto,i.alca);this.marcas.addLayer(y.polyline([a,i.alca],{pane:et,color:dt,weight:1,opacity:.8,interactive:!1}));for(const s of[a,i.alca])this.marcas.addLayer(y.circleMarker(s,{pane:et,radius:3,color:dt,weight:1,fillColor:"#fff",fillOpacity:1,interactive:!1}))}for(const i of o)this.marcas.addLayer(y.circleMarker(i,{pane:et,radius:4,color:"#111",weight:1,fillColor:dt,fillOpacity:1,interactive:!1}));this.atualizarHud(e)}desenharGeometria(t,e){const o={pane:et,color:dt,weight:2,dashArray:e?"6 4":void 0,fillColor:dt,fillOpacity:.15,interactive:!1},i=ti(t,o);if(i)return i;if(t.tipo==="Polygon")return y.polygon(t.aneis,o);if(t.tipo==="Circle")return y.circle(t.centro,{...o,radius:t.raioMetros});if(t.tipo==="LineString")return y.polyline(t.coordenadas,o);const a=(t.tipo==="Point",t.coordenada);return y.circleMarker(a,{...o,radius:5})}mostrarMedicao(t,e){this.limparMedicao();const o=y.layerGroup().addTo(this.dep.map);this.medicao=o,o.addLayer(this.desenharGeometria(t,!1));const i=t.tipo==="Polygon"?t.aneis[0]:t.tipo==="LineString"?t.coordenadas:[],a=t.tipo==="Polygon",s=(l,d)=>{const h=document.createElement("div");h.textContent=d,h.style.cssText="white-space:nowrap;font:600 11px sans-serif;color:#fff;background:rgba(15,23,42,.85);padding:1px 5px;border-radius:3px;transform:translate(-50%,-50%)",o.addLayer(y.marker(l,{pane:et,interactive:!1,keyboard:!1,icon:y.divIcon({className:"custom-leaflet-marker",iconSize:void 0,html:h})}))},r=a?i.length:i.length-1;for(let l=0;l<r;l++){const d=i[l],h=i[(l+1)%i.length];s([(d[0]+h[0])/2,(d[1]+h[1])/2],G(st(d,h)))}const c={tipo:e==="medir-area"?"area":"distancia",pontos:i,comprimentoM:kt(i,!1)};if(t.tipo==="Polygon")c.areaM2=Q(t)??0,c.perimetroM=tt(t)??0;else if(e==="medir-distancia"&&i.length>=3){const l={tipo:"Polygon",aneis:[i]};c.areaM2=Q(l)??0,c.perimetroM=tt(l)??0}return c}mostrarSnap(t){this.grupo&&(this.marcadorSnap?this.marcadorSnap.setLatLng(t):this.marcadorSnap=y.marker(t,{pane:et,interactive:!1,keyboard:!1,icon:y.divIcon({className:"custom-leaflet-marker cm-snap",iconSize:[18,18],html:'<div style="width:18px;height:18px;box-sizing:border-box;border:2px solid #22d3ee;transform:rotate(45deg);border-radius:2px"></div>'})}).addTo(this.grupo))}esconderSnap(){var t;this.marcadorSnap&&((t=this.grupo)==null||t.removeLayer(this.marcadorSnap),this.marcadorSnap=null)}montarHud(){const t=this.sessao;if(!t)return;const e=document.createElement("div");e.id=Zi,e.style.cssText=Ge+"gap:10px;align-items:center;padding:6px 12px;border-radius:8px;background:rgba(15,23,42,.92);color:#fff;font:12px var(--ui-fonte-base,sans-serif);border:1px solid rgba(255,255,255,.2);pointer-events:auto";const o=r=>{const c=document.createElement("span");return c.dataset.campo=r,c},i=document.createElement("strong");i.textContent=Ta[t.ferramenta];const a=o("dica");a.style.opacity=".7",a.textContent=Da[t.ferramenta];const s=(r,c,l=!1)=>{const d=document.createElement("button");return d.type="button",d.textContent=r,d.style.cssText=`padding:3px 10px;border-radius:4px;border:1px solid ${l?dt:"rgba(255,255,255,.3)"};background:${l?dt:"transparent"};color:${l?"#111":"#fff"};cursor:pointer;font-weight:600`,d.addEventListener("click",c),d};e.append(i,o("nos"),o("medida"),a),t.ehSequencial&&e.append(s("Concluir",()=>this.concluir(),!0)),e.append(s("Sair",()=>this.desativar())),y.DomEvent.disableClickPropagation(e),y.DomEvent.disableScrollPropagation(e),this.dep.map.getContainer().appendChild(e),this.hud=e}atualizarHud(t){const e=this.sessao;if(!this.hud||!e)return;const o=this.hud.querySelector('[data-campo="nos"]'),i=this.hud.querySelector('[data-campo="medida"]');if(o&&(o.textContent=e.nos>0?`Nós: ${e.nos}`:""),!i)return;let a="";if((t==null?void 0:t.tipo)==="Polygon")a=`Área: ${rt(Q(t)??0)} · Perímetro: ${G(tt(t)??0)}`;else if((t==null?void 0:t.tipo)==="LineString"){if(a=`Extensão: ${G(e.comprimentoMetros())}`,e.ferramenta==="medir-distancia"&&e.nos>=3&&t.coordenadas.length>=3){const s={tipo:"Polygon",aneis:[t.coordenadas]};a+=` · Área: ${rt(Q(s)??0)} · Perímetro: ${G(tt(s)??0)}`}}else(t==null?void 0:t.tipo)==="Circle"&&(a=`Raio: ${G(t.raioMetros)}`);i.textContent=a}clicarEm(t){const e=this.sessao;if(!e)return;const o=e.clicar(t);o.concluida?o.concluida.tipo==="Text"?this.pedirTexto(t):this.finalizar(o.concluida):this.atualizar()}moverPara(t){var e;(e=this.sessao)==null||e.mover(t),this.atualizar()}}const Ki=6,me=(n,t)=>Math.hypot(n.x-t.x,n.y-t.y);function Lo(n,t,e){const o=e.x-t.x,i=e.y-t.y,a=o*o+i*i,s=a===0?0:Math.max(0,Math.min(1,((n.x-t.x)*o+(n.y-t.y)*i)/a));return Math.hypot(n.x-(t.x+s*o),n.y-(t.y+s*i))}function $a(n,t){const e=n.geometria;if(e.tipo!=="Polygon")return 0;const o=e.aneis[0].map(t),i=o.map(s=>s.x),a=o.map(s=>s.y);return(Math.max(...i)-Math.min(...i))*(Math.max(...a)-Math.min(...a))}function Ee(n,t,e,o=Ki){let i=null,a=null,s=null;for(const r of t){if(r.excluida||r.oculta)continue;const c=r.geometria;if(c.tipo==="Point"||c.tipo==="Text"){const l=me(n,e(c.coordenada));l<=o+2&&(!i||l<i.d)&&(i={f:r,d:l})}else if(c.tipo==="LineString"){let l=1/0;for(const d of j(c)){const h=d.map(e);for(let u=1;u<h.length;u++)l=Math.min(l,Lo(n,h[u-1],h[u]))}l<=o&&(!a||l<a.d)&&(a={f:r,d:l})}else if(c.tipo==="Circle"){const l=e(c.centro),d=e([c.centro[0]+c.raioMetros/111320,c.centro[1]]),h=me(l,d);if(me(n,l)<=h){const u=Math.PI*h*h;(!s||u<s.a)&&(s={f:r,a:u})}}else{const l=c.aneis[0].map(e);let d=1/0;for(const[u,m]of Ve(c))d=Math.min(d,Lo(n,l[u],l[m]));if(Be([n.y,n.x],[l.map(u=>[u.y,u.x]),...c.aneis.slice(1).map(u=>u.map(e).map(m=>[m.y,m.x]))])||d<=o){const u=$a(r,e);(!s||u<s.a)&&(s={f:r,a:u})}}}return(i==null?void 0:i.f)??(a==null?void 0:a.f)??(s==null?void 0:s.f)??null}const H="feicoes",qa=new Set(["ponto","linha","poligono","retangulo","elipse","poligono-regular","estrela","circulo","texto","caneta"]);class Na{constructor(t){p(this,"selecao");p(this,"popup");p(this,"editor",null);p(this,"snap");p(this,"desenho",null);p(this,"camadaDesenho",null);p(this,"estiloDesenho",{});p(this,"sequenciaId",0);p(this,"regra");p(this,"cacheOficiais",new WeakMap);p(this,"posicoes",new Map);p(this,"cursores");p(this,"hoverId",null);p(this,"hoverAgendado",!1);p(this,"margensHud",{});p(this,"aceitarOrigem",!1);p(this,"opcoesPopup",{copiarParaAreaDeTransferencia:!0});this.contexto=t,this.regra=t.regra??new Zt,this.cursores=new mi(()=>this.contexto.obterMapa()),this.snap=new Sa({aoMudar:e=>{var o,i,a;this.contexto.emitir("cad-snap",e),(o=this.editor)==null||o.atualizarSnapNoHud(),(a=(i=this.contexto).aoSnapMudar)==null||a.call(i,e.ligado)}}),this.popup=new Ai({obterMapa:()=>this.contexto.obterMapa(),obterCamada:e=>this.contexto.obterLayerManager().getLayerDef(e),aoAcao:(e,o)=>this.tratarAcaoPopup(e,o)}),this.selecao=new gi({obterFeicao:e=>this.buscar(e.camadaId,e.id),aplicarVisual:(e,o)=>{const i=this.contexto.obterLayerManager().getLayerInstance(e),a=F.get(H);i&&a&&a.aplicarSelecao(i,o)},aoSelecionar:e=>{var o;if(this.contexto.emitir("cad-selecao",{feicoes:e}),(o=this.editor)!=null&&o.ativo){const i=this.editor.feicao;e.length===1&&e[0].id===i.id&&e[0].camadaId===i.camadaId||this.editor.parar();return}e.length===1?this.popup.abrir(e[0]):this.popup.fechar()},aoSelecionarUma:e=>this.contexto.emitir("cad-feicao-selecionada",{feicao:e}),visivel:e=>this.selecionavelAgora(e),selecionavel:e=>!e.oculta})}aposDados(){var o;if(this.selecao.reconciliar(),(o=this.editor)!=null&&o.ativo){const i=this.editor.feicao,a=this.buscar(i.camadaId,i.id);!a||a.excluida?this.editor.parar():a!==i&&this.editor.sincronizar(a)}const t=this.popup.aberto;if(!t)return;const e=this.buscar(t.camadaId,t.id);e&&!e.excluida?this.popup.atualizar(e):this.popup.fechar()}lista(t){var o;const e=(o=this.contexto.obterLayerManager().getLayerDef(t))==null?void 0:o.dados;return Array.isArray(e==null?void 0:e.feicoes)?e.feicoes:[]}posicaoDe(t){const e=this.lista(t),o=this.posicoes.get(t);if(o&&o.lista===e)return o.pos;const i=new Map;for(let a=0;a<e.length;a++)i.set(e[a].id,a);return this.posicoes.set(t,{lista:e,pos:i}),i}buscar(t,e){const o=this.lista(t),i=this.posicaoDe(t).get(e),a=i===void 0?void 0:o[i];if(a&&a.id===e)return a;if(i===void 0)return;this.posicoes.delete(t);const s=this.posicaoDe(t).get(e);return s===void 0?void 0:o[s]}garantirCamada(t,e){const o=this.contexto.obterLayerManager(),i=o.getLayerDef(t);if(i&&i.tipo!==H)return!1;const a=o.getOrCreateLayer(t,H,(e==null?void 0:e.nome)??t);return e!=null&&e.nome&&(a.nome=e.nome),e!=null&&e.estilo&&(a.estilo={...a.estilo,...e.estilo}),(e==null?void 0:e.interativo)!==void 0&&(a.interativo=e.interativo),(e==null?void 0:e.zIndex)!==void 0&&o.setLayerZIndex(t,e.zIndex),(e==null?void 0:e.opacidade)!==void 0&&o.setLayerOpacity(t,e.opacidade),o.ensurePanes(),!0}opcoesNormalizacao(){return{aceitarOrigem:this.aceitarOrigem}}definirFeicoes(t,e,o){if(!this.garantirCamada(t,o))return{aceitas:0,recusadas:["camada existente não é de feições"]};const i=[],a=new Map;return(Array.isArray(e)?e:[]).forEach((s,r)=>{const c=Rt(s,t,this.opcoesNormalizacao());c?a.set(c.id,c):i.push(String((s==null?void 0:s.id)??`#${r}`))}),this.contexto.obterLayerManager().setLayerData(t,{feicoes:[...a.values()]}),this.aposDados(),{aceitas:a.size,recusadas:i}}adicionarFeicao(t,e,o){return this.aplicar(t,{adicionar:[e]},o).adicionadas[0]??null}atualizarFeicao(t,e,o,i){return this.aplicar(t,{atualizar:[{...o,id:e}]},i).atualizadas[0]??null}substituir(t,e){this.contexto.obterLayerManager().getLayerDef(t)&&this.aplicar(t,{adicionar:[e]})}removerFeicao(t,e){return this.aplicar(t,{remover:[e]}).resultado.removidas>0}aplicarLote(t,e,o){return this.aplicar(t,e,o).resultado}mesclar(t,e,o,i){const a=i&&e.propriedades&&typeof e.propriedades=="object"?{...e.propriedades}:{...t.propriedades,...e.propriedades};return Rt({...t,...e,id:t.id,estilo:{...t.estilo,...e.estilo},propriedades:a},o,this.opcoesNormalizacao())}aplicar(t,e,o={}){const i={adicionadas:0,atualizadas:0,removidas:0,recusadas:[]},a=[],s=[],r=Array.isArray(e==null?void 0:e.adicionar)?e.adicionar:[],c=Array.isArray(e==null?void 0:e.atualizar)?e.atualizar:[],l=Array.isArray(e==null?void 0:e.remover)?e.remover:[],d=(L,w)=>String((L==null?void 0:L.id)??`#${w}`),h=[],u=L=>(i.recusadas.push(...h),L),m=[];r.forEach((L,w)=>{const I=Rt(L,t,this.opcoesNormalizacao());I?m.push(I):h.push(d(L,w))});const f=this.contexto.obterLayerManager(),g=f.getLayerDef(t);if(!(!g||g.tipo===H)||!g&&m.length===0)return c.forEach((L,w)=>i.recusadas.push(d(L,w))),m.forEach(L=>h.push(L.id)),u({resultado:i,adicionadas:a,atualizadas:s});if((m.length>0||g)&&!this.garantirCamada(t,o))return m.forEach(L=>h.push(L.id)),u({resultado:i,adicionadas:a,atualizadas:s});const A=this.lista(t),M=this.posicaoDe(t),C=A.slice(),z=[],P=[];let v=!1;for(const L of l){const w=String(L),I=M.get(w);I===void 0||C[I]===null||(C[I]=null,z.push(w),i.removidas++,v=!0)}c.forEach((L,w)=>{const I=L&&typeof L=="object"&&L.id!==void 0&&L.id!==null?String(L.id):"",_=M.get(I),O=_===void 0?null:C[_],T=O?this.mesclar(O,L,t,!!o.substituirPropriedades):null;if(!T||_===void 0){i.recusadas.push(I||d(L,w));return}C[_]=T,P.push(T),s.push(T),i.atualizadas++});for(const L of m){const w=M.get(L.id);w!==void 0&&C[w]!==null?C[w]=L:(M.set(L.id,C.length),C.push(L)),P.push(L),a.push(L),i.adicionadas++}if(P.length===0&&z.length===0)return u({resultado:i,adicionadas:a,atualizadas:s});const b=v?C.filter(L=>L!==null):C,E={feicoes:b,delta:{base:A,mudadas:P,removidas:z}};return f.setLayerData(t,E),delete E.delta,v?this.posicoes.delete(t):this.posicoes.set(t,{lista:b,pos:M}),this.aposDados(),u({resultado:i,adicionadas:a,atualizadas:s})}obterFeicoes(t){return this.lista(t).map(e=>({...e}))}tratarAcaoCamada(t,e){var o;if(t==="feicao-movida")return this.substituir(e.camadaId,e.feicao),"cad-feicao-atualizada";if(t==="feicao-clique"){if((o=this.desenho)!=null&&o.ativo)return null;const i={camadaId:e.camadaId,id:e.feicao.id};return e.aditivo?this.selecao.alternar(i):this.selecao.selecionar([i]),"cad-feicao-clique"}return null}selecionarFeicoes(t,e=!1){this.selecao.selecionar(Array.isArray(t)?t:[],e)}alternarSelecaoFeicao(t){this.selecao.alternar(t)}limparSelecaoFeicoes(){this.selecao.limpar()}aoPedirLimpeza(){var t,e;(t=this.desenho)!=null&&t.ativo||((e=this.editor)!=null&&e.ativo?this.editor.parar():this.selecao.limpar())}obterFeicoesSelecionadas(){return this.selecao.obter()}selecionarNoLaco(t){var o;const e=[];for(const i of this.contexto.obterLayerManager().getActiveSelectableLayers())if(i.tipo===H)for(const a of this.lista(i.id))this.desenhada(a)&&Mi(a,t)&&e.push({camadaId:i.id,id:a.id});(o=this.desenho)==null||o.desativar(),this.selecao.selecionar(e)}selecionarNaCaixa(t,e,o){const i=this.contexto.obterMapa();if(!i)return;const a=r=>i.latLngToContainerPoint(r),s=[];for(const r of this.contexto.obterLayerManager().getActiveSelectableLayers())if(r.tipo===H)for(const c of this.lista(r.id))this.desenhada(c)&&Si(c,t,a,e)&&s.push({camadaId:r.id,id:c.id});o?this.selecao.alternarVarias(s):this.selecao.selecionar(s)}definirMargensPopup(t){this.popup.definirMargens(t)}fecharPopup(){this.popup.fechar()}definirOpcoesPopup(t){this.opcoesPopup={...this.opcoesPopup,...t}}obterOpcoesPopup(){return{...this.opcoesPopup}}definirMargensHud(t){this.margensHud={...this.margensHud,...t},this.aplicarMargensHud()}aplicarMargensHud(){const t=this.contexto.obterMapa();t&&Vi(t.getContainer(),this.margensHud)}get regraVersoes(){return this.regra}oficiaisDe(t){const e=this.lista(t);let o=this.cacheOficiais.get(e);return o||(o=Zt.oficiais(e),this.cacheOficiais.set(e,o)),o}visivelPorVersao(t){const e=this.contexto.obterLayerManager().getLayerInstance(t.camadaId),o=F.get(H);return e&&o?o.feicaoVisivel(e,t):this.regra.visivel(t,this.oficiaisDe(t.camadaId))}desenhada(t){return!t.excluida&&!t.oculta&&this.visivelPorVersao(t)}selecionavelAgora(t){var o;const e=(o=this.editor)!=null&&o.ativo?this.editor.feicao:null;return e&&e.id===t.id&&e.camadaId===t.camadaId?!0:!t.oculta&&this.visivelPorVersao(t)}aplicarVersoes(){const t=this.contexto.obterLayerManager(),e=F.get(H);for(const o of t.getLayers()){if(o.tipo!==H)continue;const i=t.getLayerInstance(o.id);i&&e&&e.reavaliarVersoes(i)}this.aposDados()}get previasGlobais(){return this.regra.global}definirPreviasGlobais(t){const e=!!t;this.regra.global!==e&&(this.regra.global=e,this.aplicarVersoes(),this.contexto.emitir("cad-previas",{global:e}))}alternarPreviasGlobais(){this.definirPreviasGlobais(!this.regra.global)}alternarPrevia(t,e){const o=this.buscar(t,e);if(!o)return null;const i=nt(o),a=this.regra.alternarIndividual(t,i);return this.aplicarVersoes(),this.contexto.emitir("cad-previas",{camadaId:t,entidadeId:i,ativa:a}),a}previaSolicitada(t,e){const o=this.buscar(t,e);return!!o&&this.regra.previaSolicitada(o)}atualizarCursorRemoto(t,e){const o=X(e,this.opcoesNormalizacao());return!!o&&this.cursores.atualizar(t,o)}removerCursorRemoto(t){return this.cursores.remover(t)}limparCursoresRemotos(){this.cursores.limpar()}get cursoresRemotos(){return this.cursores.quantidade}garantirVisivel(t){const e=this.contexto.obterLayerManager(),o=e.getLayerDef(t.camadaId);if(o&&!o.visivel&&e.setLayerVisibility(t.camadaId,!0),!this.visivelPorVersao(t)){const i=nt(t);this.regra.definirIndividual(t.camadaId,i,!0),this.aplicarVersoes(),this.contexto.emitir("cad-previas",{camadaId:t.camadaId,entidadeId:i,ativa:!0})}}limitesDe(t){let e=1/0,o=1/0,i=-1/0,a=-1/0;for(const s of t){const[[r,c],[l,d]]=De(s.geometria);r<e&&(e=r),c<o&&(o=c),l>i&&(i=l),d>a&&(a=d)}return Number.isFinite(e)?[[e,o],[i,a]]:null}enquadrar(t){const e=this.contexto.obterMapa(),o=this.limitesDe(t);return!e||!o?!1:(o[0][0]===o[1][0]&&o[0][1]===o[1][1]?e.flyTo([o[0][0],o[0][1]],Math.max(e.getZoom(),17)):e.fitBounds(o,{padding:[60,60],maxZoom:18}),!0)}zoomParaFeicao(t,e){const o=this.buscar(t,e);return!o||o.excluida?!1:(this.garantirVisivel(o),this.enquadrar([o]))}zoomParaFeicoes(t){const e=[];for(const o of Array.isArray(t)?t:[]){const i=this.buscar(o.camadaId,o.id);i&&!i.excluida&&(this.garantirVisivel(i),e.push(i))}return e.length>0&&this.enquadrar(e)}ajustarTudo(){const t=[];for(const e of this.contexto.obterLayerManager().getLayers())e.tipo!==H||!e.visivel||t.push(...this.lista(e.id).filter(o=>this.desenhada(o)));return this.enquadrar(t)}ajustarCamada(t){const e=this.contexto.obterLayerManager(),o=e.getLayerDef(t);return!o||o.tipo!==H?!1:(o.visivel||e.setLayerVisibility(t,!0),this.enquadrar(this.lista(t).filter(i=>this.desenhada(i))))}feicaoSob(t,e){const o=this.contexto.obterMapa();if(!o)return null;const i=o.getContainer().getBoundingClientRect(),a=y.point(t-i.left,e-i.top),s=o.containerPointToLatLng(a),r=[s.lat,s.lng];return{feicao:Ee({x:a.x,y:a.y},this.candidatasEm(r,8),l=>o.latLngToContainerPoint(l)),coordenada:r}}aoMoverMouse(t){var r,c;if(t.buttons!==0||!!((r=this.desenho)!=null&&r.ativo)||!!((c=this.editor)!=null&&c.ativo)){this.hoverId!==null&&(this.hoverId=null,this.contexto.emitir("cad-feicao-hover",{feicao:null}));return}if(this.hoverAgendado)return;this.hoverAgendado=!0;const{clientX:o,clientY:i}=t;let a=!1;const s=()=>{if(a)return;a=!0,this.hoverAgendado=!1;const l=this.feicaoSob(o,i),d=l!=null&&l.feicao?`${l.feicao.camadaId}\0${l.feicao.id}`:null;d!==this.hoverId&&(this.hoverId=d,this.contexto.emitir("cad-feicao-hover",{feicao:(l==null?void 0:l.feicao)??null}))};typeof requestAnimationFrame=="function"&&requestAnimationFrame(s),setTimeout(s,100)}menuContexto(t){var o;if((o=this.desenho)!=null&&o.ativo){this.desenho.botaoDireito();return}const e=this.feicaoSob(t.clientX,t.clientY);e&&this.contexto.emitir("cad-feicao-menu",{feicao:e.feicao,coordenada:e.coordenada,x:t.clientX,y:t.clientY})}destruir(){var t;(t=this.desenho)==null||t.desativar(),this.desenho=null,this.cursores.limpar(),this.hoverId=null}tratarAcaoPopup(t,e){var o,i,a;if(t==="zoom"&&this.zoomParaFeicao(e.camadaId,e.id),t==="vertices"&&this.iniciarEdicao(e.camadaId,e.id),t==="copiar"&&this.opcoesPopup.copiarParaAreaDeTransferencia){const[s,r]=Et(e);(a=(i=(o=globalThis.navigator)==null?void 0:o.clipboard)==null?void 0:i.writeText(`${s.toFixed(6)}, ${r.toFixed(6)}`))==null||a.catch(()=>{})}this.contexto.emitir("cad-feicao-acao",{acao:t,feicao:e})}get snapLigado(){return this.snap.ligado}get snapAtivo(){return this.snap.ativo}definirSnap(t){this.snap.definir(!!t)}alternarSnap(){this.snap.alternar()}conectarTeclado(){this.snap.conectar()}desconectarTeclado(){this.snap.desconectar()}candidatasEm(t,e){const o=this.contexto.obterMapa(),i=this.contexto.obterLayerManager(),a=F.get(H);if(!o||!a)return[];const s=o.latLngToContainerPoint(t),r=o.containerPointToLatLng([s.x-e,s.y+e]),c=o.containerPointToLatLng([s.x+e,s.y-e]),l={minLon:Math.min(r.lng,c.lng),maxLon:Math.max(r.lng,c.lng),minLat:Math.min(r.lat,c.lat),maxLat:Math.max(r.lat,c.lat)},d=[];for(const h of i.getLayers()){if(h.tipo!==H||!h.visivel)continue;const u=i.getLayerInstance(h.id);u&&d.push(...a.consultarProximas(u,l).filter(m=>this.desenhada(m)))}return d}buscarSnapEm(t,e){const o=this.contexto.obterMapa();if(!o)return null;const i=o.latLngToContainerPoint(t),a=this.candidatasEm(t,je);return Ui({x:i.x,y:i.y},a,s=>o.latLngToContainerPoint(s),{},e)}get editando(){var t;return!!((t=this.editor)!=null&&t.ativo)}iniciarEdicao(t,e){var d,h;const o=this.buscar(t,e);if(!o||o.excluida)return{ok:!1,motivo:"inexistente"};const i=this.contexto.obterLayerManager().getLayerDef(t),a=ki(o,!!(i!=null&&i.bloqueada));if(a)return this.contexto.emitir("cad-edicao-recusada",{motivo:a,feicao:o}),{ok:!1,motivo:a};const s=this.contexto.obterMapa();if(!s)return{ok:!1,motivo:"sem-mapa"};(d=this.desenho)==null||d.desativar(),(h=this.editor)==null||h.parar(),this.aplicarMargensHud(),this.selecao.selecionar([{camadaId:t,id:e}]),this.popup.fechar();const r=this.contexto.obterLayerManager(),c=F.get(H),l=new ji({map:s,snapLigado:()=>this.snap.ativo,alternarSnap:()=>this.snap.alternar(),buscarSnap:(u,m)=>this.buscarSnapEm(u,m),previsualizar:u=>{const m=r.getLayerInstance(u.camadaId);m&&c&&c.previsualizar(m,u)},aoGesto:u=>{this.substituir(u.camadaId,u),this.contexto.emitir("cad-feicao-atualizada",{camadaId:u.camadaId,feicao:u})},aoEncerrar:u=>{this.editor=null;const m=this.buscar(u.camadaId,u.id)??u;this.contexto.emitir("cad-edicao-concluida",{feicao:m});const f=this.selecao.obter();f.length===1&&this.popup.abrir(f[0])}});return this.editor=l,l.iniciar(o),this.contexto.emitir("cad-edicao-iniciada",{feicao:o}),{ok:!0}}pararEdicao(){var t;(t=this.editor)==null||t.parar()}get ferramentaAtiva(){var t;return((t=this.desenho)==null?void 0:t.ferramenta)??null}definirCamadaDesenho(t){this.camadaDesenho=t||null}get camadaDeDesenho(){return this.camadaDesenho}definirEstiloDesenho(t){this.estiloDesenho={...t}}obterEstiloDesenho(){return{...this.estiloDesenho}}alternarFerramenta(t){var e;return((e=this.desenho)==null?void 0:e.ferramenta)===t?(this.desenho.desativar(),{ok:!0}):this.ativarFerramenta(t)}ativarFerramenta(t,e={}){var a,s,r;if(!Ue(t))return{ok:!1,motivo:"ferramenta-invalida"};const o=this.contexto.obterMapa();if(!o)return{ok:!1,motivo:"sem-mapa"};if(qa.has(t)){const c=this.motivoCamadaDesenhoInvalida();if(c)return this.contexto.emitir("cad-desenho-recusado",{ferramenta:t,motivo:c}),{ok:!1,motivo:c}}(a=this.editor)==null||a.parar(),this.popup.fechar(),this.aplicarMargensHud(),this.desenho||(this.desenho=new Yi({map:o,buscarSnap:c=>this.buscarSnapEm(c),snapAtivo:()=>this.snap.ativo,aoGeometria:(c,l)=>this.concluirFerramenta(c,l),aoMedir:c=>this.contexto.emitir("cad-medicao",c),aoAmostrar:c=>this.amostrarEstilo(c),aoSolicitarTexto:c=>this.solicitarTexto(c),aoDesativar:()=>{var c,l;this.contexto.emitir("cad-ferramenta",{ferramenta:null}),(l=(c=this.contexto).aoFerramenta)==null||l.call(c,null)}})),this.desenho.ativar(t,e),this.contexto.emitir("cad-ferramenta",{ferramenta:t}),(r=(s=this.contexto).aoFerramenta)==null||r.call(s,t);const i=e.iniciarEm?X(e.iniciarEm,this.opcoesNormalizacao()):null;return i&&this.desenho.clicarEm(i),{ok:!0}}desativarFerramenta(){var t;(t=this.desenho)==null||t.desativar()}limparMedicao(){var t;(t=this.desenho)==null||t.limparMedicao()}get nosDesenho(){var t;return((t=this.desenho)==null?void 0:t.nos)??0}desfazerVerticeDesenho(){var t;return((t=this.desenho)==null?void 0:t.desfazerVertice())??!1}definirAtalhoSnap(t){this.snap.atalhoS=t}motivoCamadaDesenhoInvalida(){if(!this.camadaDesenho)return"sem-camada";const t=this.contexto.obterLayerManager().getLayerDef(this.camadaDesenho);return t&&t.tipo!==H?"camada-invalida":t!=null&&t.bloqueada?"camada-bloqueada":null}novoId(t,e){const o=new Set(this.lista(e).map(a=>a.id));let i;do this.sequenciaId++,i=`${t}-${Date.now().toString(36)}${this.sequenciaId.toString(36)}`;while(o.has(i));return i}idLivre(t,e){const o=new Set(this.lista(t).map(a=>a.id));if(!o.has(e))return e;let i=2;for(;o.has(`${e}_${i}`);)i++;return`${e}_${i}`}solicitarTexto(t){const e={coordenada:t,camadaId:this.camadaDesenho,concluir:o=>{const i=typeof o=="string"?o.trim():"";return i?this.concluirFerramenta("texto",{tipo:"Text",coordenada:t,texto:i}):null}};return this.contexto.emitir("cad-texto-solicitado",e,!0)===!0}concluirFerramenta(t,e){if(t==="dividir")return e.tipo==="LineString"&&this.dividirComLinha(e.coordenadas),null;if(t==="medir-distancia"||t==="medir-area")return null;if(t==="selecao-laco")return e.tipo==="Polygon"&&this.selecionarNoLaco(e.aneis[0]),null;const o=this.camadaDesenho;if(!o)return null;const i=Object.keys(this.estiloDesenho).length>0,a=this.adicionarFeicao(o,{id:this.novoId(t,o),geometria:e,estilo:i?{...this.estiloDesenho}:void 0,propriedades:{}});return a?this.contexto.emitir("cad-feicao-criada",{camadaId:o,feicao:a}):this.contexto.emitir("cad-desenho-recusado",{ferramenta:t,motivo:"geometria-invalida"}),a}amostrarEstilo(t){const e=this.contexto.obterMapa();if(!e)return;const o=e.latLngToContainerPoint(t),i=this.candidatasEm(t,8),a=Ee({x:o.x,y:o.y},i,d=>e.latLngToContainerPoint(d));if(!a){this.contexto.emitir("cad-conta-gotas",{cor:"",feicao:null,estilo:{}});return}const s=this.contexto.obterLayerManager().getLayerDef(a.camadaId),r=a.estilo??{},c={},l=r.corTraco??(s==null?void 0:s.estilo.corPrimaria);l&&(c.corTraco=l),r.corPreenchimento&&(c.corPreenchimento=r.corPreenchimento),r.espessuraTraco!==void 0&&(c.espessuraTraco=r.espessuraTraco),r.opacidadePreenchimento!==void 0&&(c.opacidadePreenchimento=r.opacidadePreenchimento),r.dashArray&&(c.dashArray=r.dashArray),this.estiloDesenho={...this.estiloDesenho,...c},this.contexto.emitir("cad-conta-gotas",{cor:l??r.corPreenchimento??"",feicao:a,estilo:c})}dividirComLinha(t){var l;const e=this.contexto.obterLayerManager(),o=d=>(this.contexto.emitir("cad-divisao-falhou",{motivo:d}),!1),i=this.selecao.obter().filter(d=>d.geometria.tipo==="Polygon");let a=i;if(a.length===0){a=[];for(const d of e.getActiveSelectableLayers())d.tipo===H&&a.push(...this.lista(d.id).filter(h=>h.geometria.tipo==="Polygon"&&this.desenhada(h)))}if(a.length===0)return o(i.length===0&&this.selecao.obter().some(d=>wt(d.geometria))?"multiparte":"nenhum-poligono");const s=d=>{var h;return!!d.bloqueada||!!((h=e.getLayerDef(d.camadaId))!=null&&h.bloqueada)},r=a.filter(d=>!s(d)&&d.geometria.tipo==="Polygon"&&d.geometria.aneis.length===1);if(r.length===0)return o(a.some(s)?"bloqueada":"poligono-com-furos");let c=!1;for(const d of r){if(d.geometria.tipo!=="Polygon")continue;const h=yi(d.geometria.aneis[0],t);if(!h)continue;((l=this.desenho)==null?void 0:l.ferramenta)==="dividir"&&this.selecao.contem({camadaId:d.camadaId,id:d.id})&&this.desenho.desativar(),this.removerFeicao(d.camadaId,d.id);const u=[];if(h.forEach((m,f)=>{const g=Bt(d,this.idLivre(d.camadaId,`${d.id}-${f+1}`),{tipo:"Polygon",aneis:[m]}),x=this.adicionarFeicao(d.camadaId,g);x&&u.push(x)}),u.length!==h.length){for(const m of u)this.removerFeicao(m.camadaId,m.id);return this.adicionarFeicao(d.camadaId,d),o("geometria-invalida")}if(this.contexto.emitir("cad-feicao-dividida",{origem:d,partes:u}),c=!0,i.length===0)break}return c||o("sem-intersecao")}gerarBuffer(t,e,o,i={}){const a=this.buscar(t,e);if(!a)return null;const s=Ci(a.geometria,o);if(!s)return null;const r=i.camadaDestino??t,c=this.adicionarFeicao(r,{id:i.id??this.idLivre(r,`${e}-buffer`),geometria:{tipo:"Polygon",aneis:[s]},estilo:a.estilo?{...a.estilo}:void 0,propriedades:{...a.propriedades,origem:e}});return c&&this.contexto.emitir("cad-feicao-criada",{camadaId:r,feicao:c}),c}duplicarFeicao(t,e,o={},i={}){const a=this.buscar(t,e);if(!a)return null;const s=Li(a.geometria,o.lesteM??0,o.norteM??0),r=this.adicionarFeicao(t,Bt(a,i.id??this.idLivre(t,`${e}-copia`),s));return r&&this.contexto.emitir("cad-feicao-criada",{camadaId:t,feicao:r}),r}juntarFeicoes(t,e,o={}){const i=h=>(this.contexto.emitir("cad-uniao-falhou",{motivo:h}),null),a=e.map(h=>this.buscar(t,h));if(a.length<2||a.some(h=>!h))return i("feicoes-insuficientes");const s=a;if(new Set(s.map(h=>h.id)).size!==s.length)return i("feicoes-insuficientes");const r=this.contexto.obterLayerManager();if(s.some(h=>{var u;return h.excluida||h.bloqueada||((u=r.getLayerDef(h.camadaId))==null?void 0:u.bloqueada)}))return i("bloqueada");const c=o.toleranciaM??0;let l=null;if(s.every(h=>h.geometria.tipo==="LineString")){if(s.some(m=>wt(m.geometria)))return i("multiparte");const h=s.map(m=>m.geometria.coordenadas),u=bi(h,c);u&&(l=yt([u]))}else if(s.every(h=>h.geometria.tipo==="Polygon"&&h.geometria.aneis.length===1)){let h=s[0].geometria.aneis[0];for(const u of s.slice(1))h=h?Pi(h,u.geometria.aneis[0],c):null;h&&(l={tipo:"Polygon",aneis:[h]})}else return i("tipos-incompativeis");if(!l)return i("sem-ligacao");for(const h of s)this.removerFeicao(t,h.id);const d=this.adicionarFeicao(t,Bt(s[0],o.id??this.idLivre(t,`${s[0].id}-uniao`),l));if(!d){for(const h of s)this.adicionarFeicao(t,h);return i("geometria-invalida")}return this.contexto.emitir("cad-feicao-unida",{origens:s,resultado:d}),d}}const So={ponto:"Ponto",linha:"Linha",poligono:"Polígono",retangulo:"Retângulo",elipse:"Elipse","poligono-regular":"Hexágono",estrela:"Estrela",circulo:"Círculo",texto:"Texto",caneta:"Caneta","medir-distancia":"Medir","medir-area":"Área",dividir:"Dividir","selecao-laco":"Laço","conta-gotas":"Cor"};function ge(n){if(!n)return[];const t=n.split(/[\s,]+/).map(o=>o.trim().toLowerCase()).filter(Boolean);if(t.includes("todas"))return[...oe];const e=new Set(t.filter(Ue));return oe.filter(o=>e.has(o))}class Oa{constructor(t){p(this,"barra",null);this.ctx=t}montar(t){var o;if((o=this.barra)==null||o.remove(),this.barra=null,t.length===0)return;const e=document.createElement("div");e.className="cad-quick-toolbar cad-draw-toolbar",e.setAttribute("role","toolbar"),e.setAttribute("aria-label","Ferramentas de desenho");for(const i of t){const a=document.createElement("button");a.type="button",a.className="cad-btn-tool cad-draw-btn",a.dataset.ferramenta=i,a.textContent=So[i],a.title=So[i],a.setAttribute("aria-pressed","false"),a.addEventListener("click",()=>this.ctx.aoEscolher(i)),e.appendChild(a)}this.ctx.raiz.appendChild(e),this.barra=e}marcar(t){var e;(e=this.barra)==null||e.querySelectorAll("[data-ferramenta]").forEach(o=>{const i=o.dataset.ferramenta===t;o.classList.toggle("active",i),o.setAttribute("aria-pressed",String(i))})}desmontar(){var t;(t=this.barra)==null||t.remove(),this.barra=null}}const Fa="data-cad-estilos-externos";function Ra(n){try{return Array.from(n.cssRules,t=>t.cssText).join(`
166
- `)}catch{return""}}function Ba(n){return typeof n=="string"?n.trim()?[n]:[]:Array.isArray(n)?n.map(t=>typeof t=="string"?t:Ra(t)).filter(t=>t.trim()!==""):[]}class Ha{constructor(t){p(this,"textos",[]);p(this,"adotadas",[]);p(this,"fallback",null);this.shadow=t}get pedido(){return this.textos}definir(t){this.textos=Ba(t),this.aplicar()}limpar(){this.remover()}aplicar(){if(this.remover(),this.textos.length===0)return;const t=this.shadow;if(typeof CSSStyleSheet<"u"&&Array.isArray(t.adoptedStyleSheets))try{this.adotadas=this.textos.map(o=>{const i=new CSSStyleSheet;return i.replaceSync(o),i}),t.adoptedStyleSheets=[...t.adoptedStyleSheets,...this.adotadas];return}catch{this.adotadas=[]}const e=document.createElement("style");e.setAttribute(Fa,""),e.textContent=this.textos.join(`
167
- `),this.shadow.appendChild(e),this.fallback=e}remover(){var e;const t=this.shadow;this.adotadas.length>0&&Array.isArray(t.adoptedStyleSheets)&&(t.adoptedStyleSheets=t.adoptedStyleSheets.filter(o=>!this.adotadas.includes(o))),this.adotadas=[],(e=this.fallback)==null||e.remove(),this.fallback=null}}class Ji extends Mo.SafeHTMLElement{constructor(){var a;super();p(this,"shadow");p(this,"mapContainer",null);p(this,"layersPanel",null);p(this,"controller");p(this,"controladorTamanho");p(this,"toolbarPainel");p(this,"broadcastConfig");p(this,"colecoesDados");p(this,"feicoes");p(this,"barraFerramentas");p(this,"hoverListeners",new ve.ListenerBag);p(this,"layerItemListeners",new ve.ListenerBag);p(this,"initTimeout");p(this,"estilosExternos");p(this,"lastPopupActionEmit");p(this,"lastCanvasClickTime",0);p(this,"_chaveGrupo");p(this,"_zonaProjecao",22);this.shadow=this.attachShadow({mode:"open"}),this.controller=new ie,this.controladorTamanho=pi(this,this.controller),this.shadow.innerHTML=Wn(),this.estilosExternos=new Ha(this.shadow),this.mapContainer=this.shadow.getElementById("cad-map-container"),this.layersPanel=this.shadow.getElementById("qgis-layer-panel"),this.toolbarPainel=new Gn({shadow:this.shadow,mapContainer:this.mapContainer,layersPanel:this.layersPanel,onToggleCamadas:()=>this.toggleLayersPanel(),onCloseCamadas:()=>this.closeLayersPanel(),onZoomExtents:()=>this.zoomExtents(),onLimparSelecao:()=>this.limparSelecao(),onToggleSnap:()=>this.feicoes.alternarSnap(),onTratarCliqueCanvas:s=>this.tratarCliqueLivreCanvas(s),onDispararAcaoPopup:(s,r)=>this.dispararAcaoPopup(s,r)}),this.broadcastConfig=new Vn({host:this,controller:this.controller,mapContainer:this.mapContainer,setLayerOpacity:(s,r)=>this.setLayerOpacity(s,r)}),this.colecoesDados=new jn({obterController:()=>this.controller,obterChaveGrupo:()=>this.chaveGrupo,setLayerVisibility:(s,r)=>this.setLayerVisibility(s,r)});const e=new Zt,o=this.controller.context,i=this.controller.canvasInteracao.ctx;Object.assign(o,{regraVersoes:e}),this.feicoes=new Na({obterLayerManager:()=>this.controller.layerManager,obterMapa:()=>this.controller.getMap(),regra:e,aoFerramenta:s=>{this.barraFerramentas.marcar(s)},aoSnapMudar:s=>{var r;(r=this.shadow.getElementById("btn-toggle-snap"))==null||r.classList.toggle("active",s)},emitir:(s,r,c)=>{const l=new CustomEvent(s,{detail:r,bubbles:!0,composed:!0,cancelable:!!c});return this.dispatchEvent(l),l.defaultPrevented}}),Object.assign(o,{onLayerAction:(s,r)=>{const c=this.feicoes.tratarAcaoCamada(s,r);c&&this.dispatchEvent(new CustomEvent(c,{detail:r,bubbles:!0,composed:!0}))}}),this.barraFerramentas=new Oa({raiz:this.shadow.getElementById("cad-root"),aoEscolher:s=>{this.feicoes.alternarFerramenta(s)}}),this.barraFerramentas.montar(ge(this.getAttribute("ferramentas"))),Object.assign(i,{aoMenuContexto:s=>this.feicoes.menuContexto(s),ferramentaAtiva:()=>this.feicoes.ferramentaAtiva!==null,aoLimparSelecao:()=>this.feicoes.aoPedirLimpeza(),selecionarFeicoesNaCaixa:(s,r,c)=>this.feicoes.selecionarNaCaixa(s,r,c)}),(a=this.shadow.getElementById("btn-toggle-snap"))==null||a.classList.add("active")}static get observedAttributes(){return["sat-opacity","scale-mode","crosshair","modo-sequencial","chave-grupo","zona-projecao","fuso","canal-configuracao","ferramentas","sem-atalho-snap","aceitar-origem","sem-camadas-padrao","sem-painel-camadas","sem-barra-rapida"]}connectedCallback(){const e=this.getAttribute("zona-projecao")||this.getAttribute("fuso");if(e){const o=parseInt(e,10);!isNaN(o)&&o>0&&(this._zonaProjecao=o,this.controller.zonaProjecao=o,this.controller.context.zonaProjecao=o)}this.controladorTamanho.observe(),this.feicoes.conectarTeclado(),this.hoverListeners.cleanup(),this.mapContainer&&this.hoverListeners.add(this.mapContainer,"mousemove",o=>this.feicoes.aoMoverMouse(o)),this.barraFerramentas.montar(ge(this.getAttribute("ferramentas"))),this.broadcastConfig.conectar(),this.estilosExternos.aplicar(),this.initTimeout=window.setTimeout(()=>{this.initTimeout=void 0,this.inicializarAgora()},0)}destroy(){if(this.initTimeout&&(window.clearTimeout(this.initTimeout),this.initTimeout=void 0),this.controladorTamanho.disconnect(),this.estilosExternos.limpar(),this.feicoes.pararEdicao(),this.feicoes.desativarFerramenta(),this.feicoes.limparMedicao(),this.feicoes.desconectarTeclado(),this.feicoes.destruir(),this.hoverListeners.cleanup(),this.broadcastConfig.desconectar(),this.limparDestaque(),this.toolbarPainel.limpar(),this.layerItemListeners.cleanup(),this.controller.destroy(),this.mapContainer&&this.mapContainer._leaflet_id)try{delete this.mapContainer._leaflet_id}catch{this.mapContainer._leaflet_id=void 0}}disconnectedCallback(){this.destroy()}invalidateSizeSafely(){this.controladorTamanho.invalidateSizeSafely()}attributeChangedCallback(e,o,i){var a,s,r,c,l;if(e==="sem-atalho-snap"){(a=this.feicoes)==null||a.definirAtalhoSnap(i===null);return}if(!(e==="sem-camadas-padrao"||e==="sem-barra-rapida")){if(e==="sem-painel-camadas"){i!==null&&((s=this.toolbarPainel)==null||s.closeLayersPanel());return}if(e==="aceitar-origem"){this.feicoes&&(this.feicoes.aceitarOrigem=i!==null&&i!=="false");return}if(e==="ferramentas"){(r=this.barraFerramentas)==null||r.montar(ge(i)),(l=this.barraFerramentas)==null||l.marcar(((c=this.feicoes)==null?void 0:c.ferramentaAtiva)??null);return}Xn({host:this,controller:this.controller,mapContainer:this.mapContainer,broadcastConfig:this.broadcastConfig,setLayerOpacity:(d,h)=>this.setLayerOpacity(d,h),setLayerScaleMode:(d,h)=>this.setLayerScaleMode(d,h),atualizarZonaProjecao:d=>{this._zonaProjecao=d}},e,o,i)}}inicializarAgora(){this.initTimeout!==void 0&&(window.clearTimeout(this.initTimeout),this.initTimeout=void 0);const e=this.controller.getMap();return e||(this.hasAttribute("sem-camadas-padrao")&&this.controller.layerManager.descartarCamadasPadrao(),this.initCAD(),this.controller.getMap())}definirEstilosExternos(e){this.estilosExternos.definir(e)}initCAD(){Zn({host:this,shadow:this.shadow,mapContainer:this.mapContainer,controller:this.controller,toolbarPainel:this.toolbarPainel,colecoesDados:this.colecoesDados,obterContextoEventos:()=>this.obterContextoEventos(),renderLayersUI:()=>this.renderLayersUI(),invalidateSizeSafely:()=>this.invalidateSizeSafely(),tratarCliqueLivreCanvas:(e,o,i)=>this.tratarCliqueLivreCanvas(e,o,i),dispararAcaoPopup:(e,o,i)=>this.dispararAcaoPopup(e,o,i)})}obterContextoEventos(){return{host:this,controller:this.controller,mapContainer:this.mapContainer,modoSequencial:this.modoSequencial,mouseMovedSinceDown:this.toolbarPainel.houveMovimentoMouse,obterElementoPorId:e=>this.colecoesDados.obterElementoPorId(e),fecharPopup:()=>{var e;(e=this.controller.getMap())==null||e.closePopup()}}}tratarCliqueLivreCanvas(e,o,i){const a=Date.now();a-this.lastCanvasClickTime<50||(this.lastCanvasClickTime=a,li(this.obterContextoEventos(),e,o,i))}dispararAcaoPopup(e,o,i){const a=Date.now();this.lastPopupActionEmit&&this.lastPopupActionEmit.acaoId===e&&this.lastPopupActionEmit.elementoId===o&&a-this.lastPopupActionEmit.time<50||(this.lastPopupActionEmit={acaoId:e,elementoId:o,time:a},di(this.obterContextoEventos(),e,o,i))}toggleLayersPanel(){this.hasAttribute("sem-painel-camadas")||this.toolbarPainel.toggleLayersPanel()}closeLayersPanel(){this.toolbarPainel.closeLayersPanel()}renderLayersUI(){const e=this.shadow.getElementById("layers-list-container");ci(e,this.controller.layerManager.getLayers(),this.layerItemListeners,{setLayerVisibility:(o,i)=>this.setLayerVisibility(o,i),setLayerOpacity:(o,i)=>this.setLayerOpacity(o,i),setLayerBlocked:(o,i)=>this.controller.layerManager.setLayerBlocked(o,i),setLayerScaleMode:(o,i)=>this.setLayerScaleMode(o,i)})}get pontos(){return this.colecoesDados.pontos}set pontos(e){this.colecoesDados.pontos=e}get segmentos(){return this.colecoesDados.segmentos}set segmentos(e){this.colecoesDados.segmentos=e}get bancoPontos(){return this.colecoesDados.bancoPontos}set bancoPontos(e){this.colecoesDados.bancoPontos=e}get pontosHomologados(){return this.bancoPontos}set pontosHomologados(e){this.bancoPontos=e}get confrontantes(){return this.colecoesDados.confrontantes}set confrontantes(e){this.colecoesDados.confrontantes=e}get vizinhos(){return this.confrontantes}set vizinhos(e){this.confrontantes=e}get aceitarOrigem(){return this.hasAttribute("aceitar-origem")&&this.getAttribute("aceitar-origem")!=="false"}set aceitarOrigem(e){e?this.setAttribute("aceitar-origem",""):this.removeAttribute("aceitar-origem")}get modoSequencial(){return this.hasAttribute("modo-sequencial")}set modoSequencial(e){var i;const o=!!e;o?this.hasAttribute("modo-sequencial")||this.setAttribute("modo-sequencial",""):this.hasAttribute("modo-sequencial")&&this.removeAttribute("modo-sequencial"),this.controller.modoCliqueSequencialAtivo=o,this.controller.context.modoSequencial=o,o&&((i=this.controller.getMap())==null||i.closePopup())}get chaveGrupo(){return this.getAttribute("chave-grupo")||this._chaveGrupo}set chaveGrupo(e){this._chaveGrupo=e,e?this.getAttribute("chave-grupo")!==e&&this.setAttribute("chave-grupo",e):this.hasAttribute("chave-grupo")&&this.removeAttribute("chave-grupo"),this.controller.chaveGrupo=e,this.controller.context.chaveGrupo=e,this.controller.layerManager.updateContext({chaveGrupo:e})}get zonaProjecao(){return this._zonaProjecao??22}set zonaProjecao(e){const o=typeof e=="number"?Math.floor(e):parseInt(String(e),10);if(!isNaN(o)&&o>0){this._zonaProjecao=o;const i=String(o);this.getAttribute("zona-projecao")!==i&&this.setAttribute("zona-projecao",i),this.hasAttribute("fuso")&&this.getAttribute("fuso")!==i&&this.setAttribute("fuso",i),this.controller.zonaProjecao=o,this.controller.context.zonaProjecao=o}}get canalConfiguracao(){return this.getAttribute("canal-configuracao")}set canalConfiguracao(e){e?this.setAttribute("canal-configuracao",e):this.removeAttribute("canal-configuracao")}fitBounds(e,o=[40,40],i=!1){this.controller.fitBounds(e,o,i)}zoomExtents(){this.controller.canvasInteracao.zoomExtents()}selectPonto(e,o){this.controller.selectPonto(e,o)}selecionarPonto(e,o){this.controller.selectPonto(e,o)}get pontosSelecionados(){return this.controller.context.selectedPontoIds||this.controller.canvasInteracao.ctx.selectedPontoIds||[]}set pontosSelecionados(e){const o=Array.isArray(e)?e:[];this.controller.canvasInteracao.ctx.selectedPontoIds=o,this.controller.context.selectedPontoIds=[...o],this.controller.atualizarDestaqueMarcadores()}atualizarDestaqueMarcadores(){this.controller.atualizarDestaqueMarcadores()}selectSegmento(e){this.controller.selectSegmento(e)}get segmentoSelecionado(){return this.controller.context.selectedSegmentoId||null}set segmentoSelecionado(e){this.controller.selectSegmento(e)}limparSelecao(){this.controller.canvasInteracao.limparSelecao(),this.feicoes.limparSelecaoFeicoes()}setLayerVisibility(e,o){this.controller.layerManager.setLayerVisibility(e,o)}setLayerOpacity(e,o){this.controller.layerManager.setLayerOpacity(e,o)}setLayerScaleMode(e,o){this.controller.layerManager.setLayerScaleMode(e,o)}setGraphicScale(e){this.controller.setGraphicScale(e)}exportState(){return this.controller.exportState()}importState(e){this.controller.importState(e)}invalidateSize(){this.invalidateSizeSafely()}get destaqueAtivo(){return this.controller.destaqueAtivo}destacarElemento(e,o){this.inicializarAgora(),this.controller.destacarElemento(e,o)}limparDestaque(){this.controller.limparDestaque()}plotarPontos(e,o="vertices",i){this.colecoesDados.plotarPontos(e,o,i)}plotarConexoes(e,o="linhas"){this.colecoesDados.plotarConexoes(e,o)}plotarPolilinhaSequencial(e,o=!0,i="polilinha",a){this.colecoesDados.plotarPolilinhaSequencial(e,o,i,a)}plotarPoligonos(e,o="poligonos"){this.colecoesDados.plotarPoligonos(e,o)}limparCamadas(e){this.colecoesDados.limparCamadas(e)}obterMarcadores(e){return this.colecoesDados.obterMarcadores(e)}plotPontos(e,o){this.colecoesDados.plotPontos(e,o)}plotSegmentos(e,o){this.colecoesDados.plotSegmentos(e,o)}plotPolilinhaTemporaria(e){this.colecoesDados.plotPolilinhaTemporaria(e)}plotPoligonalHomologada(e){this.colecoesDados.plotPoligonalHomologada(e)}plotPontosVizinhos(e){this.colecoesDados.plotPontosVizinhos(e)}plotPoligonosVizinhos(e){this.colecoesDados.plotPoligonosVizinhos(e)}clearOverlays(e=!1){this.colecoesDados.clearOverlays(e)}getMarkers(){return this.colecoesDados.getMarkers()}getVizinhosMarkers(){return this.colecoesDados.getVizinhosMarkers()}definirFeicoes(e,o,i){return this.feicoes.definirFeicoes(e,o,i)}adicionarFeicao(e,o,i){return this.feicoes.adicionarFeicao(e,o,i)}atualizarFeicao(e,o,i,a){return this.feicoes.atualizarFeicao(e,o,i,a)}aplicarLote(e,o,i){return this.feicoes.aplicarLote(e,o,i)}removerFeicao(e,o){return this.feicoes.removerFeicao(e,o)}obterFeicoes(e){return this.feicoes.obterFeicoes(e)}selecionarFeicoes(e,o=!1){this.feicoes.selecionarFeicoes(e,o)}selecionarFeicao(e,o){this.feicoes.selecionarFeicoes([{camadaId:e,id:o}])}alternarSelecaoFeicao(e,o){this.feicoes.alternarSelecaoFeicao({camadaId:e,id:o})}limparSelecaoFeicoes(){this.feicoes.limparSelecaoFeicoes()}obterFeicoesSelecionadas(){return this.feicoes.obterFeicoesSelecionadas()}editarVertices(e,o){return this.feicoes.iniciarEdicao(e,o)}pararEdicaoVertices(){this.feicoes.pararEdicao()}get editandoVertices(){return this.feicoes.editando}get snapLigado(){return this.feicoes.snapLigado}definirSnap(e){this.feicoes.definirSnap(e)}alternarSnap(){this.feicoes.alternarSnap()}definirCamadaDesenho(e){this.feicoes.definirCamadaDesenho(e)}get camadaDesenho(){return this.feicoes.camadaDeDesenho}definirEstiloDesenho(e){this.feicoes.definirEstiloDesenho(e)}obterEstiloDesenho(){return this.feicoes.obterEstiloDesenho()}definirFerramenta(e,o){return e===null?(this.feicoes.desativarFerramenta(),{ok:!0}):this.feicoes.ativarFerramenta(e,o)}get ferramentaAtiva(){return this.feicoes.ferramentaAtiva}limparMedicao(){this.feicoes.limparMedicao()}get nosDesenho(){return this.feicoes.nosDesenho}desfazerVerticeDesenho(){return this.feicoes.desfazerVerticeDesenho()}definirAtalhoSnap(e){this.feicoes.definirAtalhoSnap(e)}gerarBuffer(e,o,i,a){return this.feicoes.gerarBuffer(e,o,i,a)}duplicarFeicao(e,o,i,a){return this.feicoes.duplicarFeicao(e,o,i,a)}juntarFeicoes(e,o,i){return this.feicoes.juntarFeicoes(e,o,i)}zoomParaFeicao(e,o){return this.feicoes.zoomParaFeicao(e,o)}zoomParaFeicoes(e){return this.feicoes.zoomParaFeicoes(e)}ajustarTudo(){return this.feicoes.ajustarTudo()}ajustarCamada(e){return this.feicoes.ajustarCamada(e)}get previasGlobais(){return this.feicoes.previasGlobais}definirPreviasGlobais(e){this.feicoes.definirPreviasGlobais(e)}alternarPreviasGlobais(){this.feicoes.alternarPreviasGlobais()}alternarPrevia(e,o){return this.feicoes.alternarPrevia(e,o)}previaSolicitada(e,o){return this.feicoes.previaSolicitada(e,o)}atualizarCursorRemoto(e,o){return this.feicoes.atualizarCursorRemoto(e,o)}removerCursorRemoto(e){return this.feicoes.removerCursorRemoto(e)}limparCursoresRemotos(){this.feicoes.limparCursoresRemotos()}fecharPopupFeicao(){this.feicoes.fecharPopup()}definirOpcoesPopup(e){this.feicoes.definirOpcoesPopup(e)}definirMargensPopup(e){this.feicoes.definirMargensPopup(e)}definirMargensHud(e){this.feicoes.definirMargensHud(e)}getMap(){return this.controller.getMap()}getController(){return this.controller}getLayerManager(){return this.controller.layerManager}}Mo.definirCustomElement("ui-canvas-cad",Ji);class Va{constructor(t,e){p(this,"polylines",[]);p(this,"bancoPontosAtivo",!1);p(this,"core");this.core=t}setBancoPontosAtivo(t){this.bancoPontosAtivo=t}plotSegmentos(t,e){this.core.map&&t.forEach(o=>{const i=e.find(s=>String(s.id)===String(o.ponto_inicio_id)),a=e.find(s=>String(s.id)===String(o.ponto_fim_id));if(i&&a&&i.lat&&i.lon&&a.lat&&a.lon){const s=o.tipo_limite_sigef||o.tipo_limite||"",r=o.metodo_posicionamento_sigef||o.metodo_posicionamento||"",c=this.bancoPontosAtivo?"#94a3b8":s==="LA1"?"#10b981":"#3b82f6",l=this.core.config.perimetroWeight,d=this.bancoPontosAtivo?.4:1,h=[[i.lat,i.lon],[a.lat,a.lon]],u=y.polyline(h,{color:"#080d0a",weight:l+3,opacity:.85,lineCap:"round",lineJoin:"round",dashArray:s==="LN1"?"6, 6":void 0,pane:"perimetroPane",interactive:!1}).addTo(this.core.map);this.polylines.push(u);const m=y.polyline(h,{color:c,weight:l,opacity:d,dashArray:s==="LN1"?"6, 6":void 0,pane:"perimetroPane"}).bindPopup(`
165
+ `}function Ya(a,t,e,o){if(e!==o){if(t==="sat-opacity"){const i=parseFloat(o);isNaN(i)||a.setLayerOpacity("satelite",i)}else if(t==="scale-mode")(o==="world"||o==="screen")&&(a.setLayerScaleMode("perimetro",o),a.setLayerScaleMode("vertices",o));else if(t==="modo-sequencial")a.host.modoSequencial=o!==null&&o!=="false";else if(t==="chave-grupo")a.host.chaveGrupo=o||void 0;else if(t==="zona-projecao"||t==="fuso"){const i=parseInt(o,10);!isNaN(i)&&i>0&&(a.atualizarZonaProjecao(i),t==="fuso"&&a.host.getAttribute("zona-projecao")!==o?a.host.setAttribute("zona-projecao",o):t==="zona-projecao"&&a.host.hasAttribute("fuso")&&a.host.getAttribute("fuso")!==o&&a.host.setAttribute("fuso",o),a.controller.zonaProjecao=i,a.controller.context.zonaProjecao=i)}else if(t==="canal-configuracao")a.broadcastConfig.conectar(o);else if(t==="crosshair"){const i=o!==null&&o!=="false";a.mapContainer&&(a.mapContainer.style.cursor=i?"crosshair":"");const n=a.controller.getMap();if(n){const s=n.getContainer();s&&(s.style.cursor=i?"crosshair":"")}a.controller.core.config.crosshair=i}}}function Ka(a){if(!a.mapContainer)return;if(a.mapContainer._leaflet_id&&!a.controller.getMap())try{delete a.mapContainer._leaflet_id}catch{a.mapContainer._leaflet_id=void 0}if(a.controller.init(a.mapContainer,a.shadow),a.toolbarPainel.vincularEventos(),a.renderLayersUI(),a.host.hasAttribute("modo-sequencial")&&(a.controller.modoCliqueSequencialAtivo=!0,a.controller.context.modoSequencial=!0),a.host.hasAttribute("chave-grupo")){const o=a.host.getAttribute("chave-grupo");o&&(a.host.chaveGrupo=o)}if(a.host.hasAttribute("zona-projecao")||a.host.hasAttribute("fuso")){const o=a.host.zonaProjecao;a.controller.zonaProjecao=o,a.controller.context.zonaProjecao=o}if(a.host.hasAttribute("crosshair")){const o=a.host.getAttribute("crosshair")!=="false";a.mapContainer&&(a.mapContainer.style.cursor=o?"crosshair":""),a.controller.core.config.crosshair=o}a.colecoesDados.sincronizarInicial(),a.controller.layerManager.onChange(o=>{a.renderLayersUI(),a.host.dispatchEvent(new CustomEvent("ui-camadas-alteradas",{detail:{layers:o},bubbles:!0,composed:!0}))});const t=a.controller.context.onMarkerClick;a.controller.context.onMarkerClick=(o,i,n,s)=>{gi(a.obterContextoEventos(),o,i,n,s,t,a.colecoesDados.customMarkerClickHandler)},a.controller.context.onSegmentoClick=(o,i,n)=>{vi(a.obterContextoEventos(),o,i,n)},a.controller.context.onPopupAcao=(o,i,n)=>{a.dispararAcaoPopup(o,i,n)};const e=a.controller.getMap();e&&e.on("click",o=>{a.toolbarPainel.houveMovimentoMouse||a.tratarCliqueLivreCanvas(o,o.latlng,o.containerPoint)}),setTimeout(()=>{a.invalidateSizeSafely()},150)}function X(a,t){let e,o;if(Array.isArray(a))[e,o]=a;else if(a&&typeof a=="object"){const n=a;e=n.lat??n.latitude,o=n.lng??n.lon??n.longitude}else return null;const i=S.parseCoordenada(e,o,t);return!i||!Number.isFinite(i.lat)||!Number.isFinite(i.lon)?null:[i.lat,i.lon]}function Ja(a,t){return a[0]===t[0]&&a[1]===t[1]}function Ge(a,t){const e=a.map(o=>X(o,t)).filter(o=>o!==null);return e.length>1&&Ja(e[0],e[e.length-1])&&e.pop(),e.length>=3?e:null}function _e(a,t){const e=a.map(o=>X(o,t)).filter(o=>o!==null);return e.length>=2?e:null}function xi(a,t){if(!Array.isArray(a)||a.length===0)return null;const o=(Array.isArray(a[0])&&Array.isArray(a[0][0])?a:[a]).map(i=>Ge(i,t));return o.some(i=>i===null)?null:o}function Qa(a,t){const e=S.parseCoordenada(a.lat,a.lon);return e?{id:String(a.id),camadaId:t,geometria:{tipo:"Point",coordenada:[e.lat,e.lon]},propriedades:{...a}}:null}function tn(a,t,e){const o=t.get(String(a.ponto_inicio_id)),i=t.get(String(a.ponto_fim_id));if(!o||!i)return null;const n=S.parseCoordenada(o.lat,o.lon),s=S.parseCoordenada(i.lat,i.lon);if(!n||!s)return null;const r=(a.tipo_limite_sigef??a.tipo_limite)==="LN1";return{id:String(a.id??`${a.ponto_inicio_id}-${a.ponto_fim_id}`),camadaId:e,geometria:{tipo:"LineString",coordenadas:[[n.lat,n.lon],[s.lat,s.lon]]},estilo:r?{dashArray:"6, 6"}:void 0,propriedades:{...a}}}function en(a,t){if(!a.poligono_wkt)return null;const e=/POLYGON\s*\(\s*\(\s*(.*?)\s*\)\s*\)/i.exec(a.poligono_wkt);if(!e)return null;const o=e[1].split(",").map(n=>{const[s,r]=n.trim().split(/\s+/);return[r,s]}),i=Ge(o);return i?{id:String(a.id??a.nome??""),camadaId:t,geometria:{tipo:"Polygon",aneis:[i]},propriedades:{nome:a.nome,nome_propriedade:a.nome_propriedade}}:null}function po(a,t){const e=La(a);if(!e)return null;const o=[];for(const i of e){const n=X(i.ponto,t);if(!n)return null;const s={ponto:n},r=i.entrada&&X(i.entrada,{...t,aceitarOrigem:!0}),c=i.saida&&X(i.saida,{...t,aceitarOrigem:!0});r&&(s.entrada=r),c&&(s.saida=c),o.push(s)}return o}const on=new Set(["Point","LineString","Polygon","Circle","Text"]);function Gt(a,t,e){if(!a||typeof a!="object")return null;const o=a,i=o.geometria;if(!i||!on.has(i.tipo)||o.id===void 0||o.id===null||o.id==="")return null;let n=null;switch(i.tipo){case"Point":{const r=X(i.coordenada,e);r&&(n={tipo:"Point",coordenada:r});break}case"Text":{const r=X(i.coordenada,e);r&&typeof i.texto=="string"&&i.texto&&(n={tipo:"Text",coordenada:r,texto:i.texto});break}case"LineString":{const r=Array.isArray(i.partes)?i.partes.map(l=>Array.isArray(l)?_e(l,e):null).filter(l=>l!==null):[];if(r.length>0)n=bt(r);else{const l=Array.isArray(i.coordenadas)?_e(i.coordenadas,e):null;l&&(n=bt([l]))}const c=r.length<=1?po(i.curva,e):null;n&&n.tipo==="LineString"&&c&&c.length>=2&&(n={tipo:"LineString",coordenadas:Pt(c,!1),curva:c});break}case"Polygon":{const r=Array.isArray(i.aneis)?xi(i.aneis,e):null;r&&(n={tipo:"Polygon",aneis:r});const c=r&&r.length===1?po(i.curva,e):null;n&&c&&c.length>=3&&(n={tipo:"Polygon",aneis:[Pt(c,!0)],curva:c});break}case"Circle":{const r=X(i.centro,e),c=Number(i.raioMetros);r&&Number.isFinite(c)&&c>0&&(n={tipo:"Circle",centro:r,raioMetros:c});break}}if(!n)return null;const s={id:String(o.id),camadaId:t,geometria:n,estilo:o.estilo&&typeof o.estilo=="object"?{...o.estilo}:void 0,propriedades:o.propriedades&&typeof o.propriedades=="object"?{...o.propriedades}:{},bloqueada:!!o.bloqueada,status:"oficial",excluida:!!o.excluida};return o.oculta&&(s.oculta=!0),(typeof o.entidadeId=="string"||typeof o.entidadeId=="number")&&(s.entidadeId=String(o.entidadeId)),s.status=K({...s,status:o.status}),s}const ye="cad-cursores",an=/^#[0-9a-f]{3,8}$/i,nn="#94a3b8";function ae(a){return typeof a=="string"&&an.test(a.trim())?a.trim():nn}const sn='<svg width="18" height="18" viewBox="0 0 24 24" style="display:block;filter:drop-shadow(0 1px 1px rgba(0,0,0,.6))"><path d="M3 2 L3 19 L8 14.5 L11.5 22 L14.5 20.5 L11 13.5 L18 13 Z" fill="currentColor" stroke="#fff" stroke-width="1.2" stroke-linejoin="round"/></svg>';function fo(a){const t=document.createElement("div");t.style.cssText=`color:${ae(a.cor)};position:relative;pointer-events:none`,t.innerHTML=sn;const e=document.createElement("span");return e.textContent=String(a.nome??a.id),e.style.cssText=`position:absolute;left:16px;top:14px;white-space:nowrap;font:600 11px sans-serif;color:#fff;background:${ae(a.cor)};padding:1px 5px;border-radius:3px;max-width:160px;overflow:hidden;text-overflow:ellipsis`,t.appendChild(e),y.divIcon({className:"custom-leaflet-marker cad-cursor-remoto",iconSize:[18,18],iconAnchor:[3,2],html:t})}class bi{constructor(t){p(this,"marcadores",new Map);this.obterMapa=t}get quantidade(){return this.marcadores.size}atualizar(t,e){const o=this.obterMapa();if(!o||!t||t.id===void 0||t.id===null||t.id===""||!Number.isFinite(e==null?void 0:e[0])||!Number.isFinite(e==null?void 0:e[1]))return!1;const i=String(t.id),n=`${t.nome??""}\0${ae(t.cor)}`,s=this.marcadores.get(i);if(s)return s.marker.setLatLng(e),s.assinatura!==n&&(s.marker.setIcon(fo(t)),s.assinatura=n),!0;o.getPane(ye)||(o.createPane(ye).style.zIndex="9500");const r=y.marker(e,{icon:fo(t),pane:ye,interactive:!1,keyboard:!1}).addTo(o);return this.marcadores.set(i,{marker:r,assinatura:n}),!0}remover(t){const e=this.marcadores.get(String(t));return e?(e.marker.remove(),this.marcadores.delete(String(t)),!0):!1}limpar(){for(const t of this.marcadores.values())t.marker.remove();this.marcadores.clear()}}const Rt=a=>`${a.camadaId}\0${a.id}`;class Pi{constructor(t){p(this,"itens",new Map);this.dep=t}get quantidade(){return this.itens.size}contem(t){return this.itens.has(Rt(t))}obter(){const t=[];for(const e of this.itens.values()){const o=this.dep.obterFeicao(e);o&&t.push(o)}return t}selecionar(t,e=!1){const o=this.assinatura(),i=new Set;e||this.itens.forEach(n=>i.add(n.camadaId)),e||this.itens.clear();for(const n of t)this.alcancavel(n)&&(this.itens.set(Rt(n),{camadaId:n.camadaId,id:n.id}),i.add(n.camadaId));this.finalizar(o,i)}alternar(t){const e=this.assinatura(),o=Rt(t);this.itens.has(o)?this.itens.delete(o):this.alcancavel(t)&&this.itens.set(o,{camadaId:t.camadaId,id:t.id}),this.finalizar(e,new Set([t.camadaId]))}alternarVarias(t){const e=this.assinatura(),o=new Set;for(const i of t){const n=Rt(i);this.itens.has(n)?this.itens.delete(n):this.alcancavel(i)&&this.itens.set(n,{camadaId:i.camadaId,id:i.id}),o.add(i.camadaId)}this.finalizar(e,o)}alcancavel(t){const e=this.dep.obterFeicao(t);return!!e&&(!this.dep.selecionavel||this.dep.selecionavel(e))}limpar(){if(this.itens.size===0)return;const t=this.assinatura(),e=new Set([...this.itens.values()].map(o=>o.camadaId));this.itens.clear(),this.finalizar(t,e)}reconciliar(){const t=this.assinatura(),e=new Set;for(const[o,i]of this.itens){const n=this.dep.obterFeicao(i);(!n||n.excluida||this.dep.visivel&&!this.dep.visivel(n))&&(this.itens.delete(o),e.add(i.camadaId))}e.size!==0&&this.finalizar(t,e)}assinatura(){return[...this.itens.keys()].join("|")}finalizar(t,e){for(const i of e){const n=new Set;for(const s of this.itens.values())s.camadaId===i&&n.add(s.id);this.dep.aplicarVisual(i,n)}if(this.assinatura()===t)return;const o=this.obter();this.dep.aoSelecionar(o),o.length<=1&&this.dep.aoSelecionarUma(o[0]??null)}}const ne=63710088e-1,mo=111320,se=a=>a*Math.PI/180;function yt(a){return{lat0:a[0],lon0:a[1],cos0:Math.cos(se(a[0]))}}function Te(a,t){return[se(a[1]-t.lon0)*t.cos0*ne,se(a[0]-t.lat0)*ne]}function xt(a,t){return[t.lat0+a[1]/ne*(180/Math.PI),t.lon0+a[0]/(ne*t.cos0)*(180/Math.PI)]}function je(a,t){const e=o=>{let i=!1;for(let n=0,s=o.length-1;n<o.length;s=n++){const[r,c]=o[n],[l,d]=o[s];r>a[0]!=l>a[0]&&a[1]<(d-c)*(a[0]-r)/(l-r)+c&&(i=!i)}return i};return!t[0]||!e(t[0])?!1:!t.slice(1).some(e)}function Ci(a,t,e,o){const i=t[0]-a[0],n=t[1]-a[1],s=o[0]-e[0],r=o[1]-e[1],c=i*r-n*s;if(Math.abs(c)<1e-12)return null;const l=((e[0]-a[0])*r-(e[1]-a[1])*s)/c,d=((e[0]-a[0])*n-(e[1]-a[1])*i)/c;return l<0||l>1||d<0||d>=1?null:{t:l,u:d}}function re(a){let t=0;for(let e=0;e<a.length;e++){const[o,i]=a[e],[n,s]=a[(e+1)%a.length];t+=o*s-n*i}return Math.abs(t)/2}function Li(a,t){if(a.length<3||t.length<2)return null;const e=yt(a[0]),o=a.map(s=>Te(s,e)),i=t.map(s=>Te(s,e)),n=Si(o,i,0);return n&&n.length>=2?n.map(s=>s.map(r=>xt(r,e))):null}function Si(a,t,e){if(e>8)return null;const o=a.length,i=[];for(let b=0;b<t.length-1;b++)for(let v=0;v<o;v++){const P=Ci(t[b],t[b+1],a[v],a[(v+1)%o]);P&&i.push({tLinha:b+P.t,tAnel:v+P.u,ponto:[t[b][0]+P.t*(t[b+1][0]-t[b][0]),t[b][1]+P.t*(t[b+1][1]-t[b][1])]})}if(i.sort((b,v)=>b.tLinha-v.tLinha),i.length<2)return null;const[n,s]=i,r=[];for(let b=Math.floor(n.tLinha)+1;b<=Math.floor(s.tLinha);b++)b>n.tLinha&&b<s.tLinha&&r.push(t[b]);const c=[n.ponto,...r,s.ponto];let l=n,d=s,h=c;n.tAnel>s.tAnel&&(l=s,d=n,h=[...c].reverse());const u=Math.floor(l.tAnel),g=Math.floor(d.tAnel),m=h.slice(1,-1),f=[l.ponto];for(let b=u+1;b<=g;b++)f.push(a[b%o]);f.push(d.ponto,...[...m].reverse());const x=[d.ponto];for(let b=g+1;b<=u+o;b++)x.push(a[b%o]);x.push(l.ponto,...m);const M=re(a)*1e-9,A=[f,x].filter(b=>b.length>=3&&re(b)>M);if(A.length<2)return null;const C=[s.ponto,...t.slice(Math.floor(s.tLinha)+1)];if(i.length>2&&C.length>=2){const b=[];for(const v of A){const P=Si(v,C,e+1);P?b.push(...P):b.push(v)}return b}return A}function Ct(a,t){return a.map(e=>Te(e,t))}const it=(a,t)=>Math.hypot(a[0]-t[0],a[1]-t[1]);function Mi(a,t=0){if(a.length===0||a.some(n=>n.length<2))return null;const e=yt(a[0][0]),o=a.slice(1).map(n=>Ct(n,e));let i=Ct(a[0],e);for(;o.length>0;){let n=null;if(o.forEach((d,h)=>{const u=i[0],g=i[i.length-1],m=[{inverter:!1,noFim:!0,d:it(g,d[0])},{inverter:!0,noFim:!0,d:it(g,d[d.length-1])},{inverter:!1,noFim:!1,d:it(u,d[d.length-1])},{inverter:!0,noFim:!1,d:it(u,d[0])}];for(const f of m)(!n||f.d<n.d)&&(n={idx:h,...f})}),!n||n.d>t)return null;const{idx:s,inverter:r,noFim:c}=n;let l=o.splice(s,1)[0];r&&(l=[...l].reverse()),i=c?[...i,...it(i[i.length-1],l[0])>0?l:l.slice(1)]:[...l,...it(l[l.length-1],i[0])>0?i:i.slice(1)]}return i.map(n=>xt(n,e))}function rn(a,t,e,o){const i=Ci(a,t,e,o);return!!i&&i.t>1e-9&&i.t<1-1e-9&&i.u>1e-9}function cn(a,t){for(let e=0;e<a.length;e++)for(let o=0;o<t.length;o++)if(rn(a[e],a[(e+1)%a.length],t[o],t[(o+1)%t.length]))return!0;return!1}function Ai(a,t,e=0){if(a.length<3||t.length<3)return null;const o=yt(a[0]),i=Ct(a,o),n=Ct(t,o);if(cn(i,n))return null;let s={i:0,j:0,d:1/0};for(let d=0;d<i.length;d++)for(let h=0;h<n.length;h++){const u=it(i[d],n[h]);u<s.d&&(s={i:d,j:h,d:u})}if(s.d>e)return null;const{i:r,j:c}=s,l=[];for(let d=0;d<=i.length;d++)l.push(i[(r+d)%i.length]);for(let d=0;d<=n.length;d++)l.push(n[(c+d)%n.length]);return l.map(d=>xt(d,o))}const go=16;function vo(a,t,e,o){const i=[];for(let n=0;n<=go;n++){const s=e+(o-e)*n/go;i.push([a[0]+t*Math.cos(s),a[1]+t*Math.sin(s)])}return i}function Ft(a,t){const e=it(a,t)||1;return[-(t[1]-a[1])/e,(t[0]-a[0])/e]}function xe(a,t,e){const o=a.length,i=[],n=o;for(let s=0;s<n;s++){const r=e?a[(s-1+o)%o]:a[Math.max(0,s-1)],c=a[s],l=e?a[(s+1)%o]:a[Math.min(o-1,s+1)],d=s===0&&!e?Ft(c,l):Ft(r,c),h=s===o-1&&!e?Ft(r,c):Ft(c,l);let u=d[0]+h[0],g=d[1]+h[1];const m=Math.hypot(u,g);if(m<1e-9){i.push([c[0]+d[0]*t,c[1]+d[1]*t]);continue}u/=m,g/=m;const f=u*d[0]+g*d[1],x=Math.min(1/Math.max(f,.5),2);i.push([c[0]+u*t*x,c[1]+g*t*x])}return i}function ln(a){let t=0;for(let e=0;e<a.length;e++){const[o,i]=a[e],[n,s]=a[(e+1)%a.length];t+=(n-o)*(s+i)}return t>0}function wi(a,t){if(!Number.isFinite(t)||t===0)return null;if(a.tipo==="Point"||a.tipo==="Text"||a.tipo==="Circle"){const e=a.tipo==="Circle"?a.centro:a.coordenada,o=a.tipo==="Circle"?a.raioMetros+t:t;if(o<=0)return null;const i=yt(e),n=64;return Array.from({length:n},(s,r)=>[o*Math.cos(2*Math.PI*r/n),o*Math.sin(2*Math.PI*r/n)]).map(s=>xt(s,i))}if(a.tipo==="LineString"){if(t<0||a.coordenadas.length<2||kt(a))return null;const e=yt(a.coordenadas[0]),o=Ct(a.coordenadas,e),i=xe(o,t,!1),n=xe([...o].reverse(),t,!1),s=o[o.length-1],r=o[0],c=Math.atan2(s[1]-o[o.length-2][1],s[0]-o[o.length-2][0]),l=Math.atan2(r[1]-o[1][1],r[0]-o[1][0]),d=vo(s,t,c+Math.PI/2,c-Math.PI/2),h=vo(r,t,l+Math.PI/2,l-Math.PI/2);return[...i,...d,...n,...h].map(u=>xt(u,e))}if(a.tipo==="Polygon"){const e=a.aneis[0];if(!e||e.length<3)return null;const o=yt(e[0]);let i=Ct(e,o);ln(i)&&(i=[...i].reverse());const s=xe(i,-t,!0);return s.length<3||t<0&&re(s)>=re(i)?null:s.map(r=>xt(r,o))}return null}function Ei(a,t,e){const o=i=>{const n=e/mo,s=t/(mo*Math.max(.01,Math.cos(se(i[0]))));return[i[0]+n,i[1]+s]};switch(a.tipo){case"Point":return{tipo:"Point",coordenada:o(a.coordenada)};case"Text":return{...a,coordenada:o(a.coordenada)};case"Circle":return{...a,centro:o(a.centro)};case"LineString":{const i=bt(U(a).map(n=>n.map(o)));return a.curva?{...i,curva:lo(a.curva,o)}:i}case"Polygon":{const i={tipo:"Polygon",aneis:a.aneis.map(n=>n.map(o))};return a.curva?{...i,curva:lo(a.curva,o)}:i}}}const yo={m:1,km:1e3,ft:.3048,mi:1609.344},xo={m2:1,ha:1e4,km2:1e6,ac:4046.8564224,alqueire:24200};function dn(a,t,e){return a*yo[t]/yo[e]}function hn(a,t,e){return a*xo[t]/xo[e]}function un(a,t,e=2){const o=t==="lat"?a<0?"S":"N":a<0?"O":"L",i=Math.abs(a);let n=Math.floor(i),s=Math.floor((i-n)*60),r=Number(((i-n-s/60)*3600).toFixed(e));r>=60&&(r=0,s+=1),s>=60&&(s=0,n+=1);const c=r.toFixed(e).padStart(e?e+3:2,"0");return`${n}°${String(s).padStart(2,"0")}'${c}"${o}`}function pn(a){var u;if(typeof a!="string")return null;const t=a.trim().toUpperCase().replace(",","."),e=(u=/[NSLEOW]$/.exec(t))==null?void 0:u[0],o=t.replace(/[NSLEOW]$/,"").trim(),i=o.match(/-?\d+(?:\.\d+)?/g);if(!i||i.length===0||i.length>3||!/^[-\d\s°'"′″.]+$/.test(o))return null;const[n,s="0",r="0"]=i,c=Math.abs(Number(n)),l=Number(s),d=Number(r);if(l<0||l>=60||d<0||d>=60)return null;let h=c+l/60+d/3600;return(n.startsWith("-")||e==="S"||e==="O"||e==="W")&&(h=-h),h}function fn(a,t){return et(a,t)}function jt(a,t,e){return{...a,id:t,geometria:e??JSON.parse(JSON.stringify(a.geometria)),estilo:a.estilo?{...a.estilo}:void 0,propriedades:{...a.propriedades}}}const mn=111320;function Mt(a,t){return a.x>=t.x1&&a.x<=t.x2&&a.y>=t.y1&&a.y<=t.y2}function bo(a,t,e){let o=0,i=1;const n=t.x-a.x,s=t.y-a.y,r=[-n,n,-s,s],c=[a.x-e.x1,e.x2-a.x,a.y-e.y1,e.y2-a.y];for(let l=0;l<4;l++)if(r[l]===0){if(c[l]<0)return!1}else{const d=c[l]/r[l];if(r[l]<0){if(d>i)return!1;d>o&&(o=d)}else{if(d<o)return!1;d<i&&(i=d)}}return!0}function Po(a,t){let e=!1;for(let o=0,i=t.length-1;o<t.length;i=o++){const n=t[o],s=t[i];n.y>a.y!=s.y>a.y&&a.x<(s.x-n.x)*(a.y-n.y)/(s.y-n.y)+n.x&&(e=!e)}return e}function Co(a,t,e){for(let o=1;o<a.length;o++)if(bo(a[o-1],a[o],t))return!0;return e&&a.length>2&&bo(a[a.length-1],a[0],t)}function gn(a,t,e){const o=e(a),i=e([a[0]+t/mn,a[1]]);return Math.hypot(i.x-o.x,i.y-o.y)}function zi(a,t,e,o){if(a.oculta)return!1;const i=a.geometria,n=o==="window";switch(i.tipo){case"Point":case"Text":return Mt(e(i.coordenada),t);case"LineString":{const s=U(i).map(r=>r.map(e));return n?s.every(r=>r.every(c=>Mt(c,t))):s.some(r=>r.some(c=>Mt(c,t))||Co(r,t,!1))}case"Polygon":{const s=i.aneis.map(l=>l.map(e)),r=s[0];if(!r)return!1;if(n)return r.every(l=>Mt(l,t));if(s.some(l=>l.some(d=>Mt(d,t))||Co(l,t,!0)))return!0;const c={x:t.x1,y:t.y1};return Po(c,r)&&!s.slice(1).some(l=>Po(c,l))}case"Circle":{const s=e(i.centro),r=gn(i.centro,i.raioMetros,e);if(n)return s.x-r>=t.x1&&s.x+r<=t.x2&&s.y-r>=t.y1&&s.y+r<=t.y2;const c=Math.max(t.x1,Math.min(s.x,t.x2)),l=Math.max(t.y1,Math.min(s.y,t.y2));return Math.hypot(s.x-c,s.y-l)<=r}}}function ki(a,t){if(t.length<3||a.oculta)return!1;const e=i=>je(i,[t]),o=a.geometria;switch(o.tipo){case"Point":case"Text":return e(o.coordenada);case"Circle":return e(o.centro);case"LineString":return U(o).some(i=>i.some(e));case"Polygon":{const i=o.aneis[0]??[];if(i.some(e))return!0;if(i.length<3)return!1;const n=i.reduce((s,r)=>[s[0]+r[0],s[1]+r[1]],[0,0]);return e([n[0]/i.length,n[1]/i.length])}}}const vn={Point:"Ponto",LineString:"Linha",Polygon:"Polígono",Circle:"Círculo",Text:"Texto"},yn=new Set(["name","nome","category","categoria","description","descricao","author","autor","date","data","created_at","criadoEm"]),Lo=6;function At(a,t){var e;for(const o of t){const i=(e=a.propriedades)==null?void 0:e[o];if(i!=null&&String(i)!=="")return String(i)}return""}function xn(a){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(a),e=t?new Date(Number(t[1]),Number(t[2])-1,Number(t[3])):new Date(a);return Number.isNaN(e.getTime())?a:e.toLocaleDateString("pt-BR")}function bn(a){const t=typeof a=="object"?JSON.stringify(a):String(a);return t.length>80?`${t.slice(0,77)}...`:t}function Tt(a){const t=a.geometria;switch(t.tipo){case"Point":case"Text":return t.coordenada;case"Circle":return t.centro;case"LineString":return t.coordenadas[Math.floor(t.coordenadas.length/2)];case"Polygon":{const e=t.aneis[0],o=e.reduce((n,s)=>n+s[0],0)/e.length,i=e.reduce((n,s)=>n+s[1],0)/e.length;return[o,i]}}}function Pn(a){const t=a.geometria,e=[],o=Q(t),i=tt(t);if(t.tipo==="Polygon")e.push(["Área",rt(o??0)],["Perímetro",G(i??0)]),e.push(["Vértices",String(t.aneis.reduce((r,c)=>r+c.length,0))]);else if(t.tipo==="LineString"){const r=U(t);e.push(["Extensão",G(i??0)],["Vértices",String(r.reduce((c,l)=>c+l.length,0))]),r.length>1&&e.push(["Partes",String(r.length)])}else t.tipo==="Circle"&&e.push(["Raio",G(t.raioMetros)],["Área",rt(o??0)]);const[n,s]=Tt(a);return e.push(["Coordenadas",`${n.toFixed(6)}, ${s.toFixed(6)}`]),e}class Ii{constructor(t){p(this,"popup",null);p(this,"feicaoAtual",null);p(this,"margens",{topo:20,base:20,esquerda:20,direita:20});this.dep=t}definirMargens(t){this.margens={...this.margens,...t}}get aberto(){return this.feicaoAtual}abrir(t){const e=this.dep.obterMapa();e&&(this.fechar(),this.feicaoAtual=t,this.popup=y.popup({className:"compact-popup",maxWidth:280,closeOnClick:!1,autoClose:!1,autoPanPaddingTopLeft:y.point(this.margens.esquerda,this.margens.topo),autoPanPaddingBottomRight:y.point(this.margens.direita,this.margens.base)}).setLatLng(Tt(t)).setContent(this.montar(t)),this.popup.openOn(e))}atualizar(t){var e;!this.popup||((e=this.feicaoAtual)==null?void 0:e.id)!==t.id||this.feicaoAtual.camadaId!==t.camadaId||(this.feicaoAtual=t,this.popup.setLatLng(Tt(t)).setContent(this.montar(t)))}fechar(){const t=this.popup;this.popup=null,this.feicaoAtual=null,t==null||t.close()}montar(t){var f;const e=this.dep.obterCamada(t.camadaId),o=Y(((f=t.estilo)==null?void 0:f.corTraco)??(e==null?void 0:e.estilo.corPrimaria),"#38bdf8"),i=(x,E="",M)=>{const A=document.createElement(x);return E&&(A.style.cssText=E),M!==void 0&&(A.textContent=M),A},n=i("div","font-family:var(--ui-fonte-base,sans-serif);color:rgba(255,255,255,.9);line-height:1.35;min-width:200px;border-left:3px solid "+o+";padding-left:8px");n.className="cad-feicao-popup",n.appendChild(i("div","font-weight:700;font-size:13px;margin-bottom:1px",At(t,["name","nome"])||t.id));const s=At(t,["category","categoria"]),r=[vn[t.geometria.tipo],(e==null?void 0:e.nome)??t.camadaId,s].filter(Boolean).join(" · ");n.appendChild(i("div","font-size:11px;color:rgba(255,255,255,.6);margin-bottom:4px",r));const c=At(t,["description","descricao"]);c&&n.appendChild(i("div","font-size:11px;margin-bottom:4px",c));const l=x=>{const E=i("div","font-size:11px;margin-bottom:4px");for(const[M,A]of x){const C=i("div");C.appendChild(i("strong","",`${M}: `)),C.appendChild(document.createTextNode(A)),E.appendChild(C)}return E};n.appendChild(l(Pn(t)));const d=Object.entries(t.propriedades??{}).filter(([x,E])=>!yn.has(x)&&E!==void 0&&E!==null&&E!=="");d.length>0&&(n.appendChild(l(d.slice(0,Lo).map(([x,E])=>[x,bn(E)]))),d.length>Lo&&n.appendChild(i("div","font-size:10px;color:rgba(255,255,255,.55);margin-bottom:4px",`${d.length} atributos`)));const h=At(t,["author","autor"]),u=At(t,["date","data","created_at","criadoEm"]);if(h||u){const x=[h,u?xn(u):""].filter(Boolean).join(" · ");n.appendChild(i("div","font-size:10px;color:rgba(255,255,255,.55);margin-bottom:4px",x))}const g=i("div","display:flex;gap:4px;flex-wrap:wrap;margin-top:6px"),m=[["inspecionar","Inspecionar"],["zoom","Zoom"]];t.geometria.tipo==="LineString"||t.geometria.tipo==="Polygon"||t.geometria.tipo==="Point"?m.push(["vertices","Vértices"]):t.geometria.tipo==="Circle"&&m.push(["vertices","Editar"]),t.geometria.tipo==="Point"&&m.push(["copiar","Copiar"]);for(const[x,E]of m){const M=i("button","font-size:11px;padding:2px 8px;border-radius:4px;border:1px solid rgba(255,255,255,.25);background:rgba(255,255,255,.08);color:inherit;cursor:pointer",E);M.type="button",M.dataset.acao=x,M.addEventListener("click",A=>{A.stopPropagation(),this.dep.aoAcao(x,this.feicaoAtual??t)}),g.appendChild(M)}return n.appendChild(g),n}}const _i=5e3;function Lt(a){return a.tipo==="Polygon"?3:a.tipo==="LineString"?2:1}function Ut(a,t=!1){if(a.bloqueada||t)return"bloqueada";const e=a.geometria;return e.tipo!=="Point"&&e.tipo!=="LineString"&&e.tipo!=="Polygon"&&e.tipo!=="Circle"?"tipo-nao-suportado":e.tipo==="Polygon"&&e.aneis.length!==1?"poligono-com-furos":kt(e)?"multiparte":Z(e).length>_i?"muitos-vertices":null}function Z(a){return a.tipo==="Point"?[a.coordenada]:a.tipo==="LineString"?a.coordenadas:a.tipo==="Polygon"?a.aneis[0]??[]:[]}function qt(a,t){return a.tipo==="Point"?{tipo:"Point",coordenada:t[0]}:a.tipo==="LineString"?{tipo:"LineString",coordenadas:t}:a.tipo==="Polygon"?{tipo:"Polygon",aneis:[t]}:a}function Cn(a,t,e){const o=Z(a).slice();return t<0||t>=o.length?a:(o[t]=e,qt(a,o))}function Ti(a,t,e){if(a.tipo!=="LineString"&&a.tipo!=="Polygon")return a;const o=Z(a).slice();return t<0||t>=o.length?a:(o.splice(t+1,0,e),qt(a,o))}function Di(a,t){if(a.tipo!=="LineString"&&a.tipo!=="Polygon")return null;const e=Z(a);return t<0||t>=e.length||e.length<=Lt(a)?null:qt(a,e.filter((o,i)=>i!==t))}function Ue(a,t){return[(a[0]+t[0])/2,(a[1]+t[1])/2]}function We(a){const t=Z(a).length,e=[];if(a.tipo!=="LineString"&&a.tipo!=="Polygon")return e;for(let o=0;o<t-1;o++)e.push([o,o+1]);return a.tipo==="Polygon"&&t>2&&e.push([t-1,0]),e}function j(a){return(a.tipo==="LineString"||a.tipo==="Polygon")&&a.curva&&a.curva.length>=Lt(a)?a.curva:null}const Ln=63710088e-1*Math.PI/180,$i=.5;function qi(a,t){const e=Math.max(.01,Math.cos(a[0]*Math.PI/180));return[a[0],a[1]+t/(Ln*e)]}function ht(a){var t;return a.tipo==="Circle"?[a.centro,qi(a.centro,a.raioMetros)]:((t=j(a))==null?void 0:t.map(e=>e.ponto))??Z(a)}function St(a,t){const e=a.tipo==="Polygon",o=Pt(t,e);return e?{tipo:"Polygon",aneis:[o],curva:t}:{tipo:"LineString",coordenadas:o,curva:t}}function Ni(a,t){if(a.tipo==="Circle")return t.length<2?a:{...a,centro:t[0],raioMetros:Math.max($i,et(t[0],t[1]))};const e=j(a);if(!e||e.length!==t.length)return qt(a,t);const o=e.map((i,n)=>{const s=t[n][0]-i.ponto[0],r=t[n][1]-i.ponto[1],c=d=>[d[0]+s,d[1]+r],l={ponto:t[n]};return i.entrada&&(l.entrada=c(i.entrada)),i.saida&&(l.saida=c(i.saida)),l});return St(a,o)}function ft(a,t,e){return[a[0]+(t[0]-a[0])*e,a[1]+(t[1]-a[1])*e]}function Sn(a,t,e){const[o,i]=$t(a,t);let n=.5,s=1/0;for(let r=1;r<64;r++){const c=r/64,l=He(a.ponto,o,i,t.ponto,c),d=(l[0]-e[0])**2+(l[1]-e[1])**2;d<s&&(s=d,n=c)}return n}function gt(a,t,e){const o=j(a);if(!o){const s=Z(a);return Ue(s[t],s[e])}const[i,n]=$t(o[t],o[e]);return He(o[t].ponto,i,n,o[e].ponto,.5)}function Xe(a){const t=j(a);if(!t)return We(a);const e=[];for(let o=0;o<t.length-1;o++)e.push([o,o+1]);return a.tipo==="Polygon"&&t.length>2&&e.push([t.length-1,0]),e}function Oi(a,t,e){const o=j(a);if(!o)return Ti(a,t,e);if(t<0||t>=o.length)return a;const i=(t+1)%o.length,n=o[t],s=o[i],r=n.saida===void 0&&s.entrada===void 0;let c,l=n,d=s;if(r)c={ponto:e};else{const u=Sn(n,s,e),[g,m]=$t(n,s),f=ft(n.ponto,g,u),x=ft(g,m,u),E=ft(m,s.ponto,u),M=ft(f,x,u),A=ft(x,E,u);c={ponto:ft(M,A,u),entrada:M,saida:A},l={...n,saida:f},d={...s,entrada:E}}const h=o.slice();return h[t]=l,h[i]=d,h.splice(t+1,0,c),St(a,h)}function Ri(a,t){const e=j(a);return e?t<0||t>=e.length||e.length<=Lt(a)?null:St(a,e.filter((o,i)=>i!==t)):Di(a,t)}function Fi(a){return a.tipo!=="LineString"&&a.tipo!=="Polygon"?null:j(a)??Z(a).map(t=>({ponto:[t[0],t[1]]}))}function Bi(a,t,e,o,i=!0){const n=Fi(a);if(!n||t<0||t>=n.length)return a;const s={...n[t],[e]:o};i&&(s[e==="saida"?"entrada":"saida"]=Ve(s.ponto,o));const r=n.slice();return r[t]=s,St(a,r)}function Vi(a,t){const e=Fi(a);if(!e||t<0||t>=e.length)return a;const o=e[t],i=e.slice();if(o.entrada||o.saida)return i[t]={ponto:o.ponto},St(a,i);const n=a.tipo==="Polygon",s=e.length,r=t>0?e[t-1]:n?e[s-1]:null,c=t<s-1?e[t+1]:n?e[0]:null;if(!r&&!c)return a;const l=o.ponto;let d,h;if(r&&c)d=(c.ponto[0]-r.ponto[0])/6,h=(c.ponto[1]-r.ponto[1])/6;else{const u=(c??r).ponto,g=c?1:-1;d=(u[0]-l[0])/3*g,h=(u[1]-l[1])/3*g}return i[t]={ponto:l,saida:[l[0]+d,l[1]+h],entrada:[l[0]-d,l[1]-h]},St(a,i)}const Hi={topo:0,base:16,esquerda:0,direita:0},Gi=16,ji=.92,Wt={topo:"--cad-hud-topo",base:"--cad-hud-base",esquerda:"--cad-hud-esquerda",direita:"--cad-hud-direita"},Ze="position:absolute;box-sizing:border-box;z-index:10000;left:calc(var(--cad-hud-esquerda,0px) + (100% - var(--cad-hud-esquerda,0px) - var(--cad-hud-direita,0px)) / 2);bottom:var(--cad-hud-base,16px);transform:translateX(-50%);width:max-content;max-width:min(92%, calc(100% - var(--cad-hud-esquerda,0px) - var(--cad-hud-direita,0px) - 16px));max-height:calc(100% - var(--cad-hud-topo,0px) - var(--cad-hud-base,16px) - 8px);overflow:hidden;display:flex;flex-wrap:wrap;";function Mn(a,t,e={}){const o={...Hi,...e},i=Math.max(0,a-o.esquerda-o.direita);return{centroX:o.esquerda+i/2,base:o.base,larguraMax:Math.max(0,Math.min(a*ji,i-Gi)),alturaMax:Math.max(0,t-o.topo-o.base-8)}}function Ui(a,t){for(const e of Object.keys(Wt)){const o=t[e];typeof o=="number"&&Number.isFinite(o)&&o>=0?a.style.setProperty(Wt[e],`${o}px`):a.style.removeProperty(Wt[e])}}const Wi="cm-vertex-edit-hud",lt="cad-edicao-vertices",Bt="#facc15",So="#f472b6",An="#22d3ee",wn=600,En=100,zn=24,kn=2500,be=(a,t)=>a===t||JSON.stringify(a)===JSON.stringify(t);class Xi{constructor(t){p(this,"feicaoAtual",null);p(this,"base",null);p(this,"inicial",null);p(this,"historico",[]);p(this,"refeitos",[]);p(this,"pts",[]);p(this,"alcas",[]);p(this,"fantasmas",[]);p(this,"alcasBezier",[]);p(this,"marcadorSnap",null);p(this,"hud",null);p(this,"grupo",null);p(this,"ultimaInsercao",0);p(this,"selecionado",null);p(this,"arrastando",0);p(this,"gravando",!1);p(this,"retangulo",!1);p(this,"avisoTimer",null);p(this,"aoZoom",()=>{this.feicaoAtual&&this.arrastando===0&&this.reconstruir()});p(this,"aoTecla",t=>{if(!this.feicaoAtual||t.defaultPrevented||Dt(t))return;const e=t.ctrlKey||t.metaKey,o=t.key.toLowerCase();if(e&&!t.altKey&&o==="z")t.shiftKey?this.refazer():this.desfazer();else if(e&&!t.altKey&&o==="y")this.refazer();else if(t.key==="Delete"||t.key==="Backspace"){if(this.selecionado===null)return;this.excluir(this.selecionado)}else if(t.key==="Enter")this.parar();else return;t.preventDefault()});this.dep=t}get ativo(){return this.feicaoAtual!==null}get ehCirculo(){var t;return((t=this.feicaoAtual)==null?void 0:t.geometria.tipo)==="Circle"}get feicao(){return this.feicaoAtual}get noSelecionado(){return this.selecionado}get podeDesfazer(){return this.historico.length>0}get podeRefazer(){return this.refeitos.length>0}iniciar(t){this.parar(),this.feicaoAtual=t,this.base=t,this.inicial=t,this.historico=[],this.refeitos=[],this.selecionado=null,this.pts=ht(t.geometria).map(o=>[o[0],o[1]]),this.retangulo=this.detectarRetangulo();const e=this.dep.map;if(!e.getPane(lt)){const o=e.createPane(lt);o.style.zIndex="9000"}this.grupo=y.layerGroup().addTo(e),e.on("zoomend",this.aoZoom),window.addEventListener("keydown",this.aoTecla),this.montarHud(),this.reconstruir()}parar(){var e,o;const t=this.feicaoAtual;t&&(this.feicaoAtual=null,this.base=null,this.inicial=null,this.historico=[],this.refeitos=[],this.selecionado=null,this.arrastando=0,this.alcas=[],this.fantasmas=[],this.alcasBezier=[],this.dep.map.off("zoomend",this.aoZoom),window.removeEventListener("keydown",this.aoTecla),this.avisoTimer&&clearTimeout(this.avisoTimer),this.avisoTimer=null,(e=this.grupo)==null||e.remove(),this.grupo=null,this.marcadorSnap=null,(o=this.hud)==null||o.remove(),this.hud=null,this.dep.aoEncerrar(t))}cancelar(){const t=this.feicaoAtual,e=this.inicial;if(!(!t||!e)){if(!be(e.geometria,t.geometria)){const o={...t,geometria:e.geometria};this.dep.previsualizar(o),this.gravar(o)}this.parar()}}sincronizar(t){if(!(!this.feicaoAtual||this.feicaoAtual.id!==t.id)){if(this.gravando){this.feicaoAtual=t,this.base=t,this.ehCirculo&&this.circuloCompativel(t)||(this.pts=ht(t.geometria).map(e=>[e[0],e[1]])),this.retangulo=this.detectarRetangulo(),this.reconstruir();return}if(this.arrastando>0){this.feicaoAtual={...t,geometria:this.feicaoAtual.geometria};return}if(this.base&&be(t.geometria,this.base.geometria)){this.feicaoAtual=t,this.base=t;return}this.feicaoAtual=t,this.base=t,this.inicial=t,this.historico=[],this.refeitos=[],this.selecionado=null,this.pts=ht(t.geometria).map(e=>[e[0],e[1]]),this.retangulo=this.detectarRetangulo(),this.reconstruir()}}circuloCompativel(t){const e=t.geometria;return e.tipo!=="Circle"||this.pts.length<2?!1:e.centro[0]===this.pts[0][0]&&e.centro[1]===this.pts[0][1]&&Math.abs(et(this.pts[0],this.pts[1])-e.raioMetros)<.01}atualizarSnapNoHud(){var e;const t=(e=this.hud)==null?void 0:e.querySelector('[data-campo="snap"]');t&&(t.textContent=`Snap: ${this.dep.snapLigado()?"ligado":"desligado"} (S)`)}geometriaAtual(){return Ni(this.feicaoAtual.geometria,this.pts)}feicaoComPontos(){return{...this.feicaoAtual,geometria:this.geometriaAtual()}}detectarRetangulo(){var c;const t=(c=this.feicaoAtual)==null?void 0:c.geometria;if(!t||t.tipo!=="Polygon"||t.curva||this.pts.length!==4)return!1;const[e,o,i,n]=this.pts,s=e[0]===o[0]&&o[1]===i[1]&&i[0]===n[0]&&n[1]===e[1],r=e[1]===o[1]&&o[0]===i[0]&&i[1]===n[1]&&n[0]===e[0];return s||r}reconstruir(){var e;if((e=this.grupo)==null||e.clearLayers(),this.alcas=[],this.fantasmas=[],this.alcasBezier=[],!this.feicaoAtual||!this.grupo)return;this.selecionado!==null&&this.selecionado>=this.pts.length&&(this.selecionado=null);const t=this.feicaoAtual.geometria;if(this.pts.forEach((o,i)=>{const n=this.criarAlca(o,i);this.alcas.push(n),this.grupo.addLayer(n)}),this.criarAlcasBezier(),t.tipo!=="Point")for(const[o,i]of Xe(this.geometriaAtual())){if(!this.segmentoLongoNaTela(o,i))continue;const n=this.criarFantasma(o,i);this.fantasmas.push(n),this.grupo.addLayer(n.marker)}this.atualizarHud()}segmentoLongoNaTela(t,e){const o=this.pts[t],i=this.pts[e];if(!o||!i)return!1;const n=this.dep.map.latLngToContainerPoint(o),s=this.dep.map.latLngToContainerPoint(i);return Math.hypot(n.x-s.x,n.y-s.y)>=zn}icone(t,e,o){return y.divIcon({className:`custom-leaflet-marker ${t}`,iconSize:[e,e],html:`<div style="width:${e}px;height:${e}px;box-sizing:border-box;${o}"></div>`})}iconeAlca(t){const e=this.ehCirculo&&t===1,o=this.selecionado===t,i=o?An:Bt,n=o?"2px solid #fff;box-shadow:0 0 0 2px #0e7490":"2px solid #111";return this.icone("cad-vertex-handle",12,`background:${i};border:${n};border-radius:${e?"50%":"2px"};cursor:${e?"ew-resize":"move"}`)}criarAlca(t,e){const o=y.marker(t,{icon:this.iconeAlca(e),draggable:!0,pane:lt,keyboard:!1});return o.on("dragstart",()=>{this.arrastando++}),o.on("drag",i=>{const n=i.originalEvent;this.aoArrastar(o,e,!!(n!=null&&n.shiftKey))}),o.on("dragend",()=>{this.arrastando=Math.max(0,this.arrastando-1),this.esconderSnap(),this.selecionado=e,this.retangulo=this.detectarRetanguloDe(this.pts),this.confirmar(this.feicaoComPontos()),this.atualizarSelecaoVisual()}),o.on("click",i=>{y.DomEvent.stopPropagation(i.originalEvent),this.selecionarNo(e)}),o.on("contextmenu",i=>{y.DomEvent.preventDefault(i.originalEvent),y.DomEvent.stopPropagation(i.originalEvent),this.excluir(e)}),o.on("dblclick",i=>{y.DomEvent.stopPropagation(i.originalEvent),!(Date.now()-this.ultimaInsercao<wn)&&this.alternarSuave(e)}),o}detectarRetanguloDe(t){const e=this.pts;this.pts=t;try{return this.detectarRetangulo()}finally{this.pts=e}}selecionarNo(t){this.selecionado=t!==null&&t>=0&&t<this.pts.length?t:null,this.atualizarSelecaoVisual(),this.atualizarBotoes()}atualizarSelecaoVisual(){this.alcas.forEach((t,e)=>t.setIcon(this.iconeAlca(e))),this.atualizarBotoes()}criarAlcasBezier(){const t=this.feicaoAtual&&j(this.feicaoAtual.geometria);t&&t.forEach((e,o)=>this.completarAlcasDoNo(o))}completarAlcasDoNo(t){var o;const e=this.feicaoAtual&&((o=j(this.feicaoAtual.geometria))==null?void 0:o[t]);if(!(!e||!this.grupo))for(const i of["entrada","saida"]){const n=e[i];if(!n||this.alcasBezier.some(l=>l.i===t&&l.qual===i))continue;const s=y.polyline([e.ponto,n],{pane:lt,color:So,weight:1,opacity:.8,interactive:!1}),r=y.marker(n,{icon:this.icone("cad-bezier-handle",10,`background:#fff;border:2px solid ${So};border-radius:50%;cursor:move`),draggable:!0,pane:lt,keyboard:!1}),c={marker:r,haste:s,i:t,qual:i};r.on("dragstart",()=>{this.arrastando++}),r.on("drag",l=>{const d=l.originalEvent;this.aoArrastarAlca(c,!(d!=null&&d.shiftKey))}),r.on("dragend",()=>{this.arrastando=Math.max(0,this.arrastando-1),this.confirmar(this.feicaoAtual)}),this.alcasBezier.push(c),this.grupo.addLayer(s),this.grupo.addLayer(r)}}sincronizarAlcasBezier(){var e;const t=this.feicaoAtual&&j(this.feicaoAtual.geometria);if(t)for(const o of this.alcasBezier){const i=(e=t[o.i])==null?void 0:e[o.qual];i&&((o.marker.getLatLng().lat!==i[0]||o.marker.getLatLng().lng!==i[1])&&o.marker.setLatLng(i),o.haste.setLatLngs([t[o.i].ponto,i]))}}aoArrastarAlca(t,e){const o=this.feicaoAtual;if(!o)return;const{lat:i,lng:n}=t.marker.getLatLng(),s=Bi(o.geometria,t.i,t.qual,[i,n],e);this.feicaoAtual={...o,geometria:s},this.completarAlcasDoNo(t.i),this.sincronizarAlcasBezier(),this.dep.previsualizar(this.feicaoAtual),this.atualizarHud()}alternarSuave(t){const e=this.feicaoAtual;if(!e)return;const o=Vi(e.geometria,t);o!==e.geometria&&(this.feicaoAtual={...e,geometria:o},this.reconstruir(),this.dep.previsualizar(this.feicaoAtual),this.confirmar(this.feicaoAtual))}criarFantasma(t,e){const o=y.marker(gt(this.geometriaAtual(),t,e),{icon:this.icone("cad-vertex-ghost",9,`background:${Bt};opacity:.45;border:1px solid #111;border-radius:50%;cursor:copy`),pane:lt,keyboard:!1});return o.on("click",i=>{y.DomEvent.stopPropagation(i.originalEvent),this.ultimaInsercao=Date.now(),this.inserir(t,o.getLatLng())}),{marker:o,i:t,j:e}}aoArrastar(t,e,o=!1){var r;const i=this.feicaoAtual;if(!i)return;let n=[t.getLatLng().lat,t.getLatLng().lng];const s=this.dep.snapLigado()?this.dep.buscarSnap(n,{feicaoId:i.id,camadaId:i.camadaId,vertice:e}):null;if(s?(n=s.coordenada,t.setLatLng(n),this.mostrarSnap(n)):this.esconderSnap(),i.geometria.tipo==="Circle"&&e===0){const c=n[0]-this.pts[0][0],l=n[1]-this.pts[0][1];this.pts[1]=[this.pts[1][0]+c,this.pts[1][1]+l],(r=this.alcas[1])==null||r.setLatLng(this.pts[1])}this.retangulo&&!o?this.moverCantoDoRetangulo(e,n):this.pts[e]=n;for(const c of this.fantasmas)this.retangulo&&!o?c.marker.setLatLng(gt(this.geometriaAtual(),c.i,c.j)):(c.i===e||c.j===e)&&c.marker.setLatLng(gt(this.geometriaAtual(),c.i,c.j));this.dep.previsualizar(this.feicaoComPontos()),this.atualizarAlcasDoNo(e),this.atualizarHud()}moverCantoDoRetangulo(t,e){var r,c;const o=this.pts[(t+2)%4],i=(t+1)%4,n=(t+3)%4,s=this.pts[i][0]===this.pts[t][0];this.pts[t]=e,this.pts[i]=s?[e[0],o[1]]:[o[0],e[1]],this.pts[n]=s?[o[0],e[1]]:[e[0],o[1]],(r=this.alcas[i])==null||r.setLatLng(this.pts[i]),(c=this.alcas[n])==null||c.setLatLng(this.pts[n])}atualizarAlcasDoNo(t){const e=j(this.geometriaAtual());if(e)for(const o of this.alcasBezier){if(o.i!==t)continue;const i=e[t][o.qual];i&&(o.marker.setLatLng(i),o.haste.setLatLngs([e[t].ponto,i]))}}inserir(t,e){if(!this.feicaoAtual)return;const i=Oi(this.geometriaAtual(),t,[e.lat,e.lng]);this.pts=ht(i).map(s=>[s[0],s[1]]),this.retangulo=!1,this.selecionado=t+1,this.reconstruir();const n=this.feicaoComPontos();this.dep.previsualizar(n),this.confirmar(n)}confirmar(t){const e=this.base;e&&!be(e.geometria,t.geometria)&&(this.historico.push(e),this.historico.length>En&&this.historico.shift(),this.refeitos=[]),this.feicaoAtual=t,this.base=t,this.gravar(t),this.atualizarBotoes()}gravar(t){this.gravando=!0;try{this.dep.aoGesto(t)}finally{this.gravando=!1}}excluir(t){if(!this.feicaoAtual)return!1;const o=this.geometriaAtual(),i=Ri(o,t);if(!i)return o.tipo==="Circle"?this.avisar("Círculo: mova o centro ou a borda (não há nós para excluir)."):o.tipo==="Point"?this.avisar("Um ponto tem um único nó."):this.avisar(`Mínimo de ${Lt(o)} nós: não dá para excluir mais.`),!1;this.pts=ht(i).map(s=>[s[0],s[1]]),this.retangulo=!1,this.selecionado=null,this.reconstruir();const n=this.feicaoComPontos();return this.dep.previsualizar(n),this.confirmar(n),!0}excluirSelecionado(){return this.selecionado===null?(this.avisar("Clique num nó para selecioná-lo e então exclua."),!1):this.excluir(this.selecionado)}excluirVertice(t){const e=this.pts.length;return this.excluir(t),this.pts.length<e}inserirVerticeApos(t){if(t<0||t>=this.pts.length)return;const e=(t+1)%this.pts.length,o=gt(this.geometriaAtual(),t,e);this.inserir(t,y.latLng(o[0],o[1]))}desfazer(){const t=this.historico.pop();return!t||!this.base?(this.avisar("Nada a desfazer."),!1):(this.refeitos.push(this.base),this.aplicarEstado(t),!0)}refazer(){const t=this.refeitos.pop();return!t||!this.base?(this.avisar("Nada a refazer."),!1):(this.historico.push(this.base),this.aplicarEstado(t),!0)}aplicarEstado(t){if(!this.feicaoAtual)return;const e={...this.feicaoAtual,geometria:t.geometria};this.feicaoAtual=e,this.base=e,this.pts=ht(e.geometria).map(o=>[o[0],o[1]]),this.retangulo=this.detectarRetangulo(),this.reconstruir(),this.dep.previsualizar(e),this.gravar(e),this.atualizarBotoes()}mostrarSnap(t){this.grupo&&(this.marcadorSnap?this.marcadorSnap.setLatLng(t):this.marcadorSnap=y.marker(t,{icon:y.divIcon({className:"custom-leaflet-marker cm-snap",iconSize:[18,18],html:'<div style="width:18px;height:18px;box-sizing:border-box;border:2px solid #22d3ee;transform:rotate(45deg);border-radius:2px"></div>'}),interactive:!1,pane:lt,keyboard:!1}).addTo(this.grupo))}esconderSnap(){var t;this.marcadorSnap&&((t=this.grupo)==null||t.removeLayer(this.marcadorSnap),this.marcadorSnap=null)}montarHud(){var d;const t=this.dep.map.getContainer(),e=document.createElement("div");e.id=Wi,e.style.cssText=Ze+"gap:12px;align-items:center;padding:6px 12px;border-radius:8px;background:rgba(15,23,42,.92);color:#fff;font:12px var(--ui-fonte-base,sans-serif);border:1px solid rgba(255,255,255,.2);pointer-events:auto";const o=h=>{const u=document.createElement("span");return u.dataset.campo=h,u},i=(h,u,g,m,f=!1)=>{const x=document.createElement("button");return x.type="button",x.dataset.acao=h,x.textContent=u,x.title=g,x.style.cssText=`padding:3px 10px;border-radius:4px;border:1px solid ${f?Bt:"rgba(255,255,255,.3)"};background:${f?Bt:"transparent"};color:${f?"#111":"#fff"};font-weight:600;cursor:pointer`,x.addEventListener("click",m),x},n=(d=this.feicaoAtual)==null?void 0:d.geometria.tipo,s=document.createElement("strong");s.textContent=this.ehCirculo?"Editando círculo":"Editando vértices";const r=o("snap");r.style.cursor="pointer",r.title="Alternar snap (S). Alt desliga temporariamente.",r.addEventListener("click",()=>this.dep.alternarSnap());const c=o("dica");c.style.opacity=".7",c.textContent=n==="Circle"?"Ctrl+Z desfaz · Enter conclui":n==="Point"?"Arraste para mover · Ctrl+Z desfaz · Enter conclui":"Clique no nó e Delete exclui · Duplo clique: curva ↔ canto · Ctrl+Z desfaz · Segure Shift durante o arraste: alças ou cantos independentes · Enter conclui";const l=o("aviso");l.style.color="#fbbf24",l.setAttribute("role","status"),e.append(s,o("nos"),o("medida"),r,c,l),e.append(i("desfazer","Desfazer","Desfazer o último gesto (Ctrl+Z)",()=>this.desfazer())),e.append(i("refazer","Refazer","Refazer (Ctrl+Shift+Z ou Ctrl+Y)",()=>this.refazer())),(n==="LineString"||n==="Polygon")&&e.append(i("excluir-no","Excluir nó","Exclui o nó selecionado (Delete); clique num nó para selecioná-lo",()=>this.excluirSelecionado())),e.append(i("cancelar","Cancelar","Descartar tudo o que foi alterado nesta edição",()=>this.cancelar())),e.append(i("concluir","Concluir","Concluir a edição (Enter ou Esc)",()=>this.parar(),!0)),y.DomEvent.disableClickPropagation(e),y.DomEvent.disableScrollPropagation(e),t.appendChild(e),this.hud=e,this.atualizarSnapNoHud(),this.atualizarBotoes()}atualizarBotoes(){if(!this.hud)return;const t={desfazer:this.historico.length>0,refazer:this.refeitos.length>0,"excluir-no":this.selecionado!==null};for(const[e,o]of Object.entries(t)){const i=this.hud.querySelector(`[data-acao="${e}"]`);i&&(i.disabled=!o,i.style.opacity=o?"1":".4",i.style.cursor=o?"pointer":"default")}}avisar(t){var o;const e=(o=this.hud)==null?void 0:o.querySelector('[data-campo="aviso"]');e&&(e.textContent=t,this.avisoTimer&&clearTimeout(this.avisoTimer),this.avisoTimer=setTimeout(()=>{e.textContent="",this.avisoTimer=null},kn))}atualizarHud(){if(!this.hud||!this.feicaoAtual)return;const t=this.geometriaAtual(),e=this.hud.querySelector('[data-campo="nos"]'),o=this.hud.querySelector('[data-campo="medida"]');e&&(e.textContent=t.tipo==="Circle"?"Centro move · borda muda o raio":`Nós: ${this.pts.length} (mín. ${Lt(t)})`),o&&(t.tipo==="Polygon"?o.textContent=`Área: ${rt(Q(t)??0)} · Perímetro: ${G(tt(t)??0)}`:t.tipo==="LineString"?o.textContent=`Extensão: ${G(tt(t)??0)}`:t.tipo==="Point"?o.textContent=`${t.coordenada[0].toFixed(6)}, ${t.coordenada[1].toFixed(6)}`:t.tipo==="Circle"&&(o.textContent=`Raio: ${G(t.raioMetros)} · Área: ${rt(Q(t)??0)}`))}vertices(){return this.pts.map(t=>[t[0],t[1]])}get totalAlcasBezier(){return this.alcasBezier.length}arrastarAlcaPara(t,e,o,i=!1){const n=this.alcasBezier.find(s=>s.i===t&&s.qual===e);n&&(n.marker.setLatLng(o),this.aoArrastarAlca(n,!i),this.confirmar(this.feicaoAtual))}alternarSuavidadeDoNo(t){this.alternarSuave(t)}arrastarPara(t,e,o=!1){const i=this.alcas[t];i&&(i.setLatLng(e),this.aoArrastar(i,t,o),i.fire("dragend"))}}const Ye=10,wt=(a,t)=>Math.hypot(a.x-t.x,a.y-t.y);function Mo(a,t,e){const o=e.x-t.x,i=e.y-t.y,n=o*o+i*i,s=n===0?0:Math.max(0,Math.min(1,((a.x-t.x)*o+(a.y-t.y)*i)/n));return{t:s,d:Math.hypot(a.x-(t.x+s*o),a.y-(t.y+s*i))}}function Zi(a,t,e,o={},i){const n=o.toleranciaPx??Ye,s=o.vertice!==!1,r=o.meio!==!1,c=o.aresta!==!1;let l=null,d=null,h=null;const u=(g,m)=>!g||m.distanciaPx<g.distanciaPx?m:g;for(const g of t){if(g.excluida||g.oculta)continue;const m=!!i&&i.feicaoId===g.id&&(i.camadaId===void 0||i.camadaId===g.camadaId),f=g.geometria,x={feicaoId:g.id,camadaId:g.camadaId};if(f.tipo==="Point"||f.tipo==="Text"||f.tipo==="Circle"){if(!s||m)continue;const C=f.tipo==="Circle"?f.centro:f.coordenada,b=wt(a,e(C));b<=n&&(l=u(l,{tipo:"vertice",coordenada:C,distanciaPx:b,...x}));continue}if(m&&(f.tipo==="LineString"||f.tipo==="Polygon")&&f.curva)continue;const E=f.tipo==="LineString"||f.tipo==="Polygon"?j(f):null;if(E){if(s)for(const C of E){const b=wt(a,e(C.ponto));b<=n&&(l=u(l,{tipo:"vertice",coordenada:C.ponto,distanciaPx:b,...x}))}if(r)for(const[C,b]of Xe(f)){const v=gt(f,C,b),P=wt(a,e(v));P<=n&&(d=u(d,{tipo:"meio",coordenada:v,distanciaPx:P,...x}))}if(c){const C=Z(f),b=C.map(e),v=[];for(let P=0;P<C.length-1;P++)v.push([P,P+1]);f.tipo==="Polygon"&&C.length>2&&v.push([C.length-1,0]);for(const[P,w]of v){const{t:k,d:L}=Mo(a,b[P],b[w]);if(L<=n){const z=[C[P][0]+k*(C[w][0]-C[P][0]),C[P][1]+k*(C[w][1]-C[P][1])];h=u(h,{tipo:"aresta",coordenada:z,distanciaPx:L,...x})}}}continue}const M=f.tipo==="LineString"?U(f).map(C=>({pts:C,fechado:!1})):[{pts:Z(f),fechado:f.tipo==="Polygon"}],A=m?i.vertice:void 0;for(const{pts:C,fechado:b}of M){const v=C.map(e);if(s)for(let w=0;w<C.length;w++){if(w===A)continue;const k=wt(a,v[w]);k<=n&&(l=u(l,{tipo:"vertice",coordenada:C[w],distanciaPx:k,...x}))}if(!r&&!c)continue;const P=[];for(let w=0;w<C.length-1;w++)P.push([w,w+1]);b&&C.length>2&&P.push([C.length-1,0]);for(const[w,k]of P)if(!(A!==void 0&&(w===A||k===A))&&!(m&&A===void 0)){if(r){const L=Ue(C[w],C[k]),z=wt(a,e(L));z<=n&&(d=u(d,{tipo:"meio",coordenada:L,distanciaPx:z,...x}))}if(c){const{t:L,d:z}=Mo(a,v[w],v[k]);if(z<=n){const I=[C[w][0]+L*(C[k][0]-C[w][0]),C[w][1]+L*(C[k][1]-C[w][1])];h=u(h,{tipo:"aresta",coordenada:I,distanciaPx:z,...x})}}}}}return l??d??h}class In{constructor(t){p(this,"_ligado",!0);p(this,"_altSegurado",!1);p(this,"atalhoS",!0);p(this,"conectado",!1);p(this,"aoTeclaBaixo",t=>{var e,o;if(t.key==="Alt"){this.definirAlt(!0);return}this.atalhoS&&(t.key==="s"||t.key==="S")&&!t.ctrlKey&&!t.metaKey&&!t.altKey&&!Dt(t)&&(((o=(e=this.contexto).aplica)==null?void 0:o.call(e))??!0)&&this.alternar()});p(this,"aoTeclaCima",t=>{t.key==="Alt"&&this.definirAlt(!1)});p(this,"aoPerderFoco",()=>{this.definirAlt(!1)});this.contexto=t}get ativo(){return this._ligado&&!this._altSegurado}get ligado(){return this._ligado}definir(t){this._ligado!==t&&(this._ligado=t,this.notificar())}alternar(){this.definir(!this._ligado)}conectar(){if(this.conectado)return;this.conectado=!0;const t=this.contexto.alvo??window;t.addEventListener("keydown",this.aoTeclaBaixo),t.addEventListener("keyup",this.aoTeclaCima),t.addEventListener("blur",this.aoPerderFoco)}desconectar(){if(!this.conectado)return;this.conectado=!1;const t=this.contexto.alvo??window;t.removeEventListener("keydown",this.aoTeclaBaixo),t.removeEventListener("keyup",this.aoTeclaCima),t.removeEventListener("blur",this.aoPerderFoco),this._altSegurado=!1}definirAlt(t){this._altSegurado!==t&&(this._altSegurado=t,this.notificar())}notificar(){this.contexto.aoMudar({ativo:this.ativo,ligado:this._ligado,temporario:this._altSegurado})}}const Ao=36,_n=.45;function Tn(a,t){const e=Math.abs(t[0]-a[0]),o=Math.abs(t[1]-a[1]);if(e===0&&o===0)return null;const i=[];for(let n=0;n<Ao;n++){const s=n*2*Math.PI/Ao;i.push([a[0]+e*Math.sin(s),a[1]+o*Math.cos(s)])}return i}function Yi(a,t){const e=Math.cos(a[0]*Math.PI/180)||1,o=t[0]-a[0],i=(t[1]-a[1])*e,n=Math.hypot(o,i);return n===0?null:{raio:n,inicio:Math.atan2(o,i),cosLat:e}}function Dn(a,t,e=6){const o=Yi(a,t);if(!o||e<3)return null;const i=[];for(let n=0;n<e;n++){const s=o.inicio+n*2*Math.PI/e;i.push([a[0]+o.raio*Math.sin(s),a[1]+o.raio*Math.cos(s)/o.cosLat])}return i}function $n(a,t,e=5){const o=Yi(a,t);if(!o||e<3)return null;const i=e*2,n=[];for(let s=0;s<i;s++){const r=s%2===0?o.raio:o.raio*_n,c=o.inicio+s*2*Math.PI/i;n.push([a[0]+r*Math.sin(c),a[1]+r*Math.cos(c)/o.cosLat])}return n}const ce=["ponto","linha","poligono","retangulo","elipse","poligono-regular","estrela","circulo","texto","caneta","medir-distancia","medir-area","dividir","selecao-laco","conta-gotas"],Xt=2;function Ke(a){return typeof a=="string"&&ce.includes(a)}function Et(a){return a.map(t=>{const e={ponto:t.ponto};return t.alca&&(e.saida=t.alca,e.entrada=Ve(t.ponto,t.alca)),e})}function Ki(a){return Pt(Et(a),!1)}function Pe(a,t){const e=Qo(a);if(t){const i=e?Pt(a,!0):a.map(n=>n.ponto);return e?{tipo:"Polygon",aneis:[i],curva:a}:{tipo:"Polygon",aneis:[i]}}const o=e?Pt(a,!1):a.map(i=>i.ponto);return e?{tipo:"LineString",coordenadas:o,curva:a}:{tipo:"LineString",coordenadas:o}}const qn=(a,t)=>a[0]===t[0]&&a[1]===t[1],wo={elipse:Tn,"poligono-regular":(a,t)=>Dn(a,t,6),estrela:(a,t)=>$n(a,t,5)};class Zt{constructor(t,e=!1){p(this,"pontos",[]);p(this,"cursor",null);p(this,"ancoras",[]);this.ferramenta=t,this.fechar=e}get nos(){return this.ferramenta==="caneta"?this.ancoras.length:this.pontos.length}get ehSequencial(){return["linha","poligono","caneta","medir-distancia","medir-area","dividir","selecao-laco"].includes(this.ferramenta)}get ehArea(){return this.ferramenta==="poligono"||this.ferramenta==="medir-area"||this.ferramenta==="selecao-laco"||this.ferramenta==="caneta"&&this.fechar}get fechaNoPrimeiro(){return this.nos>=3&&(this.ehArea||this.ferramenta==="caneta")}get primeiro(){var t;return(this.ferramenta==="caneta"?(t=this.ancoras[0])==null?void 0:t.ponto:this.pontos[0])??null}get minimo(){return this.ehArea?3:2}get podeConcluir(){return this.ehSequencial&&this.nos>=this.minimo}mover(t){this.cursor=t}clicar(t){switch(this.ferramenta){case"ponto":return{concluida:{tipo:"Point",coordenada:t}};case"texto":return{concluida:{tipo:"Text",coordenada:t,texto:""}};case"retangulo":if(this.pontos.length===0)return this.pontos.push(t),{};{const e=this.retangulo(this.pontos[0],t);return e?{concluida:e}:{aviso:"Os dois cantos precisam diferir em latitude e em longitude."}}case"circulo":if(this.pontos.length===0)return this.pontos.push(t),{};{const e=et(this.pontos[0],t);return e>=Xt?{concluida:{tipo:"Circle",centro:this.pontos[0],raioMetros:e}}:{aviso:`Raio mínimo de ${Xt} m: clique mais longe do centro.`}}case"elipse":case"poligono-regular":case"estrela":{if(this.pontos.length===0)return this.pontos.push(t),{};const e=wo[this.ferramenta](this.pontos[0],t);return e?{concluida:{tipo:"Polygon",aneis:[e]}}:{aviso:"Clique num ponto diferente do centro."}}case"caneta":return this.ancoras.push({ponto:t}),{};case"conta-gotas":return{};default:return this.pontos.length>0&&qn(this.pontos[this.pontos.length-1],t)?{}:(this.pontos.push(t),{})}}definirAlca(t){const e=this.ancoras[this.ancoras.length-1];this.ferramenta==="caneta"&&e&&(e.alca=t)}desfazer(){const t=this.ferramenta==="caneta"?this.ancoras:this.pontos;return t.length===0?!1:(t.pop(),!0)}vertices(){return this.ferramenta==="caneta"?Ki(this.ancoras):this.pontos}retangulo(t,e){return t[0]===e[0]||t[1]===e[1]?null:{tipo:"Polygon",aneis:[[[t[0],t[1]],[t[0],e[1]],[e[0],e[1]],[e[0],t[1]]]]}}previa(){const t=this.cursor;switch(this.ferramenta){case"retangulo":return this.pontos.length===1&&t?this.retangulo(this.pontos[0],t):null;case"circulo":{if(this.pontos.length!==1||!t)return null;const e=et(this.pontos[0],t);return e>=Xt?{tipo:"Circle",centro:this.pontos[0],raioMetros:e}:null}case"caneta":{if(this.ancoras.length===0)return null;const e=Et(t?[...this.ancoras,{ponto:t}]:this.ancoras);return e.length<2?null:Pe(e,this.ehArea&&e.length>=3)}case"elipse":case"poligono-regular":case"estrela":{if(this.pontos.length!==1||!t)return null;const e=wo[this.ferramenta](this.pontos[0],t);return e?{tipo:"Polygon",aneis:[e]}:null}case"ponto":case"texto":case"conta-gotas":return null;default:{const e=t?[...this.pontos,t]:[...this.pontos];return e.length<2?null:this.ehArea&&e.length>=3?{tipo:"Polygon",aneis:[e]}:{tipo:"LineString",coordenadas:e}}}}concluir(){if(!this.podeConcluir)return null;if(this.ferramenta==="caneta")return Pe(Et(this.ancoras),this.ehArea);const t=this.vertices();return this.ehArea?{tipo:"Polygon",aneis:[t]}:{tipo:"LineString",coordenadas:t}}concluirFechando(){return this.fechaNoPrimeiro?this.ferramenta==="caneta"?Pe(Et(this.ancoras),!0):{tipo:"Polygon",aneis:[this.vertices()]}:null}comprimentoMetros(){const t=this.cursor&&this.nos>0?[...this.vertices(),this.cursor]:this.vertices();return It(t,!1)}}const Ji="cm-draw-hud",De="cad-ferramenta-ativa",ot="cad-desenho",dt="#22d3ee",Nn=4,On=450,Rn=10,Fn=2500,Bn={ponto:"Ponto",linha:"Linha",poligono:"Polígono",retangulo:"Retângulo",elipse:"Elipse","poligono-regular":"Polígono regular (hexágono)",estrela:"Estrela",circulo:"Círculo",texto:"Texto",caneta:"Caneta (Bézier)","medir-distancia":"Medir distância","medir-area":"Medir área",dividir:"Dividir polígono","selecao-laco":"Seleção por laço","conta-gotas":"Conta-gotas"},Vn={ponto:"Clique para colocar",linha:"Clique nos vértices · Enter ou duplo clique conclui",poligono:"Clique nos vértices · Enter ou duplo clique conclui",retangulo:"Clique nos dois cantos",elipse:"Clique no centro e depois no canto da caixa","poligono-regular":"Clique no centro e depois num vértice",estrela:"Clique no centro e depois numa ponta",circulo:"Clique no centro e depois num ponto da borda",texto:"Clique onde o texto vai",caneta:"Clique e arraste para curvar · Enter conclui · 1º ponto fecha","medir-distancia":"Clique nos pontos · Enter conclui","medir-area":"Clique nos vértices · Enter conclui",dividir:"Desenhe a linha de corte · Enter aplica","selecao-laco":"Desenhe o laço · Enter ou 1º ponto fecha e seleciona","conta-gotas":"Clique numa feição para copiar o estilo"};class Qi{constructor(t){p(this,"sessao",null);p(this,"fechar",!1);p(this,"grupo",null);p(this,"previa",null);p(this,"marcas",null);p(this,"medicao",null);p(this,"marcadorSnap",null);p(this,"hud",null);p(this,"campoTexto",null);p(this,"arrastando",!1);p(this,"ultimoClique",null);p(this,"avisoTimer",null);p(this,"aoClicar",t=>{var n;const e=this.sessao;if(!e||e.ferramenta==="caneta"||this.campoTexto||((n=t.originalEvent)==null?void 0:n.button)!==void 0&&t.originalEvent.button!==0)return;const o=this.coordenada(t);if(e.ferramenta==="conta-gotas"){this.dep.aoAmostrar(o,t.originalEvent);return}if(e.ehSequencial&&this.repetido(t)||this.fechaNoPrimeiroVertice(t))return;const i=e.clicar(o);if(i.concluida){i.concluida.tipo==="Text"?this.pedirTexto(o):this.finalizar(i.concluida);return}this.atualizar(),i.aviso&&this.avisar(i.aviso)});p(this,"aoPressionar",t=>{var o;const e=this.sessao;!e||e.ferramenta!=="caneta"||((o=t.originalEvent)==null?void 0:o.button)!==0||this.repetido(t)||this.fechaNoPrimeiroVertice(t)||(e.clicar(this.coordenada(t)),this.arrastando=!0,this.atualizar())});p(this,"aoSoltar",()=>{this.arrastando=!1});p(this,"aoMover",t=>{const e=this.sessao;if(!e)return;const o=this.coordenada(t);e.mover(o),this.arrastando&&e.definirAlca(o),this.atualizar()});p(this,"aoDuploClique",()=>{this.concluir()});p(this,"aoTecla",t=>{const e=this.sessao;if(!e)return;const o=Dt(t);if(t.key==="Escape"){if(o&&!this.campoTexto)return;this.campoTexto?this.cancelarTexto():e.nos>0?this.reiniciar():this.desativar(),t.preventDefault();return}o||(t.key==="Enter"?(this.concluir(),t.preventDefault()):(t.key==="Backspace"||(t.ctrlKey||t.metaKey)&&t.key.toLowerCase()==="z")&&(e.desfazer()&&this.atualizar(),t.preventDefault()))});this.dep=t}get ferramenta(){var t;return((t=this.sessao)==null?void 0:t.ferramenta)??null}get ativo(){return this.sessao!==null}get nos(){var t;return((t=this.sessao)==null?void 0:t.nos)??0}desfazerVertice(){var t;return(t=this.sessao)!=null&&t.desfazer()?(this.atualizar(),!0):!1}ativar(t,e={}){var s;const o=(s=this.sessao)==null?void 0:s.ferramenta;this.desligar(),o&&this.dep.aoDesativar(o),this.limparMedicao();const i=this.dep.map;this.fechar=!!e.fechar,this.sessao=new Zt(t,this.fechar),i.getPane(ot)||(i.createPane(ot).style.zIndex="8500"),this.grupo=y.layerGroup().addTo(i),this.marcas=y.layerGroup().addTo(this.grupo);const n=i.getContainer();n.classList.add(De),n.style.cursor=t==="conta-gotas"?"copy":"crosshair",i.on("click",this.aoClicar),i.on("dblclick",this.aoDuploClique),i.on("mousemove",this.aoMover),i.on("mousedown",this.aoPressionar),window.addEventListener("mouseup",this.aoSoltar),window.addEventListener("keydown",this.aoTecla),this.montarHud(),this.atualizar()}desativar(){var e;const t=(e=this.sessao)==null?void 0:e.ferramenta;t&&(this.desligar(),this.dep.aoDesativar(t))}limparMedicao(){var t;(t=this.medicao)==null||t.remove(),this.medicao=null}desligar(){var o,i;const t=this.dep.map;t.off("click",this.aoClicar),t.off("dblclick",this.aoDuploClique),t.off("mousemove",this.aoMover),t.off("mousedown",this.aoPressionar),window.removeEventListener("mouseup",this.aoSoltar),window.removeEventListener("keydown",this.aoTecla);const e=t.getContainer();e.classList.remove(De),e.style.cursor="",(o=this.grupo)==null||o.remove(),this.grupo=null,this.previa=null,this.marcas=null,this.marcadorSnap=null,this.avisoTimer&&clearTimeout(this.avisoTimer),this.avisoTimer=null,(i=this.hud)==null||i.remove(),this.hud=null,this.campoTexto=null,this.sessao=null,this.arrastando=!1,this.ultimoClique=null}coordenada(t){const e=[t.latlng.lat,t.latlng.lng];if(!this.dep.snapAtivo())return this.esconderSnap(),e;const o=this.dep.buscarSnap(e);return o?(this.mostrarSnap(o.coordenada),o.coordenada):(this.esconderSnap(),e)}repetido(t){const e=this.ultimoClique,o=Date.now(),i=t.containerPoint,n=!!e&&Math.hypot(e.x-i.x,e.y-i.y)<=Nn&&o-e.t<=On;return this.ultimoClique={x:i.x,y:i.y,t:o},n}fechaNoPrimeiroVertice(t){const e=this.sessao,o=e==null?void 0:e.primeiro;if(!e||!o||!e.fechaNoPrimeiro)return!1;const i=this.dep.map.latLngToContainerPoint(o);if(Math.hypot(i.x-t.containerPoint.x,i.y-t.containerPoint.y)>Rn)return!1;const n=e.concluirFechando();return n&&this.finalizar(n),!!n}concluir(){const t=this.sessao;if(!t)return;const e=t.concluir();e?this.finalizar(e):t.ehSequencial&&t.nos>0&&!t.podeConcluir&&this.avisar(`Faltam ${t.minimo-t.nos} ponto(s): mínimo de ${t.minimo}.`)}avisar(t){var o;const e=(o=this.hud)==null?void 0:o.querySelector('[data-campo="aviso"]');e&&(e.textContent=t,this.avisoTimer&&clearTimeout(this.avisoTimer),this.avisoTimer=setTimeout(()=>{e.textContent="",this.avisoTimer=null},Fn))}botaoDireito(){const t=this.sessao;if(t){if(this.campoTexto){this.cancelarTexto();return}t.podeConcluir?this.concluir():t.nos>0&&t.desfazer()?this.atualizar():this.desativar()}}reiniciar(){var e;const t=(e=this.sessao)==null?void 0:e.ferramenta;t&&(this.sessao=new Zt(t,this.fechar),this.ultimoClique=null,this.arrastando=!1,this.atualizar())}finalizar(t){const e=this.sessao.ferramenta,o=e==="medir-distancia"||e==="medir-area"?this.mostrarMedicao(t,e):null;this.sessao=new Zt(e,this.fechar),this.ultimoClique=null,this.atualizar(),o&&this.dep.aoMedir(o),this.dep.aoGeometria(e,t)}pedirTexto(t){var o,i;if(!this.hud||(i=(o=this.dep).aoSolicitarTexto)!=null&&i.call(o,t)||!this.hud)return;const e=document.createElement("input");e.type="text",e.placeholder="Texto…",e.style.cssText="padding:3px 6px;border-radius:4px;border:1px solid #475569;background:#0f172a;color:#fff;min-width:160px",e.addEventListener("keydown",n=>{if(n.stopPropagation(),n.key==="Enter"){const s=e.value.trim();this.cancelarTexto(),s&&this.finalizar({tipo:"Text",coordenada:t,texto:s})}else n.key==="Escape"&&this.cancelarTexto()}),this.campoTexto=e,this.hud.insertBefore(e,this.hud.querySelector('[data-campo="dica"]')),e.focus()}cancelarTexto(){var t;(t=this.campoTexto)==null||t.remove(),this.campoTexto=null}atualizar(){const t=this.sessao;if(!t||!this.grupo||!this.marcas)return;this.previa&&(this.grupo.removeLayer(this.previa),this.previa=null);const e=t.previa();e&&(this.previa=this.desenharGeometria(e,!0),this.grupo.addLayer(this.previa)),this.marcas.clearLayers();const o=t.ferramenta==="caneta"?t.ancoras.map(i=>i.ponto):t.pontos;if(t.ferramenta==="caneta")for(const i of t.ancoras){if(!i.alca)continue;const n=Ve(i.ponto,i.alca);this.marcas.addLayer(y.polyline([n,i.alca],{pane:ot,color:dt,weight:1,opacity:.8,interactive:!1}));for(const s of[n,i.alca])this.marcas.addLayer(y.circleMarker(s,{pane:ot,radius:3,color:dt,weight:1,fillColor:"#fff",fillOpacity:1,interactive:!1}))}for(const i of o)this.marcas.addLayer(y.circleMarker(i,{pane:ot,radius:4,color:"#111",weight:1,fillColor:dt,fillOpacity:1,interactive:!1}));this.atualizarHud(e)}desenharGeometria(t,e){const o={pane:ot,color:dt,weight:2,dashArray:e?"6 4":void 0,fillColor:dt,fillOpacity:.15,interactive:!1},i=ni(t,o);if(i)return i;if(t.tipo==="Polygon")return y.polygon(t.aneis,o);if(t.tipo==="Circle")return y.circle(t.centro,{...o,radius:t.raioMetros});if(t.tipo==="LineString")return y.polyline(t.coordenadas,o);const n=(t.tipo==="Point",t.coordenada);return y.circleMarker(n,{...o,radius:5})}mostrarMedicao(t,e){this.limparMedicao();const o=y.layerGroup().addTo(this.dep.map);this.medicao=o,o.addLayer(this.desenharGeometria(t,!1));const i=t.tipo==="Polygon"?t.aneis[0]:t.tipo==="LineString"?t.coordenadas:[],n=t.tipo==="Polygon",s=(l,d)=>{const h=document.createElement("div");h.textContent=d,h.style.cssText="white-space:nowrap;font:600 11px sans-serif;color:#fff;background:rgba(15,23,42,.85);padding:1px 5px;border-radius:3px;transform:translate(-50%,-50%)",o.addLayer(y.marker(l,{pane:ot,interactive:!1,keyboard:!1,icon:y.divIcon({className:"custom-leaflet-marker",iconSize:void 0,html:h})}))},r=n?i.length:i.length-1;for(let l=0;l<r;l++){const d=i[l],h=i[(l+1)%i.length];s([(d[0]+h[0])/2,(d[1]+h[1])/2],G(et(d,h)))}const c={tipo:e==="medir-area"?"area":"distancia",pontos:i,comprimentoM:It(i,!1)};if(t.tipo==="Polygon")c.areaM2=Q(t)??0,c.perimetroM=tt(t)??0;else if(e==="medir-distancia"&&i.length>=3){const l={tipo:"Polygon",aneis:[i]};c.areaM2=Q(l)??0,c.perimetroM=tt(l)??0}return c}mostrarSnap(t){this.grupo&&(this.marcadorSnap?this.marcadorSnap.setLatLng(t):this.marcadorSnap=y.marker(t,{pane:ot,interactive:!1,keyboard:!1,icon:y.divIcon({className:"custom-leaflet-marker cm-snap",iconSize:[18,18],html:'<div style="width:18px;height:18px;box-sizing:border-box;border:2px solid #22d3ee;transform:rotate(45deg);border-radius:2px"></div>'})}).addTo(this.grupo))}esconderSnap(){var t;this.marcadorSnap&&((t=this.grupo)==null||t.removeLayer(this.marcadorSnap),this.marcadorSnap=null)}montarHud(){const t=this.sessao;if(!t)return;const e=document.createElement("div");e.id=Ji,e.style.cssText=Ze+"gap:10px;align-items:center;padding:6px 12px;border-radius:8px;background:rgba(15,23,42,.92);color:#fff;font:12px var(--ui-fonte-base,sans-serif);border:1px solid rgba(255,255,255,.2);pointer-events:auto";const o=c=>{const l=document.createElement("span");return l.dataset.campo=c,l},i=document.createElement("strong");i.textContent=Bn[t.ferramenta];const n=o("dica");n.style.opacity=".7",n.textContent=Vn[t.ferramenta];const s=(c,l,d=!1)=>{const h=document.createElement("button");return h.type="button",h.textContent=c,h.style.cssText=`padding:3px 10px;border-radius:4px;border:1px solid ${d?dt:"rgba(255,255,255,.3)"};background:${d?dt:"transparent"};color:${d?"#111":"#fff"};cursor:pointer;font-weight:600`,h.addEventListener("click",l),h},r=o("aviso");r.style.color="#fbbf24",r.setAttribute("role","status"),e.append(i,o("nos"),o("medida"),n,r),t.ehSequencial&&e.append(s("Concluir",()=>this.concluir(),!0)),e.append(s("Sair",()=>this.desativar())),y.DomEvent.disableClickPropagation(e),y.DomEvent.disableScrollPropagation(e),this.dep.map.getContainer().appendChild(e),this.hud=e}atualizarHud(t){const e=this.sessao;if(!this.hud||!e)return;const o=this.hud.querySelector('[data-campo="nos"]'),i=this.hud.querySelector('[data-campo="medida"]');if(o&&(o.textContent=e.nos>0?`Nós: ${e.nos}`:""),!i)return;let n="";if((t==null?void 0:t.tipo)==="Polygon")n=`Área: ${rt(Q(t)??0)} · Perímetro: ${G(tt(t)??0)}`;else if((t==null?void 0:t.tipo)==="LineString"){if(n=`Extensão: ${G(e.comprimentoMetros())}`,e.ferramenta==="medir-distancia"&&e.nos>=3&&t.coordenadas.length>=3){const s={tipo:"Polygon",aneis:[t.coordenadas]};n+=` · Área: ${rt(Q(s)??0)} · Perímetro: ${G(tt(s)??0)}`}}else(t==null?void 0:t.tipo)==="Circle"&&(n=`Raio: ${G(t.raioMetros)}`);i.textContent=n}clicarEm(t){const e=this.sessao;if(!e)return;const o=e.clicar(t);o.concluida?o.concluida.tipo==="Text"?this.pedirTexto(t):this.finalizar(o.concluida):(this.atualizar(),o.aviso&&this.avisar(o.aviso))}moverPara(t){var e;(e=this.sessao)==null||e.mover(t),this.atualizar()}}const ta=6,Ce=(a,t)=>Math.hypot(a.x-t.x,a.y-t.y);function Eo(a,t,e){const o=e.x-t.x,i=e.y-t.y,n=o*o+i*i,s=n===0?0:Math.max(0,Math.min(1,((a.x-t.x)*o+(a.y-t.y)*i)/n));return Math.hypot(a.x-(t.x+s*o),a.y-(t.y+s*i))}function Hn(a,t){const e=a.geometria;if(e.tipo!=="Polygon")return 0;const o=e.aneis[0].map(t),i=o.map(s=>s.x),n=o.map(s=>s.y);return(Math.max(...i)-Math.min(...i))*(Math.max(...n)-Math.min(...n))}function $e(a,t,e,o=ta){let i=null,n=null,s=null;for(const r of t){if(r.excluida||r.oculta)continue;const c=r.geometria;if(c.tipo==="Point"||c.tipo==="Text"){const l=Ce(a,e(c.coordenada));l<=o+2&&(!i||l<i.d)&&(i={f:r,d:l})}else if(c.tipo==="LineString"){let l=1/0;for(const d of U(c)){const h=d.map(e);for(let u=1;u<h.length;u++)l=Math.min(l,Eo(a,h[u-1],h[u]))}l<=o&&(!n||l<n.d)&&(n={f:r,d:l})}else if(c.tipo==="Circle"){const l=e(c.centro),d=e([c.centro[0]+c.raioMetros/111320,c.centro[1]]),h=Ce(l,d);if(Ce(a,l)<=h){const u=Math.PI*h*h;(!s||u<s.a)&&(s={f:r,a:u})}}else{const l=c.aneis[0].map(e);let d=1/0;for(const[u,g]of We(c))d=Math.min(d,Eo(a,l[u],l[g]));if(je([a.y,a.x],[l.map(u=>[u.y,u.x]),...c.aneis.slice(1).map(u=>u.map(e).map(g=>[g.y,g.x]))])||d<=o){const u=Hn(r,e);(!s||u<s.a)&&(s={f:r,a:u})}}}return(i==null?void 0:i.f)??(n==null?void 0:n.f)??(s==null?void 0:s.f)??null}const V="feicoes",Gn=new Set(["ponto","linha","poligono","retangulo","elipse","poligono-regular","estrela","circulo","texto","caneta"]);class jn{constructor(t){p(this,"selecao");p(this,"popup");p(this,"editor",null);p(this,"vigiaCamadaEmEdicao",null);p(this,"snap");p(this,"desenho",null);p(this,"camadaDesenho",null);p(this,"estiloDesenho",{});p(this,"sequenciaId",0);p(this,"regra");p(this,"cacheOficiais",new WeakMap);p(this,"posicoes",new Map);p(this,"cursores");p(this,"hoverId",null);p(this,"hoverAgendado",!1);p(this,"margensHud",{});p(this,"aceitarOrigem",!1);p(this,"opcoesPopup",{copiarParaAreaDeTransferencia:!0});p(this,"aoTeclaEdicao",t=>{var n,s,r,c;if(t.key!=="Enter"||t.defaultPrevented||t.ctrlKey||t.metaKey||t.altKey||t.shiftKey||(n=this.editor)!=null&&n.ativo||(s=this.desenho)!=null&&s.ativo||Dt(t)||!this.atalhosValem())return;const e=((r=t.composedPath)==null?void 0:r.call(t)[0])??t.target;if((c=e==null?void 0:e.closest)!=null&&c.call(e,'button, a, summary, select, [role="button"]'))return;const o=this.selecao.obter();if(o.length!==1)return;const i=this.contexto.obterLayerManager().getLayerDef(o[0].camadaId);Ut(o[0],!!(i!=null&&i.bloqueada))===null&&this.iniciarEdicao(o[0].camadaId,o[0].id).ok&&t.preventDefault()});this.contexto=t,this.regra=t.regra??new ee,this.cursores=new bi(()=>this.contexto.obterMapa()),this.snap=new In({aplica:()=>this.atalhosValem(),aoMudar:e=>{var o,i,n;this.contexto.emitir("cad-snap",e),(o=this.editor)==null||o.atualizarSnapNoHud(),(n=(i=this.contexto).aoSnapMudar)==null||n.call(i,e.ligado)}}),this.popup=new Ii({obterMapa:()=>this.contexto.obterMapa(),obterCamada:e=>this.contexto.obterLayerManager().getLayerDef(e),aoAcao:(e,o)=>this.tratarAcaoPopup(e,o)}),this.selecao=new Pi({obterFeicao:e=>this.buscar(e.camadaId,e.id),aplicarVisual:(e,o)=>{const i=this.contexto.obterLayerManager().getLayerInstance(e),n=R.get(V);i&&n&&n.aplicarSelecao(i,o)},aoSelecionar:e=>{var o;if(this.contexto.emitir("cad-selecao",{feicoes:e}),(o=this.editor)!=null&&o.ativo){const i=this.editor.feicao;e.length===1&&e[0].id===i.id&&e[0].camadaId===i.camadaId||this.editor.parar();return}e.length===1?this.popup.abrir(e[0]):this.popup.fechar()},aoSelecionarUma:e=>this.contexto.emitir("cad-feicao-selecionada",{feicao:e}),visivel:e=>this.selecionavelAgora(e),selecionavel:e=>!e.oculta})}aposDados(){var o;if(this.selecao.reconciliar(),(o=this.editor)!=null&&o.ativo){const i=this.editor.feicao,n=this.buscar(i.camadaId,i.id);!n||n.excluida||n.bloqueada?this.editor.parar():n!==i&&this.editor.sincronizar(n)}const t=this.popup.aberto;if(!t)return;const e=this.buscar(t.camadaId,t.id);e&&!e.excluida?this.popup.atualizar(e):this.popup.fechar()}lista(t){var o;const e=(o=this.contexto.obterLayerManager().getLayerDef(t))==null?void 0:o.dados;return Array.isArray(e==null?void 0:e.feicoes)?e.feicoes:[]}posicaoDe(t){const e=this.lista(t),o=this.posicoes.get(t);if(o&&o.lista===e)return o.pos;const i=new Map;for(let n=0;n<e.length;n++)i.set(e[n].id,n);return this.posicoes.set(t,{lista:e,pos:i}),i}buscar(t,e){const o=this.lista(t),i=this.posicaoDe(t).get(e),n=i===void 0?void 0:o[i];if(n&&n.id===e)return n;if(i===void 0)return;this.posicoes.delete(t);const s=this.posicaoDe(t).get(e);return s===void 0?void 0:o[s]}garantirCamada(t,e){const o=this.contexto.obterLayerManager(),i=o.getLayerDef(t);if(i&&i.tipo!==V)return!1;const n=o.getOrCreateLayer(t,V,(e==null?void 0:e.nome)??t);return e!=null&&e.nome&&(n.nome=e.nome),e!=null&&e.estilo&&(n.estilo={...n.estilo,...e.estilo}),(e==null?void 0:e.interativo)!==void 0&&(n.interativo=e.interativo),(e==null?void 0:e.zIndex)!==void 0&&o.setLayerZIndex(t,e.zIndex),(e==null?void 0:e.opacidade)!==void 0&&o.setLayerOpacity(t,e.opacidade),o.ensurePanes(),!0}opcoesNormalizacao(){return{aceitarOrigem:this.aceitarOrigem}}definirFeicoes(t,e,o){if(!this.garantirCamada(t,o))return{aceitas:0,recusadas:["camada existente não é de feições"]};const i=[],n=new Map;return(Array.isArray(e)?e:[]).forEach((s,r)=>{const c=Gt(s,t,this.opcoesNormalizacao());c?n.set(c.id,c):i.push(String((s==null?void 0:s.id)??`#${r}`))}),this.contexto.obterLayerManager().setLayerData(t,{feicoes:[...n.values()]}),this.aposDados(),{aceitas:n.size,recusadas:i}}adicionarFeicao(t,e,o){return this.aplicar(t,{adicionar:[e]},o).adicionadas[0]??null}atualizarFeicao(t,e,o,i){return this.aplicar(t,{atualizar:[{...o,id:e}]},i).atualizadas[0]??null}substituir(t,e){this.contexto.obterLayerManager().getLayerDef(t)&&this.aplicar(t,{adicionar:[e]})}removerFeicao(t,e){return this.aplicar(t,{remover:[e]}).resultado.removidas>0}aplicarLote(t,e,o){return this.aplicar(t,e,o).resultado}mesclar(t,e,o,i){const n=i&&e.propriedades&&typeof e.propriedades=="object"?{...e.propriedades}:{...t.propriedades,...e.propriedades};return Gt({...t,...e,id:t.id,estilo:{...t.estilo,...e.estilo},propriedades:n},o,this.opcoesNormalizacao())}aplicar(t,e,o={}){const i={adicionadas:0,atualizadas:0,removidas:0,recusadas:[]},n=[],s=[],r=Array.isArray(e==null?void 0:e.adicionar)?e.adicionar:[],c=Array.isArray(e==null?void 0:e.atualizar)?e.atualizar:[],l=Array.isArray(e==null?void 0:e.remover)?e.remover:[],d=(L,z)=>String((L==null?void 0:L.id)??`#${z}`),h=[],u=L=>(i.recusadas.push(...h),L),g=[];r.forEach((L,z)=>{const I=Gt(L,t,this.opcoesNormalizacao());I?g.push(I):h.push(d(L,z))});const m=this.contexto.obterLayerManager(),f=m.getLayerDef(t);if(!(!f||f.tipo===V)||!f&&g.length===0)return c.forEach((L,z)=>i.recusadas.push(d(L,z))),g.forEach(L=>h.push(L.id)),u({resultado:i,adicionadas:n,atualizadas:s});if((g.length>0||f)&&!this.garantirCamada(t,o))return g.forEach(L=>h.push(L.id)),u({resultado:i,adicionadas:n,atualizadas:s});const E=this.lista(t),M=this.posicaoDe(t),A=E.slice(),C=[],b=[];let v=!1;for(const L of l){const z=String(L),I=M.get(z);I===void 0||A[I]===null||(A[I]=null,C.push(z),i.removidas++,v=!0)}c.forEach((L,z)=>{const I=L&&typeof L=="object"&&L.id!==void 0&&L.id!==null?String(L.id):"",_=M.get(I),O=_===void 0?null:A[_],T=O?this.mesclar(O,L,t,!!o.substituirPropriedades):null;if(!T||_===void 0){i.recusadas.push(I||d(L,z));return}A[_]=T,b.push(T),s.push(T),i.atualizadas++});for(const L of g){const z=M.get(L.id);z!==void 0&&A[z]!==null?A[z]=L:(M.set(L.id,A.length),A.push(L)),b.push(L),n.push(L),i.adicionadas++}if(b.length===0&&C.length===0)return u({resultado:i,adicionadas:n,atualizadas:s});const P=v?A.filter(L=>L!==null):A,k={feicoes:P,delta:{base:E,mudadas:b,removidas:C}};return m.setLayerData(t,k),delete k.delta,v?this.posicoes.delete(t):this.posicoes.set(t,{lista:P,pos:M}),this.aposDados(),u({resultado:i,adicionadas:n,atualizadas:s})}obterFeicoes(t){return this.lista(t).map(e=>({...e}))}tratarAcaoCamada(t,e){var o,i;if(t==="feicao-movida")return this.substituir(e.camadaId,e.feicao),"cad-feicao-atualizada";if(t==="feicao-duplo-clique"){if((o=this.desenho)!=null&&o.ativo)return null;const n=this.contexto.obterLayerManager().getLayerDef(e.camadaId);return!(this.contexto.emitir("cad-feicao-duplo-clique",{camadaId:e.camadaId,feicao:e.feicao},!0)===!0)&&!this.editando&&Ut(e.feicao,!!(n!=null&&n.bloqueada))===null&&this.iniciarEdicao(e.camadaId,e.feicao.id),null}if(t==="feicao-clique"){if((i=this.desenho)!=null&&i.ativo)return null;const n={camadaId:e.camadaId,id:e.feicao.id};return e.aditivo?this.selecao.alternar(n):this.selecao.selecionar([n]),"cad-feicao-clique"}return null}selecionarFeicoes(t,e=!1){this.selecao.selecionar(Array.isArray(t)?t:[],e)}alternarSelecaoFeicao(t){this.selecao.alternar(t)}limparSelecaoFeicoes(){this.selecao.limpar()}aoPedirLimpeza(){var t,e;(t=this.desenho)!=null&&t.ativo||((e=this.editor)!=null&&e.ativo?this.editor.parar():this.selecao.limpar())}obterFeicoesSelecionadas(){return this.selecao.obter()}selecionarNoLaco(t){var o;const e=[];for(const i of this.contexto.obterLayerManager().getActiveSelectableLayers())if(i.tipo===V)for(const n of this.lista(i.id))this.desenhada(n)&&ki(n,t)&&e.push({camadaId:i.id,id:n.id});(o=this.desenho)==null||o.desativar(),this.selecao.selecionar(e)}selecionarNaCaixa(t,e,o){const i=this.contexto.obterMapa();if(!i)return;const n=r=>i.latLngToContainerPoint(r),s=[];for(const r of this.contexto.obterLayerManager().getActiveSelectableLayers())if(r.tipo===V)for(const c of this.lista(r.id))this.desenhada(c)&&zi(c,t,n,e)&&s.push({camadaId:r.id,id:c.id});o?this.selecao.alternarVarias(s):this.selecao.selecionar(s)}definirMargensPopup(t){this.popup.definirMargens(t)}fecharPopup(){this.popup.fechar()}definirOpcoesPopup(t){this.opcoesPopup={...this.opcoesPopup,...t}}obterOpcoesPopup(){return{...this.opcoesPopup}}definirMargensHud(t){this.margensHud={...this.margensHud,...t},this.aplicarMargensHud()}aplicarMargensHud(){const t=this.contexto.obterMapa();t&&Ui(t.getContainer(),this.margensHud)}get regraVersoes(){return this.regra}oficiaisDe(t){const e=this.lista(t);let o=this.cacheOficiais.get(e);return o||(o=ee.oficiais(e),this.cacheOficiais.set(e,o)),o}visivelPorVersao(t){const e=this.contexto.obterLayerManager().getLayerInstance(t.camadaId),o=R.get(V);return e&&o?o.feicaoVisivel(e,t):this.regra.visivel(t,this.oficiaisDe(t.camadaId))}desenhada(t){return!t.excluida&&!t.oculta&&this.visivelPorVersao(t)}selecionavelAgora(t){var o;const e=(o=this.editor)!=null&&o.ativo?this.editor.feicao:null;return e&&e.id===t.id&&e.camadaId===t.camadaId?!0:!t.oculta&&this.visivelPorVersao(t)}aplicarVersoes(){const t=this.contexto.obterLayerManager(),e=R.get(V);for(const o of t.getLayers()){if(o.tipo!==V)continue;const i=t.getLayerInstance(o.id);i&&e&&e.reavaliarVersoes(i)}this.aposDados()}get previasGlobais(){return this.regra.global}definirPreviasGlobais(t){const e=!!t;this.regra.global!==e&&(this.regra.global=e,this.aplicarVersoes(),this.contexto.emitir("cad-previas",{global:e}))}alternarPreviasGlobais(){this.definirPreviasGlobais(!this.regra.global)}alternarPrevia(t,e){const o=this.buscar(t,e);if(!o)return null;const i=nt(o),n=this.regra.alternarIndividual(t,i);return this.aplicarVersoes(),this.contexto.emitir("cad-previas",{camadaId:t,entidadeId:i,ativa:n}),n}previaSolicitada(t,e){const o=this.buscar(t,e);return!!o&&this.regra.previaSolicitada(o)}atualizarCursorRemoto(t,e){const o=X(e,this.opcoesNormalizacao());return!!o&&this.cursores.atualizar(t,o)}removerCursorRemoto(t){return this.cursores.remover(t)}limparCursoresRemotos(){this.cursores.limpar()}get cursoresRemotos(){return this.cursores.quantidade}garantirVisivel(t){const e=this.contexto.obterLayerManager(),o=e.getLayerDef(t.camadaId);if(o&&!o.visivel&&e.setLayerVisibility(t.camadaId,!0),!this.visivelPorVersao(t)){const i=nt(t);this.regra.definirIndividual(t.camadaId,i,!0),this.aplicarVersoes(),this.contexto.emitir("cad-previas",{camadaId:t.camadaId,entidadeId:i,ativa:!0})}}limitesDe(t){let e=1/0,o=1/0,i=-1/0,n=-1/0;for(const s of t){const[[r,c],[l,d]]=Oe(s.geometria);r<e&&(e=r),c<o&&(o=c),l>i&&(i=l),d>n&&(n=d)}return Number.isFinite(e)?[[e,o],[i,n]]:null}enquadrar(t){const e=this.contexto.obterMapa(),o=this.limitesDe(t);return!e||!o?!1:(o[0][0]===o[1][0]&&o[0][1]===o[1][1]?e.flyTo([o[0][0],o[0][1]],Math.max(e.getZoom(),17)):e.fitBounds(o,{padding:[60,60],maxZoom:18}),!0)}zoomParaFeicao(t,e){const o=this.buscar(t,e);return!o||o.excluida?!1:(this.garantirVisivel(o),this.enquadrar([o]))}zoomParaFeicoes(t){const e=[];for(const o of Array.isArray(t)?t:[]){const i=this.buscar(o.camadaId,o.id);i&&!i.excluida&&(this.garantirVisivel(i),e.push(i))}return e.length>0&&this.enquadrar(e)}ajustarTudo(){const t=[];for(const e of this.contexto.obterLayerManager().getLayers())e.tipo!==V||!e.visivel||t.push(...this.lista(e.id).filter(o=>this.desenhada(o)));return this.enquadrar(t)}ajustarCamada(t){const e=this.contexto.obterLayerManager(),o=e.getLayerDef(t);return!o||o.tipo!==V?!1:(o.visivel||e.setLayerVisibility(t,!0),this.enquadrar(this.lista(t).filter(i=>this.desenhada(i))))}feicaoSob(t,e){const o=this.contexto.obterMapa();if(!o)return null;const i=o.getContainer().getBoundingClientRect(),n=y.point(t-i.left,e-i.top),s=o.containerPointToLatLng(n),r=[s.lat,s.lng];return{feicao:$e({x:n.x,y:n.y},this.candidatasEm(r,8),l=>o.latLngToContainerPoint(l)),coordenada:r}}aoMoverMouse(t){var r,c;if(t.buttons!==0||!!((r=this.desenho)!=null&&r.ativo)||!!((c=this.editor)!=null&&c.ativo)){this.hoverId!==null&&(this.hoverId=null,this.contexto.emitir("cad-feicao-hover",{feicao:null}));return}if(this.hoverAgendado)return;this.hoverAgendado=!0;const{clientX:o,clientY:i}=t;let n=!1;const s=()=>{if(n)return;n=!0,this.hoverAgendado=!1;const l=this.feicaoSob(o,i),d=l!=null&&l.feicao?`${l.feicao.camadaId}\0${l.feicao.id}`:null;d!==this.hoverId&&(this.hoverId=d,this.contexto.emitir("cad-feicao-hover",{feicao:(l==null?void 0:l.feicao)??null}))};typeof requestAnimationFrame=="function"&&requestAnimationFrame(s),setTimeout(s,100)}menuContexto(t){var o;if((o=this.desenho)!=null&&o.ativo){this.desenho.botaoDireito();return}const e=this.feicaoSob(t.clientX,t.clientY);e&&this.contexto.emitir("cad-feicao-menu",{feicao:e.feicao,coordenada:e.coordenada,x:t.clientX,y:t.clientY})}destruir(){var t;(t=this.desenho)==null||t.desativar(),this.desenho=null,this.cursores.limpar(),this.hoverId=null}tratarAcaoPopup(t,e){var o,i,n;if(t==="zoom"&&this.zoomParaFeicao(e.camadaId,e.id),t==="vertices"&&this.iniciarEdicao(e.camadaId,e.id),t==="copiar"&&this.opcoesPopup.copiarParaAreaDeTransferencia){const[s,r]=Tt(e);(n=(i=(o=globalThis.navigator)==null?void 0:o.clipboard)==null?void 0:i.writeText(`${s.toFixed(6)}, ${r.toFixed(6)}`))==null||n.catch(()=>{})}this.contexto.emitir("cad-feicao-acao",{acao:t,feicao:e})}get snapLigado(){return this.snap.ligado}get snapAtivo(){return this.snap.ativo}definirSnap(t){this.snap.definir(!!t)}alternarSnap(){this.snap.alternar()}conectarTeclado(){this.snap.conectar(),window.addEventListener("keydown",this.aoTeclaEdicao)}desconectarTeclado(){this.snap.desconectar(),window.removeEventListener("keydown",this.aoTeclaEdicao)}atalhosValem(){var t,e,o,i;return!!((t=this.editor)!=null&&t.ativo)||!!((e=this.desenho)!=null&&e.ativo)||(((i=(o=this.contexto).atalhoValido)==null?void 0:i.call(o))??!0)}alternarEdicaoDaSelecao(){var e;if((e=this.editor)!=null&&e.ativo)return this.editor.parar(),{ok:!0};const t=this.selecao.obter();return t.length!==1?(this.contexto.emitir("cad-edicao-recusada",{motivo:"sem-selecao",feicao:null}),{ok:!1,motivo:"sem-selecao"}):this.iniciarEdicao(t[0].camadaId,t[0].id)}candidatasEm(t,e){const o=this.contexto.obterMapa(),i=this.contexto.obterLayerManager(),n=R.get(V);if(!o||!n)return[];const s=o.latLngToContainerPoint(t),r=o.containerPointToLatLng([s.x-e,s.y+e]),c=o.containerPointToLatLng([s.x+e,s.y-e]),l={minLon:Math.min(r.lng,c.lng),maxLon:Math.max(r.lng,c.lng),minLat:Math.min(r.lat,c.lat),maxLat:Math.max(r.lat,c.lat)},d=[];for(const h of i.getLayers()){if(h.tipo!==V||!h.visivel)continue;const u=i.getLayerInstance(h.id);u&&d.push(...n.consultarProximas(u,l).filter(g=>this.desenhada(g)))}return d}buscarSnapEm(t,e){const o=this.contexto.obterMapa();if(!o)return null;const i=o.latLngToContainerPoint(t),n=this.candidatasEm(t,Ye);return Zi({x:i.x,y:i.y},n,s=>o.latLngToContainerPoint(s),{},e)}get editando(){var t;return!!((t=this.editor)!=null&&t.ativo)}iniciarEdicao(t,e){var d,h,u,g;const o=this.buscar(t,e);if(!o||o.excluida)return{ok:!1,motivo:"inexistente"};const i=this.contexto.obterLayerManager().getLayerDef(t),n=Ut(o,!!(i!=null&&i.bloqueada));if(n)return this.contexto.emitir("cad-edicao-recusada",{motivo:n,feicao:o}),{ok:!1,motivo:n};const s=this.contexto.obterMapa();if(!s)return{ok:!1,motivo:"sem-mapa"};(d=this.desenho)==null||d.desativar(),(h=this.editor)==null||h.parar(),this.aplicarMargensHud(),this.selecao.selecionar([{camadaId:t,id:e}]),this.popup.fechar();const r=this.contexto.obterLayerManager(),c=R.get(V),l=new Xi({map:s,snapLigado:()=>this.snap.ativo,alternarSnap:()=>this.snap.alternar(),buscarSnap:(m,f)=>this.buscarSnapEm(m,f),previsualizar:m=>{const f=r.getLayerInstance(m.camadaId);f&&c&&c.previsualizar(f,m)},aoGesto:m=>{this.substituir(m.camadaId,m),this.contexto.emitir("cad-feicao-atualizada",{camadaId:m.camadaId,feicao:m})},aoEncerrar:m=>{var E,M;this.editor=null,this.pararDeVigiarCamadaEmEdicao(),(M=(E=this.contexto).aoEdicao)==null||M.call(E,!1);const f=this.buscar(m.camadaId,m.id)??m;this.contexto.emitir("cad-edicao-concluida",{feicao:f});const x=this.selecao.obter();x.length===1&&this.popup.abrir(x[0])}});return this.editor=l,l.iniciar(o),(g=(u=this.contexto).aoEdicao)==null||g.call(u,!0),this.vigiaCamadaEmEdicao=r.onChange(()=>{var x,E;const m=(x=this.editor)==null?void 0:x.feicao;if(!m)return;const f=r.getLayerDef(m.camadaId);(!f||!f.visivel||f.bloqueada)&&((E=this.editor)==null||E.parar())}),this.contexto.emitir("cad-edicao-iniciada",{feicao:o}),{ok:!0}}pararDeVigiarCamadaEmEdicao(){var t;(t=this.vigiaCamadaEmEdicao)==null||t.call(this),this.vigiaCamadaEmEdicao=null}pararEdicao(){var t;(t=this.editor)==null||t.parar()}get ferramentaAtiva(){var t;return((t=this.desenho)==null?void 0:t.ferramenta)??null}definirCamadaDesenho(t){this.camadaDesenho=t||null}get camadaDeDesenho(){return this.camadaDesenho}definirEstiloDesenho(t){this.estiloDesenho={...t}}obterEstiloDesenho(){return{...this.estiloDesenho}}alternarFerramenta(t){var e;return((e=this.desenho)==null?void 0:e.ferramenta)===t?(this.desenho.desativar(),{ok:!0}):this.ativarFerramenta(t)}ativarFerramenta(t,e={}){var n,s,r;if(!Ke(t))return{ok:!1,motivo:"ferramenta-invalida"};const o=this.contexto.obterMapa();if(!o)return{ok:!1,motivo:"sem-mapa"};if(Gn.has(t)){const c=this.motivoCamadaDesenhoInvalida();if(c)return this.contexto.emitir("cad-desenho-recusado",{ferramenta:t,motivo:c}),{ok:!1,motivo:c}}(n=this.editor)==null||n.parar(),this.popup.fechar(),this.aplicarMargensHud(),this.desenho||(this.desenho=new Qi({map:o,buscarSnap:c=>this.buscarSnapEm(c),snapAtivo:()=>this.snap.ativo,aoGeometria:(c,l)=>this.concluirFerramenta(c,l),aoMedir:c=>this.contexto.emitir("cad-medicao",c),aoAmostrar:c=>this.amostrarEstilo(c),aoSolicitarTexto:c=>this.solicitarTexto(c),aoDesativar:()=>{var c,l;this.contexto.emitir("cad-ferramenta",{ferramenta:null}),(l=(c=this.contexto).aoFerramenta)==null||l.call(c,null)}})),this.desenho.ativar(t,e),this.contexto.emitir("cad-ferramenta",{ferramenta:t}),(r=(s=this.contexto).aoFerramenta)==null||r.call(s,t);const i=e.iniciarEm?X(e.iniciarEm,this.opcoesNormalizacao()):null;return i&&this.desenho.clicarEm(i),{ok:!0}}desativarFerramenta(){var t;(t=this.desenho)==null||t.desativar()}limparMedicao(){var t;(t=this.desenho)==null||t.limparMedicao()}get nosDesenho(){var t;return((t=this.desenho)==null?void 0:t.nos)??0}desfazerVerticeDesenho(){var t;return((t=this.desenho)==null?void 0:t.desfazerVertice())??!1}definirAtalhoSnap(t){this.snap.atalhoS=t}motivoCamadaDesenhoInvalida(){if(!this.camadaDesenho)return"sem-camada";const t=this.contexto.obterLayerManager().getLayerDef(this.camadaDesenho);return t&&t.tipo!==V?"camada-invalida":t!=null&&t.bloqueada?"camada-bloqueada":null}novoId(t,e){const o=new Set(this.lista(e).map(n=>n.id));let i;do this.sequenciaId++,i=`${t}-${Date.now().toString(36)}${this.sequenciaId.toString(36)}`;while(o.has(i));return i}idLivre(t,e){const o=new Set(this.lista(t).map(n=>n.id));if(!o.has(e))return e;let i=2;for(;o.has(`${e}_${i}`);)i++;return`${e}_${i}`}solicitarTexto(t){const e={coordenada:t,camadaId:this.camadaDesenho,concluir:o=>{const i=typeof o=="string"?o.trim():"";return i?this.concluirFerramenta("texto",{tipo:"Text",coordenada:t,texto:i}):null}};return this.contexto.emitir("cad-texto-solicitado",e,!0)===!0}concluirFerramenta(t,e){if(t==="dividir")return e.tipo==="LineString"&&this.dividirComLinha(e.coordenadas),null;if(t==="medir-distancia"||t==="medir-area")return null;if(t==="selecao-laco")return e.tipo==="Polygon"&&this.selecionarNoLaco(e.aneis[0]),null;const o=this.camadaDesenho;if(!o)return null;const i=Object.keys(this.estiloDesenho).length>0,n=this.adicionarFeicao(o,{id:this.novoId(t,o),geometria:e,estilo:i?{...this.estiloDesenho}:void 0,propriedades:{}});return n?this.contexto.emitir("cad-feicao-criada",{camadaId:o,feicao:n}):this.contexto.emitir("cad-desenho-recusado",{ferramenta:t,motivo:"geometria-invalida"}),n}amostrarEstilo(t){const e=this.contexto.obterMapa();if(!e)return;const o=e.latLngToContainerPoint(t),i=this.candidatasEm(t,8),n=$e({x:o.x,y:o.y},i,d=>e.latLngToContainerPoint(d));if(!n){this.contexto.emitir("cad-conta-gotas",{cor:"",feicao:null,estilo:{}});return}const s=this.contexto.obterLayerManager().getLayerDef(n.camadaId),r=n.estilo??{},c={},l=r.corTraco??(s==null?void 0:s.estilo.corPrimaria);l&&(c.corTraco=l),r.corPreenchimento&&(c.corPreenchimento=r.corPreenchimento),r.espessuraTraco!==void 0&&(c.espessuraTraco=r.espessuraTraco),r.opacidadePreenchimento!==void 0&&(c.opacidadePreenchimento=r.opacidadePreenchimento),r.dashArray&&(c.dashArray=r.dashArray),this.estiloDesenho={...this.estiloDesenho,...c},this.contexto.emitir("cad-conta-gotas",{cor:l??r.corPreenchimento??"",feicao:n,estilo:c})}dividirComLinha(t){var l;const e=this.contexto.obterLayerManager(),o=d=>(this.contexto.emitir("cad-divisao-falhou",{motivo:d}),!1),i=this.selecao.obter().filter(d=>d.geometria.tipo==="Polygon");let n=i;if(n.length===0){n=[];for(const d of e.getActiveSelectableLayers())d.tipo===V&&n.push(...this.lista(d.id).filter(h=>h.geometria.tipo==="Polygon"&&this.desenhada(h)))}if(n.length===0)return o(i.length===0&&this.selecao.obter().some(d=>kt(d.geometria))?"multiparte":"nenhum-poligono");const s=d=>{var h;return!!d.bloqueada||!!((h=e.getLayerDef(d.camadaId))!=null&&h.bloqueada)},r=n.filter(d=>!s(d)&&d.geometria.tipo==="Polygon"&&d.geometria.aneis.length===1);if(r.length===0)return o(n.some(s)?"bloqueada":"poligono-com-furos");let c=!1;for(const d of r){if(d.geometria.tipo!=="Polygon")continue;const h=Li(d.geometria.aneis[0],t);if(!h)continue;((l=this.desenho)==null?void 0:l.ferramenta)==="dividir"&&this.selecao.contem({camadaId:d.camadaId,id:d.id})&&this.desenho.desativar(),this.removerFeicao(d.camadaId,d.id);const u=[];if(h.forEach((g,m)=>{const f=jt(d,this.idLivre(d.camadaId,`${d.id}-${m+1}`),{tipo:"Polygon",aneis:[g]}),x=this.adicionarFeicao(d.camadaId,f);x&&u.push(x)}),u.length!==h.length){for(const g of u)this.removerFeicao(g.camadaId,g.id);return this.adicionarFeicao(d.camadaId,d),o("geometria-invalida")}if(this.contexto.emitir("cad-feicao-dividida",{origem:d,partes:u}),c=!0,i.length===0)break}return c||o("sem-intersecao")}gerarBuffer(t,e,o,i={}){const n=this.buscar(t,e);if(!n)return null;const s=wi(n.geometria,o);if(!s)return null;const r=i.camadaDestino??t,c=this.adicionarFeicao(r,{id:i.id??this.idLivre(r,`${e}-buffer`),geometria:{tipo:"Polygon",aneis:[s]},estilo:n.estilo?{...n.estilo}:void 0,propriedades:{...n.propriedades,origem:e}});return c&&this.contexto.emitir("cad-feicao-criada",{camadaId:r,feicao:c}),c}duplicarFeicao(t,e,o={},i={}){const n=this.buscar(t,e);if(!n)return null;const s=Ei(n.geometria,o.lesteM??0,o.norteM??0),r=this.adicionarFeicao(t,jt(n,i.id??this.idLivre(t,`${e}-copia`),s));return r&&this.contexto.emitir("cad-feicao-criada",{camadaId:t,feicao:r}),r}juntarFeicoes(t,e,o={}){const i=h=>(this.contexto.emitir("cad-uniao-falhou",{motivo:h}),null),n=e.map(h=>this.buscar(t,h));if(n.length<2||n.some(h=>!h))return i("feicoes-insuficientes");const s=n;if(new Set(s.map(h=>h.id)).size!==s.length)return i("feicoes-insuficientes");const r=this.contexto.obterLayerManager();if(s.some(h=>{var u;return h.excluida||h.bloqueada||((u=r.getLayerDef(h.camadaId))==null?void 0:u.bloqueada)}))return i("bloqueada");const c=o.toleranciaM??0;let l=null;if(s.every(h=>h.geometria.tipo==="LineString")){if(s.some(g=>kt(g.geometria)))return i("multiparte");const h=s.map(g=>g.geometria.coordenadas),u=Mi(h,c);u&&(l=bt([u]))}else if(s.every(h=>h.geometria.tipo==="Polygon"&&h.geometria.aneis.length===1)){let h=s[0].geometria.aneis[0];for(const u of s.slice(1))h=h?Ai(h,u.geometria.aneis[0],c):null;h&&(l={tipo:"Polygon",aneis:[h]})}else return i("tipos-incompativeis");if(!l)return i("sem-ligacao");for(const h of s)this.removerFeicao(t,h.id);const d=this.adicionarFeicao(t,jt(s[0],o.id??this.idLivre(t,`${s[0].id}-uniao`),l));if(!d){for(const h of s)this.adicionarFeicao(t,h);return i("geometria-invalida")}return this.contexto.emitir("cad-feicao-unida",{origens:s,resultado:d}),d}}const zo={ponto:"Ponto",linha:"Linha",poligono:"Polígono",retangulo:"Retângulo",elipse:"Elipse","poligono-regular":"Hexágono",estrela:"Estrela",circulo:"Círculo",texto:"Texto",caneta:"Caneta","medir-distancia":"Medir","medir-area":"Área",dividir:"Dividir","selecao-laco":"Laço","conta-gotas":"Cor"};function Un(a){if(!a)return[];const t=a.split(/[\s,]+/).map(o=>o.trim().toLowerCase()).filter(Boolean);if(t.includes("todas"))return[...ce];const e=new Set(t.filter(Ke));return ce.filter(o=>e.has(o))}function Wn(a){if(!a)return!1;const t=a.split(/[\s,]+/).map(e=>e.trim().toLowerCase());return t.includes("todas")||t.includes("editar")}class Xn{constructor(t){p(this,"barra",null);p(this,"editando",!1);this.ctx=t}montar(t,e=!1){var n;(n=this.barra)==null||n.remove(),this.barra=null;const o=e&&!!this.ctx.aoEditar;if(t.length===0&&!o)return;const i=document.createElement("div");i.className="cad-quick-toolbar cad-draw-toolbar",i.setAttribute("role","toolbar"),i.setAttribute("aria-label","Ferramentas de desenho");for(const s of t){const r=document.createElement("button");r.type="button",r.className="cad-btn-tool cad-draw-btn",r.dataset.ferramenta=s,r.textContent=zo[s],r.title=zo[s],r.setAttribute("aria-pressed","false"),r.addEventListener("click",()=>this.ctx.aoEscolher(s)),i.appendChild(r)}if(o){const s=document.createElement("button");s.type="button",s.className="cad-btn-tool cad-draw-btn",s.dataset.acao="editar",s.textContent="Editar",s.title="Editar os vértices da feição selecionada (Enter ou duplo clique)",s.setAttribute("aria-pressed",String(this.editando)),s.classList.toggle("active",this.editando),s.addEventListener("click",()=>this.ctx.aoEditar()),i.appendChild(s)}this.ctx.raiz.appendChild(i),this.barra=i}marcarEdicao(t){var o;this.editando=t;const e=(o=this.barra)==null?void 0:o.querySelector('[data-acao="editar"]');e&&(e.classList.toggle("active",t),e.setAttribute("aria-pressed",String(t)))}marcar(t){var e;(e=this.barra)==null||e.querySelectorAll("[data-ferramenta]").forEach(o=>{const i=o.dataset.ferramenta===t;o.classList.toggle("active",i),o.setAttribute("aria-pressed",String(i))})}desmontar(){var t;(t=this.barra)==null||t.remove(),this.barra=null}}const Zn="data-cad-estilos-externos";function Yn(a){try{return Array.from(a.cssRules,t=>t.cssText).join(`
166
+ `)}catch{return""}}function Kn(a){return typeof a=="string"?a.trim()?[a]:[]:Array.isArray(a)?a.map(t=>typeof t=="string"?t:Yn(t)).filter(t=>t.trim()!==""):[]}class Jn{constructor(t){p(this,"textos",[]);p(this,"adotadas",[]);p(this,"fallback",null);this.shadow=t}get pedido(){return this.textos}definir(t){this.textos=Kn(t),this.aplicar()}limpar(){this.remover()}aplicar(){if(this.remover(),this.textos.length===0)return;const t=this.shadow;if(typeof CSSStyleSheet<"u"&&Array.isArray(t.adoptedStyleSheets))try{this.adotadas=this.textos.map(o=>{const i=new CSSStyleSheet;return i.replaceSync(o),i}),t.adoptedStyleSheets=[...t.adoptedStyleSheets,...this.adotadas];return}catch{this.adotadas=[]}const e=document.createElement("style");e.setAttribute(Zn,""),e.textContent=this.textos.join(`
167
+ `),this.shadow.appendChild(e),this.fallback=e}remover(){var e;const t=this.shadow;this.adotadas.length>0&&Array.isArray(t.adoptedStyleSheets)&&(t.adoptedStyleSheets=t.adoptedStyleSheets.filter(o=>!this.adotadas.includes(o))),this.adotadas=[],(e=this.fallback)==null||e.remove(),this.fallback=null}}class ea extends ko.SafeHTMLElement{constructor(){var n;super();p(this,"shadow");p(this,"mapContainer",null);p(this,"layersPanel",null);p(this,"controller");p(this,"controladorTamanho");p(this,"toolbarPainel");p(this,"broadcastConfig");p(this,"colecoesDados");p(this,"feicoes");p(this,"barraFerramentas");p(this,"hoverListeners",new Le.ListenerBag);p(this,"layerItemListeners",new Le.ListenerBag);p(this,"initTimeout");p(this,"estilosExternos");p(this,"lastPopupActionEmit");p(this,"lastCanvasClickTime",0);p(this,"ponteiroSobre",!1);p(this,"_chaveGrupo");p(this,"_zonaProjecao",22);this.shadow=this.attachShadow({mode:"open"}),this.controller=new le,this.controladorTamanho=yi(this,this.controller),this.shadow.innerHTML=Za(),this.estilosExternos=new Jn(this.shadow),this.mapContainer=this.shadow.getElementById("cad-map-container"),this.layersPanel=this.shadow.getElementById("qgis-layer-panel"),this.toolbarPainel=new Ua({shadow:this.shadow,mapContainer:this.mapContainer,layersPanel:this.layersPanel,onToggleCamadas:()=>this.toggleLayersPanel(),onCloseCamadas:()=>this.closeLayersPanel(),onZoomExtents:()=>this.zoomExtents(),onLimparSelecao:()=>this.limparSelecao(),onToggleSnap:()=>this.feicoes.alternarSnap(),onTratarCliqueCanvas:s=>this.tratarCliqueLivreCanvas(s),onDispararAcaoPopup:(s,r)=>this.dispararAcaoPopup(s,r)}),this.broadcastConfig=new ja({host:this,controller:this.controller,mapContainer:this.mapContainer,setLayerOpacity:(s,r)=>this.setLayerOpacity(s,r)}),this.colecoesDados=new Wa({obterController:()=>this.controller,obterChaveGrupo:()=>this.chaveGrupo,setLayerVisibility:(s,r)=>this.setLayerVisibility(s,r)});const e=new ee,o=this.controller.context,i=this.controller.canvasInteracao.ctx;Object.assign(o,{regraVersoes:e}),this.feicoes=new jn({obterLayerManager:()=>this.controller.layerManager,obterMapa:()=>this.controller.getMap(),regra:e,aoFerramenta:s=>{this.barraFerramentas.marcar(s)},aoEdicao:s=>{this.barraFerramentas.marcarEdicao(s)},atalhoValido:()=>this.ponteiroSobre||this.matchesFocoInterno()||this.ehUnicoCanvas(),aoSnapMudar:s=>{var r;(r=this.shadow.getElementById("btn-toggle-snap"))==null||r.classList.toggle("active",s)},emitir:(s,r,c)=>{const l=new CustomEvent(s,{detail:r,bubbles:!0,composed:!0,cancelable:!!c});return this.dispatchEvent(l),l.defaultPrevented}}),Object.assign(o,{onLayerAction:(s,r)=>{const c=this.feicoes.tratarAcaoCamada(s,r);c&&this.dispatchEvent(new CustomEvent(c,{detail:r,bubbles:!0,composed:!0}))}}),this.barraFerramentas=new Xn({raiz:this.shadow.getElementById("cad-root"),aoEscolher:s=>{this.feicoes.alternarFerramenta(s)},aoEditar:()=>{this.feicoes.alternarEdicaoDaSelecao()}}),this.montarBarra(this.getAttribute("ferramentas")),Object.assign(i,{aoMenuContexto:s=>this.feicoes.menuContexto(s),ferramentaAtiva:()=>this.feicoes.ferramentaAtiva!==null,aoLimparSelecao:()=>this.feicoes.aoPedirLimpeza(),selecionarFeicoesNaCaixa:(s,r,c)=>this.feicoes.selecionarNaCaixa(s,r,c)}),(n=this.shadow.getElementById("btn-toggle-snap"))==null||n.classList.add("active")}static get observedAttributes(){return["sat-opacity","scale-mode","crosshair","modo-sequencial","chave-grupo","zona-projecao","fuso","canal-configuracao","ferramentas","sem-atalho-snap","aceitar-origem","sem-camadas-padrao","sem-painel-camadas","sem-barra-rapida"]}connectedCallback(){const e=this.getAttribute("zona-projecao")||this.getAttribute("fuso");if(e){const o=parseInt(e,10);!isNaN(o)&&o>0&&(this._zonaProjecao=o,this.controller.zonaProjecao=o,this.controller.context.zonaProjecao=o)}this.controladorTamanho.observe(),this.feicoes.conectarTeclado(),this.hoverListeners.cleanup(),this.mapContainer&&this.hoverListeners.add(this.mapContainer,"mousemove",o=>this.feicoes.aoMoverMouse(o)),this.hoverListeners.add(this,"mouseenter",()=>{this.ponteiroSobre=!0}),this.hoverListeners.add(this,"mouseleave",()=>{this.ponteiroSobre=!1}),this.montarBarra(this.getAttribute("ferramentas")),this.broadcastConfig.conectar(),this.estilosExternos.aplicar(),this.initTimeout=window.setTimeout(()=>{this.initTimeout=void 0,this.inicializarAgora()},0)}montarBarra(e){var o;(o=this.barraFerramentas)==null||o.montar(Un(e),Wn(e))}ehUnicoCanvas(){var o;const e=this.getRootNode();return(((o=e.querySelectorAll)==null?void 0:o.call(e,"ui-canvas-cad").length)??1)<=1}matchesFocoInterno(){try{return this.matches(":focus-within")}catch{return!1}}destroy(){if(this.initTimeout&&(window.clearTimeout(this.initTimeout),this.initTimeout=void 0),this.controladorTamanho.disconnect(),this.estilosExternos.limpar(),this.feicoes.pararEdicao(),this.feicoes.desativarFerramenta(),this.feicoes.limparMedicao(),this.feicoes.desconectarTeclado(),this.feicoes.destruir(),this.hoverListeners.cleanup(),this.broadcastConfig.desconectar(),this.limparDestaque(),this.toolbarPainel.limpar(),this.layerItemListeners.cleanup(),this.controller.destroy(),this.mapContainer&&this.mapContainer._leaflet_id)try{delete this.mapContainer._leaflet_id}catch{this.mapContainer._leaflet_id=void 0}}disconnectedCallback(){this.destroy()}invalidateSizeSafely(){this.controladorTamanho.invalidateSizeSafely()}attributeChangedCallback(e,o,i){var n,s,r,c,l,d;if(e==="sem-atalho-snap"){(n=this.feicoes)==null||n.definirAtalhoSnap(i===null);return}if(!(e==="sem-camadas-padrao"||e==="sem-barra-rapida")){if(e==="sem-painel-camadas"){i!==null&&((s=this.toolbarPainel)==null||s.closeLayersPanel());return}if(e==="aceitar-origem"){this.feicoes&&(this.feicoes.aceitarOrigem=i!==null&&i!=="false");return}if(e==="ferramentas"){this.montarBarra(i),(c=this.barraFerramentas)==null||c.marcar(((r=this.feicoes)==null?void 0:r.ferramentaAtiva)??null),(d=this.barraFerramentas)==null||d.marcarEdicao(!!((l=this.feicoes)!=null&&l.editando));return}Ya({host:this,controller:this.controller,mapContainer:this.mapContainer,broadcastConfig:this.broadcastConfig,setLayerOpacity:(h,u)=>this.setLayerOpacity(h,u),setLayerScaleMode:(h,u)=>this.setLayerScaleMode(h,u),atualizarZonaProjecao:h=>{this._zonaProjecao=h}},e,o,i)}}inicializarAgora(){this.initTimeout!==void 0&&(window.clearTimeout(this.initTimeout),this.initTimeout=void 0);const e=this.controller.getMap();return e||(this.hasAttribute("sem-camadas-padrao")&&this.controller.layerManager.descartarCamadasPadrao(),this.initCAD(),this.controller.getMap())}definirEstilosExternos(e){this.estilosExternos.definir(e)}initCAD(){Ka({host:this,shadow:this.shadow,mapContainer:this.mapContainer,controller:this.controller,toolbarPainel:this.toolbarPainel,colecoesDados:this.colecoesDados,obterContextoEventos:()=>this.obterContextoEventos(),renderLayersUI:()=>this.renderLayersUI(),invalidateSizeSafely:()=>this.invalidateSizeSafely(),tratarCliqueLivreCanvas:(e,o,i)=>this.tratarCliqueLivreCanvas(e,o,i),dispararAcaoPopup:(e,o,i)=>this.dispararAcaoPopup(e,o,i)})}obterContextoEventos(){return{host:this,controller:this.controller,mapContainer:this.mapContainer,modoSequencial:this.modoSequencial,mouseMovedSinceDown:this.toolbarPainel.houveMovimentoMouse,obterElementoPorId:e=>this.colecoesDados.obterElementoPorId(e),fecharPopup:()=>{var e;(e=this.controller.getMap())==null||e.closePopup()}}}tratarCliqueLivreCanvas(e,o,i){const n=Date.now();n-this.lastCanvasClickTime<50||(this.lastCanvasClickTime=n,fi(this.obterContextoEventos(),e,o,i))}dispararAcaoPopup(e,o,i){const n=Date.now();this.lastPopupActionEmit&&this.lastPopupActionEmit.acaoId===e&&this.lastPopupActionEmit.elementoId===o&&n-this.lastPopupActionEmit.time<50||(this.lastPopupActionEmit={acaoId:e,elementoId:o,time:n},mi(this.obterContextoEventos(),e,o,i))}toggleLayersPanel(){this.hasAttribute("sem-painel-camadas")||this.toolbarPainel.toggleLayersPanel()}closeLayersPanel(){this.toolbarPainel.closeLayersPanel()}renderLayersUI(){const e=this.shadow.getElementById("layers-list-container");pi(e,this.controller.layerManager.getLayers(),this.layerItemListeners,{setLayerVisibility:(o,i)=>this.setLayerVisibility(o,i),setLayerOpacity:(o,i)=>this.setLayerOpacity(o,i),setLayerBlocked:(o,i)=>this.controller.layerManager.setLayerBlocked(o,i),setLayerScaleMode:(o,i)=>this.setLayerScaleMode(o,i)})}get pontos(){return this.colecoesDados.pontos}set pontos(e){this.colecoesDados.pontos=e}get segmentos(){return this.colecoesDados.segmentos}set segmentos(e){this.colecoesDados.segmentos=e}get bancoPontos(){return this.colecoesDados.bancoPontos}set bancoPontos(e){this.colecoesDados.bancoPontos=e}get pontosHomologados(){return this.bancoPontos}set pontosHomologados(e){this.bancoPontos=e}get confrontantes(){return this.colecoesDados.confrontantes}set confrontantes(e){this.colecoesDados.confrontantes=e}get vizinhos(){return this.confrontantes}set vizinhos(e){this.confrontantes=e}get aceitarOrigem(){return this.hasAttribute("aceitar-origem")&&this.getAttribute("aceitar-origem")!=="false"}set aceitarOrigem(e){e?this.setAttribute("aceitar-origem",""):this.removeAttribute("aceitar-origem")}get modoSequencial(){return this.hasAttribute("modo-sequencial")}set modoSequencial(e){var i;const o=!!e;o?this.hasAttribute("modo-sequencial")||this.setAttribute("modo-sequencial",""):this.hasAttribute("modo-sequencial")&&this.removeAttribute("modo-sequencial"),this.controller.modoCliqueSequencialAtivo=o,this.controller.context.modoSequencial=o,o&&((i=this.controller.getMap())==null||i.closePopup())}get chaveGrupo(){return this.getAttribute("chave-grupo")||this._chaveGrupo}set chaveGrupo(e){this._chaveGrupo=e,e?this.getAttribute("chave-grupo")!==e&&this.setAttribute("chave-grupo",e):this.hasAttribute("chave-grupo")&&this.removeAttribute("chave-grupo"),this.controller.chaveGrupo=e,this.controller.context.chaveGrupo=e,this.controller.layerManager.updateContext({chaveGrupo:e})}get zonaProjecao(){return this._zonaProjecao??22}set zonaProjecao(e){const o=typeof e=="number"?Math.floor(e):parseInt(String(e),10);if(!isNaN(o)&&o>0){this._zonaProjecao=o;const i=String(o);this.getAttribute("zona-projecao")!==i&&this.setAttribute("zona-projecao",i),this.hasAttribute("fuso")&&this.getAttribute("fuso")!==i&&this.setAttribute("fuso",i),this.controller.zonaProjecao=o,this.controller.context.zonaProjecao=o}}get canalConfiguracao(){return this.getAttribute("canal-configuracao")}set canalConfiguracao(e){e?this.setAttribute("canal-configuracao",e):this.removeAttribute("canal-configuracao")}fitBounds(e,o=[40,40],i=!1){this.controller.fitBounds(e,o,i)}zoomExtents(){this.controller.canvasInteracao.zoomExtents()}selectPonto(e,o){this.controller.selectPonto(e,o)}selecionarPonto(e,o){this.controller.selectPonto(e,o)}get pontosSelecionados(){return this.controller.context.selectedPontoIds||this.controller.canvasInteracao.ctx.selectedPontoIds||[]}set pontosSelecionados(e){const o=Array.isArray(e)?e:[];this.controller.canvasInteracao.ctx.selectedPontoIds=o,this.controller.context.selectedPontoIds=[...o],this.controller.atualizarDestaqueMarcadores()}atualizarDestaqueMarcadores(){this.controller.atualizarDestaqueMarcadores()}selectSegmento(e){this.controller.selectSegmento(e)}get segmentoSelecionado(){return this.controller.context.selectedSegmentoId||null}set segmentoSelecionado(e){this.controller.selectSegmento(e)}limparSelecao(){this.controller.canvasInteracao.limparSelecao(),this.feicoes.limparSelecaoFeicoes()}setLayerVisibility(e,o){this.controller.layerManager.setLayerVisibility(e,o)}setLayerOpacity(e,o){this.controller.layerManager.setLayerOpacity(e,o)}setLayerScaleMode(e,o){this.controller.layerManager.setLayerScaleMode(e,o)}setGraphicScale(e){this.controller.setGraphicScale(e)}exportState(){return this.controller.exportState()}importState(e){this.controller.importState(e)}invalidateSize(){this.invalidateSizeSafely()}get destaqueAtivo(){return this.controller.destaqueAtivo}destacarElemento(e,o){this.inicializarAgora(),this.controller.destacarElemento(e,o)}limparDestaque(){this.controller.limparDestaque()}plotarPontos(e,o="vertices",i){this.colecoesDados.plotarPontos(e,o,i)}plotarConexoes(e,o="linhas"){this.colecoesDados.plotarConexoes(e,o)}plotarPolilinhaSequencial(e,o=!0,i="polilinha",n){this.colecoesDados.plotarPolilinhaSequencial(e,o,i,n)}plotarPoligonos(e,o="poligonos"){this.colecoesDados.plotarPoligonos(e,o)}limparCamadas(e){this.colecoesDados.limparCamadas(e)}obterMarcadores(e){return this.colecoesDados.obterMarcadores(e)}plotPontos(e,o){this.colecoesDados.plotPontos(e,o)}plotSegmentos(e,o){this.colecoesDados.plotSegmentos(e,o)}plotPolilinhaTemporaria(e){this.colecoesDados.plotPolilinhaTemporaria(e)}plotPoligonalHomologada(e){this.colecoesDados.plotPoligonalHomologada(e)}plotPontosVizinhos(e){this.colecoesDados.plotPontosVizinhos(e)}plotPoligonosVizinhos(e){this.colecoesDados.plotPoligonosVizinhos(e)}clearOverlays(e=!1){this.colecoesDados.clearOverlays(e)}getMarkers(){return this.colecoesDados.getMarkers()}getVizinhosMarkers(){return this.colecoesDados.getVizinhosMarkers()}definirFeicoes(e,o,i){return this.feicoes.definirFeicoes(e,o,i)}adicionarFeicao(e,o,i){return this.feicoes.adicionarFeicao(e,o,i)}atualizarFeicao(e,o,i,n){return this.feicoes.atualizarFeicao(e,o,i,n)}aplicarLote(e,o,i){return this.feicoes.aplicarLote(e,o,i)}removerFeicao(e,o){return this.feicoes.removerFeicao(e,o)}obterFeicoes(e){return this.feicoes.obterFeicoes(e)}selecionarFeicoes(e,o=!1){this.feicoes.selecionarFeicoes(e,o)}selecionarFeicao(e,o){this.feicoes.selecionarFeicoes([{camadaId:e,id:o}])}alternarSelecaoFeicao(e,o){this.feicoes.alternarSelecaoFeicao({camadaId:e,id:o})}limparSelecaoFeicoes(){this.feicoes.limparSelecaoFeicoes()}obterFeicoesSelecionadas(){return this.feicoes.obterFeicoesSelecionadas()}editarVertices(e,o){return this.feicoes.iniciarEdicao(e,o)}pararEdicaoVertices(){this.feicoes.pararEdicao()}get editandoVertices(){return this.feicoes.editando}get snapLigado(){return this.feicoes.snapLigado}definirSnap(e){this.feicoes.definirSnap(e)}alternarSnap(){this.feicoes.alternarSnap()}definirCamadaDesenho(e){this.feicoes.definirCamadaDesenho(e)}get camadaDesenho(){return this.feicoes.camadaDeDesenho}definirEstiloDesenho(e){this.feicoes.definirEstiloDesenho(e)}obterEstiloDesenho(){return this.feicoes.obterEstiloDesenho()}definirFerramenta(e,o){return e===null?(this.feicoes.desativarFerramenta(),{ok:!0}):this.feicoes.ativarFerramenta(e,o)}get ferramentaAtiva(){return this.feicoes.ferramentaAtiva}limparMedicao(){this.feicoes.limparMedicao()}get nosDesenho(){return this.feicoes.nosDesenho}desfazerVerticeDesenho(){return this.feicoes.desfazerVerticeDesenho()}definirAtalhoSnap(e){this.feicoes.definirAtalhoSnap(e)}gerarBuffer(e,o,i,n){return this.feicoes.gerarBuffer(e,o,i,n)}duplicarFeicao(e,o,i,n){return this.feicoes.duplicarFeicao(e,o,i,n)}juntarFeicoes(e,o,i){return this.feicoes.juntarFeicoes(e,o,i)}zoomParaFeicao(e,o){return this.feicoes.zoomParaFeicao(e,o)}zoomParaFeicoes(e){return this.feicoes.zoomParaFeicoes(e)}ajustarTudo(){return this.feicoes.ajustarTudo()}ajustarCamada(e){return this.feicoes.ajustarCamada(e)}get previasGlobais(){return this.feicoes.previasGlobais}definirPreviasGlobais(e){this.feicoes.definirPreviasGlobais(e)}alternarPreviasGlobais(){this.feicoes.alternarPreviasGlobais()}alternarPrevia(e,o){return this.feicoes.alternarPrevia(e,o)}previaSolicitada(e,o){return this.feicoes.previaSolicitada(e,o)}atualizarCursorRemoto(e,o){return this.feicoes.atualizarCursorRemoto(e,o)}removerCursorRemoto(e){return this.feicoes.removerCursorRemoto(e)}limparCursoresRemotos(){this.feicoes.limparCursoresRemotos()}fecharPopupFeicao(){this.feicoes.fecharPopup()}definirOpcoesPopup(e){this.feicoes.definirOpcoesPopup(e)}definirMargensPopup(e){this.feicoes.definirMargensPopup(e)}definirMargensHud(e){this.feicoes.definirMargensHud(e)}getMap(){return this.controller.getMap()}getController(){return this.controller}getLayerManager(){return this.controller.layerManager}}ko.definirCustomElement("ui-canvas-cad",ea);class Qn{constructor(t,e){p(this,"polylines",[]);p(this,"bancoPontosAtivo",!1);p(this,"core");this.core=t}setBancoPontosAtivo(t){this.bancoPontosAtivo=t}plotSegmentos(t,e){this.core.map&&t.forEach(o=>{const i=e.find(s=>String(s.id)===String(o.ponto_inicio_id)),n=e.find(s=>String(s.id)===String(o.ponto_fim_id));if(i&&n&&i.lat&&i.lon&&n.lat&&n.lon){const s=o.tipo_limite_sigef||o.tipo_limite||"",r=o.metodo_posicionamento_sigef||o.metodo_posicionamento||"",c=this.bancoPontosAtivo?"#94a3b8":s==="LA1"?"#10b981":"#3b82f6",l=this.core.config.perimetroWeight,d=this.bancoPontosAtivo?.4:1,h=[[i.lat,i.lon],[n.lat,n.lon]],u=y.polyline(h,{color:"#080d0a",weight:l+3,opacity:.85,lineCap:"round",lineJoin:"round",dashArray:s==="LN1"?"6, 6":void 0,pane:"perimetroPane",interactive:!1}).addTo(this.core.map);this.polylines.push(u);const g=y.polyline(h,{color:c,weight:l,opacity:d,dashArray:s==="LN1"?"6, 6":void 0,pane:"perimetroPane"}).bindPopup(`
168
168
  <div style="font-family:sans-serif; color:rgba(255, 255, 255, 0.9); line-height:1.3;">
169
- <div style="font-weight:700; font-size:12px; margin-bottom:3px; color:#ffffff;">${S.escapeHtml(i.nome_vertice)} ↔ ${S.escapeHtml(a.nome_vertice)}</div>
169
+ <div style="font-weight:700; font-size:12px; margin-bottom:3px; color:#ffffff;">${S.escapeHtml(i.nome_vertice)} ↔ ${S.escapeHtml(n.nome_vertice)}</div>
170
170
  <div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">Limite: ${S.escapeHtml(s)} · ${S.escapeHtml(r)}</div>
171
171
  </div>
172
- `,{className:"compact-popup",maxWidth:220}).addTo(this.core.map);this.polylines.push(m)}})}plotPolilinhaTemporaria(t){var c,l,d;if(!this.core.map)return;const e=t.filter(h=>h.lat&&h.lon&&h.lat!==0&&h.lon!==0&&h.tipo_ponto!=="B"&&h.tipo!=="B"&&h.ignorar_poligono!==1);if(e.length<2)return;const o=((c=this.core.controller)==null?void 0:c.chaveGrupo)||((d=(l=this.core.controller)==null?void 0:l.context)==null?void 0:d.chaveGrupo),i=S.agruparPontosPorChave(e,o),a=this.bancoPontosAtivo?"#94a3b8":"#10b981",s=this.core.config.fechamentoWeight||2,r=this.bancoPontosAtivo?.4:1;Object.values(i).forEach(h=>{const u=S.ordenarPontosPorSequencia(h);if(u.length<2)return;for(let M=0;M<u.length-1;M++){const C=u[M],z=u[M+1],P=[[C.lat,C.lon],[z.lat,z.lon]],v=y.polyline(P,{color:"#080d0a",weight:s+3,opacity:.85,lineCap:"round",lineJoin:"round",pane:"perimetroPane",interactive:!1}).addTo(this.core.map);this.polylines.push(v);const b=y.polyline(P,{color:a,weight:s,opacity:r,pane:"perimetroPane"}).addTo(this.core.map);this.polylines.push(b)}const m=u[u.length-1],f=u[0],g=[[m.lat,m.lon],[f.lat,f.lon]],x=y.polyline(g,{color:"#080d0a",weight:s+2.5,opacity:.75,dashArray:"4, 4",pane:"perimetroPane",interactive:!1}).addTo(this.core.map);this.polylines.push(x);const A=y.polyline(g,{color:a,weight:s,opacity:r,dashArray:"4, 4",pane:"perimetroPane"}).addTo(this.core.map);this.polylines.push(A)})}plotPoligonalHomologada(t){var a,s,r;if(!this.core.map||!this.core.bancoPontosGroup)return;this.core.bancoPontosGroup.clearLayers();const e=t.filter(c=>c.lat&&c.lon&&c.lat!==0&&c.lon!==0);if(e.length===0)return;this.bancoPontosAtivo=!0,e.forEach(c=>{const l=`
172
+ `,{className:"compact-popup",maxWidth:220}).addTo(this.core.map);this.polylines.push(g)}})}plotPolilinhaTemporaria(t){var c,l,d;if(!this.core.map)return;const e=t.filter(h=>h.lat&&h.lon&&h.lat!==0&&h.lon!==0&&h.tipo_ponto!=="B"&&h.tipo!=="B"&&h.ignorar_poligono!==1);if(e.length<2)return;const o=((c=this.core.controller)==null?void 0:c.chaveGrupo)||((d=(l=this.core.controller)==null?void 0:l.context)==null?void 0:d.chaveGrupo),i=S.agruparPontosPorChave(e,o),n=this.bancoPontosAtivo?"#94a3b8":"#10b981",s=this.core.config.fechamentoWeight||2,r=this.bancoPontosAtivo?.4:1;Object.values(i).forEach(h=>{const u=S.ordenarPontosPorSequencia(h);if(u.length<2)return;for(let M=0;M<u.length-1;M++){const A=u[M],C=u[M+1],b=[[A.lat,A.lon],[C.lat,C.lon]],v=y.polyline(b,{color:"#080d0a",weight:s+3,opacity:.85,lineCap:"round",lineJoin:"round",pane:"perimetroPane",interactive:!1}).addTo(this.core.map);this.polylines.push(v);const P=y.polyline(b,{color:n,weight:s,opacity:r,pane:"perimetroPane"}).addTo(this.core.map);this.polylines.push(P)}const g=u[u.length-1],m=u[0],f=[[g.lat,g.lon],[m.lat,m.lon]],x=y.polyline(f,{color:"#080d0a",weight:s+2.5,opacity:.75,dashArray:"4, 4",pane:"perimetroPane",interactive:!1}).addTo(this.core.map);this.polylines.push(x);const E=y.polyline(f,{color:n,weight:s,opacity:r,dashArray:"4, 4",pane:"perimetroPane"}).addTo(this.core.map);this.polylines.push(E)})}plotPoligonalHomologada(t){var n,s,r;if(!this.core.map||!this.core.bancoPontosGroup)return;this.core.bancoPontosGroup.clearLayers();const e=t.filter(c=>c.lat&&c.lon&&c.lat!==0&&c.lon!==0);if(e.length===0)return;this.bancoPontosAtivo=!0,e.forEach(c=>{const l=`
173
173
  <div class="w-4.5 h-4.5 bg-amber-500 text-slate-950 border-2 border-slate-900 rounded-full flex items-center justify-center text-[7px] font-black font-mono shadow-md hover:scale-125 transition-transform" id="banco-marker-${c.id}">
174
174
  H
175
175
  </div>
@@ -183,13 +183,13 @@
183
183
  <div style="font-size:10px; color:rgba(255, 255, 255, 0.45);">Método: ${S.escapeHtml(c.metodo_posicionamento)||"N/A"} · Limite: ${S.escapeHtml(c.tipo_limite)||"N/A"}</div>
184
184
  ${c.confrontante_descritivo?`<div style="font-size:10px; color:rgba(255, 255, 255, 0.65); border-top:1px solid rgba(255, 255, 255, 0.1); padding-top:4px; margin-top:4px; word-break:break-word;"><strong>Conf:</strong> ${S.escapeHtml(c.confrontante_descritivo)}</div>`:""}
185
185
  </div>
186
- `;y.marker([c.lat,c.lon],{icon:d,pane:"verticesPane"}).bindPopup(h,{className:"compact-popup",maxWidth:220}).addTo(this.core.bancoPontosGroup)});const o=((a=this.core.controller)==null?void 0:a.chaveGrupo)||((r=(s=this.core.controller)==null?void 0:s.context)==null?void 0:r.chaveGrupo),i=S.agruparPontosPorChave(e,o);for(const c in i){const l=S.ordenarPontosPorSequencia(i[c]);if(l.length>=2){const d=l.map(h=>y.latLng(h.lat,h.lon));d.push(y.latLng(l[0].lat,l[0].lon)),y.polyline(d,{color:"#f59e0b",weight:this.core.config.bancoWeight,dashArray:"6, 8",pane:"perimetroPane"}).addTo(this.core.bancoPontosGroup)}}}clearLinhas(){this.core.map&&this.polylines.forEach(t=>this.core.map.removeLayer(t)),this.core.bancoPontosGroup&&this.core.bancoPontosGroup.clearLayers(),this.polylines=[]}}class Ga{constructor(t,e){p(this,"markers",[]);p(this,"vizinhosMarkers",[]);p(this,"vizinhosPoligonos",[]);p(this,"core");p(this,"controller");this.core=t,this.controller=e}plotPontos(t,e){this.core.map&&t.forEach(o=>{var i,a,s;if(o.lat&&o.lon&&o.lat!==0&&o.lon!==0){const r=o.tipo_ponto==="B"||o.tipo==="B",c=o.tipo_ponto==="M"||o.tipo==="M";let l="bg-mint-vibrant",d="x",h=7;c?(l="bg-indigo-500",h=9):r&&(l="bg-rose-500",h=9);const u=this.core.config.enableAnimations?"transition-all duration-150":"",m=(a=(i=this.controller)==null?void 0:i.linhas)!=null&&a.bancoPontosAtivo?"opacity-40 hover:opacity-100":"",f=At(d,h,l,`${u} ${m}`,`map-marker-${o.id}`),g=y.divIcon({html:f,className:"custom-leaflet-marker flex items-center justify-center",iconSize:[h+6,h+6]}),x=c?"Base Homologada PPP":r?"Base de Campo (Translação)":"Vértice de Perímetro",A=y.marker([o.lat,o.lon],{icon:g,pane:"verticesPane"});A.pontoId=o.id,(s=this.controller)!=null&&s.modoCliqueSequencialAtivo||A.bindPopup(`
186
+ `;y.marker([c.lat,c.lon],{icon:d,pane:"verticesPane"}).bindPopup(h,{className:"compact-popup",maxWidth:220}).addTo(this.core.bancoPontosGroup)});const o=((n=this.core.controller)==null?void 0:n.chaveGrupo)||((r=(s=this.core.controller)==null?void 0:s.context)==null?void 0:r.chaveGrupo),i=S.agruparPontosPorChave(e,o);for(const c in i){const l=S.ordenarPontosPorSequencia(i[c]);if(l.length>=2){const d=l.map(h=>y.latLng(h.lat,h.lon));d.push(y.latLng(l[0].lat,l[0].lon)),y.polyline(d,{color:"#f59e0b",weight:this.core.config.bancoWeight,dashArray:"6, 8",pane:"perimetroPane"}).addTo(this.core.bancoPontosGroup)}}}clearLinhas(){this.core.map&&this.polylines.forEach(t=>this.core.map.removeLayer(t)),this.core.bancoPontosGroup&&this.core.bancoPontosGroup.clearLayers(),this.polylines=[]}}class ts{constructor(t,e){p(this,"markers",[]);p(this,"vizinhosMarkers",[]);p(this,"vizinhosPoligonos",[]);p(this,"core");p(this,"controller");this.core=t,this.controller=e}plotPontos(t,e){this.core.map&&t.forEach(o=>{var i,n,s;if(o.lat&&o.lon&&o.lat!==0&&o.lon!==0){const r=o.tipo_ponto==="B"||o.tipo==="B",c=o.tipo_ponto==="M"||o.tipo==="M";let l="bg-mint-vibrant",d="x",h=7;c?(l="bg-indigo-500",h=9):r&&(l="bg-rose-500",h=9);const u=this.core.config.enableAnimations?"transition-all duration-150":"",g=(n=(i=this.controller)==null?void 0:i.linhas)!=null&&n.bancoPontosAtivo?"opacity-40 hover:opacity-100":"",m=zt(d,h,l,`${u} ${g}`,`map-marker-${o.id}`),f=y.divIcon({html:m,className:"custom-leaflet-marker flex items-center justify-center",iconSize:[h+6,h+6]}),x=c?"Base Homologada PPP":r?"Base de Campo (Translação)":"Vértice de Perímetro",E=y.marker([o.lat,o.lon],{icon:f,pane:"verticesPane"});E.pontoId=o.id,(s=this.controller)!=null&&s.modoCliqueSequencialAtivo||E.bindPopup(`
187
187
  <div style="font-family:var(--ui-fonte-base, sans-serif); color:rgba(255, 255, 255, 0.9); line-height:1.3;">
188
188
  <div style="font-weight:700; font-size:13px; margin-bottom:4px; color:#ffffff;">${S.escapeHtml(o.nome_vertice)}</div>
189
189
  <div style="font-size:11px; color:rgba(255, 255, 255, 0.65);">${S.escapeHtml(x)} · ${S.escapeHtml(o.tipo_ponto||o.tipo)}</div>
190
190
  <div style="font-size:11px; color:rgba(255, 255, 255, 0.45); font-family:var(--ui-fonte-codigo, monospace); margin-top:4px;">Lat ${o.lat.toFixed(6)} &nbsp; Lon ${o.lon.toFixed(6)}</div>
191
191
  </div>
192
- `,{className:"compact-popup",maxWidth:220}),A.addTo(this.core.map),A.setZIndexOffset(1e3),A.on("click",()=>{e(o.id)}),this.markers.push(A)}})}plotPontosVizinhos(t){if(!this.core.map||!this.core.pontosVizinhosGroup)return;this.core.map.hasLayer(this.core.pontosVizinhosGroup)||this.core.pontosVizinhosGroup.addTo(this.core.map),this.vizinhosMarkers&&this.vizinhosMarkers.length>0&&(this.vizinhosMarkers.forEach(o=>{o.off(),o.unbindPopup()}),this.vizinhosMarkers=[]),this.core.pontosVizinhosGroup.clearLayers();const e=new Map;(t||[]).forEach(o=>{const i=o.lat??o.latitude??o.y,a=o.lon??o.lng??o.longitude??o.x,s=typeof i=="string"?parseFloat(i.replace(",",".")):Number(i),r=typeof a=="string"?parseFloat(a.replace(",",".")):Number(a);if(s!==void 0&&r!==void 0&&!isNaN(s)&&!isNaN(r)&&s!==0&&r!==0){o.lat=s,o.lon=r;const c=o.confrontante_id!==void 0&&o.confrontante_id!==null?String(o.confrontante_id):"0";e.has(c)||e.set(c,[]),e.get(c).push(o)}}),e.forEach(o=>{if(o.length>=2){o.sort((a,s)=>Number(a.id)-Number(s.id));const i=o.map(a=>y.latLng(a.lat,a.lon));o.length>2&&i.push(y.latLng(o[0].lat,o[0].lon)),y.polyline(i,{color:"#a855f7",weight:this.core.config.vizinhoWeight,dashArray:"4, 6",pane:"overlayPane"}).addTo(this.core.pontosVizinhosGroup)}o.forEach(i=>{var u,m;const a=document.createElement("div");a.className="p-2 font-sans text-xs bg-[#0c1510] text-white min-w-[200px] rounded",a.innerHTML=`
192
+ `,{className:"compact-popup",maxWidth:220}),E.addTo(this.core.map),E.setZIndexOffset(1e3),E.on("click",()=>{e(o.id)}),this.markers.push(E)}})}plotPontosVizinhos(t){if(!this.core.map||!this.core.pontosVizinhosGroup)return;this.core.map.hasLayer(this.core.pontosVizinhosGroup)||this.core.pontosVizinhosGroup.addTo(this.core.map),this.vizinhosMarkers&&this.vizinhosMarkers.length>0&&(this.vizinhosMarkers.forEach(o=>{o.off(),o.unbindPopup()}),this.vizinhosMarkers=[]),this.core.pontosVizinhosGroup.clearLayers();const e=new Map;(t||[]).forEach(o=>{const i=o.lat??o.latitude??o.y,n=o.lon??o.lng??o.longitude??o.x,s=typeof i=="string"?parseFloat(i.replace(",",".")):Number(i),r=typeof n=="string"?parseFloat(n.replace(",",".")):Number(n);if(s!==void 0&&r!==void 0&&!isNaN(s)&&!isNaN(r)&&s!==0&&r!==0){o.lat=s,o.lon=r;const c=o.confrontante_id!==void 0&&o.confrontante_id!==null?String(o.confrontante_id):"0";e.has(c)||e.set(c,[]),e.get(c).push(o)}}),e.forEach(o=>{if(o.length>=2){o.sort((n,s)=>Number(n.id)-Number(s.id));const i=o.map(n=>y.latLng(n.lat,n.lon));o.length>2&&i.push(y.latLng(o[0].lat,o[0].lon)),y.polyline(i,{color:"#a855f7",weight:this.core.config.vizinhoWeight,dashArray:"4, 6",pane:"overlayPane"}).addTo(this.core.pontosVizinhosGroup)}o.forEach(i=>{var u,g;const n=document.createElement("div");n.className="p-2 font-sans text-xs bg-[#0c1510] text-white min-w-[200px] rounded",n.innerHTML=`
193
193
  <div class="font-bold text-purple-400 mb-1 border-b border-white/10 pb-1">Confrontante (Importado)</div>
194
194
  <div class="mb-1"><strong>Vértice:</strong> <span class="font-mono">${S.escapeHtml(i.nome_vertice||"")}</span></div>
195
195
  <div class="mb-1"><strong>Proprietário:</strong> ${S.escapeHtml(i.nome_confrontante||"")||"Desconhecido"}</div>
@@ -204,10 +204,10 @@
204
204
  Ocultar
205
205
  </button>
206
206
  </div>
207
- `,(u=a.querySelector(".btn-integrar"))==null||u.addEventListener("click",()=>{window.dispatchEvent(new CustomEvent("gerencigeo:integrar_vizinho",{detail:{pontoId:i.id}}))}),(m=a.querySelector(".btn-ocultar"))==null||m.addEventListener("click",()=>{window.dispatchEvent(new CustomEvent("gerencigeo:ocultar_vizinho",{detail:{pontoId:i.id}}))});let s=this.core.config.markerStyleV||"cross",r=this.core.config.markerSizeV||8;i.tipo_ponto==="M"||i.tipo==="M"||i.tipo==="B"?(s=this.core.config.markerStyleM||"circle-dot",r=this.core.config.markerSizeM||14):(i.tipo_ponto==="P"||i.tipo==="P"||i.tipo==="O")&&(s=this.core.config.markerStyleP||"circle",r=this.core.config.markerSizeP||10);const c=this.core.config.enableAnimations?"transition-all duration-150":"",l=At(s,r,"bg-[#a855f7]",c,`map-marker-vizinho-${i.id}`),d=y.divIcon({html:l,className:"custom-leaflet-marker flex items-center justify-center",iconSize:[r+4,r+4]}),h=y.marker([i.lat,i.lon],{icon:d,pane:"overlayPane"}).bindPopup(a,{className:"custom-leaflet-popup"});h.pontoId=i.id,h.isVizinho=!0,h.addTo(this.core.pontosVizinhosGroup),this.vizinhosMarkers.push(h)})})}plotPoligonosVizinhos(t){!this.core.map||!this.core.pontosVizinhosGroup||(this.core.map.hasLayer(this.core.pontosVizinhosGroup)||this.core.pontosVizinhosGroup.addTo(this.core.map),this.vizinhosPoligonos.length>0&&(this.vizinhosPoligonos.forEach(e=>e.off()),this.vizinhosPoligonos=[]),(t||[]).forEach(e=>{if(!e||!e.poligono_wkt)return;const o=/POLYGON\s*\(\s*\(\s*(.*?)\s*\)\s*\)/i.exec(e.poligono_wkt);if(!o)return;const i=o[1].split(",").map(c=>{const l=c.trim().split(/\s+/),d=parseFloat(l[0]),h=parseFloat(l[1]);return!isNaN(h)&&!isNaN(d)?[h,d]:null}).filter(c=>c!==null);if(i.length<3)return;const a=S.escapeHtml(e.nome_propriedade||"Propriedade Vizinha"),s=S.escapeHtml(e.nome||"Desconhecido"),r=y.polygon(i,{color:"#a855f7",weight:this.core.config.vizinhoWeight,dashArray:"4, 6",fillColor:"#a855f7",fillOpacity:.05,pane:"overlayPane"}).bindPopup(`
207
+ `,(u=n.querySelector(".btn-integrar"))==null||u.addEventListener("click",()=>{window.dispatchEvent(new CustomEvent("gerencigeo:integrar_vizinho",{detail:{pontoId:i.id}}))}),(g=n.querySelector(".btn-ocultar"))==null||g.addEventListener("click",()=>{window.dispatchEvent(new CustomEvent("gerencigeo:ocultar_vizinho",{detail:{pontoId:i.id}}))});let s=this.core.config.markerStyleV||"cross",r=this.core.config.markerSizeV||8;i.tipo_ponto==="M"||i.tipo==="M"||i.tipo==="B"?(s=this.core.config.markerStyleM||"circle-dot",r=this.core.config.markerSizeM||14):(i.tipo_ponto==="P"||i.tipo==="P"||i.tipo==="O")&&(s=this.core.config.markerStyleP||"circle",r=this.core.config.markerSizeP||10);const c=this.core.config.enableAnimations?"transition-all duration-150":"",l=zt(s,r,"bg-[#a855f7]",c,`map-marker-vizinho-${i.id}`),d=y.divIcon({html:l,className:"custom-leaflet-marker flex items-center justify-center",iconSize:[r+4,r+4]}),h=y.marker([i.lat,i.lon],{icon:d,pane:"overlayPane"}).bindPopup(n,{className:"custom-leaflet-popup"});h.pontoId=i.id,h.isVizinho=!0,h.addTo(this.core.pontosVizinhosGroup),this.vizinhosMarkers.push(h)})})}plotPoligonosVizinhos(t){!this.core.map||!this.core.pontosVizinhosGroup||(this.core.map.hasLayer(this.core.pontosVizinhosGroup)||this.core.pontosVizinhosGroup.addTo(this.core.map),this.vizinhosPoligonos.length>0&&(this.vizinhosPoligonos.forEach(e=>e.off()),this.vizinhosPoligonos=[]),(t||[]).forEach(e=>{if(!e||!e.poligono_wkt)return;const o=/POLYGON\s*\(\s*\(\s*(.*?)\s*\)\s*\)/i.exec(e.poligono_wkt);if(!o)return;const i=o[1].split(",").map(c=>{const l=c.trim().split(/\s+/),d=parseFloat(l[0]),h=parseFloat(l[1]);return!isNaN(h)&&!isNaN(d)?[h,d]:null}).filter(c=>c!==null);if(i.length<3)return;const n=S.escapeHtml(e.nome_propriedade||"Propriedade Vizinha"),s=S.escapeHtml(e.nome||"Desconhecido"),r=y.polygon(i,{color:"#a855f7",weight:this.core.config.vizinhoWeight,dashArray:"4, 6",fillColor:"#a855f7",fillOpacity:.05,pane:"overlayPane"}).bindPopup(`
208
208
  <div class="p-2 font-sans text-xs bg-[#0c1510] text-white min-w-[200px] rounded">
209
209
  <div class="font-bold text-purple-400 mb-1 border-b border-white/10 pb-1">Limite do Vizinho (Importado)</div>
210
- <div class="mb-1"><strong>Propriedade:</strong> ${a}</div>
210
+ <div class="mb-1"><strong>Propriedade:</strong> ${n}</div>
211
211
  <div class="mb-1"><strong>Proprietário:</strong> ${s}</div>
212
212
  </div>
213
- `,{className:"custom-leaflet-popup"});r.addTo(this.core.pontosVizinhosGroup),this.vizinhosPoligonos.push(r)}))}clearMarkers(){this.markers&&(this.markers.forEach(t=>{t.off(),t.unbindPopup(),this.core.map&&this.core.map.removeLayer(t)}),this.markers=[]),this.vizinhosMarkers&&(this.vizinhosMarkers.forEach(t=>{t.off(),t.unbindPopup()}),this.vizinhosMarkers=[]),this.vizinhosPoligonos&&(this.vizinhosPoligonos.forEach(t=>t.off()),this.vizinhosPoligonos=[]),this.core.pontosVizinhosGroup&&this.core.pontosVizinhosGroup.clearLayers()}}exports.agruparPontosPorChave=S.agruparPontosPorChave;exports.bindPopupAcoesEvents=S.bindPopupAcoesEvents;exports.escapeHtml=S.escapeHtml;exports.extrairCentroDeWkt=S.extrairCentroDeWkt;exports.formatUTM=S.formatUTM;exports.ordenarPontosPorSequencia=S.ordenarPontosPorSequencia;exports.parseCoordenada=S.parseCoordenada;exports.renderPopupAcoesHtml=S.renderPopupAcoesHtml;exports.AgrupadorCluster=ni;exports.CADMapaController=ie;exports.CAD_INTERACTIVE_PANES=wo;exports.CELULA_CLUSTER_PX=zt;exports.CLASSE_FERRAMENTA_ATIVA=ze;exports.COR_SELECAO=ft;exports.CSS_POSICAO_HUD=Ge;exports.CanvasCADController=ie;exports.CanvasInteracao=To;exports.CanvasLayerManager=si;exports.ControleDesenho=Yi;exports.CursoresRemotos=mi;exports.DEFAULT_CONFIG=ye;exports.DEFAULT_LAYERS=Se;exports.EditorVertices=ji;exports.FERRAMENTAS=oe;exports.FOLGA_HUD=Bi;exports.FRACAO_LARGURA_HUD=Hi;exports.FeicaoPopup=Ai;exports.FeicoesLayerRenderer=ai;exports.GerenciGeoMapaController=ie;exports.GridLayerRenderer=Bo;exports.ICONES_FEICAO=Ft;exports.ID_HUD_DESENHO=Zi;exports.ID_HUD_EDICAO=Gi;exports.IndiceEspacial=Go;exports.LIMIAR_DENSIDADE_ALTA=Ut;exports.LIMITE_CULLING=Le;exports.LayerRendererFactory=F;exports.MARGEM_HUD_PADRAO=Ri;exports.MAX_PONTOS_SEM_CLUSTER=oi;exports.MAX_VERTICES_EDICAO=wi;exports.MIN_VERTICES_SIMPLIFICAR=$e;exports.MapaConfigManager=jt;exports.MapaCore=Ao;exports.MapaLinhas=Va;exports.MapaMarcadores=Ga;exports.PROPRIEDADES_HUD=Vt;exports.RAIO_MINIMO_CIRCULO_M=ke;exports.RAIO_MINIMO_EDICAO_CIRCULO_M=Ii;exports.RegraVersoes=Zt;exports.SelecaoFeicoes=gi;exports.SessaoDesenho=Gt;exports.TOLERANCIA_AMOSTRA_PX=Ki;exports.TOLERANCIA_LINHA_PX=Ot;exports.TOLERANCIA_PONTO_PX=Eo;exports.TOLERANCIA_SNAP_PX=je;exports.TileLayerRenderer=Do;exports.UICanvasCAD=Ji;exports.VectorLinesLayerRenderer=No;exports.VectorPointsLayerRenderer=Fo;exports.VectorPolygonsLayerRenderer=Ro;exports.WmsLayerRenderer=$o;exports.ZOOM_DESMEMBRAR=ei;exports.ZOOM_SEM_SIMPLIFICACAO=Xt;exports.agruparPontos=Ln;exports.alternarSuavidade=Fi;exports.amostrarBezier=Xi;exports.aplicarMargensHud=Vi;exports.areaDaGeometria=Q;exports.areaMetros2=Ho;exports.buscarSnap=Ui;exports.caixaDaFeicao=Ce;exports.caixasSeTocam=mt;exports.centroDe=ii;exports.clonarFeicao=Bt;exports.comPontos=Ti;exports.comVertices=Tt;exports.comprimentoMetros=kt;exports.confrontanteParaFeicao=Qn;exports.consultarFeicoesNoPonto=_e;exports.converterArea=ca;exports.converterComprimento=ra;exports.coordenadaDeReferencia=Et;exports.corHexSegura=Jt;exports.corSegura=Z;exports.criarControladorTamanho=pi;exports.criarLinha=yt;exports.ddParaDms=la;exports.deslocarGeometria=Li;exports.deveAgrupar=Kt;exports.distanciaEntre=ha;exports.distanciaMetros=st;exports.dividirPoligonoComLinha=yi;exports.dmsParaDd=da;exports.ehFerramenta=Ue;exports.ehMultilinha=wt;exports.entidadeDe=nt;exports.extensaoDaGeometria=tt;exports.extrairCorPonto=Oo;exports.fatorDensidade=Te;exports.feicaoNaCaixa=Si;exports.feicaoNoLaco=Mi;exports.feicaoNoPonto=Ee;exports.feicaoNoTopo=hn;exports.formatarArea=rt;exports.formatarExtensao=G;exports.garantirCanvasSemEventos=Io;exports.gerarBuffer=Ci;exports.getPointShapeHtml=At;exports.inserirPonto=$i;exports.inserirVertice=zi;exports.juntarLinhas=bi;exports.juntarPoligonos=Pi;exports.limitesDaGeometria=De;exports.minimoVertices=_t;exports.modoDensidade=Wt;exports.moverAlca=Oi;exports.moverVertice=xa;exports.normalizarAnel=Re;exports.normalizarCoordenada=X;exports.normalizarFeicaoEntrada=Rt;exports.normalizarLinha=Ae;exports.normalizarPoligono=fi;exports.nosDe=U;exports.nosDeAncoras=Mt;exports.partesDaLinha=j;exports.pontoDaBordaDoCirculo=_i;exports.pontoMedio=He;exports.pontoMedioDoSegmento=Ht;exports.pontoNoPoligono=Be;exports.pontoParaFeicao=Kn;exports.pontosDe=St;exports.posicaoHud=Ca;exports.processarAcaoPopup=di;exports.processarCliqueLivreCanvas=li;exports.removerPonto=qi;exports.removerVertice=Ei;exports.renderizarPainelCamadas=ci;exports.resolverCliqueCentral=_o;exports.segmentoParaFeicao=Jn;exports.segmentosDe=Ve;exports.segmentosDoEditor=Di;exports.simplificarAnel=Uo;exports.simplificarGeometria=Wo;exports.simplificarLinha=qe;exports.statusDe=Y;exports.textoRotulo=Vo;exports.toleranciaPorZoom=jo;exports.tratarCliqueMarcador=hi;exports.tratarCliqueSegmento=ui;exports.verificarEditavel=ki;exports.vertices=Ne;exports.verticesDe=K;
213
+ `,{className:"custom-leaflet-popup"});r.addTo(this.core.pontosVizinhosGroup),this.vizinhosPoligonos.push(r)}))}clearMarkers(){this.markers&&(this.markers.forEach(t=>{t.off(),t.unbindPopup(),this.core.map&&this.core.map.removeLayer(t)}),this.markers=[]),this.vizinhosMarkers&&(this.vizinhosMarkers.forEach(t=>{t.off(),t.unbindPopup()}),this.vizinhosMarkers=[]),this.vizinhosPoligonos&&(this.vizinhosPoligonos.forEach(t=>t.off()),this.vizinhosPoligonos=[]),this.core.pontosVizinhosGroup&&this.core.pontosVizinhosGroup.clearLayers()}}exports.agruparPontosPorChave=S.agruparPontosPorChave;exports.bindPopupAcoesEvents=S.bindPopupAcoesEvents;exports.escapeHtml=S.escapeHtml;exports.extrairCentroDeWkt=S.extrairCentroDeWkt;exports.formatUTM=S.formatUTM;exports.ordenarPontosPorSequencia=S.ordenarPontosPorSequencia;exports.parseCoordenada=S.parseCoordenada;exports.renderPopupAcoesHtml=S.renderPopupAcoesHtml;exports.AgrupadorCluster=li;exports.CADMapaController=le;exports.CAD_INTERACTIVE_PANES=_o;exports.CELULA_CLUSTER_PX=_t;exports.CLASSE_FERRAMENTA_ATIVA=De;exports.COR_SELECAO=mt;exports.CSS_POSICAO_HUD=Ze;exports.CanvasCADController=le;exports.CanvasInteracao=Oo;exports.CanvasLayerManager=hi;exports.ControleDesenho=Qi;exports.CursoresRemotos=bi;exports.DEFAULT_CONFIG=Se;exports.DEFAULT_LAYERS=ke;exports.EditorVertices=Xi;exports.FERRAMENTAS=ce;exports.FOLGA_HUD=Gi;exports.FRACAO_LARGURA_HUD=ji;exports.FeicaoPopup=Ii;exports.FeicoesLayerRenderer=di;exports.GerenciGeoMapaController=le;exports.GridLayerRenderer=Uo;exports.ICONES_FEICAO=Ht;exports.ID_HUD_DESENHO=Ji;exports.ID_HUD_EDICAO=Wi;exports.IndiceEspacial=Zo;exports.LIMIAR_DENSIDADE_ALTA=Jt;exports.LIMITE_CULLING=ze;exports.LayerRendererFactory=R;exports.MARGEM_HUD_PADRAO=Hi;exports.MAX_PONTOS_SEM_CLUSTER=ri;exports.MAX_VERTICES_EDICAO=_i;exports.MIN_VERTICES_SIMPLIFICAR=Re;exports.MapaConfigManager=Yt;exports.MapaCore=Io;exports.MapaLinhas=Qn;exports.MapaMarcadores=ts;exports.PROPRIEDADES_HUD=Wt;exports.RAIO_MINIMO_CIRCULO_M=Xt;exports.RAIO_MINIMO_EDICAO_CIRCULO_M=$i;exports.RegraVersoes=ee;exports.SelecaoFeicoes=Pi;exports.SessaoDesenho=Zt;exports.TOLERANCIA_AMOSTRA_PX=ta;exports.TOLERANCIA_LINHA_PX=Vt;exports.TOLERANCIA_PONTO_PX=$o;exports.TOLERANCIA_SNAP_PX=Ye;exports.TileLayerRenderer=Ro;exports.UICanvasCAD=ea;exports.VectorLinesLayerRenderer=Vo;exports.VectorPointsLayerRenderer=Go;exports.VectorPolygonsLayerRenderer=jo;exports.WmsLayerRenderer=Fo;exports.ZOOM_DESMEMBRAR=si;exports.ZOOM_SEM_SIMPLIFICACAO=te;exports.agruparPontos=Ma;exports.alternarSuavidade=Vi;exports.amostrarBezier=Ki;exports.aplicarMargensHud=Ui;exports.areaDaGeometria=Q;exports.areaMetros2=Wo;exports.buscarSnap=Zi;exports.caixaDaFeicao=Ee;exports.caixasSeTocam=vt;exports.centroDe=ci;exports.clonarFeicao=jt;exports.comPontos=Ni;exports.comVertices=qt;exports.comprimentoMetros=It;exports.confrontanteParaFeicao=en;exports.consultarFeicoesNoPonto=qe;exports.converterArea=hn;exports.converterComprimento=dn;exports.coordenadaDeReferencia=Tt;exports.corHexSegura=ae;exports.corSegura=Y;exports.criarControladorTamanho=yi;exports.criarLinha=bt;exports.ddParaDms=un;exports.deslocarGeometria=Ei;exports.deveAgrupar=ie;exports.distanciaEntre=fn;exports.distanciaMetros=et;exports.dividirPoligonoComLinha=Li;exports.dmsParaDd=pn;exports.ehFerramenta=Ke;exports.ehMultilinha=kt;exports.entidadeDe=nt;exports.extensaoDaGeometria=tt;exports.extrairCorPonto=Ho;exports.fatorDensidade=Ne;exports.feicaoNaCaixa=zi;exports.feicaoNoLaco=ki;exports.feicaoNoPonto=$e;exports.feicaoNoTopo=pa;exports.formatarArea=rt;exports.formatarExtensao=G;exports.garantirCanvasSemEventos=No;exports.gerarBuffer=wi;exports.getPointShapeHtml=zt;exports.inserirPonto=Oi;exports.inserirVertice=Ti;exports.juntarLinhas=Mi;exports.juntarPoligonos=Ai;exports.limitesDaGeometria=Oe;exports.minimoVertices=Lt;exports.modoDensidade=Qt;exports.moverAlca=Bi;exports.moverVertice=Cn;exports.normalizarAnel=Ge;exports.normalizarCoordenada=X;exports.normalizarFeicaoEntrada=Gt;exports.normalizarLinha=_e;exports.normalizarPoligono=xi;exports.nosDe=j;exports.nosDeAncoras=Et;exports.partesDaLinha=U;exports.pontoDaBordaDoCirculo=qi;exports.pontoMedio=Ue;exports.pontoMedioDoSegmento=gt;exports.pontoNoPoligono=je;exports.pontoParaFeicao=Qa;exports.pontosDe=ht;exports.posicaoHud=Mn;exports.processarAcaoPopup=mi;exports.processarCliqueLivreCanvas=fi;exports.removerPonto=Ri;exports.removerVertice=Di;exports.renderizarPainelCamadas=pi;exports.resolverCliqueCentral=Ae;exports.segmentoParaFeicao=tn;exports.segmentosDe=We;exports.segmentosDoEditor=Xe;exports.simplificarAnel=Ko;exports.simplificarGeometria=Jo;exports.simplificarLinha=Fe;exports.statusDe=K;exports.textoRotulo=Xo;exports.toleranciaPorZoom=Yo;exports.tratarCliqueMarcador=gi;exports.tratarCliqueSegmento=vi;exports.verificarEditavel=Ut;exports.vertices=Be;exports.verticesDe=Z;