let paises = [];
let nombresDeVariables = [];
let seleccionAnno="2020";
document.addEventListener('DOMContentLoaded', function () {
    d3.csv("./datos/paises.csv").then(function (data) {
        nombresDeVariables = Object.keys(data[0]);
        dibujaSelector();
        data.forEach(function (fila) {
            let countryData = [fila.countryName];
            Object.keys(fila).forEach(function (key) {
                if (key !== "countryName") {
                    // Convert the value to a number if it's a valid number, otherwise keep it as a string
                    const value = isNaN(fila[key]) ? fila[key] : parseFloat(fila[key]);
                    countryData.push(value);
                    /*console.log(value);*/
                }
            });
            paises.push(countryData);
            
        });
        dibujaMapa(seleccionAnno);
    });
});
function dibujaSelector(){
    nombresDeVariables.pop();
    const container = document.getElementById("yearSelectorContainer");
    const select = document.createElement("select");
    select.id = "yearSelector";  // Asignamos un id para referencia futura
    nombresDeVariables.forEach(function(year) {
        const option = document.createElement("option");
        option.value = year;
        option.textContent = year;
        select.appendChild(option);  // Agregar la opción al select
    });
    container.appendChild(select);
    select.value=seleccionAnno;
        // Escuchar cambios en el selector
    select.addEventListener("change", function () {
        seleccionAnno = select.value; // Actualizar la variable seleccionAnno
       /* console.log(seleccionAnno);*/
        dibujaMapa(seleccionAnno);
    });
} 
function dibujaMapa(seleccionAnno) {
    /*console.log(paises);*/
    anno=parseInt(seleccionAnno);
    
    let datosAnno=[];
    for(i=0;i<paises.length;i++){
        datosAnno.push(paises[i][anno-1959]);
    }/**aqui seleccionamos los valores para los paises y el anno seleccionado para poder tener el maximo y el minimo*/
    
    //console.log(datosAnno);   
    
    let min=Math.min(...datosAnno.filter(value => value !== 0)); /* minimo y maximo para poder hacer la escala de colores */
    let max=Math.max(...datosAnno);
    d3.json("./JsonPaises/world-geo.json").then(function (geojson) {
        // Configuración del mapa
        var DivMapa = document.getElementById("map");
        var width = DivMapa.clientWidth;
        var height = DivMapa.clientHeight;
        
        
        // Eliminamos mapas anteriores    
        d3.selectAll("#Map").remove();
        // Creamos el svg
        var svg = d3.select("#map")
            .append("svg")
            .attr("id", "Map")
            .attr("width", width)
            .attr("height", height);
        // Configuración de la proyección
        var projection = d3.geoEquirectangular()
        .scale(width/8.5) 
        .rotate([0, 0]) 
        .center([0, 0]) 
        .translate([width/2,height/2 +15]); 
        var path = d3.geoPath().projection(projection);
                        
        var logScale = d3.scaleLog().domain([min, max]).range([0, 1]); 
        var colores = d3.scaleSequential(d3.interpolateViridis).domain([ Math.log(min),Math.log(max)]);
        
        geojson.features.forEach(function (feature) {
            const countryName = feature.properties.name;
            const index = paises.findIndex(p => p[0] === countryName);
            //console.log(`Buscando: ${countryName}, Encontrado en índice: ${index}`);
            if (index !== -1) {
                // Agregar un valor de datosAnno al GeoJSON
                feature.properties.value = datosAnno[index];
            } else {
                feature.properties.value = 0; // Si no se encuentra, asignar 0
            }
        });
        svg.selectAll("path")
            .data(geojson.features)
            .enter()
            .append("path")
            .attr("d", path)
            .style("fill", function (d) {
                const value = d.properties.value;
              // console.log(value);
                return value === 0 ? "#cce5df" : colores(Math.log(value)); // Colores para países con datos
            })
            .style("stroke-width", 0.55)
            .style("stroke","black")
            .on("mouseover",function(event,d){
                const centroid = path.centroid(d);
                let textX = centroid[0] + (Math.random() * 20 - 10); // Aleatorizar un poco
                let textY = centroid[1] - 20;
            
                // Verificar si el texto se sale hacia la parte superior
                if (textY < 0) {
                    textY = 20; // Mover el texto hacia abajo si está fuera por arriba
                }
            
                // Verificar si el texto se sale hacia la parte inferior
                if (textY > height - 20) {
                    textY = height - 40; // Mover el texto hacia arriba si está fuera por abajo
                }
            
                d3.select(this)
                    .raise()
                    .style("cursor", "pointer")
                    .style("stroke-width", 0.75)
                    .attr("transform", `
                        translate(${centroid[0]}, ${centroid[1]}) 
                        scale(1.2) 
                        translate(${-centroid[0]}, ${-centroid[1]})`);
                const textElement=svg.append("text")
                    .attr("id","texto")
                    .attr("x", textX)
                    .attr("y", textY-5)
                    .style("font-family","Arial")
                    .style("fill","black")
                    .text(`${d.properties.name}: ${d.properties.value ? d.properties.value.toFixed(2) : 'Sin datos'}`)
                    .style("opacity", 1);
                const textBBox = textElement.node().getBBox();
                svg.append("rect")
                .attr("id","rectanguloTexto")
                .attr("x", textBBox.x -5)
                .attr("y", textBBox.y -2)
                .attr("width", textBBox.width + 10)
                .attr("height", textBBox.height + 4)
                .attr("rx", 5) 
                .attr("ry", 5)
                .style("fill", "white")
                .style("opacity", 0.4);
                textElement.raise();
               
            })
            .on("mouseout",function(){
                d3.select(this)
                    .style("stroke-width", 0.55)
                    .attr("transform", null);
                d3.selectAll("#texto").remove();
                d3.selectAll("#rectanguloTexto").remove();
            })
            .on("click",function(event,d){
                dibujaGrafico(d.properties.name,paises);
            })
       
            var legend = svg.append("g") 
            .attr("class", "legend") 
            .attr("transform", "translate(20, 50)"); 
            var legendScale = d3.scaleLog() 
            .domain([min, max]) 
            .range([0, 300]); 
            var legendAxis = d3.axisLeft(legendScale) 
            .ticks(4) 
            .tickFormat(d3.format(".2f")); 
            var legendBar = d3.scaleSequential(d3.interpolateViridis) 
            .domain([ Math.log(min),Math.log(max)]);
            legend.append("g") 
            .attr("class", "axis") 
            .call(legendAxis)
            .selectAll("text") 
            .style("font-family","Arial")
            .attr("transform", "translate(30, 0)") // Desplazar los valores de la leyenda a la derecha 
            .style("text-anchor", "start"); // Alinear los valores de la leyenda a la derecha; 
            
    
            for (let i = Math.log(min); i <= Math.log(max); i += 0.1) {
                 legend.append("rect") 
                 .attr("x", 0) 
                 .attr("y", legendScale(Math.exp(i))) 
                 .attr("width", 20) 
                 .attr("height", legendScale(Math.exp(i + 0.1)) - legendScale(Math.exp(i)))
                 .style("fill", legendBar(i));
            }
            legend.append("text")
            .raise()
            .attr("x", 0)
            .attr("y", -10 + legendScale(Math.exp(i + 0.1)) - legendScale(Math.exp(i)))
            .style("font-size", "12px")
            .style("font-weight", "bold")
            .style("font-family","Arial")
            .text("PIB");
    });
}
function dibujaGrafico(country,paises){
    let datosPais=[];
    let index;
    for(i=0;i<paises.length;i++){
        if(paises[i][0]===country){
           // console.log(paises[i][0]);
            index=i;
            //datosPais.push(paises[i]);
            
        }
    }
    datosPais=paises[index];
    console.log(datosPais);
    const datos = nombresDeVariables.map((year, i) => ({
        Year: parseInt(year),
        Valor: typeof datosPais[i + 1] === "number" ? datosPais[i + 1] : null
    })).filter(d => d.Valor !== null); // Filtramos valores nulos o no numéricos
    const GraficoLineas = document.getElementById("grafico");
    const margin = { top: 20, right: 20, bottom: 50, left: 50 };
    const width = GraficoLineas.clientWidth - margin.left - margin.right;
    const height = GraficoLineas.clientHeight - margin.top - margin.bottom;
    // Se elimina el gráfico existente
    d3.selectAll("#GraficoLineasSvg").remove();
    // Creamos el SVG para el gráfico
    const svg = d3.select("#grafico")
        .append("svg")
        .attr("id", "GraficoLineasSvg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", `translate(${margin.left},${margin.top})`);
    // Escalas
    // Escala X
    const xScale = d3.scaleLinear()
        .domain(d3.extent(datos, d => d.Year))
        .range([0, width]);
    // Escala Y
    const yScale = d3.scaleLinear()
        .domain([d3.min(datos, d => d.Valor) - 0.05, d3.max(datos, d => d.Valor) + 0.05])
        .range([height, 0]);
    // Línea
    const line = d3.line()
        .x(d => xScale(d.Year))
        .y(d => yScale(d.Valor));
    // Ponemos la línea en el gráfico
    const path = svg.append("path")
        .data([datos])
        .attr("class", "line")
        .attr("d", line)
        .style("fill", "none")
        .style("stroke", "black")
        .style("stroke-width", 2);
    // Animación para la línea
    const totalLength = path.node().getTotalLength();
    path.attr("stroke-dasharray", totalLength + " " + totalLength)
        .attr("stroke-dashoffset", totalLength)
        .transition()
        .duration(3000)
        .ease(d3.easeLinear)
        .attr("stroke-dashoffset", 0);
    // Ejes
    // Eje X
    svg.append("g")
        .attr("class", "x axis")
        .attr("transform", `translate(0,${height})`)
        .call(d3.axisBottom(xScale).tickFormat(d3.format("d")));
    svg.append("text")
        .attr("text-anchor", "middle")
        .attr("transform", `translate(${width / 2},${height + margin.bottom - 10})`)
        .text("Años");
    // Eje Y
    svg.append("g")
        .attr("class", "y axis")
        .call(d3.axisLeft(yScale));
    svg.append("text")
        .style("font-size", "15px")
        .attr("text-anchor", "middle")
        .attr("transform", `translate(${-margin.left +35},${height / 2 -60})`)
        .text("Valor PIB");
    // Título
    svg.append("text")
        .attr("x", width / 2)
        .attr("y", -5)
        .attr("text-anchor", "middle")
        .style("font-size", "18px")
        .style("font-weight", "bold")
        .style("font-family","Arial")
        .text(`Evolución de los datos para ${country}`);
}