@extends('layouts.app')

@section('content')
<div id="finishingDesktopPage" class="transition-all duration-300">
    <x-common.page-breadcrumb pageTitle="{{ $title ?? 'Finishing' }}" />

    @php
        $hour = now()->format('H');
        $greeting =
            ($hour >= 5 && $hour < 11) ? 'Selamat pagi' :
            (($hour >= 11 && $hour < 15) ? 'Selamat siang' :
            (($hour >= 15 && $hour < 19) ? 'Selamat sore' : 'Selamat malam'));

        $userName = auth()->user()->name ?? 'User';

        $stats = $stats ?? [
            'pending' => ($finishingOrders ?? collect())->count(),
            'in_progress' => 0,
            'completed_today' => ($completedOrders ?? collect())->count(),
            'ready_for_pickup' => 0,
        ];

        $category = $category ?? request('category', 'all');
        $categories = [
            'all' => 'Semua',
            'versant' => 'Versant',
            'indoor' => 'Indoor',
            'outdoor' => 'Outdoor',
        ];
    @endphp

    <div class="mb-4 flex items-center justify-between rounded-2xl border border-gray-200 bg-white px-5 py-4 dark:border-gray-800 dark:bg-white/[0.03]">
        <div>
            <p class="text-sm text-gray-500 dark:text-gray-400">Halo,</p>
            <h2 class="text-xl font-semibold text-gray-900 dark:text-white/90">
                {{ $greeting }}, {{ $userName }} 👋
            </h2>
        </div>

        <div class="hidden sm:flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400">
            <span class="inline-flex items-center gap-2 rounded-full bg-black/5 px-3 py-1 dark:bg-white/10">
                <span class="h-2 w-2 rounded-full bg-success-500 animate-pulse"></span>
                Finishing Mode
            </span>
        </div>
    </div>

    @if(session('success'))
        <div id="flashSuccess" class="mb-4 rounded-lg bg-success-50 p-4 text-sm text-success-700 dark:bg-success-500/15 dark:text-success-500">
            {{ session('success') }}
        </div>
    @endif

    @if(session('error'))
        <div id="flashError" class="mb-4 rounded-lg bg-error-50 p-4 text-sm text-error-700 dark:bg-error-500/15 dark:text-error-500">
            {{ session('error') }}
        </div>
    @endif

    <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">Dashboard Finishing LIVE</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>

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

    <div class="mb-6 grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-4">
        <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 Finishing</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 finishing.</p>
        </div>

        <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 finishing.</p>
        </div>

        <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>

        <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="mb-6 flex flex-col gap-4">
        <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
            <div class="flex w-fit items-center gap-1 rounded-xl bg-gray-100 p-1 dark:bg-gray-800">
                <a href="{{ request()->fullUrlWithQuery(['mode' => 'per_invoice', 'page' => null]) }}"
                    class="rounded-lg px-4 py-2 text-sm font-medium transition-colors {{ ($viewMode ?? 'per_invoice') === 'per_invoice' ? 'bg-white text-gray-800 shadow-sm dark:bg-gray-700 dark:text-white' : 'text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300' }}">
                    Per Invoice
                </a>
                <a href="{{ request()->fullUrlWithQuery(['mode' => 'per_item', 'page' => null]) }}"
                    class="rounded-lg px-4 py-2 text-sm font-medium transition-colors {{ ($viewMode ?? 'per_invoice') === 'per_item' ? 'bg-white text-gray-800 shadow-sm dark:bg-gray-700 dark:text-white' : 'text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300' }}">
                    Per Item
                </a>
            </div>

            <form action="{{ url()->current() }}" method="GET" class="flex flex-wrap items-center gap-2">
                <input type="hidden" name="mode" value="{{ $viewMode ?? 'per_invoice' }}">
                <input type="hidden" name="category" value="{{ $category }}">

                <x-form.input
                    name="search"
                    placeholder="Cari file, customer, catatan..."
                    :value="$search ?? ''"
                    :prefix="'<svg class=\'fill-gray-500 dark:fill-gray-400\' width=\'20\' height=\'20\' viewBox=\'0 0 20 20\' fill=\'none\'><path fill-rule=\'evenodd\' clip-rule=\'evenodd\' d=\'M3.04175 9.37363C3.04175 5.87693 5.87711 3.04199 9.37508 3.04199C12.8731 3.04199 15.7084 5.87693 15.7084 9.37363C15.7084 12.8703 12.8731 15.7053 9.37508 15.7053C5.87711 15.7053 3.04175 12.8703 3.04175 9.37363ZM9.37508 1.54199C5.04902 1.54199 1.54175 5.04817 1.54175 9.37363C1.54175 13.6991 5.04902 17.2053 9.37508 17.2053C11.2674 17.2053 13.003 16.5344 14.357 15.4176L17.177 18.238C17.4699 18.5309 17.9448 18.5309 18.2377 18.238C18.5306 17.9451 18.5306 17.4703 18.2377 17.1774L15.418 14.3573C16.5365 13.0033 17.2084 11.2669 17.2084 9.37363C17.2084 5.04817 13.7011 1.54199 9.37508 1.54199Z\' fill=\'\' /></svg>'"
                    class="!h-10 w-72"
                />

                <x-ui.button type="submit" size="sm">Cari</x-ui.button>

                @if(!empty($search))
                    <a href="{{ request()->fullUrlWithQuery(['search' => null, 'page' => null]) }}"
                       class="inline-flex items-center justify-center rounded-lg bg-white px-4 py-3 text-sm font-medium text-gray-700 ring-1 ring-inset ring-gray-300 hover:bg-gray-50 dark:bg-gray-800 dark:text-gray-400 dark:ring-gray-700 dark:hover:bg-white/[0.03]">
                        Reset
                    </a>
                @endif
            </form>
        </div>

        <div class="flex flex-wrap items-center gap-2">
            @foreach($categories as $key => $label)
                <a href="{{ request()->fullUrlWithQuery(['category' => $key, 'page' => null]) }}"
                   class="rounded-full px-4 py-2 text-sm font-medium ring-1 ring-inset transition
                   {{ $category === $key
                        ? 'bg-brand-500 text-white ring-brand-500'
                        : 'bg-white text-gray-700 ring-gray-300 hover:bg-gray-50 dark:bg-gray-800 dark:text-gray-300 dark:ring-gray-700 dark:hover:bg-white/[0.03]' }}">
                    {{ $label }}
                </a>
            @endforeach
        </div>
    </div>

    <div class="grid grid-cols-1 gap-6 lg:grid-cols-1">
        <div class="rounded-2xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03]">
            <div class="rounded-t-2xl border-b border-gray-200 bg-purple-50 px-5 py-4 dark:border-gray-800 dark:bg-purple-500/10">
                <div class="flex items-center justify-between">
                    <h3 class="text-lg font-semibold text-purple-700 dark:text-purple-400">Antrian Finishing</h3>
                    <span class="inline-flex items-center justify-center rounded-full bg-purple-500 px-2.5 py-0.5 text-xs font-medium text-white">
                        {{ ($finishingOrders ?? collect())->count() }}
                    </span>
                </div>
                <p class="text-sm text-purple-600 dark:text-purple-400/80">QC + finishing note sebelum selesai.</p>
            </div>

            <div class="max-h-[650px] divide-y divide-gray-200 overflow-y-auto dark:divide-gray-800">
                @forelse(($finishingOrders ?? collect()) as $order)
                    <div class="p-4 hover:bg-gray-50 dark:hover:bg-white/[0.02]">
                        <div class="mb-3 flex items-start justify-between gap-3">
                            <div>
                                <a href="{{ route('produksi.show', $order) }}" class="text-sm font-bold text-brand-600 hover:text-brand-700 dark:text-brand-400 dark:hover:text-brand-300">
                                    {{ $order->invoice_number }}
                                </a>
                                <p class="text-xs text-gray-500">{{ $order->customer_name }}</p>
                            </div>
                            <div class="text-right text-xs text-gray-500 dark:text-gray-400">
                                Operator: <span class="font-medium text-gray-700 dark:text-gray-300">{{ optional($order->operator)->name ?? '-' }}</span>
                            </div>
                        </div>

                        <div class="mb-3 space-y-1">
                            @foreach($order->activeItems->take(2) as $item)
                                <div class="text-xs">
                                    <span class="font-medium text-gray-700 dark:text-gray-300">{{ $item->product_name }}</span>
                                    <span class="text-gray-500">- {{ $item->file_name }} ({{ $item->qty }}pcs)</span>
                                    @if(($item->sisi ?? 1) == 2)
                                        <span class="inline-flex items-center rounded bg-warning-100 px-1 py-0.5 text-[10px] font-bold text-warning-700 dark:bg-warning-500/20 dark:text-warning-400">2 SISI</span>
                                    @endif
                                    @if($item->finishing_note)
                                        <span class="text-brand-600 dark:text-brand-400">• {{ $item->finishing_note }}</span>
                                    @endif
                                </div>
                            @endforeach
                            @if($order->activeItems->count() > 2)
                                <div class="text-xs text-gray-500">+{{ $order->activeItems->count() - 2 }} item lainnya</div>
                            @endif
                        </div>

                        <div class="space-y-2">
                            <button type="button"
                                @click="$dispatch('open-confirm-modal', {
                                    title: 'Konfirmasi Selesai',
                                    description: 'Yakin order {{ $order->invoice_number }} sudah selesai?',
                                    action: '{{ route('produksi.complete', $order) }}',
                                    confirmText: 'Ya, Selesaikan',
                                    color: 'success'
                                })"
                                class="flex w-full items-center justify-center gap-2 rounded-lg bg-success-500 px-3 py-2 text-sm 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>

                            <button type="button"
                                @click="$dispatch('open-confirm-modal', {
                                    title: 'Kembali ke Proses Cetak',
                                    description: 'Yakin ingin mengembalikan order {{ $order->invoice_number }} ke proses cetak?',
                                    action: '{{ route('produksi.revert-cetak', $order) }}',
                                    confirmText: 'Ya, Kembalikan',
                                    color: 'warning'
                                })"
                                class="flex w-full items-center justify-center gap-2 rounded-lg border border-blue-light-300 bg-blue-light-50 px-3 py-1.5 text-xs font-medium text-blue-light-700 hover:bg-blue-light-100 dark:border-blue-light-600 dark:bg-blue-light-500/10 dark:text-blue-light-400 dark:hover:bg-blue-light-500/20">
                                <svg class="h-3 w-3 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 17l-5-5m0 0l5-5m-5 5h12" />
                                </svg>
                                Kembali ke Proses Cetak
                            </button>
                        </div>
                    </div>
                @empty
                    <div class="p-10 text-center text-sm text-gray-500 dark:text-gray-400">
                        Tidak ada antrian finishing.
                    </div>
                @endforelse
            </div>
        </div>
    </div>

    <div class="mt-6 rounded-2xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03]">
        <div class="rounded-t-2xl border-b border-gray-200 bg-gradient-to-r from-success-500/10 via-emerald-500/10 to-cyan-500/10 px-5 py-4 dark:border-gray-800">
            <div class="flex items-center justify-between">
                <div>
                    <h3 class="text-lg font-semibold text-gray-900 dark:text-white/90">Laporan Selesai Hari Ini</h3>
                    <p class="text-sm text-gray-600 dark:text-gray-400">Invoice, item, pelanggan, operator, operator finishing.</p>
                </div>
                <a href="{{ route('produksi.history') }}" class="text-sm text-success-700 hover:text-success-800 dark:text-success-400">
                    Lihat Semua
                </a>
            </div>
        </div>

        <div class="overflow-x-auto">
            <table class="w-full text-sm">
                <thead class="bg-gray-50 dark:bg-gray-800/40">
                    <tr class="border-b border-gray-200 dark:border-gray-800">
                        <th class="px-5 py-3 text-left font-medium text-gray-500 dark:text-gray-400">Invoice</th>
                        <th class="px-5 py-3 text-left font-medium text-gray-500 dark:text-gray-400">Item</th>
                        <th class="px-5 py-3 text-left font-medium text-gray-500 dark:text-gray-400">Pelanggan</th>
                        <th class="px-5 py-3 text-left font-medium text-gray-500 dark:text-gray-400">Operator</th>
                        <th class="px-5 py-3 text-left font-medium text-gray-500 dark:text-gray-400">Operator Finishing</th>
                        <th class="px-5 py-3 text-left font-medium text-gray-500 dark:text-gray-400">Selesai</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-200 dark:divide-gray-800">
                    @forelse(($completedOrders ?? collect()) as $order)
                        @php
                            $finisherId =
                                $order->finishing_operator_id
                                ?? $order->finisher_id
                                ?? $order->finishing_user_id
                                ?? $order->finisher_user_id
                                ?? null;

                            $finisherName = '-';
                            if (!empty($finisherId) && !empty($finisherMap) && isset($finisherMap[$finisherId])) {
                                $finisherName = $finisherMap[$finisherId];
                            }
                        @endphp
                        <tr class="hover:bg-gray-50 dark:hover:bg-white/[0.02]">
                            <td class="px-5 py-3">
                                <a href="{{ route('produksi.show', $order) }}" class="font-medium text-brand-600 hover:text-brand-700 dark:text-brand-400">
                                    {{ $order->invoice_number }}
                                </a>
                            </td>
                            <td class="px-5 py-3 text-gray-800 dark:text-white/90">
                                <div class="font-medium">{{ $order->activeItems->count() }} item</div>
                                <div class="text-xs text-gray-500 dark:text-gray-400">
                                    {{ $order->activeItems->pluck('product_name')->unique()->implode(', ') }}
                                </div>
                            </td>
                            <td class="px-5 py-3 text-gray-600 dark:text-gray-300">{{ $order->customer_name }}</td>
                            <td class="px-5 py-3 text-gray-600 dark:text-gray-300">{{ optional($order->operator)->name ?? '-' }}</td>
                            <td class="px-5 py-3 text-gray-600 dark:text-gray-300">{{ $finisherName }}</td>
                            <td class="px-5 py-3 text-gray-500 dark:text-gray-400">{{ $order->finished_at?->format('H:i') ?? '-' }}</td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="6" class="px-5 py-10 text-center text-sm text-gray-500 dark:text-gray-400">
                                Belum ada order selesai hari ini.
                            </td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
    </div>

    <div class="mt-12 border-t border-gray-200 pt-6 text-center text-xs text-gray-500 dark:border-gray-800 dark:text-gray-400">
        <p>
            © 2026 <span class="font-semibold text-gray-700 dark:text-gray-300">aplikasipercetakan.com</span>.
            All rights reserved.
        </p>
    </div>

    <x-ui.confirm />
</div>
@endsection

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function () {
    const hasFlash = {{ session()->has('success') || session()->has('error') ? 'true' : 'false' }};
    const shouldForceTop = sessionStorage.getItem('finishing_force_scroll_top') === '1';

    if (hasFlash || shouldForceTop) {
        sessionStorage.removeItem('finishing_force_scroll_top');

        if ('scrollRestoration' in history) {
            history.scrollRestoration = 'manual';
        }

        setTimeout(() => {
            window.scrollTo({
                top: 0,
                behavior: 'smooth'
            });
        }, 120);
    }
});

(function () {
    const LIVE_URL = @json(url('/operator/dashboard/live'));
    const POLL_ACTIVE_MS = 3000;
    const POLL_HIDDEN_MS = 12000;

    let pollTimer = null;
    let busy = false;
    let lastSeenPendingId = Number(localStorage.getItem('op_last_seen_pending_id') || 0);

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

    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'),

        toastContainer: document.getElementById('toastContainer'),

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

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

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

    function setLive(ok) {
        if (!el.liveDot || !el.liveText || !el.liveBadge) return;

        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') {
        if (!el.toastContainer) return;

        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);
    }

    function pickBestVoice() {
        const voices = window.speechSynthesis?.getVoices?.() || [];
        if (!voices.length) return;

        const idVoices = voices.filter(v => (v.lang || '').toLowerCase().startsWith('id'));
        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';
        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(); };

        window.speechSynthesis.speak(u);
    }

    function updateVoiceUI() {
        if (!el.toggleVoiceBtn || !el.voiceIcon || !el.voiceLabel) return;

        if (voiceEnabled) {
            el.voiceIcon.textContent = '🔊';
            el.voiceLabel.textContent = 'Suara: ON';
            el.toggleVoiceBtn.className =
                "inline-flex items-center gap-2 rounded-lg border border-success-300 bg-success-50 px-3 py-2 text-xs font-semibold text-success-700 dark:border-success-900/40 dark:bg-success-500/10 dark:text-success-300";
        } 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();

    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);

        if (el.lastUpdatedText) el.lastUpdatedText.textContent = formatTime(payload.server_time);
        if (el.aiInsightText) el.aiInsightText.textContent = aiInsight(payload.stats);

        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);

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

        const newOnes = Array.isArray(payload.new_pending_orders) ? payload.new_pending_orders : [];

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

        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));
        }
    }

    function handleOffline(err) {
        console.log('LIVE error:', err);
        setLive(false);
        if (el.aiInsightText) {
            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());

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

@push('styles')
<style>
    @media (min-width: 1024px) {
        #finishingDesktopPage {
            padding-left: 17rem !important;
        }

        #sidebar,
        .sidebar,
        .app-sidebar,
        [data-sidebar],
        aside#sidebar,
        aside[class*="sidebar"] {
            width: 16rem !important;
            min-width: 16rem !important;
            max-width: 16rem !important;
            transform: translateX(0) !important;
            opacity: 1 !important;
            visibility: visible !important;
            overflow: visible !important;
        }

        #sidebar.collapsed,
        .sidebar.collapsed,
        .app-sidebar.collapsed,
        [data-sidebar].collapsed,
        aside[class*="sidebar"].collapsed {
            width: 16rem !important;
            min-width: 16rem !important;
            max-width: 16rem !important;
            transform: translateX(0) !important;
        }

        .group:hover #sidebar,
        .group:hover .sidebar,
        .group:hover .app-sidebar,
        .group:hover [data-sidebar] {
            width: 16rem !important;
            min-width: 16rem !important;
            max-width: 16rem !important;
        }

        #sidebar *,
        .sidebar *,
        .app-sidebar *,
        [data-sidebar] * {
            opacity: 1 !important;
            visibility: visible !important;
        }
    }

    @media (max-width: 1023.98px) {
        #finishingDesktopPage {
            padding-left: 0 !important;
        }
    }
</style>
@endpush