import maplibregl from "maplibre-gl";
import proj4 from "proj4";
import * as THREE from "three";
console.log(THREE);
proj4.defs(
  "EPSG:25832",
  "+proj=utm +zone=32 +ellps=GRS80 +units=m +no_defs"
);


const center = [9.209116842757239, 52.26520546238239]

const map = new maplibregl.Map({
    container: 'map',
    style: "https://tiles.openfreemap.org/styles/bright",
    center: center,
    zoom: 17
});

map.addControl(
    new maplibregl.NavigationControl({
        visualizePitch: true,
        showZoom: true,
        showCompass: true
    })
);

// 2. Create an HTML element to display coordinates (e.g., <pre id="coordinates"></pre>)
const coordinatesDiv = document.getElementById('coordinates');

// 3. Listen for mouse movement
map.on('mousemove', (e) => {
    // e.lngLat contains the longitude and latitude
    const lng = e.lngLat.lng.toFixed(5);
    const lat = e.lngLat.lat.toFixed(5);
    
    coordinatesDiv.innerHTML = `Lon: ${lng}° | Lat: ${lat}°`;
});


const elRenderArea=document.getElementById("potree_render_area");

const viewer=new Potree.Viewer(elRenderArea, {noDragAndDrop:true});
viewer.setEDLEnabled(true);
viewer.setFOV(60);
viewer.setPointBudget(3*1000*1000);
viewer.setMinNodeSize(0);
viewer.setBackground("none"); 


//Dateipfade der Punktwolken
const pointCloudFiles={
  //Namen sind gerade nur Platzhalter. Richtige namen müssen rein
  first: 'output/metadata.json',
  second: 'standpunkt2/metadata.json',
  third: 'punktwolke_3_converted/metadata.json',
}


//Aktuelle Datei und Sichtbarkeit
let currentPointCloud=null;
let isVisible=true;

function loadPointCloud(path){
  console.log("Laden aufgerufen")
  if(currentPointCloud){
    viewer.scene.removePointCloud(currentPointCloud);
    currentPointCloud=null;
  }

  if(!path ||!isVisible) return;

  Potree.loadPointCloud(path, "punktwolke", function(e) {
    currentPointCloud=e.pointcloud;
    viewer.scene.addPointCloud(currentPointCloud);

   // View-Objekt inspizieren
    console.log("view:", viewer.scene.view);
    console.log("view.lookAt:", viewer.scene.view.lookAt);
    console.log("view.position:", viewer.scene.view.position);
    console.log("view keys:", Object.keys(viewer.scene.view));
    

    let material =currentPointCloud.material;
    material.size =1;
    material.pointSizeType=Potree.PointSizeType.ADAPTIVE;
    
    viewer.fitToScreen();
    syncCamera();
  });
}


function syncCamera() {

    if (!currentPointCloud) return;

    const center = map.getCenter();

    // -----------------------------------------
    // WGS84 -> ETRS89 / UTM32
    // -----------------------------------------

    const [x, y] = proj4(
        "EPSG:4326",
        "EPSG:25832",
        [center.lng, center.lat]
    );

    // -----------------------------------------
    // Map Parameter
    // -----------------------------------------

    const pitch = map.getPitch() * Math.PI / 180;
    const bearing = map.getBearing() * Math.PI / 180;
    const zoom = map.getZoom();

    // -----------------------------------------
    // Abstand abhängig vom Zoom
    // -----------------------------------------
    const earthCircumference = 40075016.686;
    const metersPerPixel = earthCircumference * Math.cos(center.lat * Math.PI / 180) / Math.pow(2, zoom + 8);
    const distance = metersPerPixel * map.getCanvas().height;

    // -----------------------------------------
    // Zielpunkt = Kartenzentrum
    // -----------------------------------------
    const target = new THREE.Vector3(x, y, 0);

    // -----------------------------------------
    // Kameraoffset
    // -----------------------------------------
    const offset = new THREE.Vector3(0, -distance * Math.sin(pitch), distance * Math.cos(pitch)
    );

    // Bearing rotieren
    offset.applyAxisAngle(new THREE.Vector3(0, 0, 1), -bearing);

    // -----------------------------------------
    // Kameraposition
    // -----------------------------------------
    const cameraPosition = target.clone().add(offset);

    // -----------------------------------------
    // Potree Kamera setzen
    // -----------------------------------------
    const camera = viewer.scene.getActiveCamera();
    camera.position.copy(cameraPosition);
    camera.lookAt(target);
    viewer.scene.view.position.copy(cameraPosition);
    viewer.scene.view.lookAt(target);
    camera.updateMatrixWorld();
    viewer.renderer.render(
        viewer.scene.scene,
        camera
    );
}

// Kameras bei jeder Kartenbewegung synchronisieren
  map.on('move', syncCamera);
  map.on('zoom', syncCamera);
  map.on('pitch', syncCamera);
  map.on('rotate', syncCamera);




// Hintergrundkarte ändern
function changeBaseMap(newMap){
  var basemapStyle;
  switch(newMap){
    case "openfree_dark":
      basemapStyle = "https://tiles.openfreemap.org/styles/dark"
      break;
    case "openfree_bright":
      basemapStyle = "https://tiles.openfreemap.org/styles/bright"
      break;
    case "openfree_liberty":
      basemapStyle = "https://tiles.openfreemap.org/styles/liberty"
      break;
    case "google_satellite":
   basemapStyle = {
    version: 8,
    sources: {
      "raster-tiles": {
        type: "raster",
        tiles: [
          "https://api.maptiler.com/tiles/satellite-v2/{z}/{x}/{y}.jpg?key=6mG881AthmTTWyLvFyjH"
        ],
        tileSize: 256,
        attribution: "&copy; MapTiler",
        maxzoom: 20
      }
    },
    layers: [
      {
        id: "satellite-layer",
        type: "raster",
        source: "raster-tiles"
      }
    ]
  }
    break;
  case "terrain":
    basemapStyle = {
        version: 8,
        sources: {
            topo: {
        type: 'raster',
        url: 'https://api.maptiler.com/maps/topo-v4/tiles.json?key=6mG881AthmTTWyLvFyjH',
        tileSize: 256,
        maxzoom: 20
      },
            // Use a different source for terrain and hillshade layers, to improve render quality
            terrainSource: {
                type: 'raster-dem',
                url: 'https://tiles.mapterhorn.com/tilejson.json',
            },
            hillshadeSource: {
                type: 'raster-dem',
                url: 'https://tiles.mapterhorn.com/tilejson.json'
            }
        },
        layers: [
            {
                id: 'topo',
                type: 'raster',
                source: 'topo'
            },
            {
                id: 'hills',
                type: 'hillshade',
                source: 'hillshadeSource',
                layout: {visibility: 'visible'},
                paint: {'hillshade-shadow-color': '#473B24'}
            }
        ],
        terrain: {
            source: 'terrainSource',
            exaggeration: 1
        },
        sky: {}
    }
    break;
    case "satellite_terrain": 
      basemapStyle =  {
        version: 8,
        sources: {
             "raster-tiles": {
        type: "raster",
        tiles: [
          "https://api.maptiler.com/tiles/satellite-v2/{z}/{x}/{y}.jpg?key=6mG881AthmTTWyLvFyjH"
        ],
        tileSize: 256,
        attribution: "&copy; MapTiler",
        maxzoom: 20
      },
            // Use a different source for terrain and hillshade layers, to improve render quality
            terrainSource: {
                type: 'raster-dem',
                url: 'https://tiles.mapterhorn.com/tilejson.json',
            },
            hillshadeSource: {
                type: 'raster-dem',
                url: 'https://tiles.mapterhorn.com/tilejson.json'
            }
        },
        layers: [
            {
                id: 'raster-tiles',
                type: 'raster',
                source: 'raster-tiles'
            },
            {
                id: 'hills',
                type: 'hillshade',
                source: 'hillshadeSource',
                layout: {visibility: 'visible'},
                paint: {'hillshade-shadow-color': '#473B24'}
            }
        ],
        terrain: {
            source: 'terrainSource',
            exaggeration: 1
        },
        sky: {}
    }
	
  }
  map.setStyle(basemapStyle);
}


const button = document.querySelector('#disable')

button.addEventListener('click', () => {

    isVisible = !isVisible;

    if(currentPointCloud){
        currentPointCloud.visible = isVisible;
    }

    button.textContent = isVisible
        ? "Punktwolke ausblenden"
        : "Punktwolke anzeigen";

});


// ausgewähltes Element im BaseMap DropDown Feld
const selectElement = document.querySelector('select[name="basemap"]');
selectElement.addEventListener('change', (event) => {
  changeBaseMap(event.target.value);
});



// ausgewähltes Element im Punktwolken DropDown Feld
document.querySelector('select[name="pointcloud"]').addEventListener('change', (event) => {
  loadPointCloud(pointCloudFiles[event.target.value]);
});


// Auf Zentrum zurück zoomen
document.getElementById("location").addEventListener("click", () => {
 map.flyTo({center, zoom: 17 })
});


var pointCountSlider = document.getElementById("pointSlider");
var pointCountOutput = document.getElementById("pointSliderValue");
pointCountOutput.innerHTML = "Dargestellte Punkte: " + Number(pointCountSlider.value).toLocaleString();

pointCountSlider.oninput = function() {
  pointCountOutput.innerHTML = "Dargestellte Punkte: " + Number(this.value).toLocaleString('de-DE');;
}


var pointSizeSlider = document.getElementById("pointSizeSlider");
var pointSizeOutput = document.getElementById("pointSizeSliderValue");
pointSizeOutput.innerHTML = "Punktgröße (mm): " + Number(pointSizeSlider.value).toLocaleString();

pointSizeSlider.oninput = function() {
  pointSizeOutput.innerHTML = "Punktgröße (mm): " + Number(this.value).toLocaleString('de-DE');;
}

const closeButton = document.getElementById("closeSideBarButton");
const sidebar = document.getElementById("sidebar");
const openOuter = document.getElementById("openButtonOuter");

if (closeButton) {
    closeButton.addEventListener("click", () => {
      const rect = closeButton.getBoundingClientRect();  
      sidebar.style.display = "none";
        
        openOuter.innerHTML = "<button class='sideBarButtons' id='openSideBarButton' title='Menü ausklappen'>>></button>";
        const openButton = document.getElementById("openSideBarButton");
        openButton.style.top = `${rect.top + window.scrollY -2}px`;
        if (openButton) {
            openButton.addEventListener("click", () => {
                sidebar.style.display = "flex";
              
                openOuter.innerHTML = ""; 
            });
        }
    });
}

// Qualitätsbuttons aktivieren/deaktivieren
const qualityButtons = document.querySelectorAll('.qualityButtons');

qualityButtons.forEach(button => {

    button.addEventListener('click', () => {

        qualityButtons.forEach(btn => {
            btn.classList.remove('active');
        });

        button.classList.add('active');

    });

});


// Farbbuttons aktivieren/deaktivieren
const colorButtons = document.querySelectorAll('.colorButtons');

colorButtons.forEach(button => {

    button.addEventListener('click', () => {

        colorButtons.forEach(btn => {
            btn.classList.remove('active');
        });

        button.classList.add('active');

    });

});