/* ===== Lista de aeropuertos organizada ===== */
const FLIGHT_CALC_AIRPORTS_LIST = {
  "Colombia": [
    {code: "BOG", name: "Bogotá (El Dorado)", lat: 4.7016, lon: -74.1469},
    {code: "MDE", name: "Medellín (JMC)", lat: 6.1645, lon: -75.4231},
    {code: "EOH", name: "Medellín (Olaya Herrera)", lat: 6.2205, lon: -75.5906},
    {code: "CLO", name: "Cali (Alfonso Bonilla)", lat: 3.5432, lon: -76.3816},
    {code: "BAQ", name: "Barranquilla", lat: 10.8896, lon: -74.7808},
    {code: "CTG", name: "Cartagena", lat: 10.4424, lon: -75.5130},
    {code: "SMR", name: "Santa Marta", lat: 11.1196, lon: -74.2306},
    {code: "BGA", name: "Bucaramanga", lat: 7.1265, lon: -73.1848},
    {code: "CUC", name: "Cúcuta", lat: 7.9276, lon: -72.5115},
    {code: "PEI", name: "Pereira", lat: 4.8127, lon: -75.7395},
    {code: "ADZ", name: "San Andrés", lat: 12.5836, lon: -81.7112},
    {code: "MTR", name: "Montería", lat: 8.8237, lon: -75.8258}
  ],
  "América Latina": [
    {code: "PTY", name: "Panamá", lat: 9.0714, lon: -79.3835},
    {code: "LIM", name: "Lima", lat: -12.0219, lon: -77.1143},
    {code: "UIO", name: "Quito", lat: -0.1292, lon: -78.3575},
    {code: "GYE", name: "Guayaquil", lat: -2.1574, lon: -79.8836},
    {code: "SCL", name: "Santiago", lat: -33.3929, lon: -70.7858},
    {code: "GRU", name: "São Paulo", lat: -23.4356, lon: -46.4731},
    {code: "EZE", name: "Buenos Aires", lat: -34.8222, lon: -58.5358},
    {code: "MEX", name: "Ciudad de México", lat: 19.4361, lon: -99.0719},
    {code: "CUN", name: "Cancún", lat: 21.0365, lon: -86.8771}
  ],
  "Internacional": [
    {code: "MIA", name: "Miami", lat: 25.7933, lon: -80.2906},
    {code: "JFK", name: "New York (JFK)", lat: 40.6413, lon: -73.7781},
    {code: "ATL", name: "Atlanta", lat: 33.6407, lon: -84.4277},
    {code: "MAD", name: "Madrid", lat: 40.4719, lon: -3.5626},
    {code: "BCN", name: "Barcelona", lat: 41.2974, lon: 2.0833},
    {code: "CDG", name: "París", lat: 49.0097, lon: 2.5479},
    {code: "FRA", name: "Frankfurt", lat: 50.0379, lon: 8.5622},
    {code: "LHR", name: "Londres", lat: 51.4700, lon: -0.4543}
  ]
};

/* Crear lookup rápido por código */
const FLIGHT_CALC_AIRPORTS = {};
Object.values(FLIGHT_CALC_AIRPORTS_LIST).forEach(group => {
  group.forEach(airport => {
    FLIGHT_CALC_AIRPORTS[airport.code] = {lat: airport.lat, lon: airport.lon};
  });
});

/* ===== Parámetros de cálculo ===== */
const FLIGHT_CALC_FE_BASE = {short: 0.15, medium: 0.12, long: 0.09};
const FLIGHT_CALC_CLASS_MULT = {economy: 1, premium: 1.25, business: 1.75, first: 2.5};
const FLIGHT_CALC_RF_MULT = 1.9;
const FLIGHT_CALC_ROUTE_UPLIFT = 1.05;
const FLIGHT_CALC_CAR_KG_PER_KM = 0.18;
const FLIGHT_CALC_DIST_BOUNDS = {short: 1500, medium: 3500};

/* Variables globales para rastrear selección */
let flightCalcSelectedAirports = {
  origen: null,
  destino: null
};

/* ===== Funciones de Dropdown ===== */

/* Mostrar dropdown */
function flightCalcShowDropdown(fieldId) {
  const dropdown = document.getElementById(fieldId + '-dropdown');
  const input = document.getElementById(fieldId);
  
  // Cerrar otros dropdowns
  document.querySelectorAll('.flight-calc-dropdown').forEach(d => {
    if (d.id !== fieldId + '-dropdown') {
      d.classList.remove('show');
    }
  });
  
  // Si está vacío, mostrar todos
  if (!input.value.trim()) {
    flightCalcRenderDropdown(fieldId, null);
  }
  
  dropdown.classList.add('show');
}

/* Filtrar aeropuertos */
function flightCalcFilterAirports(fieldId) {
  const input = document.getElementById(fieldId);
  const query = input.value.trim().toLowerCase();
  
  flightCalcRenderDropdown(fieldId, query);
}

/* Renderizar dropdown */
function flightCalcRenderDropdown(fieldId, query) {
  const dropdown = document.getElementById(fieldId + '-dropdown');
  let html = '';
  let hasResults = false;
  
  Object.entries(FLIGHT_CALC_AIRPORTS_LIST).forEach(([groupName, airports]) => {
    const filtered = query 
      ? airports.filter(a => 
          a.code.toLowerCase().includes(query) || 
          a.name.toLowerCase().includes(query)
        )
      : airports;
    
    if (filtered.length > 0) {
      hasResults = true;
      html += `<div class="flight-calc-dropdown-group">${groupName}</div>`;
      filtered.forEach(airport => {
        html += `<div class="flight-calc-dropdown-item" onclick="flightCalcSelectAirport('${fieldId}', '${airport.code}', '${airport.name.replace(/'/g, "\\'")}')">
          <strong>${airport.code}</strong> — ${airport.name}
        </div>`;
      });
    }
  });
  
  if (!hasResults) {
    html = '<div class="flight-calc-dropdown-empty">No se encontraron aeropuertos</div>';
  }
  
  dropdown.innerHTML = html;
  dropdown.classList.add('show');
}

/* Seleccionar aeropuerto */
function flightCalcSelectAirport(fieldId, code, name) {
  const input = document.getElementById(fieldId);
  const dropdown = document.getElementById(fieldId + '-dropdown');
  
  input.value = `${code} — ${name}`;
  flightCalcSelectedAirports[fieldId] = code;
  
  dropdown.classList.remove('show');
}

/* Cerrar dropdown al hacer click fuera */
document.addEventListener('click', function(e) {
  if (!e.target.closest('.flight-calc-searchable-select')) {
    document.querySelectorAll('.flight-calc-dropdown').forEach(d => {
      d.classList.remove('show');
    });
  }
});

/* ===== Navegación UI ===== */
function flightCalcSetProgress(n) {
  ['p1', 'p2', 'p3', 'p4'].forEach((id, i) => 
    document.getElementById(id).classList.toggle('fill', i < n)
  );
}

function flightCalcShow(id) {
  ['step1', 'step2', 'step3', 'step4'].forEach(s => 
    document.getElementById(s).style.display = 'none'
  );
  document.getElementById(id).style.display = 'block';
}

function flightCalcNext(from) {
  if (from === 1) {
    if (!flightCalcSelectedAirports.origen || !flightCalcSelectedAirports.destino) {
      alert("Selecciona origen y destino válidos");
      return;
    }
    if (flightCalcSelectedAirports.origen === flightCalcSelectedAirports.destino) {
      alert("El origen y destino no pueden ser iguales");
      return;
    }
    flightCalcShow('step2');
    flightCalcSetProgress(2);
  } else if (from === 2) {
    const p = parseInt(document.getElementById('pasajeros').value || '1', 10);
    if (isNaN(p) || p < 1) {
      alert("Mínimo 1 pasajero");
      return;
    }
    flightCalcShow('step3');
    flightCalcSetProgress(3);
  }
}

function flightCalcBack(from) {
  if (from === 2) {
    flightCalcShow('step1');
    flightCalcSetProgress(1);
  }
  if (from === 3) {
    flightCalcShow('step2');
    flightCalcSetProgress(2);
  }
}

function flightCalcReset() {
  // Limpiar campos
  document.getElementById('origen').value = '';
  document.getElementById('destino').value = '';
  flightCalcSelectedAirports = {origen: null, destino: null};
  document.getElementById('pasajeros').value = '1';
  document.getElementById('roundtrip').value = 'true';
  document.getElementById('clase').value = 'economy';
  document.getElementById('rf').value = 'on';
  
  flightCalcShow('step1');
  flightCalcSetProgress(1);
}

/* ===== Utilidades ===== */
const flightCalcToRad = d => d * Math.PI / 180;

function flightCalcHaversineKm(a, b) {
  const R = 6371;
  const dLat = flightCalcToRad(b.lat - a.lat);
  const dLon = flightCalcToRad(b.lon - a.lon);
  const lat1 = flightCalcToRad(a.lat);
  const lat2 = flightCalcToRad(b.lat);
  const h = Math.sin(dLat / 2) ** 2 + Math.cos(lat1) * Math.cos(lat2) * Math.sin(dLon / 2) ** 2;
  return 2 * R * Math.asin(Math.sqrt(h));
}

function flightCalcTramo(k) {
  if (k < FLIGHT_CALC_DIST_BOUNDS.short) return "short";
  if (k < FLIGHT_CALC_DIST_BOUNDS.medium) return "medium";
  return "long";
}

/* ===== Cálculo + envío a Google Forms ===== */
function flightCalcCalcular() {
  const usuario = "Anónimo";
  const o = flightCalcSelectedAirports.origen;
  const d = flightCalcSelectedAirports.destino;
  const cl = document.getElementById('clase').value;
  const pax = Math.max(1, parseInt(document.getElementById('pasajeros').value || '1', 10));
  const isRT = document.getElementById('roundtrip').value === 'true';
  const rfOn = document.getElementById('rf').value === 'on';
  
  if (!o || !d || o === d) {
    alert("Revisa origen/destino");
    return;
  }

  let km = flightCalcHaversineKm(FLIGHT_CALC_AIRPORTS[o], FLIGHT_CALC_AIRPORTS[d]) * FLIGHT_CALC_ROUTE_UPLIFT;
  if (isRT) km *= 2;

  const t = flightCalcTramo(km);
  const base = FLIGHT_CALC_FE_BASE[t] * (FLIGHT_CALC_CLASS_MULT[cl] || 1);
  const kgNoRF = km * base * pax;
  const kgRF = kgNoRF * FLIGHT_CALC_RF_MULT;
  const kg = rfOn ? kgRF : kgNoRF;

  // Salida UI
  document.getElementById('out-kg').textContent = `${Math.round(kg).toLocaleString('es-CO')} kgCO₂e`;
  document.getElementById('out-kg-norf').textContent = `${Math.round(kgNoRF).toLocaleString('es-CO')} kgCO₂e`;
  document.getElementById('out-route').textContent = `${o} → ${d}${isRT ? " (ida/vuelta)" : ""} · ${Math.round(km).toLocaleString('es-CO')} km`;
  document.getElementById('pill-tramo').textContent = `Tramo: ${t}`;
  document.getElementById('pill-clase').textContent = `Clase: ${cl}`;
  document.getElementById('pill-pax').textContent = `Pasajeros: ${pax}`;
  document.getElementById('out-car').textContent = `≈ Conducir ${(kg / FLIGHT_CALC_CAR_KG_PER_KM).toLocaleString('es-CO', {maximumFractionDigits: 0})} km en auto.`;
  document.getElementById('out-tip').textContent = t === 'long'
    ? "Tip: una escala eficiente puede reducir desvíos."
    : (t === 'short' ? "Tip: para tramos cortos, evalúa tren/bus." : "Tip: Premium Economy incrementa la huella por mayor espacio.");
  
  flightCalcShow('step4');
  flightCalcSetProgress(4);

  // Enviar a Google Forms
  flightCalcEnviarDatos(usuario, o, pax, d, Math.round(kg).toString());
}

function flightCalcEnviarDatos(usuario, origen, pasajeros, destino, resultado) {
  const formURL = "https://docs.google.com/forms/d/e/1FAIpQLSdd352oLudpxhyhXREmVt_6vbELtVSlwHKNf4b1641f6o2y9Q/formResponse";
  const fd = new FormData();
  fd.append("entry.1195792273", usuario);
  fd.append("entry.600138554", origen);
  fd.append("entry.746865423", pasajeros);
  fd.append("entry.1584395466", destino);
  fd.append("entry.1271743559", resultado);
  
  fetch(formURL, {method: "POST", body: fd, mode: "no-cors"})
    .then(() => console.log("✅ Datos enviados a Google Form"))
    .catch(err => console.error("❌ Error enviando datos:", err));
}

// Inicialización
window.addEventListener('DOMContentLoaded', () => flightCalcSetProgress(1));