import React, { useState, useEffect } from "react"; import { DBService } from "../lib/db"; import { PlatformAccount } from "../types"; import { User, Plus, Key, ShieldCheck, Trash, ShieldAlert, Clock, RefreshCw, Eye, EyeOff, Search, Sparkles } from "lucide-react"; export default function AccountsTab({ triggerHaptic }: { triggerHaptic: () => void }) { const [accounts, setAccounts] = useState([]); const [platform, setPlatform] = useState("Vercel"); const [username, setUsername] = useState(""); const [email, setEmailVal] = useState(""); const [password, setPassword] = useState(""); const [totpSecret, setTotpSecret] = useState(""); const [searchQuery, setSearchQuery] = useState(""); const [totpToken, setTotpToken] = useState("142 857"); const [totpCountdown, setTotpCountdown] = useState(30); const [visiblePassMap, setVisiblePassMap] = useState>({}); // Multi-Email Interactive Session States for 20+ Emails SSO switcher const [activeEmailSession, setActiveEmailSession] = useState("eissaaly07@gmail.com"); const [sessionEmails, setSessionEmails] = useState([ "eissaaly07@gmail.com", "eissaaly0007@gmail.com" ]); const [newSessionEmail, setNewSessionEmail] = useState(""); const [ssoSearchQuery, setSsoSearchQuery] = useState(""); const [showActiveOnly, setShowActiveOnly] = useState(true); useEffect(() => { loadAccounts(); // 2FA TOTP Simulation countdown const timer = setInterval(() => { setTotpCountdown((prev) => { if (prev <= 1) { regenerateTotpTokens(); return 30; } return prev - 1; }); }, 1000); return () => clearInterval(timer); }, []); const loadAccounts = async () => { const list = await DBService.getAll("accounts"); let finalAccounts = list; if (list.length === 0) { const seed: PlatformAccount[] = [ { id: "acc_1", platform: "Vercel", username: "developer_hero", email: "eissaaly07@gmail.com", password: "myVercelSuperPassword", status: "active", totpSecret: "JBSWY3DPEHPK3PXP", activeSessions: 2, lastLogin: Date.now() - 3600000 * 2 }, { id: "acc_2", platform: "GitHub", username: "eissa_git", email: "eissaaly07@gmail.com", password: "MyGitHubUltraSecret", status: "active", totpSecret: "HXDMVJ3XPO76ASDL", activeSessions: 1, lastLogin: Date.now() - 3600000 * 24 }, { id: "acc_3", platform: "Vercel", username: "developer_pro", email: "eissaaly0007@gmail.com", password: "MyVercelQuantumSeed", status: "active", totpSecret: "HXDMVJ3XPO76AAAA", activeSessions: 1, lastLogin: Date.now() - 3600000 * 50 } ]; for (const a of seed) { await DBService.put("accounts", a); } finalAccounts = seed; } setAccounts(finalAccounts); // Load active email session const activeSetting = await DBService.getSetting("activeEmailSession"); if (activeSetting) { setActiveEmailSession(activeSetting); } else { setActiveEmailSession("eissaaly07@gmail.com"); await DBService.putSetting("activeEmailSession", "eissaaly07@gmail.com"); } // Compile list of unique emails from registered accounts, saved custom emails & emails vault store const emailsSet = new Set([ "eissaaly07@gmail.com", "eissaaly0007@gmail.com" ]); // 1. From platform account profiles finalAccounts.forEach(acc => { if (acc.email) emailsSet.add(acc.email.trim()); }); // 2. From emails vault store (the EmailsTab registers here) try { const emailVaultList = await DBService.getAll("emails"); emailVaultList.forEach(e => { if (e.email) emailsSet.add(e.email.trim()); }); } catch (e) { console.warn("Could not retrieve emails from emails store:", e); } // 3. From session emails configuration list const storedList = await DBService.getSetting("sessionEmailsList"); if (storedList) { storedList.forEach(e => emailsSet.add(e.trim())); } setSessionEmails(Array.from(emailsSet)); }; const handleSwitchEmailSession = async (selectedEmail: string) => { triggerHaptic(); setActiveEmailSession(selectedEmail); await DBService.putSetting("activeEmailSession", selectedEmail); // Save to audit trail await DBService.put("auditLog", { id: "log_" + Date.now(), timestamp: Date.now(), action: "تغيير جلسة البريد النشط", details: `تم تبديل البريد الموحد النشط للمواقع إلى [${selectedEmail}] لتمرير تفويض الدخول على الفور`, status: "success" }); }; const handleAddCustomSessionEmail = async (e: React.FormEvent) => { e.preventDefault(); if (!newSessionEmail || !newSessionEmail.includes("@")) return; triggerHaptic(); const normalized = newSessionEmail.trim(); // Save to sessionEmailsList settings first const storedList = await DBService.getSetting("sessionEmailsList") || []; const emailsSet = new Set(storedList); emailsSet.add(normalized); const updatedList = Array.from(emailsSet); await DBService.putSetting("sessionEmailsList", updatedList); // Also let's save to the "emails" vault store so it is fully integrated across all tabs try { const emailVaultList = await DBService.getAll("emails"); const exists = emailVaultList.some((em: any) => em.email.toLowerCase() === normalized.toLowerCase()); if (!exists) { await DBService.put("emails", { id: "email_" + Date.now(), provider: normalized.includes("gmail") ? "Gmail" : normalized.includes("proton") ? "ProtonMail" : normalized.includes("outlook") ? "Outlook" : "Gmail", email: normalized, password: "DefaultSessionPassword123!", category: "dev", faStatus: true, status: "active", passwordHealth: "good", lastChecked: Date.now() }); } } catch (err) { console.warn("Could not put to emails store:", err); } // Switch to it & reload accounts (which will merge all unique session lists) await handleSwitchEmailSession(normalized); await loadAccounts(); setNewSessionEmail(""); }; const handleDeleteSessionEmail = async (emailToDelete: string) => { triggerHaptic(); if (emailToDelete === "eissaaly07@gmail.com" || emailToDelete === "eissaaly0007@gmail.com") { alert("لا يمكن حذف البريد الافتراضي المصنع للنظام."); return; } // 1. Remove from settings list const storedList = await DBService.getSetting("sessionEmailsList") || []; const updatedList = storedList.filter(e => e.toLowerCase() !== emailToDelete.toLowerCase()); await DBService.putSetting("sessionEmailsList", updatedList); // 2. Also, remove from 'emails' store so that it doesn't reappear try { const emailVaultList = await DBService.getAll("emails"); const targetInVault = emailVaultList.find((em: any) => em.email.toLowerCase() === emailToDelete.toLowerCase()); if (targetInVault) { await DBService.delete("emails", targetInVault.id); } } catch (err) { console.warn("Could not delete from emails store:", err); } // Switch to default email if deleted active one if (activeEmailSession.toLowerCase() === emailToDelete.toLowerCase()) { await handleSwitchEmailSession("eissaaly07@gmail.com"); } // Reload list await loadAccounts(); }; const handleAutoGeneratePlatformsForEmail = async (targetEmail: string) => { triggerHaptic(); const list = await DBService.getAll("accounts"); const platformsToCreate = ["Vercel", "GitHub", "Netlify", "Render", "Railway", "Glitch", "Cloudflare", "Supabase"]; let addedCount = 0; for (const plt of platformsToCreate) { const exists = list.some(a => a.email.toLowerCase() === targetEmail.toLowerCase() && a.platform === plt); if (!exists) { const usernamePrefix = targetEmail.split("@")[0] || "member"; const newAcc: PlatformAccount = { id: `acc_${plt.toLowerCase()}_${Date.now()}_${Math.floor(Math.random()*1000)}`, platform: plt, username: `${usernamePrefix}_${plt.toLowerCase()}`, email: targetEmail, password: `pass_${Math.random().toString(36).substring(4, 10)}`, status: "active", totpSecret: "HXDMVJ3XPO76" + Math.random().toString(36).substring(2, 6).toUpperCase(), activeSessions: 1, lastLogin: Date.now() }; await DBService.put("accounts", newAcc); addedCount++; } } await loadAccounts(); await DBService.put("auditLog", { id: "log_" + Date.now(), timestamp: Date.now(), action: "تهيئة منصات فرعية للبريد", details: `تم تهيئة وتوليد عدد ${addedCount} حسابات سحابية لبريد الجلسة [${targetEmail}]`, status: "success" }); alert(`✓ تم ربط وتوليد البوابات وحسابات السيرفر السريع بنجاح للبريد المختار: ${targetEmail}!\nتمت تصفية وتجهيز Vercel و GitHub و Netlify و Render و Glitch و Cloudflare و Supabase للعمل معاً بضغطة واحدة.`); }; const regenerateTotpTokens = () => { setTotpToken(() => { const code1 = Math.floor(Math.random() * 900) + 100; const code2 = Math.floor(Math.random() * 900) + 100; return `${code1} ${code2}`; }); }; const handleAddAccount = async (e: React.FormEvent) => { e.preventDefault(); if (!username || !email) return; triggerHaptic(); const newAccount: PlatformAccount = { id: "acc_" + Date.now(), platform, username, email, password: password || undefined, totpSecret: totpSecret || undefined, status: "active", activeSessions: 1, lastLogin: Date.now() }; await DBService.put("accounts", newAccount); await loadAccounts(); await DBService.put("auditLog", { id: "log_" + Date.now(), timestamp: Date.now(), action: "إضافة حساب منصة", details: `تم تسجيل حساب [${username}] على منصة [${platform}] بنجاح`, status: "success" }); setUsername(""); setEmailVal(""); setPassword(""); setTotpSecret(""); }; const handleDelete = async (id: string) => { triggerHaptic(); await DBService.delete("accounts", id); setAccounts(prev => prev.filter(a => a.id !== id)); }; const togglePasswordVisibility = (id: string) => { setVisiblePassMap(prev => ({ ...prev, [id]: !prev[id] })); }; const simulateTotpForSecret = (secret: string | undefined): string => { if (!secret) return "--- ---"; let val = 0; for (let i = 0; i < secret.length; i++) { val += secret.charCodeAt(i); } const factor = Math.floor(Date.now() / 30000); const code = ((val * factor) % 900000) + 100000; const s = String(code); return `${s.substring(0, 3)} ${s.substring(3)}`; }; const filteredAccounts = accounts.filter(a => { const matchesSearch = a.username.toLowerCase().includes(searchQuery.toLowerCase()) || a.platform.toLowerCase().includes(searchQuery.toLowerCase()); if (showActiveOnly) { return matchesSearch && a.email.toLowerCase() === activeEmailSession.toLowerCase(); } return matchesSearch; }); return (
{/* 20+ Master Email SSO Switcher Panel (Arabic / English high contrast design) */}

بوابة الدخول الموحد وجلسات البريد المتعددة (Multi-Account SSO Gateway)

قم بإدارة أكثر من 20 بريد إلكتروني ومزامنتها بضغطة زر واحدة. تفعيل الجلسة يربط ويظهر حسابات المنصات التابعة للبريد المختار فوراً.

{/* Active indicator */}
البريد النشط حالياً {activeEmailSession}
{/* Email Pills List with local search to handle 20+ emails */}
{/* Real-time search inside the SSO Gateway */}
setSsoSearchQuery(e.target.value)} id="sso-email-search" className="bg-white/10 placeholder:text-sky-300 text-white text-[11px] px-3 py-1 rounded-xl focus:outline-none focus:bg-white focus:text-slate-900 border border-white/20 transition w-full sm:w-48 font-mono text-left" />
{sessionEmails .filter(mail => mail.toLowerCase().includes(ssoSearchQuery.toLowerCase())) .map((mail) => { const isSelected = mail.toLowerCase() === activeEmailSession.toLowerCase(); const linkedCount = accounts.filter(a => a.email.toLowerCase() === mail.toLowerCase()).length; const isDefault = mail === "eissaaly07@gmail.com" || mail === "eissaaly0007@gmail.com"; return (
{!isDefault && ( )}
); })} {sessionEmails.filter(mail => mail.toLowerCase().includes(ssoSearchQuery.toLowerCase())).length === 0 && (
لا توجد إيميلات مطابقة للبحث... أضف بريداً جديداً بالأسفل متاحاً لأي عدد!
)}
{/* Quick Utilities: Add Custom Email AND Auto Seeder */}
{/* Add Email Form */}
setNewSessionEmail(e.target.value)} className="bg-white/10 placeholder:text-sky-200 text-white border border-white/25 rounded-2xl px-4 py-2 text-xs focus:outline-none focus:bg-white focus:text-slate-900 flex-1 transition font-mono" />
{/* Auto platforms generator for current email */}
{/* Control Panel (Left) */}

كرت حساب جديد

setUsername(e.target.value)} className="bg-white border border-sky-200 rounded-xl px-4 py-2 text-xs text-slate-800 focus:outline-none focus:border-sky-500 w-full text-left font-semibold" />
setEmailVal(e.target.value)} className="bg-white border border-sky-200 rounded-xl px-4 py-2 text-xs text-slate-800 focus:outline-none focus:border-sky-500 w-full text-left font-semibold" />
setPassword(e.target.value)} className="bg-white border border-sky-200 rounded-xl px-4 py-2 text-xs text-slate-800 focus:outline-none focus:border-sky-500 w-full text-left" />
setTotpSecret(e.target.value)} className="bg-white border border-sky-200 rounded-xl px-4 py-2 text-xs text-slate-800 focus:outline-none focus:border-sky-500 w-full text-left font-mono" />
{/* Accounts List View (Right) */}
{/* Search bar */}
setSearchQuery(e.target.value)} className="bg-transparent text-xs text-slate-800 focus:outline-none w-full placeholder:text-slate-400" />
{/* Filter Toggle */} ظهر: {filteredAccounts.length} من {accounts.length}
{/* List display */} {filteredAccounts.map((a) => (

{a.platform}

@{a.username} جلسات نشطة: {a.activeSessions}

{a.email}

{a.password && (
الرمز: {visiblePassMap[a.id] ? a.password : "••••••••"}
)}
{/* Built-in TOTP token code widget */} {a.totpSecret ? (
المولّد الموحّد (2FA TOTP) {simulateTotpForSecret(a.totpSecret)}
{totpCountdown}s
) : (
لا يوجد كود مصادقة 2FA مسجل
)} {/* Quick action buttons */}
))} {filteredAccounts.length === 0 && (
لا توجد حسابات منصة مطابقة للبحث. يرجى تسجيل حساب لعرضه.
)}
); }