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

{% block title %}Upload File{% endblock %}
{% block page_title %}Upload File Audio{% endblock %}

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

  .dropzone {
    border: 2px dashed var(--border);
    border-radius: var(--radius);
    padding: 52px 28px;
    text-align: center;
    cursor: pointer;
    transition: all .2s;
    position: relative;
    background: var(--surface);
  }
  .dropzone:hover, .dropzone.drag-over {
    border-color: var(--accent);
    background: rgba(88,166,255,.04);
  }
  .dropzone input[type="file"] {
    position: absolute;
    inset: 0; opacity: 0; cursor: pointer;
    width: 100%; height: 100%;
  }
  .dz-icon {
    width: 60px; height: 60px;
    background: rgba(88,166,255,.1);
    border-radius: 14px;
    display: flex; align-items: center; justify-content: center;
    font-size: 26px;
    margin: 0 auto 16px;
    transition: transform .2s;
  }
  .dropzone:hover .dz-icon { transform: translateY(-4px); }
  .dz-title {
    font-family: 'Sora', sans-serif;
    font-size: 1rem; font-weight: 700;
    margin-bottom: 6px;
  }
  .dz-sub { font-size: .85rem; color: var(--muted); margin-bottom: 16px; }
  .dz-formats {
    display: flex; flex-wrap: wrap; justify-content: center; gap: 6px;
    margin-top: 16px;
  }
  .format-pill {
    padding: 3px 10px;
    background: var(--surface2);
    border: 1px solid var(--border);
    border-radius: 20px;
    font-size: .72rem;
    font-weight: 600;
    color: var(--muted);
    font-family: 'DM Mono', monospace;
  }

  .file-preview {
    display: none;
    align-items: center;
    gap: 14px;
    background: rgba(63,185,80,.06);
    border: 1px solid rgba(63,185,80,.25);
    border-radius: var(--radius-sm);
    padding: 12px 16px;
    margin-top: 14px;
  }
  .file-preview.show { display: flex; }
  .file-icon {
    width: 36px; height: 36px;
    background: rgba(63,185,80,.1);
    border-radius: 8px;
    display: flex; align-items: center; justify-content: center;
    font-size: 16px;
  }
  .file-name { font-size: .875rem; font-weight: 600; flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
  .file-size { font-size: .78rem; color: var(--muted); }
  .btn-remove {
    background: none; border: none;
    color: var(--muted); cursor: pointer;
    padding: 4px;
    transition: color .2s;
  }
  .btn-remove:hover { color: var(--danger); }

  .option-group {
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    padding: 20px;
  }
  .option-title {
    font-family: 'Sora', sans-serif;
    font-size: .88rem; font-weight: 700;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid var(--border2);
  }
  .toggle-row {
    display: flex; align-items: center; justify-content: space-between;
    padding: 10px 0;
    border-bottom: 1px solid var(--border2);
  }
  .toggle-row:last-child { border-bottom: none; }
  .toggle-label { font-size: .875rem; }
  .toggle-desc { font-size: .75rem; color: var(--muted); margin-top: 2px; }

  .toggle {
    position: relative; width: 40px; height: 22px;
    flex-shrink: 0;
  }
  .toggle input { opacity: 0; width: 0; height: 0; }
  .toggle-slider {
    position: absolute; inset: 0;
    background: var(--border);
    border-radius: 22px;
    cursor: pointer;
    transition: .2s;
  }
  .toggle-slider::before {
    content: '';
    position: absolute;
    width: 16px; height: 16px;
    left: 3px; bottom: 3px;
    background: #fff;
    border-radius: 50%;
    transition: .2s;
  }
  .toggle input:checked + .toggle-slider { background: var(--accent); }
  .toggle input:checked + .toggle-slider::before { transform: translateX(18px); }

  .submit-btn {
    width: 100%;
    padding: 12px;
    background: var(--accent);
    color: #fff; border: none;
    border-radius: var(--radius-sm);
    font-family: 'DM Sans', sans-serif;
    font-size: .9rem; font-weight: 600;
    cursor: pointer;
    margin-top: 14px;
    display: flex; align-items: center; justify-content: center; gap: 8px;
    transition: all .2s;
  }
  .submit-btn:hover:not(:disabled) { background: #79b8ff; transform: translateY(-1px); }
  .submit-btn:disabled { opacity: .5; cursor: not-allowed; transform: none; }

  .upload-progress {
    display: none;
    margin-top: 14px;
  }
  .upload-progress.show { display: block; }
  .progress-bar { height: 6px; background: var(--border); border-radius: 3px; overflow: hidden; margin-bottom: 8px; }
  .progress-fill {
    height: 100%; width: 0;
    background: linear-gradient(90deg, var(--accent-dim), var(--accent));
    border-radius: 3px;
    transition: width .3s;
    animation: progress-pulse 1.5s ease infinite;
  }
  @keyframes progress-pulse { 0%,100%{opacity:1} 50%{opacity:.7} }
  .progress-text { font-size: .8rem; color: var(--muted); }

  .result-box {
    display: none;
    margin-top: 14px;
    padding: 14px;
    background: rgba(63,185,80,.06);
    border: 1px solid rgba(63,185,80,.2);
    border-radius: var(--radius-sm);
    font-size: .875rem;
  }
  .result-box.show { display: block; }
  .result-box a { color: var(--accent); font-weight: 600; text-decoration: none; }
  .result-box a:hover { text-decoration: underline; }

  /* Badge whisper-1 saat engine API dipilih */
  .api-model-info {
    display: none;
    padding: 8px 12px;
    background: rgba(88,166,255,.08);
    border: 1px solid rgba(88,166,255,.2);
    border-radius: var(--radius-sm);
    font-size: .8rem;
    color: var(--accent);
    margin-top: 6px;
  }
  .api-model-info.show { display: block; }
</style>
{% endblock %}

{% block content %}
<div class="upload-layout">
  <!-- Left: upload area -->
  <div>
    <div class="card" style="margin-bottom:16px">
      <div class="dropzone" id="dropzone">
        <input type="file" id="file-input" accept=".mp3,.mp4,.wav,.m4a,.ogg,.webm,.flac" />
        <div class="dz-icon">📁</div>
        <div class="dz-title">Tarik file ke sini atau klik untuk pilih</div>
        <div class="dz-sub">Ukuran maksimum 100MB</div>
        <div class="dz-formats">
          <span class="format-pill">MP3</span>
          <span class="format-pill">MP4</span>
          <span class="format-pill">WAV</span>
          <span class="format-pill">M4A</span>
          <span class="format-pill">OGG</span>
          <span class="format-pill">WebM</span>
          <span class="format-pill">FLAC</span>
        </div>
      </div>

      <!-- File preview -->
      <div class="file-preview" id="file-preview">
        <div class="file-icon">🎵</div>
        <div>
          <div class="file-name" id="file-name">nama_file.mp3</div>
          <div class="file-size" id="file-size">—</div>
        </div>
        <button class="btn-remove" onclick="removeFile()">
          <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
        </button>
      </div>

      <!-- Upload progress -->
      <div class="upload-progress" id="upload-progress">
        <div class="progress-bar"><div class="progress-fill" id="progress-fill"></div></div>
        <div class="progress-text" id="progress-text">Mengupload file...</div>
      </div>

      <!-- Result -->
      <div class="result-box" id="result-box"></div>
    </div>

    <div class="alert alert-info">
      <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
      <span>Transkripsi berjalan di background. Anda bisa memantau hasilnya di halaman status.</span>
    </div>
  </div>

  <!-- Right: options -->
  <div>
    <div class="option-group">
      <div class="option-title">⚙️ Pengaturan Transkripsi</div>

      <div class="form-group">
        <label class="form-label">Engine</label>
        <select class="form-select" id="engine" onchange="onEngineChange()">
          <option value="local">Lokal (Whisper)</option>
          <option value="api">OpenAI API</option>
        </select>
        <div class="form-hint">Lokal: gratis, lebih lambat. API: cepat, butuh API key.</div>
      </div>

      <!-- Model: hanya tampil saat engine = local -->
      <div class="form-group" id="model-group">
        <label class="form-label">Model</label>
        <select class="form-select" id="model-type">
          <option value="tiny">Tiny — paling cepat</option>
          <option value="base" selected>Base — seimbang</option>
          <option value="small">Small — lebih akurat</option>
          <option value="medium">Medium — akurat</option>
          <option value="large">Large — paling akurat</option>
        </select>
        <div class="form-hint">Model lebih besar = lebih lambat tapi hasil lebih baik.</div>
      </div>

      <!-- Info model API: hanya tampil saat engine = api -->
      <div class="api-model-info" id="api-model-info">
        🤖 OpenAI API menggunakan model <strong>whisper-1</strong> secara otomatis.
      </div>

      <div class="toggle-row">
        <div>
          <div class="toggle-label">Mode Sidang</div>
          <div class="toggle-desc">Normalisasi label speaker pengadilan</div>
        </div>
        <label class="toggle">
          <input type="checkbox" id="court-mode" />
          <span class="toggle-slider"></span>
        </label>
      </div>

      <button class="submit-btn" id="btn-upload" onclick="startUpload()" disabled>
        <svg width="16" height="16" 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-4M17 8l-5-5-5 5M12 3v12"/>
        </svg>
        Upload &amp; Transkripsi
      </button>
    </div>

    <div class="option-group" style="margin-top:14px">
      <div class="option-title">💡 Tips</div>
      <ul style="font-size:.82rem;color:var(--muted);padding-left:16px;line-height:1.9">
        <li>Pastikan audio jelas dan minim noise</li>
        <li>Format WAV/FLAC memberi hasil terbaik</li>
        <li>Untuk rapat panjang, gunakan model Medium+</li>
        <li>Mode sidang hanya untuk pengadilan Indonesia</li>
      </ul>
    </div>
  </div>
</div>
{% endblock %}

{% block scripts %}
<script>
  const dz = document.getElementById('dropzone');
  const fi = document.getElementById('file-input');
  let selectedFile = null;

  fi.addEventListener('change', e => { if (e.target.files[0]) setFile(e.target.files[0]); });

  dz.addEventListener('dragover', e => { e.preventDefault(); dz.classList.add('drag-over'); });
  dz.addEventListener('dragleave', () => dz.classList.remove('drag-over'));
  dz.addEventListener('drop', e => {
    e.preventDefault();
    dz.classList.remove('drag-over');
    if (e.dataTransfer.files[0]) setFile(e.dataTransfer.files[0]);
  });

  function onEngineChange() {
    const isApi = document.getElementById('engine').value === 'api';
    document.getElementById('model-group').style.display    = isApi ? 'none'  : 'block';
    document.getElementById('api-model-info').classList.toggle('show', isApi);
  }

  function setFile(f) {
    selectedFile = f;
    document.getElementById('file-name').textContent = f.name;
    document.getElementById('file-size').textContent = formatBytes(f.size);
    document.getElementById('file-preview').classList.add('show');
    document.getElementById('btn-upload').disabled = false;
    document.getElementById('result-box').classList.remove('show');
  }

  function removeFile() {
    selectedFile = null;
    fi.value = '';
    document.getElementById('file-preview').classList.remove('show');
    document.getElementById('btn-upload').disabled = true;
  }

  function formatBytes(b) {
    if (b < 1024) return b + ' B';
    if (b < 1024*1024) return (b/1024).toFixed(1) + ' KB';
    return (b/(1024*1024)).toFixed(1) + ' MB';
  }

  async function startUpload() {
    if (!selectedFile) return;

    const engine   = document.getElementById('engine').value;
    // Jika engine API, kirim whisper-1; jika lokal, kirim pilihan user
    const modelType = engine === 'api'
      ? 'whisper-1'
      : document.getElementById('model-type').value;

    const btn  = document.getElementById('btn-upload');
    const prog = document.getElementById('upload-progress');
    const fill = document.getElementById('progress-fill');
    const txt  = document.getElementById('progress-text');
    const res  = document.getElementById('result-box');

    btn.disabled = true;
    btn.innerHTML = '⏳ Mengupload...';
    prog.classList.add('show');
    fill.style.width = '30%';
    txt.textContent  = 'Mengupload file...';
    res.classList.remove('show');

    const fd = new FormData();
    fd.append('file',          selectedFile);
    fd.append('engine',        engine);
    fd.append('model_type',    modelType);
    fd.append('is_court_mode', document.getElementById('court-mode').checked);

    try {
      fill.style.width = '60%';
      txt.textContent  = 'Memproses...';

      const r = await fetch('/api/upload', { method: 'POST', body: fd });
      const d = await r.json();

      if (!r.ok) throw new Error(d.detail || 'Upload gagal');

      fill.style.width = '100%';
      txt.textContent  = 'Upload berhasil!';

      res.classList.add('show');
      res.innerHTML = `
        <div style="display:flex;align-items:center;gap:8px;color:var(--success);font-weight:600;margin-bottom:8px">
          ✅ File berhasil diupload. Transkripsi berjalan...
        </div>
        <a href="/transkripsi/status/${d.task_id}">→ Pantau status transkripsi (Task #${d.task_id})</a>
      `;

      setTimeout(() => { window.location.href = `/transkripsi/status/${d.task_id}`; }, 2000);
    } catch (e) {
      fill.style.width = '100%';
      fill.style.background = 'var(--danger)';
      txt.textContent = 'Upload gagal.';
      res.classList.add('show');
      res.style.borderColor = 'rgba(248,81,73,.3)';
      res.style.background  = 'rgba(248,81,73,.06)';
      res.innerHTML = `<span style="color:var(--danger)">❌ ${e.message}</span>`;

      setTimeout(() => {
        btn.disabled = false;
        btn.innerHTML = '📁 Upload & Transkripsi';
        fill.style.background = '';
        prog.classList.remove('show');
      }, 3000);
    }
  }
</script>
{% endblock %}