<!DOCTYPE html>
<html lang="pl">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>S.H.I.E.L.D. SECURE ACCESS</title>
    <!-- Fonts -->
    <link
        href="https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700;900&family=Rajdhani:wght@300;500;700&display=swap"
        rel="stylesheet">
    <!-- HTML5-QRCode Library -->
    <script src="https://unpkg.com/html5-qrcode" type="text/javascript"></script>
    <style>
        :root {
            --stark-blue: #00a8ff;
            --stark-cyan: #00f3ff;
            --reactor-core: #ffffff;
            --hud-bg: rgba(0, 10, 20, 0.85);
            --hud-border: rgba(0, 243, 255, 0.6);
            --alert-red: #ff3333;
            --gold-accent: #ffd700;
        }

        body {
            background-color: #000;
            background-image:
                radial-gradient(circle at 50% 50%, #051a2e 0%, #000000 100%),
                linear-gradient(0deg, rgba(0, 243, 255, 0.03) 1px, transparent 1px),
                linear-gradient(90deg, rgba(0, 243, 255, 0.03) 1px, transparent 1px);
            background-size: 100% 100%, 40px 40px, 40px 40px;
            color: var(--stark-cyan);
            font-family: 'Rajdhani', sans-serif;
            margin: 0;
            padding: 0;
            position: fixed;
            /* Prevent scroll bounce */
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            overflow: hidden;
            perspective: 1000px;
        }

        /* Vignette */
        body::before {
            content: "";
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: radial-gradient(circle, transparent 50%, black 150%);
            z-index: 1;
            pointer-events: none;
        }

        /* Rotating Background Ring (Arc Reactor Style) */
        .bg-ring {
            position: absolute;
            width: 80vh;
            height: 80vh;
            border: 2px dashed rgba(0, 243, 255, 0.1);
            border-radius: 50%;
            animation: rotate 60s linear infinite;
            z-index: 0;
            pointer-events: none;
        }

        .bg-ring::after {
            content: "";
            position: absolute;
            top: -10px;
            left: -10px;
            right: -10px;
            bottom: -10px;
            border: 1px dotted rgba(0, 243, 255, 0.15);
            border-radius: 50%;
        }

        @keyframes rotate {
            from {
                transform: rotate(0deg);
            }

            to {
                transform: rotate(360deg);
            }
        }

        #ui-container {
            width: 90%;
            /* Responsive width */
            max-width: 550px;
            height: auto;
            max-height: 90%;
            /* Leave space for margins */
            position: relative;
            z-index: 10;
            background: var(--hud-bg);
            border: 2px solid var(--hud-border);
            clip-path: polygon(30px 0, 100% 0, 100% calc(100% - 30px), calc(100% - 30px) 100%, 0 100%, 0 30px);
            padding: 20px;
            box-sizing: border-box;
            backdrop-filter: blur(10px);
            box-shadow: 0 0 50px rgba(0, 243, 255, 0.2);
            display: flex;
            flex-direction: column;
            justify-content: center;
            /* Vertical center content */
            align-items: center;
            overflow-y: auto;
            /* Allow internal scrolling if content is tall */
            scrollbar-width: thin;
            scrollbar-color: var(--stark-cyan) var(--hud-bg);
        }

        /* Landscape/Large Screen Adjustments */
        @media (min-width: 1000px) {
            #ui-container {
                max-width: 800px;
                /* Wider for desktop/landscape tablet */
                min-height: 700px;
            }
        }

        /* Mobile/Small Tablet Adjustments */
        @media (max-width: 600px) {
            #ui-container {
                width: 100%;
                height: 100%;
                /* Full screen on mobile */
                max-height: 100%;
                border: none;
                padding: 10px;
                clip-path: none;
                /* Simplify shape */
                justify-content: flex-start;
                /* Align top on mobile to avoid blocked logic */
                padding-top: 40px;
            }

            h1 {
                font-size: 1.5rem;
                margin-top: 10px;
            }
        }

        /* Decorative Corners (Updated to match new container) */
        #ui-container::before {
            content: "";
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background:
                linear-gradient(135deg, var(--stark-cyan) 20px, transparent 0) top left,
                linear-gradient(-135deg, var(--stark-cyan) 20px, transparent 0) bottom right;
            background-size: 30px 30px;
            background-repeat: no-repeat;
            pointer-events: none;
            opacity: 0.5;
        }

        h1 {
            font-family: 'Orbitron', sans-serif;
            text-align: center;
            color: var(--stark-blue);
            text-transform: uppercase;
            letter-spacing: 4px;
            margin-bottom: 5px;
            text-shadow: 0 0 10px var(--stark-blue);
            font-weight: 900;
        }

        .sub-header {
            text-align: center;
            font-size: 0.8rem;
            color: var(--stark-cyan);
            letter-spacing: 2px;
            margin-bottom: 30px;
            opacity: 0.8;
        }

        /* Identity Banner */
        #user-identity {
            display: none;
            background: rgba(0, 243, 255, 0.1);
            border-left: 3px solid var(--stark-cyan);
            padding: 10px;
            margin-bottom: 20px;
            text-align: center;
            font-family: 'Orbitron';
            color: #fff;
            text-shadow: 0 0 5px var(--stark-cyan);
            animation: slideIn 0.5s ease-out;
        }

        @keyframes slideIn {
            from {
                transform: translateX(-20px);
                opacity: 0;
            }

            to {
                transform: translateX(0);
                opacity: 1;
            }
        }

        /* Steps */
        .step-container {
            display: none;
            flex-direction: column;
            align-items: center;
            opacity: 0;
            transition: opacity 0.5s ease;
            width: 100%;
            flex-grow: 1;
        }

        .active-step {
            display: flex;
            opacity: 1;
        }

        h2 {
            font-family: 'Orbitron';
            color: var(--reactor-core);
            text-transform: uppercase;
            font-size: 1.4rem;
            margin-bottom: 20px;
            border-bottom: 1px solid var(--stark-blue);
            padding-bottom: 5px;
            width: 90%;
            text-align: center;
        }

        /* QR Scanner */
        .tech-frame {
            width: 100%;
            flex-grow: 1;
            max-height: 50vh;
            border: 2px solid var(--stark-cyan);
            box-shadow: 0 0 20px var(--stark-cyan);
            position: relative;
            overflow: hidden;
            margin-bottom: 20px;
        }

        .tech-frame::after {
            content: "";
            position: absolute;
            top: 10px;
            left: 10px;
            right: 10px;
            bottom: 10px;
            border: 1px dashed rgba(255, 255, 255, 0.3);
            pointer-events: none;
        }

        #reader video {
            width: 100% !important;
            height: 100% !important;
            object-fit: cover;
        }

        #reader {
            border: none;
        }

        /* Inputs */
        .stark-input {
            background: rgba(0, 0, 0, 0.5);
            border: 1px solid var(--stark-blue);
            color: var(--stark-cyan);
            font-family: 'Orbitron', monospace;
            font-size: 1.8rem;
            text-align: center;
            padding: 15px;
            width: 85%;
            margin-top: 20px;
            outline: none;
            transition: 0.3s;
            box-shadow: inset 0 0 10px rgba(0, 168, 255, 0.2);
        }

        .stark-input:focus {
            border-color: var(--stark-cyan);
            box-shadow: 0 0 20px var(--stark-cyan), inset 0 0 10px rgba(0, 243, 255, 0.3);
        }

        /* Biometrics */
        .bio-frame {
            position: relative;
            padding: 5px;
            border: 1px solid var(--stark-blue);
            background: rgba(0, 20, 40, 0.5);
            width: 100%;
            max-width: 640px;
            flex-grow: 1;
            display: flex;
            flex-direction: column;
        }

        #biometric-video {
            width: 100%;
            height: 100%;
            object-fit: cover;
            filter: grayscale(100%) contrast(1.2) sepia(20%) hue-rotate(180deg) saturate(200%);
        }

        .scanning-arc {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 90%;
            height: 90%;
            border: 2px solid rgba(0, 243, 255, 0.5);
            border-radius: 50%;
            animation: pulse-ring 2s infinite;
            pointer-events: none;
        }

        .scan-line {
            position: absolute;
            width: 100%;
            height: 4px;
            background: var(--stark-cyan);
            box-shadow: 0 0 20px var(--stark-cyan), 0 0 40px var(--stark-blue);
            animation: scan-vertical 1.5s cubic-bezier(0.4, 0, 0.2, 1) infinite;
            z-index: 10;
            opacity: 0.8;
            top: 0;
        }

        @keyframes scan-vertical {
            0% {
                top: 0%;
                opacity: 0.5;
            }

            50% {
                opacity: 1;
            }

            100% {
                top: 100%;
                opacity: 0.5;
            }
        }

        @keyframes pulse-ring {
            0% {
                transform: translate(-50%, -50%) scale(0.8);
                opacity: 0.5;
            }

            100% {
                transform: translate(-50%, -50%) scale(1.1);
                opacity: 0;
            }
        }

        /* Status */
        .status-message {
            margin-top: 20px;
            font-size: 1.1rem;
            text-transform: uppercase;
            font-weight: bold;
            letter-spacing: 1px;
            text-align: center;
        }

        .status-success {
            color: #0f0;
            text-shadow: 0 0 10px #0f0;
        }

        .status-error {
            color: var(--alert-red);
            text-shadow: 0 0 10px var(--alert-red);
        }

        /* Access Granted */
        #arc-reactor {
            width: 100px;
            height: 100px;
            background: radial-gradient(circle, #fff, #aaddff, #00a8ff);
            border-radius: 50%;
            margin: 20px auto;
            box-shadow: 0 0 50px var(--stark-cyan);
            position: relative;
        }

        #arc-reactor::after {
            content: "";
            position: absolute;
            top: 10px;
            left: 10px;
            right: 10px;
            bottom: 10px;
            border: 3px solid #333;
            border-radius: 50%;
        }

        button {
            background: transparent;
            border: 2px solid var(--stark-cyan);
            color: var(--stark-cyan);
            padding: 15px 40px;
            font-family: 'Orbitron';
            margin-top: 30px;
            cursor: pointer;
            text-transform: uppercase;
            transition: 0.3s;
            font-size: 1.5rem;
        }

        button:hover {
            background: var(--stark-cyan);
            color: #000;
            box-shadow: 0 0 20px var(--stark-cyan);
        }

        .corner {
            position: absolute;
            width: 20px;
            height: 20px;
            border-color: var(--stark-cyan);
            border-style: solid;
            pointer-events: none;
            z-index: 5;
        }

        .tl {
            top: -2px;
            left: -2px;
            border-width: 2px 0 0 2px;
        }

        .tr {
            top: -2px;
            right: -2px;
            border-width: 2px 2px 0 0;
        }

        .bl {
            bottom: -2px;
            left: -2px;
            border-width: 0 0 2px 2px;
        }

        .br {
            bottom: -2px;
            right: -2px;
            border-width: 0 2px 2px 0;
        }

        /* START OVERLAY */
        #start-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.95);
            z-index: 10000;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            text-align: center;
            backdrop-filter: blur(10px);
            margin: 0;
            padding: 0;
        }

        .start-btn {
            width: 200px;
            height: 200px;
            background: radial-gradient(circle, rgba(0, 243, 255, 0.2), transparent 70%);
            border: 2px solid var(--stark-cyan);
            border-radius: 50%;
            color: var(--stark-cyan);
            font-family: 'Orbitron';
            font-size: 1.5rem;
            text-transform: uppercase;
            letter-spacing: 2px;
            cursor: pointer;
            box-shadow: 0 0 30px var(--stark-cyan), inset 0 0 20px var(--stark-cyan);
            animation: pulse-ring 2s infinite;
            display: flex;
            justify-content: center;
            align-items: center;
            text-align: center;
            /* Enforces multi-line limit centering */
            transition: all 0.3s;
            margin: 0 auto;
			margin-right:270px;
            /* Safety centering */
        }

        .start-btn:hover {
            transform: scale(1.1);
            background: rgba(0, 243, 255, 0.3);
            text-shadow: 0 0 10px #fff;
        }
    </style>
</head>

<body>

    <div class="bg-ring"></div>
    <div class="bg-ring" style="width: 60vh; height: 60vh; animation-direction: reverse; border-style: dotted;"></div>

    <div id="start-overlay">
        <div style="display: flex; flex-direction: column; align-items: center; justify-content: center; width: 100%; height: 100%;">
            <div class="start-btn" onclick="initSystem()">START<br>SYSTEM</div>
            <div style="margin-top: 20px; color: var(--stark-blue); font-family: 'Rajdhani'; letter-spacing: 3px; text-align: center; width: 100%;">
                INITIALIZING SECURE PROTOCOLS</div>
        </div>
    </div>

    <div id="ui-container">
        <div id="header">
            <h1>IT PARTY 2026</h1>
            <div class="sub-header">DOSTĘP DO IMPREZY CHRONIONY</div>

            <!-- Persistent Identity -->
            <div id="user-identity">
                ZIDENTYFIKOWANO: <span id="id-display" style="color: var(--gold-accent);">NIEZNANY</span>
            </div>


        </div>

        <!-- STEP 1: QR AUTH -->
        <div id="step-1" class="step-container active-step">
            <h2> KROK 1: Identyfikacja </h2>
            <div id="reader" class="tech-frame"></div>
            <div id="qr-status" class="status-message"> ZESKANUJ KOD DOSTĘPU </div>
        </div>

        <!-- STEP 2: LOGIC CHALLENGE -->
        <div id="step-2" class="step-container">
            <h2> KROK 2: Weryfikacja</h2>
            <div
                style="width: 90%; text-align: center; margin: 20px; border: 1px solid var(--stark-blue); padding: 20px; background: rgba(0,0,0,0.6);">
                <div style="font-size: 0.8rem; color: var(--stark-blue);">PYTANIE KONTROLNE</div>
                <div id="riddle-content"
                    style="font-size: 1.5rem; color: var(--gold-accent); letter-spacing: 2px; margin-top: 10px; font-weight: bold;">
                    ŁADOWANIE...</div>
            </div>
            <input type="text" id="riddle-input" class="stark-input" placeholder="WPROWADŹ ODPOWIEDŹ"
                autocomplete="off">
            <div id="riddle-status" class="status-message"> OCZEKIWANIE... </div>
        </div>

        <!-- STEP 3: BIOMETRIC SIMULATION -->
        <div id="step-3" class="step-container">
            <h2> KROK 3: SKAN BIOMETRYCZNY </h2>
            <div class="bio-frame">
                <div class="corner tl"></div>
                <div class="corner tr"></div>
                <div class="corner bl"></div>
                <div class="corner br"></div>

                <video id="biometric-video" autoplay playsinline muted></video>
                <div class="scanning-arc"></div>
                <div class="scan-line"></div>

                <div
                    style="position: absolute; top: 10px; left: 10px; background: rgba(0,0,0,0.7); padding: 2px 5px; font-size: 0.7rem;">
                    SKAN SIATKÓWKI</div>
                <div
                    style="position: absolute; bottom: 10px; right: 10px; background: rgba(0,0,0,0.7); padding: 2px 5px; font-size: 0.7rem;">
                    ANALIZA DNA</div>
            </div>
            <div id="bio-timer"
                style="margin-top: 15px; font-family: 'Orbitron'; color: var(--stark-blue); font-size: 1.5rem;">
                INICJALIZACJA...</div>
            <div id="bio-status" class="status-message"> PROSZĘ STAC NIERUCHOMO </div>
        </div>

        <!-- STEP 4: ACCESS GRANTED -->
        <div id="step-4" class="step-container">
            <div id="arc-reactor"></div>
            <h2
                style="border: none; color: var(--stark-cyan); font-size: 2.5rem; text-shadow: 0 0 20px var(--stark-cyan); margin-top: 20px;">
                DOSTĘP PRZYZNANY</h2>
            <p>WITAJ PONOWNIE, <span id="guest-name-final"
                    style="color: var(--gold-accent); font-weight: bold; font-size: 1.5rem; text-transform: uppercase;">GOŚĆ</span>
            </p>
            <button onclick="location.reload()">RESTART SYSTEMU</button>
        </div>
    </div>

    <script>
        // --- AUDIO SYSTEM (LOUD VERSION) ---
        const AudioSys = {
            ctx: null,
            voices: [],
            init: function () {
                window.AudioContext = window.AudioContext || window.webkitAudioContext;
                this.ctx = new AudioContext();
                if ('speechSynthesis' in window) {
                    this.loadVoices();
                    window.speechSynthesis.onvoiceschanged = this.loadVoices.bind(this);
                }
            },
            loadVoices: function () {
                this.voices = window.speechSynthesis.getVoices();
            },
            playTone: function (freq, type, duration, vol = 0.5) {
                if (!this.ctx) this.init();
                if (this.ctx.state === 'suspended') this.ctx.resume();

                const osc = this.ctx.createOscillator();
                const gain = this.ctx.createGain();
                osc.type = type;
                osc.frequency.setValueAtTime(freq, this.ctx.currentTime);
                gain.gain.setValueAtTime(vol, this.ctx.currentTime);
                gain.gain.exponentialRampToValueAtTime(0.01, this.ctx.currentTime + duration);
                osc.connect(gain);
                gain.connect(this.ctx.destination);
                osc.start();
                osc.stop(this.ctx.currentTime + duration);
            },
            playSuccess: function () {
                if (!this.ctx) this.init();
                this.playTone(400, 'square', 0.1, 0.4);
                setTimeout(() => this.playTone(800, 'square', 0.1, 0.4), 100);
                setTimeout(() => this.playTone(1200, 'square', 0.3, 0.4), 200);
            },
            playError: function () {
                if (!this.ctx) this.init();
                this.playTone(100, 'sawtooth', 0.5, 0.6);
            },
            playScan: function () {
                if (!this.ctx) this.init();
                this.playTone(1200, 'square', 0.05, 0.1);
            },
            speak: function (text) {
                if ('speechSynthesis' in window) {
                    window.speechSynthesis.cancel();

                    // Try to reload voices if empty
                    if (this.voices.length === 0) {
                        this.voices = window.speechSynthesis.getVoices();
                    }

                    const utterance = new SpeechSynthesisUtterance(text);
                    const plVoice = this.voices.find(v => v.lang.includes('pl'));
                    if (plVoice) {
                        utterance.voice = plVoice;
                    } else {
                        console.warn("Polish voice not found, using default.");
                    }

                    utterance.lang = 'pl-PL';
                    utterance.rate = 1.0;
                    utterance.pitch = 0.9;
                    window.speechSynthesis.speak(utterance);
                }
            }
        };

        // Global State
        let currentGuestId = null;
        let currentGuestName = "";
        const html5QrCode = new Html5Qrcode("reader");

        // Utilities
        function showStatus(elementId, message, type = 'normal') {
            const el = document.getElementById(elementId);
            el.innerText = message;
            if (type === 'error') {
                el.className = 'status-message status-error';
                AudioSys.playError();
            } else if (type === 'success') {
                el.className = 'status-message status-success';
                AudioSys.playSuccess();
            } else {
                el.className = 'status-message';
            }
        }

        function switchStep(stepNumber) {
            document.querySelectorAll('.step-container').forEach(el => {
                el.classList.remove('active-step');
                setTimeout(() => {
                    if (!el.classList.contains('active-step')) el.style.display = 'none';
                }, 500);
            });

            const next = document.getElementById('step-' + stepNumber);
            next.style.display = 'flex';
            void next.offsetWidth;
            next.classList.add('active-step');
        }

        // --- STEP 1: QR CODE ---
        function onScanSuccess(decodedText) {
            AudioSys.playScan();
            html5QrCode.stop().then(() => {
                verifyQrCode(decodedText);
            });
        }

        function startQrScanner() {
            const config = { fps: 15, qrbox: { width: 300, height: 300 } };
            html5QrCode.start({ facingMode: "user" }, config, onScanSuccess, () => { })
                .catch(err => {
                    showStatus('qr-status', "KAMERA OFFLINE", 'error');
                });
        }

        async function verifyQrCode(code) {
            showStatus('qr-status', "ANALIZA DANYCH...", 'normal');
            try {
                const response = await fetch('check_guest.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ qr_code: code })
                });
                const data = await response.json();

                if (data.status === 'success') {
                    currentGuestId = data.guest_id;
                    currentGuestName = data.guest_name;
                    const guestName = data.guest_name.toUpperCase();

                    document.getElementById('user-identity').style.display = 'block';
                    document.getElementById('id-display').innerText = guestName;



                    document.getElementById('guest-name-final').innerText = guestName;

                    showStatus('qr-status', "TOŻSAMOŚĆ POTWIERDZONA", 'success');
                    AudioSys.speak("Witaj " + data.guest_name + ". Przejdź do weryfikacji.");

                    setTimeout(() => {
                        switchStep(2);
                        const question = data.riddle_question || "BŁĄD DANYCH";
                        document.getElementById('riddle-content').innerText = question;
                        document.getElementById('riddle-input').focus();
                    }, 4000); // 4s delay
                } else {
                    showStatus('qr-status', "BŁĄD KODU", 'error');
                    setTimeout(() => startQrScanner(), 2000);
                }
            } catch (e) {
                console.error(e);
                showStatus('qr-status', "BŁĄD SERWERA", 'error');
            }
        }

        // --- STEP 2: RIDDLE ---
        document.getElementById('riddle-input').addEventListener('keypress', function (e) {
            if (e.key === 'Enter') verifyRiddle(this.value);
        });

        async function verifyRiddle(answer) {
            showStatus('riddle-status', "OBLICZANIE...", 'normal');
            AudioSys.playScan();
            try {
                const response = await fetch('verify_riddle.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ guest_id: currentGuestId, answer: answer })
                });
                const data = await response.json();

                if (data.status === 'success') {
                    showStatus('riddle-status', "ODPOWIEDŹ POPRAWNA", 'success');
                    AudioSys.speak("Odpowiedź poprawna. Uruchamiam skan biometryczny.");
                    setTimeout(() => { switchStep(3); startBiometricScan(); }, 3000); // 3s delay
                } else {
                    showStatus('riddle-status', "BŁĄD ODPOWIEDZI", 'error');
                    document.getElementById('riddle-input').value = '';
                }
            } catch (e) { showStatus('riddle-status', "BŁĄD", 'error'); }
        }

        // --- STEP 3: BIOMETRICS ---
        function startBiometricScan() {
            const video = document.getElementById('biometric-video');
            const timerEl = document.getElementById('bio-timer');
            let progress = 0;

            navigator.mediaDevices.getUserMedia({ video: { facingMode: "user" } })
                .then(stream => {
                    video.srcObject = stream;

                    const interval = setInterval(() => {
                        progress += 5;
                        timerEl.innerText = `ANALIZA: ${progress}%`;
                        AudioSys.playScan();

                        if (progress === 30) showStatus('bio-status', "ROZPOZNAWANIE TWARZY...");
                        if (progress === 70) showStatus('bio-status', "SYNCHRONIZACJA DNA...");

                        if (progress >= 100) {
                            clearInterval(interval);
                            captureAndSave(video, stream);
                        }
                    }, 250); // Total around 5s
                })
                .catch(err => {
                    showStatus('bio-status', "BŁĄD SENSORA", 'error');
                });
        }

        function captureAndSave(video, stream) {
            const canvas = document.createElement('canvas');
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;
            const ctx = canvas.getContext('2d');

            ctx.filter = 'grayscale(100%)';
            ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
            // Iron Man HUD tint
            ctx.globalCompositeOperation = "overlay";
            ctx.fillStyle = "rgba(0, 168, 255, 0.3)";
            ctx.fillRect(0, 0, canvas.width, canvas.height);

            const imageData = canvas.toDataURL('image/png');
            stream.getTracks().forEach(track => track.stop());

            saveBiometrics(imageData);
        }

        async function saveBiometrics(imageData) {
            showStatus('bio-status', "WYSYŁANIE...", 'normal');
            try {
                const response = await fetch('save_biometrics.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ guest_id: currentGuestId, image: imageData })
                });
                const data = await response.json();

                if (data.status === 'success') {
                    showStatus('bio-status', "ZAKOŃCZONO", 'success');
                    AudioSys.playSuccess();
                    AudioSys.speak("Dostęp przyznany. Witamy " + currentGuestName);
                    switchStep(4);

                    setTimeout(() => location.reload(), 7000); // 7s delay
                } else {
                    showStatus('bio-status', data.message, 'error');
                }
            } catch (e) {
                showStatus('bio-status', "BŁĄD SIECI", 'error');
            }
        }

        function initSystem() {
            const overlay = document.getElementById('start-overlay');
            overlay.style.transition = 'opacity 0.5s';
            overlay.style.opacity = '0';
            setTimeout(() => overlay.style.display = 'none', 500);

            // Initialize Audio Logic
            AudioSys.init();
            if (AudioSys.ctx && AudioSys.ctx.state === 'suspended') {
                AudioSys.ctx.resume();
            }
            // Trigger empty speech to unlock iOS/Android TTS constraints
            if ('speechSynthesis' in window) {
                const u = new SpeechSynthesisUtterance("");
                window.speechSynthesis.speak(u);
            }

            startQrScanner();
        }

        // window.onload moved to initSystem trigger
        // window.onload = function () { AudioSys.init(); startQrScanner(); };
    </script>
</body>

</html>