// Check if running in Telegram WebApp let tg; let sb; let BOT_TOKEN = "7738670821:AAFKVB9khxP96eAqKOafBLKcxhZiz1z_X28"; if (window.Telegram && window.Telegram.WebApp) { tg = window.Telegram.WebApp; tg.expand(); const S_URL = "https://keounthkxwtcrshginfw.supabase.co"; const S_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imtlb3VudGhreHd0Y3JzaGdpbmZ3Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjYwNzM0OTcsImV4cCI6MjA4MTY0OTQ5N30.7ECXzBhUVKjlro_9InfW-bVFThPXMVpJBW_MNjjviNs"; sb = supabase.createClient(S_URL, S_KEY); tg.MainButton.text = "Bosh menyu"; tg.MainButton.show(); } else { // Fallback for non-Telegram environment console.warn("Not running in Telegram WebApp - using mock data"); tg = { initDataUnsafe: { user: { id: "DEV_TEST", first_name: "Test", last_name: "User" }}, showAlert: alert, showPopup: (opts, callback) => { alert(opts.message); if (callback) callback(0); }, MainButton: { show: () => {}, hide: () => {}, showProgress: () => {}, hideProgress: () => {}, setText: () => {} }, expand: () => {} }; // Mock Supabase client sb = { from: () => ({ select: () => Promise.resolve({ data: null, error: null }), insert: () => Promise.resolve({ error: null }), update: () => Promise.resolve({ error: null }), eq: () => ({ single: () => Promise.resolve({ data: null, error: null }) }) }) }; } let user = tg.initDataUnsafe?.user || { id: "DEV_TEST", first_name: "Test", last_name: "User", username: "testuser" }; let currentUser = null; let currentView = null; // Telegram Bot Command Handlers function setupBotCommands() { tg.onEvent('mainButtonClicked', () => { showView('main'); }); if (tg.initDataUnsafe?.start_param) { const param = tg.initDataUnsafe.start_param; if (param.startsWith('test_')) { const testCode = param.replace('test_', ''); document.querySelector('custom-test-solver').shadowRoot.getElementById('solve-code').value = testCode; showView('student'); } } } function showView(view) { currentView = view; document.getElementById('main-content').classList.remove('hidden'); document.getElementById('auth-section').classList.add('hidden'); document.getElementById('teacher-view').classList.add('hidden'); document.getElementById('student-view').classList.add('hidden'); document.getElementById('result-view').classList.add('hidden'); document.getElementById('history-view').classList.add('hidden'); if (view === 'teacher') { document.getElementById('teacher-view').classList.remove('hidden'); tg.MainButton.setText("Test yaratish"); } else if (view === 'student') { document.getElementById('student-view').classList.remove('hidden'); tg.MainButton.setText("Test topshirish"); } else if (view === 'result') { document.getElementById('result-view').classList.remove('hidden'); tg.MainButton.setText("Yangi test"); } else if (view === 'history') { document.getElementById('history-view').classList.remove('hidden'); tg.MainButton.setText("Orqaga"); } else { if (currentUser.role === 'teacher') { showView('teacher'); } else { showView('student'); } } } async function init() { try { const { data, error } = await sb.from('profiles').select('*').eq('tg_id', user.id.toString()).single(); if (data) { currentUser = data; setupBotCommands(); handleDeepLink(); // Handle deep linking after user is authenticated showView('main'); } else { document.getElementById('auth-section').classList.remove('hidden'); } } catch (e) { console.error("Init error:", e); // Fallback to auth section if error occurs document.getElementById('auth-section').classList.remove('hidden'); } } // Add this function to handle deep linking function handleDeepLink() { if (tg.initDataUnsafe?.start_param) { const param = tg.initDataUnsafe.start_param; if (param.startsWith('test_')) { const testCode = param.replace('test_', ''); // Set the test code in the solver component setTimeout(() => { const solverComponent = document.querySelector('custom-test-solver'); if (solverComponent) { const codeInput = solverComponent.shadowRoot.getElementById('solve-code'); if (codeInput) { codeInput.value = testCode; } } }, 500); showView('student'); } } } async function register(name, role) { if (!name || name.trim().length < 3) { tg.showAlert("Iltimos, ismingizni to'liq kiriting!"); return; } const cleanName = name.trim(); tg.MainButton.showProgress(); try { const { error } = await sb.from('profiles').insert([{ tg_id: user.id.toString(), full_name: cleanName, role: role, username: user.username || '', language_code: user.language_code || 'uz' }]); if (!error) { tg.showPopup({ title: "Muvaffaqiyatli!", message: "Profil muvaffaqiyatli yaratildi!", buttons: [{ type: 'ok' }] }, () => { currentUser = { tg_id: user.id.toString(), full_name: cleanName, role: role, username: user.username || '', language_code: user.language_code || 'uz' }; handleDeepLink(); // Handle deep linking after registration showView('main'); }); } else { throw new Error(error.message); } } catch (err) { tg.showAlert("Xatolik yuz berdi: " + err.message); } finally { tg.MainButton.hideProgress(); } } async function toggleRole() { tg.MainButton.showProgress(); try { const newRole = currentUser.role === 'teacher' ? 'student' : 'teacher'; const { error } = await sb.from('profiles').update({ role: newRole }).eq('tg_id', currentUser.tg_id); if (!error) { currentUser.role = newRole; showView('main'); } else { throw new Error(error.message); } } catch (err) { tg.showAlert("Rolni almashtirishda xatolik yuz berdi: " + err.message); } finally { tg.MainButton.hideProgress(); } } // Enhanced sendBotMsg with retry logic async function sendBotMsg(chatId, text) { if (!BOT_TOKEN) return; const maxRetries = 3; for (let i = 0; i < maxRetries; i++) { try { const response = await fetch(`https://api.telegram.org/bot${BOT_TOKEN}/sendMessage`, { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ chat_id: chatId, text: text, parse_mode: 'HTML' }) }); const data = await response.json(); if (data.ok) { return data; } else { console.error("Telegram API error:", data); if (i === maxRetries - 1) throw new Error(data.description); } } catch (e) { console.error(`Attempt ${i+1} failed to send message:`, e); if (i === maxRetries - 1) { console.error("All attempts failed to send message:", e); } // Wait before retrying await new Promise(resolve => setTimeout(resolve, 1000 * (i+1))); } } } // Enhanced getBotInfo with error handling async function getBotInfo() { if (!BOT_TOKEN) return { username: 'test_bot' }; try { const response = await fetch(`https://api.telegram.org/bot${BOT_TOKEN}/getMe`); const data = await response.json(); if (data.ok) { return data.result; } else { throw new Error(data.description); } } catch (e) { console.error("Failed to get bot info:", e); return { username: 'test_bot' }; } } init();