<script lang="ts">
    import { onMount } from 'svelte';
    import {
        Html5QrcodeScanner,
        type Html5QrcodeResult,
        Html5QrcodeScanType,
        Html5QrcodeSupportedFormats,
        Html5QrcodeScannerState,
    } from 'html5-qrcode';

    let width: number = 300;
    let height: number = 300;

    let { message = $bindable() } = $props();

    function onScanSuccess(decodedText: string, decodedResult: Html5QrcodeResult): void {
        //console.log(`Code scanned = ${decodedText}`);
        message = decodedText;
    }

    // usually better to ignore and keep scanning
    function onScanFailure(message: string) {
        //console.log(`Code scan error = ${message}`);
    }

    let scanner: Html5QrcodeScanner;
    onMount(() => {
        scanner = new Html5QrcodeScanner(
            'qr-scanner',
            {
                fps: 5,
                qrbox: { width, height },
                aspectRatio: 1,
                supportedScanTypes: [Html5QrcodeScanType.SCAN_TYPE_CAMERA],
                formatsToSupport: [Html5QrcodeSupportedFormats.QR_CODE],
            },
            false // non-verbose
        );
        scanner.render(onScanSuccess, onScanFailure);
    });
</script>

<div id="qr-scanner" class="w-full max-w-sm bg-slate-700 rounded-lg overflow-hidden"></div>

<style>
    /* Hide unwanted icons */
    #qr-scanner :global(img[alt='Info icon']),
    #qr-scanner :global(img[alt='Camera based scan']) {
        display: none;
    }

    /* Change camera permission button text */
    #qr-scanner :global(#html5-qrcode-button-camera-permission) {
        visibility: hidden;
    }
    #qr-scanner :global(#html5-qrcode-button-camera-permission::after) {
        position: absolute;
        inset: auto 0 0;
        display: block;
        content: 'Allow camera access';
        visibility: visible;
        padding: 10px 0;
    }
</style>