(()=>{function S(p,e="#757575"){let i={GOB:"--gob-color",CEN:"--cen-color",DEP:"--dep-color",INS:"--ins-color",SER:"--ser-color",OTR:"--otr-color"}[p];if(!i)return e;try{return getComputedStyle(document.documentElement).getPropertyValue(i).trim()||e}catch{return e}}var l={GOOGLE_MAPS_API_KEY:"AIzaSyBffInKpFhzWQLFg7DWpYuO09naW_UdN_o",MAP_CENTER:{lat:39.4815,lng:-.347},MAP_ZOOM:16,SUPERTIPOS:{GOB:{name:"\xD3rganos de gobierno",nameShort:"GOB",get color(){return S("GOB","#7B1FA2")},textColor:"#FFFFFF",visible:!0},CEN:{name:"Centros docentes",nameShort:"CEN",get color(){return S("CEN","#D73333")},textColor:"#FFFFFF",visible:!0},DEP:{name:"Departamentos",nameShort:"DEP",get color(){return S("DEP","#2C76A0")},textColor:"#FFFFFF",visible:!1},INS:{name:"Estructuras de investigaci\xF3n",nameShort:"INS",get color(){return S("INS","#946C00")},textColor:"#FFFFFF",visible:!1},SER:{name:"Servicios generales",nameShort:"SER",get color(){return S("SER","#0E8A00")},textColor:"#FFFFFF",visible:!1},OTR:{name:"Otras entidades",nameShort:"OTR",get color(){return S("OTR","#595959")},textColor:"#FFFFFF",visible:!1}},PRIORIDAD_SUPERTIPOS:["GOB","CEN","DEP","INS","SER","OTR"],CAMPUS:{V:{name:"Vera",nameLong:"Campus de Valencia",lat:39.480734,lng:-.341096},A:{name:"Alcoy",nameLong:"Campus de Alcoy",lat:38.6941453,lng:-.4773104},G:{name:"Gandia",nameLong:"Campus de Gandia",lat:38.995972,lng:-.165734},H:{name:"Buihang",nameLong:"BUIHANG",lat:39.983108,lng:116.3446315}},PATHS:{DATA_JSON:"/plano/data/entidades.json",POIS_JSON:"/plano/data/pois.json",IMAGES_BASE:"/plano/imagenes/",POIS_IMAGES:"/plano/imagenes/pois/"},SEARCH:{MIN_CHARS:2,MAX_RESULTS:15}};var X={es:{searchPlaceholder:"BUSCAR EDIFICIO O ENTIDAD...",searchResultsLabel:"Resultados de b\xFAsqueda",searchResultsCount:"{count} resultados encontrados",searchNoResults:"No se encontraron resultados",filtersTitle:"ENTIDADES",toggleShowAll:"Todos los edificios",toggleHideAll:"Ocultar todos",buildingLabel:"Edificio",buildingTitle:"Edificio",building:"Edificio",noEntities:"Sin entidades registradas",howToGet:"C\xF3mo llegar",website:"Sitio web",otherEntities:"Otras entidades en edificio",noResults:"No se encontraron resultados",buildings:"Edificios",close:"Cerrar",openMapsTitle:"Ver plantas y espacios",viewOnBaiduMaps:"Ver en Baidu Maps",valenbisiLoading:"Cargando disponibilidad...",valenbisiError:"No se pudo obtener disponibilidad",valenbisiFreeBikes:"Bicis disponibles",valenbisiEmptySlots:"Huecos libres",valenbisiClosed:"Estaci\xF3n cerrada",valenbisiOpen:"Estaci\xF3n abierta"},va:{searchPlaceholder:"CERCAR EDIFICI O ENTITAT...",searchResultsLabel:"Resultats de cerca",searchResultsCount:"{count} resultats trobats",searchNoResults:"No s'han trobat resultats",filtersTitle:"ENTITATS",toggleShowAll:"Tots els edificis",toggleHideAll:"Ocultar tots",buildingLabel:"Edifici",buildingTitle:"Edifici",building:"Edifici",noEntities:"Sense entitats registrades",howToGet:"Com arribar",website:"Lloc web",otherEntities:"Altres entitats en edifici",noResults:"No s'han trobat resultats",buildings:"Edificis",close:"Tancar",openMapsTitle:"Veure plantes i espais",viewOnBaiduMaps:"Veure en Baidu Maps",valenbisiLoading:"Carregant disponibilitat...",valenbisiError:"No s'ha pogut obtenir disponibilitat",valenbisiFreeBikes:"Bicis disponibles",valenbisiEmptySlots:"Espais lliures",valenbisiClosed:"Estaci\xF3 tancada",valenbisiOpen:"Estaci\xF3 oberta"},en:{searchPlaceholder:"SEARCH BUILDING OR ENTITY...",searchResultsLabel:"Search results",searchResultsCount:"{count} results found",searchNoResults:"No results found",filtersTitle:"ENTITIES",toggleShowAll:"All buildings",toggleHideAll:"Hide all",buildingLabel:"Building",buildingTitle:"Building",building:"Building",noEntities:"No registered entities",howToGet:"How to get there",website:"Website",otherEntities:"Other entities in building",noResults:"No results found",buildings:"Buildings",close:"Close",openMapsTitle:"View floors and spaces",viewOnBaiduMaps:"View on Baidu Maps",valenbisiLoading:"Loading availability...",valenbisiError:"Could not get availability",valenbisiFreeBikes:"Bikes available",valenbisiEmptySlots:"Empty slots",valenbisiClosed:"Station closed",valenbisiOpen:"Station open"}};var x=class{constructor(){this.map=null,this.markers=[],this.AdvancedMarkerElement=null,this.PinElement=null}async init(e){let{AdvancedMarkerElement:t,PinElement:i}=await google.maps.importLibrary("marker");return this.AdvancedMarkerElement=t,this.PinElement=i,this.map=new google.maps.Map(document.getElementById(e),{center:l.MAP_CENTER,zoom:l.MAP_ZOOM,mapId:"a52506311d702df46371be76",heading:0,tilt:0,mapTypeControl:!0,mapTypeControlOptions:{style:google.maps.MapTypeControlStyle.DROPDOWN_MENU,mapTypeIds:["roadmap","satellite","hybrid"]},streetViewControl:!0,fullscreenControl:!0,zoomControl:!0,rotateControl:!0,rotateControlOptions:{position:google.maps.ControlPosition.RIGHT_BOTTOM},gestureHandling:"greedy"}),console.log("Mapa inicializado con AdvancedMarkerElement"),this.map}centerOnCampus(e){let t=l.CAMPUS[e];t?(this.map.setCenter({lat:t.lat,lng:t.lng}),this.map.setZoom(16),console.log(`Centrado en campus: ${t.name}`)):console.error(`Campus no encontrado: ${e}`)}centerOnLocation(e,t,i=18){this.map.setCenter({lat:e,lng:t}),this.map.setZoom(i)}fitBounds(e){this.map.fitBounds(e)}addMarker(e){this.markers.push(e)}clearMarkers(){this.markers.forEach(e=>e.map=null),this.markers=[]}getMarkers(){return this.markers}};var P=class{constructor(e,t,i){this.map=e,this.PinElement=t,this.AdvancedMarkerElement=i}createBuildingMarker(e,t){let i=this.getPrincipalSupertipo(t),s=l.SUPERTIPOS[i],o=document.createElement("div");o.className="custom-marker",o.style.cssText=`
width: 40px;
height: 40px;
background-color: ${s.color};
border: 3px solid #FFFFFF;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
color: #FFFFFF;
font-weight: bold;
font-size: 14px;
cursor: pointer;
box-shadow: 0 2px 6px rgba(0,0,0,0.3);
transition: transform 0.2s ease, box-shadow 0.2s ease;
`,o.textContent=e.edificio;let n=new this.AdvancedMarkerElement({map:this.map,position:{lat:e.lat,lng:e.lon},content:o,title:`Edificio ${e.edificio}`,gmpClickable:!0});return n.edificioData=e,n.entidadesData=t,n.supertipo=i,n.customConfig={color:s.color,label:e.edificio},n}getPrincipalSupertipo(e){if(!e||e.length===0)return"OTR";for(let t of l.PRIORIDAD_SUPERTIPOS)if(e.some(i=>i.supertipo===t))return t;return"OTR"}showMarker(e){e.map=this.map}hideMarker(e){e.map=null}highlightMarker(e){e.content&&e.content.style&&(e.content.style.width="50px",e.content.style.height="50px",e.content.style.fontSize="16px",e.content.style.transform="scale(1)",e.content.style.boxShadow="0 4px 12px rgba(0,0,0,0.5)",e.content.style.zIndex="1000")}unhighlightMarker(e){e.content&&e.content.style&&(e.content.style.width="40px",e.content.style.height="40px",e.content.style.fontSize="14px",e.content.style.transform="scale(1)",e.content.style.boxShadow="0 2px 6px rgba(0,0,0,0.3)",e.content.style.zIndex="auto")}};var w={globe:'',mail:'',phone:'',mapPin:'',route:'',link:'',xCircle:'',search:'',hamburgerMenuUPV:'',hamburgerMenuCloseUPV:''};var N=class{constructor(e,t=()=>!1){this.map=e,this.isMobile=t,this.currentInfoWindow=null,this.currentMarker=null,this.closeTimeout=null,this.setupMapListeners()}setupMapListeners(){this.map.addListener("center_changed",()=>{this.centerChangeTimeout&&clearTimeout(this.centerChangeTimeout),this.centerChangeTimeout=setTimeout(()=>{if(this.currentInfoWindow&&this.currentMarker){let t=this.currentMarker.position,i=this.map.getCenter();Math.sqrt(Math.pow(t.lat-i.lat(),2)+Math.pow(t.lng-i.lng(),2))>.01&&this.close()}},500)});let e=this.map.getDiv();e&&(e.addEventListener("mouseleave",()=>{this.closeTimeout=setTimeout(()=>{this.close()},500)}),e.addEventListener("mouseenter",()=>{this.closeTimeout&&(clearTimeout(this.closeTimeout),this.closeTimeout=null)}))}attachToMarker(e){e.content&&(this.isMobile()||(e.content.addEventListener("mouseenter",()=>{this.closeTimeout&&(clearTimeout(this.closeTimeout),this.closeTimeout=null),this.showInfoWindow(e)}),e.content.addEventListener("mouseleave",()=>{this.closeTimeout=setTimeout(()=>{this.close()},300)})),e.content.addEventListener("click",()=>{let t=e.entidadesData||[];this.isMobile()||t.length===0?this.openMobileDrawer(e):this.showInfoWindow(e)}));try{e.addListener("click",()=>{let t=e.entidadesData||[];this.isMobile()||t.length===0?this.openMobileDrawer(e):this.showInfoWindow(e)})}catch{}}openMobileDrawer(e){let t=e.edificioData,i=e.entidadesData||[],s=i.length>0?i[0]:null;window.dispatchEvent(new CustomEvent("openMobileDrawer",{detail:{edificio:t,entidad:s,edificioOrigen:t.edificio}}))}showInfoWindow(e){this.closeTimeout&&(clearTimeout(this.closeTimeout),this.closeTimeout=null),this.currentInfoWindow&&this.currentInfoWindow.close(),window.app&&window.app.closePoiInfoWindow&&window.app.closePoiInfoWindow();let t=e.edificioData,i=e.entidadesData,s=this.createContent(t,i);this.currentInfoWindow=new google.maps.InfoWindow({content:s,disableAutoPan:!1}),this.currentMarker=e,this.currentInfoWindow.open(this.map,e),setTimeout(()=>{this.attachEntityEvents(i),this.attachCloseButtonEvent(),this.attachInfoWindowHoverEvents()},100)}createContent(e,t){let i=`
`;return t&&t.length>0?t.forEach(s=>{let o=l.SUPERTIPOS[s.supertipo],n=o?o.nameShort:"OTR",c=l.getText(s,"nombre"),a=s.acronimo||s.siglas;i+=`
-
${c}
(${a})
${n}
`}):i+=`- ${l.TRANSLATIONS.noEntities}
`,i+=`
`,i}attachEntityEvents(e){document.querySelectorAll(".entity-item[data-siglas]").forEach(t=>{t.addEventListener("click",i=>{let s=i.currentTarget.dataset.siglas,o=e.find(n=>n.siglas===s);if(o){let n=this.currentMarker?.edificioData?.edificio||null;window.dispatchEvent(new CustomEvent("showEntityPanel",{detail:{entidad:o,edificioOrigen:n}}))}})})}attachCloseButtonEvent(){let e=document.querySelector(".gm-style-iw-c");if(e){let t=e.querySelector(".infowindow-close");t&&t.addEventListener("click",i=>{i.stopPropagation(),this.close()})}}attachInfoWindowHoverEvents(){let e=document.querySelector(".gm-style-iw-c");e&&(e.addEventListener("mouseenter",()=>{this.closeTimeout&&(clearTimeout(this.closeTimeout),this.closeTimeout=null)}),e.addEventListener("mouseleave",()=>{this.closeTimeout=setTimeout(()=>{this.close()},300)}))}close(){this.closeTimeout&&(clearTimeout(this.closeTimeout),this.closeTimeout=null),this.currentInfoWindow&&(this.currentInfoWindow.close(),this.currentInfoWindow=null),this.currentMarker=null}closeAll(){this.close(),document.querySelectorAll(".gm-style-iw").forEach(i=>{let s=i.parentElement;s&&(s.style.display="none",setTimeout(()=>{s&&s.parentElement&&s.parentElement.removeChild(s)},100))}),document.querySelectorAll(".gm-style-iw-c, .gm-style-iw-d").forEach(i=>{let s=i.parentElement;s&&(s.style.display="none")})}};async function _(p){try{let e=await fetch(p);if(!e.ok)throw new Error(`HTTP error! status: ${e.status}`);return await e.json()}catch(e){throw console.error("Error loading JSON:",e),e}}function K(p,e){let t;return function(...s){let o=()=>{clearTimeout(t),p(...s)};clearTimeout(t),t=setTimeout(o,e)}}function A(p){return p.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"")}function Y(p){let e=p.replace(/\D/g,"");if(e.length===9)return`+34 ${e.substring(0,2)} ${e.substring(2,5)} ${e.substring(5,7)} ${e.substring(7,9)}`;if(e.length===11&&e.startsWith("34")){let t=e.substring(2);return`+34 ${t.substring(0,2)} ${t.substring(2,5)} ${t.substring(5,7)} ${t.substring(7,9)}`}if(e.length===11||e.length===12){let t=e.substring(e.length-9);return`+34 ${t.substring(0,2)}-${t.substring(2,5)}-${t.substring(5,7)}-${t.substring(7,9)}`}return p}function Q(){let p=new URLSearchParams(window.location.search),e={};for(let[t,i]of p)e[t.toLowerCase()]=i;return e}function ee(p){let e={};if(p.campus){let t=p.campus.toUpperCase();/^[VAGH]$/.test(t)&&(e.campus=t)}if(p.entidad){let t=p.entidad.toUpperCase();/^[A-Z0-9]{1,12}$/.test(t)&&(e.entidad=t)}if(p.edificio){let t=p.edificio.toUpperCase();/^[A-Z0-9]{2,3}$/.test(t)&&(t.length===2&&(t="V"+t),e.edificio=t)}return e}var R=class{constructor(e){this.app=e,this.searchInput=document.getElementById("search-input"),this.searchResults=document.getElementById("search-results"),this.selectedIndex=-1,this.setupEvents(),this.setupKeyboardNavigation()}setupEvents(){let e=K(t=>this.performSearch(t),300);this.searchInput.addEventListener("input",t=>{let i=t.target.value.trim();i.length>=l.SEARCH.MIN_CHARS?e(i):this.hideResults()}),document.addEventListener("click",t=>{!this.searchInput.contains(t.target)&&!this.searchResults.contains(t.target)&&this.hideResults()})}setupKeyboardNavigation(){this.searchInput.addEventListener("keydown",e=>{let t=this.searchResults.querySelectorAll(".search-result-item");if(t.length!==0)switch(e.key){case"ArrowDown":e.preventDefault(),this.selectedIndex=Math.min(this.selectedIndex+1,t.length-1),this.highlightResult(t);break;case"ArrowUp":e.preventDefault(),this.selectedIndex=Math.max(this.selectedIndex-1,-1),this.selectedIndex===-1?this.clearHighlight(t):this.highlightResult(t);break;case"Enter":e.preventDefault(),this.selectedIndex>=0&&t[this.selectedIndex]&&t[this.selectedIndex].click();break;case"Escape":e.preventDefault(),this.hideResults(),this.selectedIndex=-1;break}})}highlightResult(e){if(e.forEach(t=>{t.classList.remove("keyboard-selected"),t.setAttribute("aria-selected","false")}),this.selectedIndex>=0){let t=e[this.selectedIndex];t.classList.add("keyboard-selected"),t.setAttribute("aria-selected","true"),t.scrollIntoView({block:"nearest",behavior:"smooth"}),this.searchInput.setAttribute("aria-activedescendant",t.id)}else this.searchInput.removeAttribute("aria-activedescendant")}clearHighlight(e){e.forEach(t=>{t.classList.remove("keyboard-selected"),t.setAttribute("aria-selected","false")})}performSearch(e){let t=A(e),i=[];this.app.data.Entidades.forEach(o=>{let n=A(o.nombre||""),c=A(o.acronimo||""),a=A(o.siglas||"");(n.includes(t)||c.includes(t)||a.includes(t))&&i.push({type:"entidad",data:o,score:this.calculateScore(t,n,c,a)})}),this.app.data.Edificios.forEach(o=>{A(o.edificio||"").includes(t)&&i.push({type:"edificio",data:o,score:100})}),i.sort((o,n)=>n.score-o.score);let s=i.slice(0,l.SEARCH.MAX_RESULTS);this.displayResults(s,e)}calculateScore(e,t,i,s){let o=0;return i===e?o+=100:i.startsWith(e)?o+=80:i.includes(e)&&(o+=40),s===e?o+=90:s.startsWith(e)?o+=70:s.includes(e)&&(o+=30),t.startsWith(e)?o+=60:t.includes(e)&&(o+=20),o}displayResults(e,t){if(this.selectedIndex=-1,e.length===0){this.searchResults.innerHTML=`${l.TRANSLATIONS.searchNoResults}
`,this.searchResults.setAttribute("role","status"),this.searchResults.removeAttribute("aria-label"),this.showResults(),this.announceResults(0);return}let i="";e.forEach((s,o)=>{if(s.type==="entidad"){let n=s.data,c=l.SUPERTIPOS[n.supertipo]||l.SUPERTIPOS.OTR,a=n.edificios?n.edificios.join(", "):"N/A",r=n.campus,d=l.CAMPUS[r],h=d?d.name:r;i+=`
${l.getText(n,"nombre")}
${n.acronimo||n.siglas}
${c.nameShort}
Campus: ${h}, Edificios: ${a}
`}else if(s.type==="edificio"){let n=s.data,c=l.CAMPUS[n.cam],a=c?c.name:n.cam;i+=`
Edificio ${n.edificio}
Campus: ${a}
`}}),this.searchResults.innerHTML=i,this.searchResults.setAttribute("role","listbox"),this.showResults(),this.announceResults(e.length),this.attachResultEvents()}attachResultEvents(){this.searchResults.querySelectorAll(".search-result-item").forEach(e=>{e.addEventListener("click",()=>{let t=e.dataset.type;if(t==="entidad"){let i=e.dataset.siglas,s=this.app.data.Entidades.find(o=>o.siglas===i);s&&this.selectEntity(s)}else if(t==="edificio"){let i=e.dataset.edificio,s=e.dataset.campus,o=this.app.data.Edificios.find(n=>n.edificio===i&&n.cam===s);o&&this.selectBuilding(o)}this.hideResults(),this.searchInput.value=""})})}selectEntity(e){console.log("Entidad seleccionada:",e.siglas,"Campus:",e.campus);let t=e.campus;if(e.edificios&&e.edificios.length>0){let i=[];e.edificios.forEach(s=>{let o=this.app.allMarkers.find(n=>n.edificioData.edificio===s&&n.edificioData.cam===t);o?i.push(o):(console.warn(`Marcador no encontrado: Edificio ${s}, Campus ${t}`),console.log("Marcadores disponibles:",this.app.allMarkers.length),console.log("Primeros 3 marcadores:",this.app.allMarkers.slice(0,3).map(n=>({edificio:n.edificioData?.edificio,campus:n.edificioData?.cam}))))}),i.length>0?(this.app.visibleSupertipos.clear(),document.querySelectorAll("#filters-panel .filter-item").forEach(s=>{let o=s.querySelector('input[type="checkbox"]');o.checked=!1,s.setAttribute("aria-checked","false")}),this.app.allMarkers.forEach(s=>{this.app.markerManager.hideMarker(s)}),i.forEach(s=>{this.app.markerManager.showMarker(s)}),console.log("Cambiando a campus:",t),t&&(document.querySelectorAll(".campus-btn").forEach(s=>{s.dataset.campus===t?s.classList.add("active"):s.classList.remove("active")}),l.CAMPUS[t]&&(this.app.mapManager.centerOnCampus(t),console.log("Centrado en campus:",t,l.CAMPUS[t]))),window.dispatchEvent(new CustomEvent("showEntityPanel",{detail:e})),setTimeout(()=>{let s=new google.maps.LatLngBounds;i.forEach(o=>{s.extend(o.position)}),this.app.mapManager.map.fitBounds(s),i.length===1&&setTimeout(()=>{this.app.mapManager.map.setZoom(18)},300)},800)):console.error("No se encontraron marcadores para:",e.siglas,"Edificios:",e.edificios,"Campus:",t)}}selectBuilding(e){console.log("Edificio seleccionado:",e.edificio,"Campus:",e.cam),this.app.visibleSupertipos.clear(),document.querySelectorAll("#filters-panel .filter-item").forEach(i=>{let s=i.querySelector('input[type="checkbox"]');s.checked=!1,i.setAttribute("aria-checked","false")}),document.querySelectorAll(".campus-btn").forEach(i=>{i.classList.remove("active"),i.dataset.campus===e.cam&&i.classList.add("active")}),this.app.mapManager.centerOnCampus(e.cam);let t=this.app.allMarkers.find(i=>i.edificioData.edificio===e.edificio&&i.edificioData.cam===e.cam);t?setTimeout(()=>{this.app.mapManager.centerOnLocation(e.lat,e.lon,18),this.app.allMarkers.forEach(i=>{i===t?this.app.markerManager.showMarker(i):this.app.markerManager.hideMarker(i)}),setTimeout(()=>{this.app.infoWindowManager.showInfoWindow(t)},500)},800):console.warn("Marcador no encontrado para edificio:",e.edificio,"Campus:",e.cam)}showResults(){this.searchResults.classList.add("show"),this.searchInput.setAttribute("aria-expanded","true")}hideResults(){this.searchResults.classList.remove("show"),this.searchInput.setAttribute("aria-expanded","false"),this.searchInput.removeAttribute("aria-activedescendant")}announceResults(e){let t=document.getElementById("search-live");if(t){let i=e>0?l.TRANSLATIONS.searchResultsCount.replace("{count}",e):l.TRANSLATIONS.searchNoResults;t.textContent=i}}};var B=class{constructor(){this.viewport=this.detectViewport(),this.listeners=[],this.setupListeners()}detectViewport(){return window.innerWidth<768?(document.documentElement.classList.add("mobile-viewport"),document.documentElement.classList.remove("desktop-viewport"),"mobile"):(document.documentElement.classList.add("desktop-viewport"),document.documentElement.classList.remove("mobile-viewport"),"desktop")}isMobile(){return this.viewport==="mobile"}isDesktop(){return this.viewport==="desktop"}isTouchDevice(){return"ontouchstart"in window||navigator.maxTouchPoints>0||navigator.msMaxTouchPoints>0}setupListeners(){let e;window.addEventListener("resize",()=>{clearTimeout(e),e=setTimeout(()=>{let t=this.detectViewport();if(t!==this.viewport){let i=this.viewport;this.viewport=t,this.notifyListeners(t,i)}},250)}),window.addEventListener("orientationchange",()=>{setTimeout(()=>{let t=this.detectViewport();if(t!==this.viewport){let i=this.viewport;this.viewport=t,this.notifyListeners(t,i)}},100)})}onChange(e){this.listeners.push(e)}notifyListeners(e,t){this.listeners.forEach(i=>{try{i(e,t)}catch(s){console.error("Error en listener de viewport:",s)}})}getViewportSize(){return{width:window.innerWidth,height:window.innerHeight}}getDeviceInfo(){return{viewport:this.viewport,isTouch:this.isTouchDevice(),dimensions:this.getViewportSize(),pixelRatio:window.devicePixelRatio||1,orientation:window.screen?.orientation?.type||"unknown",userAgent:navigator.userAgent}}};var D=class{constructor(e){if(this.app=e,this.drawer=document.getElementById("mobile-drawer"),this.overlay=document.getElementById("drawer-overlay"),this.isOpen=!1,!this.drawer||!this.overlay){console.warn("DrawerManager: Drawer o overlay no encontrados");return}this.setupEvents()}open(){this.isOpen||(this.syncFiltersFromDesktop(),this.drawer.classList.add("active"),this.overlay.classList.add("active"),document.body.style.overflow="hidden",this.isOpen=!0)}close(){this.isOpen&&(this.drawer.classList.remove("active"),this.overlay.classList.remove("active"),document.body.style.overflow="",this.isOpen=!1)}toggle(){this.isOpen?this.close():this.open()}setupEvents(){let e=document.getElementById("mobile-hamburger");e&&e.addEventListener("click",i=>{i.preventDefault(),this.open()});let t=document.getElementById("drawer-close");t&&t.addEventListener("click",i=>{i.preventDefault(),this.close()}),this.overlay&&this.overlay.addEventListener("click",()=>{this.close()}),document.addEventListener("keydown",i=>{i.key==="Escape"&&this.isOpen&&this.close()}),this.setupCampusButtons(),this.setupFilters(),this.setupToggleAllBuildings()}setupCampusButtons(){let e=this.drawer.querySelectorAll(".campus-btn-mobile");e.forEach(t=>{t.addEventListener("click",i=>{i.preventDefault();let s=t.dataset.campus;e.forEach(n=>n.classList.remove("active")),t.classList.add("active");let o=document.querySelector(`.campus-btn[data-campus="${s}"]`);o&&o.click(),setTimeout(()=>{this.close()},300)})})}setupFilters(){this.drawer.querySelectorAll(".filter-item-mobile").forEach(t=>{let i=t.querySelector('input[type="checkbox"]');t.addEventListener("click",s=>{s.target!==i&&(s.preventDefault(),i.checked=!i.checked,i.dispatchEvent(new Event("change")))}),i.addEventListener("change",()=>{t.setAttribute("aria-checked",i.checked)})})}setupToggleAllBuildings(){let e=document.getElementById("toggle-all-buildings-mobile");e&&(this.allEntitiesSelected=!1,e.addEventListener("click",t=>{t.preventDefault(),this.allEntitiesSelected=!this.allEntitiesSelected,this.drawer.querySelectorAll('.drawer-filters:not(.drawer-filters-pois) .filter-item-mobile input[type="checkbox"]').forEach(o=>{o.checked=this.allEntitiesSelected;let n=o.closest("label");n&&n.setAttribute("aria-checked",this.allEntitiesSelected)});let s=e.querySelector(".toggle-text");if(s&&this.app&&this.app.constructor.name==="App"){let o=window.CONFIG?.TRANSLATIONS;o&&(s.textContent=this.allEntitiesSelected?o.toggleHideAll:o.toggleShowAll)}}))}syncFiltersFromDesktop(){let e=document.querySelectorAll('#filters-panel .filters:not(.filters-pois) input[type="checkbox"]'),t=this.drawer.querySelectorAll('.drawer-filters:not(.drawer-filters-pois) .filter-item-mobile input[type="checkbox"]');e.forEach(o=>{let n=o.value,c=Array.from(t).find(a=>a.value===n);if(c){c.checked=o.checked;let a=c.closest("label");a&&a.setAttribute("aria-checked",o.checked)}});let i=document.querySelectorAll('#filters-panel .filters-pois input[type="checkbox"]'),s=this.drawer.querySelectorAll('.drawer-filters-pois .filter-item-mobile input[type="checkbox"]');i.forEach(o=>{let n=o.dataset.poiType,c=Array.from(s).find(a=>a.dataset.poiType===n);if(c){c.checked=o.checked;let a=c.closest("label");a&&a.setAttribute("aria-checked",o.checked)}}),this.syncCampusFromDesktop(),this.syncToggleBuildingsFromDesktop()}syncCampusFromDesktop(){let e=document.querySelector(".campus-btn.active");if(!e)return;let t=e.dataset.campus;this.drawer.querySelectorAll(".campus-btn-mobile").forEach(s=>{s.dataset.campus===t?s.classList.add("active"):s.classList.remove("active")})}syncToggleBuildingsFromDesktop(){let e=document.getElementById("toggle-all-buildings-mobile");if(!e)return;let t=this.drawer.querySelectorAll('.drawer-filters:not(.drawer-filters-pois) .filter-item-mobile input[type="checkbox"]'),i=Array.from(t).every(o=>o.checked);this.allEntitiesSelected=i;let s=e.querySelector(".toggle-text");if(s){let o=window.CONFIG?.TRANSLATIONS;o&&(s.textContent=i?o.toggleHideAll:o.toggleShowAll)}}updateCounts(e){console.log("DrawerManager: updateCounts",e)}};var ne="https://api.citybik.es/v2/networks/valenbisi";var V=class{constructor(){this.cache=null,this.cacheTimestamp=null,this.loading=!1,this.loadPromise=null}haversineDistance(e,t,i,s){let n=h=>h*Math.PI/180,c=n(i-e),a=n(s-t),r=Math.sin(c/2)*Math.sin(c/2)+Math.cos(n(e))*Math.cos(n(i))*Math.sin(a/2)*Math.sin(a/2);return 6371e3*(2*Math.atan2(Math.sqrt(r),Math.sqrt(1-r)))}async fetchData(){if(this.cache&&this.cacheTimestamp&&Date.now()-this.cacheTimestamp<12e4)return console.log("ValenbisiService: usando datos en cach\xE9"),this.cache;if(this.loading&&this.loadPromise)return console.log("ValenbisiService: esperando petici\xF3n en curso"),this.loadPromise;this.loading=!0,this.loadPromise=this._doFetch();try{return await this.loadPromise}finally{this.loading=!1,this.loadPromise=null}}async _doFetch(){try{console.log("ValenbisiService: obteniendo datos de la API...");let e=await fetch(ne);if(!e.ok)throw new Error(`HTTP ${e.status}`);let t=await e.json();return this.cache=t.network.stations,this.cacheTimestamp=Date.now(),console.log(`ValenbisiService: ${this.cache.length} estaciones cargadas`),this.cache}catch(e){throw console.error("ValenbisiService: error al obtener datos",e),e}}async findNearestStation(e,t,i=100){try{let s=await this.fetchData(),o=null,n=1/0;for(let c of s){let a=this.haversineDistance(e,t,c.latitude,c.longitude);a{let t=F[T];return e==="nombre"?p[t.nombre]||p.nombre||p.siglas:e==="campus_nombre"?p[t.campusLargo]||p.cam:e==="tipo_nombre"?p[t.tipo]||p.supertipo:p[e]||""};var G=class{constructor(){this.mapManager=null,this.markerManager=null,this.infoWindowManager=null,this.searchManager=null,this.responsiveManager=null,this.drawerManager=null,this.data=null,this.allMarkers=[],this.visibleSupertipos=new Set(["GOB","CEN"]),this.showAllBuildings=!1,this.currentTimezone="Europe/Madrid",this.poisData=null,this.poiMarkers=[],this.visiblePoiTypes=new Set,this.TIPOS_POI_ACTIVOS=[0,1,2,3,4],this.currentPoiInfoWindow=null,this.poiCloseTimeout=null}async init(){console.log("Inicializando aplicaci\xF3n...");try{if(this.data=await _(l.PATHS.DATA_JSON),console.log(`Datos cargados: ${this.data.Edificios.length} edificios, ${this.data.Entidades.length} entidades`),this.data.Campus){let e=F[T];this.data.Campus.forEach(t=>{l.CAMPUS[t.cam]={name:t[e.campus]||t[e.campusLargo],nameLong:t[e.campusLargo],lat:parseFloat(t.lat),lng:parseFloat(t.lon)}}),console.log("Campus data cargados:",Object.keys(l.CAMPUS))}if(this.data.Tipos){let e=F[T];this.data.Tipos.forEach(t=>{l.SUPERTIPOS[t.supertipo]&&(l.SUPERTIPOS[t.supertipo].name=t[e.tipo])})}try{this.poisData=await _(l.PATHS.POIS_JSON),this.poisData.Pois=this.poisData.Pois.filter(e=>this.TIPOS_POI_ACTIVOS.includes(e.tipo)),console.log(`POIs cargados: ${this.poisData.Pois.length} puntos de inter\xE9s`)}catch(e){console.warn("No se pudieron cargar los POIs:",e),this.poisData={Pois:[],TiposPoi:[]}}this.mapManager=new x,await this.mapManager.init("map"),this.markerManager=new P(this.mapManager.map,this.mapManager.PinElement,this.mapManager.AdvancedMarkerElement),this.responsiveManager=new B,this.infoWindowManager=new N(this.mapManager.map,()=>this.responsiveManager.isMobile()),this.searchManager=new R(this),this.drawerManager=new D(this),console.log("DrawerManager inicializado"),this.createAllMarkers(),this.createPoiMarkers(),this.setupEvents(),this.initClock(),this.processURLParams(),console.log("Aplicaci\xF3n inicializada correctamente")}catch(e){console.error("Error al inicializar aplicaci\xF3n:",e),console.error("Stack trace:",e.stack),console.error("Error name:",e.name),console.error("Error message:",e.message)}}initClock(){let e=()=>{let t=new Date,i={timeZone:this.currentTimezone,hour:"2-digit",minute:"2-digit",hour12:!1},s=t.toLocaleTimeString("es-ES",i),o=document.querySelector("#widget-clock .clock-time");o&&(o.textContent=s)};e(),this.clockInterval=setInterval(e,1e3)}updateTimezone(e){this.currentTimezone=e==="H"?"Asia/Shanghai":"Europe/Madrid",this.clockInterval&&clearInterval(this.clockInterval),this.initClock()}createAllMarkers(){let{Edificios:e,Entidades:t}=this.data;e.filter(s=>s.lat!=null&&s.lon!=null).forEach(s=>{let o=t.filter(c=>s.siglas&&s.siglas.includes(c.siglas)),n=this.markerManager.createBuildingMarker(s,o);this.infoWindowManager.attachToMarker(n),this.allMarkers.push(n),this.mapManager.addMarker(n),this.updateMarkerVisibility(n)}),console.log(`${this.allMarkers.length} marcadores creados`)}updateMarkerVisibility(e){let i=(e.entidadesData||[]).some(s=>this.visibleSupertipos.has(s.supertipo));this.showAllBuildings||i?this.markerManager.showMarker(e):(this.infoWindowManager.currentMarker===e&&this.infoWindowManager.close(),this.markerManager.hideMarker(e))}updateAllMarkers(){this.allMarkers.forEach(e=>{this.updateMarkerVisibility(e)})}createPoiMarkers(){if(!this.poisData||!this.poisData.Pois)return;let e=F[T];this.poisData.Pois.forEach(t=>{let i=t[e.nombre]||t.nombre,s=document.createElement("div");if(s.className=`poi-marker marker-POI-${t.tipo}`,t.icono){let h=`${l.PATHS.POIS_IMAGES}${t.icono}`;s.innerHTML=`
`}else s.innerHTML='\u25CF';let o=new this.mapManager.AdvancedMarkerElement({position:{lat:t.lat,lng:t.lon},map:null,content:s,title:i});o.poiData=t,o.poiType=t.tipo;let n=t.icono==="valenbici.png"||t.nombre.toLowerCase().includes("valenbisi");o.isValenbisi=n;let c=`https://www.google.com/maps/dir/?api=1&destination=${t.lat},${t.lon}`,a=this.createPoiInfoContent(t,i,c,n),r=new google.maps.InfoWindow({content:a});o.infoWindow=r;let d=async()=>{if(this.poiCloseTimeout&&(clearTimeout(this.poiCloseTimeout),this.poiCloseTimeout=null),this.infoWindowManager.closeAll(),this.currentPoiInfoWindow&&this.currentPoiInfoWindow!==r&&this.currentPoiInfoWindow.close(),n&&r.setContent(this.createPoiInfoContent(t,i,c,!0,"loading")),r.open({anchor:o,map:this.mapManager.map}),this.currentPoiInfoWindow=r,n)try{let h=await q.findNearestStation(t.lat,t.lon,100),f=q.formatStationData(h);r.setContent(this.createPoiInfoContent(t,i,c,!0,"success",f))}catch{r.setContent(this.createPoiInfoContent(t,i,c,!0,"error"))}setTimeout(()=>{this.attachPoiInfoWindowHoverEvents()},100)};s&&(s.addEventListener("mouseenter",()=>{this.poiCloseTimeout&&(clearTimeout(this.poiCloseTimeout),this.poiCloseTimeout=null),d()}),s.addEventListener("mouseleave",()=>{this.poiCloseTimeout=setTimeout(()=>{this.closePoiInfoWindow()},300)}),s.addEventListener("click",()=>{d()})),o.addListener("click",()=>{d()}),this.poiMarkers.push(o)}),console.log(`${this.poiMarkers.length} marcadores de POI creados`)}createPoiInfoContent(e,t,i,s=!1,o=null,n=null){let c=`
display: inline-flex;
align-items: center;
gap: 6px;
padding: 6px 12px;
background-color: #c32c25;
color: white;
text-decoration: none;
border-radius: 4px;
font-size: 13px;
font-weight: 500;
transition: background-color 0.2s;
`,a="";if(s){if(o==="loading")a=`
${l.TRANSLATIONS.valenbisiLoading}
`;else if(o==="error")a=`
${l.TRANSLATIONS.valenbisiError}
`;else if(o==="success"&&n){let r=n.isOpen?"#28a745":"#dc3545",d=n.isOpen?l.TRANSLATIONS.valenbisiOpen:l.TRANSLATIONS.valenbisiClosed;a=`
${n.freeBikes} ${l.TRANSLATIONS.valenbisiFreeBikes}
${n.emptySlots} ${l.TRANSLATIONS.valenbisiEmptySlots}
${d}
`}}return`
`}updatePoiMarkerVisibility(e){let t=e.poiType;this.visiblePoiTypes.has(t)?e.map=this.mapManager.map:e.map=null}updateAllPoiMarkers(){this.currentPoiInfoWindow&&(this.currentPoiInfoWindow.close(),this.currentPoiInfoWindow=null),this.poiMarkers.forEach(e=>{this.updatePoiMarkerVisibility(e)})}closePoiInfoWindow(){this.poiCloseTimeout&&(clearTimeout(this.poiCloseTimeout),this.poiCloseTimeout=null),this.currentPoiInfoWindow&&(this.currentPoiInfoWindow.close(),this.currentPoiInfoWindow=null)}attachPoiInfoWindowHoverEvents(){let e=document.querySelector(".gm-style-iw-c");e&&(e.addEventListener("mouseenter",()=>{this.poiCloseTimeout&&(clearTimeout(this.poiCloseTimeout),this.poiCloseTimeout=null)}),e.addEventListener("mouseleave",()=>{this.poiCloseTimeout=setTimeout(()=>{this.closePoiInfoWindow()},300)}))}setupEvents(){let e=document.getElementById("search-label");e&&(e.textContent=l.TRANSLATIONS.searchPlaceholder);let t=document.getElementById("search-results");t&&t.setAttribute("aria-label",l.TRANSLATIONS.searchResultsLabel);let i=document.querySelector("#filters-panel h3.filters-title");if(i){let a=i.firstChild;a&&a.nodeType===Node.TEXT_NODE&&(a.textContent=l.TRANSLATIONS.filtersTitle+" ")}document.querySelectorAll(".info-tooltip-trigger").forEach(a=>{a.addEventListener("click",r=>{r.stopPropagation(),a.classList.toggle("active")})}),document.addEventListener("click",()=>{document.querySelectorAll(".info-tooltip-trigger.active").forEach(a=>{a.classList.remove("active")})}),document.querySelectorAll(".campus-btn").forEach(a=>{let r=a.dataset.campus,d=l.CAMPUS[r];d&&(a.textContent=d.name)}),document.querySelectorAll("#filters-panel .filter-item").forEach(a=>{let r=a.querySelector('input[type="checkbox"]'),d=a.querySelector(".filter-label"),h=r.value;d&&l.SUPERTIPOS[h]&&(d.textContent=l.SUPERTIPOS[h].name)}),document.querySelectorAll("#filters-panel .filter-item, .drawer-filters:not(.drawer-filters-pois) .filter-item-mobile").forEach(a=>{let r=a.querySelector('input[type="checkbox"]');r.addEventListener("change",d=>{let h=d.target.value,f=d.target.checked;a.setAttribute("aria-checked",f),f?this.visibleSupertipos.add(h):this.visibleSupertipos.delete(h),document.querySelectorAll(`input[type="checkbox"][value="${h}"]`).forEach(u=>{!u.dataset.poiType&&u!==d.target&&(u.checked=f,(u.closest(".filter-item")||u.closest(".filter-item-mobile"))?.setAttribute("aria-checked",f))}),this.infoWindowManager.closeAll(),this.updateAllMarkers(),console.log("Filtros actualizados:",Array.from(this.visibleSupertipos))}),a.addEventListener("keydown",d=>{(d.key===" "||d.key==="Enter")&&(d.preventDefault(),r.checked=!r.checked,r.dispatchEvent(new Event("change")))})}),document.querySelectorAll(".filters-pois .filter-item, .drawer-filters-pois .filter-item-mobile").forEach(a=>{let r=a.querySelector('input[type="checkbox"]'),d=parseInt(r.dataset.poiType,10);r.addEventListener("change",h=>{let f=h.target.checked;a.setAttribute("aria-checked",f),f?this.visiblePoiTypes.add(d):this.visiblePoiTypes.delete(d),document.querySelectorAll(`input[data-poi-type="${d}"]`).forEach(u=>{u!==h.target&&(u.checked=f,(u.closest(".filter-item")||u.closest(".filter-item-mobile"))?.setAttribute("aria-checked",f))}),this.updateAllPoiMarkers(),console.log("Filtros POI actualizados:",Array.from(this.visiblePoiTypes))}),a.addEventListener("keydown",h=>{(h.key===" "||h.key==="Enter")&&(h.preventDefault(),r.checked=!r.checked,r.dispatchEvent(new Event("change")))})});let o=document.getElementById("toggle-all-buildings"),n=document.getElementById("toggle-all-buildings-mobile"),c=()=>{this.showAllBuildings=!this.showAllBuildings,[o,n].forEach(r=>{if(r){let d=r.querySelector(".toggle-text");d&&(d.textContent=this.showAllBuildings?l.TRANSLATIONS.toggleHideAll:l.TRANSLATIONS.toggleShowAll),this.showAllBuildings?r.classList.add("active"):r.classList.remove("active")}}),document.querySelectorAll('#filters-panel .filter-item input[type="checkbox"], .drawer-filters:not(.drawer-filters-pois) .filter-item-mobile input[type="checkbox"]').forEach(r=>{r.dataset.poiType||(r.checked=this.showAllBuildings,(r.closest(".filter-item")||r.closest(".filter-item-mobile"))?.setAttribute("aria-checked",this.showAllBuildings),this.showAllBuildings?this.visibleSupertipos.add(r.value):this.visibleSupertipos.delete(r.value))}),this.infoWindowManager.closeAll(),this.updateAllMarkers()};[o,n].forEach(a=>{if(a){let r=a.querySelector(".toggle-text");r&&(r.textContent=l.TRANSLATIONS.toggleShowAll),a.addEventListener("click",c)}}),document.querySelectorAll(".campus-btn").forEach(a=>{a.addEventListener("click",r=>{document.querySelectorAll(".campus-btn").forEach(h=>h.classList.remove("active")),r.target.classList.add("active");let d=r.target.dataset.campus;this.infoWindowManager.closeAll(),this.updateTimezone(d),this.mapManager.centerOnCampus(d)})}),window.addEventListener("showEntityPanel",a=>{let{entidad:r,edificioOrigen:d}=a.detail.entidad?a.detail:{entidad:a.detail,edificioOrigen:null};this.showEntityPanel(r,d)}),window.addEventListener("openMobileDrawer",a=>{let{edificio:r,entidad:d,edificioOrigen:h}=a.detail;d?this.showEntityPanel(d,h):this.showBuildingOnlyPanel(r)})}showBuildingOnlyPanel(e){let t=document.getElementById("info-panel"),i=document.getElementById("panel-content"),s=document.querySelector("#info-panel .panel-header");s.innerHTML=`
${l.TRANSLATIONS.buildingTitle} ${e.edificio}
`;let o=this.getBuildingImagePath(e),n=e.lat&&e.lon?`https://www.google.com/maps/dir/?api=1&destination=${e.lat},${e.lon}`:null,c="";if(e.cam==="H"){let h=window.PLANO_EXTRA?.baiduMapsUrl||"https://j.map.baidu.com/37/iOvu";c=`
${l.TRANSLATIONS.viewOnBaiduMaps||"Ver en Baidu Maps"}
`}else{let h=`https://openmaps.upv.es/?locate=${e.cam}.${e.edificio}`;c=`
${l.TRANSLATIONS.openMapsTitle||"Ver plantas y espacios"}
`}if(i.innerHTML=`
${l.TRANSLATIONS.noEntities}
${n?`
`:""}
${c}
`,this.responsiveManager&&this.responsiveManager.isMobile()){t.parentElement.id==="app"&&document.body.appendChild(t),t.classList.remove("hidden"),t.classList.add("active");let h=document.getElementById("mobile-panel-overlay");h&&h.classList.add("active"),document.body.classList.add("modal-open")}else t.classList.remove("hidden"),t.classList.remove("active");let a=document.getElementById("carousel-image"),r=document.getElementById("image-container");a&&r&&(a.complete&&a.naturalHeight!==0?(a.classList.add("loaded"),r.style.animation="none"):(a.addEventListener("load",()=>{a.classList.add("loaded"),r.style.animation="none"}),a.addEventListener("error",()=>{r.classList.add("error"),a.style.display="none"})));let d=document.getElementById("close-panel");if(d&&d.addEventListener("click",()=>{this.closeEntityPanel()}),this.responsiveManager&&this.responsiveManager.isMobile()){let h=document.getElementById("mobile-panel-overlay");h&&h.addEventListener("click",()=>{this.closeEntityPanel()},{once:!0})}}showEntityPanel(e,t=null){let i=document.getElementById("info-panel"),s=document.getElementById("panel-content"),o=document.querySelector("#info-panel .panel-header"),n=l.getText(e,"nombre"),c=e.acronimo||e.siglas,a=l.SUPERTIPOS[e.supertipo],r=a?a.nameShort:"OTR",d=`
`;o.innerHTML=d;let h=e.edificios||[],f=e.campus,u=h.map(m=>this.data.Edificios.find(g=>g.edificio===m&&g.cam===f)).filter(m=>m),v=0;if(t){let m=u.findIndex(g=>g.edificio===t.edificio);m!==-1&&(v=m)}let C="",L="",I="";if(u.length>0){let m=u[v],g=this.getBuildingImagePath(m),b=l.CAMPUS[f]?.name||f;C=`
`,I=`
Campus: ${b} \xB7 Ed: ${m.edificio}
`,u.length>1&&(L=`
${u.map((O,$)=>`
`).join("")}
`)}let j=f==="H"?window.PLANO_EXTRA?.hangzhouUrl||"https://biss.buaa.edu.cn/":`https://www.upv.es/entidades/${c.toUpperCase()}`,k='";let E=u.length>0?u[v]:null,Z="";if(E){let m=this.data.Entidades.filter(g=>g.siglas!==e.siglas&&g.campus===e.campus&&E.siglas&&E.siglas.includes(g.siglas));m.length>0&&(Z=`
${l.TRANSLATIONS.otherEntities} ${E.edificio}:
${m.map(g=>{let b=l.getText(g,"nombre"),O=g.acronimo||g.siglas,$=l.SUPERTIPOS[g.supertipo],oe=$?$.nameShort:"OTR";return`
-
${b}
(${O})
${oe}
`}).join("")}
`)}let H=E?.lat,U=E?.lon,te=H&&U?`https://www.google.com/maps/dir/?api=1&destination=${H},${U}`:"#",ie=E?.edificio||"",se=H&&U?`
`:"",W="";if(u.length>0)if(f==="H"){let m=window.PLANO_EXTRA?.baiduMapsUrl||"https://j.map.baidu.com/37/iOvu";W=`
${l.TRANSLATIONS.viewOnBaiduMaps||"Ver en Baidu Maps"}
`}else{let m=u.map(g=>`
${l.TRANSLATIONS.building} ${g.edificio}
`).join("");W=`
${l.TRANSLATIONS.openMapsTitle||"Ver plantas y espacios"}
${m}
`}if(s.innerHTML=`
${C}
${I}
${L}
${k}
${se}
${W}
${Z}
`,this.responsiveManager&&this.responsiveManager.isMobile()){i.parentElement.id==="app"&&document.body.appendChild(i),i.classList.remove("hidden"),i.classList.add("active");let m=document.getElementById("mobile-panel-overlay");m&&m.classList.add("active"),document.body.classList.add("modal-open")}else i.classList.remove("hidden"),i.classList.remove("active");let y=document.getElementById("carousel-image"),M=document.getElementById("image-container");y&&M&&(y.complete&&y.naturalHeight!==0?(y.classList.add("loaded"),M.style.animation="none"):(y.addEventListener("load",()=>{y.classList.add("loaded"),M.style.animation="none"}),y.addEventListener("error",()=>{M.classList.add("error"),y.style.display="none"})));let J=document.getElementById("close-panel");if(J&&J.addEventListener("click",()=>{this.closeEntityPanel()}),this.responsiveManager&&this.responsiveManager.isMobile()){let m=document.getElementById("mobile-panel-overlay");m&&(this.mobileOverlayClickHandler&&m.removeEventListener("click",this.mobileOverlayClickHandler),this.mobileOverlayClickHandler=b=>{b.target===m&&b.currentTarget===m&&this.closeEntityPanel()},m.addEventListener("click",this.mobileOverlayClickHandler));let g=b=>{b.key==="Escape"&&(this.closeEntityPanel(),document.removeEventListener("keydown",g))};document.addEventListener("keydown",g)}u.length>1&&this.setupCarouselEvents(u,e),this.attachOtherEntitiesEvents(),console.log("Panel de entidad abierto:",e.siglas)}closeEntityPanel(){let e=document.getElementById("info-panel");if(e&&(e.classList.add("hidden"),e.classList.remove("active")),this.responsiveManager&&this.responsiveManager.isMobile()){let t=document.getElementById("mobile-panel-overlay");if(t&&t.classList.remove("active"),document.body.classList.remove("modal-open"),this.mobileOverlayClickHandler&&t&&(t.removeEventListener("click",this.mobileOverlayClickHandler),this.mobileOverlayClickHandler=null),e&&e.parentElement===document.body){let i=document.getElementById("app");i&&i.appendChild(e)}}console.log("Panel de entidad cerrado")}attachOtherEntitiesEvents(){document.querySelectorAll(".other-entities .entity-item[data-siglas]").forEach(e=>{e.addEventListener("click",t=>{t.preventDefault();let i=t.currentTarget.dataset.siglas,s=this.data.Entidades.find(o=>o.siglas===i);if(s){let o=document.getElementById("info-panel");o&&(o.scrollTop=0);let c=t.currentTarget.closest(".other-entities")?.dataset.edificio,a=c?this.data.Edificios.find(r=>r.edificio===c):null;this.showEntityPanel(s,a)}})})}setupCarouselEvents(e,t){document.querySelectorAll(".building-tab").forEach(i=>{i.addEventListener("click",s=>{let o=s.target.dataset.edificio,n=e.find(c=>c.edificio===o);if(n){let c=document.getElementById("carousel-image"),a=document.getElementById("image-container");if(c.classList.remove("loaded"),a&&(a.classList.remove("error"),a.style.animation="skeleton-loading 1.5s ease-in-out infinite"),c.src=this.getBuildingImagePath(n),c.alt=`${l.TRANSLATIONS.buildingLabel} ${n.edificio}`,c.complete&&c.naturalHeight!==0)c.classList.add("loaded"),a&&(a.style.animation="none");else{let u=()=>{c.classList.add("loaded"),a&&(a.style.animation="none"),c.removeEventListener("load",u)},v=()=>{a&&(a.classList.add("error"),a.style.animation="none"),c.style.display="none",c.removeEventListener("error",v)};c.addEventListener("load",u),c.addEventListener("error",v)}let r=document.getElementById("current-building");r&&(r.textContent=n.edificio),document.querySelectorAll(".building-tab").forEach(u=>u.classList.remove("active")),s.target.classList.add("active");let d=document.getElementById("btn-directions");if(d&&n.lat&&n.lon){let u=`https://www.google.com/maps/dir/?api=1&destination=${n.lat},${n.lon}`;d.href=u,d.innerHTML=`${w.route} ${l.TRANSLATIONS.howToGet} -> ${n.edificio}`}let h=this.data.Entidades.filter(u=>u.siglas!==t.siglas&&u.campus===t.campus&&n.siglas&&n.siglas.includes(u.siglas)),f=document.getElementById("other-entities-list");f&&(h.length>0?(f.dataset.edificio=n.edificio,f.innerHTML=`
${l.TRANSLATIONS.otherEntities} ${n.edificio}:
${h.map(u=>{let v=l.getText(u,"nombre"),C=u.acronimo||u.siglas,L=l.SUPERTIPOS[u.supertipo],I=L?L.nameShort:"OTR";return`
-
${v}
(${C})
${I}
`}).join("")}
`,this.attachOtherEntitiesEvents()):f.innerHTML="")}})})}getBuildingImagePath(e){let t=e.img||e.thumb;return t?`${l.PATHS.IMAGES_BASE}${t}`:`${l.PATHS.IMAGES_BASE}placeholder.jpg`}processURLParams(){let e=Q(),t=ee(e);console.log("Par\xE1metros URL:",t),t.entidad?this.handleURLEntity(t.entidad):t.edificio?this.handleURLBuilding(t.edificio):t.campus&&this.handleURLCampus(t.campus)}handleURLEntity(e){let t=this.data.Entidades.find(i=>i.siglas===e||i.acronimo===e);if(!t){console.warn(`Entidad no encontrada: ${e}`);return}setTimeout(()=>{this.searchManager.selectEntity(t)},800)}handleURLBuilding(e){setTimeout(()=>{let[t,...i]=e,s=i.join("");console.log(`Buscando edificio: ${s} en campus: ${t}`);let o=this.data.Edificios.find(n=>n.edificio===s&&n.cam===t);o?this.searchManager.selectBuilding(o):console.warn(`Edificio no encontrado: ${e} (Campus: ${t}, Edificio: ${s})`)},800)}handleURLCampus(e){setTimeout(()=>{let t=document.querySelector(`.campus-btn[data-campus="${e}"]`);t&&t.click()},800)}};window.initApp=()=>{window.app=new G,window.app.init()};document.addEventListener("DOMContentLoaded",()=>{let p=document.getElementById("close-panel");p&&p.addEventListener("click",()=>{document.getElementById("info-panel").classList.add("hidden")})});})();