import React, { useState, useEffect, useCallback } from 'react';
import {
  LayoutDashboard,
  ShieldAlert,
  Users,
  Settings,
  Lock,
  Activity,
  Network,
  Terminal,
  Server,
  Zap,
  Download,
  Plus,
  Trash2,
  Loader2,
  AlertCircle,
  LogOut,
  ChevronRight,
  Bell,
  Search,
  Database,
  MoreVertical,
  ArrowRightLeft,
  Key,
} from 'lucide-react';
import { VaultProvider, useVault } from './contexts/VaultContext';
import { LoginV2 } from './components/LoginV2';
import { Register } from './components/Register';
import { Profile } from './components/Profile';
import { RightsManagement } from './components/RightsManagement';
import { Players } from './components/Players';
import { Nodes } from './components/Nodes';
import { PlayerInsights } from './components/PlayerInsights';
import { PlayerContextMenu } from './components/PlayerContextMenu';
import { Button } from './components/ui/button';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from './components/ui/card';
import { Badge } from './components/ui/badge';
import { ScrollArea } from './components/ui/scroll-area';
import { Separator } from './components/ui/separator';
import { Avatar, AvatarFallback, AvatarImage } from './components/ui/avatar';
import { Input } from './components/ui/input';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
  DropdownMenuSeparator,
  DropdownMenuLabel,
} from "./components/ui/dropdown-menu";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "./components/ui/dialog";
import { cn, base64ToUint8Array, uint8ArrayToBase64 } from './lib/utils';

type Page = 'dashboard' | 'servers' | 'console' | 'players' | 'security' | 'rights' | 'profile' | 'nodes';

// ============================================================================
// SHARED COMPONENTS
// ============================================================================

const SidebarItem = ({
  icon: Icon, label, active = false, onClick,
}: { icon: any; label: string; active?: boolean; onClick?: () => void }) => (
  <button
    onClick={onClick}
    className={cn(
      "flex items-center w-full gap-3 px-3 py-2 rounded-lg transition-all duration-200 group text-sm font-medium",
      active
        ? "bg-primary/10 text-primary shadow-sm"
        : "text-muted-foreground hover:bg-accent hover:text-accent-foreground"
    )}
  >
    <Icon className={cn("w-4 h-4", active ? "text-primary" : "text-muted-foreground group-hover:text-accent-foreground")} />
    {label}
  </button>
);

const MetricCard = ({ label, value, unit, icon: Icon, color, trend }: any) => (
  <Card className="overflow-hidden relative group border-border/50 bg-card/50 backdrop-blur-sm">
    <div className={cn("absolute top-0 right-0 w-24 h-24 -mr-8 -mt-8 opacity-5 transition-all duration-500 group-hover:scale-110", color)}>
      <Icon className="w-full h-full" />
    </div>
    <CardHeader className="p-4 pb-2">
      <div className="flex justify-between items-start">
        <div className="p-2 w-fit bg-muted rounded-lg border border-border">
          <Icon className={cn("w-4 h-4", color)} />
        </div>
        {trend && (
          <span className={cn("text-[10px] font-bold px-1.5 py-0.5 rounded-full", trend > 0 ? "bg-emerald-500/10 text-emerald-500" : "bg-destructive/10 text-destructive")}>
            {trend > 0 ? '+' : ''}{trend}%
          </span>
        )}
      </div>
    </CardHeader>
    <CardContent className="p-4 pt-0 space-y-1">
      <CardDescription className="text-[10px] font-bold uppercase tracking-wider">{label}</CardDescription>
      <div className="flex items-baseline gap-1">
        <span className="text-2xl font-black tabular-nums">{value}</span>
        <span className="text-xs text-muted-foreground font-medium">{unit}</span>
      </div>
    </CardContent>
  </Card>
);

// ============================================================================
// SERVER MANAGEMENT PAGE
// ============================================================================

interface DevServer {
  id: string;
  name: string;
  description: string;
  workerId: string;
  storageId: string;
  encryptedRcon: string; // E2EE blob
  mockActive: boolean;
  createdAt: string;
}

interface DevNode {
  id: string;
  name: string;
  type: string;
  status: string;
}

const apiHeaders = () => ({
  'Content-Type': 'application/json',
  'Authorization': `Bearer ${localStorage.getItem('auth_token') ?? ''}`,
});

const EditServerDialog: React.FC<{
  server: DevServer | null;
  nodes: DevNode[];
  open: boolean;
  onOpenChange: (o: boolean) => void;
  onSave: () => void;
}> = ({ server, nodes, open, onOpenChange, onSave }) => {
  const { encrypt, decrypt } = useVault();
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState({
    name: '',
    description: '',
    workerId: '',
    storageId: '',
    rconAddress: '',
    rconPort: 2302,
    rconPass: '',
  });

  useEffect(() => {
    const loadEncryptedData = async () => {
      if (server) {
        let rconDetails = { address: '', port: 2302, pass: '' };
        
        if (server.encryptedRcon) {
          try {
            const decrypted = await decrypt(base64ToUint8Array(server.encryptedRcon));
            rconDetails = JSON.parse(decrypted);
          } catch (e) {
            console.error('Failed to decrypt RCON credentials', e);
          }
        }

        setFormData({
          name: server.name,
          description: server.description || '',
          workerId: server.workerId || '',
          storageId: server.storageId || '',
          rconAddress: rconDetails.address || '',
          rconPort: rconDetails.port || 2302,
          rconPass: '', // Keep pass hidden
        });
      }
    };
    
    if (open) loadEncryptedData();
  }, [server, open, decrypt]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!server) return;
    setLoading(true);
    try {
      // 1. Bundle RCON details
      const rconData = JSON.stringify({
        address: formData.rconAddress,
        port: formData.rconPort,
        pass: formData.rconPass || '', 
      });

      // 2. Encrypt with Community Master Key (E2EE)
      const encrypted = await encrypt(rconData);
      const encryptedBlob = uint8ArrayToBase64(encrypted);

      // 3. Transmit to backend
      const res = await fetch('/api/servers', {
        method: 'PUT',
        headers: apiHeaders(),
        body: JSON.stringify({ 
          id: server.id, 
          name: formData.name,
          description: formData.description,
          workerId: formData.workerId,
          storageId: formData.storageId,
          encryptedRcon: encryptedBlob 
        }),
      });
      if (!res.ok) throw new Error('Update failed');
      onSave();
      onOpenChange(false);
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  const workers = nodes.filter(n => n.type === 'worker');
  const storages = nodes.filter(n => n.type === 'storage');

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-xl bg-card border-border shadow-2xl">
        <DialogHeader>
          <DialogTitle className="text-xl font-black uppercase italic italic">Configure Operational Node</DialogTitle>
          <DialogDescription className="text-xs font-bold uppercase tracking-widest text-muted-foreground/60">
            Modify infrastructure assignment and security parameters
          </DialogDescription>
        </DialogHeader>

        <form onSubmit={handleSubmit} className="space-y-6 py-4">
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <label className="text-[10px] font-black uppercase tracking-widest text-muted-foreground/60">Server Designation</label>
              <Input value={formData.name} onChange={e => setFormData({...formData, name: e.target.value})} className="bg-background/50" />
            </div>
            <div className="space-y-2">
              <label className="text-[10px] font-black uppercase tracking-widest text-muted-foreground/60">Operational Desc</label>
              <Input value={formData.description} onChange={e => setFormData({...formData, description: e.target.value})} className="bg-background/50" />
            </div>
          </div>

          <div className="grid grid-cols-2 gap-4 pt-2 border-t border-border/20">
            <div className="space-y-2">
              <label className="text-[10px] font-black uppercase tracking-widest text-muted-foreground/60">Assigned Worker (Migration)</label>
              <select 
                value={formData.workerId} 
                onChange={e => setFormData({...formData, workerId: e.target.value})}
                className="w-full h-9 px-3 bg-background border border-border/50 rounded-md text-sm text-foreground focus:outline-none focus:ring-1 focus:ring-primary"
              >
                <option value="">No Worker Assigned</option>
                {workers.map(n => <option key={n.id} value={n.id}>{n.name} ({n.status})</option>)}
              </select>
            </div>
            <div className="space-y-2">
              <label className="text-[10px] font-black uppercase tracking-widest text-muted-foreground/60">Assigned Storage</label>
              <select 
                value={formData.storageId} 
                onChange={e => setFormData({...formData, storageId: e.target.value})}
                className="w-full h-9 px-3 bg-background border border-border/50 rounded-md text-sm text-foreground focus:outline-none focus:ring-1 focus:ring-primary"
              >
                <option value="">No Storage Assigned</option>
                {storages.map(n => <option key={n.id} value={n.id}>{n.name} ({n.status})</option>)}
              </select>
            </div>
          </div>

          <div className="space-y-4 pt-2 border-t border-border/20">
            <div className="flex items-center gap-2 text-primary font-black uppercase tracking-tighter text-sm">
               <Key className="w-4 h-4" />
               RCON Protocol Configuration
            </div>
            <div className="grid grid-cols-3 gap-3">
              <div className="col-span-2 space-y-2">
                <label className="text-[10px] font-black uppercase tracking-widest text-muted-foreground/60">Address</label>
                <Input placeholder="127.0.0.1" value={formData.rconAddress} onChange={e => setFormData({...formData, rconAddress: e.target.value})} className="bg-background/50" />
              </div>
              <div className="space-y-2">
                <label className="text-[10px] font-black uppercase tracking-widest text-muted-foreground/60">Port</label>
                <Input type="number" value={formData.rconPort} onChange={e => setFormData({...formData, rconPort: parseInt(e.target.value)})} className="bg-background/50" />
              </div>
            </div>
            <div className="space-y-2">
              <label className="text-[10px] font-black uppercase tracking-widest text-muted-foreground/60">Access Secret</label>
              <Input type="password" placeholder="Leave empty to keep current" value={formData.rconPass} onChange={e => setFormData({...formData, rconPass: e.target.value})} className="bg-background/50" />
            </div>
          </div>

          <DialogFooter className="pt-4">
             <Button type="button" variant="ghost" onClick={() => onOpenChange(false)}>Cancel</Button>
             <Button type="submit" disabled={loading}>
                {loading && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
                Commit Configuration
             </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
};

const ServersPage: React.FC = () => {
  const { encrypt } = useVault();
  const [servers, setServers] = useState<DevServer[]>([]);
  const [nodes, setNodes] = useState<DevNode[]>([]);
  const [loading, setLoading] = useState(true);
  const [newName, setNewName] = useState('');
  const [newDesc, setNewDesc] = useState('');
  const [newWorkerId, setNewWorkerId] = useState('');
  const [newStorageId, setNewStorageId] = useState('');
  const [newRconAddr, setNewRconAddr] = useState('');
  const [newRconPort, setNewRconPort] = useState(2302);
  const [newRconPass, setNewRconPass] = useState('');
  const [adding, setAdding] = useState(false);
  const [addError, setAddError] = useState<string | null>(null);
  const [showForm, setShowForm] = useState(false);

  // Edit/Migrate State
  const [editServer, setEditServer] = useState<DevServer | null>(null);
  const [editOpen, setEditOpen] = useState(false);

  const fetchServers = async () => {
    try {
      const res = await fetch('/api/servers', { headers: apiHeaders() });
      const data = await res.json();
      setServers(data.servers ?? []);
    } catch {
    } finally {
      setLoading(false);
    }
  };

  const fetchNodes = async () => {
    try {
      const res = await fetch('/api/nodes', { headers: apiHeaders() });
      const data = await res.json();
      setNodes(data.nodes ?? []);
    } catch {}
  };

  useEffect(() => { 
    fetchServers();
    fetchNodes();
  }, []);

  const handleAdd = async (e: React.FormEvent) => {
    e.preventDefault();
    setAddError(null);
    setAdding(true);
    try {
      // 1. Encrypt RCON data for provisioning
      const rconData = JSON.stringify({
        address: newRconAddr,
        port: newRconPort,
        pass: newRconPass,
      });
      const encrypted = await encrypt(rconData);
      const encryptedBlob = uint8ArrayToBase64(encrypted);

      const res = await fetch('/api/servers', {
        method: 'POST',
        headers: apiHeaders(),
        body: JSON.stringify({ 
          name: newName, 
          description: newDesc,
          workerId: newWorkerId,
          storageId: newStorageId,
          encryptedRcon: encryptedBlob,
        }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error ?? 'Failed to add server');
      setServers(prev => [...prev, data]);
      setNewName('');
      setNewDesc('');
      setNewWorkerId('');
      setNewStorageId('');
      setNewRconAddr('');
      setNewRconPort(2302);
      setNewRconPass('');
      setShowForm(false);
    } catch (err) {
      setAddError((err as Error).message);
    } finally {
      setAdding(false);
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await fetch(`/api/servers?id=${id}`, { method: 'DELETE', headers: apiHeaders() });
      setServers(prev => prev.filter(s => s.id !== id));
    } catch {}
  };

  const workers = nodes.filter(n => n.type === 'worker');
  const storages = nodes.filter(n => n.type === 'storage');

  return (
    <div className="space-y-6 animate-in fade-in slide-in-from-bottom-2 duration-500">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-3xl font-black tracking-tight text-foreground uppercase italic">Operational Fleet</h2>
          <p className="text-[10px] font-black uppercase tracking-widest text-muted-foreground/60 mt-1">Deploy and orchestrate distributed game nodes</p>
        </div>
        <Button onClick={() => setShowForm(!showForm)} className="shadow-lg shadow-primary/20">
          <Plus className="w-4 h-4 mr-2" />
          Provision Node
        </Button>
      </div>

      {showForm && (
        <Card className="border-primary/20 bg-primary/5 backdrop-blur-sm overflow-hidden relative animate-in slide-in-from-top-4 duration-500">
          <div className="absolute top-0 left-0 w-1 h-full bg-primary" />
          <CardHeader>
            <CardTitle className="text-lg uppercase italic font-black">Provision New Node</CardTitle>
            <CardDescription className="text-xs font-bold uppercase tracking-widest text-muted-foreground/60">Initialize operational parameters and node assignment</CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="space-y-4">
                 <div className="space-y-2">
                    <label className="text-[10px] font-black uppercase tracking-widest text-muted-foreground/60">Node Identification</label>
                    <Input
                      value={newName}
                      onChange={e => setNewName(e.target.value)}
                      placeholder="e.g., Tactical-EU-01"
                      disabled={adding}
                      className="bg-background/50"
                    />
                  </div>
                  <div className="space-y-2">
                    <label className="text-[10px] font-black uppercase tracking-widest text-muted-foreground/60">Operational Scope (Description)</label>
                    <Input
                      value={newDesc}
                      onChange={e => setNewDesc(e.target.value)}
                      placeholder="e.g., EU-Central-1, 64 Capacity"
                      disabled={adding}
                      className="bg-background/50"
                    />
                  </div>
              </div>

              <div className="space-y-4">
                  <div className="space-y-2">
                    <label className="text-[10px] font-black uppercase tracking-widest text-muted-foreground/60">Initial Worker Assignment</label>
                    <select 
                      value={newWorkerId} 
                      onChange={e => setNewWorkerId(e.target.value)}
                      className="w-full h-10 px-3 bg-background/50 border border-border/50 rounded-md text-sm text-foreground focus:outline-none focus:ring-1 focus:ring-primary"
                    >
                      <option value="">No Worker Assigned</option>
                      {workers.map(n => <option key={n.id} value={n.id}>{n.name} ({n.status})</option>)}
                    </select>
                  </div>
                  <div className="space-y-2">
                    <label className="text-[10px] font-black uppercase tracking-widest text-muted-foreground/60">Initial Storage Assignment</label>
                    <select 
                      value={newStorageId} 
                      onChange={e => setNewStorageId(e.target.value)}
                      className="w-full h-10 px-3 bg-background/50 border border-border/50 rounded-md text-sm text-foreground focus:outline-none focus:ring-1 focus:ring-primary"
                    >
                      <option value="">No Storage Assigned</option>
                      {storages.map(n => <option key={n.id} value={n.id}>{n.name} ({n.status})</option>)}
                    </select>
                  </div>
              </div>
            </div>

            <div className="space-y-4 pt-4 border-t border-border/20">
               <div className="flex items-center gap-2 text-primary font-black uppercase tracking-tighter text-sm">
                  <Key className="w-4 h-4" />
                  Initial RCON Protocol Security (E2EE)
               </div>
               <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <div className="space-y-2">
                    <label className="text-[10px] font-black uppercase tracking-widest text-muted-foreground/60">Target Address</label>
                    <Input placeholder="127.0.0.1" value={newRconAddr} onChange={e => setNewRconAddr(e.target.value)} className="bg-background/50" />
                  </div>
                  <div className="space-y-2">
                    <label className="text-[10px] font-black uppercase tracking-widest text-muted-foreground/60">Protocol Port</label>
                    <Input type="number" value={newRconPort} onChange={e => setNewRconPort(parseInt(e.target.value))} className="bg-background/50" />
                  </div>
                  <div className="space-y-2">
                    <label className="text-[10px] font-black uppercase tracking-widest text-muted-foreground/60">Access Secret</label>
                    <Input type="password" placeholder="••••••••" value={newRconPass} onChange={e => setNewRconPass(e.target.value)} className="bg-background/50" />
                  </div>
               </div>
            </div>
            {addError && (
              <div className="p-3 bg-destructive/10 border border-destructive/20 rounded-lg flex items-center gap-2 text-xs text-destructive animate-in shake-1">
                <AlertCircle className="w-4 h-4 flex-shrink-0" />
                {addError}
              </div>
            )}
            <div className="flex gap-2 pt-2">
              <Button onClick={handleAdd} disabled={adding || !newName.trim()} className="font-black uppercase tracking-widest">
                {adding && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
                Execute Provisioning
              </Button>
              <Button variant="ghost" onClick={() => setShowForm(false)} className="uppercase font-bold text-[10px] tracking-widest">Abort</Button>
            </div>
          </CardContent>
        </Card>
      )}

      {loading ? (
        <div className="flex flex-col items-center gap-4 text-muted-foreground py-24 justify-center">
          <div className="relative">
            <Loader2 className="w-10 h-10 animate-spin text-primary" />
            <div className="absolute inset-0 bg-primary blur-xl opacity-20 animate-pulse"></div>
          </div>
          <span className="font-bold uppercase tracking-widest text-[10px] animate-pulse">Synchronizing Fleet Ingress...</span>
        </div>
      ) : servers.length === 0 ? (
        <Card className="border-dashed border-2 py-20 bg-muted/20 flex flex-col items-center text-center space-y-6">
          <div className="w-16 h-16 bg-muted border rounded-2xl flex items-center justify-center">
            <Server className="w-8 h-8 text-muted-foreground/30" />
          </div>
          <div className="space-y-2">
            <h3 className="text-xl font-bold uppercase italic font-black">No Active Node Assets</h3>
            <p className="text-muted-foreground text-xs font-bold uppercase tracking-widest max-w-sm mx-auto">
              Deployment queue empty. Initialize your first node asset to begin monitoring.
            </p>
          </div>
          <Button variant="outline" onClick={() => setShowForm(true)} className="rounded-full px-8 uppercase font-black tracking-widest text-[10px]">
            <Plus className="w-4 h-4 mr-2" />
            Provision Primary Asset
          </Button>
        </Card>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {servers.map(server => (
            <Card key={server.id} className="group hover:border-primary/50 transition-all duration-500 bg-card/40 backdrop-blur-xl relative overflow-hidden border-border/50">
               <div className="absolute top-0 right-0 p-4 flex gap-2">
                 <Button
                    variant="ghost"
                    size="icon"
                    onClick={() => { setEditServer(server); setEditOpen(true); }}
                    className="opacity-0 group-hover:opacity-100 text-muted-foreground hover:text-primary transition-all rounded-full h-8 w-8 bg-background/40 backdrop-blur-md"
                  >
                    <Settings className="w-4 h-4" />
                  </Button>
                 <Button
                    variant="ghost"
                    size="icon"
                    onClick={() => handleDelete(server.id)}
                    className="opacity-0 group-hover:opacity-100 text-muted-foreground hover:text-destructive transition-all rounded-full h-8 w-8 bg-background/40 backdrop-blur-md"
                  >
                    <Trash2 className="w-4 h-4" />
                  </Button>
               </div>
              <CardHeader className="p-6 pb-2">
                <div className="flex items-center gap-4">
                  <div className="p-4 bg-primary/10 border border-primary/20 rounded-2xl group-hover:bg-primary/20 transition-colors shadow-inner shadow-primary/5">
                    <Server className="w-6 h-6 text-primary" />
                  </div>
                  <div className="min-w-0">
                    <CardTitle className="text-lg font-black truncate uppercase italic">{server.name}</CardTitle>
                    {server.description && (
                      <CardDescription className="text-[10px] font-black uppercase tracking-widest truncate opacity-60">{server.description}</CardDescription>
                    )}
                  </div>
                </div>
              </CardHeader>
              <CardContent className="p-6 pt-6 space-y-4">
                <div className="grid grid-cols-2 gap-3">
                   <div className="p-3 bg-muted/30 rounded-xl border border-border/50 space-y-1">
                      <span className="text-[8px] font-black uppercase tracking-widest text-muted-foreground/60">Worker Node</span>
                      <div className="flex items-center gap-1.5 overflow-hidden">
                         <div className={cn("w-1.5 h-1.5 rounded-full shrink-0", server.workerId ? "bg-primary animate-pulse" : "bg-muted-foreground/30")} />
                         <span className="text-[10px] font-bold truncate">{nodes.find(n => n.id === server.workerId)?.name || 'UNASSIGNED'}</span>
                      </div>
                   </div>
                   <div className="p-3 bg-muted/30 rounded-xl border border-border/50 space-y-1">
                      <span className="text-[8px] font-black uppercase tracking-widest text-muted-foreground/60">Storage Cluster</span>
                      <div className="flex items-center gap-1.5 overflow-hidden">
                         <div className={cn("w-1.5 h-1.5 rounded-full shrink-0", server.storageId ? "bg-indigo-500 animate-pulse" : "bg-muted-foreground/30")} />
                         <span className="text-[10px] font-bold truncate">{nodes.find(n => n.id === server.storageId)?.name || 'UNASSIGNED'}</span>
                      </div>
                   </div>
                </div>

                <div className="flex items-center justify-between pt-2">
                  <div className="flex items-center gap-2">
                    {server.mockActive ? (
                      <Badge variant="outline" className="bg-emerald-500/10 text-emerald-500 border-emerald-500/20 text-[9px] font-black py-0.5 px-2">
                        <span className="w-1.5 h-1.5 bg-emerald-500 rounded-full mr-1.5 animate-pulse" />
                        OPERATIONAL
                      </Badge>
                    ) : (
                      <Badge variant="outline" className="bg-muted text-muted-foreground border-border text-[9px] font-black py-0.5 px-2">
                        OFFLINE
                      </Badge>
                    )}
                  </div>
                  <Button 
                    variant="ghost" 
                    size="sm" 
                    onClick={() => { setEditServer(server); setEditOpen(true); }}
                    className="h-7 px-3 text-[9px] font-black uppercase tracking-widest text-muted-foreground hover:text-primary transition-all group-hover:bg-primary/5"
                  >
                    <ArrowRightLeft className="w-3 h-3 mr-1.5" />
                    Migrate Asset
                  </Button>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      <EditServerDialog 
        server={editServer} 
        nodes={nodes} 
        open={editOpen} 
        onOpenChange={setEditOpen} 
        onSave={fetchServers} 
      />
    </div>
  );
};

// ============================================================================
// MAIN DASHBOARD
// ============================================================================

interface LogEvent {
  timestamp: string;
  type: string;
  content: string;
  playerName?: string;
  playerNameHash?: string;
  serverId?: string;
  serverName?: string;
}

const Dashboard = () => {
  const { isLocked, isAuthenticated, unlock, decrypt, username, logout } = useVault();
  const [logs, setLogs] = useState<LogEvent[]>([]);
  const [telemetry, setTelemetry] = useState({ fps: 0, players: 0 });
  const [authView, setAuthView] = useState<'login' | 'register'>('login');
  const [activePage, setActivePage] = useState<Page>('dashboard');
  
  // Insights State
  const [insightPlayer, setInsightPlayer] = useState<{name: string, nameHash: string} | null>(null);
  const [insightOpen, setInsightOpen] = useState(false);

  useEffect(() => {
    if (!isAuthenticated) return;
    const socket = new WebSocket('ws://localhost:8080/ws?role=dashboard');
    socket.binaryType = 'arraybuffer';

    socket.onmessage = async (event) => {
      if (event.data instanceof ArrayBuffer) {
        if (!isLocked) {
          try {
            const decrypted = await decrypt(new Uint8Array(event.data));
            const logObj = JSON.parse(decrypted);
            setLogs(prev => [logObj, ...prev].slice(0, 100));
          } catch (err) {
            console.error('Decryption failed', err);
          }
        }
      } else {
        try {
          const data = JSON.parse(event.data);
          if (data.type === 'TELEMETRY') {
            setTelemetry({ fps: data.fps, players: data.players });
          }
        } catch (e) {}
      }
    };

    return () => socket.close();
  }, [isAuthenticated, isLocked, decrypt]);

  if (!isAuthenticated) {
    if (authView === 'register') {
      return (
        <Register
          onRegisterSuccess={(token, key, communityId, user, uid, userRole) => {
            localStorage.setItem('auth_token', token);
            unlock(key, communityId, user, uid, userRole);
          }}
          onSwitchToLogin={() => setAuthView('login')}
        />
      );
    }
    return (
      <LoginV2
        onLoginSuccess={(token, key, communityId, user, uid, userRole) => {
          localStorage.setItem('auth_token', token);
          unlock(key, communityId, user, uid, userRole);
        }}
        onSwitchToRegister={() => setAuthView('register')}
      />
    );
  }

  const handleExport = async () => {
    if (logs.length === 0) return;
    const exportData = { community_id: 'comm-123-abc', export_date: new Date().toISOString(), logs };
    const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `arma-cloud-export-${Date.now()}.json`;
    a.click();
    URL.revokeObjectURL(url);
  };

  const handleOpenInsights = (p: {name: string, nameHash: string}) => {
    setInsightPlayer(p);
    setInsightOpen(true);
  };

  const renderPage = () => {
    switch (activePage) {
      case 'servers':
        return <ServersPage />;
      case 'players':
        return <Players onOpenInsights={handleOpenInsights} />;
      case 'nodes':
        return <Nodes />;
      case 'security':
      case 'rights':
        return <RightsManagement />;
      case 'profile':
        return <Profile />;
      default:
        return (
          <div className="space-y-6 animate-in fade-in slide-in-from-bottom-4 duration-700">
            {/* Metrics Grid */}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
              <MetricCard label="Server FPS" value={telemetry.fps.toFixed(1)} unit="FPS" icon={Activity} color="text-emerald-500" trend={12} />
              <MetricCard label="Players Online" value={telemetry.players} unit="/ 64" icon={Users} color="text-primary" />
              <MetricCard label="Network" value="0.8" unit="Gbps" icon={Network} color="text-blue-500" trend={-2} />
              <MetricCard label="Latency" value="12" unit="ms" icon={Server} color="text-amber-500" />
            </div>

            {isLocked ? (
              <Card className="border-dashed py-24 bg-muted/5 backdrop-blur-sm">
                <CardContent className="flex flex-col items-center text-center space-y-8">
                  <div className="relative">
                    <div className="absolute inset-0 bg-amber-500 blur-3xl opacity-20 animate-pulse"></div>
                    <div className="relative w-24 h-24 bg-muted border border-amber-500/20 rounded-[2rem] flex items-center justify-center shadow-2xl">
                      <Lock className="w-10 h-10 text-amber-500" />
                    </div>
                  </div>
                  <div className="space-y-3">
                    <h3 className="text-3xl font-black tracking-tighter">Session Locked</h3>
                    <p className="text-muted-foreground text-sm max-w-sm mx-auto leading-relaxed">
                      Your session has been paused and encryption keys cleared. Reload the page to continue.
                    </p>
                  </div>
                  <Button variant="outline" onClick={() => window.location.reload()} className="rounded-full px-10 h-12 font-bold border-amber-500/30 text-amber-500 hover:bg-amber-500/10">
                    Reload Page
                  </Button>
                </CardContent>
              </Card>
            ) : (
              <Card className="border-border/50 shadow-2xl bg-card/40 backdrop-blur-xl overflow-hidden">
                <CardHeader className="flex flex-row items-center justify-between border-b border-border/50 bg-muted/30 px-6 py-5">
                  <div className="flex items-center gap-4">
                    <div className="relative">
                       <div className="w-3 h-3 bg-emerald-500 rounded-full animate-ping absolute"></div>
                       <div className="w-3 h-3 bg-emerald-500 rounded-full relative"></div>
                    </div>
                    <div>
                      <CardTitle className="text-lg font-black tracking-tight">Live Event Log</CardTitle>
                      <CardDescription className="text-[10px] uppercase font-bold tracking-widest mt-0.5 opacity-60">Events from your servers, end-to-end encrypted</CardDescription>
                    </div>
                  </div>
                  <Badge variant="outline" className="text-[10px] uppercase font-black tracking-widest bg-emerald-500/10 text-emerald-500 border-emerald-500/20 px-3 py-1">
                    Live
                  </Badge>
                </CardHeader>
                <ScrollArea className="h-[600px]">
                  <div className="min-w-full">
                    <table className="min-w-full">
                      <thead className="bg-muted/50 sticky top-0 z-10 backdrop-blur-md">
                        <tr>
                          <th className="px-6 py-4 text-left text-[10px] font-black uppercase tracking-widest text-muted-foreground border-b border-border/50">Type</th>
                          <th className="px-6 py-4 text-left text-[10px] font-black uppercase tracking-widest text-muted-foreground border-b border-border/50">Message</th>
                          <th className="px-6 py-4 text-right text-[10px] font-black uppercase tracking-widest text-muted-foreground border-b border-border/50">Server</th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-border/20">
                        {logs.length === 0 ? (
                          <tr>
                            <td colSpan={3} className="px-6 py-32 text-center">
                              <div className="flex flex-col items-center gap-4 text-muted-foreground italic text-sm">
                                <Loader2 className="w-8 h-8 animate-spin opacity-20" />
                                <p>Waiting for events from connected servers...</p>
                              </div>
                            </td>
                          </tr>
                        ) : (
                          logs.map((log, i) => {
                            const pInfo = log.playerNameHash ? {
                              name: log.playerName || 'Unknown',
                              nameHash: log.playerNameHash
                            } : null;
                            
                            const row = (
                              <tr key={i} className="hover:bg-primary/5 transition-colors group cursor-default">
                                <td className="px-6 py-4 whitespace-nowrap">
                                  <Badge variant={
                                    log.type === 'CHAT' ? 'default' :
                                    log.type === 'JOIN' ? 'secondary' :
                                    log.type === 'LEAVE' ? 'destructive' : 'outline'
                                  } className="text-[10px] px-2 py-0.5 h-5 font-black uppercase tracking-wider rounded-md">
                                    {log.type}
                                  </Badge>
                                </td>
                                <td className="px-6 py-4 text-sm font-medium">
                                  <div className="flex items-center justify-between">
                                    {pInfo ? (
                                      <div className="flex items-center gap-2">
                                        <span className="text-[10px] font-black bg-primary/10 text-primary px-1.5 py-0.5 rounded border border-primary/20">{pInfo.name}</span>
                                        <span className="text-foreground/90 font-medium">{log.content}</span>
                                      </div>
                                    ) : (
                                      <span className="text-foreground/90 font-medium">{log.content}</span>
                                    )}
                                    
                                    {pInfo && (
                                      <DropdownMenu>
                                        <DropdownMenuTrigger asChild>
                                          <Button variant="ghost" size="icon" className="h-6 w-6 rounded-full opacity-0 group-hover:opacity-100 transition-opacity">
                                            <MoreVertical className="w-3.5 h-3.5" />
                                          </Button>
                                        </DropdownMenuTrigger>
                                        <DropdownMenuContent align="end" className="w-48 bg-card/95 backdrop-blur-xl border-border/50">
                                          <DropdownMenuLabel className="text-[10px] uppercase font-black tracking-widest text-muted-foreground/60">Player Actions</DropdownMenuLabel>
                                          <DropdownMenuSeparator />
                                          <DropdownMenuItem onClick={() => handleOpenInsights(pInfo)} className="font-bold">
                                             <Activity className="w-4 h-4 mr-2" /> Insights
                                          </DropdownMenuItem>
                                          <DropdownMenuItem onClick={() => window.open(`https://steamcommunity.com/search/users/#text=${pInfo.name}`, '_blank')} className="font-bold">
                                             <Network className="w-4 h-4 mr-2" /> Steam Search
                                          </DropdownMenuItem>
                                        </DropdownMenuContent>
                                      </DropdownMenu>
                                    )}
                                  </div>
                                </td>
                                <td className="px-6 py-4 text-right text-[10px] font-mono font-bold text-muted-foreground/60">
                                   {log.serverName || 'UNKNOWN-NODE'}
                                </td>
                              </tr>
                            );

                            return pInfo ? (
                              <PlayerContextMenu 
                                key={i} 
                                player={pInfo} 
                                onViewInsights={handleOpenInsights}
                              >
                                {row}
                              </PlayerContextMenu>
                            ) : row;
                          })
                        )}
                      </tbody>
                    </table>
                  </div>
                </ScrollArea>
              </Card>
            )}
          </div>
        );
    }
  };

  const pageTitles: Record<Page, string> = {
    dashboard: 'Dashboard',
    servers: 'Servers',
    console: 'Console',
    players: 'Players',
    security: 'Moderation',
    rights: 'Permissions',
    profile: 'Profile',
    nodes: 'Infrastructure',
  };

  return (
    <div className="flex h-screen bg-[#02040a] text-foreground selection:bg-primary/30 overflow-hidden font-sans">
      {/* Sidebar */}
      <aside className="w-72 border-r border-border/50 flex flex-col p-6 bg-card/50 backdrop-blur-3xl z-20">
        <div className="flex items-center gap-4 px-2 mb-12">
          <div className="relative group">
            <div className="absolute inset-0 bg-primary blur-xl opacity-20 group-hover:opacity-40 transition-opacity"></div>
            <div className="relative w-10 h-10 bg-primary rounded-xl flex items-center justify-center shadow-2xl shadow-primary/20 rotate-3 group-hover:rotate-0 transition-transform">
              <Zap className="w-6 h-6 text-primary-foreground fill-primary-foreground" />
            </div>
            <div className="absolute -bottom-1 -right-1 w-3.5 h-3.5 bg-emerald-500 border-4 border-[#090b14] rounded-full"></div>
          </div>
          <div className="flex flex-col">
            <span className="text-lg font-black tracking-tighter leading-none uppercase italic">ArmaCloud</span>
            <span className="text-[10px] text-primary font-black uppercase tracking-[0.2em] mt-1 opacity-70">Control Center</span>
          </div>
        </div>

        <div className="mb-8">
           <div className="px-3 mb-2 flex items-center justify-between">
              <span className="text-[10px] font-black uppercase tracking-widest text-muted-foreground/60">Overview</span>
           </div>
           <nav className="space-y-1">
            <SidebarItem icon={LayoutDashboard} label="Dashboard" active={activePage === 'dashboard'} onClick={() => setActivePage('dashboard')} />
            <SidebarItem icon={Server} label="Servers" active={activePage === 'servers'} onClick={() => setActivePage('servers')} />
            <SidebarItem icon={Database} label="Infrastructure" active={activePage === 'nodes'} onClick={() => setActivePage('nodes')} />
            <SidebarItem icon={Terminal} label="Console" active={activePage === 'console'} onClick={() => setActivePage('console')} />
          </nav>
        </div>

        <div className="mb-8">
           <div className="px-3 mb-2 flex items-center justify-between">
              <span className="text-[10px] font-black uppercase tracking-widest text-muted-foreground/60">Players</span>
           </div>
           <nav className="space-y-1">
            <SidebarItem icon={Users} label="Players" active={activePage === 'players'} onClick={() => setActivePage('players')} />
            <SidebarItem icon={ShieldAlert} label="Permissions" active={activePage === 'rights'} onClick={() => setActivePage('rights')} />
          </nav>
        </div>

        <div className="mt-auto space-y-6">
          <Card className={cn("p-5 border-none shadow-2xl transition-all relative overflow-hidden", isLocked ? "bg-amber-500/5 ring-1 ring-amber-500/20" : "bg-primary/5 ring-1 ring-primary/20")}>
            <div className={cn("absolute top-0 right-0 w-16 h-16 -mr-4 -mt-4 opacity-10", isLocked ? "text-amber-500" : "text-primary")}>
               {isLocked ? <Lock className="w-full h-full" /> : <ShieldAlert className="w-full h-full" />}
            </div>
            <div className="flex items-center justify-between mb-3">
              <span className="text-[9px] font-black uppercase tracking-widest text-muted-foreground/60">Session Status</span>
              {isLocked ? <div className="w-1.5 h-1.5 bg-amber-500 rounded-full animate-pulse" /> : <div className="w-1.5 h-1.5 bg-primary rounded-full animate-pulse" />}
            </div>
            <div className={cn("text-xs font-black uppercase tracking-tight", isLocked ? "text-amber-500" : "text-primary")}>
              {isLocked ? 'Session Locked' : 'Connected'}
            </div>
          </Card>

          <div className="px-2">
            <Button variant="ghost" size="sm" onClick={logout} className="w-full justify-start text-muted-foreground hover:text-destructive hover:bg-destructive/10 rounded-xl font-bold transition-all group">
              <LogOut className="w-4 h-4 mr-2 group-hover:-translate-x-1 transition-transform" />
              Log out
            </Button>
          </div>
        </div>
      </aside>

      {/* Main View */}
      <main className="flex-1 overflow-y-auto flex flex-col relative">
        <header className="h-20 border-b border-border/50 flex items-center justify-between px-10 bg-background/80 backdrop-blur-xl sticky top-0 z-10">
          <div className="flex items-center gap-3 text-[11px] font-bold uppercase tracking-widest">
            <span className="text-muted-foreground/60">ArmaCloud</span>
            <ChevronRight className="w-3 h-3 text-muted-foreground/30" />
            <span className="text-primary">{pageTitles[activePage]}</span>
          </div>

          <div className="flex items-center gap-6">
            <div className="relative hidden md:block">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground/40" />
              <Input placeholder="Search records..." className="h-9 w-64 pl-10 bg-muted/20 border-border/50 rounded-full text-xs" />
            </div>

            <div className="flex items-center gap-2">
               <Button variant="ghost" size="icon" className="relative text-muted-foreground hover:text-primary rounded-full">
                  <Bell className="w-5 h-5" />
                  <span className="absolute top-2 right-2 w-2 h-2 bg-primary rounded-full border-2 border-background"></span>
               </Button>
               <Button variant="ghost" size="icon" className="text-muted-foreground hover:text-primary rounded-full" onClick={() => setActivePage('profile')}>
                  <Settings className="w-5 h-5" />
               </Button>
            </div>

            <Separator orientation="vertical" className="h-8 opacity-20" />

            {activePage === 'dashboard' && !isLocked && (
              <Button variant="outline" size="sm" onClick={handleExport} className="h-9 text-[10px] font-black uppercase tracking-widest px-5 rounded-full border-primary/20 hover:bg-primary/5 transition-all">
                <Download className="w-3.5 h-3.5 mr-2" />
                Data Export
              </Button>
            )}

            <div className="flex items-center gap-4 group cursor-pointer" onClick={() => setActivePage('profile')}>
              <div className="flex flex-col items-end">
                <span className="text-xs text-foreground font-black uppercase tracking-tight leading-none">{username ?? 'Admin'}</span>
                <span className="text-[9px] text-emerald-500 font-bold uppercase tracking-widest mt-1">Online</span>
              </div>
              <Avatar className="h-10 w-10 border-2 border-primary/20 p-0.5 group-hover:scale-110 transition-transform">
                <AvatarImage src={`https://avatar.vercel.sh/${username ?? 'Admin'}.png`} />
                <AvatarFallback className="bg-primary text-primary-foreground font-black text-xs">
                   {(username ?? 'A').slice(0, 1).toUpperCase()}
                </AvatarFallback>
              </Avatar>
            </div>
          </div>
        </header>

        <div className="p-10 max-w-7xl mx-auto w-full flex-1">
          {renderPage()}
        </div>

        <footer className="px-10 py-6 border-t border-border/20 text-center">
           <p className="text-[10px] font-bold text-muted-foreground/40 uppercase tracking-[0.3em]">
              ArmaCloud &copy; 2026
           </p>
        </footer>
      </main>

      {/* Player Insights Dialog */}
      <PlayerInsights 
        player={insightPlayer} 
        open={insightOpen} 
        onOpenChange={setInsightOpen} 
      />
    </div>
  );
};

function App() {
  return (
    <VaultProvider>
      <Dashboard />
    </VaultProvider>
  );
}

export default App;