import { useState, useEffect, useRef } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import {
useTrendingMovies,
useTrendingTv,
usePopularMovies,
usePopularTv,
useTopRatedMovies,
useTopRatedTv,
useUpcomingMovies,
} from '@/hooks/useTmdb';
import { useLibrary, useCreateEntry } from '@/hooks/useEntries';
import { useLibraryStore } from '@/stores/useLibraryStore';
import { Button } from '@/components/ui/button';
import {
Star,
Plus,
Play,
TrendingUp,
Award,
Calendar,
Search,
ChevronLeft,
ChevronRight,
} from 'lucide-react';
import type { TmdbEntry } from '@/types';
export function HomePage3() {
useLibrary();
const trendingMovies = useTrendingMovies();
const trendingTv = useTrendingTv();
const popularMovies = usePopularMovies();
const popularTv = usePopularTv();
const topRatedMovies = useTopRatedMovies();
const topRatedTv = useTopRatedTv();
const upcomingMovies = useUpcomingMovies();
const trendingMovieEntries = trendingMovies.data?.pages.flatMap((p) => p.results) ?? [];
const trendingTvEntries = trendingTv.data?.pages.flatMap((p) => p.results) ?? [];
const popularMovieEntries = popularMovies.data?.pages.flatMap((p) => p.results) ?? [];
const popularTvEntries = popularTv.data?.pages.flatMap((p) => p.results) ?? [];
const topRatedMovieEntries = topRatedMovies.data?.pages.flatMap((p) => p.results) ?? [];
const topRatedTvEntries = topRatedTv.data?.pages.flatMap((p) => p.results) ?? [];
const upcomingMovieEntries = upcomingMovies.data?.pages.flatMap((p) => p.results) ?? [];
// Trending grid auto-rotation: exit→swap→enter
const [trendingIdx, setTrendingIdx] = useState(0);
const [trendingPhase, setTrendingPhase] = useState<'idle' | 'exit' | 'enter'>('idle');
const trendingPool = trendingMovieEntries.slice(2);
const visibleTrending =
trendingPool.length >= 4
? [0, 1, 2, 3].map((offset) => trendingPool[(trendingIdx + offset) % trendingPool.length])
: trendingPool;
useEffect(() => {
if (trendingPool.length <= 4) return;
const timer = setInterval(() => {
// 1. Slide existing cards out to the left
setTrendingPhase('exit');
setTimeout(() => {
// 2. Swap in next set
setTrendingIdx((i) => i + 1);
setTrendingPhase('enter');
// 3. Return to idle after enter animation finishes
setTimeout(() => setTrendingPhase('idle'), 600);
}, 380);
}, 7000);
return () => clearInterval(timer);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [trendingPool.length]);
const isLoading =
trendingMovies.isLoading ||
popularMovies.isLoading ||
topRatedMovies.isLoading ||
upcomingMovies.isLoading;
if (isLoading) {
return ;
}
return (
{/* ─── Hero Slider — bleeds full width, breaks out of container padding ─── */}
{/* ─── Trending Now ─────────────────────────────────────────────── */}
}
title="Trending Now"
category="trending"
/>
{/* 2x2 backdrop grid — slides out left, new set slides in from right */}
{visibleTrending.map((item, i) => (
))}
{/* Numbered TV list */}
Trending TV
{trendingTvEntries.slice(0, 8).map((item, i) => (
))}
{/* ─── Popular Right Now — infinite moving belt ─────────────────── */}
}
title="Popular Right Now"
category="popular"
/>
{/* Overflow clip so the belt bleeds edge-to-edge within the section */}
((e.currentTarget as HTMLDivElement).style.animationPlayState = 'paused')}
onMouseLeave={(e) => ((e.currentTarget as HTMLDivElement).style.animationPlayState = 'running')}
>
{/* Original + duplicate for seamless loop */}
{[...Array(2)].flatMap((_, pass) =>
[...popularMovieEntries.slice(0, 8), ...popularTvEntries.slice(0, 6)].map((item) => (
))
)}
{/* ─── Top Rated ─────────────────────────────────────────────────── */}
}
title="Top Rated"
category="top-rated"
/>
Movies
{topRatedMovieEntries[0] && (
)}
{topRatedMovieEntries.slice(1, 5).map((item) => (
))}
TV Shows
{topRatedTvEntries.slice(0, 10).map((item, i) => (
))}
{/* ─── Coming Soon — horizontal scroll, small cards ─────────────── */}
}
title="Coming Soon"
category="upcoming"
/>
{upcomingMovieEntries.slice(0, 14).map((item) => (
))}
);
}
/* ─── Hero Slider ───────────────────────────────────────────────────── */
function HeroSlider({ entries }: { entries: TmdbEntry[] }) {
const navigate = useNavigate();
const [activeIndex, setActiveIndex] = useState(0);
const [searchInput, setSearchInput] = useState('');
const intervalRef = useRef | null>(null);
const createEntry = useCreateEntry();
const libraryEntries = useLibraryStore((s) => s.entries);
const slides = entries.slice(0, 8);
const go = (idx: number) => {
setActiveIndex((idx + slides.length) % slides.length);
};
const startAutoplay = () => {
if (intervalRef.current) clearInterval(intervalRef.current);
if (slides.length === 0) return;
intervalRef.current = setInterval(
() => setActiveIndex((i) => (i + 1) % slides.length),
6000,
);
};
useEffect(() => {
startAutoplay();
return () => {
if (intervalRef.current) clearInterval(intervalRef.current);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [slides.length]);
const handleSearch = () => {
const q = searchInput.trim();
if (q) navigate(`/search?q=${encodeURIComponent(q)}`);
};
if (slides.length === 0) return null;
return (
{/* ── Slide track — full-width flex rail that translates on index change ── */}
{slides.map((entry) => {
const title = entry.title || entry.name || 'Untitled';
const backdrop = entry.backdrop_path
? `https://image.tmdb.org/t/p/original${entry.backdrop_path}`
: null;
const isTv = entry.media_type === 'tv' || !!entry.name;
const matchedEntry = Array.from(libraryEntries.values()).find(
(e) => e.entryIds?.tmdb_id === entry.id,
);
return (
{backdrop ? (
) : (
)}
{/* Per-slide info — slides with the track */}
{isTv ? 'Series' : 'Movie'}
{entry.vote_average > 0 && (
{entry.vote_average.toFixed(1)}
)}
{title}
{entry.overview && (
{entry.overview}
)}
{matchedEntry ? (
Details
) : (
createEntry.mutate({ tmdb_id: entry.id, is_tvserie: isTv })}
disabled={createEntry.isPending}
>
Add
)}
);
})}
{/* ── Search bar — fixed top-center overlay ── */}
{/* ── Left arrow ── */}
{ go(activeIndex - 1); startAutoplay(); }}
aria-label="Previous"
>
{/* ── Right arrow ── */}
{ go(activeIndex + 1); startAutoplay(); }}
aria-label="Next"
>
{/* ── Dot indicators — fixed bottom-right overlay ── */}
{slides.map((_, i) => (
{ go(i); startAutoplay(); }}
aria-label={`Go to slide ${i + 1}`}
className={`rounded-full transition-all duration-300 ${
i === activeIndex
? 'h-1.5 w-6 bg-white'
: 'h-1.5 w-1.5 bg-white/30 hover:bg-white/60'
}`}
/>
))}
);
}
/* ─── Backdrop Card (16:9, used in grids) ───────────────────────────── */
function BackdropCard({
entry,
showRating,
animClass,
animDelay,
}: {
entry: TmdbEntry;
showRating?: boolean;
animClass?: string;
animDelay?: number;
}) {
const title = entry.title || entry.name || 'Untitled';
const backdrop = entry.backdrop_path
? `https://image.tmdb.org/t/p/w780${entry.backdrop_path}`
: null;
const isTv = entry.media_type === 'tv' || !!entry.name;
const linkTo = `/entry/tmdb/${isTv ? 'tv' : 'movie'}/${entry.id}`;
return (
{backdrop ? (
) : (
)}
{title}
{showRating && entry.vote_average > 0 && (
{entry.vote_average.toFixed(1)}
)}
);
}
/* ─── Backdrop Scroll Card (fixed width, for horizontal scroll row) ─── */
function BackdropScrollCard({
entry,
}: {
entry: TmdbEntry;
}) {
const title = entry.title || entry.name || 'Untitled';
const backdrop = entry.backdrop_path
? `https://image.tmdb.org/t/p/w780${entry.backdrop_path}`
: null;
const isTv = entry.media_type === 'tv' || !!entry.name;
const linkTo = `/entry/tmdb/${isTv ? 'tv' : 'movie'}/${entry.id}`;
return (
{backdrop ? (
) : (
)}
{title}
{entry.vote_average > 0 && (
{entry.vote_average.toFixed(1)}
)}
);
}
/* ─── Numbered List Item ────────────────────────────────────────────── */
function NumberedListItem({ entry, rank }: { entry: TmdbEntry; rank: number }) {
const title = entry.title || entry.name || 'Untitled';
const poster = entry.poster_path
? `https://image.tmdb.org/t/p/w92${entry.poster_path}`
: null;
const isTv = entry.media_type === 'tv' || !!entry.name;
const linkTo = `/entry/tmdb/${isTv ? 'tv' : 'movie'}/${entry.id}`;
return (
{rank}
{poster &&
}
{title}
{entry.vote_average > 0 && (
{entry.vote_average.toFixed(1)}
)}
);
}
/* ─── Mini Poster Card ──────────────────────────────────────────────── */
function MiniPosterCard({ entry, hideTitle }: { entry: TmdbEntry; hideTitle?: boolean }) {
const title = entry.title || entry.name || 'Untitled';
const poster = entry.poster_path
? `https://image.tmdb.org/t/p/w342${entry.poster_path}`
: null;
const isTv = entry.media_type === 'tv' || !!entry.name;
const linkTo = `/entry/tmdb/${isTv ? 'tv' : 'movie'}/${entry.id}`;
return (
{poster ? (
) : (
No Image
)}
{!hideTitle && {title}
}
);
}
/* ─── Upcoming Card (small, for horizontal scroll) ──────────────────── */
function formatRelativeTime(dateStr: string): string {
const now = new Date();
const release = new Date(dateStr);
const diffMs = release.getTime() - now.getTime();
if (diffMs <= 0) return 'Out now';
const totalMinutes = Math.floor(diffMs / 60000);
const totalHours = Math.floor(totalMinutes / 60);
const totalDays = Math.floor(totalHours / 24);
const months = Math.floor(totalDays / 30);
const remDays = totalDays % 30;
if (months > 0 && remDays > 0) return `in ${months}m ${remDays}d`;
if (months > 0) return `in ${months}m`;
if (totalDays > 0) return `in ${totalDays} day${totalDays !== 1 ? 's' : ''}`;
if (totalHours > 0) return `in ${totalHours} hour${totalHours !== 1 ? 's' : ''}`;
if (totalMinutes > 0) return `in ${totalMinutes} min`;
return 'Very soon';
}
function UpcomingCard({ entry }: { entry: TmdbEntry }) {
const title = entry.title || entry.name || 'Untitled';
const poster = entry.poster_path
? `https://image.tmdb.org/t/p/w185${entry.poster_path}`
: null;
const isTv = entry.media_type === 'tv' || !!entry.name;
const linkTo = `/entry/tmdb/${isTv ? 'tv' : 'movie'}/${entry.id}`;
const releaseDate = entry.release_date || entry.first_air_date;
const relativeTime = releaseDate ? formatRelativeTime(releaseDate) : null;
return (
{poster ? (
) : (
No Image
)}
{/* Date overlay — always visible at bottom of poster */}
{releaseDate && (
{new Date(releaseDate).toLocaleDateString('en-US', {
month: 'short',
day: 'numeric',
year: 'numeric',
})}
)}
{/* Hover overlay — shows relative countdown */}
{relativeTime && (
{relativeTime}
)}
);
}
/* ─── Section Header ────────────────────────────────────────────────── */
function SectionHeader({
icon,
title,
category,
}: {
icon: React.ReactNode;
title: string;
category: string;
}) {
return (
{icon}
{title}
Explore All →
);
}
/* ─── Loading Skeleton ──────────────────────────────────────────────── */
function LoadingSkeleton() {
return (
);
}