import '@material/web/all.js';
import "@fontsource/roboto";

let dbInt = {}, dbExt = {};
let audio = null;
const get = (id) => document.getElementById(id);

async function init() {
  try {
    const [rI, rE] = await Promise.all([
      fetch('/data/lineas.json'), 
      fetch('/data/exterior.json')
    ]);
    dbInt = await rI.json();
    dbExt = await rE.json();

    // 1. Rellenar Líneas (Interior y Exterior)
    const lineas = Object.keys(dbInt);
    const opts = lineas.map(id => `<md-select-option value="${id}"><div slot="headline">${id}</div></md-select-option>`).join('');
    
    if(get('int-linea')) get('int-linea').innerHTML = opts;
    if(get('ext-linea')) get('ext-linea').innerHTML = opts;

    // 2. Generar Coches
    let coches = [];
    for (let i = 315; i <= 334; i++) coches.push(i);
    for (let i = 400; i <= 409; i++) coches.push(i);
    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 (e) { 
    console.error("Error cargando TsSAEx:", e); 
  }
  
  // Quitar Splash
  setTimeout(() => {
    const splash = get('loading-screen');
    if(splash) splash.style.opacity = '0';
    setTimeout(() => {
      if(splash) splash.style.display = 'none';
      const app = get('app');
      if(app) app.style.display = 'flex';
    }, 500);
  }, 2000);
}

// REPRODUCTOR
function play(lista, volumen) {
  if (audio) { audio.pause(); audio.currentTime = 0; }
  if (!lista || lista.length === 0) return;
  const file = lista.shift();
  audio = new Audio(`${file}?t=${Date.now()}`);
  audio.volume = volumen;
  audio.play().catch(() => play(lista, volumen));
  audio.onended = () => play(lista, volumen);
}

// --- EVENTO CLAVE: CAMBIO DE LÍNEA INTERIOR ---
get('int-linea')?.addEventListener('change', (e) => {
  const lineaSeleccionada = e.target.value;
  const paradas = dbInt[lineaSeleccionada] || [];
  const selectorParadas = get('int-parada');

  if (selectorParadas) {
    // Insertar nuevas paradas
    selectorParadas.innerHTML = paradas.map(p => 
      `<md-select-option value="${p.id}"><div slot="headline">${p.nombre}</div></md-select-option>`
    ).join('');
    
    // IMPORTANTE: Resetear valor y habilitar
    selectorParadas.value = ""; 
    selectorParadas.disabled = false;
  }
});

// BOTÓN ANUNCIAR
get('btn-int')?.addEventListener('click', () => {
  const lineaId = get('int-linea').value;
  const paradaId = get('int-parada').value;
  const tipo = document.querySelector('md-radio[name="tipo"][checked]')?.value || "actual";
  
  if(!lineaId || !paradaId) return alert("Selecciona línea y parada");

  const p = dbInt[lineaId]?.find(x => x.id === paradaId);
  if (!p) return;

  let cola = [`/audio/parada_${tipo}.wav`, `/audio/${p.id}.wav` ];
  if (p.enlaces?.length > 0) {
    cola.push(`/audio/correspondencia.wav`);
    p.enlaces.includes("todas") ? cola.push(`/audio/todas_las_lineas.wav`) : p.enlaces.forEach(e => cola.push(`/audio/linea_${e}.wav`));
  }
  play(cola, get('vol').value);
});

// LOGICA EXTERIOR (POPUP)
get('btn-abrir-exterior').onclick = () => get('dialog-exterior').show();

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

get('btn-reproducir-ext').onclick = () => {
  const c = get('ext-coche').value, l = get('ext-linea').value, d = get('ext-destino').value;
  if (!c || !l || !d) return;
  const destFile = d.toLowerCase().replace(/ /g, "_");
  play(['/audio/linea.wav', `/audio/${l}.wav`, '/audio/autobus.wav', `/audio/${c}.wav`, '/audio/destino.wav', `/audio/${destFile}.wav`], get('vol-ext').value);
};

// BOTONES ESPECIALES
get('btn-colision').onclick = () => play(['/audio/colision.wav'], get('vol').value);
get('btn-hora').onclick = () => play(['/audio/hora_salida.wav'], get('vol').value);
get('btn-saldo').onclick = () => play(['/audio/atencion_saldo.wav'], get('vol').value);
get('btn-insuficiente').onclick = () => play(['/audio/saldo_insuficiente.wav'], get('vol').value);

init();