import React, { useState, useRef, useEffect } from "react"; import { DBService } from "../lib/db"; import { MessageSquare, Send, Bot, RefreshCw, Sparkles, X, ChevronUp } from "lucide-react"; interface ChatMessage { role: "user" | "model"; content: string; } export default function AiAssistant({ triggerHaptic }: { triggerHaptic: () => void }) { const [isOpen, setIsOpen] = useState(false); const [messages, setMessages] = useState([ { role: "model", content: "أهلاً بك في تطبيق SiteClone Pro v20! أنا مستشار التكويد الذكي الخاص بك. لقد تم تنشيطي وتهيئة نظام الكشف والتبديل التلقائي لمفاتيح API والبروكسيات. اختر المزود المفضل لديك من الأعلى للاتصال الفوري والحي بـ Gemini أو OpenAI أو Groq!" } ]); const [userInput, setUserInput] = useState(""); const [loading, setLoading] = useState(false); const scrollRef = useRef(null); // Switcher states const [availableKeys, setAvailableKeys] = useState([]); const [selectedKeyId, setSelectedKeyId] = useState("default"); useEffect(() => { if (scrollRef.current) { scrollRef.current.scrollTop = scrollRef.current.scrollHeight; } }, [messages, isOpen]); useEffect(() => { if (isOpen) { loadAiKeys(); } }, [isOpen]); const loadAiKeys = async () => { try { const allKeys = await DBService.getAll("keys"); const filtered = allKeys.filter((k: any) => k.type === "Google Gemini API" || k.type === "OpenAI API" || k.type === "Groq API (جروك)" || k.type === "Custom AI Proxy (بروكسي ذكاء مخصص)" ); setAvailableKeys(filtered); const cachedActive = localStorage.getItem("active_system_key"); if (cachedActive && filtered.some(k => k.id === cachedActive)) { setSelectedKeyId(cachedActive); } else if (filtered.length > 0) { setSelectedKeyId(filtered[0].id); } else { setSelectedKeyId("default"); } } catch (e) { console.warn("Could not load AI keys:", e); } }; const handleSendMessage = async (text: string) => { if (!text.trim() || loading) return; triggerHaptic(); const userMsg: ChatMessage = { role: "user", content: text }; setMessages(prev => [...prev, userMsg]); setUserInput(""); setLoading(true); // DYNAMIC KEY EXTRACTION: Try loading working API Key from IndexedDB let customApiKey = ""; let provider = "Google Gemini API"; let customEndpoint = ""; let providerName = "المحاكي المدمج"; try { const allKeys = await DBService.getAll("keys"); const targetKey = allKeys.find((k: any) => k.id === selectedKeyId); if (targetKey) { customApiKey = targetKey.value; provider = targetKey.type; customEndpoint = targetKey.proxyAgentIp || ""; providerName = `${targetKey.name} (${targetKey.type === "Google Gemini API" ? "Gemini" : targetKey.type === "OpenAI API" ? "OpenAI" : targetKey.type === "Groq API (جروك)" ? "Groq" : "Proxy"})`; } else { // Fallback to active system key in localStorage const cachedActive = localStorage.getItem("active_system_key"); const activeKey = allKeys.find((k: any) => k.id === cachedActive); if (activeKey) { customApiKey = activeKey.value; provider = activeKey.type; customEndpoint = activeKey.proxyAgentIp || ""; providerName = `${activeKey.name} (أساسي)`; } } } catch (err) { console.warn("Could not load credentials:", err); } try { const response = await fetch("/api/ai/chat", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ messages: [...messages, userMsg].map(m => ({ role: m.role, content: m.content })), customApiKey, provider, customEndpoint }) }); if (!response.ok) { const errData = await response.json(); throw new Error(errData.error || "فشل توجيه السيرفر مع البوّابة"); } const data = await response.json(); setMessages(prev => [...prev, { role: "model", content: data.text || "لم أستطع تحليل هذا الرمز بشكل كافٍ." }]); } catch (err: any) { setMessages(prev => [...prev, { role: "model", content: `عذرًا، حدث خطأ أثناء الاتصال بمحرك الذكاء [${providerName}]: ${err?.message || String(err)}` }]); } finally { setLoading(false); triggerHaptic(); } }; const quickSuggestions = [ "كيف أفحص كفاءة عنوان IP الوكيل؟", "Gemini لا يعمل، كيف أفعل المحرك الفعلي؟", "كيف أدمج المتصفح لتسجيل مفاتيح API؟", "اقترح بدائل استضافة مجانية لـ Vercel" ]; return (
{/* 1. Toggle Button */} {!isOpen && ( )} {/* 2. Chat Floating Panel styled with Eye-comfort sky/white scheme */} {isOpen && (
{/* Header */}
مستشار التكويد والأتمتة الذكي ⚡ مدعوم بـ Gemini 3.5 Flash الفعلي
{/* Dynamic AI Key Switcher Header Panel */}
🎯 تبديل المحرك السريع:
{/* Conversations display panel */}
{messages.map((m, index) => (
{m.content}
))} {loading && (
يتم الآن الاتصال بمحرك Gemini...
)}
{/* Quick suggestions sliders */}
{quickSuggestions.map((s, index) => ( ))}
{/* User inputs */}
{ e.preventDefault(); handleSendMessage(userInput); }} className="p-3 bg-white border-t border-sky-500/10 flex gap-2" > setUserInput(e.target.value)} className="bg-sky-50/50 border border-sky-200 rounded-xl px-3 py-2 text-xs text-slate-800 focus:outline-none focus:border-sky-500 flex-1 font-semibold" />
)}
); }