<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Transkripsi Sidang</title>
<style>
*, *::before, *::after { box-sizing:border-box; margin:0; padding:0; }
:root {
    --bg:      #060d18;
    --surface: #0d1a2e;
    --panel:   #0a1422;
    --border:  #1b2e44;
    --b2:      #1e3a55;
    --muted:   #45607a;
    --sub:     #6e8fad;
    --text:    #cce0f5;
    --gold:    #c89a38;
}
body { font-family:'Georgia','Times New Roman',serif; background:var(--bg); color:var(--text); height:100vh; display:grid; grid-template-rows:auto 1fr auto; overflow:hidden; }

/* HEADER */
header { background:var(--surface); border-bottom:1px solid var(--border); padding:8px 18px; display:flex; align-items:center; gap:10px; flex-wrap:wrap; }
.brand { font-weight:700; font-size:.88rem; color:var(--gold); letter-spacing:.04em; font-style:italic; white-space:nowrap; }
.perkara-row { display:flex; gap:6px; flex:1; flex-wrap:wrap; }
.perkara-row input { background:var(--panel); border:1px solid var(--b2); border-radius:5px; color:var(--text); padding:5px 9px; font-size:.76rem; outline:none; font-family:inherit; min-width:0; }
.perkara-row input:focus { border-color:#2275b8; }
#inPerkara { flex:2; min-width:160px; } #inHakim { flex:1; min-width:110px; } #inLokasi { flex:1; min-width:100px; }
.hbtns { display:flex; gap:5px; flex-shrink:0; align-items:center; }
.hbtn { padding:5px 11px; border:1px solid var(--b2); border-radius:5px; cursor:pointer; font-size:.72rem; font-weight:700; font-family:'Segoe UI',sans-serif; background:var(--panel); color:var(--sub); transition:all .15s; white-space:nowrap; }
.hbtn:hover { border-color:#2275b8; color:var(--text); }
.hbtn-blue  { background:#0c3d6a; color:#8dcff5; border-color:#1a5fa0; }
.hbtn-blue:hover { background:#1a5fa0; }
.hbtn-amber { background:#3e2500; color:#f0c060; border-color:#c89a38; }
.hbtn-amber:hover { background:#c89a38; color:#1a0e00; }

/* MAIN */
#mainArea { overflow-y:auto; overflow-x:hidden; display:flex; flex-direction:column; }

/* ── STEP 0 ── */
#stepType { flex:1; display:flex; flex-direction:column; align-items:center; justify-content:center; gap:22px; padding:30px 20px; }
.step-lbl { font-size:.78rem; font-weight:700; color:var(--muted); text-transform:uppercase; letter-spacing:.1em; font-family:'Segoe UI',sans-serif; }
.type-cards { display:flex; gap:14px; flex-wrap:wrap; justify-content:center; }
.type-card { width:170px; padding:20px 15px; border:2px solid var(--b2); border-radius:10px; background:var(--surface); cursor:pointer; text-align:center; transition:all .2s; position:relative; }
.type-card:hover { transform:translateY(-2px); }
.type-card.sel { transform:translateY(-2px); }
.tc-pidana:hover,.tc-pidana.sel   { border-color:#1a5ca0; box-shadow:0 0 22px rgba(26,92,160,.35); }
.tc-perdata:hover,.tc-perdata.sel { border-color:#0a7040; box-shadow:0 0 22px rgba(10,112,64,.35); }
.tc-icon { font-size:1.9rem; margin-bottom:9px; }
.tc-name { font-size:.88rem; font-weight:700; color:var(--text); margin-bottom:4px; font-family:'Segoe UI',sans-serif; }
.tc-sub  { font-size:.69rem; color:var(--muted); line-height:1.5; font-style:italic; }
.tc-check { position:absolute; top:8px; right:10px; font-size:.7rem; font-weight:800; opacity:0; color:#7ec8f5; font-family:'Segoe UI',sans-serif; }
.type-card.sel .tc-check { opacity:1; }
.btn-primary { padding:10px 30px; background:linear-gradient(135deg,#0d3d6a,#1a5fa0); color:#8dcff5; border:none; border-radius:7px; font-size:.85rem; font-weight:700; cursor:pointer; font-family:'Segoe UI',sans-serif; transition:all .2s; }
.btn-primary:hover { background:linear-gradient(135deg,#1a5fa0,#2275b8); transform:translateY(-1px); }
.btn-primary:disabled { opacity:.35; cursor:not-allowed; transform:none; }

/* ── STEP 1 ── */
#stepSetup { display:none; flex:1; padding:16px 22px; overflow-y:auto; flex-direction:column; gap:12px; }
.setup-hd { display:flex; align-items:center; gap:10px; flex-wrap:wrap; }
.setup-hd h2 { font-size:.78rem; font-weight:700; color:var(--muted); text-transform:uppercase; letter-spacing:.08em; font-family:'Segoe UI',sans-serif; font-style:normal; }
.type-pill { padding:2px 9px; border-radius:999px; font-size:.67rem; font-weight:800; font-family:'Segoe UI',sans-serif; }
.pill-pidana  { background:#0c2e55; color:#7ec8f5; }
.pill-perdata { background:#053822; color:#5ddba0; }
.setup-cols { display:flex; gap:12px; flex-wrap:wrap; }
.setup-col { flex:1; min-width:200px; background:var(--panel); border:1px solid var(--b2); border-radius:9px; padding:13px 14px; display:flex; flex-direction:column; gap:8px; }
.sc-title { font-size:.66rem; font-weight:800; color:var(--muted); text-transform:uppercase; letter-spacing:.07em; font-family:'Segoe UI',sans-serif; }
.sc-desc  { font-size:.68rem; color:var(--muted); font-style:italic; font-family:'Segoe UI',sans-serif; }
.role-btns { display:flex; flex-wrap:wrap; gap:5px; }
.role-btn { padding:5px 11px; border-radius:999px; border:1.5px solid var(--b2); background:var(--surface); color:var(--sub); font-size:.72rem; font-weight:700; cursor:pointer; font-family:'Segoe UI',sans-serif; transition:all .15s; white-space:nowrap; display:flex; align-items:center; gap:4px; }
.role-btn:hover { color:var(--text); border-color:var(--sub); }
.role-btn.sel { color:#fff; border-color:transparent; }
.sc-name { width:100%; background:var(--surface); border:1px solid var(--b2); border-radius:6px; color:var(--text); padding:7px 10px; font-size:.8rem; outline:none; font-family:inherit; }
.sc-name:focus { border-color:#2275b8; }
.extra-section { background:var(--panel); border:1px solid var(--b2); border-radius:9px; padding:13px 14px; }
.extra-hint { font-size:.69rem; color:var(--muted); font-style:italic; font-family:'Segoe UI',sans-serif; margin:5px 0 10px; line-height:1.5; }
.extra-chip-row { display:flex; flex-wrap:wrap; gap:5px; margin-bottom:8px; }
.extra-chip { padding:4px 10px; border-radius:999px; border:1.5px solid var(--b2); background:var(--surface); color:var(--sub); font-size:.7rem; font-weight:700; cursor:pointer; font-family:'Segoe UI',sans-serif; transition:all .15s; }
.extra-chip:hover { color:var(--text); border-color:var(--sub); }
.extra-list { display:flex; flex-direction:column; gap:5px; }
.extra-item { display:flex; align-items:center; gap:7px; padding:6px 10px; background:var(--surface); border:1px solid var(--b2); border-radius:7px; animation:fadeUp .2s ease; }
.ei-av  { width:26px; height:26px; border-radius:50%; display:flex; align-items:center; justify-content:center; font-size:.78rem; flex-shrink:0; }
.ei-lbl { font-size:.66rem; color:var(--muted); font-family:'Segoe UI',sans-serif; white-space:nowrap; min-width:90px; }
.ei-nm  { flex:1; background:var(--panel); border:1px solid var(--b2); border-radius:5px; color:var(--text); padding:4px 8px; font-size:.76rem; outline:none; font-family:inherit; min-width:0; }
.ei-nm:focus { border-color:#2275b8; }
.ei-rm  { background:none; border:none; color:var(--muted); cursor:pointer; font-size:.78rem; padding:2px 5px; border-radius:4px; }
.ei-rm:hover { color:#ef4444; background:rgba(239,68,68,.1); }
.engine-row { display:flex; gap:10px; align-items:center; flex-wrap:wrap; background:var(--panel); border:1px solid var(--b2); border-radius:8px; padding:9px 13px; }
.engine-row label { font-size:.69rem; color:var(--muted); font-family:'Segoe UI',sans-serif; font-weight:700; }
.engine-row select { background:var(--surface); border:1px solid var(--b2); border-radius:5px; color:var(--text); padding:4px 8px; font-size:.75rem; outline:none; cursor:pointer; }
.setup-actions { display:flex; gap:8px; align-items:center; }
.btn-green { padding:10px 26px; background:linear-gradient(135deg,#043a1e,#07602e); color:#5ddba0; border:none; border-radius:7px; font-size:.83rem; font-weight:800; cursor:pointer; font-family:'Segoe UI',sans-serif; transition:all .2s; }
.btn-green:hover { background:linear-gradient(135deg,#07602e,#0a8040); }
.btn-ghost { background:var(--panel); border:1px solid var(--b2); color:var(--sub); padding:9px 14px; border-radius:7px; font-size:.76rem; font-weight:700; cursor:pointer; font-family:'Segoe UI',sans-serif; }
.btn-ghost:hover { color:var(--text); }

/* ── STEP 2 ── */
#stepSession { display:none; flex:1; flex-direction:column; overflow:hidden; }

/* ═══════════════════════════════════════════
   PAIR BAR
   LEFT side = currently active "penanya" (could be hakim or extra)
   RIGHT side = always responden
   SPASI always toggles LEFT ↔ RIGHT, auto-start
═══════════════════════════════════════════ */
#pairBar {
    background:var(--panel); border-bottom:1px solid var(--border);
    padding:10px 18px; display:flex; align-items:stretch; gap:10px;
}

.pair-side {
    flex:1; display:flex; align-items:center; gap:10px;
    padding:10px 15px; border-radius:10px; border:2px solid var(--b2);
    cursor:pointer; transition:border-color .2s, background .2s; position:relative; min-width:0;
}
.pair-side:hover { border-color:var(--sub); }

/* Currently recording — red pulse */
.pair-side.is-rec {
    border-color:#c0392b !important; background:rgba(192,57,43,.1) !important; cursor:default;
    animation:recglow 1.5s ease-in-out infinite;
}
@keyframes recglow { 0%,100%{box-shadow:0 0 0 0 rgba(192,57,43,0)} 50%{box-shadow:0 0 14px 2px rgba(192,57,43,.4)} }

/* Next up (idle) — blue */
.pair-side.next-up { border-color:#1a5fa0 !important; background:rgba(26,95,160,.07) !important; }

.ps-av { width:44px; height:44px; border-radius:50%; display:flex; align-items:center; justify-content:center; font-size:1.15rem; flex-shrink:0; transition:background .3s, color .3s; }
.ps-labels { flex:1; min-width:0; overflow:hidden; }
.ps-role { font-size:.62rem; font-weight:800; color:var(--muted); text-transform:uppercase; letter-spacing:.04em; font-family:'Segoe UI',sans-serif; line-height:1; margin-bottom:3px; }
.ps-name { font-size:.92rem; font-weight:700; line-height:1.2; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
.ps-tag  { font-size:.64rem; color:var(--muted); font-family:'Segoe UI',sans-serif; margin-top:2px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
.ps-dot  { width:10px; height:10px; border-radius:50%; background:var(--b2); flex-shrink:0; margin-left:4px; transition:background .2s; }
.pair-side.is-rec .ps-dot { background:#ef4444; animation:dotpulse 1s infinite; }
@keyframes dotpulse { 0%,100%{opacity:1} 50%{opacity:.2} }

/* "BERIKUTNYA" badge shown on next-up side */
.ps-badge {
    position:absolute; bottom:6px; right:10px;
    font-size:.58rem; font-weight:800; font-family:'Segoe UI',sans-serif;
    color:#5599cc; letter-spacing:.05em;
    background:#08182e; padding:1px 7px; border-radius:4px;
    display:none;
}
.pair-side.next-up .ps-badge { display:block; }
.pair-side.is-rec  .ps-badge { display:none; }

/* Center */
.pair-center { display:flex; flex-direction:column; align-items:center; justify-content:center; gap:4px; flex-shrink:0; padding:0 6px; }
.kbd { background:var(--surface); border:1px solid var(--b2); border-bottom:3px solid var(--b2); border-radius:5px; padding:3px 14px; font-family:monospace; font-size:.8rem; color:var(--text); }
.pair-center span { font-size:.61rem; color:var(--muted); font-family:'Segoe UI',sans-serif; text-align:center; line-height:1.4; }
.pair-arrow { font-size:1rem; color:var(--b2); }

.session-meta { display:flex; flex-direction:column; justify-content:center; gap:5px; flex-shrink:0; }
.btn-sm    { background:var(--b2); border:none; color:var(--sub); padding:5px 10px; border-radius:6px; cursor:pointer; font-size:.7rem; font-weight:700; font-family:'Segoe UI',sans-serif; white-space:nowrap; }
.btn-sm:hover { color:var(--text); }
.btn-add-e { background:none; border:1.5px dashed var(--b2); color:var(--muted); padding:5px 10px; border-radius:6px; cursor:pointer; font-size:.7rem; font-weight:700; font-family:'Segoe UI',sans-serif; white-space:nowrap; transition:all .15s; }
.btn-add-e:hover { border-color:var(--sub); color:var(--sub); }

/* ═══════════════════════════════════════════
   EXTRA BAR
   Cards are the "peserta lain".
   Clicking one replaces the LEFT side of the toggle.
   The selected one glows purple (active-left).
   If recording, it shows as red.
═══════════════════════════════════════════ */
#extraBar { background:var(--panel); border-bottom:1px solid var(--border); padding:7px 18px; display:flex; align-items:center; gap:8px; flex-wrap:wrap; }
#extraBar.hidden { display:none; }
.eb-lbl { font-size:.63rem; font-weight:700; color:var(--muted); text-transform:uppercase; font-family:'Segoe UI',sans-serif; letter-spacing:.05em; white-space:nowrap; }

.extra-card {
    display:flex; align-items:center; gap:6px;
    padding:5px 12px; border-radius:7px;
    border:1.5px solid var(--b2); background:var(--surface);
    cursor:pointer; transition:all .15s; font-family:'Segoe UI',sans-serif;
}
.extra-card:hover { border-color:var(--sub); }
/* This extra is now the LEFT side (replaces hakim) */
.extra-card.ec-left     { border-color:#7c3aed; background:rgba(124,58,237,.1); }
/* This extra is LEFT and currently recording */
.extra-card.ec-left-rec { border-color:#ef4444; background:rgba(239,68,68,.1); animation:recglow 1.5s infinite; }

.ec-av   { width:24px; height:24px; border-radius:50%; display:flex; align-items:center; justify-content:center; font-size:.72rem; flex-shrink:0; }
.ec-role { font-size:.58rem; color:var(--muted); text-transform:uppercase; line-height:1; }
.ec-name { font-size:.76rem; font-weight:700; max-width:90px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.ec-dot  { width:7px; height:7px; border-radius:50%; background:var(--b2); margin-left:4px; flex-shrink:0; }
.extra-card.ec-left-rec .ec-dot { background:#ef4444; animation:dotpulse 1s infinite; }

/* Penanya card (hakim) shown in extra bar when an extra has taken over */
#hakimRestoreCard {
    display:none; align-items:center; gap:6px;
    padding:5px 12px; border-radius:7px; border:1.5px dashed var(--b2);
    background:none; cursor:pointer; transition:all .15s; font-family:'Segoe UI',sans-serif; color:var(--muted); font-size:.72rem; font-weight:700;
}
#hakimRestoreCard:hover { border-color:var(--sub); color:var(--sub); }
#hakimRestoreCard.visible { display:flex; }

/* ── TRANSCRIPT ── */
#transcriptArea { flex:1; overflow-y:auto; padding:14px 22px; display:flex; flex-direction:column; gap:9px; scroll-behavior:smooth; }
.empty-state { margin:auto; text-align:center; color:var(--b2); }
.empty-state .ei { font-size:2.4rem; margin-bottom:10px; }
.empty-state p { font-size:.82rem; line-height:2; }
.empty-state strong { color:var(--muted); font-style:normal; }
.entry { display:flex; gap:9px; animation:fadeUp .22s ease; }
@keyframes fadeUp { from{opacity:0;transform:translateY(6px)} to{opacity:1;transform:none} }
.e-av   { width:32px; height:32px; border-radius:50%; display:flex; align-items:center; justify-content:center; font-size:.88rem; flex-shrink:0; margin-top:2px; }
.e-body { flex:1; min-width:0; }
.e-meta { display:flex; align-items:baseline; gap:7px; margin-bottom:3px; flex-wrap:wrap; }
.e-name { font-weight:700; font-size:.82rem; }
.e-role { font-size:.64rem; color:var(--muted); font-weight:600; text-transform:uppercase; font-family:'Segoe UI',sans-serif; }
.e-time { font-size:.63rem; color:#1e3a55; margin-left:auto; white-space:nowrap; font-family:'Segoe UI',sans-serif; }
.e-bub  { border-radius:0 9px 9px 9px; padding:8px 12px; font-size:.86rem; line-height:1.7; color:#8eb5d5; white-space:pre-wrap; word-break:break-word; position:relative; }
.e-bub.processing { font-style:italic; color:var(--muted); }
.e-play { position:absolute; top:6px; right:8px; background:var(--border); border:none; border-radius:4px; color:var(--text); padding:2px 7px; font-size:.63rem; cursor:pointer; opacity:.55; transition:opacity .15s; font-family:'Segoe UI',sans-serif; }
.e-play:hover { opacity:1; } .e-play.playing { background:#8b1515; opacity:1; }

/* ── RECORDING CONTROL BAR ── */
#recCtrlBar {
    background:#0a0f1a; border-bottom:1px solid #2a1010;
    padding:8px 18px; display:none; align-items:center; gap:10px; flex-wrap:wrap;
}
#recCtrlBar.visible { display:flex; }

.rec-indicator {
    display:flex; align-items:center; gap:7px; flex:1; min-width:0;
}
.rec-dot-big {
    width:11px; height:11px; border-radius:50%; background:#ef4444; flex-shrink:0;
    animation:dotpulse 1s infinite;
}
.rec-dot-big.paused { background:#f59e0b; animation:none; }
.rec-who {
    font-size:.8rem; font-weight:700; font-family:'Segoe UI',sans-serif;
    white-space:nowrap; overflow:hidden; text-overflow:ellipsis;
}
.rec-state {
    font-size:.68rem; color:var(--muted); font-family:'Segoe UI',sans-serif; white-space:nowrap;
}
.rec-timer {
    font-family:monospace; font-size:.9rem; color:#f87171; flex-shrink:0;
    min-width:46px; text-align:right;
}
.rec-timer.paused { color:#f59e0b; }

.ctrl-btns { display:flex; gap:6px; flex-shrink:0; }
.ctrl-btn {
    padding:6px 14px; border:none; border-radius:7px;
    font-size:.76rem; font-weight:800; cursor:pointer;
    font-family:'Segoe UI',sans-serif; transition:all .15s; white-space:nowrap;
}
/* Jeda / Resume */
.ctrl-btn-pause  { background:#3d2900; color:#fbbf24; }
.ctrl-btn-pause:hover  { background:#78500a; }
.ctrl-btn-resume { background:#1a3d0a; color:#86efac; }
.ctrl-btn-resume:hover { background:#2a6010; }
/* Akhiri giliran — stop without auto-continue */
.ctrl-btn-stop   { background:#3d0a0a; color:#fca5a5; }
.ctrl-btn-stop:hover   { background:#6a1010; }
/* Lanjut / SPASI hint */
.ctrl-btn-next   { background:#0c2a4a; color:#7ec8f5; }
.ctrl-btn-next:hover   { background:#1a5fa0; }
.ctrl-kbd { background:var(--surface); border:1px solid var(--b2); border-bottom:2px solid var(--b2); border-radius:4px; padding:2px 10px; font-family:monospace; font-size:.76rem; color:var(--text); }

/* ── BOTTOM BAR ── */
.bot-bar { background:var(--surface); border-top:1px solid var(--border); padding:6px 18px; display:flex; align-items:center; gap:12px; font-size:.73rem; font-family:'Segoe UI',sans-serif; color:var(--muted); }
#botStatus { flex:1; }

/* ── MODALS ── */
.modal-overlay { position:fixed; inset:0; background:rgba(0,0,0,.78); display:none; align-items:center; justify-content:center; z-index:200; }
.modal-overlay.open { display:flex; }
.modal-card { background:var(--surface); border:1px solid var(--b2); border-radius:12px; padding:20px; width:430px; max-width:95vw; max-height:80vh; overflow-y:auto; box-shadow:0 24px 64px rgba(0,0,0,.75); }
.modal-hd { display:flex; align-items:center; margin-bottom:14px; }
.modal-hd h3 { font-size:.88rem; flex:1; font-style:italic; }
.modal-close { background:none; border:none; color:var(--muted); font-size:1rem; cursor:pointer; }
.modal-close:hover { color:var(--text); }
.modal-chips { display:flex; flex-wrap:wrap; gap:5px; margin-bottom:12px; }
.modal-chip { padding:5px 11px; border-radius:999px; border:1.5px solid var(--b2); background:var(--surface); font-size:.72rem; font-weight:700; cursor:pointer; font-family:'Segoe UI',sans-serif; transition:all .15s; }
.modal-chip:hover { color:var(--text); border-color:var(--sub); }
.modal-chip.msel { outline:2px solid currentColor; }
.modal-name-row { display:flex; gap:7px; align-items:center; }
.modal-name-row input { flex:1; background:var(--panel); border:1px solid var(--b2); border-radius:6px; color:var(--text); padding:7px 10px; font-size:.8rem; outline:none; font-family:inherit; }
.modal-name-row input:focus { border-color:#2275b8; }
.modal-add-btn { padding:7px 16px; background:#0d3d6a; color:#8dcff5; border:none; border-radius:6px; font-size:.78rem; font-weight:800; cursor:pointer; font-family:'Segoe UI',sans-serif; }
.modal-add-btn:hover { background:#1a5fa0; }

/* PLAYBACK */
.pm-card { background:var(--surface); border:1px solid var(--b2); border-radius:12px; padding:18px; width:500px; max-width:95vw; max-height:80vh; overflow-y:auto; box-shadow:0 24px 64px rgba(0,0,0,.75); }
.pm-item { background:var(--panel); border-radius:8px; padding:9px 12px; margin-bottom:6px; border-left:3px solid var(--b2); }
.pm-item.now { outline:2px solid #2275b8; }
.pm-hd2 { display:flex; align-items:center; gap:7px; margin-bottom:4px; }
.pm-av { width:22px; height:22px; border-radius:50%; display:flex; align-items:center; justify-content:center; font-size:.67rem; flex-shrink:0; }
.pm-nm { font-size:.78rem; font-weight:700; flex:1; }
.pm-ts { font-size:.63rem; color:var(--muted); font-family:'Segoe UI',sans-serif; }
.pm-tx { font-size:.73rem; color:var(--sub); margin-bottom:4px; line-height:1.4; }
.pm-audio { width:100%; height:26px; }
.pm-ctrl { display:flex; gap:6px; margin-top:12px; }
.pm-btn { flex:1; padding:7px; border:none; border-radius:6px; font-size:.75rem; font-weight:700; cursor:pointer; font-family:'Segoe UI',sans-serif; }
.pm-btn:disabled { opacity:.3; cursor:not-allowed; }
.pm-play { background:#0c3d6a; color:#8dcff5; } .pm-stop { background:#6a0c0c; color:#fca5a5; } .pm-nav { background:var(--border); color:var(--text); }
.pm-stat { text-align:center; font-size:.67rem; color:var(--muted); margin-top:6px; font-family:'Segoe UI',sans-serif; }

::-webkit-scrollbar { width:4px; } ::-webkit-scrollbar-track { background:var(--bg); } ::-webkit-scrollbar-thumb { background:var(--b2); border-radius:2px; }
</style>
</head>
<body>

<header>
    <span class="brand">⚖ Transkripsi Sidang</span>
    <div class="perkara-row">
        <input id="inPerkara" placeholder="No. Perkara — mis: 123/Pid.B/2025/PN.Jkt" />
        <input id="inHakim"   placeholder="Nama Hakim Ketua" />
        <input id="inLokasi"  placeholder="Pengadilan / Kota" />
    </div>
    <div class="hbtns">
        <button class="hbtn hbtn-blue"  onclick="openPlayback()">▶ Putar</button>
        <button class="hbtn hbtn-amber" onclick="exportDoc()">⬇ Export</button>
        <button class="hbtn"            onclick="resetAll()">🗑 Reset</button>
        <a href="/" style="color:var(--muted);font-size:.72rem;text-decoration:none;font-family:'Segoe UI',sans-serif;">← Kembali</a>
    </div>
</header>

<div id="mainArea">

<!-- STEP 0 -->
<div id="stepType" style="flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:22px;padding:30px 20px;">
    <div class="step-lbl">Pilih Jenis Perkara</div>
    <div class="type-cards">
        <div class="type-card tc-pidana" onclick="selectType('pidana',this)">
            <div class="tc-icon">🔒</div>
            <div class="tc-name">Pidana / Jinayat</div>
            <div class="tc-sub">PN, Pengadilan Militer<br>&amp; Mahkamah Syar'iyah</div>
            <div class="tc-check">✓</div>
        </div>
        <div class="type-card tc-perdata" onclick="selectType('perdata',this)">
            <div class="tc-icon">📜</div>
            <div class="tc-name">Perdata</div>
            <div class="tc-sub">Gugatan, sengketa hak<br>&amp; keperdataan</div>
            <div class="tc-check">✓</div>
        </div>
    </div>
    <button class="btn-primary" id="btnStep1" onclick="goStep1()" disabled>Lanjut Atur Peserta →</button>
</div>

<!-- STEP 1 -->
<div id="stepSetup">
    <div class="setup-hd">
        <h2>Atur Peserta Sidang</h2>
        <span class="type-pill" id="setupPill"></span>
        <button class="btn-ghost" onclick="goStep0Back()" style="margin-left:auto;">← Ubah Jenis</button>
    </div>
    <div class="setup-cols">
        <div class="setup-col">
            <div class="sc-title">🎙 Sisi Kiri (Penanya Default)</div>
            <div class="sc-desc">Hakim atau pihak yang memimpin tanya jawab</div>
            <div class="role-btns" id="rbPenanya"></div>
            <input class="sc-name" id="namaPenanya" placeholder="Nama (mis: Hakim Dr. Budi)" />
        </div>
        <div class="setup-col">
            <div class="sc-title">🗣 Sisi Kanan (Responden)</div>
            <div class="sc-desc">Hanya Saksi, Terdakwa, atau Ahli</div>
            <div class="role-btns" id="rbResponden"></div>
            <input class="sc-name" id="namaResponden" placeholder="Nama (mis: Andi)" />
        </div>
    </div>
    <div class="extra-section">
        <div class="sc-title">➕ Peserta Lain (Jaksa, Penasihat Hukum, dll.)</div>
        <div class="extra-hint">Ketika diklik saat sidang, mereka <strong>menggantikan sisi kiri</strong> — toggle jadi mereka ↔ Responden terus-menerus. Klik Hakim di bar untuk kembali ke toggle semula.</div>
        <div class="extra-chip-row" id="extraChips"></div>
        <div class="extra-list" id="extraList"></div>
    </div>
    <div class="engine-row">
        <label>Engine:</label>
        <select id="cfgEngine"><option value="local">🖥 Local Whisper</option><option value="api">☁ OpenAI API</option></select>
        <label style="margin-left:8px;">Model:</label>
        <select id="cfgModel">
            <option value="tiny">Tiny</option><option value="base" selected>Base</option>
            <option value="small">Small</option><option value="medium">Medium</option><option value="large">Large</option>
        </select>
    </div>
    <div class="setup-actions">
        <button class="btn-green" onclick="startSession()">Mulai Sidang →</button>
        <span style="font-size:.71rem;color:var(--muted);font-family:'Segoe UI',sans-serif;">Pilih peran untuk kedua sisi.</span>
    </div>
</div>

<!-- STEP 2 -->
<div id="stepSession">

    <!-- PAIR BAR: LEFT side (changes) | center | RIGHT (always responden) -->
    <div id="pairBar">
        <!-- LEFT -->
        <div class="pair-side" id="sideL" onclick="clickLeft()">
            <div class="ps-av"     id="avL"></div>
            <div class="ps-labels">
                <div class="ps-role" id="roleL"></div>
                <div class="ps-name" id="nameL"></div>
                <div class="ps-tag"  id="tagL"></div>
            </div>
            <div class="ps-dot"></div>
            <div class="ps-badge">GILIRAN BERIKUTNYA</div>
        </div>

        <div class="pair-center">
            <div class="pair-arrow">⇄</div>
            <span class="kbd">SPASI</span>
            <span>akhiri →<br>auto lanjut</span>
        </div>

        <!-- RIGHT: always responden -->
        <div class="pair-side" id="sideR" onclick="clickRight()">
            <div class="ps-av"     id="avR"></div>
            <div class="ps-labels">
                <div class="ps-role" id="roleR"></div>
                <div class="ps-name" id="nameR"></div>
                <div class="ps-tag"  id="tagR"></div>
            </div>
            <div class="ps-dot"></div>
            <div class="ps-badge">GILIRAN BERIKUTNYA</div>
        </div>

        <div class="session-meta">
            <button class="btn-add-e" onclick="openAddModal()">＋ Peserta</button>
            <button class="btn-sm"    onclick="changeSetup()">✏️ Ubah</button>
        </div>
    </div>

    <!-- EXTRA BAR -->
    <div id="extraBar" class="hidden">
        <span class="eb-lbl">Ganti Sisi Kiri:</span>
        <!-- "Hakim" restore button, visible when extra is active -->
        <div id="hakimRestoreCard" onclick="restoreDefaultLeft()"></div>
        <div id="extraCards" style="display:flex;flex-wrap:wrap;gap:6px;align-items:center;"></div>
    </div>

    <!-- RECORDING CONTROL BAR — visible only when recording/paused -->
    <div id="recCtrlBar">
        <div class="rec-indicator">
            <div class="rec-dot-big" id="recDot"></div>
            <div>
                <div class="rec-who" id="recWho"></div>
                <div class="rec-state" id="recState">Merekam…</div>
            </div>
        </div>
        <div class="rec-timer" id="recTimer">0:00</div>
        <div class="ctrl-btns">
            <button class="ctrl-btn ctrl-btn-pause"  id="btnPause" onclick="togglePause()">⏸ Jeda</button>
            <button class="ctrl-btn ctrl-btn-stop"   onclick="stopManual()">⏹ Akhiri Giliran</button>
            <button class="ctrl-btn ctrl-btn-next"   onclick="handleSpace()"><span class="ctrl-kbd">SPASI</span> → Lanjut ke Berikutnya</button>
        </div>
    </div>

    <!-- TRANSCRIPT -->
    <div id="transcriptArea">
        <div class="empty-state" id="emptyState">
            <div class="ei">⚖️</div>
            <p>Tekan <strong>SPASI</strong> → mulai rekam sisi kiri (Penanya).<br>
            Tekan <strong>SPASI</strong> lagi → berhenti &amp; <strong>otomatis lanjut</strong> ke Responden.<br>
            Tekan lagi → otomatis balik ke kiri. Dan seterusnya.<br>
            Klik nama di bar bawah untuk ganti siapa yang di sisi kiri.</p>
        </div>
    </div>
</div>

</div>

<div class="bot-bar">
    <span id="botStatus">Pilih jenis perkara terlebih dahulu.</span>
    <span id="botCount">0 giliran</span>
</div>

<!-- ADD EXTRA MODAL -->
<div class="modal-overlay" id="addModal">
    <div class="modal-card">
        <div class="modal-hd"><h3>＋ Tambah Peserta Lain</h3><button class="modal-close" onclick="closeAddModal()">✕</button></div>
        <div class="modal-chips" id="modalChips"></div>
        <div id="modalForm" style="display:none;">
            <div style="font-size:.7rem;color:var(--muted);margin-bottom:6px;font-family:'Segoe UI',sans-serif;" id="modalHint"></div>
            <div class="modal-name-row">
                <input id="modalName" placeholder="Nama peserta (opsional)" />
                <button class="modal-add-btn" onclick="confirmAdd()">Tambah</button>
            </div>
        </div>
    </div>
</div>

<!-- PLAYBACK MODAL -->
<div class="modal-overlay" id="playbackModal">
    <div class="pm-card">
        <div class="modal-hd"><h3>▶ Putar Rekaman</h3><button class="modal-close" onclick="closePlayback()">✕</button></div>
        <div id="pmList"></div>
        <div class="pm-ctrl">
            <button class="pm-btn pm-nav"  id="pmPrev" onclick="pmGo(pmIdx-1)">⏮</button>
            <button class="pm-btn pm-play" id="pmPlay" onclick="pmToggle()">▶ Putar</button>
            <button class="pm-btn pm-stop" onclick="pmStop()">⏹</button>
            <button class="pm-btn pm-nav"  id="pmNext" onclick="pmGo(pmIdx+1)">⏭</button>
        </div>
        <div class="pm-stat" id="pmStat">–</div>
    </div>
</div>

<script>
// ═══════════════════════════════════════════
//  ROLE DATA
// ═══════════════════════════════════════════
var ROLES = {
    pidana: {
        penanya: [
            { id:'hakim_ketua',   label:'Hakim Ketua',     emoji:'👨‍⚖️', bg:'#0a2550', fg:'#90c4f8', tag:'HAKIM KETUA' },
            { id:'hakim_anggota', label:'Hakim Anggota',   emoji:'⚖️',   bg:'#0a2550', fg:'#90c4f8', tag:'HAKIM ANGGOTA' },
            { id:'jaksa',         label:'Jaksa',           emoji:'🔴',   bg:'#380808', fg:'#f8a0a0', tag:'JAKSA' },
            { id:'ph',            label:'Penasihat Hukum', emoji:'🧑‍💼', bg:'#28154a', fg:'#c4b2fa', tag:'PENASIHAT HUKUM' },
        ],
        responden: [
            { id:'saksi',    label:'Saksi',    emoji:'🗣️', bg:'#082a18', fg:'#60e0a0', tag:'SAKSI' },
            { id:'terdakwa', label:'Terdakwa', emoji:'🧑',  bg:'#281500', fg:'#fcd060', tag:'TERDAKWA' },
            { id:'ahli',     label:'Ahli',     emoji:'🎓',  bg:'#082828', fg:'#60e0e0', tag:'AHLI' },
        ],
        extra: [
            { id:'hakim_ketua',   label:'Hakim Ketua',     emoji:'👨‍⚖️', bg:'#0a2550', fg:'#90c4f8', tag:'HAKIM KETUA' },
            { id:'hakim_anggota', label:'Hakim Anggota',   emoji:'⚖️',   bg:'#0a2550', fg:'#90c4f8', tag:'HAKIM ANGGOTA' },
            { id:'panitera',      label:'Panitera',        emoji:'📋',   bg:'#0f2030', fg:'#70b8e8', tag:'PANITERA' },
            { id:'jaksa',         label:'Jaksa',           emoji:'🔴',   bg:'#380808', fg:'#f8a0a0', tag:'JAKSA' },
            { id:'ph',            label:'Penasihat Hukum', emoji:'🧑‍💼', bg:'#28154a', fg:'#c4b2fa', tag:'PENASIHAT HUKUM' },
            { id:'saksi',         label:'Saksi',           emoji:'🗣️',  bg:'#082a18', fg:'#60e0a0', tag:'SAKSI' },
            { id:'terdakwa',      label:'Terdakwa',        emoji:'🧑',   bg:'#281500', fg:'#fcd060', tag:'TERDAKWA' },
            { id:'ahli',          label:'Ahli',            emoji:'🎓',   bg:'#082828', fg:'#60e0e0', tag:'AHLI' },
        ],
    },
    perdata: {
        penanya: [
            { id:'hakim_ketua',   label:'Hakim Ketua',   emoji:'👨‍⚖️', bg:'#0a2550', fg:'#90c4f8', tag:'HAKIM KETUA' },
            { id:'hakim_anggota', label:'Hakim Anggota', emoji:'⚖️',   bg:'#0a2550', fg:'#90c4f8', tag:'HAKIM ANGGOTA' },
            { id:'kh_penggugat',  label:'KH Penggugat',  emoji:'👔',   bg:'#142808', fg:'#a0d860', tag:'KUASA HUKUM PENGGUGAT' },
            { id:'kh_tergugat',   label:'KH Tergugat',   emoji:'🕴️',  bg:'#301808', fg:'#f8a060', tag:'KUASA HUKUM TERGUGAT' },
        ],
        responden: [
            { id:'saksi',     label:'Saksi',             emoji:'🗣️', bg:'#082a18', fg:'#60e0a0', tag:'SAKSI' },
            { id:'penggugat', label:'Penggugat/Pemohon', emoji:'📣',  bg:'#0a3018', fg:'#80e890', tag:'PENGGUGAT' },
            { id:'tergugat',  label:'Tergugat/Termohon', emoji:'🛡️', bg:'#381808', fg:'#f8b060', tag:'TERGUGAT' },
            { id:'ahli',      label:'Ahli',              emoji:'🎓',  bg:'#082828', fg:'#60e0e0', tag:'AHLI' },
        ],
        extra: [
            { id:'hakim_ketua',   label:'Hakim Ketua',           emoji:'👨‍⚖️', bg:'#0a2550', fg:'#90c4f8', tag:'HAKIM KETUA' },
            { id:'hakim_anggota', label:'Hakim Anggota',         emoji:'⚖️',   bg:'#0a2550', fg:'#90c4f8', tag:'HAKIM ANGGOTA' },
            { id:'panitera',      label:'Panitera',              emoji:'📋',   bg:'#0f2030', fg:'#70b8e8', tag:'PANITERA' },
            { id:'kh_penggugat',  label:'KH Penggugat',          emoji:'👔',   bg:'#142808', fg:'#a0d860', tag:'KUASA HUKUM PENGGUGAT' },
            { id:'kh_tergugat',   label:'KH Tergugat',           emoji:'🕴️',  bg:'#301808', fg:'#f8a060', tag:'KUASA HUKUM TERGUGAT' },
            { id:'saksi',         label:'Saksi',                 emoji:'🗣️',  bg:'#082a18', fg:'#60e0a0', tag:'SAKSI' },
            { id:'penggugat',     label:'Penggugat/Pemohon',     emoji:'📣',   bg:'#0a3018', fg:'#80e890', tag:'PENGGUGAT' },
            { id:'tergugat',      label:'Tergugat/Termohon',     emoji:'🛡️',  bg:'#381808', fg:'#f8b060', tag:'TERGUGAT' },
            { id:'ahli',          label:'Ahli',                  emoji:'🎓',   bg:'#082828', fg:'#60e0e0', tag:'AHLI' },
        ],
    },
};

// ═══════════════════════════════════════════
//  STATE
//
//  Toggle model — always LEFT ↔ RIGHT:
//    RIGHT = responden (fixed forever)
//    LEFT  = whoever activeLeftPid points to:
//              null  → penanya (Hakim, default)
//              pid   → that extra participant
//
//  SPASI never resets activeLeftPid.
//  Only user actions change who's on the left:
//    • click extra card  → activeLeftPid = ep.pid
//    • click ↩ Hakim     → activeLeftPid = null
//
//  pendingLeftPid: if user clicks extra WHILE recording,
//  we swap after current recording ends.
// ═══════════════════════════════════════════
var caseType = null;
var pickP = null, pickR = null;
var extraParticipants = [], nextPid = 1;

var penanya   = null;   // hakim — default left
var responden = null;   // always right

var sessionOn      = false;
var currentSide    = 'left';   // 'left' | 'right'
var activeLeftPid  = null;     // null = hakim, number = extra pid
var pendingLeftPid = null;     // swap queued for after current recording
var isRecording    = false;
var isPaused       = false;    // MediaRecorder paused
var autoNext       = true;     // if false, stop without auto-continuing
var recTimerVal    = 0;        // seconds elapsed in current recording
var recTimerIv     = null;     // setInterval handle for timer
var mediaRec = null, recChunks = [], recStream = null;
var transcript = [];
var inlAudio = null, inlId = null;
var pmIdx = -1, pmAudioEl = null, pmPlaying = false;
var modalRole = null;

// Helper: get the person currently on the LEFT side
function leftPerson() {
    if (activeLeftPid === null) return penanya;
    var ep = extraParticipants.find(function(x) { return x.pid === activeLeftPid; });
    if (!ep) { activeLeftPid = null; return penanya; } // guard: ep deleted
    return epToPerson(ep);
}
function epToPerson(ep) {
    return { name:ep.name, role:ep.role.label, emoji:ep.role.emoji, bg:ep.role.bg, fg:ep.role.fg, tag:ep.role.tag };
}

// ═══════════════════════════════════════════
//  STEP 0
// ═══════════════════════════════════════════
function selectType(type, el) {
    document.querySelectorAll('.type-card').forEach(function(c) { c.classList.remove('sel'); });
    el.classList.add('sel'); caseType = type;
    document.getElementById('btnStep1').disabled = false;
}
function goStep1() {
    if (!caseType) return;
    var pill = document.getElementById('setupPill');
    pill.textContent = caseType === 'pidana' ? 'PIDANA / JINAYAT' : 'PERDATA';
    pill.className   = 'type-pill ' + (caseType === 'pidana' ? 'pill-pidana' : 'pill-perdata');
    buildRoleBtns(); buildExtraChips(); renderExtraSetupList();
    showStep('stepSetup'); setStatus('Pilih peran untuk kedua sisi.');
}
function goStep0Back() {
    if (isRecording) { alert('Hentikan rekaman dulu.'); return; }
    pickP = null; pickR = null; showStep('stepType');
}

// ═══════════════════════════════════════════
//  STEP 1 — SETUP
// ═══════════════════════════════════════════
function buildRoleBtns() {
    var cp = document.getElementById('rbPenanya');   cp.innerHTML = '';
    var cr = document.getElementById('rbResponden'); cr.innerHTML = '';
    ROLES[caseType].penanya.forEach(function(r)   { cp.appendChild(mkRoleBtn(r,'penanya')); });
    ROLES[caseType].responden.forEach(function(r) { cr.appendChild(mkRoleBtn(r,'responden')); });
}
function mkRoleBtn(r, side) {
    var btn = document.createElement('button');
    btn.className = 'role-btn';
    btn.innerHTML = r.emoji + ' ' + r.label;
    btn.style.color = r.fg; btn.style.borderColor = r.bg;
    btn.onclick = function() {
        btn.closest('.role-btns').querySelectorAll('.role-btn').forEach(function(b) {
            b.classList.remove('sel'); b.style.background = '';
        });
        btn.classList.add('sel'); btn.style.background = r.bg;
        if (side === 'penanya') pickP = r; else pickR = r;
    };
    return btn;
}
function buildExtraChips() {
    var chips = document.getElementById('extraChips'); chips.innerHTML = '';
    ROLES[caseType].extra.forEach(function(r) {
        var chip = document.createElement('button');
        chip.className = 'extra-chip'; chip.style.color = r.fg;
        chip.innerHTML = r.emoji + ' ' + r.label;
        chip.onclick = function() { addExtra(r); };
        chips.appendChild(chip);
    });
}
function addExtra(role) {
    extraParticipants.push({ pid: nextPid++, role: role, name: role.label });
    renderExtraSetupList();
}
function renderExtraSetupList() {
    var list = document.getElementById('extraList'); list.innerHTML = '';
    extraParticipants.forEach(function(ep) {
        var r = ep.role;
        var item = document.createElement('div'); item.className = 'extra-item';
        item.innerHTML =
            '<div class="ei-av" style="background:'+r.bg+';color:'+r.fg+';">'+r.emoji+'</div>' +
            '<div class="ei-lbl">'+esc(r.label)+'</div>' +
            '<input class="ei-nm" placeholder="Nama (opsional)" value="'+esc(ep.name===r.label?'':ep.name)+'" data-pid="'+ep.pid+'" oninput="syncEN(this)" />' +
            '<button class="ei-rm" onclick="removeExtra('+ep.pid+')">✕</button>';
        list.appendChild(item);
    });
}
function syncEN(inp) {
    var ep = extraParticipants.find(function(x) { return x.pid===parseInt(inp.dataset.pid); });
    if (ep) ep.name = inp.value.trim() || ep.role.label;
}
function removeExtra(pid) {
    extraParticipants = extraParticipants.filter(function(x) { return x.pid!==pid; });
    renderExtraSetupList();
}

// ═══════════════════════════════════════════
//  START SESSION
// ═══════════════════════════════════════════
function startSession() {
    if (!pickP) { alert('Pilih peran untuk sisi Kiri (Penanya).'); return; }
    if (!pickR) { alert('Pilih peran untuk sisi Kanan (Responden).'); return; }
    document.querySelectorAll('.ei-nm').forEach(function(inp) {
        var ep = extraParticipants.find(function(x) { return x.pid===parseInt(inp.dataset.pid); });
        if (ep) ep.name = inp.value.trim() || ep.role.label;
    });
    penanya   = mkPerson(pickP, document.getElementById('namaPenanya').value.trim());
    responden = mkPerson(pickR, document.getElementById('namaResponden').value.trim());
    activeLeftPid  = null;
    pendingLeftPid = null;
    sessionOn      = true;
    currentSide    = 'left';

    fillPairBar(); buildExtraBar();
    showStep('stepSession'); updateHighlight();
    var lp = leftPerson();
    setStatus('Tekan SPASI untuk mulai merekam ' + lp.emoji + ' ' + lp.name);
}
function mkPerson(r, nameOverride) {
    return { name: nameOverride||r.label, role:r.label, emoji:r.emoji, bg:r.bg, fg:r.fg, tag:r.tag };
}
function changeSetup() {
    if (isRecording) { alert('Hentikan rekaman dulu.'); return; }
    sessionOn = false; hideRecCtrl(); showStep('stepSetup');
}

// ═══════════════════════════════════════════
//  PAIR BAR
// ═══════════════════════════════════════════
function fillPairBar() {
    var lp = leftPerson();
    setAv('avL', lp.emoji, lp.bg, lp.fg);
    document.getElementById('roleL').textContent = lp.role;
    document.getElementById('nameL').textContent = lp.name;
    document.getElementById('tagL').textContent  = lp.tag;
    setAv('avR', responden.emoji, responden.bg, responden.fg);
    document.getElementById('roleR').textContent = responden.role;
    document.getElementById('nameR').textContent = responden.name;
    document.getElementById('tagR').textContent  = responden.tag;
}
function setAv(id, emoji, bg, fg) {
    var el = document.getElementById(id);
    el.textContent = emoji; el.style.background = bg; el.style.color = fg;
}

function updateHighlight() {
    var sl = document.getElementById('sideL');
    var sr = document.getElementById('sideR');
    sl.className = 'pair-side'; sr.className = 'pair-side';
    if (!sessionOn) return;
    if (isRecording) {
        if (currentSide === 'left')  { sl.classList.add('is-rec');  sr.classList.add('next-up'); }
        else                         { sr.classList.add('is-rec');  sl.classList.add('next-up'); }
    } else {
        if (currentSide === 'left')  sl.classList.add('next-up');
        else                         sr.classList.add('next-up');
    }
}

// Click left pair card → restore hakim if extra is active
function clickLeft() {
    if (isRecording) return;
    if (activeLeftPid === null) return; // already hakim
    restoreDefaultLeft();
}
// Click right pair card → set next turn to right
function clickRight() {
    if (isRecording) return;
    currentSide = 'right';
    updateHighlight();
    setStatus('Giliran ' + responden.emoji + ' ' + responden.name + ' — tekan SPASI untuk mulai merekam');
}

// ═══════════════════════════════════════════
//  EXTRA BAR — clicking replaces LEFT side permanently until changed
// ═══════════════════════════════════════════
function buildExtraBar() {
    var bar = document.getElementById('extraBar');
    if (!extraParticipants.length) { bar.classList.add('hidden'); return; }
    bar.classList.remove('hidden');
    renderExtraCards();
}

function renderExtraCards() {
    var hrc = document.getElementById('hakimRestoreCard');
    // Show hakim restore button only when an extra is active on left
    if (activeLeftPid !== null) {
        hrc.className = 'visible';
        hrc.innerHTML =
            '<div style="width:20px;height:20px;border-radius:50%;background:'+penanya.bg+';color:'+penanya.fg+';display:flex;align-items:center;justify-content:center;font-size:.65rem;">'+penanya.emoji+'</div>' +
            '<span style="font-size:.72rem;">↩ '+esc(penanya.name)+'</span>';
    } else {
        hrc.className = '';
    }

    var container = document.getElementById('extraCards'); container.innerHTML = '';
    extraParticipants.forEach(function(ep) {
        var r = ep.role;
        var isLeft    = activeLeftPid === ep.pid;
        var isPending = pendingLeftPid === ep.pid;
        var isRec     = isLeft && isRecording && currentSide === 'left';
        var card = document.createElement('div');
        card.className = 'extra-card' + (isRec ? ' ec-left-rec' : isLeft ? ' ec-left' : '');
        card.innerHTML =
            '<div class="ec-av" style="background:'+r.bg+';color:'+r.fg+';">'+r.emoji+'</div>' +
            '<div><div class="ec-role">'+esc(r.label)+'</div><div class="ec-name">'+esc(ep.name)+(isPending?' ⏳':'')+'</div></div>' +
            '<div class="ec-dot"></div>';
        card.onclick = function() { clickExtraCard(ep); };
        container.appendChild(card);
    });
    var ab = document.createElement('button');
    ab.className = 'btn-add-e'; ab.textContent = '＋'; ab.onclick = openAddModal;
    container.appendChild(ab);
}

function clickExtraCard(ep) {
    if (isRecording) {
        // Queue swap for after current recording ends
        pendingLeftPid = (pendingLeftPid === ep.pid) ? null : ep.pid;
        renderExtraCards();
        setStatus(pendingLeftPid !== null
            ? '📌 Setelah giliran ini → sisi kiri berganti ke ' + ep.role.emoji + ' ' + ep.name
            : 'Antrian dibatalkan.');
        return;
    }
    // Toggle: clicking active extra again → restore hakim
    if (activeLeftPid === ep.pid) {
        restoreDefaultLeft(); return;
    }
    // Set this extra as left side
    activeLeftPid  = ep.pid;
    pendingLeftPid = null;
    currentSide    = 'left';
    fillPairBar(); updateHighlight(); renderExtraCards();
    var lp = leftPerson();
    setStatus('Sisi kiri: ' + lp.emoji + ' ' + lp.name + ' ↔ ' + responden.emoji + ' ' + responden.name + ' — tekan SPASI');
}

function restoreDefaultLeft() {
    activeLeftPid  = null;
    pendingLeftPid = null;
    currentSide    = 'left';
    fillPairBar(); updateHighlight(); renderExtraCards();
    setStatus('Sisi kiri kembali ke ' + penanya.emoji + ' ' + penanya.name + ' — tekan SPASI untuk mulai');
}

// ═══════════════════════════════════════════
//  SPACEBAR — stop current → auto-start other side
//  activeLeftPid NEVER changes automatically.
//  SPASI only flips currentSide: 'left' ↔ 'right'.
// ═══════════════════════════════════════════
document.addEventListener('keydown', function(e) {
    if (e.target.tagName==='INPUT'||e.target.tagName==='TEXTAREA'||e.target.tagName==='SELECT') return;
    if (e.code==='Space') { e.preventDefault(); handleSpace(); }
});

function handleSpace() {
    if (!sessionOn) return;
    if (!isRecording) {
        autoNext = true;   // SPASI always auto-continues
        startRec();
    } else if (isPaused) {
        resumeRec();       // if paused, SPASI resumes then auto-continues
    } else {
        autoNext = true;
        stopAndFinalize();
    }
}

// ── PAUSE ──────────────────────────────────
function togglePause() {
    if (!isRecording) return;
    if (isPaused) resumeRec(); else pauseRec();
}
function pauseRec() {
    if (!mediaRec || mediaRec.state !== 'recording') return;
    mediaRec.pause();
    isPaused = true;
    clearInterval(recTimerIv);
    document.getElementById('recDot').classList.add('paused');
    document.getElementById('recTimer').classList.add('paused');
    document.getElementById('recState').textContent = 'Dijeda';
    document.getElementById('btnPause').className = 'ctrl-btn ctrl-btn-resume';
    document.getElementById('btnPause').textContent = '▶ Lanjutkan';
    setStatus('⏸ Rekaman dijeda — klik Lanjutkan atau tekan SPASI untuk resume');
}
function resumeRec() {
    if (!mediaRec || mediaRec.state !== 'paused') return;
    mediaRec.resume();
    isPaused = false;
    startTimer();
    document.getElementById('recDot').classList.remove('paused');
    document.getElementById('recTimer').classList.remove('paused');
    document.getElementById('recState').textContent = 'Merekam…';
    document.getElementById('btnPause').className = 'ctrl-btn ctrl-btn-pause';
    document.getElementById('btnPause').textContent = '⏸ Jeda';
    var person = currentSide === 'left' ? leftPerson() : responden;
    setStatus('🔴 Merekam ' + person.emoji + ' ' + person.name + ' — SPASI untuk akhiri & lanjut');
}

// ── STOP MANUAL (no auto-continue) ─────────
function stopManual() {
    if (!isRecording) return;
    autoNext = false;
    isPaused = false;
    stopAndFinalize();
}

// ── STOP & FINALIZE ─────────────────────────
function stopAndFinalize() {
    if (mediaRec && mediaRec.state !== 'inactive') mediaRec.stop();
    if (recStream) { recStream.getTracks().forEach(function(t){t.stop();}); recStream = null; }
    // onstop → finalize → scheduleNext/goIdle
}

function scheduleNext(doneSide, shouldAutoNext) {
    isRecording = false;
    isPaused    = false;
    hideRecCtrl();

    if (!shouldAutoNext) {
        // Manual stop — go idle, wait for SPASI
        // Apply any pending left swap
        if (pendingLeftPid !== null) {
            activeLeftPid  = pendingLeftPid;
            pendingLeftPid = null;
            fillPairBar();
        }
        // Flip side so next SPASI goes to the OTHER person
        currentSide = (doneSide === 'left') ? 'right' : 'left';
        updateHighlight(); renderExtraCards();
        var next = currentSide === 'left' ? leftPerson() : responden;
        setStatus('⏹ Selesai — tekan SPASI untuk mulai giliran ' + next.emoji + ' ' + next.name);
        return;
    }

    // Auto-continue
    if (pendingLeftPid !== null) {
        activeLeftPid  = pendingLeftPid;
        pendingLeftPid = null;
        currentSide    = 'left';
        fillPairBar();
    } else {
        currentSide = (doneSide === 'left') ? 'right' : 'left';
    }
    updateHighlight(); renderExtraCards();
    startRec();
}

// ── TIMER ───────────────────────────────────
function startTimer() {
    clearInterval(recTimerIv);
    recTimerIv = setInterval(function() {
        recTimerVal++;
        var m = Math.floor(recTimerVal / 60);
        var s = recTimerVal % 60;
        var el = document.getElementById('recTimer');
        if (el) el.textContent = m + ':' + (s < 10 ? '0' : '') + s;
    }, 1000);
}
function showRecCtrl(person) {
    recTimerVal = 0;
    isPaused    = false;
    var bar = document.getElementById('recCtrlBar');
    bar.classList.add('visible');
    document.getElementById('recWho').textContent  = person.emoji + ' ' + person.name + ' — ' + person.role;
    document.getElementById('recState').textContent = 'Merekam…';
    document.getElementById('recTimer').textContent = '0:00';
    document.getElementById('recTimer').classList.remove('paused');
    document.getElementById('recDot').classList.remove('paused');
    document.getElementById('btnPause').className  = 'ctrl-btn ctrl-btn-pause';
    document.getElementById('btnPause').textContent = '⏸ Jeda';
    startTimer();
}
function hideRecCtrl() {
    clearInterval(recTimerIv);
    document.getElementById('recCtrlBar').classList.remove('visible');
}

function startRec() {
    var person = currentSide === 'left' ? leftPerson() : responden;
    navigator.mediaDevices.getUserMedia({ audio: true })
        .then(function(stream) {
            recStream = stream; recChunks = []; isRecording = true; isPaused = false;
            var mime = MediaRecorder.isTypeSupported('audio/webm;codecs=opus') ? 'audio/webm;codecs=opus' : 'audio/webm';
            mediaRec = new MediaRecorder(stream, { mimeType: mime });
            mediaRec.ondataavailable = function(e) { if (e.data.size > 0) recChunks.push(e.data); };
            var snapSide     = currentSide;
            var snapPerson   = JSON.parse(JSON.stringify(person));
            var snapAutoNext = autoNext;
            mediaRec.onstop = function() {
                finalize(snapPerson, mime);
                scheduleNext(snapSide, snapAutoNext);
            };
            mediaRec.start();
            showRecCtrl(person);
            updateHighlight(); renderExtraCards();
            setStatus('🔴 Merekam ' + person.emoji + ' ' + person.name + ' — SPASI untuk akhiri & lanjut ke berikutnya');
        })
        .catch(function(err) {
            isRecording = false;
            setStatus('❌ Mikrofon: ' + err.message);
        });
}

// ═══════════════════════════════════════════
//  UPLOAD & POLL
// ═══════════════════════════════════════════
function finalize(person, mime) {
    var blob    = new Blob(recChunks, { type: mime });
    var blobUrl = URL.createObjectURL(blob);
    var now     = new Date().toLocaleTimeString('id-ID', { hour:'2-digit', minute:'2-digit', second:'2-digit' });
    var eid     = 'eid' + Date.now();
    var rec     = { id:eid, person:person, text:'⏳ Memproses...', time:now, blobUrl:blobUrl, done:false };
    transcript.push(rec); renderEntry(rec, true); updateCount();

    var fd = new FormData();
    fd.append('file', blob, 'sidang-'+Date.now()+'.webm');
    fd.append('engine',        document.getElementById('cfgEngine').value);
    fd.append('model_type',    document.getElementById('cfgModel').value);
    fd.append('is_court_mode', 'true');

    fetch('/api/record/upload', { method:'POST', body:fd })
        .then(function(r) { return r.json(); })
        .then(function(d) { if (!d.success) throw new Error(d.detail); pollEntry(d.task_id, eid, person); })
        .catch(function(err) { patchBubble(eid, '[ Error: '+err.message+' ]', true); });
}
function pollEntry(taskId, eid, person) {
    var iv = setInterval(function() {
        fetch('/api/status/'+taskId)
            .then(function(r){return r.json();})
            .then(function(d) {
                if (d.status==='completed') {
                    clearInterval(iv);
                    patchBubble(eid, person.tag+' ('+person.name+'):\n'+(d.result||''), true);
                    updateCount();
                } else if (d.status==='failed') {
                    clearInterval(iv);
                    patchBubble(eid, '[ Gagal: '+d.error_message+' ]', true);
                }
            })
            .catch(function(){clearInterval(iv);});
    }, 2000);
}

// ═══════════════════════════════════════════
//  TRANSCRIPT RENDER
// ═══════════════════════════════════════════
function renderEntry(rec, processing) {
    var area = document.getElementById('transcriptArea');
    var empty = document.getElementById('emptyState'); if (empty) empty.remove();
    var p = rec.person;
    var div = document.createElement('div'); div.className='entry'; div.id=rec.id;
    div.innerHTML =
        '<div class="e-av" style="background:'+p.bg+';color:'+p.fg+';">'+p.emoji+'</div>' +
        '<div class="e-body">' +
            '<div class="e-meta">' +
                '<span class="e-name">'+esc(p.name)+'</span>' +
                '<span class="e-role">'+esc(p.role)+'</span>' +
                '<span class="e-time">'+rec.time+'</span>' +
            '</div>' +
            '<div class="e-bub'+(processing?' processing':'')+'" id="bub-'+rec.id+'" style="background:'+p.bg+'28;border-left:3px solid '+p.fg+'50;">'+esc(rec.text)+'</div>' +
        '</div>';
    area.appendChild(div); area.scrollTop = area.scrollHeight;
}
function patchBubble(eid, text, done) {
    var rec = transcript.find(function(t){return t.id===eid;});
    if (rec) { rec.text=text; rec.done=done; }
    var b = document.getElementById('bub-'+eid); if (!b) return;
    b.className = 'e-bub'+(done?'':' processing');
    if (rec) { b.style.background=rec.person.bg+'28'; b.style.borderLeft='3px solid '+rec.person.fg+'50'; }
    b.innerHTML = esc(text);
    if (done && rec && rec.blobUrl) {
        var btn=document.createElement('button');
        btn.className='e-play'; btn.id='epl-'+eid; btn.textContent='▶';
        btn.onclick=function(){playInline(eid);}; b.appendChild(btn);
    }
}

// ═══════════════════════════════════════════
//  INLINE PLAYBACK
// ═══════════════════════════════════════════
function playInline(eid) {
    var rec = transcript.find(function(t){return t.id===eid;});
    if (!rec||!rec.blobUrl) return;
    if (inlAudio) {
        inlAudio.pause();
        var pb=document.getElementById('epl-'+inlId); if(pb){pb.textContent='▶';pb.classList.remove('playing');}
        inlAudio=null; if(inlId===eid){inlId=null;return;}
    }
    inlId=eid; inlAudio=new Audio(rec.blobUrl); inlAudio.play();
    var btn=document.getElementById('epl-'+eid); if(btn){btn.textContent='⏹';btn.classList.add('playing');}
    inlAudio.onended=function(){var b=document.getElementById('epl-'+eid);if(b){b.textContent='▶';b.classList.remove('playing');}inlAudio=null;inlId=null;};
}

// ═══════════════════════════════════════════
//  ADD EXTRA MODAL
// ═══════════════════════════════════════════
function openAddModal() {
    modalRole = null;
    var chips = document.getElementById('modalChips'); chips.innerHTML='';
    ROLES[caseType].extra.forEach(function(r) {
        var chip=document.createElement('button');
        chip.className='modal-chip'; chip.style.color=r.fg; chip.style.borderColor=r.bg;
        chip.innerHTML=r.emoji+' '+r.label;
        chip.onclick=function() {
            document.querySelectorAll('.modal-chip').forEach(function(c){c.classList.remove('msel');});
            chip.classList.add('msel'); modalRole=r;
            document.getElementById('modalHint').textContent='📌 '+r.label;
            document.getElementById('modalForm').style.display='block';
            document.getElementById('modalName').focus();
        };
        chips.appendChild(chip);
    });
    document.getElementById('modalForm').style.display='none';
    document.getElementById('modalName').value='';
    document.getElementById('addModal').classList.add('open');
}
function confirmAdd() {
    if (!modalRole) return;
    var name=document.getElementById('modalName').value.trim()||modalRole.label;
    var ep={pid:nextPid++,role:modalRole,name:name};
    extraParticipants.push(ep); closeAddModal(); buildExtraBar();
    setStatus('Peserta ditambahkan: '+ep.role.emoji+' '+name+' — klik kartu mereka untuk jadikan sisi kiri toggle.');
}
function closeAddModal() { document.getElementById('addModal').classList.remove('open'); }

// ═══════════════════════════════════════════
//  PLAYBACK MODAL
// ═══════════════════════════════════════════
function openPlayback() {
    var done=transcript.filter(function(t){return t.done&&t.blobUrl;});
    if (!done.length){alert('Belum ada rekaman yang selesai.');return;}
    var list=document.getElementById('pmList');list.innerHTML='';
    done.forEach(function(rec,i){
        var p=rec.person;
        var item=document.createElement('div');item.className='pm-item';item.id='pmi-'+i;item.style.borderLeftColor=p.fg;
        item.innerHTML=
            '<div class="pm-hd2">'+
                '<div class="pm-av" style="background:'+p.bg+';color:'+p.fg+';">'+p.emoji+'</div>'+
                '<span class="pm-nm">'+esc(p.name)+' <small style="color:var(--muted);font-weight:400;">— '+esc(p.role)+'</small></span>'+
                '<span class="pm-ts">'+rec.time+'</span>'+
            '</div>'+
            '<div class="pm-tx">'+esc(rec.text.substring(0,100))+(rec.text.length>100?'…':'')+'</div>'+
            '<audio class="pm-audio" controls src="'+rec.blobUrl+'"></audio>';
        list.appendChild(item);
    });
    pmIdx=-1;pmPlaying=false;pmUpdCtrl();
    document.getElementById('playbackModal').classList.add('open');
}
function closePlayback(){pmStop();document.getElementById('playbackModal').classList.remove('open');}
function pmToggle(){if(pmPlaying)pmPause();else pmGo(pmIdx<0?0:pmIdx);}
function pmGo(idx){
    var done=transcript.filter(function(t){return t.done&&t.blobUrl;});
    if(idx<0||idx>=done.length){pmStop();return;}
    if(pmAudioEl){pmAudioEl.pause();pmAudioEl.onended=null;}
    pmIdx=idx;pmPlaying=true;
    pmAudioEl=new Audio(done[idx].blobUrl);pmAudioEl.play();
    pmAudioEl.onended=function(){pmGo(pmIdx+1);};
    document.querySelectorAll('.pm-item').forEach(function(el,i){el.classList.toggle('now',i===idx);});
    document.getElementById('pmStat').textContent='Memutar '+(idx+1)+'/'+done.length+' — '+done[idx].person.name;
    pmUpdCtrl();
}
function pmPause(){if(pmAudioEl)pmAudioEl.pause();pmPlaying=false;pmUpdCtrl();}
function pmStop(){
    if(pmAudioEl){pmAudioEl.pause();pmAudioEl.onended=null;pmAudioEl=null;}
    pmPlaying=false;pmIdx=-1;
    document.querySelectorAll('.pm-item').forEach(function(el){el.classList.remove('now');});
    document.getElementById('pmStat').textContent='–';pmUpdCtrl();
}
function pmUpdCtrl(){
    var done=transcript.filter(function(t){return t.done&&t.blobUrl;});
    var pp=document.getElementById('pmPlay');if(pp)pp.textContent=pmPlaying?'⏸ Jeda':'▶ Putar';
    var pv=document.getElementById('pmPrev');if(pv)pv.disabled=pmIdx<=0;
    var nx=document.getElementById('pmNext');if(nx)nx.disabled=pmIdx>=done.length-1;
}

// ═══════════════════════════════════════════
//  EXPORT
// ═══════════════════════════════════════════
function exportDoc(){
    if (!transcript.length){alert('Belum ada transkripsi.');return;}
    var perkara=document.getElementById('inPerkara').value||'-';
    var hakim=document.getElementById('inHakim').value||'-';
    var lokasi=document.getElementById('inLokasi').value||'-';
    var tgl=new Date().toLocaleDateString('id-ID',{weekday:'long',year:'numeric',month:'long',day:'numeric'});
    var tStr=caseType==='perdata'?'PERDATA':'PIDANA / JINAYAT';
    var lines=[
        '═════════════════════════════════════════════════════════',
        '         BERITA ACARA TRANSKRIPSI PERSIDANGAN',
        '═════════════════════════════════════════════════════════',
        'No. Perkara   : '+perkara,'Jenis Perkara : '+tStr,
        'Hakim Ketua   : '+hakim,'Pengadilan    : '+lokasi,
        'Tanggal       : '+tgl,'Waktu         : '+new Date().toLocaleTimeString('id-ID'),
        '','PESERTA SIDANG:',
    ];
    if (penanya)   lines.push('  [Kiri/Default] '+penanya.tag+' — '+penanya.name);
    if (responden) lines.push('  [Kanan]        '+responden.tag+' — '+responden.name);
    extraParticipants.forEach(function(ep){lines.push('  [Tambahan]     '+ep.role.tag+' — '+ep.name);});
    lines.push('','─────────────────────────────────────────────────────────','');
    transcript.forEach(function(t){lines.push('['+t.time+'] '+t.person.tag+' — '+t.person.name);lines.push(t.text);lines.push('');});
    lines.push('─────────────────────────────────────────────────────────');
    lines.push('Total giliran : '+transcript.length,'Sistem        : Transkripsi AI (Whisper)');
    var blob=new Blob([lines.join('\n')],{type:'text/plain;charset=utf-8'});
    var a=document.createElement('a');a.href=URL.createObjectURL(blob);
    a.download='transkripsi-sidang-'+Date.now()+'.txt';a.click();
}

// ═══════════════════════════════════════════
//  RESET
// ═══════════════════════════════════════════
function resetAll(){
    if(isRecording){alert('Hentikan rekaman dulu.');return;}
    if(!confirm('Reset semua sesi dan transkripsi?'))return;
    transcript.forEach(function(t){if(t.blobUrl)URL.revokeObjectURL(t.blobUrl);});
    transcript=[];extraParticipants=[];nextPid=1;
    sessionOn=false;caseType=null;pickP=null;pickR=null;
    penanya=null;responden=null;activeLeftPid=null;pendingLeftPid=null;currentSide='left';
    isPaused=false; autoNext=true; hideRecCtrl();
    document.querySelectorAll('.type-card').forEach(function(c){c.classList.remove('sel');});
    document.getElementById('btnStep1').disabled=true;
    document.getElementById('transcriptArea').innerHTML=
        '<div class="empty-state" id="emptyState"><div class="ei">⚖️</div><p>Tekan <strong>SPASI</strong> → mulai rekam sisi kiri (Penanya).<br>Tekan <strong>SPASI</strong> lagi → berhenti &amp; <strong>otomatis lanjut</strong> ke Responden.<br>Tekan lagi → otomatis balik ke kiri. Dan seterusnya.<br>Klik nama di bar bawah untuk ganti siapa yang di sisi kiri.</p></div>';
    showStep('stepType');updateCount();setStatus('Pilih jenis perkara terlebih dahulu.');
}

// ═══════════════════════════════════════════
//  UTILS
// ═══════════════════════════════════════════
function showStep(id){
    ['stepType','stepSetup','stepSession'].forEach(function(s){
        var el=document.getElementById(s);
        el.style.display=(s===id)?'flex':'none';
        el.style.flexDirection='column';
    });
}
function setStatus(s){document.getElementById('botStatus').textContent=s;}
function updateCount(){document.getElementById('botCount').textContent=transcript.length+' giliran';}
function esc(s){return String(s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');}

['playbackModal','addModal'].forEach(function(id){
    document.getElementById(id).addEventListener('click',function(e){
        if(e.target===this){if(id==='playbackModal')closePlayback();else closeAddModal();}
    });
});
showStep('stepType');
</script>
</body>
</html>