@extends('layouts.technician')
@section('title', 'Scan QR Tiket')

@push('head')
{{-- html5-qrcode --}}
<script src="https://unpkg.com/html5-qrcode@2.3.8/html5-qrcode.min.js"></script>
@endpush

@section('content')
<div class="py-4" x-data="qrScanner()">

    {{-- Header --}}
    <div class="text-center mb-5">
        <h1 class="text-lg font-bold text-gray-800">Scan QR Label Tiket</h1>
        <p class="text-xs text-gray-500 mt-1">Arahkan kamera ke QR Code pada label barang</p>
    </div>

    {{-- Kamera view --}}
    <div class="relative rounded-2xl overflow-hidden shadow-lg bg-black aspect-square max-w-xs mx-auto">
        <div id="qr-reader" class="w-full h-full"></div>

        {{-- Overlay frame --}}
        <div class="absolute inset-0 pointer-events-none flex items-center justify-center">
            <div class="w-48 h-48 relative">
                <span class="absolute top-0 left-0 w-8 h-8 border-t-4 border-l-4 border-emerald-400 rounded-tl-lg"></span>
                <span class="absolute top-0 right-0 w-8 h-8 border-t-4 border-r-4 border-emerald-400 rounded-tr-lg"></span>
                <span class="absolute bottom-0 left-0 w-8 h-8 border-b-4 border-l-4 border-emerald-400 rounded-bl-lg"></span>
                <span class="absolute bottom-0 right-0 w-8 h-8 border-b-4 border-r-4 border-emerald-400 rounded-br-lg"></span>
            </div>
        </div>
    </div>

    {{-- Status & feedback --}}
    <div class="mt-5 text-center min-h-[4rem]">

        {{-- Scanning state --}}
        <div x-show="state === 'scanning'" class="flex flex-col items-center gap-2">
            <div class="flex items-center gap-2 text-sm text-emerald-700 font-medium">
                <svg class="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24">
                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"/>
                    <path class="opacity-75" fill="currentColor"
                          d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"/>
                </svg>
                Memindai…
            </div>
        </div>

        {{-- Success redirect --}}
        <div x-show="state === 'found'" class="flex flex-col items-center gap-2">
            <div class="inline-flex items-center gap-2 text-xs font-semibold text-emerald-700
                        bg-emerald-50 border border-emerald-200 rounded-full px-4 py-2">
                <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                    <path fill-rule="evenodd"
                          d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586
                             7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z"
                          clip-rule="evenodd"/>
                </svg>
                QR terbaca! Mengalihkan…
            </div>
        </div>

        {{-- Error --}}
        <div x-show="state === 'error'" class="flex flex-col items-center gap-3">
            <div class="inline-flex items-center gap-2 text-xs font-medium text-red-700
                        bg-red-50 border border-red-200 rounded-full px-4 py-2">
                <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                    <path fill-rule="evenodd"
                          d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10
                             l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414
                             L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z"
                          clip-rule="evenodd"/>
                </svg>
                QR tidak dikenali — bukan tiket servis
            </div>
            <button @click="resetScanner()"
                    class="text-xs font-medium text-emerald-700 underline underline-offset-2">
                Coba lagi
            </button>
        </div>

        {{-- Camera denied --}}
        <div x-show="state === 'denied'" class="flex flex-col items-center gap-3 px-4">
            <div class="text-sm text-red-700 bg-red-50 border border-red-200 rounded-xl px-4 py-3">
                <p class="font-semibold mb-1">Akses kamera ditolak.</p>
                <p class="text-xs text-red-600">Izinkan akses kamera di pengaturan browser, lalu muat ulang halaman.</p>
            </div>
        </div>

    </div>

    {{-- Divider --}}
    <div class="mt-6 flex items-center gap-3 text-xs text-gray-400">
        <div class="flex-1 border-t border-gray-200"></div>
        atau masukkan kode tiket manual
        <div class="flex-1 border-t border-gray-200"></div>
    </div>

    {{-- Manual entry --}}
        <form method="GET" action="{{ route('technician.scanner.manual') }}" class="mt-4 flex gap-2">
        <input type="text" name="code" placeholder="SRV-20260429-0001" required
             class="flex-1 rounded-xl border border-gray-300 px-4 py-2.5 text-xs
                      focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-transparent
                      placeholder-gray-400 uppercase tracking-wider"
               oninput="this.value = this.value.toUpperCase()">
        <button type="submit"
              class="flex-shrink-0 bg-emerald-600 text-white text-xs font-semibold
                       px-4 py-2.5 rounded-xl hover:bg-emerald-700 active:bg-emerald-800 transition">
            Buka
        </button>
    </form>

    <a href="{{ route('technician.tickets.index') }}"
    class="mt-3 inline-flex w-full items-center justify-center rounded-xl border border-gray-300
        px-4 py-2.5 text-xs font-medium text-gray-700 hover:bg-gray-50 transition">
        Lihat List Service
    </a>

</div>
@endsection

@push('scripts')
<script>
function qrScanner() {
    return {
        state: 'scanning',
        scanner: null,

        init() {
            this.startScanner();
        },

        startScanner() {
            this.state = 'scanning';

            this.scanner = new Html5Qrcode('qr-reader');

            const config = {
                fps: 10,
                qrbox: { width: 220, height: 220 },
                aspectRatio: 1.0,
            };

            this.scanner.start(
                { facingMode: 'environment' },
                config,
                (decodedText) => this.onSuccess(decodedText),
                () => { /* ignore per-frame failures */ }
            ).catch(() => {
                this.state = 'denied';
            });
        },

        onSuccess(text) {
            // Match /tickets/{id} anywhere in the URL
            const match = text.match(/\/tickets\/(\d+)/);
            if (match) {
                this.state = 'found';
                this.scanner.stop().then(() => {
                    window.location.href = `{{ url('/technician/tickets') }}/${match[1]}/book`;
                });
            } else {
                this.scanner.stop().then(() => {
                    this.state = 'error';
                });
            }
        },

        resetScanner() {
            this.startScanner();
        }
    }
}
</script>
@endpush
