import{r as i}from"./index-C4inJ1rU.js";import{u as C}from"./maplibre-gl-ClZLWYTA.js";const E={light:"https://basemaps.cartocdn.com/gl/positron-gl-style/style.json",dark:"https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json"},x={light:"basemap-light-",dark:"basemap-dark-"},m={};async function R(n){if(m[n])return m[n];const t=await(await fetch(E[n])).json();return m[n]=t,t}function W({mode:n}){const{current:l}=C(),[t,v]=i.useState(null),u=i.useRef({light:!1,dark:!1}),L=i.useRef({light:[],dark:[]}),h=i.useRef(n);i.useEffect(()=>{h.current=n},[n]),i.useEffect(()=>{const e=()=>{var a;const s=(a=l==null?void 0:l.getMap)==null?void 0:a.call(l);s&&!t&&v(s)};e();const r=setInterval(e,50),o=setTimeout(()=>clearInterval(r),5e3);return()=>{clearInterval(r),clearTimeout(o)}},[l,t]);const p=i.useCallback(async(e,r,o)=>{var b,I;if(u.current[r])return;const s=x[r],a=await R(r),g=[];for(const[y,d]of Object.entries(a.sources||{})){const c=s+y;e.getSource(c)||e.addSource(c,d)}const S=(I=(((b=e.getStyle())==null?void 0:b.layers)||[]).find(y=>!y.id.startsWith("basemap-light-")&&!y.id.startsWith("basemap-dark-")))==null?void 0:I.id;for(const y of a.layers||[]){const d=s+y.id;if(g.push(d),e.getLayer(d))continue;const c={...y,id:d};"source"in c&&typeof c.source=="string"&&(c.source=s+c.source),c.layout||(c.layout={}),c.layout.visibility=o?"visible":"none";try{e.addLayer(c,S)}catch(w){console.warn(`[BasemapLayer] Failed to add layer ${d}:`,w)}}L.current[r]=g,u.current[r]=!0},[]),f=i.useCallback((e,r,o)=>{const s=L.current[r],a=o?"visible":"none";for(const g of s)if(e.getLayer(g))try{e.setLayoutProperty(g,"visibility",a)}catch{}},[]),k=i.useCallback(e=>{var s;const o=(((s=e.getStyle())==null?void 0:s.layers)||[]).filter(a=>!a.id.startsWith("basemap-light-")&&!a.id.startsWith("basemap-dark-"));for(const a of o)try{e.moveLayer(a.id)}catch{}},[]);return i.useEffect(()=>{if(!t)return;const e=r=>{t.hasImage(r.id)||t.addImage(r.id,{width:1,height:1,data:new Uint8Array([0,0,0,0])})};return t.on("styleimagemissing",e),()=>{t.off("styleimagemissing",e)}},[t]),i.useEffect(()=>{if(!t)return;let e=!1;const r=async()=>{if(!e)try{const s=h.current;await Promise.all([p(t,"light",s==="light"),p(t,"dark",s==="dark")]),e||(f(t,"light",h.current==="light"),f(t,"dark",h.current==="dark"),k(t),t.resize())}catch(s){console.error("[BasemapLayer] Setup error:",s)}};t.isStyleLoaded()?r():(t.once("style.load",r),t.once("load",()=>{!e&&!u.current.light&&r()}));const o=()=>{e||setTimeout(()=>{!e&&u.current.light&&u.current.dark&&k(t)},100)};return t.on("styledata",o),()=>{e=!0,t.off("styledata",o)}},[t,p,k,f]),i.useEffect(()=>{t&&(!u.current.light||!u.current.dark||(f(t,"light",n==="light"),f(t,"dark",n==="dark"),t.resize(),t.triggerRepaint()))},[t,n,f]),null}export{W as B};
