

"use client";

import { useState, useEffect, useMemo } from "react";
import type { Stream, UploadedVideo, AssociatedVideo, PlaylistItem, Playlist, ViewLog } 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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { ArrowLeft, Edit, UserCog, Send, Eye, Users, LogOut, PlusCircle, Video as VideoIconLucide, Briefcase, ListVideo, Trash2, ArrowDown, ArrowUp, FolderPlus, AreaChart, Calendar as CalendarIcon } 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, query, orderByChild, equalTo, remove } from "firebase/database";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { ScrollArea } from "@/components/ui/scroll-area";
import { AudioPlayer } from "@/components/audio-player";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { format, startOfDay, endOfDay, subDays, subMonths, startOfMonth } from "date-fns";
import type { ChartConfig } from "@/components/ui/chart";
import { ChartContainer, ChartTooltip, ChartTooltipContent } from "@/components/ui/chart";
import { Bar, BarChart as RechartsBarChart, CartesianGrid, XAxis, PieChart, Pie, Cell } from "recharts";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Calendar } from "@/components/ui/calendar";
import { cn } from "@/lib/utils";

const chartConfig = {
  views: {
    label: "Views",
    color: "hsl(var(--foreground))",
  },
  "chart-1": { label: "Chart 1", color: "hsl(var(--chart-1))", },
  "chart-2": { label: "Chart 2", color: "hsl(var(--chart-2))", },
  "chart-3": { label: "Chart 3", color: "hsl(var(--chart-3))", },
  "chart-4": { label: "Chart 4", color: "hsl(var(--chart-4))", },
  "chart-5": { label: "Chart 5", 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;


export default function UserDashboardPage() {
  const [isClient, setIsClient] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [editableStreams, setEditableStreams] = useState<Stream[]>([]);
  const [editingStream, setEditingStream] = useState<Stream | null>(null);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const { toast } = useToast();

  const [editedName, setEditedName] = useState('');
  const [editedUrl1, setEditedUrl1] = useState('');
  const [editedUrl2, setEditedUrl2] = useState('');
  const [editedUrl3, setEditedUrl3] = useState('');
  const [editedDescription, setEditedDescription] = useState('');

  const [selectedStreamForPreview, setSelectedStreamForPreview] = useState<Stream | null>(null);
  const [isPreviewDialogOpen, setIsPreviewDialogOpen] = useState(false);
  const [activePreviewPlayingUrl, setActivePreviewPlayingUrl] = 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 [isAddYouTubeDialogOpen, setIsAddYouTubeDialogOpen] = useState(false);

  // State for adding new HLS stream
  const [isAddStreamDialogOpen, setIsAddStreamDialogOpen] = useState(false);
  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 [manageVideosStreamId, setManageVideosStreamId] = useState<string>('');


  const [approvedUserVideos, setApprovedUserVideos] = useState<UploadedVideo[]>([]);
  const [selectedVideoToPlay, setSelectedVideoToPlay] = useState<AssociatedVideo | null>(null);
  const [isPlayVideoDialogOpen, setIsPlayVideoDialogOpen] = useState(false);

  // 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('');

  // Analytics State
  const [allApprovedStreams, setAllApprovedStreams] = useState<Stream[]>([]);
  const [viewLogs, setViewLogs] = useState<ViewLog[]>([]);
  const [selectedDate, setSelectedDate] = useState<Date | undefined>(new Date());


  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 loadCreatorDataFromRTDB = () => {
    if (!userId) return [];
    setIsLoading(true);

    const streamsQuery = query(ref(db, 'streams'), orderByChild('creatorId'), equalTo(userId));
    const streamsUnsubscribe = onValue(streamsQuery, (snapshot) => {
        const streamsData = snapshot.val() || {};
        const userStreams: Stream[] = Object.keys(streamsData)
            .map(key => ({ id: key, ...streamsData[key] }))
            .filter(s => s.status === 'approved' || s.status === 'pending');
        
        setEditableStreams(userStreams.sort((a,b) => (b.createdAt || 0) - (a.createdAt || 0)));

        if (userStreams.length > 0 && !selectedStreamForVideo) {
            const firstApprovedVideoChannel = userStreams.find(s => s.status === 'approved' && s.streamType !== 'audio');
            if (firstApprovedVideoChannel) {
                setSelectedStreamForVideo(firstApprovedVideoChannel.id);
            }
        }
    }, (error) => {
        console.error("Error fetching creator streams:", error);
        toast({ title: "Error", description: "Could not load your stream data.", variant: "destructive" });
    });

    const allStreamsRef = ref(db, 'streams');
    const allStreamsUnsubscribe = onValue(allStreamsRef, (snapshot) => {
        const allStreamsData = snapshot.val() || {};
        const allStreams: Stream[] = Object.keys(allStreamsData).map(key => ({ id: key, ...allStreamsData[key] }));
        setAllApprovedStreams(allStreams.filter(s => s.status === 'approved'));
    });

    const viewLogsRef = ref(db, 'view_logs');
    const viewLogsUnsubscribe = onValue(viewLogsRef, (snapshot) => {
        const viewLogsData = snapshot.val() || {};
        const viewLogsList: ViewLog[] = Object.keys(viewLogsData).map(key => ({ id: key, ...viewLogsData[key]}));
        setViewLogs(viewLogsList);
    });

    Promise.all([
        get(streamsQuery),
        get(allStreamsRef),
        get(viewLogsRef)
    ]).then(() => {
        setIsLoading(false);
    }).catch(error => {
        console.error("Error fetching initial data for creator dashboard:", error);
        toast({ title: "Error", description: "Could not load all dashboard data.", variant: "destructive" });
        setIsLoading(false);
    });

    return [streamsUnsubscribe, allStreamsUnsubscribe, viewLogsUnsubscribe];
  };
  

  useEffect(() => {
    setIsClient(true);
    if (typeof window !== 'undefined') {
      if (!isAuthenticated || (userRole !== 'creator' && userRole !== 'admin') || !userId) {
        router.push('/login');
        return;
      }
      const unsubscribers = loadCreatorDataFromRTDB();
      return () => unsubscribers.forEach(unsub => unsub());
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isAuthenticated, userRole, router, userId]);
  
  useEffect(() => {
    // This effect keeps the playlist dialog in sync with the live data from Firebase
    if (playlistStream) {
      const updatedStreamData = editableStreams.find(s => s.id === playlistStream.id);
      setPlaylistStream(updatedStreamData || null);
      if (currentPlaylist) {
        const updatedPlaylistData = updatedStreamData?.playlists?.[currentPlaylist.id];
        setCurrentPlaylist(updatedPlaylistData || null);
      }
    }
  }, [editableStreams, playlistStream, currentPlaylist]);

  const handleEditStream = (streamToEdit: Stream) => {
    setEditingStream(streamToEdit);
    setEditedName(streamToEdit.name);
    setEditedUrl1(streamToEdit.sourceUrls[0] || '');
    setEditedUrl2(streamToEdit.sourceUrls[1] || '');
    setEditedUrl3(streamToEdit.sourceUrls[2] || '');
    setEditedDescription(streamToEdit.description || '');
    setIsEditDialogOpen(true);
  };
  
  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 validateUrlForForm = (url: string, fieldName: string, streamType: 'video' | 'audio', isPrimary = false) => {
    const trimmedUrl = url.trim();
    if (isPrimary && !trimmedUrl) {
        toast({ title: "Validation Error", description: `${fieldName} is required.`, variant: "destructive" });
        return false;
    }
    if (trimmedUrl) {
        const isYouTubeUrl = trimmedUrl.includes("youtube.com") || trimmedUrl.includes("youtu.be");
        if (isYouTubeUrl && streamType === 'video') {
            return true;
        }

        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 if (!trimmedUrl.startsWith('https://')) {
            toast({ title: "Validation Error", description: `URL for "${fieldName}" must start with https://.`, variant: "destructive" });
            return false;
        }
    }
    return true;
  };

  const handleSaveStream = async () => {
    if (!editingStream || !userId || editingStream.creatorId !== userId) {
        toast({ title: "Error", description: "You cannot edit a stream you do not own.", variant: "destructive" });
        return;
    }
    
    const streamType = editingStream.streamType || 'video';

    if (!validateUrlForForm(editedUrl1, "Primary Stream URL", streamType, true) || (editedUrl2.trim() && !validateUrlForForm(editedUrl2, "Backup URL 1", streamType)) || (editedUrl3.trim() && !validateUrlForForm(editedUrl3, "Backup URL 2", streamType))) {
        return;
    }

    const updatedSourceUrls = [editedUrl1.trim()];
    if (editedUrl2.trim()) updatedSourceUrls.push(editedUrl2.trim());
    if (editedUrl3.trim()) updatedSourceUrls.push(editedUrl3.trim());

    try {
        await update(ref(db, `streams/${editingStream.id}`), {
            name: editedName.trim() || editingStream.name,
            sourceUrls: updatedSourceUrls,
            description: editedDescription.trim() || '',
        });
        toast({ title: "Stream Updated", description: `${editingStream.name} has been updated.` });
        setIsEditDialogOpen(false);
        setEditingStream(null);
    } catch (error) {
        console.error("Error updating stream:", error);
        toast({ title: "Error", description: "Could not update the stream.", variant: "destructive" });
    }
  };

  const handleRequestStreamDeletion = async (streamToDelete: Stream) => {
    if (streamToDelete.creatorId !== userId) {
        toast({ title: "Error", description: "You can only request deletion for your own streams.", variant: "destructive" });
        return;
    }

    try {
        await update(ref(db, `streams/${streamToDelete.id}`), { status: 'pending_deletion' });
        toast({ title: "Deletion Requested", description: `Request to delete ${streamToDelete.name} sent to admin.` });
    } catch (error) {
        console.error("Error requesting stream deletion:", error);
        toast({ title: "Error", description: "Could not request deletion.", 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 approvedEditableStreams = editableStreams.filter(s => s.status === 'approved');
    const selectedStreamObject = approvedEditableStreams.find(s => s.id === selectedStreamForVideo);
    
    if (!selectedStreamObject) {
       toast({ title: "Channel Not Found", description: "The selected channel is not valid or not approved.", 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 your 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 handleAddNewStreamSubmit = async () => {
    if (!newStreamName.trim()) { toast({ title: "Validation Error", description: "Stream Name required.", variant: "destructive" }); return; }
    if (!validateUrlForForm(newStreamUrl1, "Primary Stream URL", newStreamType, true) || (newStreamUrl2.trim() && !validateUrlForForm(newStreamUrl2, "Backup URL 1", newStreamType)) || (newStreamUrl3.trim() && !validateUrlForForm(newStreamUrl3, "Backup URL 2", newStreamType))) return;
    if (!userId) { toast({ title: "Auth Error", description: "Your user ID was 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", description: `${newStreamData.name} has been sent for admin approval.` });
        
        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 handleOpenPlaylistDialog = (stream: Stream | null) => {
    if (!stream) return;
    setPlaylistStream(stream);
    setCurrentPlaylist(null); // Reset current playlist
    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 openPreviewDialog = (stream: Stream) => {
    setSelectedStreamForPreview(stream);
    setActivePreviewPlayingUrl(null);
    setIsPreviewDialogOpen(true);
  };

  const closePreviewDialog = () => {
    setIsPreviewDialogOpen(false);
    setSelectedStreamForPreview(null);
    setActivePreviewPlayingUrl(null);
  };

  const openPlayVideoDialog = (video: AssociatedVideo) => {
    setSelectedVideoToPlay(video);
    setIsPlayVideoDialogOpen(true);
  };
  const closePlayVideoDialog = () => {
    setIsPlayVideoDialogOpen(false);
    setSelectedVideoToPlay(null);
  };

  const approvedEditableStreams = editableStreams.filter(s => s.status === 'approved' && s.streamType !== 'audio');

  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 = allApprovedStreams.find((s) => s.id === log.streamId);
        dailyChannelViews[log.streamId] = {
          name: stream?.name || "Unknown Channel",
          views: 0,
        };
      }
      dailyChannelViews[log.streamId].views++;
    });

    const topChannels = Object.values(dailyChannelViews)
        .map(channel => ({ ...channel, 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);

    const dynamicChartConfig: ChartConfig = { ...chartConfig };
    topChannels.forEach((item, index) => {
        if (!dynamicChartConfig[item.name]) {
            const key = `chart-${(index % 5) + 1}`; // Cycle through chart-1 to chart-5
            dynamicChartConfig[item.name] = {
                label: item.name,
                color: `hsl(var(--${key}))`,
            };
        }
    });

    return { topChannels, totalViewsToday, dynamicChartConfig, dailyData, monthlyData, twoHourIntervalData: twoHourIntervals, totalViewsForDayInIntervals };
  }, [viewLogs, allApprovedStreams, selectedDate]);
  
  const videoChannelsWithContent = useMemo(() => {
    return editableStreams.filter(stream => stream.status === 'approved' && stream.streamType !== 'audio' && stream.associatedVideos && Object.keys(stream.associatedVideos).length > 0);
  }, [editableStreams]);

  const selectedStreamForVideoManagement = useMemo(() => {
    return editableStreams.find(s => s.id === manageVideosStreamId);
  }, [editableStreams, manageVideosStreamId]);

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


  if (!isClient || !isAuthenticated || (userRole !== 'creator' && userRole !== 'admin') || !userId) {
    return (
      <div className="min-h-screen flex flex-col items-center justify-center p-4">
        <Card className="w-full max-w-2xl shadow-xl rounded-lg"><CardHeader><CardTitle className="text-2xl text-center">Access Denied</CardTitle></CardHeader><CardContent><p className="text-muted-foreground text-center">Redirecting to login...</p></CardContent></Card>
      </div>
    );
  }
  
  if (isLoading) {
    return (
      <div className="min-h-screen flex flex-col items-center justify-center p-4">
        <Card className="w-full max-w-2xl shadow-xl rounded-lg"><CardHeader><CardTitle className="text-2xl text-center">Loading Dashboard...</CardTitle></CardHeader><CardContent><p className="text-muted-foreground text-center">Fetching your data from the cloud...</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-4xl 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"><UserCog className="w-8 h-8 text-primary" /><CardTitle className="text-2xl sm:text-3xl font-bold text-foreground">Creator 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="manage" className="w-full">
            <TabsList className="grid w-full grid-cols-2">
              <TabsTrigger value="manage">Manage Content</TabsTrigger>
              <TabsTrigger value="analytics">Analytics</TabsTrigger>
            </TabsList>
            <TabsContent value="manage" className="mt-4 space-y-4 md:space-y-6">
              <Card>
                <CardHeader><CardTitle className="text-xl sm:text-2xl text-foreground">Manage Your Content</CardTitle><CardDescription>Submit new channels or manage existing content.</CardDescription></CardHeader>
                <CardContent>
                  <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">
                        <div className="flex flex-wrap gap-2">
                            <Dialog open={isAddStreamDialogOpen} onOpenChange={setIsAddStreamDialogOpen}>
                                <DialogTrigger asChild>
                                  <Button variant="outline"><PlusCircle className="mr-2 h-4 w-4" />Submit New Channel</Button>
                                </DialogTrigger>
                                <DialogContent className="sm:max-w-md">
                                  <DialogHeader>
                                    <DialogTitle>Submit New Channel for Approval</DialogTitle>
                                    <DialogDescription>Your channel will be reviewed by an admin before it goes live.</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="c-type-video" className="peer sr-only" /><Label htmlFor="c-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="c-type-audio" className="peer sr-only" /><Label htmlFor="c-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">Channel Name</Label><Input id="new-stream-name" value={newStreamName} onChange={(e) => setNewStreamName(e.target.value)} placeholder="E.g., My Awesome Live Show" /></div>
                                    <div><Label htmlFor="new-stream-url1">Primary Stream URL ({newStreamType === 'video' ? 'HLS/YouTube/Embed' : 'Audio'})</Label><Input id="new-stream-url1" type="url" value={newStreamUrl1} onChange={(e) => setNewStreamUrl1(e.target.value)} placeholder="https://example.com/stream.m3u8"/></div>
                                    <div><Label htmlFor="new-stream-url2">Backup URL 1 (Optional)</Label><Input id="new-stream-url2" type="url" value={newStreamUrl2} onChange={(e) => setNewStreamUrl2(e.target.value)} placeholder="https://backup.example.com/stream.m3u8"/></div>
                                    <div><Label htmlFor="new-stream-url3">Backup URL 2 (Optional)</Label><Input id="new-stream-url3" type="url" value={newStreamUrl3} onChange={(e) => setNewStreamUrl3(e.target.value)} placeholder="https://another.com/stream.m3u8"/></div>
                                    <div><Label htmlFor="new-stream-description">Description (Optional)</Label><Textarea id="new-stream-description" value={newStreamDescription} onChange={(e) => setNewStreamDescription(e.target.value)} placeholder="A brief description of your stream." 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 for Approval</Button>
                                  </DialogFooter>
                                </DialogContent>
                            </Dialog>
                        </div>
                        <div className="mt-4">
                            <h3 className="text-lg font-semibold mb-2">Your Submitted Channels</h3>
                            <div className="overflow-x-auto border rounded-lg">
                            {editableStreams.length === 0 ? (<p className="text-muted-foreground p-4 text-center">No channels submitted yet for your account.</p>) 
                            : (<Table><TableHeader><TableRow><TableHead>Name</TableHead><TableHead>Status</TableHead><TableHead className="text-center">Views</TableHead><TableHead className="text-right">Actions</TableHead></TableRow></TableHeader>
                                <TableBody>{editableStreams.map((stream) => (<TableRow key={stream.id}><TableCell className="font-medium">{stream.name}</TableCell>
                                <TableCell>
                                    <span className={`px-2 py-1 text-xs font-medium rounded-full ${
                                        stream.status === 'approved' ? 'bg-green-100 text-green-800' :
                                        stream.status === 'pending' ? 'bg-yellow-100 text-yellow-800' :
                                        stream.status === 'rejected' ? 'bg-red-100 text-red-800' :
                                        'bg-gray-100 text-gray-800'
                                    }`}>
                                        {stream.status}
                                    </span>
                                </TableCell>
                                <TableCell className="text-center text-sm text-muted-foreground"><div className="flex items-center justify-center gap-1"><Users className="w-4 h-4" />{(stream.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={() => openPreviewDialog(stream)}><Eye className="w-4 h-4 sm:mr-1" /><span className="hidden sm:inline">Preview</span></Button>
                                        {stream.streamType !== 'audio' && (
                                          <Button variant="outline" size="sm" onClick={() => handleOpenPlaylistDialog(stream)} disabled={stream.status !== 'approved'}><ListVideo className="w-4 h-4 sm:mr-1" /><span className="hidden sm:inline">Playlists</span></Button>
                                        )}
                                        <Button variant="outline" size="sm" onClick={() => handleEditStream(stream)} disabled={stream.status !== 'approved'}><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 hover:bg-yellow-500/10" onClick={() => handleRequestStreamDeletion(stream)} disabled={stream.status !== 'approved'}><Send className="w-4 h-4 sm:mr-1" /><span className="hidden sm:inline">Request Deletion</span></Button>
                                    </div>
                                </TableCell>
                                </TableRow>))}</TableBody>
                                </Table>
                            )}
                            </div>
                        </div>
                    </TabsContent>
                    <TabsContent value="videos" className="mt-4">
                        <div className="flex flex-wrap gap-2">
                           <Dialog open={isAddYouTubeDialogOpen} onOpenChange={setIsAddYouTubeDialogOpen}>
                                <DialogTrigger asChild>
                                    <Button variant="outline" disabled={approvedEditableStreams.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 one of your approved video channels.</DialogDescription>
                                    </DialogHeader>
                                    <ScrollArea className="max-h-[70vh] pr-6">
                                    <div className="space-y-4 py-4">
                                        {approvedEditableStreams.length > 0 ? (
                                            <>
                                                <div className="space-y-2">
                                                    <Label htmlFor="channel-select-dialog">Select Channel</Label>
                                                    <Select value={selectedStreamForVideo} onValueChange={setSelectedStreamForVideo}>
                                                        <SelectTrigger id="channel-select-dialog"><SelectValue placeholder="Select a channel..." /></SelectTrigger>
                                                        <SelectContent>{approvedEditableStreams.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-dialog">YouTube Video Title</Label><Input id="yt-video-title-dialog" value={youtubeVideoTitle} onChange={(e) => setYoutubeVideoTitle(e.target.value)} placeholder="E.g., My Latest Update" /></div>
                                                <div className="space-y-2"><Label htmlFor="yt-video-url-dialog">YouTube Video URL</Label><Input id="yt-video-url-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-dialog">Description (Optional)</Label><Textarea id="yt-video-desc-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 text-center py-4">You need to have at least one approved video channel to add a video.</p>
                                        )}
                                    </div>
                                    </ScrollArea>
                                    <DialogFooter>
                                        <DialogClose asChild><Button type="button" variant="outline">Cancel</Button></DialogClose>
                                        <Button onClick={handleAddYoutubeVideo} disabled={approvedEditableStreams.length === 0}><PlusCircle className="mr-2 h-4 w-4" /> Add Video</Button>
                                    </DialogFooter>
                                </DialogContent>
                            </Dialog>
                        </div>
                        <div className="mt-4">
                            <h3 className="text-lg font-semibold mb-2">Your Associated YouTube Videos</h3>
                             {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 mt-4">
                                                <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 border rounded-lg">No channels have associated YouTube videos.</p>
                                )}
                        </div>
                    </TabsContent>
                  </Tabs>
                </CardContent>
              </Card>
            </TabsContent>
            <TabsContent value="analytics" className="mt-4">
               <div className="space-y-4">
                 <Card>
                    <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>Compare your channel's performance with others on the platform.</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">
                        {analyticsData.topChannels.length > 0 ? (
                        <div className="relative mx-auto flex h-full w-full max-w-[300px] items-center justify-center aspect-square">
                                <ChartContainer
                                    config={analyticsData.dynamicChartConfig}
                                    className="h-full w-full"
                                >
                                    <PieChart>
                                        <ChartTooltip
                                            content={<ChartTooltipContent nameKey="views" hideLabel />}
                                        />
                                        <Pie
                                            data={analyticsData.topChannels}
                                            dataKey="views"
                                            nameKey="name"
                                            innerRadius={60}
                                            outerRadius={100}
                                        >
                                            {analyticsData.topChannels.map((entry) => (
                                            <Cell key={`cell-${entry.name}`} fill={analyticsData.dynamicChartConfig[entry.name]?.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>
                        ) : (
                        <p className="text-muted-foreground text-center py-4">No views recorded on {selectedDate ? format(selectedDate, 'PPP') : 'this day'}.</p>
                        )}
                    </CardContent>
                    {analyticsData.topChannels.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.topChannels.map((entry) => (
                                    <div key={entry.name} className="flex items-center gap-2">
                                        <div className="w-3 h-3 rounded-full" style={{ backgroundColor: analyticsData.dynamicChartConfig[entry.name]?.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>
          </Tabs>
        </div>

      </div>

      {editingStream && (
        <Dialog open={isEditDialogOpen} onOpenChange={(isOpen) => { if (!isOpen) setEditingStream(null); setIsEditDialogOpen(isOpen); }}>
          <DialogContent className="sm:max-w-[600px]"><DialogHeader><DialogTitle>Edit Stream: {editingStream.name}</DialogTitle><DialogDescription>Update stream details.</DialogDescription></DialogHeader>
            <div className="grid gap-4 py-4">
              <div className="grid grid-cols-4 items-center gap-4"><Label htmlFor="edit-stream-name" className="text-right col-span-1">Name</Label><Input id="edit-stream-name" value={editedName} onChange={(e) => setEditedName(e.target.value)} className="col-span-3" /></div>
              <div className="grid grid-cols-4 items-center gap-4"><Label htmlFor="edit-stream-url1" className="text-right col-span-1">Primary URL</Label><Input id="edit-stream-url1" type="url" value={editedUrl1} onChange={(e) => setEditedUrl1(e.target.value)} className="col-span-3" /></div>
              <div className="grid grid-cols-4 items-center gap-4"><Label htmlFor="edit-stream-url2" className="text-right col-span-1">Backup URL 1</Label><Input id="edit-stream-url2" type="url" value={editedUrl2} onChange={(e) => setEditedUrl2(e.target.value)} className="col-span-3" /></div>
              <div className="grid grid-cols-4 items-center gap-4"><Label htmlFor="edit-stream-url3" className="text-right col-span-1">Backup URL 2</Label><Input id="edit-stream-url3" type="url" value={editedUrl3} onChange={(e) => setEditedUrl3(e.target.value)} className="col-span-3" /></div>
              <div className="grid grid-cols-4 items-center gap-4"><Label htmlFor="edit-stream-description" className="text-right col-span-1">Description</Label><Textarea id="edit-stream-description" value={editedDescription} onChange={(e) => setEditedDescription(e.target.value)} className="col-span-3" /></div>
            </div>
            <DialogFooter><DialogClose asChild><Button type="button" variant="outline">Cancel</Button></DialogClose><Button type="button" onClick={handleSaveStream}>Save Changes</Button></DialogFooter>
          </DialogContent>
        </Dialog>
      )}

      {selectedStreamForPreview && (
        <Dialog open={isPreviewDialogOpen} onOpenChange={(isOpen) => { setIsPreviewDialogOpen(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 rounded-lg overflow-hidden">
             {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 className="font-medium">Active Source: </span>
                <code className="text-xs bg-muted p-1 rounded-sm break-all">{activePreviewPlayingUrl}</code>
              </div>
            )}
            <DialogFooter className="mt-4"><Button type="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">Your stream has been submitted for approval.</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>
      )}

      {selectedVideoToPlay && (
        <Dialog open={isPlayVideoDialogOpen} onOpenChange={(isOpen) => { if (!isOpen) closePlayVideoDialog(); }}>
          <DialogContent className="sm:max-w-[600px] md:max-w-[800px] lg:max-w-[1000px] w-full"><DialogHeader><DialogTitle>Playing: {selectedVideoToPlay.title}</DialogTitle>{selectedVideoToPlay.description && <DialogDescription>{selectedVideoToPlay.description}</DialogDescription>}</DialogHeader>
            <div className="my-4 rounded-lg overflow-hidden"><HlsPlayer src={[selectedVideoToPlay.youtubeUrl]} autoPlay={true} /></div>
            <DialogFooter className="mt-4"><Button type="button" variant="secondary" onClick={closePlayVideoDialog}>Close Player</Button></DialogFooter>
          </DialogContent>
        </Dialog>
      )}
      
      {isPlaylistDialogOpen && (
        <Dialog open={isPlaylistDialogOpen} onOpenChange={(open) => { setIsPlaylistDialogOpen(open); if(!open) { setPlaylistStream(null); setCurrentPlaylist(null); }}}>
            <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 for your approved channels.</DialogDescription>
              </DialogHeader>
              <div className="grid flex-1 grid-cols-1 gap-6 overflow-hidden md:grid-cols-2">
                    <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-creator">Select Channel</Label>
                                <Select
                                value={playlistStream?.id || ''}
                                onValueChange={(streamId) => {
                                    const stream = approvedEditableStreams.find(s => s.id === streamId);
                                    handleOpenPlaylistDialog(stream || null);
                                }}
                                >
                                <SelectTrigger id="playlist-channel-select-creator"><SelectValue placeholder="Select a channel..." /></SelectTrigger>
                                <SelectContent>{approvedEditableStreams.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-creator">Create New Playlist</Label>
                                <div className="flex gap-2">
                                <Input id="new-playlist-title-creator" 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-creator">Video Title</Label><Input id="playlist-item-title-creator" value={playlistItemTitle} onChange={(e) => setPlaylistItemTitle(e.target.value)} placeholder="Video Title" />
                                <Label htmlFor="playlist-item-url-creator">YouTube URL</Label><Input id="playlist-item-url-creator" 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>
      )}

    </main>
  );
}



    

    

    


