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

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://telegram.org/js/telegram-web-app.js"></script>
    <title>Xác thực Tài khoản</title>
    <style>
        body {
            --bg-color: #fff !important;
            --text-color: #05596f !important;
            --hint-color: #999 !important;
            --secondary-bg-color: #f5f5f5 !important;
            --button-color: #D70018 !important;
            --button-text-color: #ffffff !important;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
            background-color: var(--bg-color);
            color: var(--text-color);
            margin: 0;
            padding: 0;
            line-height: 1.5;
            padding-bottom: 60px;
            /*background: url(https://cdn2.cellphones.com.vn/x/media/wysiwyg/BGNoel-1920x1080.jpg);*/
            background: url(https://cdn2.cellphones.com.vn/x/media/wysiwyg/BGNoel-1920x1080.jpg) left top / 105% no-repeat fixed;
        }

        .profile-header {
            padding: 20px;
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .avatar-container {
            position: relative;
            width: 80px;
            height: 80px;
        }

        .avatar {
            width: 100%;
            height: 100%;
            border-radius: 50%;
            object-fit: cover;
            border: 2px solid #D70018;
            background-color: var(--secondary-bg-color);
        }

        .avatar-placeholder {
            width: 100%;
            height: 100%;
            border-radius: 50%;
            background-color: var(--button-color);
            color: var(--button-text-color);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 32px;
            font-weight: 500;
        }

        .profile-info {
            flex: 1;
        }

        .logo-image {
        }

        .full-name {
            font-size: 22px;
            font-weight: 500;
            margin: 0;
            color: var(--text-color);
        }

        .username {
            color: #D70018;
            font-size: 16px;
            margin: 4px 0;
        }

        .user-id {
            color: var(--hint-color);
            font-size: 14px;
            display: none;
        }

        .info-section {
            padding: 10px;
        }

        .info-item {
            border-radius: 10px;
            padding: 16px;
            margin-bottom: 7px;
            position: relative;
        }

        .info-label {
            color: #05596f !important;
            font-size: 16px;
            margin-bottom: 8px;
            font-weight: 500;
        }

        .info-value {
            color: var(--text-color);
            font-size: 16px;
            margin-bottom: 12px;
        }

        .info-input {
            width: 100%;
            padding: 10px;
            border: 1px solid var(--hint-color);
            border-radius: 8px;
            background-color: var(--bg-color);
            color: var(--text-color);
            font-size: 16px;
            box-sizing: border-box;
            outline: none;
        }

            .info-input:focus {
                border-color: #D70018;
            }

        button {
            width: 100%;
            padding: 12px 20px;
            background-color: var(--button-color);
            color: var(--button-text-color);
            border: none;
            border-radius: 8px;
            font-size: 16px;
            cursor: pointer;
            transition: opacity 0.2s;
            font-weight: 500;
        }

            button:hover {
                opacity: 0.9;
            }

            button:active {
                opacity: 0.8;
            }

        .status {
            margin-top: 8px;
            font-size: 14px;
            padding: 8px 0;
        }

        .ok {
            color: #34c759;
        }

        .err {
            color: #ff3b30;
        }


        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.8) !important;
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }

        .spinner {
            width: 50px;
            height: 50px;
            border: 5px solid #dff8ff;
            border-top: 5px solid #12576d;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

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

            100% {
                transform: rotate(360deg);
            }
        }

        .status-badge {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 500;
        }

        .status-verified {
            /*background-color: rgb(56 162 108 / 10%);
            color: #34bf05;*/
            border: 1px solid #77d45166 !important;
            background-color: rgb(251 251 251 / 60%);
            color: #16a139;
        }

        .status-not-verified,
        .status-notfound,
        .status-mismatch {
            background-color: #f5f5f5b5 !important;
            border: 1px solid #9bafbc66 !important;
            color: #34596f !important;
        }

        .status-pending {
            background-color: rgba(215, 0, 24, 0.05);
            color: #D70018;
            border: 1px solid #D70018;
        }

        .notice-section {
            padding: 10px 16px;
        }

        .notice-content {
            color: var(--text-color);
            font-size: 14px;
            line-height: 1.5;
        }

        .notice-list {
            padding-left: 20px;
            margin: 8px 0;
        }

            .notice-list li {
                margin-bottom: 6px;
            }

        .notice-warning {
            background-color: #e8d9a50a;
            border: 1px solid #f0cc79;
            color: #D70018;
            padding: 12px;
            border-radius: 8px;
            margin: 10px 0;
            font-size: 14px;
        }

        .deadline {
            color: #D70018;
            font-weight: 500;
        }

        .status {
            margin-top: 8px;
            font-size: 14px;
            padding: 8px 0;
            display: flex;
            align-items: center;
            gap: 6px;
        }

            .status svg {
                width: 16px;
                height: 16px;
            }

            .status.ok {
                color: #34c759;
            }

            .status.err {
                color: #ff3b30;
            }

        /* Style for user phone number */
        #userPhone {
            font-size: 16px;
            font-weight: 500;
            padding: 10px 12px;
            border-radius: 6px;
            margin-bottom: 0px;
            background-color: #fff !important;
            border: 1px solid rgba(215, 0, 24, 0.2) !important;
            color: #12576d !important;
            border-color: #1a86c1 !important;
        }


        /* Style for HRW code input */
     
        #hrwCode {
            font-size: 16px;
            font-weight: 500;
            padding: 12px;
            border-color: #1a86c1 !important;
            background-color: #fff !important;
            border-radius: 8px;
            width: 100%;
            color: #12576d !important;
            box-sizing: border-box;
            transition: all 0.2s ease;
        }

            #hrwCode:focus {
                box-shadow: 0 0 0 1px rgb(119 176 195);
            }

            #hrwCode:disabled {
                opacity: 0.8;
                cursor: not-allowed;
            }

            #hrwCode::placeholder {
                color: var(--hint-color);
                opacity: 0.8;
            }

        /* Light theme enforcement overrides */
        :root {
            color-scheme: light !important;
        }

        /* Force light theme for any dark mode overrides */
        @media (prefers-color-scheme: dark) {
            body {
                --bg-color: #fff !important;
                --text-color: #05596f !important;
                --hint-color: #999 !important;
                --secondary-bg-color: #f5f5f5 !important;
                background-color: #fff !important;
                color: #222 !important;
            }
        }

        /* Form input area light theme */
        .info-item {
            border: 1px solid rgb(18 140 195 / 36%) !important;
        }


        /* Force all text to proper light theme colors */
        * {
            color-scheme: light !important;
        }


        canvas#canvas {
            position: absolute;
            left: 0;
            top: 0;
            z-index: 99;
            pointer-events: none;
            width: 100%;
        }
    </style>
</head>

<body>

    <div class="loading-overlay">
        <div class="spinner"></div>
    </div>

    <div class="profile-header">
        <div class="avatar-container" id="avatarContainer">
            <img id="userPhoto" width="80" height="80" class="avatar" alt="Profile Photo" src="https://dev.api.cps.onl/stg/telegram/photo/975998919.jpg">
        </div>
        <div class="profile-info">
            <h1 class="full-name" id="userName">Tuyn Doan</h1>
            <div class="username" id="userUsername">@tuyndv</div>
            <div class="user-id" id="userId"></div>
        </div>
        <!--<div class="profile-logo">
          <img src="https://cares.vn/wp-content/uploads/2023/10/cps.png" alt="CellphoneS" class="logo-image">
        </div>-->
    </div>

    <div class="info-section">
        <div class="info-item">
            <div class="info-label">Mã nhân viên</div>

            <input type="text" class="info-input" id="hrwCode" placeholder="Nhập Mã nhân viên" inputmode="text"
                   onblur="handleInputBlur(this)" autocomplete="off">
        </div>

        <div class="info-item">
            <div class="info-label">Số điện thoại</div>
            <div id="userPhone" class="info-value not-shared" onclick="requestPhoneNumber(this)">Nhấn để Chia sẻ</div>
        </div>

        <div class="info-item">
            <div class="info-label">Trạng thái</div>
            <div id="accountStatus" class="status-badge"></div>
        </div>
    </div>

    <div class="notice-section">
        <div class="notice-content">
            <strong>Lưu ý quan trọng:</strong>
            <ul class="notice-list">
                <li>Vui lòng sử dụng số điện thoại đã đăng ký trên HRWs</li>
                <li>Xác thực phải được hoàn tất <span class="deadline">trước ngày 17/11/2024</span></li>
            </ul>
            <div class="notice-warning">
                Tài khoản chưa xác thực sẽ bị xóa khỏi các nhóm của Công ty sau thời hạn trên
            </div>
        </div>
    </div>

    <script>
        const webapp = window.Telegram.WebApp;
        let userPhoneNumber = null;
        let userStatus = null;

        function showLoading() {
            document.querySelector('.loading-overlay').style.display = 'flex';
        }

        function hideLoading() {
            document.querySelector('.loading-overlay').style.display = 'none';
        }
        
        
        function showAlert(message, title = 'Thông báo') {
                webapp.showPopup({
                    title: title,
                    message: message,
                    buttons: [
                        {text: 'OK', type: 'ok'}
                    ]
                });
        }
        

        function handleInputBlur(input) {
            // Đóng bàn phím của Telegram
            if (window.Telegram && window.Telegram.WebApp) {
                window.Telegram.WebApp.closeScanQrPopup();
                window.Telegram.WebApp.closeKeyboard();
            }

            // Bỏ focus khỏi input
            input.blur();
        }

        document.addEventListener('click', function (event) {
            const input = document.getElementById('hrwCode');
            if (event.target !== input) {
                handleInputBlur(input);
            }
        });

        function createAvatarPlaceholder(name) {
            const container = document.getElementById('avatarContainer');
            const initials = name.split(' ')
                .map(word => word.charAt(0))
                .join('')
                .toUpperCase()
                .slice(0, 2);

            // Remove existing content
            container.innerHTML = '';

            const placeholder = document.createElement('div');
            placeholder.className = 'avatar-placeholder';
            placeholder.textContent = initials;
            container.appendChild(placeholder);
        }

        function setUserPhoto(photoUrl, userName) {
            if (!photoUrl) {
                createAvatarPlaceholder(userName);
                return;
            }

            const container = document.getElementById('avatarContainer');

            // Clear container
            container.innerHTML = '';

            // Create new image element
            const img = document.createElement('img');
            img.id = 'userPhoto';
            img.className = 'avatar';
            img.alt = 'Profile Photo';
            img.src = photoUrl;

            img.onerror = () => {
                console.log('Error loading photo, using placeholder');
                createAvatarPlaceholder(userName);
            };

            container.appendChild(img);
        }

        async function loadUserData() {
            showLoading();
            try {
                const response = await fetch(`https://dev.api.cps.onl/stg/telegram/users/${webapp.initDataUnsafe.user.id}`);
                const data = await response.json();
                const phoneDisplay = document.getElementById('userPhone');
                const hrwCode = document.getElementById('hrwCode');
                if (data.success && data.data) {
                    const userData = data.data;
                    const avatarUrl = `https://dev.api.cps.onl/stg/telegram/photo/${userData.userId}.jpg`;
                    setUserPhoto(avatarUrl, document.getElementById('userUsername').textContent);
                    phoneDisplay.textContent = userData.phoneNumber;
                    hrwCode.value = userData.userCode;
                    hrwCode.setAttribute('disabled', true);

                    // Update status
                    updateAccountStatus(userData.status);

                    // Hide main button if already verified
                    if (userData.status === 'Verified') {
                        webapp.MainButton.hide();
                    }
                }
                else {
                    updateAccountStatus("not-verified");
                }
            } catch (error) {
                console.error('Error loading user data:', error);
                showAlert('Không thể tải thông tin người dùng. Vui lòng thử lại sau.', 'Thông báo');
            } finally {
                hideLoading();
            }
        }

        function updateAccountStatus(status) {
            userStatus = status;
            const statusElement = document.getElementById('accountStatus');
            statusElement.textContent = status === 'Verified' ? 'Đã xác thực' :
                status === 'Pending' ? 'Đang chờ xác thực' : 'Chưa xác thực';
            statusElement.className = `status-badge status-${status.toLowerCase()}`;

            if (status === 'Verified') {
                document.getElementById('hrwCode').setAttribute('disabled', true);
                webapp.MainButton.hide();
            }
            else
            {
                webapp.MainButton.setParams({
                    text: 'Xác thực',
                    color: '#D70018',  // CellphoneS Red #D70018 #Xanh #12576d
                    textColor: '#FFFFFF'
                }).show();
            }

        }

        function formatPhoneNumber(phoneNumber) {
            // Kiểm tra nếu số bắt đầu bằng 84
            if (phoneNumber.startsWith('84')) {
                return '0' + phoneNumber.slice(2); // Cắt bỏ 84 và thêm số 0
            }

            // Kiểm tra nếu số bắt đầu bằng +84
            if (phoneNumber.startsWith('+84')) {
                return '0' + phoneNumber.slice(3); // Cắt bỏ +84 và thêm số 0
            }

            // Trường hợp còn lại giữ nguyên số
            return phoneNumber;
        }

        function requestPhoneNumber(el) {
            
            const phoneDisplay = document.getElementById('userPhone');
            const phoneStatus = document.getElementById('phoneStatus');
            
            if(phoneDisplay.textContent!=="Nhấn để Chia sẻ" && phoneDisplay.textContent!=="Chưa được Chia sẻ")
            {
                return;
            }
            
            Telegram.WebApp.requestContact(function (sent, event) {
                if (sent) {
                    const phoneNumber = event && event.responseUnsafe &&
                        event.responseUnsafe.contact &&
                        event.responseUnsafe.contact.phone_number;

                    if (phoneNumber) {
                        userPhoneNumber = formatPhoneNumber(event.responseUnsafe.contact.phone_number);
                        phoneDisplay.textContent = userPhoneNumber;
                        phoneDisplay.classList.remove('not-shared');
                        webapp.MainButton.show();
                    }
                } else {
                    phoneDisplay.textContent = 'Chưa được Chia sẻ';
                    phoneDisplay.classList.add('not-shared');
                    userPhoneNumber = null;
                }
            });
        }

        function validateAccountInfo() {
            const hrwCode = document.getElementById('hrwCode').value.trim();
            const phoneDisplay = document.getElementById('userPhone');

            const messages = [];

            if (!hrwCode) {
                messages.push("Vui lòng nhập Mã nhân viên");
            }

            if (phoneDisplay.textContent == "Chưa được Chia sẻ" ||
            phoneDisplay.textContent=="Nhấn để Chia sẻ") {
                messages.push("Vui lòng chia sẻ Số điện thoại");
            }

            return messages;
        }

        function createFlatTelegramData(webapp, userCode, userPhoneNumber) {
            const user = webapp.initDataUnsafe.user;

            return {
                app_version: webapp.version,
                platform: webapp.platform,
                user_id: webapp.initDataUnsafe.user.id,
                user_code: userCode.trim(),
                phone_number: userPhoneNumber,
                first_name: webapp.initDataUnsafe.user.first_name,
                last_name: webapp.initDataUnsafe.user.last_name || '',
                username: webapp.initDataUnsafe.user.username || '',
                language_code: webapp.initDataUnsafe.user.language_code,
                allows_write_to_pm: webapp.initDataUnsafe.user.allows_write_to_pm,
                chat_instance: webapp.initDataUnsafe.chat_instance,
                chat_type: webapp.initDataUnsafe.chat_type,
                auth_date: webapp.initDataUnsafe.auth_date,
                // Use the raw initData string from Telegram
                hash: webapp.initData


            };
        }

        function verifyAccount() {
            const validationMessages = validateAccountInfo();

            if (validationMessages.length > 0) {
                showAlert(validationMessages.join("\n"), 'Thiếu thông tin');
                return;
            }

            showLoading();
            const verificationData = createFlatTelegramData(
                webapp,
                document.getElementById('hrwCode').value,
                userPhoneNumber
            );

            fetch('https://dev.api.cps.onl/stg/telegram/verify', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(verificationData)
            })
                .then(response => response.json())
                .then(data => {
                    if (!data.success) {
                        showAlert(`${data.message}`, 'Thông báo');
                        return;
                    }
                    updateAccountStatus(data.status);
                    showAlert(`${data.message}`, 'Thông báo');
                })
                .catch(error => {
                    showAlert('Có lỗi, vui lòng thử lại sau.', 'Thông báo');
                })
                .finally(() => {
                    hideLoading();
                });
        }

        // Force light theme for header
        const setLightTheme = () => {
            try {
                // Set white background for header
                webapp.headerColor = '#ffffff';
                webapp.backgroundColor = '#ffffff';
                webapp.bottomBarColor = "#ffffff";

                // Ensure it gets applied
                webapp.expand();
                webapp.enableClosingConfirmation();
                webapp.ready();
            } catch (e) {
                console.log('Error setting theme:', e);
            }
        };

        // Apply immediately and on theme change
        setLightTheme();
        webapp.onEvent('themeChanged', setLightTheme);
        webapp.onEvent('viewportChanged', setLightTheme);

        // Set up user info
        const initData = webapp.initDataUnsafe;
        if (initData.user) {
            const user = initData.user;

            // Set name
            const fullName = `${user.first_name} ${user.last_name || ''}`.trim();
            document.getElementById('userName').textContent = fullName;

            // Set username
            if (user.username) {
                document.getElementById('userUsername').textContent = `@${user.username}`;
            } else {
                document.getElementById('userUsername').style.display = 'none';
            }

            // Set user ID
            document.getElementById('userId').textContent = `ID: ${user.id}`;

            // Set photo
            setUserPhoto(user.photo_url, fullName);
        }

        loadUserData();

        // Set up Main/Back Button

        webapp.BackButton.hide()

        webapp.MainButton.setText('Xác thực').onClick(verifyAccount);


        document.addEventListener("DOMContentLoaded", function () {
            setTimeout(function () {
                var canv = `<canvas id="canvas"></canvas>`;
                document.body.insertAdjacentHTML("beforeend", canv);
                var body = document.body,
                    htmlElement = document.documentElement;
                var height = body.offsetHeight;
                document.querySelector("#canvas").style.height = height + "px"
                function startAnimation() {
                    const CANVAS_WIDTH = window.innerWidth;
                    const CANVAS_HEIGHT = height;
                    const MIN = 0;
                    const MAX = CANVAS_WIDTH;
                    const canvas = document.querySelector("#canvas");
                    const ctx = canvas.getContext("2d");
                    canvas.width = CANVAS_WIDTH;
                    canvas.height = CANVAS_HEIGHT;
                    function clamp(number, min = MIN, max = MAX) {
                        return Math.max(min, Math.min(number, max));
                    }
                    function random(factor = 1) {
                        return Math.random() * factor;
                    }
                    function degreeToRadian(deg) {
                        return deg * (Math.PI / 180);
                    }
                    class Circle {
                        radius = 0;
                        x = 0;
                        y = 0;
                        vx = 0;
                        vy = 0;
                        constructor(ctx) {
                            this.ctx = ctx;
                            this.reset();
                        }
                        draw() {
                            this.ctx.beginPath();
                            this.ctx.fillStyle = "rgba(255,255,255,0.8)";
                            this.ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
                            this.ctx.fill();
                            this.ctx.closePath();
                        }
                        reset() {
                            this.radius = random(2.5);
                            this.x = random(CANVAS_WIDTH);
                            this.y = this.y ? 0 : random(CANVAS_HEIGHT);
                            this.vx = clamp((Math.random() - 0.5) * 0.4, -0.4, 0.4);
                            this.vy = clamp(random(1.5), 0.1, 0.8) * this.radius * 0.5;
                        }
                    }
                    let circles = [];
                    for (let i = 0; i < 300; i++) {
                        circles.push(new Circle(ctx));
                    }
                    function clearCanvas() {
                        ctx.clearRect(0, 0, canvas.width, canvas.height);
                    }
                    let canvasOffset = {
                        x0: ctx.canvas.offsetLeft,
                        y0: ctx.canvas.offsetTop,
                        x1: ctx.canvas.offsetLeft + ctx.canvas.width,
                        y1: ctx.canvas.offsetTop + ctx.canvas.height
                    };
                    function animate() {
                        clearCanvas();
                        circles.forEach((e) => {
                            if (
                                e.x <= canvasOffset.x0 ||
                                e.x >= canvasOffset.x1 ||
                                e.y <= canvasOffset.y0 ||
                                e.y >= canvasOffset.y1
                            ) {
                                e.reset();
                            }
                            e.x = e.x + e.vx;
                            e.y = e.y + e.vy;
                            e.draw();
                        });
                        requestAnimationFrame(animate);
                    }
                    animate();
                }
                startAnimation();
                window.addEventListener("resize", startAnimation);
            }, 500);
        });
    </script>
</body>

</html>