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

{% block title %}Rekam Audio{% endblock %}
{% block page_title %}Rekam Audio{% endblock %}

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

  /* Visualizer */
  .recorder-card {
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    padding: 28px;
    text-align: center;
  }
  .visualizer-wrap {
    position: relative;
    height: 80px;
    background: var(--bg);
    border-radius: 10px;
    overflow: hidden;
    margin-bottom: 24px;
    display: flex; align-items: center; justify-content: center;
  }
  canvas#viz { position: absolute; inset: 0; width: 100%; height: 100%; }
  .viz-idle {
    display: flex; align-items: center; gap: 3px;
  }
  .viz-idle span {
    display: inline-block;
    width: 3px;
    background: var(--border);
    border-radius: 2px;
    animation: idle-wave 1.2s ease infinite;
  }
  .viz-idle span:nth-child(1) { height: 12px; animation-delay: 0s; }
  .viz-idle span:nth-child(2) { height: 20px; animation-delay: .1s; }
  .viz-idle span:nth-child(3) { height: 28px; animation-delay: .2s; }
  .viz-idle span:nth-child(4) { height: 20px; animation-delay: .3s; }
  .viz-idle span:nth-child(5) { height: 12px; animation-delay: .4s; }
  @keyframes idle-wave { 0%,100%{opacity:.3} 50%{opacity:.6} }

  .timer {
    font-family: 'DM Mono', monospace;
    font-size: 2.4rem; font-weight: 500;
    letter-spacing: 2px;
    margin-bottom: 6px;
    color: var(--text);
  }
  .timer.recording { color: var(--danger); }
  .rec-status {
    font-size: .8rem; color: var(--muted);
    margin-bottom: 24px;
    display: flex; align-items: center; justify-content: center; gap: 6px;
    min-height: 20px;
  }
  .rec-dot {
    width: 8px; height: 8px;
    background: var(--danger);
    border-radius: 50%;
    animation: blink .8s ease infinite;
    display: none;
  }
  .rec-dot.show { display: block; }
  @keyframes blink { 0%,100%{opacity:1} 50%{opacity:.2} }

  .record-btn {
    width: 72px; height: 72px;
    border-radius: 50%;
    border: none;
    cursor: pointer;
    display: flex; align-items: center; justify-content: center;
    font-size: 28px;
    margin: 0 auto 20px;
    transition: all .2s;
    position: relative;
  }
  .record-btn.idle {
    background: rgba(248,81,73,.12);
    border: 2px solid rgba(248,81,73,.4);
    color: var(--danger);
  }
  .record-btn.idle:hover { background: rgba(248,81,73,.2); transform: scale(1.06); }
  .record-btn.recording {
    background: var(--danger);
    color: #fff;
    box-shadow: 0 0 0 0 rgba(248,81,73,.4);
    animation: record-pulse 1.5s ease infinite;
  }
  @keyframes record-pulse {
    0% { box-shadow: 0 0 0 0 rgba(248,81,73,.4); }
    70% { box-shadow: 0 0 0 16px rgba(248,81,73,0); }
    100% { box-shadow: 0 0 0 0 rgba(248,81,73,0); }
  }
  .record-controls {
    display: flex; gap: 10px; justify-content: center;
  }

  /* ── Audio player preview ── */
  .audio-preview {
    display: none;
    margin-top: 18px;
    background: var(--bg);
    border: 1px solid var(--border);
    border-radius: var(--radius-sm);
    padding: 14px 16px;
  }
  .audio-preview.show { display: block; }
  .audio-preview-label {
    font-size: .72rem; font-weight: 600;
    color: var(--muted); text-transform: uppercase; letter-spacing: .5px;
    margin-bottom: 10px;
  }
  .audio-preview audio {
    width: 100%;
    accent-color: var(--accent);
  }
  audio {
    filter: invert(1) hue-rotate(180deg);
  }

  /* Mode tabs */
  .mode-tabs {
    display: flex;
    background: var(--bg);
    border: 1px solid var(--border);
    border-radius: var(--radius-sm);
    padding: 3px;
    margin-bottom: 20px;
  }
  .mode-tab {
    flex: 1; padding: 7px;
    border: none; background: none;
    color: var(--muted);
    font-family: 'DM Sans', sans-serif;
    font-size: .8rem; font-weight: 600;
    cursor: pointer;
    border-radius: 6px;
    transition: all .2s;
  }
  .mode-tab.active {
    background: var(--surface);
    color: var(--text);
    box-shadow: 0 1px 3px rgba(0,0,0,.3);
  }

  /* Transcript live */
  .transcript-wrap {
    background: var(--bg);
    border: 1px solid var(--border);
    border-radius: var(--radius-sm);
    min-height: 200px;
    max-height: 360px;
    overflow-y: auto;
    padding: 14px;
    font-size: .875rem;
    line-height: 1.8;
    position: relative;
  }
  .transcript-empty {
    color: var(--muted);
    text-align: center;
    padding: 40px 20px;
    font-size: .85rem;
  }
  .transcript-chunk {
    padding: 8px 10px;
    border-radius: 6px;
    margin-bottom: 8px;
    background: rgba(88,166,255,.06);
    border-left: 2px solid rgba(88,166,255,.3);
    animation: slide-in .2s ease;
  }
  .transcript-chunk .chunk-meta {
    font-size: .7rem; color: var(--muted);
    margin-bottom: 3px;
    font-family: 'DM Mono', monospace;
  }
  @keyframes slide-in {
    from { opacity: 0; transform: translateY(6px); }
    to   { opacity: 1; transform: translateY(0); }
  }
  .transcript-toolbar {
    display: flex; gap: 8px; justify-content: space-between; align-items: center;
    margin-bottom: 8px;
    flex-wrap: wrap;
  }
  .transcript-label { font-size: .78rem; font-weight: 600; color: var(--muted); text-transform: uppercase; letter-spacing: .5px; }

  /* Live status indicator */
  .live-status {
    display: inline-flex; align-items: center; gap: 6px;
    font-size: .75rem; color: var(--muted);
    padding: 3px 10px;
    background: var(--surface2);
    border: 1px solid var(--border2);
    border-radius: 20px;
  }
  .live-dot {
    width: 6px; height: 6px;
    border-radius: 50%;
    background: var(--muted);
  }
  .live-dot.connected  { background: var(--success); animation: blink .8s ease infinite; }
  .live-dot.processing { background: var(--warning);  animation: blink .4s ease infinite; }
  .live-dot.error      { background: var(--danger); }

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

{% block content %}
<div class="record-layout">
  <!-- Left: recorder -->
  <div>
    <!-- Mode switch -->
    <div class="mode-tabs">
      <button class="mode-tab active" id="tab-upload" onclick="switchMode('upload')">📁 Rekam + Upload</button>
      <button class="mode-tab" id="tab-live" onclick="switchMode('live')">⚡ Transkripsi Real-time</button>
    </div>

    <div class="recorder-card">
      <!-- Visualizer -->
      <div class="visualizer-wrap">
        <canvas id="viz"></canvas>
        <div class="viz-idle" id="viz-idle">
          <span></span><span></span><span></span><span></span><span></span>
        </div>
      </div>

      <div class="timer" id="timer">00:00</div>
      <div class="rec-status">
        <div class="rec-dot" id="rec-dot"></div>
        <span id="rec-status-txt">Siap merekam</span>
      </div>

      <button class="record-btn idle" id="rec-btn" onclick="toggleRecord()">🎙️</button>
      <div class="record-controls">
        <button class="btn btn-ghost btn-sm" id="btn-upload-rec" onclick="uploadRecording()" disabled>
          <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-4M17 8l-5-5-5 5M12 3v12"/></svg>
          Kirim untuk Transkripsi
        </button>
        <button class="btn btn-ghost btn-sm" id="btn-reset" onclick="resetRecorder()" disabled>
          <svg width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 102.13-9.36L1 10"/></svg>
          Reset
        </button>
      </div>

      <div class="audio-preview" id="audio-preview">
        <div class="audio-preview-label">🎧 Putar ulang rekaman</div>
        <audio id="audio-player" controls preload="auto"></audio>
      </div>

      <div id="upload-result" style="display:none;margin-top:16px"></div>
    </div>

    <!-- Live transcript (only in live mode) -->
    <div id="live-panel" style="display:none;margin-top:16px">
      <div class="card">
        <div class="transcript-toolbar">
          <span class="transcript-label">📝 Hasil Real-time</span>
          <div style="display:flex;gap:8px;align-items:center">
            <span class="live-status" id="live-status">
              <span class="live-dot" id="live-dot"></span>
              <span id="live-status-txt">Tidak terhubung</span>
            </span>
            <button class="btn btn-ghost btn-sm" onclick="copyLive()">Salin</button>
            <button class="btn btn-ghost btn-sm" onclick="clearLive()">Hapus</button>
          </div>
        </div>
        <div class="transcript-wrap" id="live-transcript">
          <div class="transcript-empty">Mulai merekam untuk melihat hasil transkripsi real-time...</div>
        </div>
      </div>
    </div>
  </div>

  <!-- Right: settings -->
  <div>
    <div class="card">
      <div class="card-header">
        <span class="card-title">⚙️ Pengaturan</span>
      </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>

      <!-- 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</option>
          <option value="medium">Medium</option>
          <option value="large">Large</option>
        </select>
      </div>

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

      <div style="display:flex;align-items:center;justify-content:space-between;padding:8px 0;">
        <div>
          <div style="font-size:.875rem">Mode Sidang</div>
          <div style="font-size:.75rem;color:var(--muted)">Format output pengadilan</div>
        </div>
        <label class="toggle">
          <input type="checkbox" id="court-mode" />
          <span class="toggle-slider"></span>
        </label>
      </div>

      <div id="live-chunk-setting" style="display:none;margin-top:14px;padding-top:14px;border-top:1px solid var(--border2)">
        <label class="form-label">Interval Chunk (detik)</label>
        <select class="form-select" id="chunk-interval">
          <option value="3">3 detik</option>
          <option value="5" selected>5 detik</option>
          <option value="10">10 detik</option>
        </select>
        <div class="form-hint">Seberapa sering audio dikirim ke server untuk ditranskripsi.</div>
      </div>
    </div>

    <div class="card" style="margin-top:14px">
      <div class="card-header"><span class="card-title">💡 Panduan</span></div>
      <ul style="font-size:.8rem;color:var(--muted);padding-left:16px;line-height:2">
        <li>Izinkan akses mikrofon</li>
        <li>Tekan 🎙️ untuk mulai merekam</li>
        <li>Tekan lagi untuk berhenti</li>
        <li>Putar ulang rekaman sebelum dikirim</li>
        <li>Mode real-time: transkripsi langsung muncul</li>
        <li>Mode upload: kirim rekaman penuh ke server</li>
      </ul>
    </div>
  </div>
</div>
{% endblock %}

{% block scripts %}
<script>
  let mediaRecorder, audioChunks = [], stream, animFrame;
  let timerInterval, seconds = 0;
  let recording = false;
  let currentMode = 'upload';
  let ws = null;
  let liveTranscriptContent = '';

  // ── Engine change ────────────────────────────────────────────────
  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);
  }

  // Helper: ambil model_type sesuai engine
  function getModelType() {
    const engine = document.getElementById('engine').value;
    return engine === 'api' ? 'openai/whisper-1' : document.getElementById('model-type').value;
  }

  // ── Mode switch ─────────────────────────────────────────────────
  function switchMode(mode) {
    currentMode = mode;
    document.getElementById('tab-upload').classList.toggle('active', mode === 'upload');
    document.getElementById('tab-live').classList.toggle('active', mode === 'live');
    document.getElementById('live-panel').style.display         = mode === 'live' ? 'block' : 'none';
    document.getElementById('live-chunk-setting').style.display = mode === 'live' ? 'block' : 'none';
    document.getElementById('btn-upload-rec').style.display     = mode === 'upload' ? 'flex' : 'none';
    if (recording) stopRecording();
  }

  // ── Timer ────────────────────────────────────────────────────────
  function startTimer() {
    seconds = 0;
    timerInterval = setInterval(() => {
      seconds++;
      const m = String(Math.floor(seconds/60)).padStart(2,'0');
      const s = String(seconds % 60).padStart(2,'0');
      document.getElementById('timer').textContent = `${m}:${s}`;
    }, 1000);
  }

  // ── Visualizer ───────────────────────────────────────────────────
  let audioCtxForViz = null;

  function startVisualizer(strm) {
    const canvas   = document.getElementById('viz');
    const ctx      = canvas.getContext('2d');
    audioCtxForViz = new AudioContext();
    const analyser = audioCtxForViz.createAnalyser();
    const source   = audioCtxForViz.createMediaStreamSource(strm);
    source.connect(analyser);
    analyser.fftSize = 256;
    const buf = new Uint8Array(analyser.frequencyBinCount);

    document.getElementById('viz-idle').style.display = 'none';

    function draw() {
      animFrame = requestAnimationFrame(draw);
      analyser.getByteFrequencyData(buf);
      canvas.width  = canvas.offsetWidth;
      canvas.height = canvas.offsetHeight;
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      const barW = (canvas.width / buf.length) * 2.5;
      let x = 0;
      buf.forEach(v => {
        const h = (v / 255) * canvas.height;
        ctx.fillStyle = `rgba(88,166,255,${0.3 + (v/255)*0.7})`;
        ctx.fillRect(x, (canvas.height - h)/2, barW-1, h);
        x += barW;
      });
    }
    draw();
  }

  function stopVisualizer() {
    cancelAnimationFrame(animFrame);
    audioCtxForViz?.close();
    audioCtxForViz = null;
    const canvas = document.getElementById('viz');
    const ctx    = canvas.getContext('2d');
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    document.getElementById('viz-idle').style.display = 'flex';
  }

  // ── Record toggle ────────────────────────────────────────────────
  async function toggleRecord() {
    if (!recording) await startRecording();
    else             stopRecording();
  }

  async function startRecording() {
    try {
      stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    } catch {
      alert('Akses mikrofon ditolak. Izinkan akses mikrofon di browser Anda.');
      return;
    }
    recording    = true;
    audioChunks  = [];

    document.getElementById('audio-preview').classList.remove('show');
    document.getElementById('rec-btn').className   = 'record-btn recording';
    document.getElementById('rec-btn').textContent = '⏹';
    document.getElementById('rec-dot').classList.add('show');
    document.getElementById('rec-status-txt').textContent = 'Merekam...';
    document.getElementById('timer').classList.add('recording');
    document.getElementById('btn-reset').disabled      = true;
    document.getElementById('btn-upload-rec').disabled = true;

    startVisualizer(stream);
    startTimer();

    if (currentMode === 'live') {
      startLiveMode();
    } else {
      mediaRecorder = new MediaRecorder(stream, { mimeType: getSupportedMimeType() });
      mediaRecorder.ondataavailable = e => { if (e.data.size > 0) audioChunks.push(e.data); };
      mediaRecorder.start(100);
    }
  }

  function stopRecording() {
    recording = false;
    clearInterval(timerInterval);
    stopVisualizer();
    stream?.getTracks().forEach(t => t.stop());

    document.getElementById('rec-btn').className    = 'record-btn idle';
    document.getElementById('rec-btn').textContent  = '🎙️';
    document.getElementById('rec-dot').classList.remove('show');
    document.getElementById('timer').classList.remove('recording');
    document.getElementById('btn-reset').disabled   = false;

    if (currentMode === 'live') {
      stopLiveMode();
      document.getElementById('rec-status-txt').textContent = 'Rekaman selesai';
    } else {
      mediaRecorder?.stop();

      mediaRecorder.onstop = () => {
        const mimeType = getSupportedMimeType();
        const blob     = new Blob(audioChunks, { type: mimeType });

        const player  = document.getElementById('audio-player');
        const preview = document.getElementById('audio-preview');
        player.src    = URL.createObjectURL(blob);
        preview.classList.add('show');

        document.getElementById('btn-upload-rec').disabled = false;
        document.getElementById('rec-status-txt').textContent = 'Rekaman selesai — putar ulang atau kirim';
      };
    }
  }

  function resetRecorder() {
    audioChunks = [];
    seconds     = 0;
    document.getElementById('timer').textContent          = '00:00';
    document.getElementById('rec-status-txt').textContent = 'Siap merekam';
    document.getElementById('btn-upload-rec').disabled    = true;
    document.getElementById('btn-reset').disabled         = true;
    document.getElementById('upload-result').style.display = 'none';

    const player  = document.getElementById('audio-player');
    const preview = document.getElementById('audio-preview');
    if (player.src) URL.revokeObjectURL(player.src);
    player.src = '';
    preview.classList.remove('show');
  }

  // ── Deteksi MIME type yang didukung browser ──────────────────────
  function getSupportedMimeType() {
    const types = ['audio/webm;codecs=opus', 'audio/webm', 'audio/ogg;codecs=opus', 'audio/mp4'];
    for (const t of types) {
      if (MediaRecorder.isTypeSupported(t)) return t;
    }
    return '';
  }

  // ── Upload mode ──────────────────────────────────────────────────
  async function uploadRecording() {
    if (!audioChunks.length) return;

    const mimeType = getSupportedMimeType();
    const ext      = mimeType.includes('ogg') ? '.ogg' : mimeType.includes('mp4') ? '.mp4' : '.webm';
    const blob     = new Blob(audioChunks, { type: mimeType });
    const engine   = document.getElementById('engine').value;

    const fd = new FormData();
    fd.append('file',          new File([blob], `rekaman${ext}`, { type: mimeType }));
    fd.append('engine',        engine);
    fd.append('model_type',    getModelType());  // ← otomatis whisper-1 jika API
    fd.append('is_court_mode', document.getElementById('court-mode').checked);

    const btn = document.getElementById('btn-upload-rec');
    btn.disabled = true;
    btn.innerHTML = '⏳ Mengirim...';

    try {
      const r = await fetch('/api/record/upload', { method: 'POST', body: fd });
      const d = await r.json();
      if (!r.ok) throw new Error(d.detail);

      const res = document.getElementById('upload-result');
      res.style.display = 'block';
      res.innerHTML = `<div class="alert alert-success">✅ Rekaman berhasil dikirim! <a href="/transkripsi/status/${d.task_id}" style="color:inherit;font-weight:700">→ Lihat Status Task #${d.task_id}</a></div>`;
      setTimeout(() => window.location.href = `/transkripsi/status/${d.task_id}`, 2000);
    } catch (e) {
      const res = document.getElementById('upload-result');
      res.style.display = 'block';
      res.innerHTML = `<div class="alert alert-danger">❌ Gagal: ${e.message}</div>`;
      btn.disabled  = false;
      btn.innerHTML = '<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-4M17 8l-5-5-5 5M12 3v12"/></svg> Kirim untuk Transkripsi';
    }
  }

  // ── Live mode via WebSocket ──────────────────────────────────────
  let liveMediaRecorder = null;

  function setLiveStatus(state, text) {
    const dot = document.getElementById('live-dot');
    const txt = document.getElementById('live-status-txt');
    dot.className = `live-dot ${state}`;
    txt.textContent = text;
  }

  function startLiveMode() {
    const proto = location.protocol === 'https:' ? 'wss' : 'ws';
    ws = new WebSocket(`${proto}://${location.host}/api/record/live`);
    setLiveStatus('', 'Menghubungkan...');

    ws.onopen = () => {
      setLiveStatus('connected', 'Terhubung');
      ws.send(JSON.stringify({
        type:       'config',
        engine:     document.getElementById('engine').value,
        model_type: getModelType(),  // ← otomatis whisper-1 jika API
      }));
      startLiveChunking();
    };

    ws.onmessage = e => {
      const msg = JSON.parse(e.data);
      if (msg.type === 'transcript') {
        setLiveStatus('connected', 'Terhubung');
        appendLiveChunk(msg.text, msg.processing_time);
      } else if (msg.type === 'processing') {
        setLiveStatus('processing', 'Memproses...');
      } else if (msg.type === 'error') {
        setLiveStatus('error', 'Error');
        appendLiveChunk(`[ERROR] ${msg.message}`, null, true);
      } else if (msg.type === 'empty') {
        setLiveStatus('connected', 'Terhubung — tidak ada suara');
      }
    };

    ws.onerror = () => setLiveStatus('error', 'Koneksi error');
    ws.onclose = () => {
      setLiveStatus('', 'Terputus');
      stopLiveChunking();
    };
  }

  function stopLiveMode() {
    stopLiveChunking();
    if (ws && ws.readyState === WebSocket.OPEN) ws.close();
    ws = null;
    setLiveStatus('', 'Tidak terhubung');
  }

  function startLiveChunking() {
    const mimeType   = getSupportedMimeType();
    const intervalMs = parseInt(document.getElementById('chunk-interval').value) * 1000;

    liveMediaRecorder = new MediaRecorder(stream, { mimeType });
    liveMediaRecorder.ondataavailable = e => {
      if (e.data.size > 0 && ws?.readyState === WebSocket.OPEN) {
        ws.send(e.data);
        setLiveStatus('processing', 'Memproses chunk...');
      }
    };
    liveMediaRecorder.start(intervalMs);
  }

  function stopLiveChunking() {
    if (liveMediaRecorder && liveMediaRecorder.state !== 'inactive') {
      liveMediaRecorder.stop();
    }
    liveMediaRecorder = null;
  }

  function appendLiveChunk(text, procTime, isError = false) {
    const el    = document.getElementById('live-transcript');
    const empty = el.querySelector('.transcript-empty');
    if (empty) empty.remove();

    const div = document.createElement('div');
    div.className = 'transcript-chunk';
    if (isError) div.style.borderLeftColor = 'var(--danger)';

    const time = new Date().toLocaleTimeString('id-ID');
    const meta = procTime ? `${time} · ${procTime}s` : time;
    div.innerHTML = `<div class="chunk-meta">${meta}</div>${text}`;
    el.appendChild(div);
    el.scrollTop = el.scrollHeight;

    liveTranscriptContent += (liveTranscriptContent ? '\n' : '') + text;
  }

  function copyLive() {
    if (!liveTranscriptContent) return;
    navigator.clipboard.writeText(liveTranscriptContent).then(() => {
      const btn  = event.target.closest('button');
      const orig = btn.textContent;
      btn.textContent = '✅ Tersalin!';
      setTimeout(() => btn.textContent = orig, 2000);
    });
  }

  function clearLive() {
    liveTranscriptContent = '';
    document.getElementById('live-transcript').innerHTML =
      '<div class="transcript-empty">Hasil transkripsi akan muncul di sini...</div>';
  }

  // Init
  document.getElementById('btn-upload-rec').style.display = 'flex';
</script>
{% endblock %}