import 'https://cdn.jsdelivr.net/npm/@material/web/all.js/+esm';

let dbInt = {};
let dbExt = { lineas: {} }; // Base de datos exterior inicializada
let audioActual = null;
const get = (id) => document.getElementById(id);

// --- 1. INICIO DEL SISTEMA ---
async function init() {
  try {
    const [resInt, resExt] = await Promise.all([
      fetch('data/lineas.json'),
      fetch('data/exterior.json')
    ]);
    
    if (!resInt.ok || !resExt.ok) throw new Error("Error cargando archivos JSON");
    
    dbInt = await resInt.json();
    dbExt = await resExt.json();

    const lineasHTML = Object.keys(dbInt).map(id => 
      `<md-select-option value="${id}"><div slot="headline">${id}</div></md-select-option>`
    ).join('');

    if (get('int-linea')) get('int-linea').innerHTML = lineasHTML;
    if (get('ext-linea')) get('ext-linea').innerHTML = lineasHTML;

    // Generar números de coche de Huelva (315-334 y 400-409)
    const coches = [...Array(20).keys()].map(i => i + 315).concat([...Array(10).keys()].map(i => i + 400));
    if (get('ext-coche')) {
      get('ext-coche').innerHTML = coches.map(c => 
        `<md-select-option value="${c}"><div slot="headline">${c}</div></md-select-option>`
      ).join('');
    }

  } catch (err) {
    console.error("Error cargando DB:", err);
  } finally {
    const splash = get('loading-screen');
    if (splash) {
      splash.style.opacity = '0';
      setTimeout(() => {
        splash.style.display = 'none';
        get('app').style.display = 'flex';
      }, 500);
    }
  }
}

// --- 2. MOTOR DE AUDIO ---
function play(cola, volId = 'vol') {
  if (audioActual) { audioActual.pause(); audioActual.currentTime = 0; }
  if (!cola || cola.length === 0) return;

  const item = cola.shift();
  audioActual = new Audio(`${item.file}?cb=${Date.now()}`);
  
  // Usar el slider correspondiente (interior o exterior)
  const slider = get(volId);
  audioActual.volume = slider ? slider.value : 0.8;
  
  audioActual.play().catch(e => console.warn("Audio no encontrado:", item.file));
  audioActual.onended = () => setTimeout(() => play(cola, volId), item.gap || 400);
}

// --- 3. EVENTOS PANEL INTERIOR ---
get('int-linea')?.addEventListener('change', (e) => {
  const linea = dbInt[e.target.value];
  const selParada = get('int-parada');
  if (linea && selParada) {
    selParada.innerHTML = linea.paradas.map(p => 
      `<md-select-option value="${p.id}"><div slot="headline">${p.nombre}</div></md-select-option>`
    ).join('');
    selParada.disabled = false;
    selParada.value = "";
  }
  get('container-regulacion').style.display = 'none';
});

get('int-parada')?.addEventListener('change', (e) => {
  const paradasReg = ['zafra', 'orden_baja', 'hospital_jrj'];
  const esReg = paradasReg.includes(e.target.value);
  get('container-regulacion').style.display = esReg ? 'flex' : 'none';
  if (!esReg) get('chk-regulacion').checked = false;
});

get('btn-int')?.addEventListener('click', () => {
  const lId = get('int-linea').value, pId = get('int-parada').value;
  if (!lId || !pId) return;

  const paradaData = dbInt[lId].paradas.find(p => p.id === pId);
  const tipo = document.querySelector('md-radio[value="siguiente"]')?.checked ? "siguiente" : "actual";

  let cola = [
    { file: `audio/parada_${tipo}.wav`, gap: 400 },
    { file: `audio/${pId}.wav`, gap: 600 }
  ];

  if (paradaData.enlaces?.length > 0) {
    const enlaces = paradaData.enlaces.filter(en => en.trim() !== "");
    if (enlaces.includes("todas")) {
      cola.push({ file: `audio/correspondencia_todas_las_lineas.wav`, gap: 400 });
    } else if (enlaces.length > 0) {
      cola.push({ file: `audio/${enlaces.length === 1 ? 'correspondencia_linea' : 'correspondencia_lineas'}.wav`, gap: 300 });
      enlaces.forEach(en => cola.push({ file: `audio/linea_${en}.wav`, gap: 300 }));
    }
  }

  if (get('chk-regulacion')?.checked) cola.push({ file: `audio/parada_regulacion.wav`, gap: 400 });
  play(cola, 'vol');
});

// --- 4. LÓGICA EXTERIOR (RESTAURADA) ---
get('btn-abrir-exterior').onclick = () => get('dialog-exterior').show();

get('ext-linea')?.addEventListener('change', (e) => {
  const lineaId = e.target.value;
  const destinos = dbExt.lineas[lineaId]?.destinos || [];
  const selDest = get('ext-destino');
  if (selDest) {
    selDest.innerHTML = destinos.map(d => `<md-select-option value="${d}"><div slot="headline">${d}</div></md-select-option>`).join('');
    selDest.disabled = false;
  }
});

get('btn-reproducir-ext')?.addEventListener('click', () => {
  const linea = get('ext-linea').value;
  const destino = get('ext-destino').value;
  const coche = get('ext-coche').value;

  if (!linea || !destino || !coche) return;

  const destFile = destino.toLowerCase().replace(/ /g, "_");
  
  // Cola exterior: Línea X -> Autobús XXX -> Destino YYY
  const colaExt = [
    { file: `audio/exterior/linea_${linea}.wav`, gap: 300 },
    { file: `audio/exterior/autobus_${coche}.wav`, gap: 500 },
    { file: `audio/exterior/destino_${destFile}.wav`, gap: 300 }
  ];

  play(colaExt, 'vol-ext');
});

// --- 5. ESPECIALES ---
get('btn-colision').onclick = () => play([{ file: `audio/colision.wav` }]);
get('btn-hora').onclick = () => play([{ file: `audio/hora_salida.wav` }]);
get('btn-saldo').onclick = () => play([{ file: `audio/atencion_saldo.wav` }]);
get('btn-insuficiente').onclick = () => play([{ file: `audio/saldo_insuficiente.wav` }]);

init();