AI 숙제 해결사

전체 SVG 아이콘, 로딩 화면, 핑 검사기, IP 검사기, 상태 모니터

// ==UserScript==
// @name              AI Homework Solver
// @name:vi           Trình Giải Bài Tập Về Nhà Bằng AI
// @name:es           Solucionador de Tareas con IA v
// @name:zh-CN        AI 作业解答器
// @name:ja           AI宿題ソルバー
// @name:ko           AI 숙제 해결사
// @name:de           KI-Hausaufgabenlöser
// @name:fr           Solveur de Devoirs IA
// @name:ru           Решатель домашних заданий с ИИ
// @name:pt-BR           Solucionador de Dever de Casa com IA
// @name:ar           حل الواجبات المدرسية بالذكاء الاصطناعي
// @name:hi           एआई होमवर्क सॉल्वर
// @namespace         http://tampermonkey.net/
// @version           1.0.1
// @description       Full SVG Icons, Loading Screen, Ping Checker, IP Checker, Status Monitor
// @description:vi    Biểu tượng SVG đầy đủ, Màn hình tải, Kiểm tra Ping, Kiểm tra IP, Giám sát trạng thái
// @description:es    Iconos SVG completos, Pantalla de carga, Comprobador de ping, Comprobador de IP, Monitor de estado
// @description:zh-CN 完整的 SVG 图标、加载屏幕、Ping 检查器、IP 检查器、状态监视器
// @description:ja    完全なSVGアイコン、読み込み画面、Pingチェッカー、IPチェッカー、ステータスモニター
// @description:ko    전체 SVG 아이콘, 로딩 화면, 핑 검사기, IP 검사기, 상태 모니터
// @description:de    Vollständige SVG-Symbole, Ladebildschirm, Ping-Prüfer, IP-Prüfer, Statusmonitor
// @description:fr    Icônes SVG complètes, Écran de chargement, Vérificateur de ping, Vérificateur d'IP, Moniteur de statut
// @description:ru    Полные SVG-иконки, Экран загрузки, Проверка пинга, Проверка IP, Монитор состояния
// @description:pt-BR Ícones SVG completos, Tela de carregamento, Verificador de ping, Verificador de IP, Monitor de status
// @description:ar    أيقونات SVG كاملة، شاشة تحميل، مدقق اختبار الاتصال، مدقق IP، مراقب الحالة
// @description:hi    पूर्ण एसवीजी आइकन, लोडिंग स्क्रीन, पिंग चेकर, आईपी चेcker, स्थिति मॉनिटर
// @author            Enhanced Version
// @match             *://*/*
// @grant             GM_xmlhttpRequest
// @grant             GM_getValue
// @grant             GM_setValue
// @grant             GM_addStyle
// @require           https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js
// @connect           generativelanguage.googleapis.com
// @connect           api.ipify.org
// @connect           cloudflare.com
// @license           MIT
// @homepageURL       https://twisk.fun/
// ==/UserScript==

(function() {
    'use strict';

    GM_addStyle(`
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');

        @keyframes slideInRight {
            from { opacity: 0; transform: translateX(100%); }
            to { opacity: 1; transform: translateX(0); }
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        @keyframes fadeOut {
            from { opacity: 1; }
            to { opacity: 0; }
        }

        @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }

        @keyframes shimmer {
            0% { background-position: -1000px 0; }
            100% { background-position: 1000px 0; }
        }

        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }

        @keyframes progressBar {
            0% { width: 0%; }
            100% { width: 100%; }
        }

        #aiSolverLoadingScreen {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            z-index: 9999999;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            font-family: 'Inter', sans-serif;
            color: white;
        }

        #aiSolverLoadingScreen.hidden {
            animation: fadeOut 0.5s forwards;
            pointer-events: none;
        }

        .loading-logo {
            width: 80px;
            height: 80px;
            margin-bottom: 30px;
            animation: spin 2s linear infinite;
        }

        .loading-title {
            font-size: 32px;
            font-weight: 700;
            margin-bottom: 10px;
            letter-spacing: -0.5px;
        }

        .loading-subtitle {
            font-size: 16px;
            opacity: 0.9;
            margin-bottom: 40px;
        }

        .loading-progress-container {
            width: 300px;
            height: 6px;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 3px;
            overflow: hidden;
            margin-bottom: 20px;
        }

        .loading-progress-bar {
            height: 100%;
            background: white;
            border-radius: 3px;
            animation: progressBar 2s ease-out forwards;
        }

        .loading-status {
            font-size: 14px;
            opacity: 0.8;
            text-align: center;
        }

        .loading-dots::after {
            content: '';
            animation: dots 1.5s steps(4, end) infinite;
        }

        @keyframes dots {
            0%, 20% { content: '.'; }
            40% { content: '..'; }
            60%, 100% { content: '...'; }
        }

        #aiSolverPanel {
            position: fixed;
            top: 0;
            right: -500px;
            width: 480px;
            height: 100vh;
            background: #ffffff;
            box-shadow: -4px 0 24px rgba(0, 0, 0, 0.12);
            z-index: 999999;
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            color: #1a1a1a;
            display: flex;
            flex-direction: column;
            transition: right 0.4s cubic-bezier(0.4, 0, 0.2, 1);
        }

        #aiSolverPanel.show {
            right: 0;
        }

        #aiSolverToggle {
            position: fixed;
            top: 50%;
            right: 20px;
            transform: translateY(-50%);
            width: 56px;
            height: 56px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            border-radius: 50%;
            box-shadow: 0 4px 16px rgba(102, 126, 234, 0.4);
            cursor: pointer;
            z-index: 999998;
            display: none;
            align-items: center;
            justify-content: center;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }

        #aiSolverToggle.ready {
            display: flex;
            animation: fadeIn 0.5s forwards;
        }

        #aiSolverToggle:hover {
            transform: translateY(-50%) scale(1.1);
            box-shadow: 0 6px 24px rgba(102, 126, 234, 0.5);
        }

        #aiSolverToggle.active {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        }

        #aiSolverToggle svg {
            width: 28px;
            height: 28px;
            fill: white;
        }

        .panel-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 20px 24px;
            color: white;
            flex-shrink: 0;
            position: relative;
        }

        .panel-header h1 {
            margin: 0 0 8px 0;
            font-size: 24px;
            font-weight: 700;
            letter-spacing: -0.5px;
        }

        .panel-header .subtitle {
            font-size: 13px;
            opacity: 0.9;
            font-weight: 500;
        }

        .close-panel-btn {
            position: absolute;
            top: 20px;
            right: 20px;
            background: rgba(255, 255, 255, 0.2);
            border: none;
            width: 32px;
            height: 32px;
            border-radius: 8px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s;
        }

        .close-panel-btn:hover {
            background: rgba(255, 255, 255, 0.3);
            transform: scale(1.1);
        }

        .close-panel-btn svg {
            width: 18px;
            height: 18px;
            stroke: white;
            stroke-width: 2.5;
        }

        .discord-banner {
            background: linear-gradient(135deg, #5865F2 0%, #7289DA 100%);
            padding: 16px 24px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex-shrink: 0;
            border-bottom: 2px solid rgba(0, 0, 0, 0.05);
        }

        .discord-info {
            display: flex;
            align-items: center;
            gap: 12px;
            color: white;
        }

        .discord-icon {
            width: 32px;
            height: 32px;
            fill: white;
        }

        .discord-text h3 {
            margin: 0;
            font-size: 14px;
            font-weight: 600;
        }

        .discord-text p {
            margin: 2px 0 0 0;
            font-size: 12px;
            opacity: 0.9;
        }

        .discord-join-btn {
            background: white;
            color: #5865F2;
            border: none;
            padding: 10px 20px;
            border-radius: 8px;
            font-weight: 600;
            font-size: 13px;
            cursor: pointer;
            transition: all 0.2s;
            text-decoration: none;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .discord-join-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
        }

        .stats-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 16px 24px;
            background: #f8f9fa;
            border-bottom: 1px solid #e9ecef;
            flex-shrink: 0;
            gap: 12px;
        }

        .stat-item {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 13px;
            color: #495057;
            font-weight: 500;
        }

        .stat-item svg {
            width: 16px;
            height: 16px;
        }

        .stat-badge {
            background: #667eea;
            color: white;
            padding: 4px 10px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 600;
        }

        .stat-badge.success {
            background: #38ef7d;
        }

        .stat-badge.warning {
            background: #ff6b6b;
        }

        .stat-badge.info {
            background: #4ecdc4;
        }

        .network-status {
            display: flex;
            gap: 12px;
            padding: 12px 24px;
            background: white;
            border-bottom: 1px solid #e9ecef;
            flex-wrap: wrap;
        }

        .network-item {
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 12px;
            color: #495057;
            background: #f8f9fa;
            padding: 6px 12px;
            border-radius: 8px;
        }

        .network-item svg {
            width: 14px;
            height: 14px;
        }

        .network-item.good {
            background: #d4edda;
            color: #155724;
        }

        .network-item.medium {
            background: #fff3cd;
            color: #856404;
        }

        .network-item.bad {
            background: #f8d7da;
            color: #721c24;
        }

        .panel-content {
            flex: 1;
            overflow-y: auto;
            padding: 24px;
        }

        .form-section {
            margin-bottom: 24px;
        }

        .form-label {
            display: block;
            font-size: 13px;
            font-weight: 600;
            color: #212529;
            margin-bottom: 8px;
            letter-spacing: 0.2px;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .form-label svg {
            width: 16px;
            height: 16px;
        }

        .form-input,
        .form-select,
        .form-textarea {
            width: 100%;
            padding: 12px 16px;
            background: #ffffff;
            border: 2px solid #e9ecef;
            border-radius: 12px;
            color: #212529;
            font-size: 14px;
            font-family: inherit;
            box-sizing: border-box;
            transition: all 0.2s;
        }

        .form-input:focus,
        .form-select:focus,
        .form-textarea:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
        }

        .form-textarea {
            resize: vertical;
            min-height: 100px;
            font-family: 'Inter', sans-serif;
        }

        .button-group {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
        }

        .btn {
            flex: 1;
            min-width: 120px;
            padding: 14px 20px;
            border: none;
            border-radius: 12px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            letter-spacing: 0.3px;
        }

        .btn svg {
            width: 18px;
            height: 18px;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 16px rgba(102, 126, 234, 0.4);
        }

        .btn-secondary {
            background: #f8f9fa;
            color: #495057;
            border: 2px solid #e9ecef;
        }

        .btn-secondary:hover {
            background: #e9ecef;
            border-color: #dee2e6;
        }

        .btn-success {
            background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
            color: white;
            box-shadow: 0 4px 12px rgba(17, 153, 142, 0.3);
        }

        .btn-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 16px rgba(17, 153, 142, 0.4);
        }

        .btn-danger {
            background: linear-gradient(135deg, #ff6b6b 0%, #ee5a6f 100%);
            color: white;
            box-shadow: 0 4px 12px rgba(255, 107, 107, 0.3);
        }

        .btn-danger:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 16px rgba(255, 107, 107, 0.4);
        }

        .btn:active {
            transform: translateY(0);
        }

        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none !important;
        }

        .result-container {
            background: #f8f9fa;
            border: 2px solid #e9ecef;
            border-radius: 12px;
            padding: 20px;
            min-height: 200px;
            max-height: 400px;
            overflow-y: auto;
            font-size: 14px;
            line-height: 1.7;
            white-space: pre-wrap;
            word-wrap: break-word;
        }

        .result-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;
        }

        .mode-toggle {
            display: flex;
            gap: 8px;
            padding: 4px;
            background: #f8f9fa;
            border-radius: 12px;
            border: 2px solid #e9ecef;
        }

        .mode-btn {
            flex: 1;
            padding: 10px 20px;
            background: transparent;
            border: none;
            border-radius: 8px;
            font-size: 13px;
            font-weight: 600;
            color: #6c757d;
            cursor: pointer;
            transition: all 0.2s;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
        }

        .mode-btn svg {
            width: 16px;
            height: 16px;
        }

        .mode-btn.active {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
        }

        .info-card {
            background: linear-gradient(135deg, #e0c3fc 0%, #8ec5fc 100%);
            padding: 16px;
            border-radius: 12px;
            margin-bottom: 24px;
            font-size: 13px;
            color: #1a1a1a;
            line-height: 1.6;
        }

        .info-card strong {
            display: block;
            margin-bottom: 8px;
            font-size: 14px;
        }

        .feature-card {
            background: white;
            border: 2px solid #e9ecef;
            border-radius: 12px;
            padding: 16px;
            margin-bottom: 16px;
        }

        .feature-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;
        }

        .feature-title {
            font-size: 14px;
            font-weight: 600;
            color: #212529;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .feature-title svg {
            width: 18px;
            height: 18px;
        }

        .toggle-switch {
            position: relative;
            width: 48px;
            height: 26px;
            background: #e9ecef;
            border-radius: 13px;
            cursor: pointer;
            transition: background 0.3s;
        }

        .toggle-switch.active {
            background: #667eea;
        }

        .toggle-switch::after {
            content: '';
            position: absolute;
            top: 3px;
            left: 3px;
            width: 20px;
            height: 20px;
            background: white;
            border-radius: 50%;
            transition: transform 0.3s;
        }

        .toggle-switch.active::after {
            transform: translateX(22px);
        }

        .feature-desc {
            font-size: 12px;
            color: #6c757d;
            line-height: 1.5;
        }

        .loading-animation {
            background: linear-gradient(90deg, #f8f9fa 25%, #e9ecef 50%, #f8f9fa 75%);
            background-size: 1000px 100%;
            animation: shimmer 2s infinite;
            height: 20px;
            border-radius: 4px;
            margin: 8px 0;
        }

        .screenshot-preview {
            width: 100%;
            max-height: 150px;
            object-fit: contain;
            border-radius: 8px;
            margin-top: 12px;
            border: 2px solid #e9ecef;
        }

        .history-item {
            background: white;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            padding: 12px;
            margin-bottom: 8px;
            cursor: pointer;
            transition: all 0.2s;
        }

        .history-item:hover {
            border-color: #667eea;
            transform: translateX(-4px);
        }

        .history-time {
            font-size: 11px;
            color: #6c757d;
            margin-bottom: 4px;
        }

        .history-preview {
            font-size: 13px;
            color: #212529;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .panel-content::-webkit-scrollbar {
            width: 8px;
        }

        .panel-content::-webkit-scrollbar-track {
            background: #f8f9fa;
        }

        .panel-content::-webkit-scrollbar-thumb {
            background: #dee2e6;
            border-radius: 4px;
        }

        .panel-content::-webkit-scrollbar-thumb:hover {
            background: #adb5bd;
        }

        .result-container::-webkit-scrollbar {
            width: 6px;
        }

        .result-container::-webkit-scrollbar-track {
            background: #e9ecef;
            border-radius: 3px;
        }

        .result-container::-webkit-scrollbar-thumb {
            background: #adb5bd;
            border-radius: 3px;
        }

        @media (max-width: 768px) {
            #aiSolverPanel {
                width: 100%;
                right: -100%;
            }
        }
    `);

    const SVG_ICONS = {
        robot: '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 2a2 2 0 0 1 2 2c0 .74-.4 1.39-1 1.73V7h1a7 7 0 0 1 7 7h1a1 1 0 0 1 1 1v3a1 1 0 0 1-1 1h-1v1a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-1H2a1 1 0 0 1-1-1v-3a1 1 0 0 1 1-1h1a7 7 0 0 1 7-7h1V5.73c-.6-.34-1-.99-1-1.73a2 2 0 0 1 2-2M7.5 13A2.5 2.5 0 0 0 5 15.5A2.5 2.5 0 0 0 7.5 18a2.5 2.5 0 0 0 2.5-2.5A2.5 2.5 0 0 0 7.5 13m9 0a2.5 2.5 0 0 0-2.5 2.5a2.5 2.5 0 0 0 2.5 2.5a2.5 2.5 0 0 0 2.5-2.5a2.5 2.5 0 0 0-2.5-2.5Z"/></svg>',
        close: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M18 6L6 18M6 6l12 12" stroke-linecap="round" stroke-linejoin="round"/></svg>',
        camera: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"></path><circle cx="12" cy="13" r="4"></circle></svg>',
        edit: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path></svg>',
        shield: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"></path></svg>',
        ghost: '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M12,2A9,9 0 0,0 3,11V22L6,19L9,22L12,19L15,22L18,19L21,22V11A9,9 0 0,0 12,2M9,8A2,2 0 0,1 11,10A2,2 0 0,1 9,12A2,2 0 0,1 7,10A2,2 0 0,1 9,8M15,8A2,2 0 0,1 17,10A2,2 0 0,1 15,12A2,2 0 0,1 13,10A2,2 0 0,1 15,8Z"/></svg>',
        save: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"></path><polyline points="17 21 17 13 7 13 7 21"></polyline><polyline points="7 3 7 8 15 8"></polyline></svg>',
        history: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"></circle><polyline points="12 6 12 12 16 14"></polyline></svg>',
        copy: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg>',
        trash: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path></svg>',
        wifi: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M5 12.55a11 11 0 0 1 14.08 0"></path><path d="M1.42 9a16 16 0 0 1 21.16 0"></path><path d="M8.53 16.11a6 6 0 0 1 6.95 0"></path><line x1="12" y1="20" x2="12.01" y2="20"></line></svg>',
        globe: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"></circle><line x1="2" y1="12" x2="22" y2="12"></line><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"></path></svg>',
        activity: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"></polyline></svg>',
        send: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="22" y1="2" x2="11" y2="13"></line><polygon points="22 2 15 22 11 13 2 9 22 2"></polygon></svg>',
        image: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><circle cx="8.5" cy="8.5" r="1.5"></circle><polyline points="21 15 16 10 5 21"></polyline></svg>',
        scissors: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="6" cy="6" r="3"></circle><circle cx="6" cy="18" r="3"></circle><line x1="20" y1="4" x2="8.12" y2="15.88"></line><line x1="14.47" y1="14.48" x2="20" y2="20"></line><line x1="8.12" y1="8.12" x2="12" y2="12"></line></svg>',
        key: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"></path></svg>',
        lightbulb: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M9 18h6"></path><path d="M10 22h4"></path><path d="M15.09 14c.18-.98.65-1.74 1.41-2.5A4.65 4.65 0 0 0 18 8 6 6 0 0 0 6 8c0 1 .23 2.23 1.5 3.5A4.61 4.61 0 0 1 8.91 14"></path></svg>',
        check: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"></polyline></svg>',
        rocket: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"></path><path d="m12 15-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"></path><path d="M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"></path><path d="M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"></path></svg>',
        upload: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="17 8 12 3 7 8"></polyline><line x1="12" y1="3" x2="12" y2="15"></line></svg>'
    };

    let panelVisible = false;
    let lastScreenshot = null;
    let textMode = false;
    let usageCount = GM_getValue('usageCount', 0);
    let antiDetectEnabled = GM_getValue('antiDetect', true);
    let autoSaveEnabled = GM_getValue('autoSave', true);
    let stealthModeEnabled = GM_getValue('stealthMode', false);
    let historyEnabled = GM_getValue('historyEnabled', true);
    let queryHistory = GM_getValue('queryHistory', []);
    let userIP = 'Checking...';
    let pingTime = 'Checking...';
    let systemStatus = 'Initializing...';
    let minDelay = GM_getValue('minDelay', 1000);
    let maxDelay = GM_getValue('maxDelay', 5000);
    let userAgents = GM_getValue('userAgents', ['Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15']).filter(Boolean);
    let randomizeReferrer = GM_getValue('randomizeReferrer', true);
    let referrers = ['https://www.google.com/', 'https://www.bing.com/', 'https://www.yahoo.com/'];

    function createLoadingScreen() {
        const loadingScreen = document.createElement('div');
        loadingScreen.id = 'aiSolverLoadingScreen';
        loadingScreen.innerHTML = `
            <svg class="loading-logo" viewBox="0 0 24 24" fill="white">
                <path d="M12 2a2 2 0 0 1 2 2c0 .74-.4 1.39-1 1.73V7h1a7 7 0 0 1 7 7h1a1 1 0 0 1 1 1v3a1 1 0 0 1-1 1h-1v1a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-1H2a1 1 0 0 1-1-1v-3a1 1 0 0 1 1-1h1a7 7 0 0 1 7-7h1V5.73c-.6-.34-1-.99-1-1.73a2 2 0 0 1 2-2M7.5 13A2.5 2.5 0 0 0 5 15.5A2.5 2.5 0 0 0 7.5 18a2.5 2.5 0 0 0 2.5-2.5A2.5 2.5 0 0 0 7.5 13m9 0a2.5 2.5 0 0 0-2.5 2.5a2.5 2.5 0 0 0 2.5 2.5a2.5 2.5 0 0 0 2.5-2.5a2.5 2.5 0 0 0-2.5-2.5Z"/>
            </svg>
            <h1 class="loading-title">HomeworkGPT</h1>
            <p class="loading-subtitle">Initializing enhanced features</p>
            <div class="loading-progress-container">
                <div class="loading-progress-bar"></div>
            </div>
            <p class="loading-status">
                <span class="loading-dots">Loading components</span>
            </p>
        `;
        document.body.appendChild(loadingScreen);
        return loadingScreen;
    }

    async function checkIPAddress() {
        return new Promise((resolve) => {
            GM_xmlhttpRequest({
                method: 'GET',
                url: 'https://api.ipify.org?format=json',
                onload: function(response) {
                    try {
                        const data = JSON.parse(response.responseText);
                        userIP = data.ip;
                        resolve(data.ip);
                    } catch (e) {
                        userIP = 'Unknown';
                        resolve('Unknown');
                    }
                },
                onerror: function() {
                    userIP = 'Error';
                    resolve('Error');
                },
                ontimeout: function() {
                    userIP = 'Timeout';
                    resolve('Timeout');
                }
            });
        });
    }

    async function checkPing() {
        return new Promise((resolve) => {
            const startTime = Date.now();
            GM_xmlhttpRequest({
                method: 'HEAD',
                url: 'https://www.cloudflare.com',
                onload: function() {
                    const endTime = Date.now();
                    pingTime = (endTime - startTime) + 'ms';
                    resolve(pingTime);
                },
                onerror: function() {
                    pingTime = 'Error';
                    resolve('Error');
                },
                ontimeout: function() {
                    pingTime = 'Timeout';
                    resolve('Timeout');
                }
            });
        });
    }

    function updateLoadingStatus(screen, message) {
        const statusEl = screen.querySelector('.loading-status .loading-dots');
        if (statusEl) {
            statusEl.textContent = message;
        }
    }

    async function initializeSystem() {
        const loadingScreen = createLoadingScreen();

        updateLoadingStatus(loadingScreen, 'Checking IP address');
        await checkIPAddress();
        await new Promise(resolve => setTimeout(resolve, 500));

        updateLoadingStatus(loadingScreen, 'Testing network latency');
        await checkPing();
        await new Promise(resolve => setTimeout(resolve, 500));

        updateLoadingStatus(loadingScreen, 'Loading UI components');
        await new Promise(resolve => setTimeout(resolve, 500));

        updateLoadingStatus(loadingScreen, 'Almost ready');
        systemStatus = 'Ready';
        await new Promise(resolve => setTimeout(resolve, 500));

        loadingScreen.classList.add('hidden');
        setTimeout(() => {
            loadingScreen.remove();
            toggleBtn.classList.add('ready');
            if (stealthModeEnabled) {
                toggleBtn.style.display = 'none';
            }
        }, 500);
    }

    const toggleBtn = document.createElement('button');
    toggleBtn.id = 'aiSolverToggle';
    toggleBtn.innerHTML = SVG_ICONS.robot;
    toggleBtn.title = 'Open AI Homework Solver (Alt+Q)';
    document.body.appendChild(toggleBtn);

    const panel = document.createElement('div');
    panel.id = 'aiSolverPanel';
    panel.innerHTML = `
        <div class="panel-header">
            <button class="close-panel-btn" id="closePanelBtn">
                ${SVG_ICONS.close}
            </button>
            <h1>AI Homework Solver</h1>
            <div class="subtitle">Powered by tw1sk</div>
        </div>

        <div class="discord-banner">
            <div class="discord-info">
                <svg class="discord-icon" viewBox="0 0 71 55" xmlns="http://www.w3.org/2000/svg">
                    <path d="M60.1045 4.8978C55.5792 2.8214 50.7265 1.2916 45.6527 0.41542C45.5603 0.39851 45.468 0.440769 45.4204 0.525289C44.7963 1.6353 44.105 3.0834 43.6209 4.2216C38.1637 3.4046 32.7345 3.4046 27.3892 4.2216C26.905 3.0581 26.1886 1.6353 25.5617 0.525289C25.5141 0.443589 25.4218 0.40133 25.3294 0.41542C20.2584 1.2888 15.4057 2.8186 10.8776 4.8978C10.8384 4.9147 10.8048 4.9429 10.7825 4.9795C1.57795 18.7309 -0.943561 32.1443 0.293408 45.3914C0.299005 45.4562 0.335386 45.5182 0.385761 45.5576C6.45866 50.0174 12.3413 52.7249 18.1147 54.5195C18.2071 54.5477 18.305 54.5139 18.3638 54.4378C19.7295 52.5728 20.9469 50.6063 21.9907 48.5383C22.0523 48.4172 21.9935 48.2735 21.8676 48.2256C19.9366 47.4931 18.0979 46.6 16.3292 45.5858C16.1893 45.5041 16.1781 45.304 16.3068 45.2082C16.679 44.9293 17.0513 44.6391 17.4067 44.3461C17.471 44.2926 17.5606 44.2813 17.6362 44.3151C29.2558 49.6202 41.8354 49.6202 53.3179 44.3151C53.3935 44.2785 53.4831 44.2898 53.5502 44.3433C53.9057 44.6363 54.2779 44.9293 54.6529 45.2082C54.7816 45.304 54.7732 45.5041 54.6333 45.5858C52.8646 46.6197 51.0259 47.4931 49.0921 48.2228C48.9662 48.2707 48.9102 48.4172 48.9718 48.5383C50.038 50.6034 51.2554 52.5699 52.5959 54.435C52.6519 54.5139 52.7526 54.5477 52.845 54.5195C58.6464 52.7249 64.529 50.0174 70.6019 45.5576C70.6551 45.5182 70.6887 45.459 70.6943 45.3942C72.1747 30.0791 68.2147 16.7757 60.1968 4.9823C60.1772 4.9429 60.1437 4.9147 60.1045 4.8978ZM23.7259 37.3253C20.2276 37.3253 17.3451 34.1136 17.3451 30.1693C17.3451 26.225 20.1717 23.0133 23.7259 23.0133C27.308 23.0133 30.1626 26.2532 30.1066 30.1693C30.1066 34.1136 27.28 37.3253 23.7259 37.3253ZM47.3178 37.3253C43.8196 37.3253 40.9371 34.1136 40.9371 30.1693C40.9371 26.225 43.7636 23.0133 47.3178 23.0133C50.9 23.0133 53.7545 26.2532 53.6986 30.1693C53.6986 34.1136 50.9 37.3253 47.3178 37.3253Z"/>
                </svg>
                <div class="discord-text">
                    <h3>Join Our Community</h3>
                    <p>Get support & updates</p>
                </div>
            </div>
            <a href="https://discord.gg/xma3JdqnXC" target="_blank" class="discord-join-btn">
                Join Discord
            </a>
        </div>

        <div class="stats-bar">
            <div class="stat-item">
                ${SVG_ICONS.activity}
                <span>Usage</span>
                <span class="stat-badge" id="usageCount">${usageCount}</span>
            </div>
            <div class="stat-item">
                <span id="statusText">Ready</span>
            </div>
            <div class="stat-item">
                <span class="stat-badge ${antiDetectEnabled ? 'success' : 'warning'}" id="antiDetectStatus">
                    ${antiDetectEnabled ? 'Protected' : 'Exposed'}
                </span>
            </div>
        </div>

        <div class="network-status">
            <div class="network-item" id="ipStatus">
                ${SVG_ICONS.globe}
                <span>IP: <strong id="ipAddress">${userIP}</strong></span>
            </div>
            <div class="network-item" id="pingStatus">
                ${SVG_ICONS.wifi}
                <span>Ping: <strong id="pingTime">${pingTime}</strong></span>
            </div>
            <div class="network-item info" id="systemStatus">
                ${SVG_ICONS.activity}
                <span>Status: <strong id="systemStatusText">${systemStatus}</strong></span>
            </div>
        </div>

        <div class="panel-content">
            <div class="info-card">
                <strong>🚀 Quick Start Guide</strong>
                Choose between Image Mode or Text Mode, configure your settings, and click Submit to get AI-powered solutions!
            </div>

            <div class="form-section">
                <label class="form-label">Security Features</label>

                <div class="feature-card">
                    <div class="feature-header">
                        <div class="feature-title">
                            ${SVG_ICONS.shield}
                            <span>Anti-Detection Mode</span>
                        </div>
                        <div class="toggle-switch ${antiDetectEnabled ? 'active' : ''}" id="antiDetectToggle"></div>
                    </div>
                    <div class="feature-desc">Randomizes request patterns, adds variable delays, rotates user-agents, and spoofs referrers to avoid detection</div>
                </div>

                <div class="feature-card">
                    <div class="feature-header">
                        <div class="feature-title">
                            ${SVG_ICONS.ghost}
                            <span>Stealth Mode</span>
                        </div>
                        <div class="toggle-switch ${stealthModeEnabled ? 'active' : ''}" id="stealthToggle"></div>
                    </div>
                    <div class="feature-desc">Hides the floating button and uses keyboard shortcuts only (Alt+Q)</div>
                </div>

                <div class="feature-card">
                    <div class="feature-header">
                        <div class="feature-title">
                            ${SVG_ICONS.save}
                            <span>Auto-Save Responses</span>
                        </div>
                        <div class="toggle-switch ${autoSaveEnabled ? 'active' : ''}" id="autoSaveToggle"></div>
                    </div>
                    <div class="feature-desc">Automatically saves all AI responses to your browser</div>
                </div>

                <div class="feature-card">
                    <div class="feature-header">
                        <div class="feature-title">
                            ${SVG_ICONS.history}
                            <span>Query History</span>
                        </div>
                        <div class="toggle-switch ${historyEnabled ? 'active' : ''}" id="historyToggle"></div>
                    </div>
                    <div class="feature-desc">Keep track of your previous questions and answers</div>
                </div>
            </div>

            <div class="form-section">
                <label class="form-label">Advanced Anti-Detect Customization</label>
                <div class="form-section">
                    <label class="form-label">Min Delay (ms)</label>
                    <input type="number" class="form-input" id="minDelayInput" value="${minDelay}" min="0">
                </div>
                <div class="form-section">
                    <label class="form-label">Max Delay (ms)</label>
                    <input type="number" class="form-input" id="maxDelayInput" value="${maxDelay}" min="0">
                </div>
                <div class="form-section">
                    <label class="form-label">User-Agents (one per line)</label>
                    <textarea class="form-textarea" id="userAgentsInput">${userAgents.join('\n')}</textarea>
                </div>
                <div class="feature-card">
                    <div class="feature-header">
                        <div class="feature-title">
                            ${SVG_ICONS.globe}
                            <span>Randomize Referrer</span>
                        </div>
                        <div class="toggle-switch ${randomizeReferrer ? 'active' : ''}" id="referrerToggle"></div>
                    </div>
                    <div class="feature-desc">Spoofs referrer headers for better anonymity</div>
                </div>
                <button class="btn btn-primary" id="saveAntiDetectBtn" style="width: 100%;">Save Anti-Detect Settings</button>
            </div>

            <div class="form-section">
                <label class="form-label">Input Mode</label>
                <div class="mode-toggle">
                    <button class="mode-btn active" id="imageModeBtn">
                        ${SVG_ICONS.camera}
                        <span>Image Mode</span>
                    </button>
                    <button class="mode-btn" id="textModeBtn">
                        ${SVG_ICONS.edit}
                        <span>Text Mode</span>
                    </button>
                </div>
            </div>

            <div class="form-section">
                <label class="form-label">
                    ${SVG_ICONS.key}
                    <span>Gemini API Key</span>
                </label>
                <input type="password" class="form-input" id="apiKeyInput" placeholder="Enter your API key here">
            </div>

            <div class="form-section">
                <label class="form-label">AI Model</label>
                <select class="form-select" id="modelSelect">
                    <option value="gemini-2.0-flash-exp">Gemini 2.0 Flash (Experimental)</option>
                    <option value="gemini-1.5-flash">Gemini 1.5 Flash</option>
                    <option value="gemini-1.5-pro">Gemini 1.5 Pro</option>
                    <option value="gemini-pro-vision">Gemini Pro Vision</option>
                </select>
            </div>

            <div class="form-section">
                <label class="form-label">Subject</label>
                <select class="form-select" id="subjectSelect">
                    <option value="math">Mathematics</option>
                    <option value="physics">Physics</option>
                    <option value="chemistry">Chemistry</option>
                    <option value="biology">Biology</option>
                    <option value="english">English</option>
                    <option value="literature">Literature</option>
                    <option value="history">History</option>
                    <option value="geography">Geography</option>
                    <option value="general">General</option>
                </select>
            </div>

            <div class="form-section">
                <label class="form-label">Response Language</label>
                <select class="form-select" id="languageSelect">
                    <option value="en">English</option>
                    <option value="vi">Vietnamese</option>
                    <option value="es">Spanish</option>
                    <option value="fr">French</option>
                    <option value="de">German</option>
                    <option value="ja">Japanese</option>
                    <option value="ko">Korean</option>
                    <option value="zh">Chinese</option>
                </select>
            </div>

            <div class="form-section">
                <label class="form-label">Output Style</label>
                <select class="form-select" id="outputModeSelect">
                    <option value="detailed">Detailed Explanation</option>
                    <option value="brief">Brief Summary</option>
                    <option value="step">Step-by-Step</option>
                    <option value="visual">Visual Aids (if possible)</option>
                </select>
            </div>

            <div class="form-section" id="imageControls">
                <label class="form-label">Capture Options</label>
                <div class="button-group">
                    <button class="btn btn-secondary" id="captureFullBtn">
                        ${SVG_ICONS.image}
                        <span>Full Page</span>
                    </button>
                    <button class="btn btn-secondary" id="captureAreaBtn">
                        ${SVG_ICONS.scissors}
                        <span>Select Area</span>
                    </button>
                    <button class="btn btn-secondary" id="uploadImageBtn">
                        ${SVG_ICONS.upload}
                        <span>Upload Image</span>
                    </button>
                </div>
                <input type="file" id="imageUploadInput" style="display: none;" accept="image/*">
                <img id="screenshotPreview" class="screenshot-preview" style="display: none;">
            </div>

            <div class="form-section" id="textControls" style="display: none;">
                <label class="form-label">Your Question</label>
                <textarea class="form-textarea" id="textQuestionInput" placeholder="Type your question here (max 3000 characters)..."></textarea>
            </div>

            <div class="form-section">
                <label class="form-label">Custom Prompt (Optional)</label>
                <textarea class="form-textarea" id="customPromptInput" placeholder="Add custom instructions for the AI..."></textarea>
            </div>

            <div class="form-section">
                <button class="btn btn-success" id="submitBtn" style="width: 100%;">
                    ${SVG_ICONS.rocket}
                    <span>Submit Question</span>
                </button>
            </div>

            <div class="form-section">
                <div class="result-header">
                    <label class="form-label" style="margin: 0;">
                        ${SVG_ICONS.lightbulb}
                        <span>Solution</span>
                    </label>
                    <div style="display: flex; gap: 8px;">
                        <button class="btn btn-secondary" id="copyResultBtn" style="min-width: auto; padding: 8px 16px;">
                            ${SVG_ICONS.copy}
                        </button>
                        <button class="btn btn-secondary" id="saveResultBtn" style="min-width: auto; padding: 8px 16px;">
                            ${SVG_ICONS.save}
                        </button>
                    </div>
                </div>
                <div class="result-container" id="answerBox">
                    Waiting for your question...
                </div>
            </div>

            <div class="form-section" id="historySection" style="display: ${historyEnabled && queryHistory.length > 0 ? 'block' : 'none'};">
                <div class="result-header">
                    <label class="form-label" style="margin: 0;">
                        ${SVG_ICONS.history}
                        <span>Recent History</span>
                    </label>
                    <button class="btn btn-danger" id="clearHistoryBtn" style="min-width: auto; padding: 8px 16px;">
                        ${SVG_ICONS.trash}
                    </button>
                </div>
                <div id="historyContainer"></div>
            </div>
        </div>
    `;
    document.body.appendChild(panel);

    const closePanelBtn = document.getElementById('closePanelBtn');
    const apiKeyInput = document.getElementById('apiKeyInput');
    const modelSelect = document.getElementById('modelSelect');
    const subjectSelect = document.getElementById('subjectSelect');
    const languageSelect = document.getElementById('languageSelect');
    const outputModeSelect = document.getElementById('outputModeSelect');
    const customPromptInput = document.getElementById('customPromptInput');
    const imageModeBtn = document.getElementById('imageModeBtn');
    const textModeBtn = document.getElementById('textModeBtn');
    const imageControls = document.getElementById('imageControls');
    const textControls = document.getElementById('textControls');
    const textQuestionInput = document.getElementById('textQuestionInput');
    const captureFullBtn = document.getElementById('captureFullBtn');
    const captureAreaBtn = document.getElementById('captureAreaBtn');
    const uploadImageBtn = document.getElementById('uploadImageBtn');
    const imageUploadInput = document.getElementById('imageUploadInput');
    const submitBtn = document.getElementById('submitBtn');
    const answerBox = document.getElementById('answerBox');
    const copyResultBtn = document.getElementById('copyResultBtn');
    const saveResultBtn = document.getElementById('saveResultBtn');
    const usageCountEl = document.getElementById('usageCount');
    const statusText = document.getElementById('statusText');
    const screenshotPreview = document.getElementById('screenshotPreview');
    const antiDetectToggle = document.getElementById('antiDetectToggle');
    const antiDetectStatus = document.getElementById('antiDetectStatus');
    const stealthToggle = document.getElementById('stealthToggle');
    const autoSaveToggle = document.getElementById('autoSaveToggle');
    const historyToggle = document.getElementById('historyToggle');
    const historySection = document.getElementById('historySection');
    const historyContainer = document.getElementById('historyContainer');
    const clearHistoryBtn = document.getElementById('clearHistoryBtn');
    const ipAddressEl = document.getElementById('ipAddress');
    const pingTimeEl = document.getElementById('pingTime');
    const systemStatusEl = document.getElementById('systemStatusText');
    const ipStatusEl = document.getElementById('ipStatus');
    const pingStatusEl = document.getElementById('pingStatus');
    const minDelayInput = document.getElementById('minDelayInput');
    const maxDelayInput = document.getElementById('maxDelayInput');
    const userAgentsInput = document.getElementById('userAgentsInput');
    const referrerToggle = document.getElementById('referrerToggle');
    const saveAntiDetectBtn = document.getElementById('saveAntiDetectBtn');

    function updateNetworkUI() {
        ipAddressEl.textContent = userIP;
        pingTimeEl.textContent = pingTime;
        systemStatusEl.textContent = systemStatus;

        if (userIP !== 'Checking...' && userIP !== 'Error' && userIP !== 'Unknown') {
            ipStatusEl.classList.remove('bad');
            ipStatusEl.classList.add('good');
        } else if (userIP === 'Error' || userIP === 'Unknown') {
            ipStatusEl.classList.remove('good');
            ipStatusEl.classList.add('bad');
        }

        if (pingTime !== 'Checking...' && pingTime !== 'Error' && pingTime !== 'Timeout') {
            const ping = parseInt(pingTime);
            if (ping < 100) {
                pingStatusEl.classList.remove('medium', 'bad');
                pingStatusEl.classList.add('good');
            } else if (ping < 300) {
                pingStatusEl.classList.remove('good', 'bad');
                pingStatusEl.classList.add('medium');
            } else {
                pingStatusEl.classList.remove('good', 'medium');
                pingStatusEl.classList.add('bad');
            }
        } else if (pingTime === 'Error' || pingTime === 'Timeout') {
            pingStatusEl.classList.remove('good', 'medium');
            pingStatusEl.classList.add('bad');
        }
    }

    apiKeyInput.value = GM_getValue('apiKey', '');
    modelSelect.value = GM_getValue('model', 'gemini-2.0-flash-exp');
    subjectSelect.value = GM_getValue('subject', 'general');
    languageSelect.value = GM_getValue('language', 'en');
    outputModeSelect.value = GM_getValue('outputMode', 'detailed');
    customPromptInput.value = GM_getValue('customPrompt', '');

    apiKeyInput.addEventListener('input', () => GM_setValue('apiKey', apiKeyInput.value));
    modelSelect.addEventListener('change', () => GM_setValue('model', modelSelect.value));
    subjectSelect.addEventListener('change', () => GM_setValue('subject', subjectSelect.value));
    languageSelect.addEventListener('change', () => GM_setValue('language', languageSelect.value));
    outputModeSelect.addEventListener('change', () => GM_setValue('outputMode', outputModeSelect.value));
    customPromptInput.addEventListener('input', () => GM_setValue('customPrompt', customPromptInput.value));

    closePanelBtn.addEventListener('click', () => {
        panelVisible = false;
        panel.classList.remove('show');
        toggleBtn.classList.remove('active');
    });

    function togglePanel() {
        panelVisible = !panelVisible;
        if (panelVisible) {
            panel.classList.add('show');
            toggleBtn.classList.add('active');
            updateNetworkUI();
        } else {
            panel.classList.remove('show');
            toggleBtn.classList.remove('active');
        }
    }

    toggleBtn.addEventListener('click', togglePanel);

    document.addEventListener('keydown', (e) => {
        if (e.altKey && e.key === 'q') {
            e.preventDefault();
            togglePanel();
        }
    });

    antiDetectToggle.addEventListener('click', () => {
        antiDetectEnabled = !antiDetectEnabled;
        antiDetectToggle.classList.toggle('active');
        GM_setValue('antiDetect', antiDetectEnabled);
        antiDetectStatus.textContent = antiDetectEnabled ? 'Protected' : 'Exposed';
        antiDetectStatus.className = `stat-badge ${antiDetectEnabled ? 'success' : 'warning'}`;
    });

    stealthToggle.addEventListener('click', () => {
        stealthModeEnabled = !stealthModeEnabled;
        stealthToggle.classList.toggle('active');
        GM_setValue('stealthMode', stealthModeEnabled);
        toggleBtn.style.display = stealthModeEnabled ? 'none' : 'flex';
        if (stealthModeEnabled) {
            alert('🔒 Stealth Mode Enabled!\nUse Alt+Q to toggle the panel.');
        }
    });

    autoSaveToggle.addEventListener('click', () => {
        autoSaveEnabled = !autoSaveEnabled;
        autoSaveToggle.classList.toggle('active');
        GM_setValue('autoSave', autoSaveEnabled);
    });

    historyToggle.addEventListener('click', () => {
        historyEnabled = !historyEnabled;
        historyToggle.classList.toggle('active');
        GM_setValue('historyEnabled', historyEnabled);
        updateHistoryDisplay();
    });

    referrerToggle.addEventListener('click', () => {
        randomizeReferrer = !randomizeReferrer;
        referrerToggle.classList.toggle('active');
        GM_setValue('randomizeReferrer', randomizeReferrer);
    });

    saveAntiDetectBtn.addEventListener('click', () => {
        minDelay = parseInt(minDelayInput.value) || 1000;
        maxDelay = parseInt(maxDelayInput.value) || 5000;
        userAgents = userAgentsInput.value.trim().split('\n').filter(ua => ua.trim());
        GM_setValue('minDelay', minDelay);
        GM_setValue('maxDelay', maxDelay);
        GM_setValue('userAgents', userAgents);
        alert('✅ Anti-Detect settings saved! For 100% customization, edit user-agents and delays as needed.');
    });

    imageModeBtn.addEventListener('click', () => {
        textMode = false;
        imageModeBtn.classList.add('active');
        textModeBtn.classList.remove('active');
        imageControls.style.display = 'block';
        textControls.style.display = 'none';
        statusText.textContent = 'Image Mode';
    });

    textModeBtn.addEventListener('click', () => {
        textMode = true;
        textModeBtn.classList.add('active');
        imageModeBtn.classList.remove('active');
        textControls.style.display = 'block';
        imageControls.style.display = 'none';
        statusText.textContent = 'Text Mode';
    });

    textQuestionInput.addEventListener('input', () => {
        if (textQuestionInput.value.length > 3000) {
            textQuestionInput.value = textQuestionInput.value.substring(0, 3000);
            alert('⚠️ Question exceeded 3000 characters and has been truncated.');
        }
    });

    captureFullBtn.addEventListener('click', async () => {
        statusText.textContent = 'Capturing...';
        answerBox.textContent = '📸 Capturing full page...';
        try {
            const canvas = await html2canvas(document.body, {
                allowTaint: true,
                useCORS: true,
                scrollY: -window.scrollY,
                scrollX: -window.scrollX,
                windowWidth: document.documentElement.scrollWidth,
                windowHeight: document.documentElement.scrollHeight
            });
            lastScreenshot = canvas.toDataURL('image/png').split(',')[1];
            screenshotPreview.src = canvas.toDataURL('image/png');
            screenshotPreview.style.display = 'block';
            answerBox.textContent = '✅ Full page captured! Click Submit to analyze.';
            statusText.textContent = 'Ready';
        } catch (error) {
            answerBox.textContent = '❌ Capture error: ' + error.message;
            statusText.textContent = 'Error';
        }
    });

    captureAreaBtn.addEventListener('click', () => {
        statusText.textContent = 'Select Area';
        answerBox.textContent = '🖱️ Click and drag to select area...';

        const overlay = document.createElement('div');
        overlay.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.3);
            z-index: 999998;
            cursor: crosshair;
        `;

        const selection = document.createElement('div');
        selection.style.cssText = `
            position: fixed;
            border: 3px solid #667eea;
            background: rgba(102, 126, 234, 0.1);
            z-index: 999999;
            pointer-events: none;
        `;

        document.body.appendChild(overlay);
        document.body.appendChild(selection);

        let startX, startY, isDrawing = false;

        overlay.addEventListener('mousedown', (e) => {
            isDrawing = true;
            startX = e.clientX;
            startY = e.clientY;
            selection.style.left = startX + 'px';
            selection.style.top = startY + 'px';
            selection.style.width = '0';
            selection.style.height = '0';
        });

        overlay.addEventListener('mousemove', (e) => {
            if (!isDrawing) return;
            const width = e.clientX - startX;
            const height = e.clientY - startY;
            selection.style.width = Math.abs(width) + 'px';
            selection.style.height = Math.abs(height) + 'px';
            selection.style.left = (width < 0 ? e.clientX : startX) + 'px';
            selection.style.top = (height < 0 ? e.clientY : startY) + 'px';
        });

        overlay.addEventListener('mouseup', async (e) => {
            if (!isDrawing) return;
            isDrawing = false;

            const rect = selection.getBoundingClientRect();
            overlay.remove();
            selection.remove();

            if (rect.width < 10 || rect.height < 10) {
                answerBox.textContent = '❌ Selected area too small. Please try again.';
                statusText.textContent = 'Ready';
                return;
            }

            answerBox.textContent = '📸 Capturing selected area...';

            try {
                const canvas = await html2canvas(document.body, {
                    x: rect.left + window.scrollX,
                    y: rect.top + window.scrollY,
                    width: rect.width,
                    height: rect.height,
                    allowTaint: true,
                    useCORS: true
                });
                lastScreenshot = canvas.toDataURL('image/png').split(',')[1];
                screenshotPreview.src = canvas.toDataURL('image/png');
                screenshotPreview.style.display = 'block';
                answerBox.textContent = '✅ Area captured! Click Submit to analyze.';
                statusText.textContent = 'Ready';
            } catch (error) {
                answerBox.textContent = '❌ Capture error: ' + error.message;
                statusText.textContent = 'Error';
            }
        });
    });

    uploadImageBtn.addEventListener('click', () => {
        imageUploadInput.click();
    });

    imageUploadInput.addEventListener('change', (e) => {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = (event) => {
                lastScreenshot = event.target.result.split(',')[1];
                screenshotPreview.src = event.target.result;
                screenshotPreview.style.display = 'block';
                answerBox.textContent = '✅ Image uploaded! Click Submit to analyze.';
                statusText.textContent = 'Ready';
            };
            reader.readAsDataURL(file);
        }
    });

    function typeEffect(element, text, speed = 5) {
        element.textContent = '';
        let i = 0;
        const interval = setInterval(() => {
            if (i < text.length) {
                element.textContent += text.charAt(i);
                i++;
                element.scrollTop = element.scrollHeight;
            } else {
                clearInterval(interval);
            }
        }, speed);
    }

    function getRandomDelay() {
        if (!antiDetectEnabled) return 0;
        return Math.floor(Math.random() * (maxDelay - minDelay + 1)) + minDelay;
    }

    function getRandomUserAgent() {
        if (userAgents.length === 0) return 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36';
        return userAgents[Math.floor(Math.random() * userAgents.length)];
    }

    function getRandomReferrer() {
        if (!randomizeReferrer) return '';
        return referrers[Math.floor(Math.random() * referrers.length)];
    }

    function buildPrompt() {
        const subject = subjectSelect.value;
        const language = languageSelect.value;
        const outputMode = outputModeSelect.value;
        const customPrompt = customPromptInput.value.trim();

        if (customPrompt) {
            return customPrompt;
        }

        const subjectNames = {
            math: 'mathematics',
            physics: 'physics',
            chemistry: 'chemistry',
            biology: 'biology',
            english: 'English language',
            literature: 'literature',
            history: 'history',
            geography: 'geography',
            general: 'general'
        };

        const modeText = {
            detailed: 'with detailed explanation',
            brief: 'briefly and concisely',
            step: 'step-by-step clearly',
            visual: 'with visual descriptions or suggestions for diagrams'
        };

        const langText = {
            en: 'in English',
            vi: 'in Vietnamese',
            es: 'in Spanish',
            fr: 'in French',
            de: 'in German',
            ja: 'in Japanese',
            ko: 'in Korean',
            zh: 'in Chinese'
        };

        let prompt = `You are a professional educational assistant specialized in advanced problem-solving. `;

        if (textMode) {
            prompt += `Solve the following ${subjectNames[subject]} question ${modeText[outputMode]}. Provide accurate, plagiarism-free content. `;
        } else {
            prompt += `Analyze this image and solve the ${subjectNames[subject]} problem ${modeText[outputMode]}. Detect and correct any OCR errors if applicable. `;
        }

        prompt += `Respond ${langText[language]}. Include references or further reading if relevant.`;

        return prompt;
    }

    function addToHistory(question, answer) {
        if (!historyEnabled) return;

        const historyItem = {
            timestamp: new Date().toISOString(),
            question: question.substring(0, 100),
            answer: answer.substring(0, 200),
            fullAnswer: answer
        };

        queryHistory.unshift(historyItem);
        if (queryHistory.length > 20) queryHistory.pop();

        GM_setValue('queryHistory', queryHistory);
        updateHistoryDisplay();
    }

    function updateHistoryDisplay() {
        if (!historyEnabled || queryHistory.length === 0) {
            historySection.style.display = 'none';
            return;
        }

        historySection.style.display = 'block';
        historyContainer.innerHTML = '';

        queryHistory.forEach((item, index) => {
            const historyItem = document.createElement('div');
            historyItem.className = 'history-item';
            historyItem.innerHTML = `
                <div class="history-time">${new Date(item.timestamp).toLocaleString()}</div>
                <div class="history-preview">${item.question}...</div>
            `;
            historyItem.addEventListener('click', () => {
                answerBox.textContent = item.fullAnswer;
            });
            historyContainer.appendChild(historyItem);
        });
    }

    clearHistoryBtn.addEventListener('click', () => {
        if (confirm('Are you sure you want to clear all history?')) {
            queryHistory = [];
            GM_setValue('queryHistory', []);
            updateHistoryDisplay();
        }
    });

    updateHistoryDisplay();

    async function sendToGemini() {
        const apiKey = apiKeyInput.value.trim();
        if (!apiKey) {
            answerBox.textContent = '❌ Please enter your API key!';
            return;
        }

        let questionText = '';
        if (textMode) {
            questionText = textQuestionInput.value.trim();
            if (!questionText) {
                answerBox.textContent = '❌ Please enter your question!';
                return;
            }
        } else {
            if (!lastScreenshot) {
                answerBox.textContent = '❌ Please capture or upload an image first!';
                return;
            }
            questionText = 'Image question';
        }

        const delay = getRandomDelay();
        if (delay > 0) {
            statusText.textContent = `Anti-Detect (${Math.floor(delay/1000)}s)`;
            await new Promise(resolve => setTimeout(resolve, delay));
        }

        submitBtn.disabled = true;
        statusText.textContent = 'Processing...';
        answerBox.innerHTML = `
            <div class="loading-animation"></div>
            <div class="loading-animation" style="width: 80%;"></div>
            <div class="loading-animation" style="width: 60%;"></div>
            <p style="text-align: center; color: #667eea; margin-top: 16px;">⏳ AI is analyzing your question...</p>
        `;

        const prompt = buildPrompt();
        const model = modelSelect.value;
        const url = `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${apiKey}`;

        const parts = [{ text: prompt }];

        if (textMode) {
            parts.push({ text: '\n\nQuestion: ' + textQuestionInput.value });
        } else {
            parts.push({
                inline_data: {
                    mime_type: 'image/png',
                    data: lastScreenshot
                }
            });
        }

        const requestData = {
            contents: [{
                parts: parts
            }]
        };

        const headers = {
            'Content-Type': 'application/json'
        };

        if (antiDetectEnabled) {
            headers['User-Agent'] = getRandomUserAgent();
            const referrer = getRandomReferrer();
            if (referrer) {
                headers['Referer'] = referrer;
            }
            headers['Accept-Language'] = ['en-US,en;q=0.9', 'fr-FR,fr;q=0.9', 'de-DE,de;q=0.9'][Math.floor(Math.random() * 3)];
        }

        GM_xmlhttpRequest({
            method: 'POST',
            url: url,
            headers: headers,
            data: JSON.stringify(requestData),
            onload: function(response) {
                submitBtn.disabled = false;
                try {
                    const data = JSON.parse(response.responseText);
                    if (data.candidates && data.candidates[0]) {
                        const result = data.candidates[0].content.parts[0].text;
                        typeEffect(answerBox, result);
                        statusText.textContent = 'Completed';

                        usageCount++;
                        GM_setValue('usageCount', usageCount);
                        usageCountEl.textContent = usageCount;

                        addToHistory(questionText, result);

                        if (autoSaveEnabled) {
                            saveResponse(result);
                        }
                    } else {
                        answerBox.textContent = '❌ No response received from API.';
                        statusText.textContent = 'Error';
                    }
                } catch (error) {
                    answerBox.textContent = '❌ Error processing response: ' + error.message;
                    statusText.textContent = 'Error';
                }
            },
            onerror: function(error) {
                submitBtn.disabled = false;
                answerBox.textContent = '❌ API connection error. Please check your network.';
                statusText.textContent = 'Error';
            }
        });
    }

    function saveResponse(text) {
        const blob = new Blob([text], { type: 'text/plain' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `ai-solver-${Date.now()}.txt`;
        a.click();
        URL.revokeObjectURL(url);
    }

    saveResultBtn.addEventListener('click', () => {
        const text = answerBox.textContent;
        if (!text || text === 'Waiting for your question...') {
            alert('⚠️ No result to save!');
            return;
        }
        saveResponse(text);
        alert('✅ Response saved successfully!');
    });

    copyResultBtn.addEventListener('click', () => {
        const text = answerBox.textContent;
        if (!text || text === 'Waiting for your question...') {
            alert('⚠️ No result to copy!');
            return;
        }

        navigator.clipboard.writeText(text).then(() => {
            copyResultBtn.innerHTML = SVG_ICONS.check;
            setTimeout(() => {
                copyResultBtn.innerHTML = SVG_ICONS.copy;
            }, 2000);
        }).catch(err => {
            alert('❌ Copy error: ' + err.message);
        });
    });

    submitBtn.addEventListener('click', sendToGemini);

    textQuestionInput.addEventListener('keydown', (e) => {
        if (e.ctrlKey && e.key === 'Enter') {
            submitBtn.click();
        }
    });

    async function refreshNetworkStatus() {
        userIP = 'Checking...';
        pingTime = 'Checking...';
        updateNetworkUI();

        await Promise.all([checkIPAddress(), checkPing()]);
        updateNetworkUI();
    }

    document.querySelector('.network-status').addEventListener('click', refreshNetworkStatus);

    initializeSystem();

    console.log('✅ AI Homework Solver v1 loaded successfully!');
    console.log('🎨 Full SVG Icons, Loading Screen, Network Monitoring');
    console.log('⌨️ Keyboard shortcut: Alt+Q to toggle panel');
    console.log('🌐 IP: ' + userIP + ' | Ping: ' + pingTime);
    console.log('🚀 Loading screen active - Initializing...');
})();