

"use client";

import { HlsPlayer } from "@/components/stream-player";
import { StreamThumbnailCard } from "@/components/stream-thumbnail-card";
import { useState, useEffect, useMemo, useRef } from "react";
import Link from "next/link";
import Image from "next/image";
import { useRouter, useSearchParams } from "next/navigation";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import type { Stream, User, UploadedVideo, Comment, AssociatedVideo, PlaylistItem, Playlist, ViewLog } from "@/types";
import { Eye, Plus, LogIn, LogOut, UserPlus, Heart, MessageSquare, Clock, DollarSign, Play as PlayIcon, Video as VideoIconLucide, ChevronLeft, ChevronRight, Info, X, AlertTriangle, Users, UserCog, ShieldCheck, Briefcase, Radio, ListVideo, PlaySquare } from "lucide-react";
import { RuningaLogo } from "@/components/icons/runinga-logo";
import { useToast } from "@/hooks/use-toast";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { useAuth } from "@/contexts/AuthContext";
import { db } from "@/lib/firebase";
import { ref, onValue, set, runTransaction, push, serverTimestamp } from "firebase/database";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Separator } from "@/components/ui/separator";
import { VideoThumbnailCard } from "./video-thumbnail-card";
import { useIsMobile } from "@/hooks/use-mobile";
import { AudioPlayer } from "./audio-player";
import { AudioThumbnailCard } from "./audio-thumbnail-card";
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "@/components/ui/accordion";
import { getYoutubeThumbnailUrl } from "@/lib/youtube-utils";
import { startOfDay, endOfDay } from "date-fns";
import { StickyPlayerWrapper } from "./sticky-player-wrapper";

interface HomePageClientProps {
  initialStreams: Stream[];
  initialUsers: User[];
  initialApprovedVideos: UploadedVideo[];
  initialSelectedStream: Stream | null;
  initialViewLogs: ViewLog[];
}

type ActiveMedia = 
  | { type: 'stream'; source: Stream }
  | { type: 'video'; source: AssociatedVideo; parentStream: Stream }
  | { type: 'playlistItem'; source: PlaylistItem; parentStream: Stream; playlist: Playlist };

export function HomePageClient({
  initialStreams,
  initialUsers,
  initialApprovedVideos,
  initialSelectedStream,
  initialViewLogs,
}: HomePageClientProps) {
  const router = useRouter();
  const searchParams = useSearchParams();

  const [selectedStream, setSelectedStream] = useState<Stream | null>(initialSelectedStream);
  const [approvedStreams, setApprovedStreams] = useState<Stream[]>(initialStreams);
  const [allStreams, setAllStreams] = useState<Stream[]>(initialStreams);
  const [allApprovedVideos, setAllApprovedVideos] = useState<UploadedVideo[]>(initialApprovedVideos);
  const [registeredUsers, setRegisteredUsers] = useState<User[]>(initialUsers);
  const [viewLogs, setViewLogs] = useState<ViewLog[]>(initialViewLogs);
  
  const [activeMedia, setActiveMedia] = useState<ActiveMedia | null>(
    initialSelectedStream ? { type: 'stream', source: initialSelectedStream } : null
  );

  const [playingAudioStreamId, setPlayingAudioStreamId] = useState<string | null>(null);

  const [newCommentText, setNewCommentText] = useState('');
  const [currentTime, setCurrentTime] = useState('');
  const [fabOpen, setFabOpen] = useState(false);
  const [isLoadingStreams, setIsLoadingStreams] = useState(true);
  const [streamError, setStreamError] = useState<string | null>(null);
  const [isCommentsOpen, setIsCommentsOpen] = useState(false);

  const { toast } = useToast();
  const { isAuthenticated, logout, userRole, userId } = useAuth();
  
  const totalViews = useMemo(() => {
    return allStreams.reduce((acc, stream) => acc + (stream.views || 0), 0);
  }, [allStreams]);

  const totalDailyViews = useMemo(() => {
    if (!viewLogs) return 0;
    const todayStart = startOfDay(new Date()).getTime();
    const todayEnd = endOfDay(new Date()).getTime();
    return viewLogs.filter(log => log.timestamp >= todayStart && log.timestamp <= todayEnd).length;
  }, [viewLogs]);
  
  const videoStreams = useMemo(() => {
    return approvedStreams
      .filter(stream => stream.streamType !== 'audio')
      .sort((a, b) => {
        const pinA = a.pinIndex ?? Infinity;
        const pinB = b.pinIndex ?? Infinity;
        if (pinA !== pinB) return pinA - pinB;
        return (b.views || 0) - (a.views || 0);
      });
  }, [approvedStreams]);

  const audioStreams = useMemo(() => {
    return approvedStreams
      .filter(stream => stream.streamType === 'audio')
      .sort((a, b) => {
        const pinA = a.audioPinIndex ?? Infinity;
        const pinB = b.audioPinIndex ?? Infinity;
        if (pinA !== pinB) return pinA - pinB;
        return (b.views || 0) - (a.views || 0);
      });
  }, [approvedStreams]);

  const videoGridClassName = useMemo(() => {
    const count = videoStreams.length;
    if (count <= 2) return "grid grid-cols-1 sm:grid-cols-2 lg:max-w-4xl mx-auto gap-2";
    if (count <= 6) return "grid grid-cols-2 md:grid-cols-3 gap-2";
    if (count <= 12) return "grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-2";
    return "grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 xl:grid-cols-8 gap-1";
  }, [videoStreams.length]);
  
  const audioGridClassName = useMemo(() => {
    const count = audioStreams.length;
    if (count <= 3) return "grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4";
    return "grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4";
  }, [audioStreams.length]);

  const handleVideoEnded = () => {
    if (activeMedia?.type === 'playlistItem') {
      const { playlist, source, parentStream } = activeMedia;
      const items = Object.values(playlist.items || {}).sort((a,b) => a.addedAt - b.addedAt);
      const currentIndex = items.findIndex(item => item.id === source.id);
      
      const nextIndex = currentIndex + 1;
      if (nextIndex < items.length) {
        // Play the next video in the playlist
        const nextVideo = items[nextIndex];
        setActiveMedia({ type: 'playlistItem', source: nextVideo, parentStream, playlist });
      } else {
        // Playlist finished, return to live stream
        backToLiveStream();
      }
    }
  };

  useEffect(() => {
    const streamsRef = ref(db, 'streams');
    setStreamError(null);

    const unsubscribeStreams = onValue(streamsRef, (snapshot) => {
      const data = snapshot.val();
      if (data) {
        const allStreamsList: Stream[] = Object.keys(data).map(key => ({ id: key, ...data[key] }));
        
        const approvedStreamsList = allStreamsList.filter(stream => stream.status === 'approved');

        setAllStreams(allStreamsList);
        setApprovedStreams(approvedStreamsList);

        // If a stream is already selected, update its data to ensure playlists etc. are current
        setSelectedStream(prevSelectedStream => {
          if (!prevSelectedStream) return null;
          const updatedStreamData = allStreamsList.find(s => s.id === prevSelectedStream.id);
          return updatedStreamData || null;
        });
        
      } else {
        setAllStreams([]);
        setApprovedStreams([]);
      }
      setIsLoadingStreams(false);
    }, (error) => {
      console.error("Error fetching streams from Realtime Database:", error);
      setStreamError("Failed to load streams. Please ensure your Firebase setup and security rules are correct.");
      setIsLoadingStreams(false);
    });

    const usersRef = ref(db, 'users');
    const unsubscribeUsers = onValue(usersRef, (snapshot) => {
        const usersData = snapshot.val() || {};
        const usersList: User[] = Object.keys(usersData).map(key => ({ id: key, ...usersData[key] }));
        setRegisteredUsers(usersList);
    });

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

    const updateTime = () => setCurrentTime(new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' }));
    updateTime();
    const timerId = setInterval(updateTime, 1000);

    return () => {
      clearInterval(timerId);
      unsubscribeStreams();
      unsubscribeUsers();
      unsubscribeViewLogs();
    };
  }, []);

  useEffect(() => {
    const streamId = searchParams.get('stream');
    
    if (streamId) {
        const streamFromUrl = approvedStreams.find(s => s.id === streamId);
        if (streamFromUrl) {
            if (streamFromUrl.streamType === 'audio') {
              // If it's an audio stream from URL, we don't open the main player
              // We just ensure the grid is visible.
              setSelectedStream(null);
              setActiveMedia(null);
            } else if (!selectedStream || selectedStream.id !== streamFromUrl.id) {
                // For video streams, open the main player
                setSelectedStream(streamFromUrl);
                setActiveMedia({ type: 'stream', source: streamFromUrl });
            }
        } else if (!isLoadingStreams) {
            setSelectedStream(null);
            setActiveMedia(null);
            router.push('/', { scroll: false });
        }
    } else {
        setSelectedStream(null);
        setActiveMedia(null);
        setPlayingAudioStreamId(null);
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [searchParams, approvedStreams, isLoadingStreams]);


  const handleStreamSelection = (stream: Stream) => {
    // This function is now only for video streams
    if (stream.streamType === 'audio') return;

    const newViews = (stream.views || 0) + 1;
    const updatedStream = { ...stream, views: newViews };
    
    setSelectedStream(updatedStream);
    // Let the real-time listener handle updating the approved/all streams list
    
    setActiveMedia({ type: 'stream', source: updatedStream });
    setPlayingAudioStreamId(null); // Stop any audio playing
    
    router.push(`/?stream=${stream.id}`, { scroll: false });
    
    if (stream?.id) {
      const viewsRef = ref(db, `streams/${stream.id}/views`);
      runTransaction(viewsRef, (currentViews) => (currentViews || 0) + 1)
        .catch(error => console.error("Error updating views with transaction:", error));
        
      const viewLogRef = push(ref(db, 'view_logs'));
      set(viewLogRef, {
          streamId: stream.id,
          timestamp: serverTimestamp()
      }).catch(error => console.error("Error logging view:", error));
    }
  };

  const handleAudioPlayToggle = (stream: Stream) => {
    if (playingAudioStreamId === stream.id) {
      setPlayingAudioStreamId(null); // Stop playing
    } else {
      setPlayingAudioStreamId(stream.id); // Start playing this stream
      // Increment views when starting to play
      const viewsRef = ref(db, `streams/${stream.id}/views`);
      runTransaction(viewsRef, (currentViews) => (currentViews || 0) + 1);
      const viewLogRef = push(ref(db, 'view_logs'));
      set(viewLogRef, {
          streamId: stream.id,
          timestamp: serverTimestamp()
      });
    }
  };
  
  const handleLikeStream = async () => {
    if (!selectedStream || !userId || !isAuthenticated) {
      toast({ title: "Login Required", description: "You must be logged in to like a stream.", variant: "destructive"});
      return;
    }
    const streamLikesRef = ref(db, `streams/${selectedStream.id}/likes/${userId}`);
    const currentLikes = selectedStream.likes || {};
    try {
        await set(streamLikesRef, currentLikes[userId ?? ''] ? null : true);
    } catch (error) {
        toast({ title: "Error", description: "Could not update like status.", variant: "destructive" });
    }
  };

  const handleAddComment = async () => {
    if (!selectedStream || !userId || !isAuthenticated || !newCommentText.trim()) {
        toast({ title: !isAuthenticated ? "Login Required" : "Empty Comment", description: !isAuthenticated ? "You must be logged in to comment." : "Comment cannot be empty.", variant: "destructive"});
        return;
    }
    const username = registeredUsers.find(u => u.id === userId)?.username || "Anonymous";
    const newCommentRef = push(ref(db, `streams/${selectedStream.id}/comments`));
    const newComment: Omit<Comment, 'timestamp'> & { timestamp: object } = {
      id: newCommentRef.key!, userId, username, text: newCommentText.trim(), timestamp: serverTimestamp(),
    };
    try {
        await set(newCommentRef, newComment);
        setNewCommentText('');
    } catch (error) {
        console.error("Error adding new stream:", error);
        toast({ title: "Error", description: "Could not post comment.", variant: "destructive" });
    }
  };

  const playAssociatedVideo = (video: AssociatedVideo) => {
    if (selectedStream) {
      // Optimistically update the UI
      const newViews = (selectedStream.views || 0) + 1;
      const updatedStream = { ...selectedStream, views: newViews };
      
      setSelectedStream(updatedStream);
      setActiveMedia({ type: 'video', source: video, parentStream: updatedStream });
      window.scrollTo({ top: 0, behavior: 'smooth' });

      // Then update the database
      const viewsRef = ref(db, `streams/${selectedStream.id}/views`);
      runTransaction(viewsRef, (currentViews) => (currentViews || 0) + 1)
        .catch(error => console.error("Error updating views for video play:", error));
        
      const viewLogRef = push(ref(db, 'view_logs'));
      set(viewLogRef, {
          streamId: selectedStream.id,
          timestamp: serverTimestamp()
      }).catch(error => console.error("Error logging view for video play:", error));
    }
  };

  const playPlaylistItem = (item: PlaylistItem, playlist: Playlist) => {
    if (selectedStream) {
      const newViews = (selectedStream.views || 0) + 1;
      const updatedStream = { ...selectedStream, views: newViews };
      
      setSelectedStream(updatedStream);
      setActiveMedia({ type: 'playlistItem', source: item, parentStream: updatedStream, playlist: playlist });
      window.scrollTo({ top: 0, behavior: 'smooth' });
    }
  };

  const backToLiveStream = () => {
    if (activeMedia?.type === 'video' || activeMedia?.type === 'playlistItem') {
        const parentStream = activeMedia.parentStream;
        setActiveMedia({ type: 'stream', source: parentStream });
    }
  };

  const getCreatorUsername = (creatorId?: string): string => creatorId ? registeredUsers.find(u => u.id === creatorId)?.username || "Unknown" : "Unknown";

  const { sidebarVideos, moreGridVideos } = useMemo(() => {
    if (!selectedStream?.associatedVideos) {
      return { sidebarVideos: [], moreGridVideos: [] };
    }
    const allVideos = Object.values(selectedStream.associatedVideos).sort((a, b) => b.addedAt - a.addedAt);
    return {
      sidebarVideos: allVideos.slice(0, 5),
      moreGridVideos: allVideos.slice(5),
    };
  }, [selectedStream]);

  const allAssociatedVideosForGrid = useMemo(() => {
    if (!selectedStream?.associatedVideos) return [];
    return Object.values(selectedStream.associatedVideos).sort((a, b) => b.addedAt - a.addedAt);
  }, [selectedStream]);
  
  const currentPlaylists = useMemo(() => {
    if (!selectedStream?.playlists) return [];
    return Object.values(selectedStream.playlists).sort((a, b) => a.createdAt - b.createdAt);
  }, [selectedStream]);


  const currentTitle = useMemo(() => {
    if (activeMedia?.type === 'stream') return activeMedia.source.name;
    if (activeMedia?.type === 'video') return activeMedia.source.title;
    if (activeMedia?.type === 'playlistItem') return activeMedia.source.title;
    return "RUNINGA MEANS TELEVISION";
  }, [activeMedia]);

  const renderPlayer = () => {
    if (!activeMedia) return null;
    
    let src: string[] = [];
    switch (activeMedia.type) {
        case 'stream':
            src = activeMedia.source.sourceUrls;
            break;
        case 'video':
        case 'playlistItem':
            src = [activeMedia.source.youtubeUrl];
            break;
    }

    return (
        <StickyPlayerWrapper onVideoEnded={handleVideoEnded}>
            <HlsPlayer key={activeMedia.source.id} src={src} autoPlay={true} onVideoEnded={handleVideoEnded} />
        </StickyPlayerWrapper>
    );
  };

  const scrollToAudio = () => {
    const audioSection = document.getElementById('audio-streams-section');
    if (audioSection) {
      audioSection.scrollIntoView({ behavior: 'smooth' });
    }
  };

  return (
    <main className="min-h-screen flex flex-col items-center p-1 sm:p-2 md:p-4">
        <Card className="w-full max-w-screen-2xl rounded-xl min-h-[85vh] flex flex-col bg-transparent border-none shadow-none">
             <CardHeader className="bg-card-foreground/5 p-2 sm:p-4">
                <div className="flex items-center justify-center gap-3">
                    <Button variant="ghost" onClick={() => { setSelectedStream(null); setActiveMedia(null); setPlayingAudioStreamId(null); router.push('/', { scroll: false }); }} aria-label="Go to homepage" className="p-0 h-auto focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background rounded">
                        <RuningaLogo className="h-[3.6rem] w-auto text-primary-foreground" />
                    </Button>
                    <CardTitle className="text-xl sm:text-3xl font-bold text-primary-foreground text-center">
                        {currentTitle}
                    </CardTitle>
                 </div>
                <div className="mt-2 flex flex-col sm:flex-row justify-center items-center gap-2 sm:gap-4 text-xs text-muted-foreground">
                    {currentTime && <div className="flex items-center gap-1"><Clock className="w-3 h-3" /><span>{currentTime}</span></div>}
                    <div className="flex items-center gap-1"><Eye className="w-3 h-3" /><span>Total Daily Views: {totalDailyViews.toLocaleString()}</span></div>
                    <div className="flex items-center gap-1"><Eye className="w-3 h-3" /><span>Total Views: {totalViews.toLocaleString()}</span></div>
                </div>
            </CardHeader>

            <CardContent className="p-2 flex-grow">
                {streamError ? (
                  <div className="w-full aspect-video bg-muted rounded-lg flex flex-col items-center justify-center text-destructive-foreground p-4"><AlertTriangle className="w-12 h-12 mb-2" /><p className="text-lg font-semibold">Error Loading Streams</p><p className="text-sm text-center">{streamError}</p></div>
                ) : activeMedia ? (
                  <div className="w-full">
                     <div className="grid grid-cols-1 lg:grid-cols-12 gap-4 h-full">
                       {/* Main Player and Below-Player Content */}
                      <div className="lg:col-span-8 xl:col-span-9 w-full space-y-4">
                         {(activeMedia.type === 'video' || activeMedia.type === 'playlistItem') && (
                          <div className="flex justify-start">
                            <Button onClick={backToLiveStream} variant="outline">
                              <Radio className="mr-2 h-4 w-4" /> Back to Live Stream
                            </Button>
                          </div>
                        )}
                        
                        {renderPlayer()}
                        
                        <div>
                            <div className="flex items-center justify-between w-full">
                                <div className="flex items-center gap-2 text-muted-foreground">
                                    {selectedStream && (
                                      <>
                                        <div className="flex items-center gap-1 text-sm" title="Total views"><Eye className="w-4 h-4" /><span>{(selectedStream.views || 0).toLocaleString()}</span></div>
                                        <Button variant="ghost" size="sm" onClick={handleLikeStream} disabled={!isAuthenticated} className={`text-muted-foreground hover:text-accent ${!isAuthenticated && 'cursor-not-allowed opacity-50'}`}><Heart className={`w-5 h-5 mr-1 ${selectedStream.likes?.[userId ?? ''] ? 'fill-red-500 text-red-500' : 'text-muted-foreground'}`} />{Object.keys(selectedStream.likes || {}).length}</Button>
                                        <Button variant="ghost" size="sm" onClick={() => setIsCommentsOpen(!isCommentsOpen)} className="text-muted-foreground hover:text-accent">
                                          <MessageSquare className="w-5 h-5 mr-1" />
                                          {selectedStream.comments ? Object.keys(selectedStream.comments).length : 0}
                                        </Button>
                                      </>
                                    )}
                                </div>
                                {selectedStream && <p className="text-sm text-muted-foreground">Creator: {getCreatorUsername(selectedStream.creatorId)}</p>}
                            </div>
                            {activeMedia.type === 'stream' && activeMedia.source.description && <p className="text-muted-foreground text-sm mt-2">{activeMedia.source.description}</p>}
                            {activeMedia.type === 'video' && activeMedia.source.description && <p className="text-muted-foreground text-sm mt-2">{activeMedia.source.description}</p>}
                            {activeMedia.type === 'playlistItem' && <p className="text-muted-foreground text-sm mt-2">Playing from playlist: <span className="font-semibold text-foreground">{activeMedia.playlist.title}</span></p>}
                        </div>

                        {isCommentsOpen && selectedStream && (
                          <div className="space-y-4 pt-4">
                              <Separator />
                              <h3 className="text-lg font-semibold text-foreground">Comments</h3>
                              {isAuthenticated ? (<div className="flex flex-col gap-2"><Textarea value={newCommentText} onChange={(e) => setNewCommentText(e.target.value)} placeholder="Add a comment..." className="bg-input border-border placeholder:text-muted-foreground" rows={2} /><Button onClick={handleAddComment} size="sm" className="self-end bg-accent text-accent-foreground hover:bg-accent/90">Post</Button></div>) 
                              : (<p className="text-sm text-muted-foreground"><Link href="/login" className="underline hover:text-accent">Login</Link> to post a comment.</p>)}
                              
                              <ScrollArea className="h-[25vh] max-h-48">
                                <div className="space-y-3 pr-4">
                                  {(selectedStream?.comments ? Object.values(selectedStream.comments).sort((a, b) => b.timestamp - a.timestamp) : []).map(comment => (<div key={comment.id} className="p-3 rounded-md bg-muted/50 border border-border/50"><div className="flex items-center justify-between text-xs mb-1"><span className="font-semibold text-foreground">{comment.username}</span><span className="text-muted-foreground">{new Date(comment.timestamp).toLocaleString()}</span></div><p className="text-sm text-foreground">{comment.text}</p></div>))}
                                </div>
                              </ScrollArea>
                          </div>
                        )}

                        {/* Playlist Grid Section */}
                        {currentPlaylists.length > 0 && (
                          <div className="mt-6">
                            <Separator className="my-4" />
                            <h3 className="text-lg font-semibold text-foreground mb-4">Playlists</h3>
                            <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
                              {currentPlaylists.map((playlist) => {
                                const firstItem = Object.values(playlist.items || {}).sort((a, b) => a.addedAt - b.addedAt)[0];
                                if (!firstItem) return null; // Don't render a card for an empty playlist

                                const playlistAsVideo: AssociatedVideo = {
                                  id: playlist.id,
                                  title: playlist.title,
                                  description: `${Object.keys(playlist.items || {}).length} videos`,
                                  youtubeUrl: firstItem.youtubeUrl,
                                  addedAt: playlist.createdAt,
                                };

                                return (
                                  <VideoThumbnailCard
                                    key={playlist.id}
                                    video={playlistAsVideo}
                                    onVideoSelect={() => playPlaylistItem(firstItem, playlist)}
                                    variant="grid"
                                    isPlaylist
                                  />
                                );
                              })}
                            </div>
                          </div>
                        )}


                        {/* "More Videos" Grid - shows only on large screens if there are videos beyond the first 5 */}
                        <div className="hidden lg:block">
                          {moreGridVideos.length > 0 && (
                              <div className="mt-6">
                                  <Separator className="my-4"/>
                                  <h3 className="text-lg font-semibold text-foreground mb-4">Related Videos</h3>
                                  <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
                                    {moreGridVideos.map(video => (
                                      <VideoThumbnailCard
                                        key={video.id}
                                        video={video}
                                        onVideoSelect={() => playAssociatedVideo(video)}
                                        variant="grid"
                                      />
                                    ))}
                                  </div>
                              </div>
                          )}
                        </div>
                      </div>
                      
                      {/* Desktop Sidebar - shows only on large screens */}
                       <div className="hidden lg:flex lg:col-span-4 xl:col-span-3 w-full h-full flex-col">
                          <h3 className="text-lg font-semibold text-foreground shrink-0 mb-2">Related Videos</h3>
                          <div className="flex flex-col gap-2 justify-start">
                              {sidebarVideos.map(video => (
                                  <VideoThumbnailCard 
                                    key={video.id} 
                                    video={video} 
                                    onVideoSelect={() => playAssociatedVideo(video)}
                                    variant="list"
                                  />
                              ))}
                          </div>
                      </div>

                       {/* Unified Grid for Small/Medium Screens - hidden on large screens */}
                        <div className="mt-6 lg:hidden">
                          {allAssociatedVideosForGrid.length > 0 && (
                            <>
                              <Separator className="my-4"/>
                              <h3 className="text-lg font-semibold text-foreground mb-4">Related Videos</h3>
                              <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
                                {allAssociatedVideosForGrid.map(video => (
                                  <VideoThumbnailCard
                                    key={video.id}
                                    video={video}
                                    onVideoSelect={() => playAssociatedVideo(video)}
                                    variant="grid"
                                  />
                                ))}
                              </div>
                            </>
                          )}
                        </div>
                    </div>
                  </div>
                ) : (
                  <div className="w-full mx-auto space-y-8">
                    <div>
                        <div className="flex items-center gap-4 mb-4">
                            <Button variant="outline" size="sm" className="pointer-events-none">
                                <VideoIconLucide className="mr-2 h-4 w-4" />
                                Live TV
                            </Button>
                            {audioStreams.length > 0 && (
                                <Button variant="outline" size="sm" onClick={scrollToAudio}>
                                <Radio className="mr-2 h-4 w-4" />
                                Online Radio
                                </Button>
                            )}
                        </div>
                        <div className={videoGridClassName}>
                            {videoStreams.map((stream) => 
                              <StreamThumbnailCard key={stream.id} stream={stream} onStreamSelect={handleStreamSelection} />
                            )}
                        </div>
                    </div>
                    {audioStreams.length > 0 && (
                      <div id="audio-streams-section">
                        <h2 className="text-2xl font-bold text-primary-foreground mb-4">Online Radio</h2>
                        <div className={audioGridClassName}>
                          {audioStreams.map((stream) => (
                              <AudioThumbnailCard 
                                key={stream.id} 
                                stream={stream} 
                                onPlayToggle={handleAudioPlayToggle}
                                isPlaying={playingAudioStreamId === stream.id}
                              />
                          ))}
                        </div>
                      </div>
                    )}
                  </div>
                )}
            </CardContent>
        </Card>
        
        {true && (
            <div className="fixed bottom-6 right-6 flex flex-col items-end gap-2 z-50">
                {fabOpen && (
                    <>
                        {isAuthenticated ? (
                            <>
                                {userRole === 'creator' && ( <Link href="/user-dashboard" className="bg-primary text-primary-foreground p-3 rounded-lg shadow-xl hover:bg-primary/90 transition-all flex items-center gap-2" aria-label="Creator Dashboard"><UserCog className="w-5 h-5" />Creator Dashboard</Link>)}
                                {userRole === 'admin' && (<Link href="/admin" className="bg-primary text-primary-foreground p-3 rounded-lg shadow-xl hover:bg-primary/90 transition-all flex items-center gap-2" aria-label="Admin Dashboard"><ShieldCheck className="w-5 h-5" />Admin Dashboard</Link>)}
                                 <Button onClick={logout} variant="destructive" className="p-3 rounded-lg shadow-xl transition-all flex items-center gap-2" aria-label="Logout"><LogOut className="w-5 h-5" />Logout</Button>
                            </>
                        ) : (
                             <>
                                <Link href="/login" className="bg-accent text-accent-foreground p-3 rounded-lg shadow-xl hover:bg-accent/90 transition-all flex items-center gap-2" aria-label="Login"><LogIn className="w-5 h-5" />Login</Link>
                                <Link href="/login" className="bg-green-600 text-white p-3 rounded-lg shadow-xl hover:bg-green-700 transition-all flex items-center gap-2" aria-label="Create Account"><UserPlus className="w-5 h-5" />Create Account</Link>
                            </>
                        )}
                         <Link href="/about" className="bg-secondary text-secondary-foreground p-3 rounded-lg shadow-xl hover:bg-secondary/90 transition-all flex items-center gap-2" aria-label="About Us"><Info className="w-5 h-5" />About Us</Link>
                    </>
                )}
                 <Button onClick={() => setFabOpen(!fabOpen)} className="bg-primary text-primary-foreground p-4 rounded-full shadow-xl hover:bg-primary/90 transition-all duration-300 ease-out" aria-label={fabOpen ? "Close actions" : "Open actions"} aria-expanded={fabOpen}>
                    {fabOpen ? <X className="w-6 h-6" /> : <Plus className="w-6 h-6" />}
                </Button>
            </div>
        )}
    </main>
  );
}

    