

"use client";

import { useState, useEffect, useMemo, useCallback } from "react";
import type { Stream, User, UploadedVideo, ViewLog, AssociatedVideo, PlaylistItem, Playlist } from "@/types";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogFooter,
  DialogClose,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { CheckCircle, XCircle, ArrowLeft, ShieldCheck, Eye, AlertTriangle, Trash2, History, LogOut, Users, PlusCircle, Video as VideoIconLucide, ThumbsUp, ThumbsDown, Briefcase, Edit, PowerOff, Power, UploadCloud, Link as LinkIcon, Star, AreaChart, Rss, Calendar as CalendarIcon, ListVideo, ArrowUp, ArrowDown, FolderPlus, Radio as RadioIcon, Film } from "lucide-react";
import Link from "next/link";
import { useToast } from "@/hooks/use-toast";
import { HlsPlayer } from "@/components/stream-player";
import { useAuth } from "@/contexts/AuthContext";
import { useRouter } from "next/navigation";
import { db } from "@/lib/firebase";
import { ref, onValue, get, update, push, set, serverTimestamp, remove } from "firebase/database";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { cn } from "@/lib/utils";
import { ScrollArea } from "@/components/ui/scroll-area";
import { ChartContainer, ChartTooltip, ChartTooltipContent } from "@/components/ui/chart";
import { Bar, BarChart as RechartsBarChart, CartesianGrid, XAxis, PieChart, Pie, Cell } from "recharts";
import type { ChartConfig } from "@/components/ui/chart";
import { subDays, subHours, subMonths, format, startOfDay, startOfMonth, endOfDay } from "date-fns";
import { RtmpStatusViewer } from "@/components/rtmp-status-viewer";
import { AudioPlayer } from "@/components/audio-player";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Calendar } from "@/components/ui/calendar";

const chartConfig = {
  views: {
    label: "Views",
    color: "hsl(var(--foreground))",
  },
  "BHB RADIO KENYA": {
    label: "BHB RADIO KENYA",
    color: "hsl(var(--chart-1))",
  },
  "Best Hiphop Radio \"badradio\"": {
    label: "Best Hiphop Radio \"badradio\"",
    color: "hsl(var(--chart-2))",
  },
  "GOSHEN WONDERS TV KENYA": {
    label: "GOSHEN WONDERS TV KENYA",
    color: "hsl(var(--chart-3))",
  },
  "GICHICHIO TV KENYA": {
    label: "GICHICHIO TV KENYA",
    color: "hsl(var(--chart-4))",
  },
  "OPENSTAR TV KENYA": {
    label: "OPENSTAR TV KENYA",
    color: "hsl(var(--chart-5))",
  },
    "Emiracle TV": {
    label: "Emiracle TV",
    color: "hsl(var(--chart-1))",
  },
  "nyumba ya mumbi tv": {
    label: "nyumba ya mumbi tv",
    color: "hsl(var(--chart-2))",
  },
  "IMANI TV ELDORET": {
    label: "IMANI TV ELDORET",
    color: "hsl(var(--chart-3))",
  },
    "ABN 3": {
    label: "ABN 3",
    color: "hsl(var(--chart-4))",
  },
  "NTV KENYA": {
    label: "NTV KENYA",
    color: "hsl(var(--chart-5))",
  },
   "Others": {
    label: "Others",
    color: "hsl(var(--muted))",
  },
    "12am-2am": { label: "12am-2am", color: "hsl(var(--chart-1))" },
    "2am-4am": { label: "2am-4am", color: "hsl(var(--chart-2))" },
    "4am-6am": { label: "4am-6am", color: "hsl(var(--chart-3))" },
    "6am-8am": { label: "6am-8am", color: "hsl(var(--chart-4))" },
    "8am-10am": { label: "8am-10am", color: "hsl(var(--chart-5))" },
    "10am-12pm": { label: "10am-12pm", color: "hsl(var(--chart-1))" },
    "12pm-2pm": { label: "12pm-2pm", color: "hsl(var(--chart-2))" },
    "2pm-4pm": { label: "2pm-4pm", color: "hsl(var(--chart-3))" },
    "4pm-6pm": { label: "4pm-6pm", color: "hsl(var(--chart-4))" },
    "6pm-8pm": { label: "6pm-8pm", color: "hsl(var(--chart-5))" },
    "8pm-10pm": { label: "8pm-10pm", color: "hsl(var(--chart-1))" },
    "10pm-12am": { label: "10pm-12am", color: "hsl(var(--chart-2))" },
} satisfies ChartConfig;

const startOfTenMinutes = (date: Date): Date => {
  const newDate = new Date(date);
  const minutes = newDate.getMinutes();
  const startMinute = Math.floor(minutes / 10) * 10;
  newDate.setMinutes(startMinute, 0, 0);
  return newDate;
};


export default function AdminDashboardPage() {
  const [isClient, setIsClient] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [pendingStreams, setPendingStreams] = useState<Stream[]>([]);
  const [approvedStreams, setApprovedStreams] = useState<Stream[]>([]);
  const [allStreams, setAllStreams] = useState<Stream[]>([]);
  const [disabledStreams, setDisabledStreams] = useState<Stream[]>([]);
  const [streamsPendingDeletion, setStreamsPendingDeletion] = useState<Stream[]>([]);
  const [deletedStreamsHistory, setDeletedStreamsHistory] = useState<Stream[]>([]);
  const [rejectedStreams, setRejectedStreams] = useState<Stream[]>([]);
  const [registeredUsers, setRegisteredUsers] = useState<User[]>([]);
  const { toast } = useToast();

  const [selectedStreamForPreview, setSelectedStreamForPreview] = useState<Stream | null>(null);
  const [isPreviewDialogOpen, setIsPreviewDialogOpen] = useState(false);
  const [activePreviewPlayingUrl, setActivePreviewPlayingUrl] = useState<string | null>(null);

  const [newStreamName, setNewStreamName] = useState('');
  const [newStreamUrl1, setNewStreamUrl1] = useState('');
  const [newStreamUrl2, setNewStreamUrl2] = useState('');
  const [newStreamUrl3, setNewStreamUrl3] = useState('');
  const [newStreamDescription, setNewStreamDescription] = useState('');
  const [newStreamType, setNewStreamType] = useState<'video' | 'audio'>('video');
  const [lastSubmittedStreamForPreview, setLastSubmittedStreamForPreview] = useState<Stream | null>(null);
  const [isPreviewSubmittedStreamDialogOpen, setIsPreviewSubmittedStreamDialogOpen] = useState(false);
  
  const [isAddStreamDialogOpen, setIsAddStreamDialogOpen] = useState(false);
  const [isAddYouTubeDialogOpen, setIsAddYouTubeDialogOpen] = useState(false);


  const [pendingVideos, setPendingVideos] = useState<UploadedVideo[]>([]);
  const [approvedVideos, setApprovedVideos] = useState<UploadedVideo[]>([]);
  const [rejectedVideos, setRejectedVideos] = useState<UploadedVideo[]>([]);
  const [selectedVideoForPreview, setSelectedVideoForPreview] = useState<UploadedVideo | null>(null);
  const [isVideoPreviewDialogOpen, setIsVideoPreviewDialogOpen] = useState(false);

  const [editingApprovedStream, setEditingApprovedStream] = useState<Stream | null>(null);
  const [isEditApprovedStreamDialogOpen, setIsEditApprovedStreamDialogOpen] = useState(false);
  const [editedApprovedStreamName, setEditedApprovedStreamName] = useState('');
  const [editedApprovedStreamUrl1, setEditedApprovedStreamUrl1] = useState('');
  const [editedApprovedStreamUrl2, setEditedApprovedStreamUrl2] = useState('');
  const [editedApprovedStreamUrl3, setEditedApprovedStreamUrl3] = useState('');
  const [editedApprovedStreamDescription, setEditedApprovedStreamDescription] = useState('');

  const [pinningStream, setPinningStream] = useState<Stream | null>(null);
  const [isPinDialogOpen, setIsPinDialogOpen] = useState(false);
  const [selectedPinSlot, setSelectedPinSlot] = useState<string | null>(null);
  
  // State for adding YouTube video
  const [youtubeVideoTitle, setYoutubeVideoTitle] = useState('');
  const [youtubeVideoUrl, setYoutubeVideoUrl] = useState('');
  const [youtubeVideoDescription, setYoutubeVideoDescription] = useState('');
  const [selectedStreamForVideo, setSelectedStreamForVideo] = useState('');
  const [manageVideosStreamId, setManageVideosStreamId] = useState<string>('');


  const [viewLogs, setViewLogs] = useState<ViewLog[]>([]);
  const [selectedDate, setSelectedDate] = useState<Date | undefined>(new Date());

  // Playlist states
  const [isPlaylistDialogOpen, setIsPlaylistDialogOpen] = useState(false);
  const [playlistStream, setPlaylistStream] = useState<Stream | null>(null);
  const [currentPlaylist, setCurrentPlaylist] = useState<Playlist | null>(null);
  const [newPlaylistTitle, setNewPlaylistTitle] = useState('');
  const [playlistItemTitle, setPlaylistItemTitle] = useState('');
  const [playlistItemUrl, setPlaylistItemUrl] = useState('');

  const { isAuthenticated, userRole, logout, userId } = useAuth();
  const router = useRouter();

  useEffect(() => {
    document.body.style.backgroundImage = 'none';
    document.body.style.backgroundColor = 'hsl(var(--background))';
    return () => {
      document.body.style.backgroundImage = '';
      document.body.style.backgroundColor = '';
    };
  }, []);
  
  const getCreatorUsername = (creatorId?: string): string => {
    if (!creatorId) return "N/A";
    const user = registeredUsers.find(u => u.id === creatorId);
    return user ? user.username : "Unknown User";
  };
  
  const validateYoutubeUrl = (url: string) => {
    const trimmedUrl = url.trim();
    if (!trimmedUrl) {
      toast({ title: "Validation Error", description: "YouTube URL is required.", variant: "destructive" });
      return false;
    }
    const isYouTubeUrl = trimmedUrl.includes("youtube.com") || trimmedUrl.includes("youtu.be");
    if (!isYouTubeUrl) {
      toast({ title: "Validation Error", description: "Please enter a valid YouTube URL.", variant: "destructive" });
      return false;
    }
    return true;
  };

  const loadAllDataFromRTDB = () => {
    setIsLoading(true);
    const streamsRef = ref(db, 'streams');
    const videosRef = ref(db, 'videos');
    const usersRef = ref(db, 'users');
    const viewLogsRef = ref(db, 'view_logs');

    const unsubscribeStreams = onValue(streamsRef, (snapshot) => {
      const allStreamsData = snapshot.val() || {};
      const allStreams: Stream[] = Object.keys(allStreamsData).map(key => ({ id: key, ...allStreamsData[key] }));
      setAllStreams(allStreams);
      
      const approved = allStreams.filter(s => s.status === 'approved').sort((a,b) => (b.views || 0) - (a.views || 0));
      setPendingStreams(allStreams.filter(s => s.status === 'pending').sort((a,b) => (b.createdAt || 0) - (a.createdAt || 0)));
      setApprovedStreams(approved);
      setDisabledStreams(allStreams.filter(s => s.status === 'disabled').sort((a,b) => (b.createdAt || 0) - (a.createdAt || 0)));
      setStreamsPendingDeletion(allStreams.filter(s => s.status === 'pending_deletion').sort((a,b) => (b.createdAt || 0) - (a.createdAt || 0)));
      setDeletedStreamsHistory(allStreams.filter(s => s.status === 'deleted').sort((a,b) => (b.deletedAt || 0) - (a.deletedAt || 0)));
      setRejectedStreams(allStreams.filter(s => s.status === 'rejected').sort((a,b) => (b.createdAt || 0) - (a.createdAt || 0)));

      if (approved.length > 0 && !selectedStreamForVideo) {
        setSelectedStreamForVideo(approved[0].id);
      }
    });

    const unsubscribeVideos = onValue(videosRef, (snapshot) => {
        const allVideosData = snapshot.val() || {};
        const allVideos: UploadedVideo[] = Object.keys(allVideosData).map(key => ({ id: key, ...allVideosData[key] }));
        setPendingVideos(allVideos.filter(v => v.status === 'pending').sort((a,b) => (b.createdAt || 0) - (a.createdAt || 0)));
        setApprovedVideos(allVideos.filter(v => v.status === 'approved').sort((a,b) => (b.actionedAt || 0) - (a.actionedAt || 0)));
        setRejectedVideos(allVideos.filter(v => v.status === 'rejected').sort((a,b) => (b.actionedAt || 0) - (a.actionedAt || 0)));
    });
    
    const unsubscribeUsers = onValue(usersRef, (snapshot) => {
        const usersData = snapshot.val() || {};
        const usersList: User[] = Object.keys(usersData).map(key => ({ id: key, ...usersData[key]}));
        setRegisteredUsers(usersList.sort((a,b) => (b.createdAt || 0) - (a.createdAt || 0)));
    });

    const unsubscribeViewLogs = onValue(viewLogsRef, (snapshot) => {
      const viewLogsData = snapshot.val() || {};
      const viewLogsList: ViewLog[] = Object.keys(viewLogsData).map(key => ({ id: key, ...viewLogsData[key]}));
      setViewLogs(viewLogsList);
      setIsLoading(false);
    });
    
    return [unsubscribeStreams, unsubscribeVideos, unsubscribeUsers, unsubscribeViewLogs];
  };

  useEffect(() => {
    setIsClient(true);
    if (typeof window !== 'undefined') {
      if (!isAuthenticated || userRole !== 'admin' || !userId) {
        return;
      }
      const unsubscribers = loadAllDataFromRTDB();
      return () => unsubscribers.forEach(unsub => unsub());
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isAuthenticated, userRole, userId]);

  useEffect(() => {
    if (playlistStream) {
      const updatedStreamData = allStreams.find(s => s.id === playlistStream.id);
      setPlaylistStream(updatedStreamData || null);
      if (currentPlaylist) {
        const updatedPlaylistData = updatedStreamData?.playlists?.[currentPlaylist.id];
        setCurrentPlaylist(updatedPlaylistData || null);
      }
    }
  }, [allStreams, playlistStream, currentPlaylist]);

  const updateStreamStatus = async (streamId: string, status: Stream['status'], extraData = {}) => {
      try {
        const streamRef = ref(db, `streams/${streamId}`);
        await update(streamRef, { status, ...extraData });
        return true;
      } catch (error) {
          console.error(`Error updating stream ${streamId} to ${status}:`, error);
          toast({ title: "Database Error", description: `Could not update stream to ${status}.`, variant: "destructive" });
          return false;
      }
  }

  const handleApproveStream = async (streamToApprove: Stream) => {
    if (await updateStreamStatus(streamToApprove.id, 'approved')) {
      toast({ title: "Stream Approved", description: `${streamToApprove.name} is now live.` });
      if (selectedStreamForPreview?.id === streamToApprove.id) closePreviewDialog();
    }
  };

  const handleRejectStream = async (streamToReject: Stream) => {
    if(await updateStreamStatus(streamToReject.id, 'rejected')) {
        toast({ title: "Stream Rejected", description: `${streamToReject.name} has been rejected.`, variant: "destructive" });
        if (selectedStreamForPreview?.id === streamToReject.id) closePreviewDialog();
    }
  };

  const handleDisableStream = async (streamToDisable: Stream) => {
    if (await updateStreamStatus(streamToDisable.id, 'disabled')) {
        toast({ title: "Stream Disabled", description: `${streamToDisable.name} has been disabled and is not visible to users.` });
    }
  };

  const handleEnableStream = async (streamToEnable: Stream) => {
    if (await updateStreamStatus(streamToEnable.id, 'approved')) {
        toast({ title: "Stream Enabled", description: `${streamToEnable.name} is now live again.` });
    }
  };

  const handleDeleteApprovedStream = async (streamToDelete: Stream) => {
    if (await updateStreamStatus(streamToDelete.id, 'deleted', { deletedAt: serverTimestamp() })) {
        toast({ title: "Stream Removed", description: `${streamToDelete.name} has been moved to deletion history.`, variant: "destructive" });
    }
  };

  const handleConfirmDeletionRequest = async (streamToDelete: Stream) => {
    if (await updateStreamStatus(streamToDelete.id, 'deleted', { deletedAt: serverTimestamp() })) {
        toast({ title: "Deletion Confirmed", description: `${streamToDelete.name} deleted and recorded.` });
        if (selectedStreamForPreview?.id === streamToDelete.id) closePreviewDialog();
    }
  };

  const handleRejectDeletionRequest = async (streamToRestore: Stream) => {
    if (await updateStreamStatus(streamToRestore.id, 'approved')) {
        toast({ title: "Deletion Rejected", description: `${streamToRestore.name} has been restored.` });
        if (selectedStreamForPreview?.id === streamToRestore.id) closePreviewDialog();
    }
  };

  const validateUrlForForm = (url: string, fieldName: string, isPrimary = false) => {
    const trimmedUrl = url.trim();
    if (isPrimary && !trimmedUrl) {
      toast({ title: "Validation Error", description: `${fieldName} is required.`, variant: "destructive" });
      return false;
    }
    if (trimmedUrl) {
      // Allow any valid https URL for video streams to support generic iframe embeds
      if (!trimmedUrl.startsWith('https://')) {
        if (trimmedUrl.startsWith('http://')) {
          toast({ title: "Potential Issue", description: `Using an insecure 'http://' URL for "${fieldName}" may be blocked by browsers. HTTPS is recommended.`, variant: "default", duration: 8000 });
        } else {
          toast({ title: "Validation Error", description: `URL for "${fieldName}" must start with https:// or http://.`, variant: "destructive" });
          return false;
        }
      }
    }
    return true;
  };

  const handleAddNewStreamSubmit = async () => {
    if (!newStreamName.trim()) { toast({ title: "Validation Error", description: "Stream Name required.", variant: "destructive" }); return; }
    if (!validateUrlForForm(newStreamUrl1, "Primary Stream URL", true) || (newStreamUrl2.trim() && !validateUrlForForm(newStreamUrl2, "Backup HLS URL 1")) || (newStreamUrl3.trim() && !validateUrlForForm(newStreamUrl3, "Backup HLS URL 2"))) return;
    if (!userId) { toast({ title: "Auth Error", description: "Admin User ID not found.", variant: "destructive" }); return; }
    
    const sourceUrls = [newStreamUrl1.trim()];
    if (newStreamUrl2.trim()) sourceUrls.push(newStreamUrl2.trim());
    if (newStreamUrl3.trim()) sourceUrls.push(newStreamUrl3.trim());

    const newStreamData: Omit<Stream, 'id'> = {
        name: newStreamName.trim(), sourceUrls, description: newStreamDescription.trim() || '', 
        views: 0, creatorId: userId, status: 'pending', createdAt: serverTimestamp() as any, streamType: newStreamType
    };

    try {
        const newStreamRef = push(ref(db, 'streams'));
        await set(newStreamRef, newStreamData);
        toast({ title: "Stream Submitted by Admin", description: `${newStreamData.name} submitted to pending queue.` });
        
        const newStreamForPreview = { ...newStreamData, id: newStreamRef.key!, createdAt: Date.now() };
        setLastSubmittedStreamForPreview(newStreamForPreview); 
        setIsPreviewSubmittedStreamDialogOpen(true);
        setIsAddStreamDialogOpen(false); // Close the dialog on success
        
        setNewStreamName(''); setNewStreamUrl1(''); setNewStreamUrl2(''); setNewStreamUrl3(''); setNewStreamDescription('');
    } catch (error) {
        console.error("Error adding new stream:", error);
        toast({ title: "Submission Error", description: "Could not save the new stream.", variant: "destructive" });
    }
  };
  
  const updateVideoStatus = async (videoId: string, status: UploadedVideo['status']) => {
      try {
        const videoRef = ref(db, `videos/${videoId}`);
        await update(videoRef, { status: status, actionedAt: serverTimestamp() });
        return true;
      } catch (error) {
        console.error(`Error updating video ${videoId} to ${status}:`, error);
        toast({ title: "Database Error", description: `Could not update video status to ${status}.`, variant: "destructive" });
        return false;
      }
  }

  const handleApproveVideo = async (videoToApprove: UploadedVideo) => {
    if (await updateVideoStatus(videoToApprove.id, 'approved')) {
      toast({ title: "Video Approved", description: `${videoToApprove.title} has been approved.` });
      if (selectedVideoForPreview?.id === videoToApprove.id) closeVideoPreviewDialog();
    }
  };

  const handleRejectVideo = async (videoToReject: UploadedVideo) => {
    if (await updateVideoStatus(videoToReject.id, 'rejected')) {
        toast({ title: "Video Rejected", description: `${videoToReject.title} has been rejected.`, variant: "destructive" });
        if (selectedVideoForPreview?.id === videoToReject.id) closeVideoPreviewDialog();
    }
  };
  
  const handleSaveEditedApprovedStream = async () => {
    if (!editingApprovedStream) return;
    
    if (!validateUrlForForm(editedApprovedStreamUrl1, "Primary Stream URL", true) || (editedApprovedStreamUrl2.trim() && !validateUrlForForm(editedApprovedStreamUrl2, "Backup URL 1")) || (editedApprovedStreamUrl3.trim() && !validateUrlForForm(editedApprovedStreamUrl3, "Backup URL 2"))) {
      return;
    }

    const updatedSourceUrls = [editedApprovedStreamUrl1.trim()];
    if (editedApprovedStreamUrl2.trim()) updatedSourceUrls.push(editedApprovedStreamUrl2.trim());
    if (editedApprovedStreamUrl3.trim()) updatedSourceUrls.push(editedApprovedStreamUrl3.trim());

    try {
        const streamRef = ref(db, `streams/${editingApprovedStream.id}`);
        await update(streamRef, {
            name: editedApprovedStreamName.trim() || editingApprovedStream.name,
            sourceUrls: updatedSourceUrls,
            description: editedApprovedStreamDescription.trim() || '',
        });
        toast({ title: "Stream Updated by Admin", description: `${editingApprovedStream.name} details have been updated.` });
        setIsEditApprovedStreamDialogOpen(false);
        setEditingApprovedStream(null);
    } catch (error) {
        console.error("Error updating stream:", error);
        toast({ title: "Update Error", description: "Could not update stream details.", variant: "destructive" });
    }
  };

  const handleAddYoutubeVideo = async () => {
    if (!youtubeVideoTitle.trim() || !validateYoutubeUrl(youtubeVideoUrl) || !selectedStreamForVideo) {
      toast({ title: "Missing Information", description: "Please fill out all required fields.", variant: "destructive" });
      return;
    }

    const newVideoRef = push(ref(db, `streams/${selectedStreamForVideo}/associatedVideos`));
    const newVideoData: AssociatedVideo = {
      id: newVideoRef.key!,
      title: youtubeVideoTitle.trim(),
      description: youtubeVideoDescription.trim() || '',
      youtubeUrl: youtubeVideoUrl.trim(),
      addedAt: serverTimestamp() as any,
    };

    try {
      await set(newVideoRef, newVideoData);
      toast({ title: "YouTube Video Added", description: `"${newVideoData.title}" has been added to the channel.` });
      setIsAddYouTubeDialogOpen(false); // Close dialog on success
      setYoutubeVideoTitle('');
      setYoutubeVideoUrl('');
      setYoutubeVideoDescription('');
    } catch (error) {
      console.error("Error adding YouTube video:", error);
      toast({ title: "Error", description: "Could not add the YouTube video.", variant: "destructive" });
    }
  };

  const handleRemoveAssociatedVideo = async (streamId: string, videoId: string) => {
    try {
        await remove(ref(db, `streams/${streamId}/associatedVideos/${videoId}`));
        toast({ title: "Video Removed", description: "The YouTube video has been removed from the channel.", variant: 'destructive' });
    } catch (error) {
        console.error("Error removing associated video:", error);
        toast({ title: "Error", description: "Could not remove the video.", variant: "destructive" });
    }
  };

  const openPreviewDialog = (stream: Stream) => { setSelectedStreamForPreview(stream); setActivePreviewPlayingUrl(null); setIsPreviewDialogOpen(true); };
  const closePreviewDialog = () => { setIsPreviewDialogOpen(false); setSelectedStreamForPreview(null); setActivePreviewPlayingUrl(null); };

  const openVideoPreviewDialog = (video: UploadedVideo) => { setSelectedVideoForPreview(video); setIsVideoPreviewDialogOpen(true); };
  const closeVideoPreviewDialog = () => { setIsVideoPreviewDialogOpen(false); setSelectedVideoForPreview(null); };

  const handleEditApprovedStreamDialog = (stream: Stream) => {
    setEditingApprovedStream(stream);
    setEditedApprovedStreamName(stream.name);
    setEditedApprovedStreamUrl1(stream.sourceUrls[0] || '');
    setEditedApprovedStreamUrl2(stream.sourceUrls[1] || '');
    setEditedApprovedStreamUrl3(stream.sourceUrls[2] || '');
    setEditedApprovedStreamDescription(stream.description || '');
    setIsEditApprovedStreamDialogOpen(true);
  };

  const handleOpenPinDialog = (stream: Stream) => {
    setPinningStream(stream);
    const pinIndex = stream.streamType === 'audio' ? stream.audioPinIndex : stream.pinIndex;
    setSelectedPinSlot(pinIndex ? String(pinIndex) : null);
    setIsPinDialogOpen(true);
  };

  const handleSavePin = async () => {
    if (!pinningStream || !selectedPinSlot) return;

    const streamsSnapshot = await get(ref(db, 'streams'));
    const allStreamsData = streamsSnapshot.val() || {};
    const currentApprovedStreams: Stream[] = Object.keys(allStreamsData)
        .map(key => ({ id: key, ...allStreamsData[key] }))
        .filter(stream => stream.status === 'approved' && stream.streamType === pinningStream.streamType);

    const newPinIndex = selectedPinSlot === 'unpin' ? null : Number(selectedPinSlot);
    const pinProperty = pinningStream.streamType === 'audio' ? 'audioPinIndex' : 'pinIndex';
    const updates: { [key: string]: any } = {};

    if (newPinIndex !== null) {
      const existingStreamInSlot = currentApprovedStreams.find(s => 
        s[pinProperty] === newPinIndex && s.id !== pinningStream.id
      );
      if (existingStreamInSlot) {
        updates[`/streams/${existingStreamInSlot.id}/${pinProperty}`] = null;
      }
    }
    
    updates[`/streams/${pinningStream.id}/${pinProperty}`] = newPinIndex;

    try {
      await update(ref(db), updates);
      toast({
        title: "Pin Updated",
        description: `${pinningStream.name} has been ${newPinIndex ? `pinned to ${pinningStream.streamType} slot ${newPinIndex}` : 'unpinned'}.`
      });
    } catch (error) {
      console.error("Error updating pin status:", error);
      toast({ title: "Error", description: "Could not update pin status.", variant: "destructive" });
    } finally {
      setIsPinDialogOpen(false);
      setPinningStream(null);
    }
  };
  
  const handleOpenPlaylistDialog = (stream: Stream | null) => {
    if (!stream) return;
    setPlaylistStream(stream);
    setCurrentPlaylist(null); // Reset current playlist when opening
    setIsPlaylistDialogOpen(true);
  };
  
  const handleCreatePlaylist = async () => {
    if (!playlistStream || !newPlaylistTitle.trim()) return;
    const newPlaylistRef = push(ref(db, `streams/${playlistStream.id}/playlists`));
    const newPlaylistData: Omit<Playlist, 'items'> = {
      id: newPlaylistRef.key!,
      title: newPlaylistTitle.trim(),
      createdAt: serverTimestamp() as any,
    };
    try {
      await set(newPlaylistRef, newPlaylistData);
      toast({ title: "Playlist Created" });
      setNewPlaylistTitle('');
    } catch (error) {
      console.error("Error creating playlist:", error);
      toast({ title: "Error", description: "Could not create playlist.", variant: "destructive" });
    }
  };

  const handleAddPlaylistItem = async () => {
    if (!playlistStream || !currentPlaylist || !playlistItemTitle.trim() || !validateYoutubeUrl(playlistItemUrl)) return;
    
    const newItemRef = push(ref(db, `streams/${playlistStream.id}/playlists/${currentPlaylist.id}/items`));
    const newItemData: PlaylistItem = {
      id: newItemRef.key!,
      title: playlistItemTitle.trim(),
      youtubeUrl: playlistItemUrl.trim(),
      addedAt: serverTimestamp() as any,
    };
    
    try {
      await set(newItemRef, newItemData);
      toast({ title: "Playlist Item Added" });
      setPlaylistItemTitle('');
      setPlaylistItemUrl('');
    } catch (error) {
      console.error("Error adding playlist item:", error);
      toast({ title: "Error", description: "Could not add item to playlist.", variant: "destructive" });
    }
  };

  const handleRemovePlaylistItem = async (itemId: string) => {
    if (!playlistStream || !currentPlaylist) return;
    try {
      await remove(ref(db, `streams/${playlistStream.id}/playlists/${currentPlaylist.id}/items/${itemId}`));
      toast({ title: "Playlist Item Removed", variant: "destructive" });
    } catch (error) {
      console.error("Error removing playlist item:", error);
      toast({ title: "Error", description: "Could not remove item from playlist.", variant: "destructive" });
    }
  };

  const handleDeletePlaylist = async (playlistId: string) => {
    if (!playlistStream) return;
    try {
        await remove(ref(db, `streams/${playlistStream.id}/playlists/${playlistId}`));
        toast({ title: "Playlist Deleted", description: "The playlist has been permanently removed.", variant: 'destructive' });
        if (currentPlaylist?.id === playlistId) {
            setCurrentPlaylist(null);
        }
    } catch (error) {
        console.error("Error deleting playlist:", error);
        toast({ title: "Error", description: "Could not delete the playlist.", variant: "destructive" });
    }
  };

  const handleReorderPlaylistItem = async (itemId: string, direction: 'up' | 'down') => {
    if (!playlistStream || !currentPlaylist || !currentPlaylist.items) return;
    const items = Object.values(currentPlaylist.items).sort((a,b) => a.addedAt - b.addedAt);
    const currentIndex = items.findIndex(item => item.id === itemId);

    if (currentIndex === -1) return;
    if (direction === 'up' && currentIndex === 0) return;
    if (direction === 'down' && currentIndex === items.length - 1) return;

    const otherIndex = direction === 'up' ? currentIndex - 1 : currentIndex + 1;
    const currentItem = items[currentIndex];
    const otherItem = items[otherIndex];

    const updates: { [key: string]: any } = {};
    updates[`/streams/${playlistStream.id}/playlists/${currentPlaylist.id}/items/${currentItem.id}/addedAt`] = otherItem.addedAt;
    updates[`/streams/${playlistStream.id}/playlists/${currentPlaylist.id}/items/${otherItem.id}/addedAt`] = currentItem.addedAt;

    try {
      await update(ref(db), updates);
      toast({ title: "Playlist Reordered" });
    } catch (error) {
      console.error("Error reordering playlist:", error);
      toast({ title: "Error", description: "Could not reorder playlist.", variant: "destructive" });
    }
  };

  const approvedVideoStreams = useMemo(() => {
    return approvedStreams.filter(s => s.streamType !== 'audio');
  }, [approvedStreams]);
  
  const approvedAudioStreams = useMemo(() => {
    return approvedStreams.filter(s => s.streamType === 'audio');
  }, [approvedStreams]);

  const currentlyPinned = useMemo(() => {
    const pinned: { [key: number]: string } = {};
    const pinProperty = pinningStream?.streamType === 'audio' ? 'audioPinIndex' : 'pinIndex';
    const streamsToSearch = approvedStreams.filter(s => s.streamType === pinningStream?.streamType);

    streamsToSearch.forEach(stream => {
        const index = stream[pinProperty];
        if (index && index >= 1 && index <= 5) {
            pinned[index] = stream.name;
        }
    });
    return pinned;
  }, [approvedStreams, pinningStream]);

  const analyticsData = useMemo(() => {
    const now = new Date();

    // Daily Data for Bar Chart
    const dailyLogs = viewLogs.filter(log => log.timestamp > subDays(now, 30).getTime());
    const dailyData = Array.from({ length: 30 }, (_, i) => {
        const dayStart = startOfDay(subDays(now, 29 - i));
        return { date: format(dayStart, 'MMM d'), views: 0 };
    });
    dailyLogs.forEach(log => {
        const logDay = format(startOfDay(new Date(log.timestamp)), 'MMM d');
        const dayData = dailyData.find(d => d.date === logDay);
        if (dayData) dayData.views++;
    });
    
    // Monthly Data for Bar Chart
    const monthlyLogs = viewLogs.filter(log => log.timestamp > subMonths(now, 12).getTime());
    const monthlyData = Array.from({ length: 12 }, (_, i) => {
        const monthStart = startOfMonth(subMonths(now, 11 - i));
        return { month: format(monthStart, 'MMM yyyy'), views: 0 };
    });
    monthlyLogs.forEach(log => {
        const logMonth = format(startOfMonth(new Date(log.timestamp)), 'MMM yyyy');
        const monthData = monthlyData.find(d => d.month === logMonth);
        if (monthData) monthData.views++;
    });

    // Daily Channel Views for Pie Chart
    const dailyChannelViews: { [key: string]: { name: string, views: number } } = {};
    const dayStart = selectedDate ? startOfDay(selectedDate).getTime() : 0;
    const dayEnd = selectedDate ? endOfDay(selectedDate).getTime() : 0;
    const viewsForSelectedDay = viewLogs.filter(log => log.timestamp >= dayStart && log.timestamp <= dayEnd);
    const totalViewsToday = viewsForSelectedDay.length;

    viewsForSelectedDay.forEach(log => {
        if (!dailyChannelViews[log.streamId]) {
            const stream = allStreams.find(s => s.id === log.streamId);
            dailyChannelViews[log.streamId] = { name: stream?.name || 'Unknown Channel', views: 0 };
        }
        dailyChannelViews[log.streamId].views++;
    });

    const topChannelsToday = Object.values(dailyChannelViews)
        .map(channel => ({ ...channel, name: channel.name, value: channel.views }))
        .sort((a, b) => b.views - a.views);
    
    // 2-Hour Interval Data for Pie Chart for the selected day
    const twoHourIntervals = Array.from({ length: 12 }, (_, i) => ({
        name: `${(i * 2) % 12 || 12}${(i < 6 || i === 11) ? 'am' : 'pm'}-${((i + 1) * 2) % 12 || 12}${((i + 1) < 6 || (i+1) === 12) ? 'am' : 'pm'}`,
        views: 0,
    }));
    
    viewsForSelectedDay.forEach(log => {
        const hour = new Date(log.timestamp).getHours();
        const intervalIndex = Math.floor(hour / 2);
        twoHourIntervals[intervalIndex].views++;
    });
    
    const totalViewsForDayInIntervals = twoHourIntervals.reduce((acc, curr) => acc + curr.views, 0);

    return { dailyData, monthlyData, topChannelsToday, totalViewsToday, twoHourIntervalData: twoHourIntervals, totalViewsForDayInIntervals };
  }, [viewLogs, allStreams, selectedDate]);
  
  const videoChannelsWithContent = useMemo(() => {
    return approvedVideoStreams.filter(stream => stream.associatedVideos && Object.keys(stream.associatedVideos).length > 0);
  }, [approvedVideoStreams]);
  
  const selectedStreamForVideoManagement = useMemo(() => {
    return approvedVideoStreams.find(s => s.id === manageVideosStreamId);
  }, [approvedVideoStreams, manageVideosStreamId]);

  useEffect(() => {
    if (videoChannelsWithContent.length > 0 && !manageVideosStreamId) {
        setManageVideosStreamId(videoChannelsWithContent[0].id);
    }
  }, [videoChannelsWithContent, manageVideosStreamId]);


  if (!isClient || !isAuthenticated || userRole !== 'admin') {
    return <div className="min-h-screen flex items-center justify-center p-4"><Card><CardHeader><CardTitle>Access Denied</CardTitle></CardHeader><CardContent><p>Redirecting...</p></CardContent></Card></div>;
  }
  
  if (isLoading) {
    return <div className="min-h-screen flex items-center justify-center p-4"><Card><CardHeader><CardTitle>Loading Admin Data...</CardTitle></CardHeader><CardContent><p>Fetching data from database...</p></CardContent></Card></div>;
  }

  return (
    <main className="min-h-screen flex flex-col items-center p-0 sm:p-2">
      <div className="w-full max-w-7xl space-y-4 md:space-y-6">
        <Card className="shadow-xl rounded-lg sticky top-0 z-50 bg-background/95 backdrop-blur-sm">
          <CardHeader className="flex flex-col sm:flex-row items-center justify-between p-2 sm:p-4">
            <div className="flex items-center gap-2"><ShieldCheck className="w-8 h-8 text-primary" /><CardTitle className="text-2xl sm:text-3xl font-bold">Admin Dashboard</CardTitle></div>
            <div className="flex items-center gap-2 mt-2 sm:mt-0">
              <Button variant="outline" asChild size="sm"><Link href="/" className="flex items-center gap-2"><ArrowLeft className="w-4 h-4" />Home</Link></Button>
              <Button variant="outline" asChild size="sm"><Link href="/invest" className="flex items-center gap-2"><Briefcase className="w-4 h-4" />Invest</Link></Button>
              <Button variant="ghost" size="sm" onClick={logout} className="text-destructive-foreground hover:bg-destructive/10"><LogOut className="w-4 h-4 mr-2" />Logout</Button>
            </div>
          </CardHeader>
        </Card>

        <div className="p-2 sm:p-0">
            <Tabs defaultValue="pending" className="w-full">
                <TabsList className="grid w-full grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-7 gap-1 h-auto flex-wrap p-1">
                    <TabsTrigger value="stream-status" className="text-xs sm:text-sm py-2 px-2"><Rss className="mr-1 h-4 w-4" />Status</TabsTrigger>
                    <TabsTrigger value="pending" className="text-xs sm:text-sm py-2 px-2"><AlertTriangle className="mr-1 h-4 w-4" />Pending</TabsTrigger>
                    <TabsTrigger value="manage" className="text-xs sm:text-sm py-2 px-2"><VideoIconLucide className="mr-1 h-4 w-4" />Manage</TabsTrigger>
                    <TabsTrigger value="add" className="text-xs sm:text-sm py-2 px-2"><PlusCircle className="mr-1 h-4 w-4" />Add</TabsTrigger>
                    <TabsTrigger value="analytics" className="text-xs sm:text-sm py-2 px-2"><AreaChart className="mr-1 h-4 w-4" />Analytics</TabsTrigger>
                    <TabsTrigger value="users" className="text-xs sm:text-sm py-2 px-2"><Users className="mr-1 h-4 w-4" />Users</TabsTrigger>
                    <TabsTrigger value="logs" className="text-xs sm:text-sm py-2 px-2"><History className="mr-1 h-4 w-4" />History</TabsTrigger>
                </TabsList>

                <TabsContent value="stream-status" className="mt-4">
                  <Card>
                    <CardHeader>
                      <CardTitle>Live RTMP Status</CardTitle>
                      <CardDescription>
                        Real-time view of incoming RTMP streams from all connected servers.
                      </CardDescription>
                    </CardHeader>
                    <CardContent>
                      <Tabs defaultValue="internal" className="w-full">
                        <TabsList>
                          <TabsTrigger value="internal">Internal</TabsTrigger>
                          <TabsTrigger value="pang">pang.runinga.co.ke</TabsTrigger>
                          <TabsTrigger value="sig">sig.runinga.co.ke</TabsTrigger>
                        </TabsList>
                        <TabsContent value="internal" className="mt-4">
                           <RtmpStatusViewer />
                        </TabsContent>
                        <TabsContent value="pang" className="mt-4">
                           <RtmpStatusViewer fetchUrl="https://pang.runinga.co.ke:8443/stats" />
                        </TabsContent>
                        <TabsContent value="sig" className="mt-4">
                           <RtmpStatusViewer fetchUrl="https://sig.runinga.co.ke:8443/stats" />
                        </TabsContent>
                      </Tabs>
                    </CardContent>
                  </Card>
                </TabsContent>
                
                <TabsContent value="pending" className="mt-4 space-y-4">
                    <Card><CardHeader><CardTitle>Pending Approval (New Streams)</CardTitle><CardDescription>Review new stream submissions from users and admins.</CardDescription></CardHeader>
                    <CardContent>
                        <div className="overflow-x-auto">
                        {pendingStreams.length === 0 ? <p>No new streams pending.</p> : (
                            <Table><TableHeader><TableRow><TableHead>Name</TableHead><TableHead>Creator</TableHead><TableHead className="text-right">Actions</TableHead></TableRow></TableHeader>
                            <TableBody>{pendingStreams.map((s) => (<TableRow key={s.id}><TableCell>{s.name}</TableCell><TableCell className="truncate">{getCreatorUsername(s.creatorId)}</TableCell><TableCell className="text-right">
                               <div className="flex justify-end items-center flex-wrap gap-1">
                                <Button variant="outline" size="sm" onClick={() => openPreviewDialog(s)}><Eye className="w-4 h-4 sm:mr-1" /><span className="hidden sm:inline">Preview</span></Button>
                                <Button variant="outline" size="sm" onClick={() => handleEditApprovedStreamDialog(s)}><Edit className="w-4 h-4 sm:mr-1" /><span className="hidden sm:inline">Edit</span></Button>
                                <Button variant="ghost" size="sm" className="text-green-500 hover:text-green-600" onClick={() => handleApproveStream(s)}><CheckCircle className="w-4 h-4 sm:mr-1" /><span className="hidden sm:inline">Approve</span></Button>
                                <Button variant="ghost" size="sm" className="text-red-500 hover:text-red-600" onClick={() => handleRejectStream(s)}><XCircle className="w-4 h-4 sm:mr-1" /><span className="hidden sm:inline">Reject</span></Button>
                               </div>
                            </TableCell></TableRow>))}</TableBody>
                            </Table>
                        )}
                        </div>
                    </CardContent>
                    </Card>
                    <Card><CardHeader><CardTitle className="flex items-center gap-2"><AlertTriangle className="w-6 h-6 text-yellow-500"/>User Deletion Requests (Streams)</CardTitle><CardDescription>Review user requests to delete their HLS streams.</CardDescription></CardHeader>
                    <CardContent>
                        <div className="overflow-x-auto">
                        {streamsPendingDeletion.length === 0 ? <p>No streams pending deletion.</p> : (
                            <Table><TableHeader><TableRow><TableHead>Name</TableHead><TableHead>Creator</TableHead><TableHead className="text-right">Actions</TableHead></TableRow></TableHeader>
                            <TableBody>{streamsPendingDeletion.map((s) => (<TableRow key={s.id}><TableCell>{s.name}</TableCell><TableCell className="truncate">{getCreatorUsername(s.creatorId)}</TableCell><TableCell className="text-right">
                                <div className="flex justify-end items-center flex-wrap gap-1">
                                <Button variant="outline" size="sm" onClick={() => openPreviewDialog(s)}><Eye className="w-4 h-4 sm:mr-1" /><span className="hidden sm:inline">Preview</span></Button>
                                <Button variant="ghost" size="sm" className="text-red-500 hover:text-red-600" onClick={() => handleConfirmDeletionRequest(s)}><Trash2 className="w-4 h-4 sm:mr-1" /><span className="hidden sm:inline">Delete</span></Button>
                                <Button variant="ghost" size="sm" className="text-green-500 hover:text-green-600" onClick={() => handleRejectDeletionRequest(s)}><CheckCircle className="w-4 h-4 sm:mr-1" /><span className="hidden sm:inline">Restore</span></Button>
                                </div>
                            </TableCell></TableRow>))}</TableBody>
                            </Table>
                        )}
                        </div>
                    </CardContent>
                    </Card>
                </TabsContent>

                <TabsContent value="manage" className="mt-4 space-y-4">
                  <Tabs defaultValue="channels" className="w-full">
                    <TabsList>
                      <TabsTrigger value="channels">Channels</TabsTrigger>
                      <TabsTrigger value="videos">YouTube Videos</TabsTrigger>
                    </TabsList>
                     <TabsContent value="channels" className="mt-4 space-y-4">
                      <Card>
                        <CardHeader>
                          <CardTitle>Approved Channels</CardTitle>
                          <CardDescription>Manage active channels. Direct deletion is permanent and recorded in history.</CardDescription>
                        </CardHeader>
                        <CardContent>
                          <Tabs defaultValue="video-channels" className="w-full">
                            <TabsList>
                              <TabsTrigger value="video-channels"><Film className="mr-2 h-4 w-4" />Video Channels</TabsTrigger>
                              <TabsTrigger value="audio-channels"><RadioIcon className="mr-2 h-4 w-4" />Audio Channels</TabsTrigger>
                            </TabsList>
                            <TabsContent value="video-channels" className="mt-4">
                                <div className="overflow-x-auto border rounded-lg">
                                  {approvedVideoStreams.length > 0 ? (
                                    <Table>
                                      <TableHeader><TableRow><TableHead>Name</TableHead><TableHead>Creator</TableHead><TableHead className="text-center">Views</TableHead><TableHead className="text-right">Actions</TableHead></TableRow></TableHeader>
                                      <TableBody>
                                        {approvedVideoStreams.map((s) => (
                                          <TableRow key={s.id}>
                                            <TableCell>{s.name}</TableCell>
                                            <TableCell className="truncate">{getCreatorUsername(s.creatorId)}</TableCell>
                                            <TableCell className="text-center"><div className="flex items-center justify-center gap-1"><Users className="w-4 h-4" />{(s.views || 0).toLocaleString()}</div></TableCell>
                                            <TableCell className="text-right">
                                              <div className="flex justify-end items-center flex-wrap gap-1">
                                                <Button variant="outline" size="sm" onClick={() => handleOpenPinDialog(s)}><Star className={cn("w-4 h-4 sm:mr-1", (s.pinIndex) && "fill-yellow-400 text-yellow-500")} /><span className="hidden sm:inline">Pin</span></Button>
                                                <Button variant="outline" size="sm" onClick={() => openPreviewDialog(s)}><Eye className="w-4 h-4 sm:mr-1" /><span className="hidden sm:inline">Preview</span></Button>
                                                <Button variant="outline" size="sm" onClick={() => handleOpenPlaylistDialog(s)}><ListVideo className="w-4 h-4 sm:mr-1" /><span className="hidden sm:inline">Playlist</span></Button>
                                                <Button variant="outline" size="sm" onClick={() => handleEditApprovedStreamDialog(s)}><Edit className="w-4 h-4 sm:mr-1" /><span className="hidden sm:inline">Edit</span></Button>
                                                <Button variant="ghost" size="sm" className="text-yellow-500 hover:text-yellow-600" onClick={() => handleDisableStream(s)}><PowerOff className="w-4 h-4 sm:mr-1" /><span className="hidden sm:inline">Disable</span></Button>
                                                <Button variant="ghost" size="sm" className="text-red-500 hover:text-red-600" onClick={() => handleDeleteApprovedStream(s)}><Trash2 className="w-4 h-4 sm:mr-1" /><span className="hidden sm:inline">Delete</span></Button>
                                              </div>
                                            </TableCell>
                                          </TableRow>
                                        ))}
                                      </TableBody>
                                    </Table>
                                  ) : <p className="p-4 text-center text-muted-foreground">No approved video channels.</p>}
                                </div>
                            </TabsContent>
                            <TabsContent value="audio-channels" className="mt-4">
                                <div className="overflow-x-auto border rounded-lg">
                                   {approvedAudioStreams.length > 0 ? (
                                     <Table>
                                      <TableHeader><TableRow><TableHead>Name</TableHead><TableHead>Creator</TableHead><TableHead className="text-center">Views</TableHead><TableHead className="text-right">Actions</TableHead></TableRow></TableHeader>
                                       <TableBody>
                                        {approvedAudioStreams.map((s) => (
                                           <TableRow key={s.id}>
                                             <TableCell>{s.name}</TableCell>
                                             <TableCell className="truncate">{getCreatorUsername(s.creatorId)}</TableCell>
                                             <TableCell className="text-center"><div className="flex items-center justify-center gap-1"><Users className="w-4 h-4" />{(s.views || 0).toLocaleString()}</div></TableCell>
                                             <TableCell className="text-right">
                                               <div className="flex justify-end items-center flex-wrap gap-1">
                                                 <Button variant="outline" size="sm" onClick={() => handleOpenPinDialog(s)}><Star className={cn("w-4 h-4 sm:mr-1", (s.audioPinIndex) && "fill-yellow-400 text-yellow-500")} /><span className="hidden sm:inline">Pin</span></Button>
                                                 <Button variant="outline" size="sm" onClick={() => openPreviewDialog(s)}><Eye className="w-4 h-4 sm:mr-1" /><span className="hidden sm:inline">Preview</span></Button>
                                                 <Button variant="outline" size="sm" onClick={() => handleEditApprovedStreamDialog(s)}><Edit className="w-4 h-4 sm:mr-1" /><span className="hidden sm:inline">Edit</span></Button>
                                                 <Button variant="ghost" size="sm" className="text-yellow-500 hover:text-yellow-600" onClick={() => handleDisableStream(s)}><PowerOff className="w-4 h-4 sm:mr-1" /><span className="hidden sm:inline">Disable</span></Button>
                                                 <Button variant="ghost" size="sm" className="text-red-500 hover:text-red-600" onClick={() => handleDeleteApprovedStream(s)}><Trash2 className="w-4 h-4 sm:mr-1" /><span className="hidden sm:inline">Delete</span></Button>
                                               </div>
                                             </TableCell>
                                           </TableRow>
                                         ))}
                                       </TableBody>
                                     </Table>
                                   ) : <p className="p-4 text-center text-muted-foreground">No approved audio channels.</p>}
                                 </div>
                            </TabsContent>
                          </Tabs>
                        </CardContent>
                      </Card>
                        <Card>
                        <CardHeader>
                            <CardTitle className="flex items-center gap-2"><PowerOff className="w-6 h-6 text-yellow-500" />Disabled Streams</CardTitle>
                            <CardDescription>Streams that are temporarily hidden from public view. They can be re-enabled.</CardDescription>
                        </CardHeader>
                        <CardContent>
                            <div className="overflow-x-auto">
                            {disabledStreams.length === 0 ? <p>No streams are currently disabled.</p> : (
                                <Table>
                                <TableHeader><TableRow><TableHead>Name</TableHead><TableHead>Creator</TableHead><TableHead className="text-right">Actions</TableHead></TableRow></TableHeader>
                                <TableBody>
                                    {disabledStreams.map((s) => (
                                    <TableRow key={s.id}>
                                        <TableCell>{s.name}</TableCell>
                                        <TableCell className="truncate">{getCreatorUsername(s.creatorId)}</TableCell>
                                        <TableCell className="text-right">
                                          <div className="flex justify-end items-center flex-wrap gap-1">
                                            <Button variant="outline" size="sm" onClick={() => openPreviewDialog(s)}><Eye className="w-4 h-4 sm:mr-1" /><span className="hidden sm:inline">Preview</span></Button>
                                            <Button variant="ghost" size="sm" className="text-green-500 hover:text-green-600" onClick={() => handleEnableStream(s)}><Power className="w-4 h-4 sm:mr-1" /><span className="hidden sm:inline">Enable</span></Button>
                                          </div>
                                        </TableCell>
                                    </TableRow>
                                    ))}
                                </TableBody>
                                </Table>
                            )}
                            </div>
                        </CardContent>
                        </Card>
                    </TabsContent>
                    <TabsContent value="videos" className="mt-4">
                        <Card>
                            <CardHeader>
                                <CardTitle>Manage Associated YouTube Videos</CardTitle>
                                <CardDescription>Remove YouTube videos linked to a specific channel.</CardDescription>
                            </CardHeader>
                            <CardContent className="space-y-4">
                                {videoChannelsWithContent.length > 0 ? (
                                    <>
                                        <div className="space-y-2">
                                            <Label htmlFor="manage-videos-channel-select">Select a Channel to Manage</Label>
                                            <Select value={manageVideosStreamId} onValueChange={setManageVideosStreamId}>
                                                <SelectTrigger id="manage-videos-channel-select"><SelectValue placeholder="Select a channel..." /></SelectTrigger>
                                                <SelectContent>{videoChannelsWithContent.map(s => <SelectItem key={s.id} value={s.id}>{s.name} ({Object.keys(s.associatedVideos || {}).length} videos)</SelectItem>)}</SelectContent>
                                            </Select>
                                        </div>
                                        {selectedStreamForVideoManagement && (
                                            <ScrollArea className="h-96 border rounded-md p-2">
                                                <div className="space-y-2">
                                                    {Object.values(selectedStreamForVideoManagement.associatedVideos || {}).sort((a,b) => b.addedAt - a.addedAt).map(video => (
                                                        <div key={video.id} className="flex items-center justify-between p-2 rounded-md bg-muted">
                                                            <div className="flex-1 overflow-hidden">
                                                                <p className="font-medium truncate" title={video.title}>{video.title}</p>
                                                                <p className="text-xs text-muted-foreground truncate" title={video.youtubeUrl}>{video.youtubeUrl}</p>
                                                            </div>
                                                            <Button size="icon" variant="ghost" className="text-destructive" onClick={() => handleRemoveAssociatedVideo(selectedStreamForVideoManagement.id, video.id)}>
                                                                <Trash2 className="h-4 w-4" />
                                                            </Button>
                                                        </div>
                                                    ))}
                                                </div>
                                            </ScrollArea>
                                        )}
                                    </>
                                ) : (
                                    <p className="text-center text-muted-foreground py-4">No channels have associated YouTube videos.</p>
                                )}
                            </CardContent>
                        </Card>
                    </TabsContent>
                  </Tabs>
                </TabsContent>

                <TabsContent value="add" className="mt-4 space-y-4">
                  <Card>
                    <CardHeader>
                      <CardTitle>Content Creation</CardTitle>
                      <CardDescription>Add new HLS streams or link YouTube videos to existing channels.</CardDescription>
                    </CardHeader>
                    <CardContent className="flex flex-wrap gap-2">
                      <Dialog open={isAddStreamDialogOpen} onOpenChange={setIsAddStreamDialogOpen}>
                        <DialogTrigger asChild>
                           <Button variant="outline" className="w-full sm:w-auto"><PlusCircle className="mr-2 h-4 w-4" />Add New Channel</Button>
                        </DialogTrigger>
                        <DialogContent className="sm:max-w-md">
                          <DialogHeader>
                            <DialogTitle>Add New Channel (to Pending)</DialogTitle>
                            <DialogDescription>Submitted channels go to the pending queue for admin approval.</DialogDescription>
                          </DialogHeader>
                          <ScrollArea className="max-h-[70vh] pr-6">
                           <div className="space-y-4 py-4">
                            <RadioGroup defaultValue="video" onValueChange={(value: 'video' | 'audio') => setNewStreamType(value)} className="grid grid-cols-2 gap-4">
                                <div><RadioGroupItem value="video" id="r-type-video" className="peer sr-only" /><Label htmlFor="r-type-video" className="flex flex-col items-center justify-between rounded-md border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary [&:has([data-state=checked])]:border-primary">Video Channel</Label></div>
                                <div><RadioGroupItem value="audio" id="r-type-audio" className="peer sr-only" /><Label htmlFor="r-type-audio" className="flex flex-col items-center justify-between rounded-md border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary [&:has([data-state=checked])]:border-primary">Audio Channel</Label></div>
                            </RadioGroup>
                            <div><Label htmlFor="new-stream-name-admin">Channel Name</Label><Input id="new-stream-name-admin" value={newStreamName} onChange={(e) => setNewStreamName(e.target.value)} placeholder="E.g., Admin's Live Event" /></div>
                            <div><Label htmlFor="new-stream-url1-admin">Primary Stream URL ({newStreamType === 'video' ? 'HLS/YouTube/Embed' : 'Audio'})</Label><Input id="new-stream-url1-admin" type="url" value={newStreamUrl1} onChange={(e) => setNewStreamUrl1(e.target.value)} placeholder="https://example.com/stream.m3u8"/></div>
                            <div><Label htmlFor="new-stream-url2-admin">Backup URL 1 (Optional)</Label><Input id="new-stream-url2-admin" type="url" value={newStreamUrl2} onChange={(e) => setNewStreamUrl2(e.target.value)} placeholder="https://backup.example.com/stream.m3u8"/></div>
                            <div><Label htmlFor="new-stream-url3-admin">Backup URL 2 (Optional)</Label><Input id="new-stream-url3-admin" type="url" value={newStreamUrl3} onChange={(e) => setNewStreamUrl3(e.target.value)} placeholder="https://another.com/stream.m3u8"/></div>
                            <div><Label htmlFor="new-stream-description-admin">Description (Optional)</Label><Textarea id="new-stream-description-admin" value={newStreamDescription} onChange={(e) => setNewStreamDescription(e.target.value)} placeholder="A brief description of the stream content." rows={2}/></div>
                          </div>
                          </ScrollArea>
                          <DialogFooter>
                            <DialogClose asChild><Button type="button" variant="outline">Cancel</Button></DialogClose>
                            <Button onClick={handleAddNewStreamSubmit}><PlusCircle className="mr-2 h-4 w-4" />Submit to Pending</Button>
                          </DialogFooter>
                        </DialogContent>
                      </Dialog>

                      <Dialog open={isAddYouTubeDialogOpen} onOpenChange={setIsAddYouTubeDialogOpen}>
                        <DialogTrigger asChild>
                          <Button variant="outline" className="w-full sm:w-auto" disabled={approvedStreams.length === 0}>
                            <VideoIconLucide className="mr-2 h-4 w-4" />Add YouTube Video
                          </Button>
                        </DialogTrigger>
                        <DialogContent className="sm:max-w-md">
                           <DialogHeader>
                              <DialogTitle>Add YouTube Video to Channel</DialogTitle>
                              <DialogDescription>Link a YouTube video to any approved channel.</DialogDescription>
                            </DialogHeader>
                            <ScrollArea className="max-h-[70vh] pr-6">
                            <div className="space-y-4 py-4">
                              {approvedStreams.length > 0 ? (
                                <>
                                  <div className="space-y-2">
                                    <Label htmlFor="channel-select-admin-dialog">Select Channel</Label>
                                    <Select value={selectedStreamForVideo} onValueChange={setSelectedStreamForVideo}>
                                        <SelectTrigger id="channel-select-admin-dialog"><SelectValue placeholder="Select a channel..." /></SelectTrigger>
                                        <SelectContent>{approvedStreams.map(s => <SelectItem key={s.id} value={s.id}>{s.name}</SelectItem>)}</SelectContent>
                                    </Select>
                                  </div>
                                  <div className="space-y-2"><Label htmlFor="yt-video-title-admin-dialog">YouTube Video Title</Label><Input id="yt-video-title-admin-dialog" value={youtubeVideoTitle} onChange={(e) => setYoutubeVideoTitle(e.target.value)} placeholder="E.g., Special Announcement" /></div>
                                  <div className="space-y-2"><Label htmlFor="yt-video-url-admin-dialog">YouTube Video URL</Label><Input id="yt-video-url-admin-dialog" type="url" value={youtubeVideoUrl} onChange={(e) => setYoutubeVideoUrl(e.target.value)} placeholder="https://www.youtube.com/watch?v=..." /></div>
                                  <div className="space-y-2"><Label htmlFor="yt-video-desc-admin-dialog">Description (Optional)</Label><Textarea id="yt-video-desc-admin-dialog" value={youtubeVideoDescription} onChange={(e) => setYoutubeVideoDescription(e.target.value)} placeholder="A brief summary of the video." rows={2}/></div>
                                </>
                              ) : <p className="text-sm text-muted-foreground">No approved channels available to add videos to.</p>}
                            </div>
                            </ScrollArea>
                           <DialogFooter>
                              <DialogClose asChild><Button type="button" variant="outline">Cancel</Button></DialogClose>
                              <Button onClick={handleAddYoutubeVideo} disabled={approvedStreams.length === 0}><PlusCircle className="mr-2 h-4 w-4" /> Add Video</Button>
                            </DialogFooter>
                        </DialogContent>
                      </Dialog>

                      <Dialog open={isPlaylistDialogOpen} onOpenChange={(open) => { setIsPlaylistDialogOpen(open); if(!open) { setPlaylistStream(null); setCurrentPlaylist(null); }}}>
                        <DialogTrigger asChild>
                          <Button 
                            variant="outline" 
                            className="w-full sm:w-auto" 
                            disabled={approvedVideoStreams.length === 0}
                            onClick={() => handleOpenPlaylistDialog(approvedVideoStreams.length > 0 ? approvedVideoStreams[0] : null)}
                          >
                            <ListVideo className="mr-2 h-4 w-4" />Manage Playlists
                          </Button>
                        </DialogTrigger>
                         <DialogContent className="sm:max-w-4xl max-h-[90vh] flex flex-col">
                           <DialogHeader>
                            <DialogTitle>Manage Channel Playlists</DialogTitle>
                            <DialogDescription>Create new playlists or manage videos in existing ones.</DialogDescription>
                          </DialogHeader>
                          <div className="flex-grow overflow-hidden grid grid-cols-1 md:grid-cols-2 gap-6 -mx-6 px-6">
                            <ScrollArea className="h-full pr-1">
                                <div className="flex flex-col gap-4 py-4">
                                   <div className="space-y-2 px-1">
                                      <Label htmlFor="playlist-channel-select">Select Channel</Label>
                                       <Select
                                        value={playlistStream?.id || ''}
                                        onValueChange={(streamId) => {
                                          const stream = approvedVideoStreams.find(s => s.id === streamId);
                                          handleOpenPlaylistDialog(stream || null);
                                        }}
                                      >
                                        <SelectTrigger id="playlist-channel-select"><SelectValue placeholder="Select a channel..." /></SelectTrigger>
                                        <SelectContent>{approvedVideoStreams.map(s => <SelectItem key={s.id} value={s.id}>{s.name}</SelectItem>)}</SelectContent>
                                      </Select>
                                    </div>
                                    <div className="space-y-2 px-1">
                                        <Label>Playlists for {playlistStream?.name || '...'}</Label>
                                        <ScrollArea className="h-60 border rounded-md p-2">
                                        {playlistStream && playlistStream.playlists && Object.values(playlistStream.playlists).length > 0 ? (
                                            Object.values(playlistStream.playlists)
                                            .sort((a,b) => a.createdAt - b.createdAt)
                                            .map(pl => (
                                                <div key={pl.id} className="flex items-center gap-1">
                                                  <Button 
                                                      variant={currentPlaylist?.id === pl.id ? 'secondary' : 'ghost'} 
                                                      className="w-full justify-start flex-1"
                                                      onClick={() => setCurrentPlaylist(pl)}
                                                  >
                                                      {pl.title}
                                                  </Button>
                                                  <Button variant="ghost" size="icon" className="h-8 w-8 text-destructive" onClick={() => handleDeletePlaylist(pl.id)}><Trash2 className="h-4 w-4" /></Button>
                                                </div>
                                            ))
                                        ) : (
                                            <p className="text-sm text-muted-foreground text-center py-4">No playlists exist for this channel.</p>
                                        )}
                                        </ScrollArea>
                                    </div>
    
                                    <div className="space-y-2 px-1">
                                      <Label htmlFor="new-playlist-title">Create New Playlist</Label>
                                      <div className="flex gap-2">
                                        <Input id="new-playlist-title" value={newPlaylistTitle} onChange={(e) => setNewPlaylistTitle(e.target.value)} placeholder="New playlist title" disabled={!playlistStream}/>
                                        <Button onClick={handleCreatePlaylist} disabled={!playlistStream || !newPlaylistTitle.trim()}><FolderPlus className="h-4 w-4" /></Button>
                                      </div>
                                    </div>
                                </div>
                            </ScrollArea>
                             <ScrollArea className="h-full pr-1">
                                <div className="flex flex-col gap-4 py-4">
                                    {currentPlaylist ? (
                                      <>
                                        <div className="space-y-2 px-1">
                                          <h3 className="text-md font-semibold mb-2">Manage Videos in: <span className="text-accent">{currentPlaylist.title}</span></h3>
                                          <div className="space-y-2">
                                            <Label htmlFor="playlist-item-title-admin">Video Title</Label><Input id="playlist-item-title-admin" value={playlistItemTitle} onChange={(e) => setPlaylistItemTitle(e.target.value)} placeholder="Video Title" />
                                            <Label htmlFor="playlist-item-url-admin">YouTube URL</Label><Input id="playlist-item-url-admin" type="url" value={playlistItemUrl} onChange={(e) => setPlaylistItemUrl(e.target.value)} placeholder="https://www.youtube.com/watch?v=..." />
                                            <Button onClick={handleAddPlaylistItem} size="sm"><PlusCircle className="mr-2 h-4 w-4" />Add to Playlist</Button>
                                          </div>
                                        </div>
                                        <div className="space-y-2 px-1">
                                          <h3 className="text-md font-semibold mb-2">Current Items</h3>
                                          <ScrollArea className="h-60 border rounded-md p-2">
                                          <div className="space-y-2">
                                              {currentPlaylist.items && Object.values(currentPlaylist.items).length > 0 ? (
                                                Object.values(currentPlaylist.items).sort((a,b) => a.addedAt - b.addedAt).map((item, index, items) => (
                                                   <div key={item.id} className="flex flex-col sm:flex-row sm:items-center sm:justify-between p-2 rounded-md bg-muted gap-2">
                                                    <p className="text-sm font-medium truncate flex-1" title={item.title}>{item.title}</p>
                                                    <div className="flex items-center gap-1 self-end sm:self-center">
                                                      <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => handleReorderPlaylistItem(item.id, 'up')} disabled={index === 0}><ArrowUp className="h-4 w-4" /></Button>
                                                      <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => handleReorderPlaylistItem(item.id, 'down')} disabled={index === items.length - 1}><ArrowDown className="h-4 w-4" /></Button>
                                                      <Button variant="ghost" size="icon" className="h-8 w-8 text-destructive" onClick={() => handleRemovePlaylistItem(item.id)}><Trash2 className="h-4 w-4" /></Button>
                                                    </div>
                                                  </div>
                                                ))
                                              ) : (
                                                <p className="text-sm text-muted-foreground text-center py-4">This playlist is empty.</p>
                                              )}
                                            </div>
                                          </ScrollArea>
                                        </div>
                                      </>
                                    ) : (
                                        <div className="h-full flex items-center justify-center text-muted-foreground border rounded-md">
                                            <p>Select or create a playlist to manage videos.</p>
                                        </div>
                                    )}
                                </div>
                            </ScrollArea>
                          </div>
                          <DialogFooter className="pt-4 border-t mt-auto">
                            <DialogClose asChild><Button type="button" variant="outline">Done</Button></DialogClose>
                          </DialogFooter>
                        </DialogContent>
                      </Dialog>

                    </CardContent>
                  </Card>
                </TabsContent>

                <TabsContent value="analytics" className="mt-4 space-y-4">
                    <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
                        <Card className="lg:col-span-2">
                            <CardHeader>
                                <div className="flex flex-col sm:flex-row justify-between sm:items-center gap-2">
                                    <div>
                                        <CardTitle>Top Channels for {selectedDate ? format(selectedDate, 'PPP') : 'Today'}</CardTitle>
                                        <CardDescription>View distribution across channels for the selected day.</CardDescription>
                                    </div>
                                    <Popover>
                                        <PopoverTrigger asChild>
                                            <Button
                                                variant={"outline"}
                                                className={cn("w-full sm:w-[240px] justify-start text-left font-normal", !selectedDate && "text-muted-foreground")}
                                            >
                                                <CalendarIcon className="mr-2 h-4 w-4" />
                                                {selectedDate ? format(selectedDate, "PPP") : <span>Pick a date</span>}
                                            </Button>
                                        </PopoverTrigger>
                                        <PopoverContent className="w-auto p-0" align="start">
                                            <Calendar
                                                mode="single"
                                                selected={selectedDate}
                                                onSelect={setSelectedDate}
                                                initialFocus
                                                disabled={(date) => date > new Date() || date < new Date("2020-01-01")}
                                            />
                                        </PopoverContent>
                                    </Popover>
                                </div>
                            </CardHeader>
                            <CardContent className="p-2 flex justify-center">
                                <div className="w-full max-w-[300px] aspect-square relative">
                                    <ChartContainer
                                        config={chartConfig}
                                        className="h-full w-full"
                                    >
                                        <PieChart>
                                            <ChartTooltip
                                                content={<ChartTooltipContent nameKey="views" hideLabel />}
                                            />
                                            <Pie
                                                data={analyticsData.topChannelsToday}
                                                dataKey="views"
                                                nameKey="name"
                                                innerRadius={60}
                                                outerRadius={100}
                                            >
                                                {analyticsData.topChannelsToday.map((entry) => (
                                                <Cell key={`cell-${entry.name}`} fill={(chartConfig[entry.name as keyof typeof chartConfig] as any)?.color || chartConfig['Others'].color} />
                                                ))}
                                            </Pie>
                                        </PieChart>
                                    </ChartContainer>
                                    <div className="absolute inset-0 flex flex-col items-center justify-center" aria-hidden="true">
                                        <span className="text-3xl font-bold text-foreground">{analyticsData.totalViewsToday.toLocaleString()}</span>
                                        <span className="text-sm text-muted-foreground">Total Views</span>
                                    </div>
                                </div>
                            </CardContent>
                            {analyticsData.topChannelsToday.length > 0 && (
                                <CardFooter className="flex-col gap-2 text-sm pt-4 border-t">
                                    <div className="w-full grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-x-4 gap-y-2">
                                        {analyticsData.topChannelsToday.map((entry) => (
                                            <div key={entry.name} className="flex items-center gap-2">
                                                <div className="w-3 h-3 rounded-full" style={{ backgroundColor: (chartConfig[entry.name as keyof typeof chartConfig] as any)?.color || chartConfig['Others'].color }} />
                                                <span className="truncate" title={entry.name}>{entry.name}</span>
                                                <span className="font-semibold ml-auto">{entry.views.toLocaleString()}</span>
                                            </div>
                                        ))}
                                    </div>
                                </CardFooter>
                            )}
                        </Card>

                        <Card>
                            <CardHeader>
                                <CardTitle>Views by Time for {selectedDate ? format(selectedDate, 'PPP') : 'Today'}</CardTitle>
                                <CardDescription>View distribution in 2-hour intervals for the selected day.</CardDescription>
                            </CardHeader>
                             <CardContent className="p-2 flex justify-center">
                                <div className="w-full max-w-[300px] aspect-square relative">
                                    <ChartContainer
                                        config={chartConfig}
                                        className="h-full w-full"
                                    >
                                        <PieChart>
                                            <ChartTooltip
                                                content={<ChartTooltipContent nameKey="views" hideLabel />}
                                            />
                                            <Pie 
                                                data={analyticsData.twoHourIntervalData} 
                                                dataKey="views" 
                                                nameKey="name"
                                                innerRadius={60}
                                                outerRadius={100}
                                            >
                                                {analyticsData.twoHourIntervalData.map((entry) => (
                                                    <Cell key={`cell-${entry.name}`} fill={(chartConfig[entry.name as keyof typeof chartConfig] as any)?.color || chartConfig['Others'].color} />
                                                ))}
                                            </Pie>
                                        </PieChart>
                                    </ChartContainer>
                                    <div className="absolute inset-0 flex flex-col items-center justify-center" aria-hidden="true">
                                        <span className="text-3xl font-bold text-foreground">{analyticsData.totalViewsForDayInIntervals.toLocaleString()}</span>
                                        <span className="text-sm text-muted-foreground">Total Views</span>
                                    </div>
                                </div>
                            </CardContent>
                            {analyticsData.totalViewsForDayInIntervals > 0 && (
                                <CardFooter className="flex-col gap-2 text-sm pt-4 border-t">
                                    <div className="w-full grid grid-cols-2 md:grid-cols-3 gap-x-4 gap-y-2">
                                        {analyticsData.twoHourIntervalData.filter(e => e.views > 0).map((entry) => (
                                            <div key={entry.name} className="flex items-center gap-2">
                                                <div className="w-3 h-3 rounded-full" style={{ backgroundColor: (chartConfig[entry.name as keyof typeof chartConfig] as any)?.color || chartConfig['Others'].color }} />
                                                <span className="truncate" title={entry.name}>{entry.name}</span>
                                                <span className="font-semibold ml-auto">{entry.views.toLocaleString()}</span>
                                            </div>
                                        ))}
                                    </div>
                                </CardFooter>
                            )}
                        </Card>
                        
                        <Card>
                        <CardHeader>
                            <CardTitle>Daily Views (Last 30 Days)</CardTitle>
                            <CardDescription>Total stream views per day.</CardDescription>
                        </CardHeader>
                        <CardContent>
                            <ChartContainer config={chartConfig} className="h-[250px] w-full">
                            <RechartsBarChart data={analyticsData.dailyData}>
                                <CartesianGrid vertical={false} />
                                <XAxis dataKey="date" tickLine={false} axisLine={false} tickMargin={8} />
                                <ChartTooltip cursor={false} content={<ChartTooltipContent indicator="line" />} />
                                <Bar dataKey="views" fill="hsl(var(--foreground))" radius={4} />
                            </RechartsBarChart>
                            </ChartContainer>
                        </CardContent>
                        </Card>
                        <Card>
                        <CardHeader>
                            <CardTitle>Monthly Views (Last 12 Months)</CardTitle>
                            <CardDescription>Total stream views per month.</CardDescription>
                        </CardHeader>
                        <CardContent>
                            <ChartContainer config={chartConfig} className="h-[250px] w-full">
                            <RechartsBarChart data={analyticsData.monthlyData}>
                                <CartesianGrid vertical={false} />
                                <XAxis dataKey="month" tickLine={false} axisLine={false} tickMargin={8} />
                                <ChartTooltip cursor={false} content={<ChartTooltipContent indicator="line" />} />
                                <Bar dataKey="views" fill="hsl(var(--foreground))" radius={4} />
                            </RechartsBarChart>
                            </ChartContainer>
                        </CardContent>
                        </Card>
                    </div>
                </TabsContent>

                <TabsContent value="users" className="mt-4 space-y-4">
                    <Card><CardHeader><CardTitle className="flex items-center gap-2"><Users className="w-6 h-6 text-primary"/>Registered Users</CardTitle><CardDescription>List of authenticated users from Firebase.</CardDescription></CardHeader>
                    <CardContent>
                        <div className="overflow-x-auto">
                        {registeredUsers.length === 0 ? <p>No users found.</p> : (
                            <Table><TableHeader><TableRow><TableHead>Username</TableHead><TableHead>Email</TableHead><TableHead>Role</TableHead><TableHead>Login Method</TableHead><TableHead>Date Created</TableHead></TableRow></TableHeader>
                            <TableBody>{registeredUsers.map((u) => (<TableRow key={u.id}><TableCell>{u.username}</TableCell><TableCell>{u.email}</TableCell><TableCell className="capitalize">{u.role}</TableCell><TableCell className="capitalize">{u.method}</TableCell><TableCell className="truncate max-w-xs">{u.createdAt ? new Date(u.createdAt).toLocaleDateString() : 'N/A'}</TableCell></TableRow>))}</TableBody>
                            </Table>
                        )}
                        </div>
                    </CardContent>
                    </Card>
                </TabsContent>

                <TabsContent value="logs" className="mt-4 space-y-4">
                    <Card>
                    <CardHeader>
                        <CardTitle className="flex items-center gap-2"><XCircle className="w-6 h-6 text-red-500" />Rejected Streams</CardTitle>
                        <CardDescription>History of HLS streams rejected by admin.</CardDescription>
                    </CardHeader>
                    <CardContent>
                        <div className="overflow-x-auto">
                        {rejectedStreams.length === 0 ? <p>No streams rejected yet.</p> : (
                            <Table>
                            <TableHeader><TableRow><TableHead>Name</TableHead><TableHead>Creator</TableHead><TableHead>Submitted At</TableHead></TableRow></TableHeader>
                            <TableBody>
                                {rejectedStreams.map((s) => (
                                <TableRow key={s.id}>
                                    <TableCell>{s.name}</TableCell>
                                    <TableCell className="truncate">{getCreatorUsername(s.creatorId)}</TableCell>
                                    <TableCell>{s.createdAt ? new Date(s.createdAt).toLocaleString() : "N/A"}</TableCell>
                                </TableRow>
                                ))}
                            </TableBody>
                            </Table>
                        )}
                        </div>
                    </CardContent>
                    </Card>
                    <Card>
                    <CardHeader><CardTitle className="flex items-center gap-2"><History className="w-6 h-6 text-primary"/>Deleted Streams History</CardTitle><CardDescription>Record of admin-deleted HLS streams.</CardDescription></CardHeader>
                    <CardContent>
                        <div className="overflow-x-auto">
                        {deletedStreamsHistory.length === 0 ? <p>No streams deleted yet.</p> : (
                            <Table><TableHeader><TableRow><TableHead>Name</TableHead><TableHead>Creator</TableHead><TableHead>Deleted At</TableHead></TableRow></TableHeader>
                            <TableBody>{deletedStreamsHistory.map((s) => (<TableRow key={s.id}><TableCell>{s.name}</TableCell><TableCell className="truncate">{getCreatorUsername(s.creatorId)}</TableCell><TableCell>{s.deletedAt ? new Date(s.deletedAt).toLocaleString() : "N/A"}</TableCell></TableRow>))}</TableBody>
                            </Table>
                        )}
                        </div>
                    </CardContent>
                    </Card>
                </TabsContent>
            </Tabs>
        </div>
      </div>

      {editingApprovedStream && (
        <Dialog open={isEditApprovedStreamDialogOpen} onOpenChange={(isOpen) => { if (!isOpen) setEditingApprovedStream(null); setIsEditApprovedStreamDialogOpen(isOpen); }}>
          <DialogContent className="sm:max-w-[600px]">
            <DialogHeader><DialogTitle>Admin Edit Stream: {editingApprovedStream.name}</DialogTitle><DialogDescription>Creator: {getCreatorUsername(editingApprovedStream.creatorId)}</DialogDescription></DialogHeader>
            <div className="grid gap-4 py-4">
              <div className="grid grid-cols-4 items-center gap-4"><Label htmlFor="edit-approved-stream-name" className="text-right col-span-1">Name</Label><Input id="edit-approved-stream-name" value={editedApprovedStreamName} onChange={(e) => setEditedApprovedStreamName(e.target.value)} className="col-span-3" /></div>
              <div className="grid grid-cols-4 items-center gap-4"><Label htmlFor="edit-approved-stream-url1" className="text-right col-span-1">Primary URL</Label><Input id="edit-approved-stream-url1" type="url" value={editedApprovedStreamUrl1} onChange={(e) => setEditedApprovedStreamUrl1(e.target.value)} className="col-span-3" /></div>
              <div className="grid grid-cols-4 items-center gap-4"><Label htmlFor="edit-approved-stream-url2" className="text-right col-span-1">Backup URL 1</Label><Input id="edit-approved-stream-url2" type="url" value={editedApprovedStreamUrl2} onChange={(e) => setEditedApprovedStreamUrl2(e.target.value)} className="col-span-3" /></div>
              <div className="grid grid-cols-4 items-center gap-4"><Label htmlFor="edit-approved-stream-url3" className="text-right col-span-1">Backup URL 2</Label><Input id="edit-approved-stream-url3" type="url" value={editedApprovedStreamUrl3} onChange={(e) => setEditedApprovedStreamUrl3(e.target.value)} className="col-span-3" /></div>
              <div className="grid grid-cols-4 items-center gap-4"><Label htmlFor="edit-approved-stream-description" className="text-right col-span-1">Description</Label><Textarea id="edit-approved-stream-description" value={editedApprovedStreamDescription} onChange={(e) => setEditedApprovedStreamDescription(e.target.value)} className="col-span-3" /></div>
            </div>
            <DialogFooter>
              <DialogClose asChild><Button type="button" variant="outline">Cancel</Button></DialogClose>
              <Button type="button" onClick={handleSaveEditedApprovedStream}>Save Changes</Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      )}

      {selectedStreamForPreview && (
        <Dialog open={isPreviewDialogOpen} onOpenChange={(isOpen) => { if (!isOpen) closePreviewDialog(); }}>
          <DialogContent className="sm:max-w-[600px] md:max-w-[800px] lg:max-w-[1000px] w-full">
            <DialogHeader>
              <DialogTitle>Preview: {selectedStreamForPreview.name}</DialogTitle>
              {selectedStreamForPreview.description && <DialogDescription>{selectedStreamForPreview.description}</DialogDescription>}
            </DialogHeader>
            <div className="my-4">
              {selectedStreamForPreview.streamType === 'audio' ? (
                <AudioPlayer src={selectedStreamForPreview.sourceUrls[0]} autoPlay={true} />
              ) : (
                <HlsPlayer src={selectedStreamForPreview.sourceUrls} autoPlay={true} onActiveSourceChanged={setActivePreviewPlayingUrl} />
              )}
            </div>
            {activePreviewPlayingUrl && selectedStreamForPreview.streamType !== 'audio' && (
              <div className="mt-2 text-sm">
                <span>Active Source: </span><code>{activePreviewPlayingUrl}</code>
              </div>
            )}
            <DialogFooter className="mt-4">
              <Button variant="secondary" onClick={closePreviewDialog}>Close</Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      )}

      {lastSubmittedStreamForPreview && (
        <Dialog open={isPreviewSubmittedStreamDialogOpen} onOpenChange={setIsPreviewSubmittedStreamDialogOpen}>
          <DialogContent className="sm:max-w-[600px] md:max-w-[800px] lg:max-w-[1000px] w-full">
            <DialogHeader>
              <DialogTitle>Preview: {lastSubmittedStreamForPreview.name}</DialogTitle>
              {lastSubmittedStreamForPreview.description && <DialogDescription>{lastSubmittedStreamForPreview.description}</DialogDescription>}
              <DialogDescription className="text-xs pt-1">Submitted to pending.</DialogDescription>
            </DialogHeader>
            <div className="my-4 rounded-lg overflow-hidden">
             {lastSubmittedStreamForPreview.streamType === 'audio' ? (
                <AudioPlayer src={lastSubmittedStreamForPreview.sourceUrls[0]} autoPlay={true} />
              ) : (
                <HlsPlayer src={lastSubmittedStreamForPreview.sourceUrls} autoPlay={true} />
              )}
            </div>
            <DialogFooter>
              <Button variant="secondary" onClick={() => setIsPreviewSubmittedStreamDialogOpen(false)}>Close</Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      )}

      {selectedVideoForPreview && (
        <Dialog open={isVideoPreviewDialogOpen} onOpenChange={(isOpen) => { if (!isOpen) closeVideoPreviewDialog(); }}>
          <DialogContent className="sm:max-w-[600px] md:max-w-[800px] lg:max-w-[1000px] w-full">
            <DialogHeader>
              <DialogTitle>Preview Video: {selectedVideoForPreview.title}</DialogTitle>
              {selectedVideoForPreview.description && <DialogDescription>{selectedVideoForPreview.description}</DialogDescription>}
            </DialogHeader>
            <div className="my-4 rounded-lg overflow-hidden">
              {selectedVideoForPreview.videoStorageUrl ? (
                <video 
                  src={selectedVideoForPreview.videoStorageUrl} 
                  controls 
                  className="w-full aspect-video rounded-md bg-muted object-contain" 
                  autoPlay 
                />
              ) : ( 
                <div className="aspect-video w-full flex flex-col items-center justify-center bg-muted rounded-md p-4">
                    <VideoIconLucide className="w-16 h-16 text-muted-foreground mb-2"/>
                    <p className="text-muted-foreground text-center">Video preview not available for this submission.</p>
                </div>
              )}
            </div>
             <DialogFooter className="mt-4">
              <Button type="button" variant="secondary" onClick={closeVideoPreviewDialog}>Close Preview</Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      )}

      {pinningStream && (
        <Dialog open={isPinDialogOpen} onOpenChange={setIsPinDialogOpen}>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Pin {pinningStream.streamType === 'audio' ? 'Audio' : 'Video'} Stream: {pinningStream.name}</DialogTitle>
              <DialogDescription>
                Select a slot from 1 to 5 to pin this stream to the top of its section on the homepage. Selecting a slot already in use will replace the existing stream.
              </DialogDescription>
            </DialogHeader>
            <RadioGroup value={selectedPinSlot || ""} onValueChange={setSelectedPinSlot} className="py-4 space-y-2">
              {Array.from({ length: 5 }, (_, i) => i + 1).map((slot) => (
                <div key={slot} className="flex items-center justify-between p-2 rounded-md border">
                  <Label htmlFor={`pin-slot-${slot}`} className="flex items-center gap-2 cursor-pointer">
                    <RadioGroupItem value={String(slot)} id={`pin-slot-${slot}`} />
                    Pin to Slot {slot}
                  </Label>
                  {currentlyPinned[slot] && (
                    <span className="text-xs text-muted-foreground">
                      Currently: <span className="font-semibold text-foreground">{currentlyPinned[slot]}</span>
                      {currentlyPinned[slot] === pinningStream.name && " (This stream)"}
                    </span>
                  )}
                </div>
              ))}
              <div className="flex items-center justify-between p-2 rounded-md border border-destructive/50">
                <Label htmlFor="unpin-slot" className="flex items-center gap-2 cursor-pointer text-destructive">
                  <RadioGroupItem value="unpin" id="unpin-slot" />
                  Unpin Stream
                </Label>
              </div>
            </RadioGroup>
            <DialogFooter>
              <Button variant="outline" onClick={() => setIsPinDialogOpen(false)}>Cancel</Button>
              <Button onClick={handleSavePin}>Save Pin</Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      )}
    </main>
  );
}

    

    















    
