function render(key) {
  const t = TEMAS[key];
  const card = document.getElementById('card');
  const noTema = document.getElementById('no-tema');
  const footerBtns = document.getElementById('footer-btns');
  if (!t) { card.style.display='none'; noTema.style.display=''; footerBtns.style.display='none'; return; }
  document.title = key + '. ' + t.titulo.slice(0,60) + ' · TAI';
  document.getElementById('header-titulo').textContent = t.titulo;
  document.getElementById('header-badge').textContent = 'Bloque ' + t.bloque + ' · Tema ' + t.tema;
  document.getElementById('card-titulo').textContent = key + '. ' + t.titulo;
  document.getElementById('card-subtitulo').textContent = t.epigrafes.length + ' epígrafes';
  const ul = document.getElementById('card-lista');
  ul.innerHTML = '';

  const fileParts = t.file.split('/');
  const relPath = fileParts.slice(-2).join('/'); // 'bloqueN/temaN.md'
  const verUrl = 'ver.html?f=' + relPath + '&tema=' + key;

  let currentSubList = null;

  t.epigrafes.forEach(function(h) {
    const isMainSection = /^\d+\.\s/.test(h);

    if (isMainSection) {
      const li = document.createElement('li');
      li.className = 'seccion-principal';
      const details = document.createElement('details');
      const summary = document.createElement('summary');
      summary.textContent = h;
      details.appendChild(summary);
      currentSubList = document.createElement('ul');
      details.appendChild(currentSubList);
      li.appendChild(details);
      ul.appendChild(li);
    } else if (currentSubList) {
      const li = document.createElement('li');
      const a = document.createElement('a');
      a.href = verUrl;
      a.target = '_blank';
      a.textContent = h;
      li.appendChild(a);
      currentSubList.appendChild(li);
    } else {
      const li = document.createElement('li');
      const a = document.createElement('a');
      a.href = verUrl;
      a.target = '_blank';
      a.textContent = h;
      li.appendChild(a);
      ul.appendChild(li);
    }
  });
  document.getElementById('btn-md').href = verUrl;
  card.style.display = '';
  noTema.style.display = 'none';
  footerBtns.style.display = '';
  document.querySelectorAll('.nav-temas a').forEach(function(a) {
    a.classList.toggle('activo', a.dataset.key === key);
  });
}

function buildNav() {
  const nav = document.getElementById('nav-temas');
  [1,2,3,4].forEach(function(b) {
    Object.keys(TEMAS).filter(k => TEMAS[k].bloque === b).sort().forEach(function(key) {
      const a = document.createElement('a');
      a.href = '?tema=' + key;
      a.textContent = key;
      a.dataset.key = key;
      nav.appendChild(a);
    });
  });
}

buildNav();
const temaParam = new URLSearchParams(window.location.search).get('tema');
if (temaParam) render(temaParam);
