import React, { useState, useEffect } from "react"; import { HardDrive, Folder, Image as ImageIcon, MessageSquare, Sparkles, Pin, Trash2, Download, RefreshCw, AlertTriangle, CheckCircle2, X, User, LogOut, FileText, ExternalLink, ShieldCheck, Cloud, Database, UploadCloud, Key, Code2, Zap, Search, CheckSquare, Square, Trash, AlertOctagon, Clock, Info, CreditCard, Check, Crown, ChevronRight, Send, Users, Sliders, Award, Layers, Copy, Smartphone, Settings, Volume2, Sun, Palette, FolderTree, FileCode, Compass, MapPin, Globe, Terminal, Activity, CheckCircle, ToggleLeft, ToggleRight, Sparkle, Cpu, BookOpen } from "lucide-react"; import { TIER_CONFIGS, SubscriptionTier } from "../types/subscription"; import { AURA_THEMES, AuraTheme } from "../types/theme"; export interface DataaiFileItem { name: string; relativePath: string; hfStoragePath: string; sizeBytes: number; sizeFormatted: string; updatedAt: string; category: "users" | "chats" | "media" | "config" | "system"; isDir: boolean; } function formatBytes(bytes: number): string { if (!bytes || bytes < 0) return "0 B"; if (bytes < 1024) return `${bytes} B`; if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; return `${(bytes / (1024 * 1024)).toFixed(2)} MB`; } interface StoredItem { id: string; name: string; folder: "media storage" | "chats" | "generated media" | "pinned chats"; sizeBytes: number; sizeFormatted: string; updatedAt: string; relativePath: string; dataUrl?: string; metadata?: any; } interface UpgradeRequest { id: string; username: string; requestedTier: string; amount: number; paymentMethod: string; transactionId: string; phoneNumber?: string; note?: string; status: "pending" | "approved" | "declined"; createdAt: string; processedAt?: string; processedBy?: string; } interface UserSummary { id: string; username: string; tier: string; isAdmin: boolean; createdAt: string; lastLoginAt?: string; usedFormatted: string; maxFormatted: string; daysRemaining?: number; tierExpiresAtFormatted?: string; hasCustomGptAccess?: boolean; } interface AccountManagerModalProps { isOpen: boolean; onClose: () => void; currentUser: { id: string; username: string; createdAt?: string; tier?: string; token?: string; stats?: any; } | null; onSignOut: () => void; onRefreshUserStats: () => Promise; onSyncChats: () => Promise; onOpenAuraCodex?: () => void; // Settings & Voice Props selectedVoiceURI?: string; onSelectVoice?: (voiceURI: string) => void; auraThemeId?: string; onSelectAuraTheme?: (themeId: string) => void; autoThemeEnabled?: boolean; onToggleAutoTheme?: (enabled: boolean) => void; darkMode?: boolean; onToggleDarkMode?: (dark: boolean) => void; themeManualOverrideUntil?: number; initialTab?: "storage" | "dataai_explorer" | "subscriptions" | "my_requests" | "admin_console" | "settings"; // Accuracy & Google AI Features Props accuracyMode?: "perfect" | "balanced" | "fast"; onSelectAccuracyMode?: (mode: "perfect" | "balanced" | "fast") => void; isOxfordContextActive?: boolean; onToggleOxfordContext?: (active: boolean) => void; onOpenOxfordModal?: () => void; googleSearchGrounding?: boolean; onToggleGoogleSearchGrounding?: (enabled: boolean) => void; googleMapsGrounding?: boolean; onToggleGoogleMapsGrounding?: (enabled: boolean) => void; fastFlashAccelerator?: boolean; onToggleFastFlashAccelerator?: (enabled: boolean) => void; googleCodeExecution?: boolean; onToggleGoogleCodeExecution?: (enabled: boolean) => void; firebaseEnabled?: boolean; onToggleFirebaseEnabled?: (enabled: boolean) => void; understandingMode?: string; onSelectUnderstandingMode?: (mode: string) => void; customApiKey?: string; onUpdateCustomApiKey?: (key: string) => void; } export default function AccountManagerModal({ isOpen, onClose, currentUser, onSignOut, onRefreshUserStats, onSyncChats, onOpenAuraCodex, selectedVoiceURI = "", onSelectVoice, auraThemeId = "aura-nebula", onSelectAuraTheme, autoThemeEnabled = true, onToggleAutoTheme, darkMode = true, onToggleDarkMode, themeManualOverrideUntil = 0, initialTab = "subscriptions", accuracyMode = "perfect", onSelectAccuracyMode, isOxfordContextActive = false, onToggleOxfordContext, onOpenOxfordModal, googleSearchGrounding = false, onToggleGoogleSearchGrounding, googleMapsGrounding = false, onToggleGoogleMapsGrounding, fastFlashAccelerator = true, onToggleFastFlashAccelerator, googleCodeExecution = false, onToggleGoogleCodeExecution, firebaseEnabled = false, onToggleFirebaseEnabled, understandingMode = "ultra-precision", onSelectUnderstandingMode, customApiKey = "", onUpdateCustomApiKey }: AccountManagerModalProps) { // Navigation Tabs: storage | dataai_explorer | subscriptions | my_requests | admin_console | settings const isHarshaAdmin = currentUser?.username?.toLowerCase() === "harsha" || currentUser?.stats?.isAdmin; const [activeTab, setActiveTab] = useState<"storage" | "dataai_explorer" | "subscriptions" | "my_requests" | "admin_console" | "settings">(initialTab); const getAuthHeaders = () => { return currentUser?.token ? { "X-Aura-Auth": currentUser.token } : {}; }; useEffect(() => { if (initialTab) { setActiveTab(initialTab); } }, [initialTab]); // Speech Synthesis Voices State const [voices, setVoices] = useState([]); useEffect(() => { if (!("speechSynthesis" in window)) return; const updateVoices = () => { const available = window.speechSynthesis.getVoices(); setVoices(available || []); }; updateVoices(); window.speechSynthesis.onvoiceschanged = updateVoices; return () => { if ("speechSynthesis" in window) { window.speechSynthesis.onvoiceschanged = null; } }; }, []); const handleTestVoice = (voiceURI?: string) => { if (!("speechSynthesis" in window)) { alert("Speech Synthesis is not supported in this browser."); return; } window.speechSynthesis.cancel(); const testUtterance = new SpeechSynthesisUtterance("Hello! I am Aura AI, speaking with your chosen voice."); if (voiceURI && voices.length > 0) { const selected = voices.find(v => v.voiceURI === voiceURI || v.name === voiceURI); if (selected) testUtterance.voice = selected; } testUtterance.rate = 1; testUtterance.pitch = 1; window.speechSynthesis.speak(testUtterance); }; // Password Change State const [currentPasswordInput, setCurrentPasswordInput] = useState(""); const [newPasswordInput, setNewPasswordInput] = useState(""); const [confirmPasswordInput, setConfirmPasswordInput] = useState(""); const [passwordStatusMsg, setPasswordStatusMsg] = useState<{ success: boolean; text: string } | null>(null); const [isSubmittingPassword, setIsSubmittingPassword] = useState(false); const handleChangePasswordSubmit = async (e: React.FormEvent) => { e.preventDefault(); setPasswordStatusMsg(null); if (!currentPasswordInput || !newPasswordInput) { setPasswordStatusMsg({ success: false, text: "Please enter both current and new password." }); return; } if (newPasswordInput !== confirmPasswordInput) { setPasswordStatusMsg({ success: false, text: "New password and confirmation do not match." }); return; } if (newPasswordInput.length < 6) { setPasswordStatusMsg({ success: false, text: "New password must be at least 6 characters long." }); return; } setIsSubmittingPassword(true); try { const res = await fetch("/api/auth/change-password", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ username: currentUser?.username, currentPassword: currentPasswordInput, newPassword: newPasswordInput }) }); const data = await res.json(); if (data.success) { setPasswordStatusMsg({ success: true, text: data.message || "Password updated successfully!" }); setCurrentPasswordInput(""); setNewPasswordInput(""); setConfirmPasswordInput(""); } else { setPasswordStatusMsg({ success: false, text: data.error || "Failed to update password." }); } } catch (err: any) { setPasswordStatusMsg({ success: false, text: err.message || "Network error updating password." }); } finally { setIsSubmittingPassword(false); } }; // Storage Tab States const [activeFolder, setActiveFolder] = useState<"all" | "media storage" | "chats" | "generated media" | "pinned chats">("all"); const [items, setItems] = useState([]); const [stats, setStats] = useState(currentUser?.stats || null); const [loading, setLoading] = useState(false); const [deletingId, setDeletingId] = useState(null); const [bulkDeleting, setBulkDeleting] = useState(false); const [syncing, setSyncing] = useState(false); const [actionMessage, setActionMessage] = useState(null); const [previewItem, setPreviewItem] = useState(null); // Search & Bulk Selection State const [searchQuery, setSearchQuery] = useState(""); const [selectedItemIds, setSelectedItemIds] = useState>(new Set()); // Custom Modal Confirmation Dialogs const [confirmDeleteModal, setConfirmDeleteModal] = useState<{ itemsToDelete: StoredItem[] } | null>(null); const [confirmHfModal, setConfirmHfModal] = useState<{ action: "pull" | "push" } | null>(null); // Hugging Face Persistence State const [hfStatus, setHfStatus] = useState(null); const [hfSyncing, setHfSyncing] = useState(false); const [showHfTokenModal, setShowHfTokenModal] = useState(false); const [customHfToken, setCustomHfToken] = useState(""); const [customHfRepo, setCustomHfRepo] = useState(""); // DataAI Explorer & Hugging Face Bucket State const [dataaiFiles, setDataaiFiles] = useState([]); const [loadingDataai, setLoadingDataai] = useState(false); const [selectedDataaiFile, setSelectedDataaiFile] = useState(null); const [selectedFileContent, setSelectedFileContent] = useState(null); const [selectedFileContentType, setSelectedFileContentType] = useState("text/plain"); const [loadingFileContent, setLoadingFileContent] = useState(false); const [dataaiSearch, setDataaiSearch] = useState(""); const [dataaiFilter, setDataaiFilter] = useState<"all" | "users" | "chats" | "media" | "config">("all"); const [hfTestLoading, setHfTestLoading] = useState(false); const [hfTestResult, setHfTestResult] = useState(null); // Subscriptions & Usage Limits State const [usageData, setUsageData] = useState(null); const [loadingUsage, setLoadingUsage] = useState(false); const [upgradeModalTier, setUpgradeModalTier] = useState(null); const [paymentMethodTab, setPaymentMethodTab] = useState<"gpay" | "razorpay">("gpay"); const [transactionIdInput, setTransactionIdInput] = useState(""); const [copiedGpay, setCopiedGpay] = useState(false); const [copiedUpiId, setCopiedUpiId] = useState(false); const [isSubmittingTxn, setIsSubmittingTxn] = useState(false); const [paymentSuccessMsg, setPaymentSuccessMsg] = useState(null); // My Requests State const [myRequests, setMyRequests] = useState([]); const [loadingMyRequests, setLoadingMyRequests] = useState(false); // Admin Console State (Harsha) const [adminRequests, setAdminRequests] = useState([]); const [adminUsers, setAdminUsers] = useState([]); const [loadingAdminData, setLoadingAdminData] = useState(false); const [adminUserSearch, setAdminUserSearch] = useState(""); const [changingTierUser, setChangingTierUser] = useState<{ username: string; tier: string } | null>(null); // Fetch Storage Items const fetchItems = async () => { if (!currentUser) return; setLoading(true); try { const res = await fetch(`/api/aura-store/items?username=${encodeURIComponent(currentUser.username)}&token=${encodeURIComponent(currentUser.token || "")}`); const data = await res.json(); if (data.success) { setItems(data.items || []); if (data.stats) { setStats(data.stats); } } } catch (e) { console.error("Failed to load Aura Store items:", e); } finally { setLoading(false); } }; // Fetch Usage & Limits const fetchUsage = async () => { const uname = currentUser?.username || localStorage.getItem("aura_user_name") || ""; setLoadingUsage(true); try { const res = await fetch(`/api/subscriptions/usage?username=${encodeURIComponent(uname)}`); const data = await res.json(); if (data.success) { setUsageData(data); } } catch (e) { console.error("Failed to load usage data:", e); } finally { setLoadingUsage(false); } }; // Fetch User's Own Upgrade Requests const fetchMyRequests = async () => { if (!currentUser) return; setLoadingMyRequests(true); try { const res = await fetch(`/api/subscriptions/my-requests?username=${encodeURIComponent(currentUser.username)}`); const data = await res.json(); if (data.success) { setMyRequests(data.requests || []); } } catch (e) { console.error("Failed to load my requests:", e); } finally { setLoadingMyRequests(false); } }; // Fetch Admin Requests & Users const fetchAdminData = async () => { if (!currentUser || !isHarshaAdmin) return; setLoadingAdminData(true); try { const [reqsRes, usersRes] = await Promise.all([ fetch(`/api/subscriptions/admin-requests?adminUsername=${encodeURIComponent(currentUser.username)}`), fetch(`/api/subscriptions/admin-users?adminUsername=${encodeURIComponent(currentUser.username)}`) ]); const reqsData = await reqsRes.json(); const usersData = await usersRes.json(); if (reqsData.success) setAdminRequests(reqsData.requests || []); if (usersData.success) setAdminUsers(usersData.users || []); } catch (e) { console.error("Failed to load admin data:", e); } finally { setLoadingAdminData(false); } }; const fetchHfStatus = async () => { try { const res = await fetch("/api/aura-store/hf-sync-status"); const data = await res.json(); if (data.success) { setHfStatus(data); if (data.repo) setCustomHfRepo(data.repo); } } catch (e) {} }; const fetchDataaiExplorer = async () => { setLoadingDataai(true); try { const res = await fetch(`/api/aura-store/dataai-explorer?username=${encodeURIComponent(currentUser.username)}&token=${encodeURIComponent(currentUser.token || "")}`); const data = await res.json(); if (data.success) { setDataaiFiles(data.files || []); if (data.files && data.files.length > 0) { // If none selected or current selection is not in list, select first setSelectedDataaiFile(prev => { const exists = prev ? data.files.some((f: any) => f.relativePath === prev.relativePath) : false; if (exists) return prev; handleSelectDataaiFile(data.files[0]); return data.files[0]; }); } else { setSelectedDataaiFile(null); setSelectedFileContent(""); } } } catch (e) { console.error("Failed to load cloud files:", e); } finally { setLoadingDataai(false); } }; const handleSelectDataaiFile = async (file: DataaiFileItem) => { setSelectedDataaiFile(file); setLoadingFileContent(true); try { const res = await fetch(`/api/aura-store/dataai-file?path=${encodeURIComponent(file.relativePath)}&username=${encodeURIComponent(currentUser.username)}&token=${encodeURIComponent(currentUser.token || "")}`); const data = await res.json(); if (data.success) { setSelectedFileContent(data.content); setSelectedFileContentType(data.contentType || "text/plain"); } else { setSelectedFileContent(`Error loading file: ${data.error}`); } } catch (e: any) { setSelectedFileContent(`Failed to read file from cloud storage: ${e.message}`); } finally { setLoadingFileContent(false); } }; const handleTestHfConnection = async () => { setHfTestLoading(true); setHfTestResult(null); try { const res = await fetch("/api/aura-store/hf-test-connection", { method: "POST", headers: { "Content-Type": "application/json", ...getAuthHeaders() }, body: JSON.stringify({ repo: customHfRepo.trim(), token: customHfToken.trim() }) }); const data = await res.json(); setHfTestResult(data); } catch (e: any) { setHfTestResult({ success: false, message: e.message || "Failed to test connection." }); } finally { setHfTestLoading(false); } }; useEffect(() => { if (isOpen && currentUser) { fetchItems(); fetchUsage(); fetchHfStatus(); if (activeTab === "dataai_explorer") fetchDataaiExplorer(); if (activeTab === "my_requests") fetchMyRequests(); if (activeTab === "admin_console" && isHarshaAdmin) fetchAdminData(); } }, [isOpen, currentUser, activeTab]); if (!isOpen || !currentUser) return null; // Single Item Delete Handler const requestDeleteSingle = (item: StoredItem) => { setConfirmDeleteModal({ itemsToDelete: [item] }); }; // Execute Deletion const executeDelete = async () => { if (!confirmDeleteModal || confirmDeleteModal.itemsToDelete.length === 0) return; const targets = confirmDeleteModal.itemsToDelete; setConfirmDeleteModal(null); if (targets.length === 1) { const item = targets[0]; setDeletingId(item.id); try { const res = await fetch("/api/aura-store/delete-item", { method: "POST", headers: { "Content-Type": "application/json", ...getAuthHeaders() }, body: JSON.stringify({ username: currentUser.username, folder: item.folder, fileName: item.name }) }); const data = await res.json(); if (data.success) { setActionMessage(`Deleted ${item.name}.`); setItems(prev => prev.filter(i => i.id !== item.id)); setSelectedItemIds(prev => { const next = new Set(prev); next.delete(item.id); return next; }); onRefreshUserStats(); fetchItems(); } else { setActionMessage(data.message || "Failed to delete item."); } } catch (e: any) { setActionMessage(e.message || "Delete request error."); } finally { setDeletingId(null); setTimeout(() => setActionMessage(null), 4000); } } else { setBulkDeleting(true); let successCount = 0; for (const item of targets) { try { const res = await fetch("/api/aura-store/delete-item", { method: "POST", headers: { "Content-Type": "application/json", ...getAuthHeaders() }, body: JSON.stringify({ username: currentUser.username, folder: item.folder, fileName: item.name }) }); const data = await res.json(); if (data.success) successCount++; } catch (e) {} } setActionMessage(`Reclaimed space: Deleted ${successCount} of ${targets.length} files.`); setBulkDeleting(false); setSelectedItemIds(new Set()); onRefreshUserStats(); fetchItems(); setTimeout(() => setActionMessage(null), 4000); } }; // Hugging Face Pull / Push Handlers const handleHfPull = async () => { setConfirmHfModal(null); setHfSyncing(true); setActionMessage("Pulling fresh data from Hugging Face bucket..."); try { const res = await fetch("/api/aura-store/hf-pull", { method: "POST", headers: { ...getAuthHeaders() } }); const data = await res.json(); if (data.success) { setActionMessage(`Synced ${data.filesDownloaded} files from Hugging Face bucket.`); fetchItems(); fetchHfStatus(); fetchDataaiExplorer(); onRefreshUserStats(); } else { setActionMessage(data.message || "Pull failed."); } } catch (e: any) { setActionMessage(e.message || "Error pulling from HF."); } finally { setHfSyncing(false); setTimeout(() => setActionMessage(null), 5000); } }; const handleHfPush = async () => { setConfirmHfModal(null); setHfSyncing(true); setActionMessage("Backing up all /dataai files to Hugging Face bucket..."); try { const res = await fetch("/api/aura-store/hf-push", { method: "POST", headers: { ...getAuthHeaders() } }); const data = await res.json(); if (data.success) { setActionMessage(`Backup complete: ${data.filesUploaded} files pushed to HF bucket.`); fetchHfStatus(); fetchDataaiExplorer(); } else { setActionMessage(data.message || "Push failed."); } } catch (e: any) { setActionMessage(e.message || "Error pushing to HF."); } finally { setHfSyncing(false); setTimeout(() => setActionMessage(null), 5000); } }; const handleSaveHfConfig = async () => { try { const res = await fetch("/api/aura-store/hf-config", { method: "POST", headers: { "Content-Type": "application/json", ...getAuthHeaders() }, body: JSON.stringify({ repo: customHfRepo.trim(), token: customHfToken.trim(), autoSync: true }) }); const data = await res.json(); if (data.success) { setShowHfTokenModal(false); fetchHfStatus(); fetchDataaiExplorer(); setActionMessage("Hugging Face dataset/bucket connection updated."); setTimeout(() => setActionMessage(null), 4000); } else { setActionMessage(data.message || "Failed to update HF configuration."); } } catch (e: any) { setActionMessage(e.message || "Failed to update HF configuration."); } }; // Submit UPI Upgrade Transaction const handleSubmitUpiTransaction = async () => { if (!upgradeModalTier || !transactionIdInput.trim()) { alert("Please enter a valid 12-digit UPI Transaction ID or UTR number."); return; } setIsSubmittingTxn(true); try { const tierConfig = TIER_CONFIGS[upgradeModalTier]; const res = await fetch("/api/upi/submit-transaction", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ username: currentUser.username, targetTier: upgradeModalTier, amount: tierConfig.priceINR, transactionId: transactionIdInput.trim(), phoneNumber: "9500076449", note: `Payment for ${tierConfig.name} on Google Pay (9500076449)` }) }); const data = await res.json(); if (data.success) { setPaymentSuccessMsg(`Upgrade request submitted! Txn ID: ${transactionIdInput.trim()}. Admin (Harsha) will verify and activate your tier.`); setTransactionIdInput(""); fetchUsage(); fetchMyRequests(); setTimeout(() => { setPaymentSuccessMsg(null); setUpgradeModalTier(null); }, 4000); } else { alert(data.error || "Failed to submit transaction."); } } catch (e: any) { alert(e.message || "Error submitting transaction."); } finally { setIsSubmittingTxn(false); } }; // Razorpay Checkout Handler const handleRazorpayPayment = async (tierKey: SubscriptionTier) => { const tierConfig = TIER_CONFIGS[tierKey]; try { const orderRes = await fetch("/api/razorpay/create-order", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ username: currentUser.username, tier: tierKey, amount: tierConfig.priceINR * 100 // paise }) }); const orderData = await orderRes.json(); if (!orderData.success) { alert(orderData.error || "Failed to create payment order."); return; } // Simulate or trigger Razorpay Checkout const verifyRes = await fetch("/api/razorpay/verify-payment", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ username: currentUser.username, targetTier: tierKey, order_id: orderData.orderId, payment_id: `rzp_pay_${Date.now()}` }) }); const verifyData = await verifyRes.json(); if (verifyData.success) { setPaymentSuccessMsg(`Instant Upgrade Verified! Your account is now ${tierConfig.name}.`); onRefreshUserStats(); fetchUsage(); setTimeout(() => { setPaymentSuccessMsg(null); setUpgradeModalTier(null); }, 3000); } } catch (e: any) { alert(e.message || "Payment verification failed."); } }; // Admin: Approve Request const handleAdminApprove = async (requestId: string) => { try { const res = await fetch("/api/subscriptions/admin-approve", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ requestId, adminUsername: currentUser.username }) }); const data = await res.json(); if (data.success) { setActionMessage(data.message || "Request approved and tier updated!"); fetchAdminData(); onRefreshUserStats(); setTimeout(() => setActionMessage(null), 4000); } else { alert(data.error || "Failed to approve request."); } } catch (e: any) { alert(e.message || "Approval error."); } }; // Admin: Decline Request const handleAdminDecline = async (requestId: string) => { try { const res = await fetch("/api/subscriptions/admin-decline", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ requestId, adminUsername: currentUser.username }) }); const data = await res.json(); if (data.success) { setActionMessage(data.message || "Request declined."); fetchAdminData(); setTimeout(() => setActionMessage(null), 4000); } } catch (e: any) { alert(e.message || "Decline error."); } }; // Admin: Directly Set User Tier const handleAdminSetTier = async (targetUsername: string, newTier: string) => { try { const res = await fetch("/api/subscriptions/admin-set-tier", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ targetUsername, tier: newTier, days: 30, adminUsername: currentUser.username }) }); const data = await res.json(); if (data.success) { setActionMessage(`Updated ${targetUsername} to ${newTier.toUpperCase()} (30 days).`); setChangingTierUser(null); fetchAdminData(); setTimeout(() => setActionMessage(null), 4000); } } catch (e: any) { alert(e.message || "Failed to change user tier."); } }; // Copy helpers const handleCopyGpayNumber = () => { navigator.clipboard.writeText("9500076449"); setCopiedGpay(true); setTimeout(() => setCopiedGpay(false), 2500); }; const handleCopyUpiId = () => { navigator.clipboard.writeText("9500076449@okaxis"); setCopiedUpiId(true); setTimeout(() => setCopiedUpiId(false), 2500); }; // Storage Filtering const filteredItems = items.filter(item => { const matchesFolder = activeFolder === "all" || item.folder === activeFolder; const matchesSearch = searchQuery === "" || item.name.toLowerCase().includes(searchQuery.toLowerCase()); return matchesFolder && matchesSearch; }); const filteredDataaiFiles = dataaiFiles.filter(file => { const matchesSearch = !dataaiSearch.trim() || file.name.toLowerCase().includes(dataaiSearch.toLowerCase()) || file.relativePath.toLowerCase().includes(dataaiSearch.toLowerCase()); if (!matchesSearch) return false; if (dataaiFilter === "all") return true; return file.category === dataaiFilter; }); const activeTierKey = (currentUser.tier || stats?.tier || "free").toLowerCase(); const currentTierConfig = TIER_CONFIGS[activeTierKey as SubscriptionTier] || TIER_CONFIGS.free; return (
e.stopPropagation()} > {/* Top Header */}

@{currentUser.username}

{isHarshaAdmin ? "Admin Master" : currentTierConfig.name} {stats?.daysRemaining !== undefined && !isHarshaAdmin && activeTierKey !== "free" && ( {stats.daysRemaining} days left )}

{stats?.usedFormatted || "0 MB"} used of {stats?.maxFormatted || currentTierConfig.storageFormatted} Cloud Storage

{/* Navigation Bar */}
{isHarshaAdmin && ( )}
{/* Global Notification Banner */} {actionMessage && (
{actionMessage}
)} {/* TAB 1: SUBSCRIPTIONS & QUOTAS */} {activeTab === "subscriptions" && (
{/* Live Daily Quotas Tracker */}

Today's Daily Quotas & Usage

(Resets daily at 00:00 UTC)
{/* Chat Responses */}
Chat
{usageData?.usage?.chatResponses || 0} / {isHarshaAdmin ? "∞" : currentTierConfig.chatResponsesPerDay}
{/* AI Images */}
Images
{usageData?.usage?.images || 0} / {isHarshaAdmin ? "∞" : currentTierConfig.imageGenerationsPerDay}
{/* AI Music */}
Music
{usageData?.usage?.music || 0} / {isHarshaAdmin ? "∞" : currentTierConfig.musicGenerationsPerDay}
{/* Documents */}
Docs
{usageData?.usage?.documents || 0} / {isHarshaAdmin ? "∞" : currentTierConfig.documentsPerDay}
{/* Aura Codex */}
Codex
{usageData?.usage?.codexMessages || 0} / {isHarshaAdmin ? "∞" : currentTierConfig.auraCodexPerDay}
{/* Cloud Storage */}
Storage
{stats?.usedFormatted || "0 MB"} / {stats?.maxFormatted || currentTierConfig.storageFormatted}
{/* Subscription Tiers Pricing Grid */}

Upgrade Your Aura AI Membership

Unlock more daily responses, higher cloud storage, fast model fleets, and creative studios. Powered by Google Pay (9500076449) & Razorpay.

{/* 1. Free Signed-In */}
Free Account
₹0 / forever
  • 1.00 GB Cloud Storage
  • 50 Chat responses/day
  • 15 Image gens/day
  • 30 Music tracks/day
  • 50 Codex messages/day
  • Gemini 2.5, 3.5, 3.6 & GPT-5.4/5.5
{activeTierKey === "free" ? (
Current Active Plan
) : (
Included Default
)}
{/* 2. AuraPlus (₹20/mo) */}
AuraPlus Popular
₹20 / month
  • 2.00 GB Cloud Storage
  • 70 Chat responses/day
  • 20 Image gens/day
  • 50 Music tracks/day
  • 100 Codex messages/day
  • All Gemini Models + GPT-5.6 Luna
  • Auto-tune to index.html view
{activeTierKey === "auraplus" ? (
Active Plan
) : ( )}
{/* 3. AuraPro (₹50/mo) */}
AuraPro
₹50 / month
  • 3.00 GB Cloud Storage
  • 100 Chat responses/day
  • 30 Image gens/day
  • 60 Music tracks/day
  • 200 Codex messages/day
  • GPT-5.6 Terra & Qwen 2.5 Coder
  • Computer-Use Terminal Studio
{activeTierKey === "aurapro" ? (
Active Plan
) : ( )}
{/* 4. AuraMax (₹100/mo) */}
AuraMax Ultimate
₹100 / month
  • 5.00 GB Cloud Storage
  • 200 Chat responses/day
  • 50 Image gens/day
  • 100 Music tracks/day
  • 300 Codex messages/day
  • GPT-5.6 Sol + Full Model Fleet
  • Custom GPT Creator & Store
{activeTierKey === "auramax" ? (
Active Plan
) : ( )}
)} {/* TAB 2: CLOUD STORAGE & FILE MANAGER */} {activeTab === "storage" && (
{/* Sidebar Navigation */}
Folders (/dataai)
{/* User Private Storage Volume Banner */}
My Cloud Volume
Private

/dataai/{currentUser.username}/

{isHarshaAdmin && (
)}
{/* Main File Browser & Controls */}
{/* Search & Actions Bar */}
setSearchQuery(e.target.value)} className="w-full pl-8 pr-3 py-1.5 rounded-xl bg-slate-900 border border-slate-800 text-xs text-white placeholder:text-slate-400 focus:outline-none focus:border-indigo-500" />
{/* Bulk Actions */} {selectedItemIds.size > 0 && (
{selectedItemIds.size} selected
)}
{/* Items Table / List */}
{loading ? (
Reading /dataai storage...
) : filteredItems.length === 0 ? (

No items found in {activeFolder}

Chats, images, and audio will appear here automatically.

) : (
{filteredItems.map(item => { const isSelected = selectedItemIds.has(item.id); return (
{item.folder === "chats" || item.folder === "pinned chats" ? ( ) : ( )}

{item.name}

{item.folder} {item.sizeFormatted} • {new Date(item.updatedAt).toLocaleDateString()}
{item.dataUrl && ( )}
); })}
)}
)} {/* TAB: MY CLOUD FILES (/dataai/{username}/) */} {activeTab === "dataai_explorer" && (
{/* Top Summary & Control Ribbon */}

{isHarshaAdmin ? "Master Cloud Directory (/dataai)" : `@${currentUser.username}'s Cloud Storage`}

{isHarshaAdmin ? "Admin Master" : "User Isolated • Private"} Persistent Cloud
Path: /dataai/{isHarshaAdmin ? "" : `${currentUser.username}/`} • {dataaiFiles.length} private files ({formatBytes(dataaiFiles.reduce((acc, f) => acc + (f.sizeBytes || 0), 0))})
{isHarshaAdmin && ( <> )}
{/* Explorer Split Panes */}
{/* Left Pane: File Directory */}
{/* Search & Filter Toolbar */}
setDataaiSearch(e.target.value)} className="w-full pl-8 pr-3 py-1.5 rounded-xl bg-slate-900 border border-slate-800 text-xs text-white placeholder:text-slate-500 focus:outline-none focus:border-indigo-500" />
{(["all", "chats", "media", "users", "config"] as const).map(cat => ( ))}
{/* Files List */}
{loadingDataai ? (
Reading @{currentUser.username}'s cloud storage...
) : filteredDataaiFiles.length === 0 ? (

No files found in your cloud storage matching "{dataaiSearch}".

Start chatting or saving media to populate your account folder.

) : ( filteredDataaiFiles.map(file => { const isSelected = selectedDataaiFile?.relativePath === file.relativePath; return ( ); }) )}
{/* Right Pane: File Viewer & Inspector */}
{selectedDataaiFile ? ( <> {/* Viewer Header */}
/dataai/{selectedDataaiFile.relativePath}
Private File

Size: {selectedDataaiFile.sizeFormatted} • Last Modified: {new Date(selectedDataaiFile.updatedAt).toLocaleString()}

{/* Viewer Content */}
{loadingFileContent ? (
Reading /dataai/{selectedDataaiFile.relativePath}...
) : selectedFileContentType.startsWith("image/") ? (
{selectedDataaiFile.name} {selectedDataaiFile.name} ({selectedDataaiFile.sizeFormatted})
) : selectedFileContentType.startsWith("audio/") ? (
) : (
                          {selectedFileContent}
                        
)}
) : (
Select a file from your cloud folder

Click any file on the left to inspect its contents, size, and download or copy securely from your isolated storage.

)}
)} {/* TAB 3: MY UPGRADE REQUESTS */} {activeTab === "my_requests" && (

My Subscription Upgrade Requests

Track payment status and manual approvals from Admin (Harsha).

{loadingMyRequests ? (
) : myRequests.length === 0 ? (

No Upgrade Requests Yet

Upgrade to AuraPlus (₹20), AuraPro (₹50), or AuraMax (₹100) from the Plans tab.

) : (
{myRequests.map(req => (
{req.requestedTier} ₹{req.amount} {req.status === "approved" ? "Approved & Activated" : req.status === "declined" ? "Declined" : "Pending Admin Review"}
Txn: {req.transactionId} • Via: {req.paymentMethod === "google_pay" ? "Google Pay (9500076449)" : "Razorpay"} • Date: {new Date(req.createdAt).toLocaleString()}
{req.note &&

"{req.note}"

}
))}
)}
)} {/* TAB 4: ADMIN CONSOLE (HARSHA ONLY) */} {activeTab === "admin_console" && isHarshaAdmin && (

Harsha Master Admin Control Console

{/* Section A: Pending Upgrade Requests */}
Pending Payment Approvals ({adminRequests.filter(r => r.status === "pending").length})
{adminRequests.filter(r => r.status === "pending").length === 0 ? (

No pending upgrade requests. All user payments processed!

) : (
{adminRequests.filter(r => r.status === "pending").map(req => (
@{req.username} Upgrade to {req.requestedTier.toUpperCase()} ₹{req.amount}
Txn / UTR: {req.transactionId} • Phone: {req.phoneNumber || "9500076449"} • {new Date(req.createdAt).toLocaleString()}
))}
)}
{/* Section B: Manage All Registered Users */}
Registered Users & Tiers ({adminUsers.length})
setAdminUserSearch(e.target.value)} className="px-3 py-1 rounded-xl bg-slate-900 border border-slate-800 text-xs text-white placeholder:text-slate-400" />
{adminUsers .filter(u => adminUserSearch === "" || u.username.toLowerCase().includes(adminUserSearch.toLowerCase())) .map(u => (
@{u.username} {u.tier} {u.daysRemaining !== undefined && ( ({u.daysRemaining} days left) )}

Storage: {u.usedFormatted} / {u.maxFormatted} • Joined: {new Date(u.createdAt).toLocaleDateString()}

))}
)} {/* TAB 5: SETTINGS */} {activeTab === "settings" && (
{/* Header Banner */}

System, AI & Engine Settings

Configure cognitive accuracy, automatic day/night theme scheduling, voice synthesis, and connected Google AI features.

Sub-Second Flash Active
{/* Section 1: Accuracy Engine [99.999%] */}

Accuracy Engine

{accuracyMode === "perfect" ? "99.999% Factual Precision" : accuracyMode === "fast" ? "Fast Burst" : "Creative Balanced"}

Controls factual rigor, hallucination suppression, and deterministic verification across all chat responses.

{/* Section 2: Added Google AI Features */}

Google AI Connected Features & Tools

Gemini Grounding & Tools

Connect official Google intelligence engines into Aura Chat for real-time verification, geospatial intelligence, code execution, and flash streaming.

{/* Google Maps Data & Grounding */}
Google Maps Geospatial Data LIVE
Grounds answers with Google Maps places, addresses, routing directions, traffic, and points of interest.
{/* Google Search Real-Time Grounding */}
Google Search Live Grounding 2026 WEB
Fetches up-to-the-minute web information, current news, and verified factual citations.
{/* Google Fast-Flash Token Accelerator */}
Google Fast-Flash Accelerator 1-SEC BURST
Delivers instant streaming with zero artificial buffering for a flash of a second response speed.
{/* Google Code Sandbox & Python Execution */}
Google Code Execution Sandbox PYTHON
Executes live code in a sandboxed Python runtime for mathematical verification and computation.
{/* Firebase / Aura Store Persistent Mode */}
Firebase Persistence Mode STORE
Enables deep integration with Aura Store / Firebase for persistent cloud file management and historical session retrieval.
{/* Section 2.5: Oxford English Academic Knowledge Base */}

Oxford Knowledge Base

{isOxfordContextActive ? "100% LEXICAL ACTIVE" : "OFF"}

Grounds AI reasoning with academic English precision, verified lexical definitions, grammar mastery, and the complete Oxford English syllabus textbooks for Grades 6, 7, and 8.

Oxford Lexical & Syllabus Grounding
100% Academic & Lexical Precision across all conversations.
{onOpenOxfordModal && ( )}
{/* Section 3: Automatic Theme (Light at 6 AM, dark at 6 PM) */}

Automatic Theme (Light at 6 AM, Dark at 6 PM)

{autoThemeEnabled ? "SCHEDULE ACTIVE" : "MANUAL MODE"}

Automatically switches the visual interface between sunlight daytime clarity and eye-safe twilight darkness according to real-world circadian time.

Circadian Auto Theme Switcher
Light Mode at 6:00 AM ☀️ | Dark Mode at 6:00 PM 🌙
Current Mode: {darkMode ? "Dark Mode 🌙" : "Light Mode ☀️"}
Manual switch pauses circadian scheduling for 6 hours.
{/* Section 4: Aura Chat Theme */}

Aura Chat Theme

{AURA_THEMES.length} Themes Available

Choose a visual theme for Aura AI Chat. Dynamically colors the header, ambient glow, buttons, bubbles, and interactive surfaces.

{AURA_THEMES.map((theme) => { const isSelected = (auraThemeId || "aura-nebula") === theme.id; return ( ); })}
{/* Section 5: AI Voice Engine */}

AI Voice Engine

Auto-Detects Language & Best Voice

Configure voice synthesis for Live Voice Mode and spoken answers. Automatically detects user language and pairs the best natural neural voice.

{/* Section 6: Change Account Password & Security */} {currentUser && (

Change Account Password

Update security credentials for user @{currentUser.username}. Passwords must be at least 6 characters.

setCurrentPasswordInput(e.target.value)} placeholder="Enter current password" className="w-full px-3.5 py-2.5 rounded-xl bg-slate-900 border border-slate-700 text-xs text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-amber-500" required />
setNewPasswordInput(e.target.value)} placeholder="Enter new password (min. 6 characters)" className="w-full px-3.5 py-2.5 rounded-xl bg-slate-900 border border-slate-700 text-xs text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-amber-500" required />
setConfirmPasswordInput(e.target.value)} placeholder="Confirm new password" className="w-full px-3.5 py-2.5 rounded-xl bg-slate-900 border border-slate-700 text-xs text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-amber-500" required />
{passwordStatusMsg && (
{passwordStatusMsg.success ? : } {passwordStatusMsg.text}
)}
)}
)} {/* PAYMENT & UPGRADE MODAL */} {upgradeModalTier && (
setUpgradeModalTier(null)} >
e.stopPropagation()} >

Upgrade to {TIER_CONFIGS[upgradeModalTier].name}

{paymentSuccessMsg ? (

{paymentSuccessMsg}

) : (
{paymentMethodTab === "gpay" ? (
Google Pay Number:
9500076449
UPI ID:
9500076449@okaxis
Amount to Pay: ₹{TIER_CONFIGS[upgradeModalTier].priceINR}
setTransactionIdInput(e.target.value)} className="w-full px-3 py-2 rounded-xl bg-slate-950 border border-slate-800 text-white font-mono text-xs focus:outline-none focus:border-emerald-500" />

After paying on Google Pay to 9500076449, enter your UTR number above. Admin (Harsha) will verify and activate your tier!

) : (
Instant automated payment checkout via Razorpay for ₹{TIER_CONFIGS[upgradeModalTier].priceINR}.
)}
)}
)} {/* Custom Confirmation Modal for Hugging Face Pull / Push Safety */} {confirmHfModal && (
setConfirmHfModal(null)} >
e.stopPropagation()} >

{confirmHfModal.action === "pull" ? "Pull from Hugging Face Bucket" : "Backup to Hugging Face Bucket"}

{hfStatus?.repo || customHfRepo}

{confirmHfModal.action === "pull" ? ( <>

Overwrite Warning:

Pulling from Hugging Face will download the latest cloud snapshot and overwrite local storage files.

) : ( <>

Cloud Backup Confirmation:

This will upload all current Aura Store account databases, chats, and media files to your Hugging Face Dataset repository: {hfStatus?.repo || customHfRepo}.

)}
)} {/* Delete Confirmation Modal */} {confirmDeleteModal && (
setConfirmDeleteModal(null)} >
e.stopPropagation()} >

Confirm Deletion ({confirmDeleteModal.itemsToDelete.length} {confirmDeleteModal.itemsToDelete.length === 1 ? "file" : "files"})

Reclaim persistent storage space.

Are you sure you want to permanently delete {confirmDeleteModal.itemsToDelete.length === 1 ? ( {confirmDeleteModal.itemsToDelete[0].name} ) : ( these {confirmDeleteModal.itemsToDelete.length} selected items )}? This will reclaim storage from local /dataai and the Hugging Face dataset bucket.

)} {/* Media Preview Modal */} {previewItem && (
setPreviewItem(null)} >
e.stopPropagation()} >

{previewItem.name}

{previewItem.name.match(/\.(jpeg|jpg|gif|png|webp|svg)$/i) ? ( {previewItem.name} ) : (
{previewItem.relativePath}
)}
)} {/* Hugging Face Bucket & Token Configuration Modal */} {showHfTokenModal && (
setShowHfTokenModal(false)} >
e.stopPropagation()} >

HF Bucket & /dataai Storage

Configure your Hugging Face Bucket persistence

setCustomHfRepo(e.target.value)} placeholder="e.g. harshasri28/harshasri28-Aura-Ai" className="w-full px-3.5 py-2.5 rounded-xl bg-slate-950 border border-slate-800 text-white font-mono text-xs focus:outline-none focus:border-amber-500" />

Files from /dataai will automatically synchronize under the dataai/ folder in this bucket.

setCustomHfToken(e.target.value)} placeholder="hf_..." className="w-full px-3.5 py-2.5 rounded-xl bg-slate-950 border border-slate-800 text-white font-mono text-xs focus:outline-none focus:border-amber-500" />

Requires write permission to push files from /dataai to your dataset repository.

{/* Connection Test Result */} {hfTestResult && (
{hfTestResult.success ? ( ) : ( )} {hfTestResult.message}
{hfTestResult.storagePath && (
Local Root: {hfTestResult.storagePath}
HF Bucket Path: {hfTestResult.hfSubfolder}
{hfTestResult.repoType &&
Repo Type: {hfTestResult.repoType}
} {hfTestResult.authenticatedUser &&
HF User: {hfTestResult.authenticatedUser}
}
)}
)} {/* Test Connection & Action Buttons */}
)}
); }