<x-app-layout>
    <x-slot name="header">
        <div class="flex items-center justify-between">
            <div class="flex items-center space-x-4">
                <a href="{{ route('petugas.pasien.show', $pasien->id) }}" class="text-white hover:text-teal-200">
                    <i class="fas fa-arrow-left text-xl"></i>
                </a>
                <div>
                    <h2 class="font-bold text-2xl">Face Scanner Pasien</h2>
                    <p class="text-sm text-teal-100">{{ $pasien->nama_lengkap }}</p>
                </div>
            </div>
        </div>
    </x-slot>

    <div class="py-8">
        <div class="max-w-4xl mx-auto px-4">

            {{-- Status Flask --}}
            @if(isset($flaskApiRunning) && !$flaskApiRunning)
                <div class="mb-6 bg-red-50 border-l-4 border-red-500 p-6 rounded-xl">
                    <h3 class="font-bold text-red-800">Flask API Tidak Berjalan!</h3>
                    <p>Jalankan: <code class="bg-red-100 px-2 py-1 rounded">python main.py</code></p>
                </div>
            @endif

            {{-- Scanner Area --}}
            <div class="bg-white dark:bg-slate-800 rounded-3xl shadow-2xl overflow-hidden border-4 border-teal-500">
                <div class="relative">
                    <video id="video" class="w-full h-[520px] object-cover" autoplay playsinline muted></video>

                    {{-- Overlay Kotak Deteksi --}}
                    <canvas id="overlay" class="absolute top-0 left-0 w-full h-full pointer-events-none"></canvas>

                    {{-- Status Indicator --}}
                    <div id="status" class="absolute top-6 left-6 bg-black/70 text-white px-5 py-2 rounded-2xl flex items-center gap-3 text-sm font-medium">
                        <div class="w-3 h-3 bg-red-500 rounded-full animate-pulse"></div>
                        Menunggu wajah...
                    </div>

                    {{-- Info Pasien --}}
                    <div class="absolute bottom-6 left-6 bg-white/90 dark:bg-slate-900/90 px-5 py-3 rounded-2xl text-sm">
                        {{ $pasien->nama_lengkap }} • {{ $pasien->no_rekam_medis }}
                    </div>
                </div>
            </div>

            <div class="text-center mt-6 text-gray-500 text-sm">
                Arahkan wajah Anda ke kamera.<br>
                Sistem akan otomatis mendeteksi dan menyimpan saat wajah sudah pas.
            </div>
        </div>
    </div>

    @push('scripts')
    <script src="https://cdn.jsdelivr.net/npm/@vladmandic/face-api@latest/dist/face-api.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
        const video          = document.getElementById('video');
        const canvas         = document.getElementById('overlay');
        const ctx            = canvas.getContext('2d');
        const PASIEN_ID      = {{ $pasien->id }};
        const STORE_URL      = '{{ route("petugas.pasien.register-face.store", $pasien->id) }}';
        const CSRF_TOKEN     = '{{ csrf_token() }}';
        const REDIRECT_URL   = '{{ route("petugas.pasien.show", $pasien->id) }}';

        let stream         = null;
        let isScanning     = true;
        let captureTimeout = null;

        // ── Load model face-api ──────────────────────────────────────────────
        async function loadModels() {
            await faceapi.nets.tinyFaceDetector.loadFromUri(
                'https://cdn.jsdelivr.net/npm/@vladmandic/face-api@latest/model'
            );
            console.log('✅ Face Detector loaded');
        }

        // ── Mulai kamera ─────────────────────────────────────────────────────
        async function startCamera() {
            try {
                stream = await navigator.mediaDevices.getUserMedia({
                    video: { facingMode: 'user', width: 1280, height: 720 }
                });
                video.srcObject = stream;
                video.onloadedmetadata = () => {
                    canvas.width  = video.videoWidth;
                    canvas.height = video.videoHeight;
                    detectFace();
                };
            } catch (err) {
                Swal.fire('Error', 'Tidak bisa mengakses kamera: ' + err.message, 'error');
            }
        }

        // ── Deteksi wajah real-time ──────────────────────────────────────────
        async function detectFace() {
            if (!isScanning) return;

            const detections = await faceapi.detectAllFaces(
                video,
                new faceapi.TinyFaceDetectorOptions({ inputSize: 512, scoreThreshold: 0.6 })
            );

            ctx.clearRect(0, 0, canvas.width, canvas.height);

            if (detections.length === 1) {
                const box = detections[0].box;

                // Gambar kotak hijau
                ctx.strokeStyle = '#10b981';
                ctx.lineWidth   = 6;
                ctx.strokeRect(box.x, box.y, box.width, box.height);

                const centerX    = box.x + box.width / 2;
                const isCentered = Math.abs(centerX - canvas.width / 2) < 80;
                const isBigEnough = box.width > 220;

                if (isCentered && isBigEnough) {
                    setStatus('green', 'Wajah terdeteksi! Sedang memproses...');
                    if (!captureTimeout) {
                        captureTimeout = setTimeout(() => autoCapture(), 1500);
                    }
                } else {
                    setStatus('yellow', 'Arahkan wajah ke tengah');
                    clearTimeout(captureTimeout);
                    captureTimeout = null;
                }

            } else if (detections.length > 1) {
                setStatus('red', 'Hanya 1 wajah yang diizinkan');
                clearTimeout(captureTimeout);
                captureTimeout = null;

            } else {
                setStatus('red', 'Wajah tidak terdeteksi', true);
                clearTimeout(captureTimeout);
                captureTimeout = null;
            }

            setTimeout(detectFace, 80); // ~12 fps
        }

        // ── Helper status indicator ──────────────────────────────────────────
        function setStatus(color, text, pulse = false) {
            const colors = { green: 'bg-green-500', yellow: 'bg-yellow-500', red: 'bg-red-500' };
            const dot    = `<div class="w-3 h-3 ${colors[color]} rounded-full ${pulse ? 'animate-pulse' : ''}"></div>`;
            document.getElementById('status').innerHTML = `${dot} ${text}`;
        }

        // ── Auto capture & kirim ke Laravel ─────────────────────────────────
        function autoCapture() {
            isScanning = false;
            clearTimeout(captureTimeout);
            captureTimeout = null;

            // Ambil frame dari video
            const tempCanvas    = document.createElement('canvas');
            tempCanvas.width    = video.videoWidth;
            tempCanvas.height   = video.videoHeight;
            tempCanvas.getContext('2d').drawImage(video, 0, 0);

            // Base64 JPEG — FIX: kirim sebagai field "image_data" (string),
            // bukan file upload "foto_wajah". Controller sudah disesuaikan.
            const base64 = tempCanvas.toDataURL('image/jpeg', 0.92);

            const formData = new FormData();
            formData.append('pasien_id',  PASIEN_ID);
            formData.append('image_data', base64);   // ← field yang benar

            Swal.fire({
                title: 'Menyimpan Wajah...',
                allowOutsideClick: false,
                didOpen: () => Swal.showLoading()
            });

            fetch(STORE_URL, {
                method:  'POST',
                body:    formData,
                headers: { 'X-CSRF-TOKEN': CSRF_TOKEN },
            })
            .then(async (response) => {
                const data = await response.json();

                if (data.success) {
                    Swal.fire({
                        icon:              'success',
                        title:             'Registrasi Berhasil!',
                        html:              `Kualitas: <b>${data.data.kualitas_gambar}</b><br>Skor: ${data.data.skor_kepercayaan}%`,
                        confirmButtonText: 'Kembali ke Detail Pasien',
                    }).then(() => {
                        window.location.href = REDIRECT_URL;
                    });
                } else {
                    // Tampilkan pesan error lengkap dari server
                    const hint    = data.hint    ? `<br><small>${data.hint}</small>`    : '';
                    const reason  = data.reason  ? `<br><small>${data.reason}</small>`  : '';
                    const details = data.details && data.details.suggestions
                        ? '<br><ul class="text-left text-sm mt-2">' +
                          data.details.suggestions.map(s => `<li>• ${s}</li>`).join('') +
                          '</ul>'
                        : '';

                    Swal.fire({
                        icon:  'error',
                        title: 'Gagal',
                        html:  (data.message || 'Terjadi kesalahan') + reason + hint + details,
                    }).then(() => {
                        // Resume scanning setelah error
                        isScanning = true;
                        detectFace();
                    });
                }
            })
            .catch((err) => {
                console.error('Fetch error:', err);
                Swal.fire('Error Jaringan', 'Gagal menghubungi server: ' + err.message, 'error')
                    .then(() => {
                        isScanning = true;
                        detectFace();
                    });
            });
        }

        // ── Init ─────────────────────────────────────────────────────────────
        loadModels().then(() => {
            startCamera();
        });
    </script>
    @endpush
</x-app-layout>