{{-- Operator Dashboard - LIVE AI --}}
<div class="mb-6 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
    <div>
        <h2 class="text-xl font-bold text-gray-800 dark:text-white"></h2>
        <div class="mt-1 flex flex-wrap items-center gap-2 text-xs text-gray-500 dark:text-gray-400">
            <span id="liveBadge" class="inline-flex items-center gap-1 rounded-full bg-gray-100 px-2 py-0.5 dark:bg-gray-800">
                <span id="liveDot" class="h-2 w-2 rounded-full bg-gray-400"></span>
                <span id="liveText" class="font-semibold">OFFLINE</span>
            </span>
            <span>Update terakhir:</span>
            <span id="lastUpdatedText" class="font-medium text-gray-700 dark:text-gray-300">-</span>
            <span class="hidden sm:inline">•</span>
            <span id="aiInsightText" class="text-gray-600 dark:text-gray-400">AI: memuat data realtime...</span>
        </div>
    </div>

    <div class="flex items-center gap-2">
        <button id="toggleVoiceBtn" type="button"
            class="inline-flex items-center gap-2 rounded-lg border border-gray-300 bg-white px-3 py-2 text-xs font-semibold text-gray-700 hover:bg-gray-50 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-200 dark:hover:bg-gray-700">
            <span id="voiceIcon">🔇</span>
            <span id="voiceLabel">Suara: OFF</span>
        </button>

        <button id="manualRefreshBtn" type="button"
            class="inline-flex items-center gap-2 rounded-lg bg-brand-500 px-3 py-2 text-xs font-semibold text-white hover:bg-brand-600">
            <svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                    d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
            </svg>
            Refresh
        </button>
    </div>
</div>

{{-- Toast Container --}}
<div id="toastContainer" class="fixed right-4 top-4 z-[99999] space-y-2"></div>

{{-- Stats (sinkron realtime) --}}
<div class="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-4 mb-6">
    {{-- Antrian --}}
    <div class="rounded-2xl border border-gray-200 bg-white p-4 dark:border-gray-800 dark:bg-white/[0.03]">
        <div class="flex items-start justify-between">
            <div>
                <p class="text-sm font-medium text-gray-500 dark:text-gray-400">Antrian</p>
                <p id="statPending" class="mt-1 text-3xl font-extrabold text-gray-800 dark:text-white">
                    {{ $stats['pending'] ?? 0 }}
                </p>
            </div>
            <div class="flex h-11 w-11 items-center justify-center rounded-xl bg-warning-50 text-warning-700 dark:bg-warning-500/10 dark:text-warning-400">
                <svg class="size-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                        d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
            </div>
        </div>
        <p id="hintPending" class="mt-2 text-xs text-gray-500 dark:text-gray-400">Sinkron realtime dengan list antrian.</p>
    </div>

    {{-- Dalam Proses --}}
    <div class="rounded-2xl border border-gray-200 bg-white p-4 dark:border-gray-800 dark:bg-white/[0.03]">
        <div class="flex items-start justify-between">
            <div>
                <p class="text-sm font-medium text-gray-500 dark:text-gray-400">Dalam Proses</p>
                <p id="statInProgress" class="mt-1 text-3xl font-extrabold text-gray-800 dark:text-white">
                    {{ $stats['in_progress'] ?? 0 }}
                </p>
            </div>
            <div class="flex h-11 w-11 items-center justify-center rounded-xl bg-blue-light-50 text-blue-light-700 dark:bg-blue-light-500/10 dark:text-blue-light-400">
                <svg class="size-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                        d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                </svg>
            </div>
        </div>
        <p id="hintInProgress" class="mt-2 text-xs text-gray-500 dark:text-gray-400">AI pantau bottleneck proses.</p>
    </div>

    {{-- Selesai Hari Ini --}}
    <div class="rounded-2xl border border-gray-200 bg-white p-4 dark:border-gray-800 dark:bg-white/[0.03]">
        <div class="flex items-start justify-between">
            <div>
                <p class="text-sm font-medium text-gray-500 dark:text-gray-400">Selesai Hari Ini</p>
                <p id="statCompletedToday" class="mt-1 text-3xl font-extrabold text-gray-800 dark:text-white">
                    {{ $stats['completed_today'] ?? 0 }}
                </p>
            </div>
            <div class="flex h-11 w-11 items-center justify-center rounded-xl bg-success-50 text-success-700 dark:bg-success-500/10 dark:text-success-400">
                <svg class="size-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                        d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
            </div>
        </div>
        <p class="mt-2 text-xs text-gray-500 dark:text-gray-400">Update otomatis.</p>
    </div>

    {{-- Siap Diambil --}}
    <div class="rounded-2xl border border-gray-200 bg-white p-4 dark:border-gray-800 dark:bg-white/[0.03]">
        <div class="flex items-start justify-between">
            <div>
                <p class="text-sm font-medium text-gray-500 dark:text-gray-400">Siap Diambil</p>
                <p id="statReadyPickup" class="mt-1 text-3xl font-extrabold text-gray-800 dark:text-white">
                    {{ $stats['ready_for_pickup'] ?? 0 }}
                </p>
            </div>
            <div class="flex h-11 w-11 items-center justify-center rounded-xl bg-brand-50 text-brand-700 dark:bg-brand-500/10 dark:text-brand-400">
                <svg class="size-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                        d="M5 13l4 4L19 7" />
                </svg>
            </div>
        </div>
        <p class="mt-2 text-xs text-gray-500 dark:text-gray-400">Siap serah terima ke customer.</p>
    </div>
</div>

<div class="grid grid-cols-1 gap-6 xl:grid-cols-2">
    {{-- Antrian (Pending) --}}
    <div class="rounded-2xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03]">
        <div class="border-b border-gray-200 px-5 py-4 dark:border-gray-800 bg-warning-50 dark:bg-warning-500/10 rounded-t-2xl">
            <h3 class="text-lg font-semibold text-warning-700 dark:text-warning-400">Antrian</h3>
            <p class="text-sm text-warning-600 dark:text-warning-400/80">Order siap dikerjakan</p>
        </div>

        <div id="pendingOrdersList" class="divide-y divide-gray-200 dark:divide-gray-800 max-h-80 overflow-y-auto">
            @forelse($pending_orders ?? [] as $order)
                <div class="p-4 hover:bg-gray-50 dark:hover:bg-white/[0.02]">
                    <div class="flex items-start justify-between">
                        <div class="flex-1">
                            <p class="text-sm font-semibold text-gray-800 dark:text-white/90">{{ $order->file_name }}</p>
                            <p class="text-xs text-gray-500">{{ $order->invoice_number }} | {{ $order->customer_name }}</p>
                            <p class="text-xs text-gray-500 mt-1">{{ $order->size }} | {{ $order->qty }} pcs</p>
                            @if($order->finishing_note)
                                <p class="text-xs text-brand-500 mt-1">{{ $order->finishing_note }}</p>
                            @endif
                        </div>
                        <form action="{{ route('produksi.start', $order) }}" method="POST">
                            @csrf
                            <button type="submit"
                                class="inline-flex items-center gap-1.5 rounded-lg bg-brand-500 px-3 py-1.5 text-xs font-medium text-white hover:bg-brand-600">
                                <svg class="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                        d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                        d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                                </svg>
                                Mulai
                            </button>
                        </form>
                    </div>
                </div>
            @empty
                <div class="p-8 text-center text-sm text-gray-500 dark:text-gray-400">Tidak ada antrian</div>
            @endforelse
        </div>
    </div>

    {{-- Dalam Proses --}}
    <div class="rounded-2xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03]">
        <div class="border-b border-gray-200 px-5 py-4 dark:border-gray-800 bg-blue-light-50 dark:bg-blue-light-500/10 rounded-t-2xl">
            <h3 class="text-lg font-semibold text-blue-light-700 dark:text-blue-light-400">Dalam Proses</h3>
            <p class="text-sm text-blue-light-600 dark:text-blue-light-400/80">Order sedang dikerjakan</p>
        </div>

        <div id="inProgressOrdersList" class="divide-y divide-gray-200 dark:divide-gray-800 max-h-80 overflow-y-auto">
            @forelse($in_progress_orders ?? [] as $order)
                <div class="p-4 hover:bg-gray-50 dark:hover:bg-white/[0.02]">
                    <div class="flex items-start justify-between">
                        <div class="flex-1">
                            <div class="flex items-center gap-2">
                                <p class="text-sm font-semibold text-gray-800 dark:text-white/90">{{ $order->file_name }}</p>
                                <span class="inline-flex rounded-full px-2 py-0.5 text-xs font-medium {{ $order->getProductionStatusBadgeClass() }}">
                                    {{ $order->getProductionStatusLabel() }}
                                </span>
                            </div>
                            <p class="text-xs text-gray-500">{{ $order->invoice_number }} | {{ $order->customer_name }}</p>
                            <p class="text-xs text-gray-500 mt-1">{{ $order->size }} | {{ $order->qty }} pcs</p>
                            @if($order->finishing_note)
                                <p class="text-xs text-brand-500 mt-1">{{ $order->finishing_note }}</p>
                            @endif
                        </div>

                        <div class="flex flex-col gap-2">
                            @if($order->isProsesCetak())
                                <form action="{{ route('produksi.finishing', $order) }}" method="POST">
                                    @csrf
                                    <button type="submit"
                                        class="inline-flex items-center gap-1.5 rounded-lg bg-blue-light-500 px-3 py-1.5 text-xs font-medium text-white hover:bg-blue-light-600">
                                        Finishing
                                    </button>
                                </form>
                            @elseif($order->isFinishing())
                                <form action="{{ route('produksi.complete', $order) }}" method="POST">
                                    @csrf
                                    <button type="submit"
                                        class="inline-flex items-center gap-1.5 rounded-lg bg-success-500 px-3 py-1.5 text-xs font-medium text-white hover:bg-success-600">
                                        <svg class="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                                d="M5 13l4 4L19 7" />
                                        </svg>
                                        Selesai
                                    </button>
                                </form>
                            @endif
                        </div>
                    </div>
                </div>
            @empty
                <div class="p-8 text-center text-sm text-gray-500 dark:text-gray-400">Tidak ada yang sedang diproses</div>
            @endforelse
        </div>
    </div>
</div>

{{-- Selesai Hari Ini (dibuat selalu ada agar bisa realtime show/hide) --}}
<div id="completedSection"
    class="mt-6 rounded-2xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03]
    {{ (isset($completed_orders) && $completed_orders->count() > 0) ? '' : 'hidden' }}">
    <div class="border-b border-gray-200 px-5 py-4 dark:border-gray-800 bg-success-50 dark:bg-success-500/10 rounded-t-2xl">
        <div class="flex items-center justify-between">
            <div>
                <h3 class="text-lg font-semibold text-success-700 dark:text-success-400">Selesai Hari Ini</h3>
            </div>
            <a href="{{ route('produksi.history') }}" class="text-sm text-success-600 hover:text-success-700">Lihat Semua</a>
        </div>
    </div>

    <div class="overflow-x-auto">
        <table class="w-full">
            <thead>
                <tr class="border-b border-gray-200 dark:border-gray-800">
                    <th class="px-5 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400">File</th>
                    <th class="px-5 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400">Pelanggan</th>
                    <th class="px-5 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400">Selesai</th>
                    <th class="px-5 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400">Status</th>
                    <th class="px-5 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400">Aksi</th>
                </tr>
            </thead>
            <tbody id="completedTbody" class="divide-y divide-gray-200 dark:divide-gray-800">
                @if(isset($completed_orders) && $completed_orders->count() > 0)
                    @foreach($completed_orders as $order)
                        <tr class="hover:bg-gray-50 dark:hover:bg-white/[0.02]">
                            <td class="px-5 py-4">
                                <p class="text-sm font-semibold text-gray-800 dark:text-white/90">{{ $order->file_name }}</p>
                                <p class="text-xs text-gray-500">{{ $order->invoice_number }}</p>
                            </td>
                            <td class="px-5 py-4 text-sm text-gray-800 dark:text-white/90">{{ $order->customer_name }}</td>
                            <td class="px-5 py-4 text-sm text-gray-500 dark:text-gray-400">{{ $order->finished_at->format('H:i') }}</td>
                            <td class="px-5 py-4">
                                <span class="inline-flex rounded-full px-2.5 py-0.5 text-xs font-medium {{ $order->getPickupStatusBadgeClass() }}">
                                    {{ $order->getPickupStatusLabel() }}
                                </span>
                            </td>
                            <td class="px-5 py-4">
                                @if($order->canMarkAsPickedUp())
                                    <form action="{{ route('orders.mark-picked-up', $order) }}" method="POST" class="inline">
                                        @csrf
                                        <button type="submit"
                                            class="inline-flex items-center gap-1.5 rounded-lg bg-success-500 px-3 py-1.5 text-xs font-medium text-white hover:bg-success-600">
                                            <svg class="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                                    d="M5 13l4 4L19 7" />
                                            </svg>
                                            Diambil
                                        </button>
                                    </form>
                                @else
                                    <span class="text-xs text-gray-400">-</span>
                                @endif
                            </td>
                        </tr>
                    @endforeach
                @else
                    <tr>
                        <td colspan="5" class="px-5 py-6 text-center text-sm text-gray-500 dark:text-gray-400">
                            Belum ada order selesai hari ini.
                        </td>
                    </tr>
                @endif
            </tbody>
        </table>
    </div>
</div>

@push('scripts')
<script>
(function () {
    // ====== CONFIG ======
    const LIVE_URL = @json(url('/operator/dashboard/live'));
    const CSRF = @json(csrf_token());

    // Route template (akan di-replace __ID__)
    const ROUTES = {
        start: @json(route('produksi.start', '__ID__')),
        finishing: @json(route('produksi.finishing', '__ID__')),
        complete: @json(route('produksi.complete', '__ID__')),
        markPickedUp: @json(route('orders.mark-picked-up', '__ID__')),
    };

    const POLL_ACTIVE_MS = 3000;   // realtime
    const POLL_HIDDEN_MS = 12000;  // hemat saat tab tidak aktif

    // ====== STATE ======
    let pollTimer = null;
    let busy = false;

    // tracking new order
    let lastSeenPendingId = Number(localStorage.getItem('op_last_seen_pending_id') || 0);

    // voice
    let voiceEnabled = (localStorage.getItem('op_voice_enabled') || '0') === '1';
    let selectedVoice = null;

    // ====== DOM ======
    const el = {
        liveDot: document.getElementById('liveDot'),
        liveText: document.getElementById('liveText'),
        liveBadge: document.getElementById('liveBadge'),
        lastUpdatedText: document.getElementById('lastUpdatedText'),
        aiInsightText: document.getElementById('aiInsightText'),

        statPending: document.getElementById('statPending'),
        statInProgress: document.getElementById('statInProgress'),
        statCompletedToday: document.getElementById('statCompletedToday'),
        statReadyPickup: document.getElementById('statReadyPickup'),

        pendingList: document.getElementById('pendingOrdersList'),
        inProgressList: document.getElementById('inProgressOrdersList'),

        completedSection: document.getElementById('completedSection'),
        completedTbody: document.getElementById('completedTbody'),

        toastContainer: document.getElementById('toastContainer'),

        toggleVoiceBtn: document.getElementById('toggleVoiceBtn'),
        voiceIcon: document.getElementById('voiceIcon'),
        voiceLabel: document.getElementById('voiceLabel'),

        manualRefreshBtn: document.getElementById('manualRefreshBtn'),
    };

    // ====== HELPERS ======
    function urlFor(template, id) {
        return template.replace('__ID__', String(id));
    }

    function escapeHtml(str) {
        return String(str ?? '')
            .replaceAll('&', '&amp;')
            .replaceAll('<', '&lt;')
            .replaceAll('>', '&gt;')
            .replaceAll('"', '&quot;')
            .replaceAll("'", '&#039;');
    }

    function setLive(ok) {
        if (ok) {
            el.liveDot.className = "h-2 w-2 rounded-full bg-success-500 animate-pulse";
            el.liveText.textContent = "LIVE";
            el.liveBadge.className = "inline-flex items-center gap-1 rounded-full bg-success-50 px-2 py-0.5 text-success-700 dark:bg-success-500/10 dark:text-success-400";
        } else {
            el.liveDot.className = "h-2 w-2 rounded-full bg-gray-400";
            el.liveText.textContent = "OFFLINE";
            el.liveBadge.className = "inline-flex items-center gap-1 rounded-full bg-gray-100 px-2 py-0.5 text-gray-600 dark:bg-gray-800 dark:text-gray-300";
        }
    }

    function formatTime(iso) {
        if (!iso) return '-';
        const d = new Date(iso);
        if (Number.isNaN(d.getTime())) return '-';
        return d.toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
    }

    function aiInsight(stats) {
        const p = Number(stats?.pending ?? 0);
        const ip = Number(stats?.in_progress ?? 0);

        if (p === 0 && ip === 0) return "AI: Kondisi aman — tidak ada antrian dan proses.";
        if (p >= 15) return `AI: Antrian sangat tinggi (${p}). Saran: tambah operator / pecah job besar / prioritaskan express.`;
        if (p >= 8) return `AI: Antrian padat (${p}). Saran: jalankan job kecil dulu untuk mempercepat throughput.`;
        if (p >= 4) return `AI: Ritme stabil. Antrian ${p}, proses ${ip}.`;
        return `AI: Lancar. Antrian ${p}, proses ${ip}.`;
    }

    function toast(message, type = 'info') {
        const box = document.createElement('div');
        const color =
            type === 'success' ? 'bg-success-50 text-success-800 dark:bg-success-500/10 dark:text-success-300 border-success-200 dark:border-success-900/40'
            : type === 'warning' ? 'bg-warning-50 text-warning-800 dark:bg-warning-500/10 dark:text-warning-300 border-warning-200 dark:border-warning-900/40'
            : 'bg-white text-gray-800 dark:bg-gray-900 dark:text-gray-100 border-gray-200 dark:border-gray-800';

        box.className = `rounded-xl border px-4 py-3 shadow-lg ${color}`;
        box.innerHTML = `
            <div class="flex items-start gap-3">
                <div class="mt-0.5 h-2 w-2 rounded-full ${type === 'success' ? 'bg-success-500' : (type === 'warning' ? 'bg-warning-500' : 'bg-brand-500')}"></div>
                <div class="text-sm font-medium">${escapeHtml(message)}</div>
            </div>
        `;

        el.toastContainer.appendChild(box);
        setTimeout(() => box.classList.add('opacity-0', 'transition', 'duration-300'), 3200);
        setTimeout(() => box.remove(), 3600);
    }

    // ====== VOICE (Female-ish Indonesian) ======
    function pickBestVoice() {
        const voices = window.speechSynthesis?.getVoices?.() || [];
        if (!voices.length) return;

        // prioritas voice Indonesia
        const idVoices = voices.filter(v => (v.lang || '').toLowerCase().startsWith('id'));
        // coba cari yang "female"
        const femaleHints = ['female', 'perempuan', 'woman', 'cewek', 'wati', 'sari'];
        const findFemale = (arr) => arr.find(v => femaleHints.some(h => (v.name || '').toLowerCase().includes(h)));

        selectedVoice = findFemale(idVoices) || idVoices[0] || findFemale(voices) || voices[0] || null;
    }

    if ('speechSynthesis' in window) {
        pickBestVoice();
        window.speechSynthesis.onvoiceschanged = () => pickBestVoice();
    }

    let ttsQueue = [];
    let ttsSpeaking = false;

    function speak(text) {
        if (!voiceEnabled) return;
        if (!('speechSynthesis' in window)) return;

        ttsQueue.push(text);
        pumpTTS();
    }

    function pumpTTS() {
        if (ttsSpeaking) return;
        if (!ttsQueue.length) return;

        const msg = ttsQueue.shift();
        const u = new SpeechSynthesisUtterance(msg);
        u.lang = 'id-ID';

        // “Perempuan natural” (tergantung voice device). Pitch sedikit dinaikkan.
        u.rate = 1.0;
        u.pitch = 1.15;
        u.volume = 1.0;

        if (selectedVoice) u.voice = selectedVoice;

        ttsSpeaking = true;
        u.onend = () => { ttsSpeaking = false; pumpTTS(); };
        u.onerror = () => { ttsSpeaking = false; pumpTTS(); };

        // jangan cancel total (biar antrian suara jalan rapi)
        window.speechSynthesis.speak(u);
    }

    function updateVoiceUI() {
        if (voiceEnabled) {
            el.voiceIcon.textContent = '🔊';
            el.voiceLabel.textContent = 'Suara: ON';
            el.toggleVoiceBtn.classList.remove('border-gray-300', 'bg-white', 'text-gray-700');
            el.toggleVoiceBtn.classList.add('border-success-300', 'bg-success-50', 'text-success-700', 'dark:bg-success-500/10', 'dark:text-success-300', 'dark:border-success-900/40');
        } else {
            el.voiceIcon.textContent = '🔇';
            el.voiceLabel.textContent = 'Suara: OFF';
            el.toggleVoiceBtn.className =
                "inline-flex items-center gap-2 rounded-lg border border-gray-300 bg-white px-3 py-2 text-xs font-semibold text-gray-700 hover:bg-gray-50 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-200 dark:hover:bg-gray-700";
        }
    }

    el.toggleVoiceBtn.addEventListener('click', () => {
        voiceEnabled = !voiceEnabled;
        localStorage.setItem('op_voice_enabled', voiceEnabled ? '1' : '0');
        updateVoiceUI();

        if (voiceEnabled) {
            toast('Notifikasi suara aktif.', 'success');
            speak('Notifikasi suara aktif.');
        } else {
            toast('Notifikasi suara dimatikan.', 'warning');
        }
    });

    updateVoiceUI();

    // ====== RENDERERS ======
    function renderPending(orders, newIdsSet) {
        if (!orders.length) {
            return `<div class="p-8 text-center text-sm text-gray-500 dark:text-gray-400">Tidak ada antrian</div>`;
        }

        return orders.map(o => {
            const isNew = newIdsSet.has(Number(o.id));
            const wrapClass = isNew
                ? "bg-brand-50/70 dark:bg-brand-500/10 ring-2 ring-brand-500"
                : "";

            return `
                <div class="p-4 hover:bg-gray-50 dark:hover:bg-white/[0.02] ${wrapClass}">
                    <div class="flex items-start justify-between">
                        <div class="flex-1">
                            <p class="text-sm font-semibold text-gray-800 dark:text-white/90">${escapeHtml(o.file_name)}</p>
                            <p class="text-xs text-gray-500">${escapeHtml(o.invoice_number)} | ${escapeHtml(o.customer_name)}</p>
                            <p class="text-xs text-gray-500 mt-1">${escapeHtml(o.size)} | ${escapeHtml(o.qty)} pcs</p>
                            ${o.finishing_note ? `<p class="text-xs text-brand-500 mt-1">${escapeHtml(o.finishing_note)}</p>` : ''}
                        </div>

                        <form action="${urlFor(ROUTES.start, o.id)}" method="POST">
                            <input type="hidden" name="_token" value="${CSRF}">
                            <button type="submit"
                                class="inline-flex items-center gap-1.5 rounded-lg bg-brand-500 px-3 py-1.5 text-xs font-medium text-white hover:bg-brand-600">
                                <svg class="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                        d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                        d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                                </svg>
                                Mulai
                            </button>
                        </form>
                    </div>
                </div>
            `;
        }).join('');
    }

    function renderInProgress(orders) {
        if (!orders.length) {
            return `<div class="p-8 text-center text-sm text-gray-500 dark:text-gray-400">Tidak ada yang sedang diproses</div>`;
        }

        return orders.map(o => {
            let actionHtml = '';
            if (o.is_proses_cetak) {
                actionHtml = `
                    <form action="${urlFor(ROUTES.finishing, o.id)}" method="POST">
                        <input type="hidden" name="_token" value="${CSRF}">
                        <button type="submit"
                            class="inline-flex items-center gap-1.5 rounded-lg bg-blue-light-500 px-3 py-1.5 text-xs font-medium text-white hover:bg-blue-light-600">
                            Finishing
                        </button>
                    </form>
                `;
            } else if (o.is_finishing) {
                actionHtml = `
                    <form action="${urlFor(ROUTES.complete, o.id)}" method="POST">
                        <input type="hidden" name="_token" value="${CSRF}">
                        <button type="submit"
                            class="inline-flex items-center gap-1.5 rounded-lg bg-success-500 px-3 py-1.5 text-xs font-medium text-white hover:bg-success-600">
                            <svg class="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                    d="M5 13l4 4L19 7" />
                            </svg>
                            Selesai
                        </button>
                    </form>
                `;
            }

            return `
                <div class="p-4 hover:bg-gray-50 dark:hover:bg-white/[0.02]">
                    <div class="flex items-start justify-between">
                        <div class="flex-1">
                            <div class="flex items-center gap-2">
                                <p class="text-sm font-semibold text-gray-800 dark:text-white/90">${escapeHtml(o.file_name)}</p>
                                <span class="inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${escapeHtml(o.production_status_badge_class)}">
                                    ${escapeHtml(o.production_status_label)}
                                </span>
                            </div>
                            <p class="text-xs text-gray-500">${escapeHtml(o.invoice_number)} | ${escapeHtml(o.customer_name)}</p>
                            <p class="text-xs text-gray-500 mt-1">${escapeHtml(o.size)} | ${escapeHtml(o.qty)} pcs</p>
                            ${o.finishing_note ? `<p class="text-xs text-brand-500 mt-1">${escapeHtml(o.finishing_note)}</p>` : ''}
                        </div>

                        <div class="flex flex-col gap-2">
                            ${actionHtml}
                        </div>
                    </div>
                </div>
            `;
        }).join('');
    }

    function renderCompleted(orders) {
        if (!orders.length) {
            return `
                <tr>
                    <td colspan="5" class="px-5 py-6 text-center text-sm text-gray-500 dark:text-gray-400">
                        Belum ada order selesai hari ini.
                    </td>
                </tr>
            `;
        }

        return orders.map(o => {
            const time = o.finished_time ? escapeHtml(o.finished_time) : '-';

            const action = o.can_mark_picked_up
                ? `
                    <form action="${urlFor(ROUTES.markPickedUp, o.id)}" method="POST" class="inline">
                        <input type="hidden" name="_token" value="${CSRF}">
                        <button type="submit"
                            class="inline-flex items-center gap-1.5 rounded-lg bg-success-500 px-3 py-1.5 text-xs font-medium text-white hover:bg-success-600">
                            <svg class="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                    d="M5 13l4 4L19 7" />
                            </svg>
                            Diambil
                        </button>
                    </form>
                  `
                : `<span class="text-xs text-gray-400">-</span>`;

            return `
                <tr class="hover:bg-gray-50 dark:hover:bg-white/[0.02]">
                    <td class="px-5 py-4">
                        <p class="text-sm font-semibold text-gray-800 dark:text-white/90">${escapeHtml(o.file_name)}</p>
                        <p class="text-xs text-gray-500">${escapeHtml(o.invoice_number)}</p>
                    </td>
                    <td class="px-5 py-4 text-sm text-gray-800 dark:text-white/90">${escapeHtml(o.customer_name)}</td>
                    <td class="px-5 py-4 text-sm text-gray-500 dark:text-gray-400">${time}</td>
                    <td class="px-5 py-4">
                        <span class="inline-flex rounded-full px-2.5 py-0.5 text-xs font-medium ${escapeHtml(o.pickup_status_badge_class)}">
                            ${escapeHtml(o.pickup_status_label)}
                        </span>
                    </td>
                    <td class="px-5 py-4">
                        ${action}
                    </td>
                </tr>
            `;
        }).join('');
    }

    // ====== LIVE FETCH ======
    async function fetchLive() {
        const url = new URL(LIVE_URL, window.location.origin);
        url.searchParams.set('since_id', String(lastSeenPendingId));

        const res = await fetch(url.toString(), {
            headers: { 'Accept': 'application/json' }
        });

        if (!res.ok) throw new Error('HTTP ' + res.status);
        return await res.json();
    }

    function applyLive(payload) {
        setLive(true);

        // waktu update
        el.lastUpdatedText.textContent = formatTime(payload.server_time);

        // AI insight
        el.aiInsightText.textContent = aiInsight(payload.stats);

        // ====== SINKRON COUNT ======
        const pendingCount = Array.isArray(payload.pending_orders) ? payload.pending_orders.length : Number(payload.stats?.pending || 0);
        const inProgressCount = Array.isArray(payload.in_progress_orders) ? payload.in_progress_orders.length : Number(payload.stats?.in_progress || 0);
        const completedCount = Array.isArray(payload.completed_orders) ? payload.completed_orders.length : Number(payload.stats?.completed_today || 0);

        el.statPending.textContent = pendingCount;
        el.statInProgress.textContent = inProgressCount;
        el.statCompletedToday.textContent = completedCount;
        el.statReadyPickup.textContent = Number(payload.stats?.ready_for_pickup || 0);

        // ====== NEW ORDER DETECTION (ALARM) ======
        const newOnes = Array.isArray(payload.new_pending_orders) ? payload.new_pending_orders : [];
        const newIdsSet = new Set(newOnes.map(x => Number(x.id)));

        if (newOnes.length > 0) {
            // highlight + toast + voice
            newOnes.slice(0, 5).forEach(o => {
                const cname = (o.customer_name || '').trim() || 'tanpa nama';
                toast(`Orderan baru masuk dari ${cname}`, 'success');

                // Ini sesuai request: "perempuan natural" + kalimat ini
                speak(`Orderan masuk dari costumer ${cname}`);
            });
        }

        // Update lastSeen (agar tidak bunyi ulang)
        if (typeof payload.latest_pending_id === 'number' && payload.latest_pending_id > lastSeenPendingId) {
            lastSeenPendingId = payload.latest_pending_id;
            localStorage.setItem('op_last_seen_pending_id', String(lastSeenPendingId));
        }

        // ====== RENDER LISTS (preserve scroll) ======
        const pendingScroll = el.pendingList.scrollTop;
        const inProgressScroll = el.inProgressList.scrollTop;

        el.pendingList.innerHTML = renderPending(payload.pending_orders || [], newIdsSet);
        el.inProgressList.innerHTML = renderInProgress(payload.in_progress_orders || []);

        el.pendingList.scrollTop = pendingScroll;
        el.inProgressList.scrollTop = inProgressScroll;

        // Completed show/hide
        const completedOrders = payload.completed_orders || [];
        if (completedOrders.length > 0) {
            el.completedSection.classList.remove('hidden');
        } else {
            el.completedSection.classList.add('hidden');
        }
        el.completedTbody.innerHTML = renderCompleted(completedOrders);
    }

    function handleOffline(err) {
        console.log('LIVE error:', err);
        setLive(false);
        el.aiInsightText.textContent = "AI: koneksi terputus — mencoba lagi otomatis...";
    }

    function getInterval() {
        return document.hidden ? POLL_HIDDEN_MS : POLL_ACTIVE_MS;
    }

    async function tick() {
        if (busy) return;
        busy = true;

        try {
            const payload = await fetchLive();
            applyLive(payload);
        } catch (err) {
            handleOffline(err);
        } finally {
            busy = false;
        }
    }

    function startPolling() {
        if (pollTimer) clearInterval(pollTimer);
        pollTimer = setInterval(tick, getInterval());
    }

    document.addEventListener('visibilitychange', () => startPolling());
    el.manualRefreshBtn.addEventListener('click', () => tick());

    // start
    startPolling();
    tick();
})();
</script>
@endpush