<!-- Biometric Scanning Modal Component with Device Detection -->
<div id="biometric-modal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
    <div class="bg-white rounded-lg shadow-lg p-8 max-w-md w-full mx-4">
        <div class="flex justify-between items-center mb-6">
            <h2 class="text-xl font-semibold text-gray-800">{{ __('Scan Biometric') }}</h2>
            <button type="button" onclick="closeBiometricModal()"
                class="text-gray-500 hover:text-gray-700 text-2xl">&times;</button>
        </div>

        <div class="space-y-4">
            <!-- Device Status -->
            <div class="p-4 bg-blue-50 border border-blue-200 rounded-lg">
                <p class="text-sm font-semibold text-blue-900 mb-1">{{ __('Device Status') }}</p>
                <p class="text-sm text-blue-700" id="modal-status">🔍 {{ __('Checking for biometric devices...') }}</p>
            </div>

            <!-- Device selector -->
            <div>
                <label for="biometric-device"
                    class="block text-sm font-medium text-gray-700">{{ __('Select Device') }}</label>
                <select id="biometric-device" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm">
                    <option value="">{{ __('Detecting...') }}</option>
                </select>
                <p class="mt-2 text-xs text-gray-600" id="device-hint">⏳ {{ __('Checking device capabilities...') }}</p>
            </div>

            <!-- Scan button -->
            <button type="button" onclick="performBiometricScan()" id="scan-btn"
                class="w-full py-3 bg-indigo-600 text-white font-semibold rounded-lg hover:bg-indigo-700 transition disabled:opacity-50 disabled:cursor-not-allowed">
                🔍 {{ __('Start Scan') }}
            </button>

            <!-- Instructions -->
            <div class="p-3 bg-yellow-50 border border-yellow-200 rounded text-xs text-gray-700">
                <p class="font-semibold mb-2">{{ __('Biometric Device Integration:') }}</p>
                <ul class="list-disc list-inside space-y-1" id="integration-hints">
                    <li>{{ __('WebAuthn (fingerprint/face) supported natively') }}</li>
                    <li>{{ __('For other devices, include SDK JavaScript') }}</li>
                    <li>{{ __('Update performBiometricScan() with device API') }}</li>
                    <li>{{ __('Device returns template → auto-fills form') }}</li>
                </ul>
            </div>

            <!-- Buttons -->
            <div class="flex gap-3 pt-4">
                <button type="button" onclick="closeBiometricModal()"
                    class="flex-1 py-2 border border-gray-300 text-gray-700 font-semibold rounded-lg hover:bg-gray-50 transition">
                    {{ __('Cancel') }}
                </button>
                <button type="button" onclick="completeBiometricScan()"
                    class="flex-1 py-2 bg-green-600 text-white font-semibold rounded-lg hover:bg-green-700 transition">
                    ✓ {{ __('Confirm') }}
                </button>
            </div>
        </div>
    </div>
</div>

<script>
    let biometricData = null;
    let availableDevices = {
        webauthn: false,
        platform: false
    };

    /**
     * Detect available biometric devices using WebAuthn API and browser capabilities
     */
    async function detectBiometricDevices() {
        const statusEl = document.getElementById('modal-status');
        const deviceSelect = document.getElementById('biometric-device');
        const hintEl = document.getElementById('device-hint');
        const scanBtn = document.getElementById('scan-btn');
        const options = [];

        try {
            // Check WebAuthn support (FIDO2 - fingerprint/face recognition)
            if (window.PublicKeyCredential) {
                const isUserVerifyingPlatformAuthenticatorAvailable = await PublicKeyCredential
                    .isUserVerifyingPlatformAuthenticatorAvailable();

                if (isUserVerifyingPlatformAuthenticatorAvailable) {
                    availableDevices.webauthn = true;
                    options.push({
                        value: 'webauthn',
                        label: '🔐 {{ __('Biometric (WebAuthn - Fingerprint/Face)') }}'
                    });
                }
            }

            // Check for platform biometric capability
            if (navigator.credentials) {
                availableDevices.platform = true;
                if (options.length === 0) {
                    options.push({
                        value: 'platform',
                        label: '🔐 {{ __('Platform Authenticator') }}'
                    });
                }
            }

            // Populate device select
            if (options.length > 0) {
                deviceSelect.innerHTML = options.map(opt =>
                    `<option value="${opt.value}">${opt.label}</option>`
                ).join('');

                statusEl.innerHTML = '✅ Biometric device detected! Ready to scan.';
                hintEl.innerHTML = '✓ Device available - click Start Scan to begin';
                scanBtn.disabled = false;

                // Log detected devices
                console.log('Detected biometric devices:', availableDevices);
            } else {
                // No biometric device found
                deviceSelect.innerHTML = '<option value="">❌ No biometric device detected</option>';
                statusEl.innerHTML = '⚠️ No biometric device detected. You can still manually enter data.';
                hintEl.innerHTML =
                    '💡 No native biometric device found. Install device SDK if using custom hardware.';
                scanBtn.disabled = true;

                console.warn('No biometric devices detected');
            }
        } catch (error) {
            deviceSelect.innerHTML = '<option value="">⚠️ Error detecting device</option>';
            statusEl.innerHTML = '⚠️ Error checking for biometric devices.';
            hintEl.innerHTML = 'Error: ' + error.message;
            scanBtn.disabled = true;

            console.error('Error detecting biometric devices:', error);
        }
    }

    function openBiometricModal() {
        document.getElementById('biometric-modal').classList.remove('hidden');
        updateBiometricStatus();
        detectBiometricDevices(); // Check for devices when modal opens
    }

    function closeBiometricModal() {
        document.getElementById('biometric-modal').classList.add('hidden');
    }

    async function performBiometricScan() {
        const statusEl = document.getElementById('modal-status');
        const deviceValue = document.getElementById('biometric-device').value;

        if (!deviceValue) {
            alert('Please select a device or manually enter biometric data.');
            return;
        }

        statusEl.innerText = '⏳ Scanning...';

        // WebAuthn scan
        if (deviceValue === 'webauthn') {
            try {
                // Get current origin for RP ID
                const currentOrigin = window.location.origin;
                const rpId = window.location.hostname;

                // Simple challenge for assertion
                const challenge = new Uint8Array(32);
                crypto.getRandomValues(challenge);

                const assertion = await navigator.credentials.get({
                    publicKey: {
                        challenge: challenge,
                        timeout: 60000,
                        rpId: rpId,
                        userVerification: 'required', // force biometric/PIN verification
                        // allowCredentials: [],
                        authenticatorSelection: {
                            authenticatorAttachment: "platform", // prefer built-in (fingerprint, Face ID, Windows Hello)
                            userVerification: "required"
                        }

                    }
                });

                if (assertion) {
                    // Use assertion ID as biometric template (in production, use proper template extraction)
                    biometricData = 'WEBAUTHN_' + btoa(String.fromCharCode(...new Uint8Array(assertion.id)));
                    statusEl.innerHTML = '✅ Biometric scan successful!';
                }
            } catch (error) {
                // WebAuthn failed - offer fallback options
                console.error('WebAuthn scan error:', error);
                statusEl.innerHTML = '⚠️ WebAuthn unavailable. Using simulated scan...';

                // Fallback: use simulated scan for development
                setTimeout(() => {
                    biometricData = 'SIMULATED_' + Date.now();
                    statusEl.innerHTML = '✅ Simulated scan successful!';
                }, 1500);
            }
            return;
        }

        // Custom device placeholder
        statusEl.innerText = '⏳ Scanning device...';
        setTimeout(() => {
            biometricData = 'SCAN_' + Date.now();
            statusEl.innerHTML = '✅ Scan successful!';
        }, 2000);
    }

    function completeBiometricScan() {
        if (!biometricData) {
            alert('No biometric data scanned. Please perform a scan first.');
            return;
        }

        document.getElementById('biometric_template').value = biometricData;
        updateBiometricStatus();
        closeBiometricModal();
    }

    function updateBiometricStatus() {
        const statusEl = document.getElementById('biometric-status');
        const templateEl = document.getElementById('biometric_template');

        if (templateEl && templateEl.value.trim()) {
            statusEl.innerHTML = '<span class="text-green-600">✓ Biometric data loaded</span>';
        }
    }

    document.addEventListener('DOMContentLoaded', updateBiometricStatus);
</script>
