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

{% block title %}Beranda{% endblock %}
{% block page_title %}Beranda{% endblock %}

{% block extra_head %}
<style>
  .greeting { margin-bottom: 28px; }
  .greeting h2 {
    font-family: 'Sora', sans-serif;
    font-size: 1.4rem; font-weight: 700;
    letter-spacing: -.3px;
    margin-bottom: 4px;
  }
  .greeting p { color: var(--muted); font-size: .9rem; }

  .stats-row {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
    gap: 14px;
    margin-bottom: 24px;
  }
  .stat-card {
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    padding: 18px 20px;
    display: flex; align-items: center; gap: 14px;
    transition: border-color .2s;
  }
  .stat-card:hover { border-color: rgba(88,166,255,.3); }
  .stat-icon {
    width: 40px; height: 40px;
    border-radius: 9px;
    display: flex; align-items: center; justify-content: center;
    font-size: 18px;
    flex-shrink: 0;
  }
  .stat-icon.blue  { background: rgba(88,166,255,.12); }
  .stat-icon.green { background: rgba(63,185,80,.12); }
  .stat-icon.yellow { background: rgba(227,179,65,.12); }
  .stat-icon.red   { background: rgba(248,81,73,.12); }
  .stat-num {
    font-family: 'Sora', sans-serif;
    font-size: 1.6rem; font-weight: 800;
    line-height: 1;
    margin-bottom: 2px;
  }
  .stat-lbl { font-size: .78rem; color: var(--muted); }

  .quick-actions {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
    gap: 14px;
    margin-bottom: 28px;
  }
  .action-card {
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    padding: 22px;
    text-decoration: none;
    color: var(--text);
    display: flex; align-items: flex-start; gap: 14px;
    transition: all .2s;
    position: relative;
    overflow: hidden;
  }
  .action-card::after {
    content: '';
    position: absolute;
    bottom: 0; left: 0; right: 0;
    height: 2px;
    background: linear-gradient(90deg, var(--accent), var(--gold));
    opacity: 0;
    transition: opacity .2s;
  }
  .action-card:hover { border-color: rgba(88,166,255,.3); transform: translateY(-2px); }
  .action-card:hover::after { opacity: 1; }
  .action-icon {
    width: 44px; height: 44px;
    border-radius: 10px;
    display: flex; align-items: center; justify-content: center;
    font-size: 20px;
    flex-shrink: 0;
  }
  .action-icon.blue   { background: rgba(88,166,255,.1); }
  .action-icon.purple { background: rgba(149,117,205,.1); }
  .action-icon.gold   { background: rgba(212,160,23,.1); }
  .action-title {
    font-family: 'Sora', sans-serif;
    font-size: .9rem; font-weight: 700;
    margin-bottom: 4px;
  }
  .action-desc { font-size: .8rem; color: var(--muted); line-height: 1.5; }
  .action-arrow {
    margin-left: auto;
    color: var(--muted);
    align-self: center;
    flex-shrink: 0;
    transition: transform .2s;
  }
  .action-card:hover .action-arrow { transform: translateX(4px); color: var(--accent); }

  .row-2 {
    display: grid;
    grid-template-columns: 1fr 300px;
    gap: 16px;
  }
  @media (max-width: 900px) { .row-2 { grid-template-columns: 1fr; } }

  .empty-state {
    text-align: center;
    padding: 40px 20px;
    color: var(--muted);
  }
  .empty-state svg { margin: 0 auto 12px; opacity: .3; }
  .empty-state p { font-size: .875rem; }

  .task-row {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 12px;
    padding: 8px;
    border-radius: var(--radius-sm);
    background: var(--bg);
    transition: background .15s;
  }
  .task-row:hover { background: var(--surface2); }
  .task-info {
    flex: 1;
    min-width: 0;
  }
  .task-name {
    font-size: .85rem; font-weight: 600;
    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
  }
  .task-meta { font-size: .75rem; color: var(--muted); margin-top: 2px; }
  .task-actions {
    display: flex;
    gap: 6px;
    flex-shrink: 0;
    align-items: center;
  }
  .badge-ba {
    background: rgba(212,160,23,.15);
    color: var(--gold);
    font-size: .65rem;
    padding: 2px 6px;
    border-radius: 20px;
  }
  .pagination {
    display: flex;
    justify-content: center;
    gap: 8px;
    margin-top: 16px;
    flex-wrap: wrap;
  }
  .page-btn {
    padding: 6px 12px;
    background: var(--surface2);
    border: 1px solid var(--border);
    border-radius: var(--radius-sm);
    color: var(--text);
    cursor: pointer;
    font-size: .8rem;
    transition: all .15s;
  }
  .page-btn.active {
    background: var(--accent);
    border-color: var(--accent);
    color: white;
  }
  .page-btn:hover:not(.active) {
    border-color: var(--accent);
    color: var(--accent);
  }

  .info-item {
    display: flex; justify-content: space-between; align-items: center;
    padding: 10px 0;
    border-bottom: 1px solid var(--border2);
    font-size: .85rem;
  }
  .info-item:last-child { border-bottom: none; }
  .info-label { color: var(--muted); }
  .info-value { font-weight: 600; }

  /* Modal preview hasil transkripsi */
  .modal-backdrop {
    display: none;
    position: fixed; inset: 0;
    background: rgba(0,0,0,.7);
    z-index: 200;
    align-items: center;
    justify-content: center;
    padding: 20px;
  }
  .modal-backdrop.show { display: flex; }
  .modal-result {
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: 14px;
    padding: 24px;
    width: 100%;
    max-width: 640px;
    max-height: 80vh;
    display: flex;
    flex-direction: column;
    animation: modal-in .2s ease;
  }
  @keyframes modal-in {
    from { opacity: 0; transform: scale(.96) translateY(10px); }
    to   { opacity: 1; transform: scale(1) translateY(0); }
  }
  .modal-result-header {
    display: flex; align-items: center; justify-content: space-between;
    margin-bottom: 16px;
  }
  .modal-result-title { font-family: 'Sora', sans-serif; font-size: .95rem; font-weight: 700; }
  .modal-result-close {
    background: none; border: none;
    color: var(--muted); cursor: pointer; font-size: 1.2rem;
    padding: 2px 6px; border-radius: 4px; transition: all .15s;
  }
  .modal-result-close:hover { background: var(--surface2); color: var(--text); }
  .modal-result-body { flex: 1; overflow-y: auto; }
  .modal-result-textarea {
    width: 100%;
    background: var(--bg);
    border: 1px solid var(--border);
    color: var(--text);
    padding: 14px;
    border-radius: var(--radius-sm);
    font-family: 'DM Sans', sans-serif;
    font-size: .875rem;
    line-height: 1.8;
    resize: none;
    min-height: 260px;
    outline: none;
  }
  .modal-result-footer {
    display: flex; gap: 8px; justify-content: flex-end;
    margin-top: 14px; padding-top: 14px;
    border-top: 1px solid var(--border2);
  }
</style>
{% endblock %}

{% block content %}
<div class="greeting">
  <h2>Selamat datang, {{ user.full_name or user.username }} 👋</h2>
  <p>Berikut ringkasan aktivitas transkripsi Anda.</p>
</div>

<!-- Stats -->
<div class="stats-row" id="stats-row">
  <div class="stat-card">
    <div class="stat-icon blue">📋</div>
    <div>
      <div class="stat-num" id="stat-total">—</div>
      <div class="stat-lbl">Total Task</div>
    </div>
  </div>
  <div class="stat-card">
    <div class="stat-icon green">✅</div>
    <div>
      <div class="stat-num" id="stat-done">—</div>
      <div class="stat-lbl">Selesai</div>
    </div>
  </div>
  <div class="stat-card">
    <div class="stat-icon yellow">⏳</div>
    <div>
      <div class="stat-num" id="stat-pending">—</div>
      <div class="stat-lbl">Dalam Antrian</div>
    </div>
  </div>
  <div class="stat-card">
    <div class="stat-icon red">❌</div>
    <div>
      <div class="stat-num" id="stat-failed">—</div>
      <div class="stat-lbl">Gagal</div>
    </div>
  </div>
</div>

<!-- Quick actions -->
<div class="quick-actions">
  <a href="/transkripsi/file" class="action-card">
    <div class="action-icon blue">📁</div>
    <div>
      <div class="action-title">Upload File</div>
      <div class="action-desc">Transkripsi dari file audio MP3, WAV, M4A, dan lainnya.</div>
    </div>
    <svg class="action-arrow" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M5 12h14M12 5l7 7-7 7"/></svg>
  </a>
  <a href="/transkripsi/rekam" class="action-card">
    <div class="action-icon purple">🎙️</div>
    <div>
      <div class="action-title">Rekam Audio</div>
      <div class="action-desc">Rekam dan transkripsi langsung dari browser secara real-time.</div>
    </div>
    <svg class="action-arrow" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M5 12h14M12 5l7 7-7 7"/></svg>
  </a>
  <a href="/sidang" class="action-card">
    <div class="action-icon gold">⚖️</div>
    <div>
      <div class="action-title">Mode Sidang</div>
      <div class="action-desc">Transkripsi dengan normalisasi label speaker persidangan Indonesia.</div>
    </div>
    <svg class="action-arrow" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M5 12h14M12 5l7 7-7 7"/></svg>
  </a>
</div>

<!-- Recent tasks + user info -->
<div class="row-2">
  <div class="card">
    <div class="card-header">
      <span class="card-title">Riwayat Transkripsi</span>
      <div style="display:flex;gap:6px">
        <button class="btn btn-ghost btn-sm" onclick="loadTasks(currentPage)">🔄 Refresh</button>
      </div>
    </div>
    <div id="task-list">
      <div class="empty-state"><p>Memuat data...</p></div>
    </div>
    <div id="pagination-container" class="pagination" style="display:none"></div>
  </div>

  <div class="card" style="height: fit-content;">
    <div class="card-header">
      <span class="card-title">Info Akun</span>
    </div>
    <div>
      <div class="info-item">
        <span class="info-label">Username</span>
        <span class="info-value">{{ user.username }}</span>
      </div>
      <div class="info-item">
        <span class="info-label">Nama</span>
        <span class="info-value">{{ user.full_name or '—' }}</span>
      </div>
      <div class="info-item">
        <span class="info-label">Role</span>
        <span class="info-value">
          <span class="badge badge-{{ user.role }}">{{ user.role }}</span>
        </span>
      </div>
      <div class="info-item">
        <span class="info-label">Email</span>
        <span class="info-value" style="font-size:.82rem">{{ user.email or '—' }}</span>
      </div>
    </div>
  </div>
</div>

<!-- Modal: Preview hasil transkripsi + BA -->
<div class="modal-backdrop" id="modal-result">
  <div class="modal-result">
    <div class="modal-result-header">
      <span class="modal-result-title" id="modal-result-title">Hasil Transkripsi</span>
      <button class="modal-result-close" onclick="closeResultModal()">✕</button>
    </div>
    <div class="modal-result-body">
      <textarea class="modal-result-textarea" id="modal-result-text" readonly></textarea>
      <div style="font-size:.75rem;color:var(--muted);margin-top:6px" id="modal-result-meta"></div>
    </div>
    <div class="modal-result-footer">
      <button class="btn btn-ghost btn-sm" onclick="copyModalResult()">
        <svg width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/></svg>
        Salin
      </button>
      <button class="btn btn-ghost btn-sm" onclick="downloadModalResult()">
        <svg width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4M7 10l5 5 5-5M12 15V3"/></svg>
        Unduh TXT
      </button>
      <div id="modal-ba-actions" style="display:flex;gap:8px;">
        <!-- Tombol buat/lihat BA akan diisi JS -->
      </div>
      <a href="#" id="modal-detail-link" class="btn btn-primary btn-sm">Detail Task →</a>
    </div>
  </div>
</div>
{% endblock %}

{% block scripts %}
<script>
  const STATUS_LABEL = {
    pending: 'Menunggu', processing: 'Diproses',
    completed: 'Selesai', failed: 'Gagal'
  };

  let currentModalTaskId = null;
  let currentModalText   = '';
  let currentPage = 1;
  let totalPages = 1;
  let currentTasks = [];

  // ── Stats ──
  async function loadStats() {
    {% if user.role == 'admin' %}
    try {
      const r = await fetch('/api/admin/stats');
      if (r.ok) {
        const d = await r.json();
        document.getElementById('stat-total').textContent   = d.tasks.total;
        document.getElementById('stat-done').textContent    = d.tasks.completed;
        document.getElementById('stat-pending').textContent = d.tasks.pending;
        document.getElementById('stat-failed').textContent  = d.tasks.failed;
        return;
      }
    } catch {}
    {% endif %}
    try {
      const r = await fetch('/api/tasks?limit=100&offset=0');
      if (!r.ok) return;
      const d = await r.json();
      const tasks = d.tasks || [];
      const done    = tasks.filter(t => t.status === 'completed').length;
      const pending = tasks.filter(t => ['pending','processing'].includes(t.status)).length;
      const failed  = tasks.filter(t => t.status === 'failed').length;
      document.getElementById('stat-total').textContent   = d.total || tasks.length;
      document.getElementById('stat-done').textContent    = done;
      document.getElementById('stat-pending').textContent = pending;
      document.getElementById('stat-failed').textContent  = failed;
    } catch {}
  }

  // ── Ambil BA per task ──
  async function hasBeritaAcara(taskId) {
    try {
      const r = await fetch(`/api/berita-acara/by-task/${taskId}`);
      if (!r.ok) return null;
      const d = await r.json();
      if (d.items && d.items.length > 0) {
        // return BA pertama (urutan desc)
        return d.items[0];
      }
      return null;
    } catch { return null; }
  }

  // ── Load tasks dengan pagination ──
  async function loadTasks(page = 1) {
    currentPage = page;
    const limit = 10;
    const offset = (page - 1) * limit;
    const el = document.getElementById('task-list');
    el.innerHTML = '<div class="empty-state"><p>Memuat data...</p></div>';

    try {
      const r = await fetch(`/api/tasks?limit=${limit}&offset=${offset}`);
      if (!r.ok) throw new Error('Gagal');
      const d = await r.json();
      const tasks = d.tasks || [];
      const total = d.total || tasks.length;
      totalPages = Math.ceil(total / limit);

      if (tasks.length === 0 && page === 1) {
        el.innerHTML = `<div class="empty-state">
          <svg width="40" height="40" fill="none" stroke="currentColor" stroke-width="1.5" viewBox="0 0 24 24">
            <path d="M9 17H5a2 2 0 00-2 2v0a2 2 0 002 2h14a2 2 0 002-2v0a2 2 0 00-2-2h-4M12 3v12M9 9l3-3 3 3"/>
          </svg>
          <p>Belum ada task transkripsi. <a href="/transkripsi/file" style="color:var(--accent)">Mulai sekarang</a></p>
        </div>`;
        document.getElementById('pagination-container').style.display = 'none';
        return;
      }

      // Cek BA untuk setiap task (parallel)
      const tasksWithBA = await Promise.all(tasks.map(async t => {
        const ba = (t.status === 'completed') ? await hasBeritaAcara(t.task_id) : null;
        return { ...t, ba };
      }));

      currentTasks = tasksWithBA;

      el.innerHTML = tasksWithBA.map(t => {
        const tid = t.task_id;
        const isCompleted = t.status === 'completed';
        let baHtml = '';
        if (isCompleted) {
          if (t.ba) {
            baHtml = `<a href="/berita-acara/${t.ba.id}?task_id=${tid}" class="badge-ba" style="text-decoration:none">📋 BA #${t.ba.id}</a>`;
          } else {
            baHtml = `<button class="btn btn-ghost btn-sm" onclick="createBA(${tid})" style="font-size:.7rem;padding:2px 6px">📝 Buat BA</button>`;
          }
        }
        return `
          <div class="task-row">
            <div class="task-info">
              <div class="task-name">Task #${tid} — ${t.model_type}</div>
              <div class="task-meta">${t.engine} · ${t.created_at ? new Date(t.created_at).toLocaleString('id-ID') : ''}</div>
            </div>
            <div class="task-actions">
              <span class="badge badge-dot badge-${t.status}">${STATUS_LABEL[t.status] || t.status}</span>
              ${baHtml}
              <button class="btn btn-ghost btn-sm" onclick="showResult(${tid})" style="font-size:.72rem;padding:3px 9px">📄 Hasil</button>
              <a href="/transkripsi/status/${tid}" class="task-link" style="white-space:nowrap">Detail →</a>
            </div>
          </div>
        `;
      }).join('');

      // Tampilkan pagination
      const pagContainer = document.getElementById('pagination-container');
      if (totalPages > 1) {
        pagContainer.style.display = 'flex';
        let pagesHtml = '';
        for (let i = 1; i <= totalPages; i++) {
          pagesHtml += `<button class="page-btn ${i === page ? 'active' : ''}" onclick="loadTasks(${i})">${i}</button>`;
        }
        pagContainer.innerHTML = pagesHtml;
      } else {
        pagContainer.style.display = 'none';
      }
    } catch (e) {
      el.innerHTML = `<div class="empty-state"><p style="color:var(--danger)">Gagal memuat data.</p></div>`;
    }
  }

  // ── Buat BA dari task ──
  async function createBA(taskId) {
    try {
      const r = await fetch('/api/berita-acara', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ task_id: taskId })
      });
      if (!r.ok) throw new Error('Gagal membuat BA');
      const d = await r.json();
      showToast('Berita Acara sedang diproses...', 'success');
      // Redirect ke halaman BA setelah beberapa saat
      setTimeout(() => {
        window.location.href = `/berita-acara/${d.ba_id}?task_id=${taskId}`;
      }, 1500);
    } catch(e) {
      alert('Gagal: ' + e.message);
    }
  }

  // ── Tampilkan hasil transkripsi di modal (dengan info BA) ──
  async function showResult(taskId) {
    currentModalTaskId = taskId;
    const modal = document.getElementById('modal-result');
    document.getElementById('modal-result-title').textContent = `Hasil Transkripsi — Task #${taskId}`;
    document.getElementById('modal-result-text').value = 'Memuat...';
    document.getElementById('modal-result-meta').textContent = '';
    document.getElementById('modal-detail-link').href = `/transkripsi/status/${taskId}`;
    modal.classList.add('show');

    try {
      const [resTask, resBA] = await Promise.all([
        fetch(`/api/status/${taskId}`),
        fetch(`/api/berita-acara/by-task/${taskId}`)
      ]);
      if (!resTask.ok) throw new Error('Gagal memuat hasil');
      const dTask = await resTask.json();
      const txt = dTask.result || '';
      currentModalText = txt;
      document.getElementById('modal-result-text').value = txt || '(Hasil kosong)';
      const wc = txt.trim() ? txt.trim().split(/\s+/).filter(Boolean).length : 0;
      document.getElementById('modal-result-meta').textContent =
        `${txt.length.toLocaleString()} karakter · ${wc.toLocaleString()} kata` +
        (dTask.processing_time ? ` · Proses: ${dTask.processing_time.toFixed(1)}s` : '') +
        (dTask.is_court_mode ? ' · ⚖️ Mode Sidang' : '');

      // Tombol BA
      const baActions = document.getElementById('modal-ba-actions');
      baActions.innerHTML = '';
      if (dTask.status === 'completed') {
        if (resBA.ok) {
          const baData = await resBA.json();
          if (baData.items && baData.items.length > 0) {
            const ba = baData.items[0];
            baActions.innerHTML = `<a href="/berita-acara/${ba.id}?task_id=${taskId}" class="btn btn-ghost btn-sm">📋 Lihat Berita Acara</a>`;
          } else {
            baActions.innerHTML = `<button class="btn btn-ghost btn-sm" onclick="createBA(${taskId})">📝 Buat Berita Acara</button>`;
          }
        } else {
          baActions.innerHTML = `<button class="btn btn-ghost btn-sm" onclick="createBA(${taskId})">📝 Buat Berita Acara</button>`;
        }
      } else {
        baActions.innerHTML = '';
      }
    } catch (e) {
      document.getElementById('modal-result-text').value = 'Gagal memuat hasil transkripsi.';
      document.getElementById('modal-ba-actions').innerHTML = '';
    }
  }

  function closeResultModal() {
    document.getElementById('modal-result').classList.remove('show');
    currentModalTaskId = null;
    currentModalText   = '';
  }

  function copyModalResult() {
    navigator.clipboard.writeText(currentModalText).then(() => {
      const btn = event.target.closest('button');
      const orig = btn.innerHTML;
      btn.innerHTML = '✅ Tersalin!';
      setTimeout(() => btn.innerHTML = orig, 2000);
    });
  }

  function downloadModalResult() {
    const blob = new Blob([currentModalText], { type: 'text/plain' });
    const url  = URL.createObjectURL(blob);
    const a    = document.createElement('a');
    a.href     = url;
    a.download = `transkripsi-task-${currentModalTaskId}.txt`;
    a.click();
    URL.revokeObjectURL(url);
  }

  function showToast(msg, type) {
    // Toast sederhana
    const toast = document.createElement('div');
    toast.textContent = msg;
    toast.style.position = 'fixed';
    toast.style.bottom = '20px';
    toast.style.right = '20px';
    toast.style.backgroundColor = type === 'success' ? '#27a33a' : '#f85149';
    toast.style.color = 'white';
    toast.style.padding = '10px 16px';
    toast.style.borderRadius = '6px';
    toast.style.zIndex = '9999';
    document.body.appendChild(toast);
    setTimeout(() => toast.remove(), 3000);
  }

  // Tutup modal klik backdrop
  document.getElementById('modal-result').addEventListener('click', function(e) {
    if (e.target === this) closeResultModal();
  });

  // Init
  loadStats();
  loadTasks(1);
</script>
{% endblock %}