<x-filament-panels::page>
    <div class="space-y-4">
        {{-- Render the Select form fields --}}
        {{-- <div class="space-y-4">
            {{ $this->form($this->form) }}
        </div> --}}

         <div class="space-y-4">
        {{ $this->form }}
    </div>

     <div class="flex flex-col items-center space-y-4">
        <video id="webcam" autoplay playsinline class="rounded-xl border"></video>

        <canvas id="snapshot" class="hidden"></canvas>

        <div class="flex space-x-4">
            <x-filament::button id="capture-btn">📸 Capture</x-filament::button>
            <x-filament::button id="upload-btn" color="success">⬆️ Upload</x-filament::button>
        </div>

        <img id="preview" class="hidden rounded-lg border mt-4" alt="Captured photo preview" />

    <script>
        const video = document.getElementById('webcam');
        const canvas = document.getElementById('snapshot');
        const preview = document.getElementById('preview');
        const captureBtn = document.getElementById('capture-btn');
        const uploadBtn = document.getElementById('upload-btn');
        const context = canvas.getContext('2d');
        let imageBlob;

        // 🔹 Access webcam
        navigator.mediaDevices.getUserMedia({ video: true })
            .then(stream => {
                video.srcObject = stream;
            })
            .catch(err => alert('Camera access denied: ' + err));

        // 🔹 Capture photo
        captureBtn.addEventListener('click', () => {
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;
            context.drawImage(video, 0, 0);
            canvas.toBlob(blob => {
                imageBlob = blob;
                preview.src = URL.createObjectURL(blob);
                preview.classList.remove('hidden');
            }, 'image/jpeg');
        });

        // 🔹 Upload photo to Laravel
        uploadBtn.addEventListener('click', async () => {
            if (!imageBlob) {
                alert('Capture a photo first!');
                return;
            }

            const formData = new FormData();
            formData.append('photo', imageBlob, '123.jpg');

            const response = await fetch('{{ route('webcam.upload') }}', {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': '{{ csrf_token() }}',
                },
                body: formData,
            });

            const result = await response.json();
            alert(result.message || 'Uploaded!');
        });
    </script>

        {{-- Render the chart widget below the form --}}
        {{-- <div class="mt-6">
            @livewire(\App\Filament\Widgets\InvoiceChart::class)
        </div> --}}
    </div>
</x-filament-panels::page>
