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

{{-- Status Cards Only --}}
<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>

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

    const POLL_ACTIVE_MS = 3000;
    const POLL_HIDDEN_MS = 12000;

    // ====== STATE ======
    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;

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

        toastContainer: document.getElementById('toastContainer'),

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

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

    // ====== HELPERS ======
    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 ======
    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 (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();

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

        el.lastUpdatedText.textContent = formatTime(payload.server_time);
        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);

        el.statPending.textContent = pendingCount;
        el.statInProgress.textContent = inProgressCount;
        el.statCompletedToday.textContent = completedCount;
        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);
        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

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