document.addEventListener('DOMContentLoaded', () => {
  // PDF.js worker
  pdfjsLib.GlobalWorkerOptions.workerSrc =
    chrome.runtime.getURL('libs/pdf.worker.js');

  const fileInput   = document.getElementById('fileInput');
  const uploadArea  = document.getElementById('uploadArea');
  const btnTxt      = document.getElementById('btnTranscribeTxt');
  const btnJson     = document.getElementById('btnTranscribeJson');
  const btnLog      = document.getElementById('btnExportLog');
  const progressBar = document.getElementById('progressBar');
  const progressFill= document.getElementById('progressFill');
  const progressText= document.getElementById('progressText');
  const spinner     = document.getElementById('spinner');
  const accordions  = document.getElementById('resultsAccordions');
  const logContent  = document.getElementById('logContent');

  // Toast
  function showToast(msg, type='info') {
    const t = document.createElement('div');
    t.className = `toast ${type}`; t.textContent = msg;
    document.getElementById('toast-container').append(t);
    setTimeout(() => t.remove(), 3000);
  }

  // Log
  function log(msg, type='info') {
    const e = document.createElement('div');
    e.className = 'log-entry '+type;
    e.textContent = `[${new Date().toLocaleTimeString()}] ${msg}`;
    logContent.appendChild(e);
    logContent.scrollTop = logContent.scrollHeight;
  }

  // Progress UI
  function showProgress(pct, page, total) {
    progressBar.style.display = 'block';
    progressFill.style.width = pct + '%';
    progressText.textContent = page && total
      ? `Page ${page} / ${total} • ${Math.round(pct)}%`
      : `${Math.round(pct)}%`;
  }
  function hideProgress() {
    progressBar.style.display = 'none';
    progressText.textContent = '';
  }

  // Spinner
  function toggleSpinner(show) {
    spinner.hidden = !show;
  }

  // Download helper
  function downloadFile(name, content, type) {
    const blob = new Blob([content], { type });
    const url  = URL.createObjectURL(blob);
    const a    = document.createElement('a');
    a.href     = url; a.download = name;
    document.body.appendChild(a);
    a.click(); a.remove(); URL.revokeObjectURL(url);
  }

  // 1) Transcrire un PDF entier
  async function transcribeSingle(file) {
    log(`Transcription ${file.name}`, 'success');
    toggleSpinner(true);
    const data = await file.arrayBuffer();
    const pdf  = await pdfjsLib.getDocument(data).promise;
    const pages= pdf.numPages;
    let fullText = '';
    for (let i = 1; i <= pages; i++) {
      const page   = await pdf.getPage(i);
      const txt    = (await page.getTextContent())
                     .items.map(it => it.str).join(' ');
      fullText    += `--- Page ${i} ---\n${txt}\n\n`;
      showProgress((i/pages)*100, i, pages);
      if (i % 5 === 0) await new Promise(r=>setTimeout(r,10));
    }
    hideProgress();
    toggleSpinner(false);
    showToast(`Terminé ${file.name}`, 'success');
    return fullText;
  }

  // 2) Catégoriser dynamiquement
  function categorizeSections(fullText) {
    const headingRe = /^([IVXLCDM0-9A-Za-z]+)\s*[-–—\.]?\s*(.+)$/gmu;
    const markers   = [];
    let match;
    while ((match = headingRe.exec(fullText)) !== null) {
      markers.push({
        key: match[1], title: match[2],
        start: match.index,
        endOfHeading: match.index + match[0].length
      });
    }
    const sections = [];
    // preamble
    if (markers.length && markers[0].start > 0) {
      sections.push({
        key: null,
        title: 'Preamble',
        content: fullText
          .slice(0, markers[0].start)
          .trim().split(/\r?\n/).filter(l=>l.trim())
      });
    }
    // each marker
    markers.forEach((m, i) => {
      const next = markers[i+1];
      const block = fullText
        .slice(m.endOfHeading, next? next.start: fullText.length)
        .trim();
      sections.push({
        key: m.key,
        title: m.title,
        content: block.split(/\r?\n/).filter(l=>l.trim())
      });
    });
    // postamble
    const last = markers[markers.length-1];
    if (last && last.endOfHeading < fullText.length) {
      const tail = fullText.slice(last.endOfHeading).trim();
      if (tail) {
        sections.push({
          key: null,
          title: 'Postamble',
          content: tail.split(/\r?\n/).filter(l=>l.trim())
        });
      }
    }
    return sections;
  }

  // MULTI-FICHIER drag/drop et input
  uploadArea.addEventListener('dragover', e => {
    e.preventDefault(); uploadArea.classList.add('dragover');
  });
  uploadArea.addEventListener('dragleave', e => {
    e.preventDefault(); uploadArea.classList.remove('dragover');
  });
  uploadArea.addEventListener('drop', e => {
    e.preventDefault(); uploadArea.classList.remove('dragover');
    fileInput.files = e.dataTransfer.files;
    showToast(`${fileInput.files.length} fichier(s) prêts`,'info');
  });
  fileInput.addEventListener('change', () => {
    showToast(`${fileInput.files.length} fichier(s) sélectionné(s)`,'info');
  });

  // BTN Transcrire TXT
  btnTxt.addEventListener('click', async () => {
    const files = Array.from(fileInput.files);
    if (!files.length) { showToast('Sélectionnez un PDF','error'); return; }
    let out = '';
    for (const f of files) {
      const text = await transcribeSingle(f);
      out += `=== ${f.name} ===\n${text}\n`;
    }
    downloadFile('transcription.txt', out, 'text/plain');
  });

  // BTN Transcrire JSON structuré
  btnJson.addEventListener('click', async () => {
    const files = Array.from(fileInput.files);
    if (!files.length) { showToast('Sélectionnez un PDF','error'); return; }
    accordions.innerHTML = '';
    const result = [];
    for (const f of files) {
      const fullText = await transcribeSingle(f);
      const secs     = categorizeSections(fullText);
      result.push({ file: f.name, sections: secs, rawText: fullText });
      // bâtir un <details> pour chaque PDF
      const d = document.createElement('details');
      const s = document.createElement('summary');
      s.innerHTML = `${f.name} <span class="stats">Sections: ${secs.length}</span>` +
                    ` <button data-file="${f.name}" class="retry-btn">🔄</button>`;
      d.appendChild(s);
      const container = document.createElement('div');
      secs.forEach(sec => {
        const card = document.createElement('div');
        card.className = 'section-card';
        card.innerHTML = `<h4>${sec.key||''} ${sec.title}</h4>` +
                         `<ul>${sec.content.map(l=>`<li>${l}</li>`).join('')}</ul>`;
        container.appendChild(card);
      });
      d.appendChild(container);
      accordions.appendChild(d);
    }
    downloadFile(
      'transcription-structured.json',
      JSON.stringify(result, null, 2),
      'application/json'
    );
    showToast('JSON structuré téléchargé','success');
  });

  // BTN Export log
  btnLog.addEventListener('click', () => {
    downloadFile('journal.txt', logContent.innerText, 'text/plain');
    showToast('Journal téléchargé','success');
  });

  // Retry individuel
  accordions.addEventListener('click', async e => {
    if (e.target.classList.contains('retry-btn')) {
      const name = e.target.dataset.file;
      const f    = Array.from(fileInput.files).find(x=>x.name===name);
      if (!f) return;
      e.target.disabled = true;
      showToast(`Réessai ${name}`,'info');
      const fullText = await transcribeSingle(f);
      const secs     = categorizeSections(fullText);
      const details  = e.target.closest('details');
      const container= details.querySelector('div');
      container.innerHTML = '';
      secs.forEach(sec => {
        const card = document.createElement('div');
        card.className = 'section-card';
        card.innerHTML = `<h4>${sec.key||''} ${sec.title}</h4>` +
                         `<ul>${sec.content.map(l=>`<li>${l}</li>`).join('')}</ul>`;
        container.appendChild(card);
      });
      e.target.disabled = false;
      showToast(`Réessai ${name} OK`,'success');
    }
  });

});
