import { useState, useRef, useCallback, useEffect } from "react"; import { useQuery } from "@tanstack/react-query"; import { motion, AnimatePresence, useMotionValue, useTransform, PanInfo } from "framer-motion"; import { useLocation } from "wouter"; import { useAuth } from "@/lib/auth"; import { useWebSocket } from "@/hooks/use-websocket"; import { getIcon } from "@/lib/iconMap"; import { usePlatformLayout, PlatformSwitch } from "@/hooks/use-platform-layout"; import { useHaptics } from "@/hooks/use-haptics"; import { useMobileNative } from "@/hooks/use-mobile-native"; import * as dataService from "@/lib/data-service"; import * as tauriNative from "@/lib/tauri-native"; import { isDesktop } from "@/lib/platform"; import { useNativeFeatures } from "@/hooks/use-native-features"; import { useBiometricAuth } from "@/hooks/use-biometric-auth"; import { StatusBar, Style } from '@capacitor/status-bar'; import { MobileQuickActions } from "@/components/MobileQuickActions"; import { Minesweeper } from "@/components/games/Minesweeper"; import { CookieClicker } from "@/components/games/CookieClicker"; import { Terminal, FileText, IdCard, Music, Settings, Globe, X, Minus, Square, Maximize2, Volume2, Wifi, Battery, ChevronUp, FolderOpen, Award, MessageCircle, Send, ExternalLink, User, LogOut, BarChart3, Loader2, Layers, Presentation, Bell, Image, Monitor, Play, Pause, ChevronRight, Network, Activity, Code2, Radio, Newspaper, Gamepad2, Users, Trophy, Calculator, StickyNote, Cpu, Camera, Eye, Shield, Zap, Skull, Lock, Unlock, Server, Database, TrendingUp, ArrowUp, ArrowDown, Hash, Key, HardDrive, FolderSearch, AlertTriangle, Briefcase, CalendarDays, FolderGit2, MessageSquare, ShoppingCart, Folder, Code, Home, Flag, Cookie, ChevronLeft, MoreVertical, Search, Mic, ArrowLeft, RefreshCw, Star, Clock, MapPin, Target, Check, Save, Download, FileCode } from "lucide-react"; interface WindowState { id: string; title: string; icon: React.ReactNode; component: string; x: number; y: number; width: number; height: number; minimized: boolean; maximized: boolean; zIndex: number; accentColor?: string; desktopId: number; iframeUrl?: string; } interface Toast { id: string; message: string; type: 'info' | 'success' | 'warning' | 'error'; } interface ThemeSettings { mode: 'dark' | 'light' | 'system'; accentColor: string; transparency: number; } interface DesktopLayout { name: string; windows: Array<{ appId: string; x: number; y: number; width: number; height: number }>; desktop: number; } const ACCENT_COLORS = [ { id: 'cyan', name: 'Cyan', color: '#06b6d4', ring: 'ring-cyan-400/50', shadow: 'shadow-cyan-500/20', bg: 'bg-cyan-500' }, { id: 'purple', name: 'Purple', color: '#a855f7', ring: 'ring-purple-400/50', shadow: 'shadow-purple-500/20', bg: 'bg-purple-500' }, { id: 'green', name: 'Green', color: '#22c55e', ring: 'ring-green-400/50', shadow: 'shadow-green-500/20', bg: 'bg-green-500' }, { id: 'orange', name: 'Orange', color: '#f97316', ring: 'ring-orange-400/50', shadow: 'shadow-orange-500/20', bg: 'bg-orange-500' }, { id: 'pink', name: 'Pink', color: '#ec4899', ring: 'ring-pink-400/50', shadow: 'shadow-pink-500/20', bg: 'bg-pink-500' }, { id: 'red', name: 'Red', color: '#ef4444', ring: 'ring-red-400/50', shadow: 'shadow-red-500/20', bg: 'bg-red-500' }, ]; type ClearanceMode = 'foundation' | 'corp'; interface ClearanceTheme { id: ClearanceMode; name: string; title: string; subtitle: string; primary: string; secondary: string; accent: string; accentSecondary: string; wallpaper: string; borderStyle: string; fontStyle: string; } const DAILY_TIPS = [ { title: "Quick Launch", tip: "Press Ctrl+Space to open Spotlight search and quickly find apps." }, { title: "Virtual Desktops", tip: "Use the numbered buttons (1-4) in the taskbar to switch between virtual desktops." }, { title: "Window Management", tip: "Double-click a window title bar to maximize/restore it." }, { title: "Keyboard Shortcuts", tip: "Ctrl+T opens Terminal, Ctrl+S opens Settings, Ctrl+F opens Files." }, { title: "Theme Switching", tip: "Click the Start menu and use 'Switch Clearance' to change between Foundation and Corp modes." }, { title: "Sound Settings", tip: "Toggle system sounds in Settings to enable audio feedback for actions." }, { title: "Dock Apps", tip: "Your most-used apps are pinned to the quick-launch dock for easy access." }, { title: "Right-Click Menu", tip: "Right-click on the desktop to access quick options like refresh and settings." }, { title: "Calculator", tip: "Need quick math? Open Calculator from the app menu or dock." }, { title: "Notifications", tip: "Click the bell icon in the taskbar to view system notifications." }, ]; const PINNED_APPS = ['terminal', 'networkneighborhood', 'calculator', 'settings']; const CLEARANCE_THEMES: Record = { foundation: { id: 'foundation', name: 'The Foundation', title: 'FOUNDATION', subtitle: 'The Architect\'s Domain', primary: '#DC2626', secondary: '#D4AF37', accent: '#DC2626', accentSecondary: '#D4AF37', wallpaper: 'radial-gradient(ellipse at 30% 20%, #4a1515 0%, #1a0505 40%, #0a0202 100%)', borderStyle: 'border-yellow-600/40', fontStyle: 'font-mono', }, corp: { id: 'corp', name: 'The Corp', title: 'CORPORATION', subtitle: 'Executive Operations', primary: '#0F172A', secondary: '#C0C0C0', accent: '#3B82F6', accentSecondary: '#C0C0C0', wallpaper: 'radial-gradient(ellipse at 70% 80%, #1e3a5f 0%, #0f172a 40%, #050a14 100%)', borderStyle: 'border-slate-400/30', fontStyle: 'font-sans', }, }; interface DesktopApp { id: string; title: string; icon: React.ReactNode; component: string; defaultWidth: number; defaultHeight: number; } interface ContextMenuState { x: number; y: number; type: 'desktop' | 'icon'; appId?: string; } const WALLPAPERS = [ { id: 'default', name: 'Cyber Grid', bg: 'linear-gradient(to bottom right, #0f172a, #1e1b4b, #0f172a)', secret: false }, { id: 'matrix', name: 'Matrix', bg: 'linear-gradient(to bottom, #001100, #002200, #001100)', secret: false }, { id: 'sunset', name: 'Neon Sunset', bg: 'linear-gradient(to bottom, #1a0533, #4a1942, #0f172a)', secret: false }, { id: 'ocean', name: 'Deep Ocean', bg: 'linear-gradient(to bottom, #0a1628, #0d3b66, #0a1628)', secret: false }, { id: 'vaporwave', name: '⚡ Vaporwave', bg: 'linear-gradient(135deg, #ff71ce, #01cdfe, #05ffa1, #b967ff)', secret: true }, { id: 'bloodmoon', name: '🔥 Blood Moon', bg: 'linear-gradient(to bottom, #1a0000, #4a0000, #1a0000)', secret: true }, { id: 'galaxy', name: '🌌 Galaxy', bg: 'radial-gradient(ellipse at center, #1b2735 0%, #090a0f 100%)', secret: true }, ]; const KONAMI_CODE = ['ArrowUp', 'ArrowUp', 'ArrowDown', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'ArrowLeft', 'ArrowRight', 'b', 'a']; export default function AeThexOS() { const layout = usePlatformLayout(); const { impact, notification } = useHaptics(); const { keyboardVisible, deviceInfo } = useMobileNative('dark'); const native = useNativeFeatures(); const biometric = useBiometricAuth(); // Skip boot sequence on mobile const [isBooting, setIsBooting] = useState(!layout.isMobile); const [bootProgress, setBootProgress] = useState(0); const [bootStep, setBootStep] = useState(''); const [windows, setWindows] = useState([]); const [activeWindowId, setActiveWindowId] = useState(null); const [maxZIndex, setMaxZIndex] = useState(1); const [showStartMenu, setShowStartMenu] = useState(false); const [time, setTime] = useState(new Date()); const [contextMenu, setContextMenu] = useState(null); const [wallpaper, setWallpaper] = useState(WALLPAPERS[0]); const [soundEnabled, setSoundEnabled] = useState(false); const [showScreensaver, setShowScreensaver] = useState(false); const [notifications, setNotifications] = useState([]); const [showNotifications, setShowNotifications] = useState(false); const [secretsUnlocked, setSecretsUnlocked] = useState(false); const [konamiProgress, setKonamiProgress] = useState([]); const [toasts, setToasts] = useState([]); const [showSpotlight, setShowSpotlight] = useState(false); const [spotlightQuery, setSpotlightQuery] = useState(''); const [currentDesktop, setCurrentDesktop] = useState(0); const [showOnboarding, setShowOnboarding] = useState(false); const [onboardingStep, setOnboardingStep] = useState(0); const [desktopIcons, setDesktopIcons] = useState([]); const [theme, setTheme] = useState(() => { const saved = localStorage.getItem('aethex-theme'); return saved ? JSON.parse(saved) : { mode: 'dark', accentColor: 'cyan', transparency: 80 }; }); const [savedLayouts, setSavedLayouts] = useState(() => { const saved = localStorage.getItem('aethex-layouts'); return saved ? JSON.parse(saved) : []; }); const [clearanceMode, setClearanceMode] = useState(() => { const saved = localStorage.getItem('aethex-clearance'); return (saved as ClearanceMode) || 'foundation'; }); const [isSwitchingClearance, setIsSwitchingClearance] = useState(false); const [showDailyTip, setShowDailyTip] = useState(false); const [dailyTip, setDailyTip] = useState(DAILY_TIPS[0]); const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 }); const audioContextRef = useRef(null); const clearanceTheme = CLEARANCE_THEMES[clearanceMode]; const desktopRef = useRef(null); const idleTimer = useRef(null); const spotlightRef = useRef(null); const { user, isAuthenticated, logout } = useAuth(); const [, setLocation] = useLocation(); const [activeTrayPanel, setActiveTrayPanel] = useState<'wifi' | 'volume' | 'battery' | 'notifications' | 'upgrade' | null>(null); const [volume, setVolume] = useState(75); const [isMuted, setIsMuted] = useState(false); // WebSocket connection for real-time updates const { connected: wsConnected, metrics: wsMetrics, alerts: wsAlerts, achievements: wsAchievements, notifications: wsNotifications } = useWebSocket(); const [batteryInfo, setBatteryInfo] = useState<{ level: number; charging: boolean } | null>(null); useEffect(() => { let battery: any = null; let levelChangeHandler: (() => void) | null = null; let chargingChangeHandler: (() => void) | null = null; if ('getBattery' in navigator) { (navigator as any).getBattery().then((bat: any) => { battery = bat; setBatteryInfo({ level: Math.round(battery.level * 100), charging: battery.charging }); levelChangeHandler = () => { setBatteryInfo(prev => prev ? { ...prev, level: Math.round(battery.level * 100) } : null); }; chargingChangeHandler = () => { setBatteryInfo(prev => prev ? { ...prev, charging: battery.charging } : null); }; battery.addEventListener('levelchange', levelChangeHandler); battery.addEventListener('chargingchange', chargingChangeHandler); }); } // Cleanup: remove battery event listeners to prevent memory leak return () => { if (battery) { if (levelChangeHandler) battery.removeEventListener('levelchange', levelChangeHandler); if (chargingChangeHandler) battery.removeEventListener('chargingchange', chargingChangeHandler); } }; }, []); const { data: weatherData, isFetching: weatherFetching } = useQuery({ queryKey: ['weather'], queryFn: async () => { const res = await fetch('https://api.open-meteo.com/v1/forecast?latitude=40.7128&longitude=-74.0060¤t_weather=true&temperature_unit=fahrenheit'); return res.json(); }, refetchInterval: 600000, staleTime: 300000, }); const addToast = useCallback((message: string, type: Toast['type'] = 'info') => { const id = Date.now().toString(); setToasts(prev => [...prev, { id, message, type }]); setTimeout(() => setToasts(prev => prev.filter(t => t.id !== id)), 4000); }, []); useEffect(() => { localStorage.setItem('aethex-theme', JSON.stringify(theme)); }, [theme]); useEffect(() => { localStorage.setItem('aethex-layouts', JSON.stringify(savedLayouts)); }, [savedLayouts]); useEffect(() => { localStorage.setItem('aethex-clearance', clearanceMode); }, [clearanceMode]); useEffect(() => { const handleMouseMove = (e: MouseEvent) => { setMousePosition({ x: e.clientX, y: e.clientY }); }; window.addEventListener('mousemove', handleMouseMove); return () => window.removeEventListener('mousemove', handleMouseMove); }, []); const [showLoginPrompt, setShowLoginPrompt] = useState(false); const [isDesktopLocked, setIsDesktopLocked] = useState(true); const [detectedIdentity, setDetectedIdentity] = useState<{ username?: string; passportId?: string } | null>(null); const [threatLevel, setThreatLevel] = useState<'scanning' | 'low' | 'medium' | 'high'>('scanning'); const [bootLogs, setBootLogs] = useState([]); useEffect(() => { const bootSequence = async () => { const addLog = (text: string) => setBootLogs(prev => [...prev.slice(-8), text]); // Phase 1: Hardware initialization const phase1 = [ { text: 'POST: Power-On Self Test...', progress: 3 }, { text: 'CPU: AMD Ryzen 9 7950X3D @ 4.2GHz... OK', progress: 5 }, { text: 'RAM: 64GB DDR5-6000 ECC... OK', progress: 8 }, { text: 'GPU: Quantum Accelerator v2.1... OK', progress: 10 }, { text: 'NVME: AeThex Vault 2TB... OK', progress: 12 }, ]; for (const step of phase1) { setBootStep(step.text); addLog(step.text); setBootProgress(step.progress); await new Promise(r => setTimeout(r, 150)); } // Phase 2: Kernel & filesystem const phase2 = [ { text: 'Loading AeThex Kernel v4.2.1...', progress: 18 }, { text: 'Initializing virtual memory manager...', progress: 22 }, { text: 'Mounting encrypted file systems...', progress: 26 }, { text: 'Loading device drivers...', progress: 30 }, ]; for (const step of phase2) { setBootStep(step.text); addLog(step.text); setBootProgress(step.progress); await new Promise(r => setTimeout(r, 200)); } // Phase 3: Passport Identity Detection setBootStep('INITIATING AETHEX PASSPORT SUBSYSTEM...'); addLog('▸ PASSPORT: Initializing identity subsystem...'); setBootProgress(35); await new Promise(r => setTimeout(r, 300)); // Check for existing session/identity let foundIdentity = false; try { // Use auth context instead of API call for desktop compatibility if (user) { foundIdentity = true; setDetectedIdentity({ username: user.email?.split('@')[0] || 'User', passportId: user.id?.slice(0, 8).toUpperCase() }); addLog(`▸ PASSPORT: Identity token detected`); setBootStep('PASSPORT: IDENTITY TOKEN DETECTED'); setBootProgress(40); await new Promise(r => setTimeout(r, 300)); addLog(`▸ PASSPORT: Verifying credentials for ${sessionData.user.username}...`); setBootStep(`Verifying credentials for ${sessionData.user.username}...`); setBootProgress(45); await new Promise(r => setTimeout(r, 400)); addLog(`▸ PASSPORT: Welcome back, ARCHITECT ${sessionData.user.username.toUpperCase()}`); setBootStep(`WELCOME BACK, ARCHITECT ${sessionData.user.username.toUpperCase()}`); setBootProgress(50); await new Promise(r => setTimeout(r, 500)); } } catch (err) { // Session fetch failed, continue with guest mode if (import.meta.env.DEV) console.debug('[Boot] Session check failed:', err); } if (!foundIdentity) { addLog('▸ PASSPORT: No active identity token found'); setBootStep('PASSPORT: NO ACTIVE IDENTITY TOKEN'); setBootProgress(42); await new Promise(r => setTimeout(r, 300)); addLog('▸ PASSPORT: Guest access mode available'); setBootStep('Guest access mode available'); setBootProgress(48); await new Promise(r => setTimeout(r, 300)); } // Phase 4: Aegis Security Layer addLog('▸ AEGIS: Initializing security layer...'); setBootStep('AEGIS: INITIALIZING SECURITY LAYER...'); setBootProgress(55); await new Promise(r => setTimeout(r, 300)); addLog('▸ AEGIS: Loading threat detection modules...'); setBootStep('Loading threat detection modules...'); setBootProgress(60); await new Promise(r => setTimeout(r, 250)); addLog('▸ AEGIS: Scanning network perimeter...'); setBootStep('AEGIS: SCANNING NETWORK PERIMETER...'); setBootProgress(65); setThreatLevel('scanning'); await new Promise(r => setTimeout(r, 600)); // Simulate threat assessment result const threatResult = Math.random(); if (threatResult < 0.7) { setThreatLevel('low'); addLog('▸ AEGIS: Threat level LOW - All systems nominal'); setBootStep('THREAT LEVEL: LOW - ALL SYSTEMS NOMINAL'); } else if (threatResult < 0.95) { setThreatLevel('medium'); addLog('▸ AEGIS: Threat level MEDIUM - Enhanced monitoring active'); setBootStep('THREAT LEVEL: MEDIUM - MONITORING ACTIVE'); } else { setThreatLevel('high'); addLog('▸ AEGIS: Threat level ELEVATED - Defensive protocols engaged'); setBootStep('THREAT LEVEL: ELEVATED - PROTOCOLS ENGAGED'); } // Schedule upgrade alert in system tray once per session try { const shown = localStorage.getItem('aethex-upgrade-alert-shown'); if (!shown) { setTimeout(() => { try { if (!localStorage.getItem('aethex-upgrade-alert-shown')) { setActiveTrayPanel('upgrade'); addToast('⚠️ Architect Access Available — Use tray to upgrade', 'info'); localStorage.setItem('aethex-upgrade-alert-shown', 'true'); } } catch (err) { if (import.meta.env.DEV) console.debug('[Boot] localStorage access failed:', err); } }, 30000); } } catch (err) { if (import.meta.env.DEV) console.debug('[Boot] Upgrade check failed:', err); } setBootProgress(75); await new Promise(r => setTimeout(r, 400)); // Phase 5: Network & Final addLog('▸ NEXUS: Connecting to AeThex network...'); setBootStep('Connecting to Nexus network...'); setBootProgress(82); await new Promise(r => setTimeout(r, 300)); addLog('▸ NEXUS: Syncing with distributed nodes...'); setBootStep('Syncing with distributed nodes...'); setBootProgress(88); await new Promise(r => setTimeout(r, 250)); addLog('▸ NEXUS: Connection established - 42 peers online'); setBootStep('NEXUS: 42 PEERS ONLINE'); setBootProgress(94); await new Promise(r => setTimeout(r, 200)); addLog('▸ SYSTEM: AeThex OS ready'); setBootStep('AETHEX OS READY'); setBootProgress(100); await new Promise(r => setTimeout(r, 500)); setShowLoginPrompt(true); }; bootSequence(); }, []); useEffect(() => { const timer = setInterval(() => setTime(new Date()), 1000); return () => clearInterval(timer); }, []); useEffect(() => { const fetchNotifications = async () => { try { if (user) { const data = await dataService.fetchNotifications(user.id); if (Array.isArray(data)) { setNotifications(data.map((n: any) => n.message)); } } } catch (err) { // Notifications fetch failed, not critical if (import.meta.env.DEV) console.debug('[OS] Notifications fetch failed:', err); } }; fetchNotifications(); const interval = setInterval(fetchNotifications, 60000); return () => clearInterval(interval); }, []); // Listen for system tray quick action events // TEMPORARILY DISABLED FOR DEBUGGING /* useEffect(() => { if (!isDesktop()) return; let unlisten: (() => void) | null = null; const setupListener = async () => { try { const tauriEvent = await import('@tauri-apps/api/event'); unlisten = await tauriEvent.listen('open-app', (event: any) => { const appName = event.payload as string; const appMap: Record = { 'projects': 'Files', 'terminal': 'Terminal', 'achievements': 'Achievements' }; const appToOpen = appMap[appName] || appName; const existingApp = openApps.find((a: any) => a.name === appToOpen); if (!existingApp) { handleLaunchApp(appToOpen); } else { setActiveApp(appToOpen); } }); } catch (err) { // Not on desktop, ignore console.debug('[OS] Tray listener not available:', err); } }; setupListener(); return () => { if (unlisten) { unlisten(); } }; }, [handleLaunchApp, openApps, setActiveApp]); */ useEffect(() => { const resetIdle = () => { if (showScreensaver) setShowScreensaver(false); if (idleTimer.current) clearTimeout(idleTimer.current); idleTimer.current = setTimeout(() => setShowScreensaver(true), 5 * 60 * 1000); }; window.addEventListener('mousemove', resetIdle); window.addEventListener('keydown', resetIdle); resetIdle(); return () => { window.removeEventListener('mousemove', resetIdle); window.removeEventListener('keydown', resetIdle); if (idleTimer.current) clearTimeout(idleTimer.current); }; }, [showScreensaver]); useEffect(() => { const handleKonami = (e: KeyboardEvent) => { setKonamiProgress(prev => { const newProgress = [...prev, e.key].slice(-10); if (newProgress.length === 10 && newProgress.every((k, i) => k === KONAMI_CODE[i])) { setSecretsUnlocked(true); setNotifications(prev => ['🎮 SECRETS UNLOCKED! Check Settings for new wallpapers.', ...prev]); return []; } return newProgress; }); }; const handleTerminalUnlock = () => { setSecretsUnlocked(true); setNotifications(prev => ['🔓 Terminal unlock activated! Check Settings.', ...prev]); }; window.addEventListener('keydown', handleKonami); window.addEventListener('aethex-unlock-secrets', handleTerminalUnlock); return () => { window.removeEventListener('keydown', handleKonami); window.removeEventListener('aethex-unlock-secrets', handleTerminalUnlock); }; }, []); useEffect(() => { if (showSpotlight && spotlightRef.current) { spotlightRef.current.focus(); } }, [showSpotlight]); useEffect(() => { const saved = localStorage.getItem('aethex-window-positions'); if (saved) { try { const positions = JSON.parse(saved); setWindows(prev => prev.map(w => { const savedPos = positions[w.id]; return savedPos ? { ...w, ...savedPos } : w; })); } catch (err) { // Corrupted localStorage data, ignore and use defaults if (import.meta.env.DEV) console.debug('[OS] Failed to restore window positions:', err); } } const hasVisited = localStorage.getItem('aethex-visited'); if (!hasVisited) { setShowOnboarding(true); localStorage.setItem('aethex-visited', 'true'); } }, []); useEffect(() => { if (windows.length > 0) { const positions: Record = {}; windows.forEach(w => { positions[w.id] = { x: w.x, y: w.y, width: w.width, height: w.height }; }); localStorage.setItem('aethex-window-positions', JSON.stringify(positions)); } }, [windows]); const foundationApps: DesktopApp[] = [ { id: "networkneighborhood", title: "Network Neighborhood", icon: , component: "networkneighborhood", defaultWidth: 500, defaultHeight: 450 }, { id: "mission", title: "README.TXT", icon: , component: "mission", defaultWidth: 500, defaultHeight: 500 }, { id: "passport", title: "Passport", icon: , component: "passport", defaultWidth: 650, defaultHeight: 500 }, { id: "achievements", title: "Achievements", icon: , component: "achievements", defaultWidth: 800, defaultHeight: 600 }, { id: "projects", title: "Projects", icon: , component: "projects", defaultWidth: 900, defaultHeight: 650 }, { id: "opportunities", title: "Opportunities", icon: , component: "opportunities", defaultWidth: 850, defaultHeight: 650 }, { id: "events", title: "Events", icon: , component: "events", defaultWidth: 900, defaultHeight: 650 }, { id: "messaging", title: "Messages", icon: , component: "messaging", defaultWidth: 850, defaultHeight: 600 }, { id: "marketplace", title: "Marketplace", icon: , component: "marketplace", defaultWidth: 900, defaultHeight: 650 }, { id: "foundry", title: "FOUNDRY.EXE", icon: , component: "foundry", defaultWidth: 450, defaultHeight: 500 }, { id: "intel", title: "INTEL", icon: , component: "intel", defaultWidth: 550, defaultHeight: 450 }, { id: "filemanager", title: "File Manager", icon: , component: "filemanager", defaultWidth: 800, defaultHeight: 600 }, { id: "codegallery", title: "Code Gallery", icon: , component: "codegallery", defaultWidth: 900, defaultHeight: 650 }, { id: "drives", title: "My Computer", icon: , component: "drives", defaultWidth: 450, defaultHeight: 400 }, { id: "chat", title: "AeThex AI", icon: , component: "chat", defaultWidth: 400, defaultHeight: 500 }, { id: "terminal", title: "Terminal", icon: , component: "terminal", defaultWidth: 750, defaultHeight: 500 }, { id: "notifications", title: "Notifications", icon: , component: "notifications", defaultWidth: 700, defaultHeight: 600 }, { id: "analytics", title: "Analytics", icon: , component: "analytics", defaultWidth: 1000, defaultHeight: 700 }, { id: "metrics", title: "System Status", icon: , component: "metrics", defaultWidth: 750, defaultHeight: 550 }, { id: "devtools", title: "Dev Tools", icon: , component: "devtools", defaultWidth: 450, defaultHeight: 400 }, { id: "music", title: "Radio AeThex", icon: , component: "music", defaultWidth: 400, defaultHeight: 350 }, { id: "codeeditor", title: "The Lab", icon: , component: "codeeditor", defaultWidth: 700, defaultHeight: 500 }, { id: "arcade", title: "Snake", icon: , component: "arcade", defaultWidth: 420, defaultHeight: 520 }, { id: "minesweeper", title: "Minesweeper", icon: , component: "minesweeper", defaultWidth: 400, defaultHeight: 500 }, { id: "cookieclicker", title: "Cookie Clicker", icon: , component: "cookieclicker", defaultWidth: 420, defaultHeight: 600 }, { id: "calculator", title: "Calculator", icon: , component: "calculator", defaultWidth: 320, defaultHeight: 450 }, { id: "settings", title: "Settings", icon: , component: "settings", defaultWidth: 550, defaultHeight: 500 }, ]; const corpApps: DesktopApp[] = [ { id: "networkneighborhood", title: "Network Neighborhood", icon: , component: "networkneighborhood", defaultWidth: 500, defaultHeight: 450 }, { id: "mission", title: "README.TXT", icon: , component: "mission", defaultWidth: 500, defaultHeight: 500 }, { id: "passport", title: "Passport", icon: , component: "passport", defaultWidth: 650, defaultHeight: 500 }, { id: "achievements", title: "Achievements", icon: , component: "achievements", defaultWidth: 800, defaultHeight: 600 }, { id: "projects", title: "Projects", icon: , component: "projects", defaultWidth: 900, defaultHeight: 650 }, { id: "opportunities", title: "Opportunities", icon: , component: "opportunities", defaultWidth: 850, defaultHeight: 650 }, { id: "events", title: "Events", icon: , component: "events", defaultWidth: 900, defaultHeight: 650 }, { id: "messaging", title: "Messages", icon: , component: "messaging", defaultWidth: 850, defaultHeight: 600 }, { id: "marketplace", title: "Marketplace", icon: , component: "marketplace", defaultWidth: 900, defaultHeight: 650 }, { id: "foundry", title: "FOUNDRY.EXE", icon: , component: "foundry", defaultWidth: 450, defaultHeight: 500 }, { id: "intel", title: "INTEL", icon: , component: "intel", defaultWidth: 550, defaultHeight: 450 }, { id: "filemanager", title: "File Manager", icon: , component: "filemanager", defaultWidth: 800, defaultHeight: 600 }, { id: "codegallery", title: "Code Gallery", icon: , component: "codegallery", defaultWidth: 900, defaultHeight: 650 }, { id: "drives", title: "My Computer", icon: , component: "drives", defaultWidth: 450, defaultHeight: 400 }, { id: "devtools", title: "Dev Tools", icon: , component: "devtools", defaultWidth: 450, defaultHeight: 400 }, { id: "notifications", title: "Notifications", icon: , component: "notifications", defaultWidth: 700, defaultHeight: 600 }, { id: "analytics", title: "Analytics", icon: , component: "analytics", defaultWidth: 1000, defaultHeight: 700 }, { id: "metrics", title: "System Status", icon: , component: "metrics", defaultWidth: 750, defaultHeight: 550 }, { id: "network", title: "Global Ops", icon: , component: "network", defaultWidth: 700, defaultHeight: 550 }, { id: "files", title: "Asset Library", icon: , component: "files", defaultWidth: 700, defaultHeight: 500 }, { id: "pitch", title: "Contracts", icon: , component: "pitch", defaultWidth: 500, defaultHeight: 400 }, { id: "sysmonitor", title: "Infrastructure", icon: , component: "sysmonitor", defaultWidth: 450, defaultHeight: 400 }, { id: "leaderboard", title: "Performance", icon: , component: "leaderboard", defaultWidth: 500, defaultHeight: 550 }, { id: "calculator", title: "Calculator", icon: , component: "calculator", defaultWidth: 320, defaultHeight: 450 }, { id: "settings", title: "Settings", icon: , component: "settings", defaultWidth: 550, defaultHeight: 500 }, ]; const apps = clearanceMode === 'foundation' ? foundationApps : corpApps; // Handle WebSocket notifications useEffect(() => { if (wsNotifications && wsNotifications.length > 0) { wsNotifications.forEach((notification: any) => { if (notification.message) { addToast(notification.message, notification.type || 'info'); } }); } }, [wsNotifications]); // Handle WebSocket alerts for admins useEffect(() => { if (user?.isAdmin && wsAlerts && wsAlerts.length > 0) { const newAlertMessages = wsAlerts.map((alert: any) => `[AEGIS] ${alert.severity?.toUpperCase()}: ${alert.message}` ); setNotifications(prev => [...new Set([...newAlertMessages, ...prev])].slice(0, 10)); } }, [wsAlerts, user?.isAdmin]); // Show WebSocket connection status useEffect(() => { if (wsConnected && !isBooting) { addToast('Real-time connection established', 'success'); } }, [wsConnected, isBooting]); const playSound = useCallback((type: 'open' | 'close' | 'minimize' | 'click' | 'notification' | 'switch') => { if (!soundEnabled) return; try { if (!audioContextRef.current) { audioContextRef.current = new AudioContext(); } const ctx = audioContextRef.current; const oscillator = ctx.createOscillator(); const gainNode = ctx.createGain(); oscillator.connect(gainNode); gainNode.connect(ctx.destination); const sounds: Record = { open: { freq: 523, duration: 0.1, type: 'sine' }, close: { freq: 392, duration: 0.1, type: 'sine' }, minimize: { freq: 330, duration: 0.08, type: 'sine' }, click: { freq: 800, duration: 0.03, type: 'square' }, notification: { freq: 880, duration: 0.15, type: 'sine' }, switch: { freq: 440, duration: 0.2, type: 'sawtooth' }, }; const sound = sounds[type] || sounds.click; oscillator.type = sound.type; oscillator.frequency.setValueAtTime(sound.freq, ctx.currentTime); gainNode.gain.setValueAtTime(0.1, ctx.currentTime); gainNode.gain.exponentialRampToValueAtTime(0.01, ctx.currentTime + sound.duration); oscillator.start(ctx.currentTime); oscillator.stop(ctx.currentTime + sound.duration); } catch (e) { console.log('Audio not available'); } }, [soundEnabled]); const switchClearance = useCallback(() => { const newMode: ClearanceMode = clearanceMode === 'foundation' ? 'corp' : 'foundation'; setIsSwitchingClearance(true); setShowStartMenu(false); playSound('switch'); setTimeout(() => { setClearanceMode(newMode); setIsSwitchingClearance(false); addToast(`Switched to ${CLEARANCE_THEMES[newMode].name}`, 'success'); }, 600); }, [clearanceMode, addToast, playSound]); const openApp = useCallback((app: DesktopApp) => { const appToOpen = (isDesktopLocked && app.id !== 'passport') ? apps.find(a => a.id === 'passport') || app : app; playSound('open'); const existingWindow = windows.find(w => w.id === appToOpen.id); if (existingWindow) { setWindows(prev => prev.map(w => w.id === appToOpen.id ? { ...w, minimized: false, zIndex: maxZIndex + 1, desktopId: currentDesktop } : w )); setMaxZIndex(prev => prev + 1); setActiveWindowId(appToOpen.id); return; } const offsetX = (windows.length % 5) * 40 + 100; const offsetY = (windows.length % 5) * 40 + 50; const newWindow: WindowState = { id: appToOpen.id, title: appToOpen.title, icon: appToOpen.icon, component: appToOpen.component, x: offsetX, y: offsetY, width: appToOpen.defaultWidth, height: appToOpen.defaultHeight, minimized: false, maximized: false, zIndex: maxZIndex + 1, desktopId: currentDesktop }; setWindows(prev => [...prev, newWindow]); setMaxZIndex(prev => prev + 1); setActiveWindowId(appToOpen.id); setShowStartMenu(false); }, [windows, maxZIndex, playSound, currentDesktop, isDesktopLocked, apps]); const closeWindow = useCallback((id: string) => { playSound('close'); setWindows(prev => prev.filter(w => w.id !== id)); if (activeWindowId === id) setActiveWindowId(null); }, [activeWindowId, playSound]); const minimizeWindow = useCallback((id: string) => { playSound('minimize'); setWindows(prev => prev.map(w => w.id === id ? { ...w, minimized: true } : w)); }, [playSound]); const toggleMaximize = useCallback((id: string) => { setWindows(prev => prev.map(w => w.id === id ? { ...w, maximized: !w.maximized } : w)); }, []); const focusWindow = useCallback((id: string) => { setWindows(prev => prev.map(w => w.id === id ? { ...w, zIndex: maxZIndex + 1 } : w)); setMaxZIndex(prev => prev + 1); setActiveWindowId(id); }, [maxZIndex]); const handleDesktopClick = (e: React.MouseEvent) => { setShowStartMenu(false); setContextMenu(null); }; const handleDesktopContextMenu = (e: React.MouseEvent) => { e.preventDefault(); setContextMenu({ x: e.clientX, y: e.clientY, type: 'desktop' }); }; const handleIconContextMenu = (e: React.MouseEvent, appId: string) => { e.preventDefault(); e.stopPropagation(); setContextMenu({ x: e.clientX, y: e.clientY, type: 'icon', appId }); }; const handleWindowSnap = useCallback((id: string, x: number, y: number, width: number, height: number) => { const screenWidth = window.innerWidth; const screenHeight = window.innerHeight - 48; if (x <= 10) { setWindows(prev => prev.map(w => w.id === id ? { ...w, x: 0, y: 0, width: screenWidth / 2, height: screenHeight } : w)); return true; } if (x + width >= screenWidth - 10) { setWindows(prev => prev.map(w => w.id === id ? { ...w, x: screenWidth / 2, y: 0, width: screenWidth / 2, height: screenHeight } : w)); return true; } if (y <= 10) { setWindows(prev => prev.map(w => w.id === id ? { ...w, x: 0, y: 0, width: screenWidth, height: screenHeight, maximized: true } : w)); return true; } return false; }, []); const handleLogout = async () => { await logout(); setLocation("/"); }; useEffect(() => { const handleGlobalKeys = (e: KeyboardEvent) => { if ((e.metaKey || e.ctrlKey) && e.key === ' ') { e.preventDefault(); setShowSpotlight(prev => !prev); setSpotlightQuery(''); } if (e.key === 'Escape') { setShowSpotlight(false); setShowStartMenu(false); setContextMenu(null); } if ((e.metaKey || e.ctrlKey) && !e.shiftKey) { const shortcuts: Record = { 't': 'terminal', 'n': 'notes', 'e': 'codeeditor', 'p': 'passport', 'm': 'metrics' }; if (shortcuts[e.key]) { e.preventDefault(); const app = apps.find(a => a.id === shortcuts[e.key]); if (app) openApp(app); } } if ((e.metaKey || e.ctrlKey) && e.key >= '1' && e.key <= '4') { e.preventDefault(); setCurrentDesktop(parseInt(e.key) - 1); addToast(`Switched to Desktop ${e.key}`, 'info'); } }; window.addEventListener('keydown', handleGlobalKeys); return () => window.removeEventListener('keydown', handleGlobalKeys); }, [apps, openApp, addToast]); const renderAppContent = (component: string) => { switch (component) { case 'terminal': return ; case 'passport': return ; case 'files': return ; case 'network': return ; case 'metrics': return ; case 'codeeditor': return ; case 'newsfeed': return ; case 'arcade': return ; case 'minesweeper': return ; case 'cookieclicker': return ; case 'profiles': return ; case 'leaderboard': return ; case 'calculator': return ; case 'notes': return ; case 'sysmonitor': return ; case 'webcam': return ; case 'achievements': return ; case 'projects': return ; case 'opportunities': return ; case 'events': return ; case 'messaging': return ; case 'marketplace': return ; case 'chat': return ; case 'music': return ; case 'pitch': return setLocation('/pitch')} />; case 'networkneighborhood': return ; case 'foundry': return ; case 'devtools': return ; case 'mission': return ; case 'intel': return ; case 'filemanager': return ; case 'codegallery': return ; case 'notifications': return ; case 'analytics': return ; case 'drives': return ; case 'iframe': return null; case 'settings': return { const layout: DesktopLayout = { name, windows: windows.map(w => ({ appId: w.component, x: w.x, y: w.y, width: w.width, height: w.height })), desktop: currentDesktop, }; setSavedLayouts(prev => [...prev.filter(l => l.name !== name), layout]); addToast(`Layout "${name}" saved`, 'success'); }} onLoadLayout={(layout) => { setWindows([]); setTimeout(() => { layout.windows.forEach((w, i) => { const app = apps.find(a => a.component === w.appId); if (app) { const windowId = `${app.id}-${Date.now()}-${i}`; setWindows(prev => [...prev, { id: windowId, title: app.title, icon: app.icon, component: app.component, x: w.x, y: w.y, width: w.width, height: w.height, minimized: false, maximized: false, zIndex: i + 1, desktopId: layout.desktop }]); } }); setCurrentDesktop(layout.desktop); addToast(`Layout "${layout.name}" loaded`, 'success'); }, 100); }} onDeleteLayout={(name) => { setSavedLayouts(prev => prev.filter(l => l.name !== name)); addToast(`Layout "${name}" deleted`, 'info'); }} />; default: return null; } }; const handleGuestContinue = () => { setShowLoginPrompt(false); setIsBooting(false); setIsDesktopLocked(false); const randomTip = DAILY_TIPS[Math.floor(Math.random() * DAILY_TIPS.length)]; setDailyTip(randomTip); setTimeout(() => setShowDailyTip(true), 1000); }; const handleLoginFromBoot = () => { setShowLoginPrompt(false); setIsBooting(false); // Keep desktop locked until login succeeds const randomTip = DAILY_TIPS[Math.floor(Math.random() * DAILY_TIPS.length)]; setDailyTip(randomTip); setTimeout(() => { setShowDailyTip(true); const passportApp = apps.find(a => a.id === 'passport'); if (passportApp) openApp(passportApp); }, 500); }; const unlockDesktop = () => { setIsDesktopLocked(false); }; const openIframeWindow = (url: string, title: string) => { // Most external sites block iframe embedding - open in new tab instead window.open(url, '_blank', 'noopener,noreferrer'); }; // ========== ALL HOOKS MUST BE CALLED BEFORE ANY CONDITIONAL RETURNS ========== // Motion values for mobile gestures and desktop parallax (framer-motion hooks) const dragX = useMotionValue(0); const dragOpacity = useTransform(dragX, [-200, 0, 200], [0.5, 1, 0.5]); // Parallax calculations for desktop background const parallaxX = (mousePosition.x / window.innerWidth - 0.5) * 10; const parallaxY = (mousePosition.y / window.innerHeight - 0.5) * 10; // Hide system navigation bar on mount (Android only) useEffect(() => { if (!layout.isMobile) return; const setupStatusBar = async () => { try { await StatusBar.hide(); if ((window as any).NavigationBar) { await (window as any).NavigationBar.backgroundColorByHexString('#00000000', false); await (window as any).NavigationBar.hide(); } document.documentElement.style.setProperty('--safe-area-inset-bottom', 'env(safe-area-inset-bottom)'); } catch (error) { console.log('StatusBar not available on this platform'); } }; setupStatusBar(); return () => { StatusBar.show().catch(() => {}); }; }, [layout.isMobile]); // ========== END OF HOOKS - Conditional returns can happen after this point ========== if (isBooting) { const threatColors = { scanning: 'text-cyan-400', low: 'text-green-400', medium: 'text-yellow-400', high: 'text-red-400' }; const threatBgColors = { scanning: 'bg-cyan-500/20 border-cyan-500/50', low: 'bg-green-500/20 border-green-500/50', medium: 'bg-yellow-500/20 border-yellow-500/50', high: 'bg-red-500/20 border-red-500/50' }; return (
{/* Scan lines overlay */}
{/* CRT flicker effect */} {/* Vignette effect */}
{/* Left side - Boot logs */}
System Log
{bootLogs.map((log, i) => ( {log} ))}
{/* Threat Level Indicator */}
Aegis Status
{threatLevel === 'scanning' ? 'SCANNING...' : `THREAT: ${threatLevel.toUpperCase()}`}
{/* Center - Main boot display */}
{/* Logo with glow */}
A
{/* Current step with typing effect */} {bootStep} _ {/* Progress bar */}
BOOT SEQUENCE {bootProgress}%
{/* Detected identity badge */} {detectedIdentity && ( {detectedIdentity.username} • ID:{detectedIdentity.passportId} )}
AeThex OS v4.2.1 • Aegis Security Layer Active
{showLoginPrompt && (
{detectedIdentity ? `IDENTITY VERIFIED • THREAT LEVEL: ${threatLevel.toUpperCase()}` : `SYSTEM READY • THREAT LEVEL: ${threatLevel.toUpperCase()}` }
{detectedIdentity ? `Enter as ${detectedIdentity.username}` : 'Login with Passport'} {!detectedIdentity && ( Continue as Guest )}
)}
{/* Right side - System specs (hidden on mobile) */}
System Info
BUILD: 2025.12.21
KERNEL: 4.2.1-aethex
ARCH: x86_64
NEXUS NETWORK
Peers: 42 online
Latency: 12ms
PASSPORT
{detectedIdentity ? 'Token: VALID' : 'Token: NONE'}
Mode: {detectedIdentity ? 'ARCHITECT' : 'GUEST'}
); } if (showScreensaver) { return (
setShowScreensaver(false)} >
AeThex
Click to wake
); } // Native Android App Layout if (layout.isMobile) { const activeWindows = windows.filter(w => !w.minimized); const currentWindow = activeWindows[activeWindows.length - 1]; return (
{/* Ingress Status Bar - Minimal */}
{[...Array(4)].map((_, i) => (
))}
{batteryInfo?.level || 100}% {time.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
{/* Main Content */}
{currentWindow ? ( // Fullscreen App View with 3D Card Flip {/* Ingress Style - Minimal App Bar */}

{currentWindow.title}

{/* App Content */}
{renderAppContent(currentWindow.component)}
) : ( // ULTRA FUTURISTIC LAUNCHER {/* Ingress Style Search Bar */}
impact('light')} />
{/* App Grid - Hexagonal */}

Quick Access

{apps.slice(0, 8).map((app) => ( ))}
{/* All Apps - Minimal List */}

All Systems

{apps.slice(8).map((app) => ( ))}
)}
{/* INGRESS STYLE NAVIGATION BAR - Lightweight */}
{/* Floating Action Button with Orbital Menu */}
); } console.log('🖥️ [OS] Rendering DESKTOP layout (isMobile=false)'); // Desktop/Web layout return (
{apps.slice(0, 9).map((app) => ( openApp(app)} onContextMenu={(e) => handleIconContextMenu(e, app.id)} /> ))}
{isDesktopLocked && windows.length === 0 && (

Desktop Locked

Sign in with your Passport to continue

)} {windows.filter(w => !w.minimized && w.desktopId === currentDesktop).map((window) => ( closeWindow(window.id)} onMinimize={() => minimizeWindow(window.id)} onMaximize={() => toggleMaximize(window.id)} onFocus={() => focusWindow(window.id)} onMove={(x, y) => setWindows(prev => prev.map(w => w.id === window.id ? { ...w, x, y } : w))} onResize={(width, height) => setWindows(prev => prev.map(w => w.id === window.id ? { ...w, width, height } : w))} onSnap={(x, y) => handleWindowSnap(window.id, x, y, window.width, window.height)} content={window.component === 'iframe' && window.iframeUrl ? (