{% extends "base.html" %}
{% set active = "upload" %}

{% block title %}Berita Acara Sidang #{{ ba_id }}{% endblock %}
{% block page_title %}Berita Acara Sidang{% endblock %}

{% block topbar_extra %}
<span style="color:var(--muted);font-size:.82rem">Task #{{ task_id }} · BA #{{ ba_id }}</span>
{% endblock %}

{% block extra_head %}
<style>
  .ba-layout {
    display: grid;
    grid-template-columns: 1fr 280px;
    gap: 20px;
    align-items: start;
  }
  @media (max-width: 960px) { .ba-layout { grid-template-columns: 1fr; } }

  .ba-toolbar {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 16px;
    flex-wrap: wrap;
  }
  .ba-toolbar-title { flex: 1; }
  #ba-title-input {
    font-family: 'Sora', sans-serif;
    font-size: 1rem;
    font-weight: 700;
    background: transparent;
    border: none;
    border-bottom: 1px dashed var(--border);
    color: var(--text);
    width: 100%;
    outline: none;
    padding: 2px 4px;
  }
  #ba-title-input:focus {
    border-bottom-color: var(--accent);
    background: rgba(88,166,255,.04);
  }

  .qa-list { width: 100%; }
  .qa-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
    border-bottom: 1px solid var(--border2);
    padding: 12px 0;
    align-items: start;
  }
  .qa-row.dragging { opacity: 0.4; }
  .qa-row.drag-over { background: rgba(88,166,255,.05); border-radius: 6px; }

  .qa-cell { display: flex; gap: 8px; align-items: flex-start; }
  .drag-handle {
    cursor: grab;
    color: var(--border);
    padding-top: 4px;
    flex-shrink: 0;
    font-size: 14px;
  }
  .drag-handle:hover { color: var(--muted); }
  .qa-cell-inner {
    flex: 1;
    min-height: 48px;
    font-size: .875rem;
    line-height: 1.6;
    color: var(--text);
    outline: none;
    border-radius: 4px;
    padding: 4px 6px;
    white-space: pre-wrap;
    word-break: break-word;
  }
  .qa-cell-inner:focus {
    background: rgba(88,166,255,.06);
    box-shadow: inset 0 0 0 1px rgba(88,166,255,.3);
  }
  .qa-cell-inner.question { font-weight: 500; }
  .qa-cell-inner.answer { color: var(--muted); }
  .qa-cell-inner.answer:focus { color: var(--text); }

  .qa-actions { display: flex; justify-content: flex-end; align-items: center; gap: 8px; }
  .btn-del-row {
    background: none; border: none;
    color: var(--border); cursor: pointer;
    padding: 5px; border-radius: 4px;
  }
  .btn-del-row:hover { color: var(--danger); background: rgba(248,81,73,.1); }

  .btn-add-row {
    display: flex; align-items: center; gap: 7px;
    margin-top: 16px; padding: 10px 14px;
    background: none; border: 1px dashed var(--border);
    color: var(--muted); border-radius: var(--radius-sm);
    font-size: .83rem; font-weight: 500;
    cursor: pointer; width: 100%; justify-content: center;
  }
  .btn-add-row:hover { border-color: var(--accent); color: var(--accent); background: rgba(88,166,255,.04); }
  .qa-empty { text-align: center; padding: 48px 20px; color: var(--muted); }

  .qa-header {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
    padding: 8px 0 12px;
    border-bottom: 1px solid var(--border);
    font-size: .72rem; font-weight: 600;
    text-transform: uppercase; letter-spacing: .8px; color: var(--muted);
  }
  .qa-header span:first-child { padding-left: 28px; }

  .ba-loading { text-align: center; padding: 80px 20px; }
  .ba-spinner {
    width: 44px; height: 44px;
    border: 3px solid var(--border);
    border-top-color: var(--accent);
    border-radius: 50%;
    animation: spin .8s linear infinite;
    margin: 0 auto 20px;
  }
  @keyframes spin { to { transform: rotate(360deg); } }

  .meta-item {
    display: flex; justify-content: space-between;
    padding: 10px 0; border-bottom: 1px solid var(--border2);
    font-size: .84rem; gap: 12px;
  }
  .meta-item:last-child { border-bottom: none; }
  .meta-key { color: var(--muted); white-space: nowrap; }
  .meta-val { font-weight: 500; text-align: right; word-break: break-all; }

  .modal-overlay {
    display: none; position: fixed; inset: 0;
    background: rgba(0,0,0,.6); z-index: 200;
    align-items: center; justify-content: center; padding: 20px;
  }
  .modal-overlay.show { display: flex; }
  .modal-box {
    background: var(--surface); border: 1px solid var(--border);
    border-radius: var(--radius); width: 100%; max-width: 720px;
    max-height: 80vh; display: flex; flex-direction: column;
  }
  .modal-header {
    display: flex; align-items: center; justify-content: space-between;
    padding: 16px 20px; border-bottom: 1px solid var(--border);
  }
  .modal-title { font-family: 'Sora', sans-serif; font-size: .9rem; font-weight: 700; }
  .modal-close { background: none; border: none; color: var(--muted); cursor: pointer; padding: 4px; }
  .modal-close:hover { color: var(--text); }
  .modal-body { padding: 16px 20px; overflow-y: auto; flex: 1; }
  .copy-options { display: flex; gap: 8px; margin-bottom: 14px; flex-wrap: wrap; }
  .copy-opt-btn {
    padding: 6px 14px; background: var(--surface2);
    border: 1px solid var(--border); color: var(--muted);
    border-radius: var(--radius-sm); font-size: .8rem; cursor: pointer;
  }
  .copy-opt-btn.active, .copy-opt-btn:hover {
    border-color: var(--accent); color: var(--accent); background: rgba(88,166,255,.06);
  }
  .copy-preview {
    background: var(--bg); border: 1px solid var(--border);
    border-radius: var(--radius-sm); padding: 14px;
    font-size: .82rem; line-height: 1.4; white-space: pre-wrap;
    font-family: 'Courier New', monospace; max-height: 300px; overflow-y: auto;
  }
  .modal-footer {
    display: flex; justify-content: flex-end; gap: 8px;
    padding: 14px 20px; border-top: 1px solid var(--border);
  }
  .save-dot {
    display: inline-block; width: 7px; height: 7px;
    border-radius: 50%; background: var(--border);
    margin-right: 5px; transition: background .3s;
  }
  .save-dot.unsaved { background: var(--warning); }
  .save-dot.saved   { background: var(--success); }
  .toast {
    position: fixed; bottom: 24px; right: 24px;
    background: var(--surface); border: 1px solid var(--border);
    border-radius: var(--radius-sm); padding: 11px 18px;
    font-size: .84rem; font-weight: 500;
    box-shadow: 0 6px 24px rgba(0,0,0,.3);
    z-index: 500; display: flex; gap: 8px; animation: fadeUp .3s ease;
  }
  .toast.success { border-left: 3px solid var(--success); }
  .toast.error   { border-left: 3px solid var(--danger); }
  @keyframes fadeUp {
    from { opacity:0; transform:translateY(16px); }
    to   { opacity:1; transform:translateY(0); }
  }
</style>
{% endblock %}

{% block content %}
<div class="ba-layout">
  <div>
    <div class="ba-toolbar">
      <div class="ba-toolbar-title">
        <input type="text" id="ba-title-input" value="Berita Acara Sidang" maxlength="120" />
      </div>
      <button class="btn btn-ghost btn-sm" onclick="openCopyModal()">📋 Salin</button>
      <button class="btn btn-ghost btn-sm" onclick="downloadDoc()">⬇️ Unduh</button>
      <button class="btn btn-primary btn-sm" onclick="saveChanges()" id="btn-save">
        <span class="save-dot" id="save-dot"></span> Simpan
      </button>
    </div>

    <div class="card">
      <div class="ba-loading" id="state-loading"><div class="ba-spinner"></div><div>Memproses...</div></div>
      <div class="ba-loading" id="state-pending" style="display:none"><div class="ba-spinner"></div><div>Menunggu antrian...</div></div>
      <div id="state-error" style="display:none; padding:24px">
        <div class="alert alert-danger"><div id="error-msg"></div></div>
        <button class="btn btn-ghost" onclick="retryProcess()">🔄 Coba Lagi</button>
      </div>
      <div id="state-editor" style="display:none">
        <div class="qa-header">
          <span>PERTANYAAN</span>
          <span>JAWABAN</span>
        </div>
        <div id="qa-list-container" class="qa-list"></div>
        <button class="btn-add-row" onclick="addRow()">+ Tambah Pasangan</button>
      </div>
    </div>
  </div>

  <div>
    <div class="card" style="margin-bottom:14px">
      <div class="card-header">Detail</div>
      <div class="meta-item"><span class="meta-key">Task ID</span><span class="meta-val"><a href="/transkripsi/status/{{ task_id }}">#{{ task_id }}</a></span></div>
      <div class="meta-item"><span class="meta-key">BA ID</span><span class="meta-val">#{{ ba_id }}</span></div>
      <div class="meta-item"><span class="meta-key">Status</span><span id="meta-status" class="meta-val">—</span></div>
      <div class="meta-item"><span class="meta-key">Model</span><span id="meta-model" class="meta-val">—</span></div>
      <div class="meta-item"><span class="meta-key">Waktu Proses</span><span id="meta-proctime" class="meta-val">—</span></div>
      <div class="meta-item"><span class="meta-key">Jumlah Q&A</span><span id="meta-count" class="meta-val">—</span></div>
      <div class="meta-item"><span class="meta-key">Dibuat</span><span id="meta-created" class="meta-val">—</span></div>
    </div>
    <div class="card">
      <div class="card-header">Aksi</div>
      <div style="display:flex; flex-direction:column; gap:8px; padding-top:4px">
        <button class="btn btn-ghost" onclick="openCopyModal()">📋 Salin ke Clipboard</button>
        <button class="btn btn-ghost" onclick="downloadDoc()">📄 Unduh TXT</button>
        <a href="/transkripsi/status/{{ task_id }}" class="btn btn-ghost">← Kembali ke Transkripsi</a>
        <hr>
        <button class="btn btn-sm" onclick="confirmDelete()" style="background:rgba(248,81,73,.08);color:var(--danger);">🗑 Hapus Berita Acara</button>
      </div>
    </div>
  </div>
</div>

<!-- Copy Modal -->
<div class="modal-overlay" id="copy-modal">
  <div class="modal-box">
    <div class="modal-header"><span class="modal-title">Salin Dokumen</span><button class="modal-close" onclick="closeCopyModal()">✕</button></div>
    <div class="modal-body">
      <div class="copy-options">
        <button class="copy-opt-btn" data-format="table">📊 Tabel (Excel/Word)</button>
        <button class="copy-opt-btn" data-format="qa">📝 Pertanyaan & Jawaban</button>
        <button class="copy-opt-btn" data-format="q">❓ Pertanyaan saja</button>
        <button class="copy-opt-btn" data-format="a">💬 Jawaban saja</button>
      </div>
      <pre class="copy-preview" id="copy-preview"></pre>
    </div>
    <div class="modal-footer">
      <button class="btn btn-ghost" onclick="closeCopyModal()">Batal</button>
      <button class="btn btn-primary" id="copy-exec-btn">Salin ke Clipboard</button>
    </div>
  </div>
</div>
{% endblock %}

{% block scripts %}
<script>
  const BA_ID   = {{ ba_id }};
  const TASK_ID = {{ task_id }};

  let qaData      = [];
  let isDirty     = false;
  let pollTimer   = null;
  let copyFormat  = 'table';
  let dragSrcIdx  = null;

  async function poll() {
    try {
      const r = await fetch(`/api/berita-acara/${BA_ID}`);
      if (!r.ok) { showState('error', 'Gagal memuat data.'); return; }
      const d = await r.json();
      updateMeta(d);
      if (d.status === 'pending') showState('pending');
      else if (d.status === 'processing') showState('loading');
      else if (d.status === 'completed') {
        clearInterval(pollTimer);
        const titleInput = document.getElementById('ba-title-input');
        if(titleInput) titleInput.value = d.title || 'Berita Acara Sidang';
        qaData = d.qa_list || [];
        renderQA();
        showState('editor');
      } else if (d.status === 'failed') {
        clearInterval(pollTimer);
        showState('error', d.error_message || 'Terjadi kesalahan.');
      }
    } catch(e) { console.warn(e); }
  }

  function showState(name, errMsg) {
    const ids = ['state-loading', 'state-pending', 'state-error', 'state-editor'];
    ids.forEach(id => {
      const el = document.getElementById(id);
      if(el) el.style.display = 'none';
    });
    const target = document.getElementById(`state-${name}`);
    if(target) target.style.display = 'block';
    if(name === 'error' && errMsg) {
      const errEl = document.getElementById('error-msg');
      if(errEl) errEl.innerText = errMsg;
    }
  }

  function updateMeta(d) {
    const badge = { pending:'Menunggu', processing:'Diproses', completed:'Selesai', failed:'Gagal' };
    const statusEl = document.getElementById('meta-status');
    if(statusEl) statusEl.innerHTML = `<span class="badge badge-${d.status}">${badge[d.status]}</span>`;
    const modelEl = document.getElementById('meta-model');
    if(modelEl) modelEl.innerText = d.model_used || '—';
    const procEl = document.getElementById('meta-proctime');
    if(procEl) procEl.innerText = d.processing_time ? d.processing_time + 's' : '—';
    const countEl = document.getElementById('meta-count');
    if(countEl) countEl.innerText = (qaData.length || d.qa_list?.length || 0) + ' pasang';
    const createdEl = document.getElementById('meta-created');
    if(createdEl) createdEl.innerText = d.created_at ? new Date(d.created_at).toLocaleString('id-ID') : '—';
  }

  function renderQA() {
    const container = document.getElementById('qa-list-container');
    if (!container) return;
    container.innerHTML = '';
    if (qaData.length === 0) {
      container.innerHTML = '<div class="qa-empty">Belum ada pasangan tanya-jawab. Klik tombol "Tambah Pasangan" untuk menambahkan.</div>';
      return;
    }

    qaData.forEach((item, idx) => {
      const row = document.createElement('div');
      row.className = 'qa-row';
      row.draggable = true;
      row.dataset.idx = idx;

      const leftCol = document.createElement('div');
      leftCol.className = 'qa-cell';
      leftCol.innerHTML = `
        <div class="drag-handle" title="Geser">⋮⋮</div>
        <div class="qa-cell-inner question" contenteditable="true" data-field="question" data-idx="${idx}">${escapeHtml(item.question)}</div>
      `;
      const rightCol = document.createElement('div');
      rightCol.className = 'qa-cell';
      rightCol.style.display = 'flex';
      rightCol.style.gap = '8px';
      rightCol.style.alignItems = 'flex-start';
      rightCol.innerHTML = `
        <div class="qa-cell-inner answer" contenteditable="true" data-field="answer" data-idx="${idx}" style="flex:1">${escapeHtml(item.answer)}</div>
        <button class="btn-del-row" onclick="deleteRow(${idx})" title="Hapus">✕</button>
      `;

      row.appendChild(leftCol);
      row.appendChild(rightCol);

      row.addEventListener('dragstart', onDragStart);
      row.addEventListener('dragover', onDragOver);
      row.addEventListener('dragleave', onDragLeave);
      row.addEventListener('drop', onDrop);
      row.addEventListener('dragend', onDragEnd);

      container.appendChild(row);
    });

    document.querySelectorAll('[contenteditable]').forEach(el => {
      el.removeEventListener('input', handleContentEdit);
      el.addEventListener('input', handleContentEdit);
      el.addEventListener('keydown', e => { if (e.key === 'Enter' && !e.shiftKey) e.preventDefault(); });
    });
  }

  function handleContentEdit(e) {
    const el = e.target;
    const idx = parseInt(el.dataset.idx);
    const field = el.dataset.field;
    if (qaData[idx] && field) {
      qaData[idx][field] = el.innerText.trim();
      markDirty();
    }
  }

  function escapeHtml(str) {
    return String(str).replace(/[&<>]/g, function(m){
      if(m==='&') return '&amp;';
      if(m==='<') return '&lt;';
      if(m==='>') return '&gt;';
      return m;
    });
  }

  function onDragStart(e) { dragSrcIdx = parseInt(this.dataset.idx); this.classList.add('dragging'); e.dataTransfer.effectAllowed = 'move'; }
  function onDragOver(e) { e.preventDefault(); e.dataTransfer.dropEffect = 'move'; this.classList.add('drag-over'); }
  function onDragLeave() { this.classList.remove('drag-over'); }
  function onDrop(e) {
    e.preventDefault();
    const destIdx = parseInt(this.dataset.idx);
    if (dragSrcIdx === null || dragSrcIdx === destIdx) return;
    const [moved] = qaData.splice(dragSrcIdx, 1);
    qaData.splice(destIdx, 0, moved);
    qaData.forEach((item, i) => item.id = i+1);
    renderQA();
    markDirty();
  }
  function onDragEnd() { document.querySelectorAll('.qa-row').forEach(r => r.classList.remove('dragging','drag-over')); dragSrcIdx = null; }

  function addRow() { qaData.push({ id: qaData.length+1, question: '', answer: '' }); renderQA(); markDirty(); }
  function deleteRow(idx) { if(confirm('Hapus baris ini?')){ qaData.splice(idx,1); qaData.forEach((item,i)=>item.id=i+1); renderQA(); markDirty(); } }

  function markDirty() {
    if(!isDirty){ isDirty=true; const d=document.getElementById('save-dot'); if(d) d.className='save-dot unsaved'; }
  }
  function markSaved() {
    isDirty=false; const d=document.getElementById('save-dot'); if(d){ d.className='save-dot saved'; setTimeout(()=>{ if(d) d.className='save-dot'; },2000); }
  }

  async function saveChanges() {
    const btn=document.getElementById('btn-save'); if(!btn) return;
    btn.disabled=true; const orig=btn.innerHTML; btn.innerHTML='⏳ Menyimpan...';
    try {
      const r=await fetch(`/api/berita-acara/${BA_ID}`,{
        method:'PATCH', headers:{'Content-Type':'application/json'},
        body:JSON.stringify({ title:document.getElementById('ba-title-input').value.trim(), qa_list:qaData })
      });
      const d=await r.json();
      if(!r.ok) throw new Error(d.detail);
      markSaved(); showToast('Tersimpan!','success');
    } catch(e){ showToast('Gagal: '+e.message,'error'); }
    finally{ btn.disabled=false; btn.innerHTML=orig; }
  }

  document.getElementById('ba-title-input').addEventListener('input',markDirty);

  // ── buildHtmlTable: tanpa border, font Arial 12pt italic, pertanyaan kiri atas & jawaban kanan bawah ──
  function buildHtmlTable() {
    const title = document.getElementById('ba-title-input').value.trim();
    const cellBase = 'font-family:Arial; font-size:12pt; font-style:italic; border:none; vertical-align:top; width:50%;';
    let rows = '';
    qaData.forEach(item => {
      rows += `
        <tr>
          <td style="${cellBase} padding:6px 12px 2px 0;">${escapeHtml(item.question)}</td>
          <td style="${cellBase}"></td>
        </tr>
        <tr>
          <td style="${cellBase}"></td>
          <td style="${cellBase} padding:2px 0 16px 12px;">${escapeHtml(item.answer)}</td>
        </tr>
      `;
    });
    return `<html>
    <body style="font-family:Arial; font-size:12pt; font-style:italic;">
      <h3 style="font-family:Arial; font-size:12pt; font-style:italic;">${escapeHtml(title)}</h3>
      <table style="border-collapse:collapse; border:none; width:100%;">
        <tbody>${rows}</tbody>
      </table>
    </body>
    </html>`;
  }

  function buildCopyText(fmt) {
    const title = document.getElementById('ba-title-input').value.trim();
    let lines = [];
    if (fmt === 'table') {
      lines.push(title);
      lines.push('='.repeat(60));
      qaData.forEach(item => {
        lines.push(`${item.question}\t${item.answer}`);
      });
    } else if (fmt === 'qa') {
      qaData.forEach(item => {
        lines.push(`P: ${item.question}`);
        lines.push(`J: ${item.answer}`);
        lines.push('');
      });
    } else if (fmt === 'q') {
      qaData.forEach((item,i) => lines.push(`${i+1}. ${item.question}`));
    } else if (fmt === 'a') {
      qaData.forEach((item,i) => lines.push(`${i+1}. ${item.answer}`));
    }
    return lines.join('\n');
  }

  function openCopyModal() {
    const modal = document.getElementById('copy-modal');
    if(!modal) return;
    document.querySelectorAll('.copy-opt-btn').forEach(btn => {
      btn.classList.remove('active');
      if(btn.dataset.format === copyFormat) btn.classList.add('active');
    });
    const preview = document.getElementById('copy-preview');
    if(preview) preview.innerText = buildCopyText(copyFormat);
    modal.classList.add('show');
  }
  function closeCopyModal() {
    const modal = document.getElementById('copy-modal');
    if(modal) modal.classList.remove('show');
  }
  function setCopyFormat(fmt) {
    copyFormat = fmt;
    document.querySelectorAll('.copy-opt-btn').forEach(btn => {
      btn.classList.remove('active');
      if(btn.dataset.format === fmt) btn.classList.add('active');
    });
    const preview = document.getElementById('copy-preview');
    if(preview) preview.innerText = buildCopyText(fmt);
  }
  async function execCopy() {
    const plainText = buildCopyText(copyFormat);
    let htmlText = '';
    if (copyFormat === 'table') {
      htmlText = buildHtmlTable();
    } else {
      htmlText = plainText.replace(/\n/g, '<br>');
    }
    try {
      const clipboardItem = new ClipboardItem({
        'text/plain': new Blob([plainText], { type: 'text/plain' }),
        'text/html': new Blob([htmlText], { type: 'text/html' })
      });
      await navigator.clipboard.write([clipboardItem]);
      showToast('✅ Disalin ke clipboard! (Tabel siap untuk Word/Excel)', 'success');
      closeCopyModal();
    } catch(err) {
      await navigator.clipboard.writeText(plainText);
      showToast('✅ Disalin sebagai teks biasa', 'success');
      closeCopyModal();
    }
  }

  document.querySelectorAll('.copy-opt-btn').forEach(btn => {
    btn.addEventListener('click', () => { setCopyFormat(btn.dataset.format); });
  });
  const copyExecBtn = document.getElementById('copy-exec-btn');
  if(copyExecBtn) copyExecBtn.addEventListener('click', execCopy);

  function downloadDoc() {
    const lines = buildCopyText('table').split('\n');
    const blob = new Blob([lines.join('\n')], {type:'text/plain'});
    const a=document.createElement('a'); a.href=URL.createObjectURL(blob); a.download=`berita-acara-${BA_ID}.txt`; a.click(); URL.revokeObjectURL(a.href);
  }

  async function confirmDelete() {
    if(confirm('Hapus Berita Acara permanen?')){
      const r=await fetch(`/api/berita-acara/${BA_ID}`,{method:'DELETE'});
      if(r.ok) { showToast('Berita Acara dihapus.','success'); setTimeout(()=>window.location.href=`/transkripsi/status/${TASK_ID}`,1200); }
      else { const d=await r.json(); showToast(d.detail||'Gagal','error'); }
    }
  }
  async function retryProcess() {
    const r=await fetch('/api/berita-acara',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({task_id:TASK_ID})});
    if(r.ok){ const d=await r.json(); window.location.href=`/berita-acara/${d.ba_id}?task_id=${TASK_ID}`; }
    else showToast('Gagal membuat ulang BA','error');
  }

  let toastTimer=null;
  function showToast(msg,type){
    const t=document.createElement('div'); t.className='toast '+type; t.innerText=msg;
    document.body.appendChild(t);
    if(toastTimer) clearTimeout(toastTimer);
    toastTimer=setTimeout(()=>t.remove(),3000);
  }

  window.addEventListener('beforeunload',e=>{ if(isDirty){ e.preventDefault(); e.returnValue=''; } });

  poll(); pollTimer=setInterval(poll,3000);
</script>
{% endblock %}