<!DOCTYPE html>
<html lang="vi" class="h-full bg-gray-100">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ứng dụng Chấm công</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
    <script
        src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.33/moment-timezone-with-data.min.js"></script>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">
    <!-- Thêm Toastify CSS -->
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css">
    <!-- Thêm Toastify JS -->
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/toastify-js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <style>
        .modal {
            transition: opacity 0.25s ease;
        }

        body.modal-active {
            overflow-x: hidden;
            overflow-y: visible !important;
        }
    </style>

</head>


<body class="h-full bg-gray-100">
    <div class="min-h-full">
        <header class="bg-white shadow">
            <div class="max-w-7xl mx-auto px-4 py-4 sm:px-6 lg:px-8">
                <h1 class="text-2xl sm:text-3xl font-bold tracking-tight text-gray-900">Chấm công</h1>
            </div>
        </header>

        <main class="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
            <!-- Login Form -->
            <div id="loginForm" class="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
                <div class="bg-white py-8 px-4 shadow sm:rounded-lg sm:px-10">
                    <form class="space-y-6" action="#" method="POST">
                        <div>
                            <label for="username" class="block text-sm font-medium text-gray-700">Tên đăng nhập</label>
                            <div class="mt-1">
                                <input id="username" name="username" type="text" autocomplete="username" required
                                    class="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                            </div>
                        </div>

                        <div>
                            <label for="password" class="block text-sm font-medium text-gray-700">Mật khẩu</label>
                            <div class="mt-1">
                                <input id="password" name="password" type="password" autocomplete="current-password"
                                    required
                                    class="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                            </div>
                        </div>

                        <div class="flex items-center justify-between">
                            <div class="flex items-center">
                                <input id="rememberLogin" name="rememberLogin" type="checkbox"
                                    class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded">
                                <label for="rememberLogin" class="ml-2 block text-sm text-gray-900">Ghi nhớ đăng
                                    nhập</label>
                            </div>
                        </div>

                        <div>
                            <button id="loginBtn" type="button"
                                class="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                                Đăng nhập
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Check In/Out Choice -->
            <div id="checkInOutChoice" class="hidden mt-8 sm:mx-auto sm:w-full sm:max-w-md">
                <div class="bg-white py-8 px-4 shadow sm:rounded-lg sm:px-10">
                    <div class="space-y-4">
                        <button id="checkInBtn"
                            class="w-full flex justify-center py-3 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                            Check In
                        </button>
                        <button id="checkOutBtn"
                            class="w-full flex justify-center py-3 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500">
                            Check Out
                        </button>
                        <button id="logoutBtn"
                            class="w-full flex justify-center py-3 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500">
                            Đăng xuất
                        </button>
                    </div>
                </div>
            </div>

            <!-- Camera Container -->
            <div id="cameraContainer" class="hidden mt-8 sm:mx-auto sm:w-full sm:max-w-md">
                <div class="bg-white py-8 px-4 shadow sm:rounded-lg sm:px-10">
                    <div class="space-y-6">
                        <div class="relative">
                            <video id="camera" class="w-full rounded-lg shadow-lg" autoplay playsinline></video>
                            <div id="cameraOverlay"
                                class="absolute top-2 left-2 bg-black bg-opacity-50 text-white p-2 rounded text-xs">
                            </div>
                        </div>
                        <div class="grid grid-cols-2 gap-4">
                            <button id="switchCameraBtn"
                                class="w-full flex justify-center items-center py-3 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-gray-600 hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500">
                                <i class="fas fa-sync-alt mr-2"></i>Đổi Camera
                            </button>
                            <button id="captureBtn"
                                class="w-full flex justify-center items-center py-3 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                                <i class="fas fa-camera mr-2"></i>Chụp ảnh vào
                            </button>
                        </div>
                        <button id="captureOutBtn"
                            class="hidden w-full flex justify-center items-center py-3 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500">
                            <i class="fas fa-camera mr-2"></i>Chụp ảnh ra
                        </button>
                        <button id="backBtn"
                            class="w-full flex justify-center items-center py-3 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-gray-600 hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500">
                            <i class="fas fa-arrow-left mr-2"></i>Quay lại
                        </button>
                        <img id="photo" class="w-full rounded-lg shadow-lg hidden"
                            alt="Ảnh đã chụp sẽ xuất hiện ở đây.">
                        <div id="infoDisplay" class="text-sm text-gray-600"></div>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <!-- Modal -->
    <div id="confirmModal"
        class="modal opacity-0 pointer-events-none fixed w-full h-full top-0 left-0 flex items-center justify-center">
        <div class="modal-overlay absolute w-full h-full bg-gray-900 opacity-50"></div>

        <div class="modal-container bg-white w-11/12 md:max-w-md mx-auto rounded shadow-lg z-50 overflow-y-auto">
            <div class="modal-content py-4 text-left px-6">
                <div class="flex justify-between items-center pb-3">
                    <p class="text-xl font-bold">Xác nhận ghi đè</p>
                    <div class="modal-close cursor-pointer z-50">
                        <svg class="fill-current text-black" xmlns="http://www.w3.org/2000/svg" width="18" height="18"
                            viewBox="0 0 18 18">
                            <path
                                d="M14.53 4.53l-1.06-1.06L9 7.94 4.53 3.47 3.47 4.53 7.94 9l-4.47 4.47 1.06 1.06L9 10.06l4.47 4.47 1.06-1.06L10.06 9z">
                            </path>
                        </svg>
                    </div>
                </div>
                <p id="modal-text" class="my-4"></p>
                <div class="flex justify-end pt-2">
                    <button
                        class="modal-close px-4 bg-transparent p-3 rounded-lg text-indigo-500 hover:bg-gray-100 hover:text-indigo-400 mr-2">Hủy</button>
                    <button id="modal-confirm"
                        class="px-4 bg-indigo-500 p-3 rounded-lg text-white hover:bg-indigo-400">Xác nhận</button>
                </div>
            </div>
        </div>
    </div>

    <div id="loadingBox" class="fixed inset-0 flex items-center justify-center bg-gray-900 bg-opacity-50 z-50 hidden">
        <div class="bg-white p-5 rounded-lg shadow-lg">
            <div class="animate-spin rounded-full h-10 w-10 border-b-2 border-gray-900"></div>
            <p class="mt-3 text-gray-700">Đang gửi dữ liệu...</p>
        </div>
    </div>

    <script>

        // Vô hiệu hóa chuột phải
        document.addEventListener('contextmenu', function (e) {
            e.preventDefault();
        }, false);

        // Vô hiệu hóa phím tắt
        document.onkeydown = function (e) {
            // Vô hiệu hóa F12
            if (e.keyCode == 123) {
                return false;
            }
            // Vô hiệu hóa Ctrl+Shift+I
            if (e.ctrlKey && e.shiftKey && e.keyCode == 'I'.charCodeAt(0)) {
                return false;
            }
            // Vô hiệu hóa Ctrl+Shift+J
            if (e.ctrlKey && e.shiftKey && e.keyCode == 'J'.charCodeAt(0)) {
                return false;
            }
            // Vô hiệu hóa Ctrl+U
            if (e.ctrlKey && e.keyCode == 'U'.charCodeAt(0)) {
                return false;
            }
        };

        const uploadToImgBB = async (base64Image) => {
            const formData = new FormData();
            formData.append('image', base64Image.split(',')[1]);

            try {
                const response = await axios.post(IMGBB_UPLOAD_URL, formData, {
                    params: {
                        key: IMGBB_API_KEY
                    }
                });
                return response.data.data.url;
            } catch (error) {
                throw new Error('Lỗi upload ảnh: ' + error.message);
            }
        }
        // Your existing JavaScript code here
        // Constants
        const APP_ID = '1216c729-76e6-4515-80c1-3b9c4ef3ed9e';
        const ACCESS_KEY = 'V2-X3g13-TINHw-bkl3F-Arpld-zMzvm-DoWDE-lsUXP-GCjuW';
        const REGION = 'www';
        const API_URL = `https://${REGION}.appsheet.com/api/v2/apps/${APP_ID}/tables`;
        const IMGBB_API_KEY = '7267d539a8c541130ce4524afdc69ad3'; // Thay bằng API key của bạn
        const IMGBB_UPLOAD_URL = 'https://api.imgbb.com/1/upload';
        // DOM Elements
        const elements = {
            camera: document.getElementById('camera'),
            captureBtn: document.getElementById('captureBtn'),
            captureOutBtn: document.getElementById('captureOutBtn'),
            switchCameraBtn: document.getElementById('switchCameraBtn'),
            backBtn: document.getElementById('backBtn'),
            cameraContainer: document.getElementById('cameraContainer'),
            checkInOutChoice: document.getElementById('checkInOutChoice'),
            photo: document.getElementById('photo'),
            infoDisplay: document.getElementById('infoDisplay'),
            alertBox: document.getElementById('alertBox'),
            loadingBox: document.getElementById('loadingBox'),
            checkInBtn: document.getElementById('checkInBtn'),
            checkOutBtn: document.getElementById('checkOutBtn'),
            logoutBtn: document.getElementById('logoutBtn'),
            loginBtn: document.getElementById('loginBtn'),
            loginForm: document.getElementById('loginForm'),
            usernameInput: document.getElementById('username'),
            passwordInput: document.getElementById('password'), modal: document.querySelector('.modal'),
            modalText: document.getElementById('modal-text'),
            modalConfirm: document.getElementById('modal-confirm'),
            modalCloseButtons: document.querySelectorAll('.modal-close'),
            rememberLoginCheckbox: document.getElementById('rememberLogin')
        };

        // Global variables
        let stream;
        let facingMode = "environment";
        let currentUser = null;

        const openModal = (message, onConfirm) => {
            elements.modalText.textContent = message;
            elements.modal.classList.remove('opacity-0', 'pointer-events-none');
            document.body.classList.add('modal-active');

            elements.modalConfirm.onclick = () => {
                closeModal();
                onConfirm();
            };
        };
        const closeModal = () => {
            elements.modal.classList.add('opacity-0', 'pointer-events-none');
            document.body.classList.remove('modal-active');
        };

        // Thêm event listener cho các nút đóng modal
        elements.modalCloseButtons.forEach(button => {
            button.addEventListener('click', closeModal);
        });


        const showLoading = () => elements.loadingBox.classList.remove('hidden');
        const hideLoading = () => elements.loadingBox.classList.add('hidden');

        const showToast = (message, type = 'info') => {
            Toastify({
                text: message,
                duration: 3000,
                close: true,
                gravity: "top",
                position: "center",
                backgroundColor: type === 'error' ? "#ff0000" : "#4CAF50",
            }).showToast();
        };

        // API functions
        const apiRequest = async (tableName, action, data, select = {}) => {
            try {
                const response = await axios.post(`${API_URL}/${tableName}/Action`, {
                    Action: action,
                    Properties: select,
                    ...data
                }, {
                    headers: {
                        'ApplicationAccessKey': ACCESS_KEY,
                        'Content-Type': 'application/json'
                    }
                });
                return response.data;
            } catch (error) {
                throw new Error('API request failed: ' + error.message);
            }
        };

        const checkExistingRecord = async (idChamCong) => {
            try {
                return await apiRequest('ChamCong', 'Find', {}, {
                    Selector: `Filter(ChamCong,[ID CV]="${idChamCong}")`
                });
            } catch (error) {
                console.error('Error checking existing record:', error);
                throw error;
            }
        };

        // Geolocation functions
        const getLocation = () => new Promise((resolve, reject) => {
            navigator.geolocation.getCurrentPosition(
                position => resolve(`${position.coords.latitude},${position.coords.longitude}`),
                error => {
                    console.error('Error getting location:', error);
                    reject('Không xác định được vị trí');
                },
                { timeout: 10000, maximumAge: 0 }
            );
        });

        const getAddressFromCoordinates = async (lat, lon) => {
            try {
                const response = await fetch(`https://nominatim.openstreetmap.org/reverse?format=json&lat=${lat}&lon=${lon}&accept-language=vi`);
                const data = await response.json();
                return data.display_name || 'Không thể lấy địa chỉ chính xác';
            } catch (error) {
                console.error('Error getting address:', error);
                return 'Không thể lấy địa chỉ';
            }
        };

        // Camera functions
        const startCamera = async () => {
            if (stream) {
                stream.getTracks().forEach(track => track.stop());
            }
            try {
                const constraints = {
                    video: {
                        facingMode: facingMode,
                        width: { ideal: 1280 },
                        height: { ideal: 720 }
                    }
                };
                stream = await navigator.mediaDevices.getUserMedia(constraints);
                elements.camera.srcObject = stream;
            } catch (err) {
                console.error("Không thể truy cập camera:", err);
                showToast("Không thể truy cập camera. Vui lòng kiểm tra quyền truy cập.", 'error');
            }
        };
        const switchCamera = async () => {
            facingMode = facingMode === "user" ? "environment" : "user";
            await startCamera();
        };
        const captureImage = async () => {
            const canvas = document.createElement('canvas');
            canvas.width = elements.camera.videoWidth;
            canvas.height = elements.camera.videoHeight;
            const ctx = canvas.getContext('2d');

            ctx.drawImage(elements.camera, 0, 0);

            const location = await getLocation();
            const [latitude, longitude] = location.split(',');
            const currentTime = moment().tz("Asia/Ho_Chi_Minh");
            const date = currentTime.format('YYYY-MM-DD');
            const timeStr = currentTime.format('HH:mm:ss');
            const address = await getAddressFromCoordinates(latitude, longitude);

            const overlayInfo = `
        Vị trí: ${latitude}, ${longitude}
        Địa chỉ: ${address}
        Thời gian: ${date} ${timeStr}
    `;

            ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
            ctx.fillRect(10, 10, canvas.width - 20, 100);
            ctx.fillStyle = 'white';
            ctx.font = '14px Arial';

            overlayInfo.split('\n').forEach((line, index) => {
                ctx.fillText(line.trim(), 20, 30 + (index * 20));
            });

            return new Promise((resolve) => {
                canvas.toBlob((blob) => {
                    const reader = new FileReader();
                    reader.onloadend = () => resolve(reader.result);
                    reader.readAsDataURL(blob);
                }, 'image/jpeg', 0.8);
            });
        };

        // Authentication functions
        const login = async () => {
            const username = elements.usernameInput.value;
            const password = elements.passwordInput.value;
            const rememberLogin = elements.rememberLoginCheckbox.checked;

            showLoading();

            try {
                const result = await apiRequest('DSNV', 'Find', {
                    Properties: {
                        Selector: `Filter(DSNV, and( [username] = "${username}" , [password] = "${password}"))`
                    }
                });

                if (result && Array.isArray(result) && result.length === 1) {
                    const user = result[0];
                    if (user.password === password) {
                        currentUser = user;
                        if (rememberLogin) {
                            localStorage.setItem('username', username);
                            localStorage.setItem('fullName', user['Họ và Tên']);
                            localStorage.setItem('loginToken', 'someTokenValue');
                        }
                        elements.loginForm.classList.add('hidden');
                        elements.checkInOutChoice.classList.remove('hidden');
                        showToast(`Đăng nhập thành công! Xin chào, ${user['Họ và Tên']}`);
                    } else {
                        showToast('Tên đăng nhập hoặc mật khẩu không đúng!', 'error');
                    }
                } else {
                    showToast('Tên đăng nhập hoặc mật khẩu không đúng!', 'error');
                }
            } catch (error) {
                console.error('Lỗi đăng nhập:', error);
                showToast(`Lỗi đăng nhập: ${error.message || 'Không xác định'}. Vui lòng thử lại sau.`, 'error');
            } finally {
                hideLoading();
            }
        };
        const logout = () => {
            localStorage.removeItem('username');
            localStorage.removeItem('fullName');
            localStorage.removeItem('loginToken');
            elements.checkInOutChoice.classList.add('hidden');
            elements.cameraContainer.classList.add('hidden');
            elements.loginForm.classList.remove('hidden');
            elements.usernameInput.value = '';
            elements.passwordInput.value = '';
            currentUser = null;
        };

        // Check-in/out functions
        // Cập nhật hàm handleCheckInOut
        const handleCheckInOut = async (type) => {
            showLoading();
            const fullName = currentUser['Họ và Tên'];
            const currentTime = moment().tz("Asia/Ho_Chi_Minh");
            const date = currentTime.format('DD/MM/YYYY');
            const timeStr = currentTime.format('HH:mm:ss');
            const idChamCong = `${fullName}${date}`;
            const datee = currentTime.format('YYYY-MM-DD');

            try {
                const existingRecord = await checkExistingRecord(idChamCong);
                const imageWithLocation = await captureImage();
                const location = await getLocation();

                let newData = {
                    "ID CV": idChamCong,
                    "NGÀY": datee,
                    "HỌ VÀ TÊN": fullName,
                    "GHI CHÚ": `Check ${type} qua API`
                };

                const processCheckInOut = async () => {
                    const record = existingRecord?.[0] || {};
                    const historyEntry = `${fullName} - ${date} ${timeStr} - ${location}`;

                    if (type === 'in') {
                        newData["IN"] = timeStr;
                        newData["HÌNH ẢNH IN"] = imageWithLocation;
                        newData["ĐỊA CHỈ IN"] = location;
                        newData["LỊCH SỬ IN"] = record["LỊCH SỬ IN"] ?
                            `${record["LỊCH SỬ IN"]}\n${historyEntry}` :
                            historyEntry;
                    } else {
                        newData["OUT"] = timeStr;
                        newData["HÌNH ẢNH OUT"] = imageWithLocation;
                        newData["ĐỊA CHỈ OUT"] = location;
                        newData["LỊCH SỬ OUT"] = record["LỊCH SỬ OUT"] ?
                            `${record["LỊCH SỬ OUT"]}\n${historyEntry}` :
                            historyEntry;
                    }

                    // Giữ lại dữ liệu cũ
                    if (record.IN) newData["IN"] = newData["IN"] || record.IN;
                    if (record["HÌNH ẢNH IN"]) newData["HÌNH ẢNH IN"] = newData["HÌNH ẢNH IN"] || record["HÌNH ẢNH IN"];
                    if (record["ĐỊA CHỈ IN"]) newData["ĐỊA CHỈ IN"] = newData["ĐỊA CHỈ IN"] || record["ĐỊA CHỈ IN"];
                    if (record.OUT) newData["OUT"] = newData["OUT"] || record.OUT;
                    if (record["HÌNH ẢNH OUT"]) newData["HÌNH ẢNH OUT"] = newData["HÌNH ẢNH OUT"] || record["HÌNH ẢNH OUT"];
                    if (record["ĐỊA CHỈ OUT"]) newData["ĐỊA CHỈ OUT"] = newData["ĐỊA CHỈ OUT"] || record["ĐỊA CHỈ OUT"];

                    const action = record ? 'Edit' : 'Add';
                    const response = await apiRequest('ChamCong', action, { Rows: [newData] });

                    if (response?.Rows?.[0]) {
                        showToast(`Check ${type} thành công!`);
                        return true;
                    }
                    throw new Error('Lỗi cập nhật dữ liệu');
                };

                // Kiểm tra điều kiện check-in/out
                if (type === 'in' && existingRecord?.[0]?.IN) {
                    openModal(`Đã check-in lúc ${existingRecord[0].IN}. Xác nhận check-in lại?`, processCheckInOut);
                    return;
                }

                if (type === 'out') {
                    if (!existingRecord?.[0]?.IN) {
                        showToast("Chưa check-in. Không thể check-out!", 'error');
                        return;
                    }
                    if (existingRecord[0].OUT) {
                        openModal(`Đã check-out lúc ${existingRecord[0].OUT}. Xác nhận check-out lại?`, processCheckInOut);
                        return;
                    }
                }

                await processCheckInOut();

            } catch (error) {
                console.error('Lỗi:', error);
                showToast(`Lỗi: ${error.message || 'Không xác định'}`, 'error');
            } finally {
                hideLoading();
            }
        };


        const updateButtonVisibility = (state) => {
            elements.checkInBtn.classList.toggle('hidden', state !== 'initial');
            elements.checkOutBtn.classList.toggle('hidden', state !== 'initial');
            elements.logoutBtn.classList.remove('hidden');
            elements.captureBtn.classList.toggle('hidden', state !== 'in');
            elements.captureOutBtn.classList.toggle('hidden', state !== 'out');
        };

        const checkLoginStatus = () => {
            const savedUsername = localStorage.getItem('username');
            const savedFullName = localStorage.getItem('fullName');
            const savedToken = localStorage.getItem('loginToken');
            if (savedUsername && savedFullName && savedToken) {
                elements.usernameInput.value = savedUsername;
                elements.loginForm.classList.add('hidden');
                elements.checkInOutChoice.classList.remove('hidden');
                updateButtonVisibility('initial');
                currentUser = { 'Họ và Tên': savedFullName };
                showToast(`Xin chào, ${savedFullName}!`);
            }
        };

        // Event listeners
        elements.switchCameraBtn.addEventListener('click', () => {
            facingMode = facingMode === "user" ? "environment" : "user";
            startCamera();
        });

        elements.captureBtn.addEventListener('click', () => handleCheckInOut('in'));
        elements.captureOutBtn.addEventListener('click', () => handleCheckInOut('out'));

        elements.backBtn.addEventListener('click', () => {
            elements.cameraContainer.classList.add('hidden');
            elements.checkInOutChoice.classList.remove('hidden');
            updateButtonVisibility('initial');
        });

        elements.checkInBtn.addEventListener('click', () => {
            elements.checkInOutChoice.classList.add('hidden');
            elements.cameraContainer.classList.remove('hidden');
            updateButtonVisibility('in');
        });

        elements.checkOutBtn.addEventListener('click', () => {
            elements.checkInOutChoice.classList.add('hidden');
            elements.cameraContainer.classList.remove('hidden');
            updateButtonVisibility('out');
        });

        elements.logoutBtn.addEventListener('click', logout);
        elements.loginBtn.addEventListener('click', login);

        // Initialization
        document.addEventListener('DOMContentLoaded', () => {
            checkLoginStatus();
            updateButtonVisibility('initial');
            startCamera();

        });
    </script>
</body>

</html>