All files / src/components/channels ChannelList.tsx

0% Statements 0/915
0% Branches 0/1
0% Functions 0/1
0% Lines 0/915

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
import { useState, useMemo, useCallback, useRef, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useVirtualizer } from "@tanstack/react-virtual";
import { Loader2, Tv2, MonitorPlay, Heart, Clapperboard, History } from "lucide-react";
import { Button } from "@/components/ui/button";
import { SearchBar } from "./SearchBar";
import { CategoryFilter } from "./CategoryFilter";
import { ChannelCard, ROW_CARD_LEFT_WIDTH } from "./ChannelCard";
import { useGroupHierarchy } from "@/hooks/useGroupHierarchy";
import { RecentlyPlayedRow } from "./RecentlyPlayedRow";
import { PinnedGroupsRow } from "./PinnedGroupsRow";
import { CategoryBrowser } from "./CategoryBrowser";
import { GroupList } from "./GroupList";
import { Breadcrumb } from "./Breadcrumb";
import { CategoryManager } from "./CategoryManager";
import { SeriesDetailModal } from "./SeriesDetailModal";
import { MovieInfoDrawer } from "./MovieInfoDrawer";
import { HistoryTab } from "./HistoryTab";
import { getGridMarks, toPct, formatHHMM } from "./EpgTimelineBar";
import { useChannels } from "@/hooks/useChannels";
import { getXtreamSeriesEpisodes, getEpgForLiveChannels, searchEpgProgrammes } from "@/lib/tauri";
import type {
	Channel,
	Category,
	EpgProgram,
	EpgSearchResult,
	WatchHistoryEntry,
} from "@/lib/types";
 
type Tab = "live" | "movie" | "series" | "favorites" | "history";
 
const TABS: { id: Tab; label: string; icon: React.ElementType }[] = [
	{ id: "live", label: "Live", icon: Tv2 },
	{ id: "movie", label: "Movies", icon: Clapperboard },
	{ id: "series", label: "Series", icon: MonitorPlay },
	{ id: "favorites", label: "Favorites", icon: Heart },
	{ id: "history", label: "History", icon: History },
];
 
/** Pixels per hour for the dynamic window (higher = wider spacing between gridlines). */
const PX_PER_HOUR = 150;
/**
 * Width (px) of the right-side buttons in a RowCard (LIVE badge + ♡ + px-2 padding).
 * Must match the right spacer added to the sticky header so gridlines align with labels.
 */
const RIGHT_BUTTONS_PX = 80;
 
const showTitle = (name: string): string => name.replace(/\s+S\d{1,3}E\d{1,3}.*/i, "").trim();
 
const formatEpgTime = (startTime: number, now: number): string => {
	const diff = startTime - now;
	if (diff <= 0) return "now";
	if (diff < 3600) return `in ${Math.ceil(diff / 60)}m`;
	if (diff < 7200) return `in ${Math.floor(diff / 3600)}h`;
	const d = new Date(startTime * 1000);
	const today = new Date(now * 1000);
	const tomorrow = new Date(today);
	tomorrow.setDate(today.getDate() + 1);
	const timeStr = d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
	if (d.toDateString() === today.toDateString()) return `today ${timeStr}`;
	if (d.toDateString() === tomorrow.toDateString()) return `tomorrow ${timeStr}`;
	return (
		d.toLocaleDateString([], { weekday: "short", month: "short", day: "numeric" }) +
		` ${timeStr}`
	);
};
 
const EpgResultLogo = ({ url }: { url?: string }) => {
	const [imgError, setImgError] = useState(false);
	const showFallback = !url || imgError;
 
	return (
		<div className="h-8 w-8 rounded bg-secondary flex items-center justify-center overflow-hidden shrink-0">
			{url && !imgError ? (
				<img
					src={url}
					alt=""
					className="h-full w-full object-contain"
					loading="lazy"
					onError={() => setImgError(true)}
				/>
			) : null}
			{showFallback ? <Tv2 className="h-3.5 w-3.5 text-muted-foreground" /> : null}
		</div>
	);
};
 
export const ChannelList = () => {
	const { channels, loading, toggleFavorite, providers } = useChannels();
	const navigate = useNavigate();
 
	const [activeTab, setActiveTab] = useState<Tab>("live");
	const [search, setSearch] = useState("");
	// Debounced search — updated 250ms after user stops typing to avoid per-keystroke re-renders
	const [debouncedSearch, setDebouncedSearch] = useState("");
	const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
 
	// Hierarchy navigation state
	const [navState, setNavState] = useState<
		| { level: "home" }
		| { level: "category"; name: string }
		| { level: "group"; name: string; parentCategory?: string }
	>({ level: "home" });
	const [showCategoryManager, setShowCategoryManager] = useState(false);
 
	const activeProviderId = providers.length > 0 ? providers[0].id : null;
	const contentType =
		activeTab === "movie" ? "movie" : activeTab === "series" ? "series" : "live";
	const hierarchy = useGroupHierarchy(activeProviderId, contentType);
	const [showFavoritesOnly, setShowFavoritesOnly] = useState(false);
	const [seriesModalData, setSeriesModalData] = useState<{
		showTitle: string;
		episodes: Channel[];
	} | null>(null);
	const [seriesLoading, setSeriesLoading] = useState(false);
	const [selectedMovie, setSelectedMovie] = useState<Channel | null>(null);
 
	// EPG data: tvgId → EpgProgram[] (all programs in the fetch window)
	const [epgMap, setEpgMap] = useState<Map<string, EpgProgram[]>>(new Map());
	// EPG search: one result per channel (earliest matching program)
	const [epgSearchResults, setEpgSearchResults] = useState<EpgSearchResult[]>([]);
 
	// Container width → dynamic EPG window + grid column calculation
	const [containerWidth, setContainerWidth] = useState(0);
	/** Root div ref — always in DOM; drives ResizeObserver for dynamic EPG window. */
	const rootRef = useRef<HTMLDivElement>(null);
	/** Virtualizer scroll ref — kept for TanStack Virtual scroll element. */
	const parentRef = useRef<HTMLDivElement>(null);
 
	const measureRoot = useCallback(() => {
		const el = rootRef.current;
		if (el) setContainerWidth(el.clientWidth);
	}, []);
 
	// Measure container width: ResizeObserver on root + window resize fallback
	useEffect(() => {
		measureRoot();
		// Re-measure after layout settles (fonts, flex, etc.)
		const rafId = requestAnimationFrame(measureRoot);
 
		const el = rootRef.current;
		const obs = el
			? new ResizeObserver(([entry]) => setContainerWidth(entry.contentRect.width))
			: null;
		if (el && obs) obs.observe(el);
		window.addEventListener("resize", measureRoot);
 
		return () => {
			cancelAnimationFrame(rafId);
			obs?.disconnect();
			window.removeEventListener("resize", measureRoot);
		};
	}, [measureRoot]);
 
	// Re-measure when switching tabs (the grid area may have a different width)
	useEffect(() => {
		measureRoot();
	}, [activeTab, measureRoot]);
 
	// Compute dynamic EPG display window: now line at 1/3 mark, 100–200 px per hour
	const { windowStart, windowEnd } = useMemo(() => {
		const now = Math.floor(Date.now() / 1000);
		// containerWidth is content-box width (inside px-3 padding).
		// Rows inside have no extra padding, so timeline = containerWidth minus the two fixed columns.
		const effectiveWidth = containerWidth > 0 ? containerWidth : 400;
		// rootRef measures the full component width; the scroll container inside has px-3 (12px)
		// padding on each side, so subtract 24px to get the actual content width.
		const timelinePx = Math.max(
			200,
			effectiveWidth - 24 - ROW_CARD_LEFT_WIDTH - RIGHT_BUTTONS_PX
		);
		const totalHours = Math.max(3, timelinePx / PX_PER_HOUR);
		const pastSec = Math.round((totalHours / 3) * 3600);
		const futureSec = Math.round(((totalHours * 2) / 3) * 3600);
		return { windowStart: now - pastSec, windowEnd: now + futureSec };
	}, [containerWidth]);
 
	const windowTotal = windowEnd - windowStart;
 
	// Debounce: update debouncedSearch 250ms after search changes
	useEffect(() => {
		const t = setTimeout(() => setDebouncedSearch(search), 250);
		return () => clearTimeout(t);
	}, [search]);
 
	const byType = useMemo(() => {
		const map: Record<"live" | "movie" | "series", Channel[]> = {
			live: [],
			movie: [],
			series: [],
		};
		for (const ch of channels) {
			const t = ch.contentType as "live" | "movie" | "series";
			if (t in map) map[t].push(ch);
			else map.live.push(ch);
		}
		return map;
	}, [channels]);
 
	const seriesShows = useMemo(() => {
		const seen = new Map<string, Channel>();
		for (const ch of byType.series) {
			const title = ch.seriesTitle ?? showTitle(ch.name);
			if (!seen.has(title)) seen.set(title, { ...ch, name: title, sources: [] });
		}
		return Array.from(seen.values());
	}, [byType.series]);
 
	const movieTitles = useMemo(() => {
		const seen = new Map<string, Channel>();
		for (const ch of byType.movie) {
			if (!seen.has(ch.name)) {
				seen.set(ch.name, { ...ch, sources: [...ch.sources] });
			} else {
				const existing = seen.get(ch.name)!;
				existing.sources.push(ch.url);
				existing.sources.push(...ch.sources);
				if (!existing.logoUrl && ch.logoUrl) existing.logoUrl = ch.logoUrl;
			}
		}
		return Array.from(seen.values());
	}, [byType.movie]);
 
	const activeChannels = useMemo(() => {
		if (activeTab === "favorites") return channels.filter((ch) => ch.isFavorite);
		if (activeTab === "series") return seriesShows;
		if (activeTab === "movie") return movieTitles;
		if (activeTab === "history") return [];
		return byType[activeTab];
	}, [activeTab, seriesShows, movieTitles, byType, channels]);
 
	const categories = useMemo<Category[]>(() => {
		if (activeTab === "series" || activeTab === "favorites" || activeTab === "history")
			return [];
		const counts: Record<string, number> = {};
		for (const ch of byType[activeTab as "live" | "movie"]) {
			const key = ch.groupTitle || "";
			counts[key] = (counts[key] ?? 0) + 1;
		}
		return Object.entries(counts)
			.map(([name, channelCount]) => ({ id: name, name, channelCount }))
			.sort((a, b) => b.channelCount - a.channelCount);
	}, [byType, activeTab]);
 
	const handleTabChange = (tab: Tab) => {
		setActiveTab(tab);
		setSelectedCategory(null);
		setSearch("");
		setDebouncedSearch("");
		setShowFavoritesOnly(false);
		setEpgSearchResults([]);
		setNavState({ level: "home" });
	};
 
	const effectiveCategory = navState.level === "group" ? navState.name : selectedCategory;
 
	// Use debouncedSearch for filtering — prevents per-keystroke re-renders of virtualizer
	const filtered = useMemo(() => {
		let result = activeChannels;
		if (effectiveCategory && activeTab !== "series" && activeTab !== "favorites") {
			result = result.filter((ch) => ch.groupTitle === effectiveCategory);
		}
		if (debouncedSearch.trim()) {
			const lower = debouncedSearch.toLowerCase();
			result = result.filter((ch) => ch.name.toLowerCase().includes(lower));
		}
		if (showFavoritesOnly && activeTab !== "favorites") {
			result = result.filter((ch) => ch.isFavorite === true);
		}
		return result;
	}, [activeChannels, effectiveCategory, debouncedSearch, activeTab, showFavoritesOnly]);
 
	// Fetch EPG for all live channels: 2h past + 4h future = 6h window (generous for wider displays)
	useEffect(() => {
		if (activeTab !== "live" || channels.length === 0) return;
		const now = Math.floor(Date.now() / 1000);
		getEpgForLiveChannels(now - 7200, now + 14400)
			.then((progs) => {
				const map = new Map<string, EpgProgram[]>();
				for (const p of progs) {
					const list = map.get(p.channelId) ?? [];
					list.push(p);
					map.set(p.channelId, list);
				}
				setEpgMap(map);
			})
			.catch(() => {});
	}, [activeTab, channels.length]);
 
	// Debounced EPG programme search (300ms — backend round trip)
	useEffect(() => {
		if (!search.trim() || activeTab !== "live") {
			setEpgSearchResults([]);
			return;
		}
		const timer = setTimeout(() => {
			const now = Math.floor(Date.now() / 1000);
			searchEpgProgrammes(search.trim(), now)
				.then(setEpgSearchResults)
				.catch(() => {});
		}, 300);
		return () => clearTimeout(timer);
	}, [search, activeTab]);
 
	const getChannelPrograms = (ch: Channel): EpgProgram[] => {
		const key = ch.tvgId ?? null;
		if (!key) return [];
		return epgMap.get(key) ?? [];
	};
 
	const handlePlay = useCallback(
		async (channel: Channel) => {
			const currentTab = activeTab;
			if (currentTab === "series") {
				const showName = channel.seriesTitle ?? showTitle(channel.name);
				if (channel.url.startsWith("xtream://series/")) {
					setSeriesLoading(true);
					try {
						const eps = await getXtreamSeriesEpisodes(channel.id);
						setSeriesModalData({ showTitle: showName, episodes: eps });
					} catch (e) {
						console.error("[Xtream] failed to fetch series episodes:", e);
					} finally {
						setSeriesLoading(false);
					}
				} else {
					const eps = byType.series.filter(
						(ep) => (ep.seriesTitle ?? showTitle(ep.name)) === showName
					);
					setSeriesModalData({ showTitle: showName, episodes: eps });
				}
			} else if (currentTab === "movie" && channel.sources.length > 0) {
				setSelectedMovie(channel);
			} else if (currentTab === "favorites") {
				if (channel.contentType === "series") {
					const showName = channel.seriesTitle ?? showTitle(channel.name);
					if (channel.url.startsWith("xtream://series/")) {
						setSeriesLoading(true);
						try {
							const eps = await getXtreamSeriesEpisodes(channel.id);
							setSeriesModalData({ showTitle: showName, episodes: eps });
						} catch (e) {
							console.error("[Xtream] failed to fetch series episodes:", e);
						} finally {
							setSeriesLoading(false);
						}
					} else {
						const eps = byType.series.filter(
							(ep) => (ep.seriesTitle ?? showTitle(ep.name)) === showName
						);
						setSeriesModalData({ showTitle: showName, episodes: eps });
					}
				} else if (channel.contentType === "movie" && channel.sources.length > 0) {
					setSelectedMovie(channel);
				} else {
					navigate("/player", {
						state: { url: channel.url, channelName: channel.name, channel },
					});
				}
			} else {
				navigate("/player", {
					state: { url: channel.url, channelName: channel.name, channel },
				});
			}
		},
		[activeTab, byType.series, navigate]
	);
 
	const handleEpgResultPlay = useCallback(
		(epgChannelId: string) => {
			const ch = byType.live.find((c) => c.tvgId === epgChannelId);
			if (ch) handlePlay(ch);
		},
		[byType.live, handlePlay]
	);
 
	const handleToggleFavorite = useCallback(
		(channel: Channel) => {
			toggleFavorite(channel.id);
		},
		[toggleFavorite]
	);
 
	const handleHistoryPlay = useCallback(
		(entry: WatchHistoryEntry) => {
			if (entry.contentType === "series") {
				// Derive series title: try matching channel by ID first, then regex extraction
				const ch = byType.series.find((c) => c.id === entry.channelId);
				const seriesName = ch?.seriesTitle ?? showTitle(entry.channelName);
				// Find the series container to handle Xtream lazy-load
				const seriesContainer = byType.series.find(
					(s) => (s.seriesTitle ?? showTitle(s.name)) === seriesName
				);
				if (seriesContainer && seriesContainer.url.startsWith("xtream://series/")) {
					setSeriesLoading(true);
					getXtreamSeriesEpisodes(seriesContainer.id)
						.then((eps) => setSeriesModalData({ showTitle: seriesName, episodes: eps }))
						.catch((e) => console.error("[Xtream] failed to fetch series episodes:", e))
						.finally(() => setSeriesLoading(false));
				} else {
					const eps = byType.series.filter(
						(ep) => (ep.seriesTitle ?? showTitle(ep.name)) === seriesName
					);
					if (eps.length > 0) {
						setSeriesModalData({ showTitle: seriesName, episodes: eps });
					}
				}
			} else if (entry.contentType === "movie") {
				const movie = byType.movie.find((ch) => ch.name === entry.channelName);
				if (movie) setSelectedMovie(movie);
			} else {
				const ch = byType.live.find((c) => c.id === entry.channelId);
				if (!ch) return;
				navigate("/player", {
					state: { url: ch.url, channelName: entry.channelName, channel: ch },
				});
			}
		},
		[byType, navigate]
	);
 
	const favoritesByType = useMemo(() => {
		const favs = filtered;
		return {
			live: favs.filter((ch) => ch.contentType === "live"),
			movie: favs.filter((ch) => ch.contentType === "movie"),
			series: favs.filter((ch) => ch.contentType === "series"),
		};
	}, [filtered]);
 
	const isGrid = activeTab !== "live";
	// Dynamic grid columns: fit as many ~180 px-wide cards as possible, stretch via 1fr.
	const gridWidth = (containerWidth > 0 ? containerWidth : 800) - 24; // minus px-3 padding
	const GAP_PX = 12;
	const MIN_CARD_W = 180;
	const columnsPerRow = isGrid
		? Math.max(2, Math.floor((gridWidth + GAP_PX) / (MIN_CARD_W + GAP_PX)))
		: 1;
	// Card height: image (aspect 2:1 = width/2) + title (~28px) + margin (~10px)
	const cardWidth = isGrid ? (gridWidth - GAP_PX * (columnsPerRow - 1)) / columnsPerRow : 0;
	const gridRowHeight = isGrid ? Math.round(cardWidth / 2 + 38) : 48;
	const rowCount =
		activeTab === "favorites" || activeTab === "history"
			? 0
			: Math.ceil(filtered.length / columnsPerRow);
 
	const virtualizer = useVirtualizer({
		count: rowCount,
		getScrollElement: () => parentRef.current,
		estimateSize: () => gridRowHeight,
		overscan: 4,
	});
 
	// Use debouncedSearch for isLiveSearch to avoid expensive view-switch on every keystroke
	const isLiveSearch = activeTab === "live" && debouncedSearch.trim().length > 0;
	// Show channel list only when: no hierarchy (flat mode), or drilled into a group, or on favorites/history
	const showChannelList =
		!hierarchy.hasHierarchy ||
		navState.level === "group" ||
		activeTab === "favorites" ||
		activeTab === "history";
	const nowSec = Math.floor(Date.now() / 1000);
 
	// Grid marks for sticky header and background gridlines (uses same window as ChannelCard)
	const headerGridMarks = useMemo(
		() => getGridMarks(windowStart, windowEnd),
		[windowStart, windowEnd]
	);
 
	if (loading) {
		return (
			<div className="flex items-center justify-center h-full">
				<Loader2 className="h-5 w-5 animate-spin text-primary" />
			</div>
		);
	}
 
	if (channels.length === 0) {
		return (
			<div className="flex flex-col items-center justify-center h-full gap-3 p-8 text-center">
				<p className="text-base font-semibold">No channels yet</p>
				<p className="text-sm text-muted-foreground">Add a playlist to start watching.</p>
				<Button onClick={() => navigate("/playlists")} size="sm" className="mt-1">
					Add Playlist
				</Button>
			</div>
		);
	}
 
	const totalFavorites = channels.filter((ch) => ch.isFavorite).length;
 
	const countLabel =
		activeTab === "live"
			? "channels"
			: activeTab === "movie"
				? "movies"
				: activeTab === "series"
					? "shows"
					: "favorites";
 
	// Pixel offset of the timeline column left edge within the virtualizer div.
	// The virtualizer div already lives inside the px-3 padding of parentRef, so no extra 12px.
	const timelineLeft = ROW_CARD_LEFT_WIDTH;
 
	return (
		<div ref={rootRef} className="flex flex-col h-full">
			{/* Tab bar */}
			<div className="flex items-center gap-0 border-b border-border px-3 shrink-0">
				{TABS.map(({ id, label, icon: Icon }) => {
					const count =
						id === "history"
							? null
							: id === "favorites"
								? totalFavorites
								: id === "series"
									? seriesShows.length
									: id === "movie"
										? movieTitles.length
										: byType[id as "live"].length;
					return (
						<button
							key={id}
							onClick={() => handleTabChange(id)}
							className={`flex items-center gap-1.5 px-4 py-3 text-sm font-medium border-b-2 transition-colors ${
								activeTab === id
									? "border-primary text-primary"
									: "border-transparent text-muted-foreground hover:text-foreground"
							}`}
						>
							<Icon className="h-3.5 w-3.5" />
							{label}
							{count !== null && (
								<span
									className={`text-[11px] px-1.5 py-0.5 rounded-full tabular-nums ${
										activeTab === id
											? "bg-primary/15 text-primary"
											: "bg-muted text-muted-foreground"
									}`}
								>
									{count.toLocaleString()}
								</span>
							)}
						</button>
					);
				})}
				<div className="flex-1" />
				{activeTab !== "history" && <SearchBar value={search} onChange={setSearch} />}
				{activeTab !== "favorites" && activeTab !== "history" && (
					<button
						onClick={() => setShowFavoritesOnly((v) => !v)}
						className={`h-8 w-8 flex items-center justify-center rounded-md ml-1 transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring ${
							showFavoritesOnly
								? "text-red-500 bg-red-500/10"
								: "text-muted-foreground hover:text-foreground hover:bg-accent"
						}`}
						aria-label={showFavoritesOnly ? "Show all" : "Show favorites only"}
						aria-pressed={showFavoritesOnly}
					>
						<Heart className={`h-4 w-4 ${showFavoritesOnly ? "fill-current" : ""}`} />
					</button>
				)}
			</div>
 
			{/* Hierarchy navigation — replaces flat CategoryFilter */}
			{activeTab !== "favorites" && activeTab !== "history" && hierarchy.loaded && (
				<div className={showChannelList ? "shrink-0" : "flex-1 overflow-y-auto"}>
					{navState.level === "home" && (
						<>
							<RecentlyPlayedRow
								contentType={contentType as "live" | "movie" | "series"}
								onPlay={handleHistoryPlay}
								channels={channels}
							/>
							<PinnedGroupsRow
								pinnedGroups={hierarchy.pinnedGroups}
								categories={categories}
								selectedGroup={null}
								onSelectGroup={(name) => setNavState({ level: "group", name })}
								onUnpin={hierarchy.unpinGroup}
							/>
							{hierarchy.hasHierarchy ? (
								<CategoryBrowser
									superCategories={hierarchy.superCategories.map((name) => {
										const groups = hierarchy.getGroupsForCategory(name);
										return {
											name,
											groupCount: groups.length,
											channelCount: groups.reduce(
												(sum, g) =>
													sum +
													(categories.find((c) => c.name === g)
														?.channelCount ?? 0),
												0
											),
										};
									})}
									topLevelGroups={hierarchy.topLevelGroups.map((name) => ({
										name,
										channelCount:
											categories.find((c) => c.name === name)?.channelCount ??
											0,
									}))}
									onSelectCategory={(name) =>
										setNavState({ level: "category", name })
									}
									onSelectGroup={(name) => setNavState({ level: "group", name })}
									onManage={() => setShowCategoryManager(true)}
								/>
							) : categories.length > 1 ? (
								<div className="px-3 pt-2.5">
									<CategoryFilter
										categories={categories}
										selected={selectedCategory}
										onSelect={setSelectedCategory}
									/>
								</div>
							) : null}
							{!hierarchy.hasHierarchy &&
								hierarchy.entries.length === 0 &&
								categories.length > 1 && (
									<div className="mx-4 mt-2 p-3 rounded-lg bg-primary/5 border border-primary/20 text-sm">
										<p className="text-muted-foreground">
											Channels not categorized yet.
										</p>
										<button
											onClick={() => setShowCategoryManager(true)}
											className="text-primary hover:underline text-xs mt-1"
										>
											Use AI to organize channels?
										</button>
									</div>
								)}
						</>
					)}
					{navState.level === "category" && (
						<>
							<Breadcrumb
								path={[
									{
										label: "All Categories",
										onClick: () => setNavState({ level: "home" }),
									},
									{ label: navState.name },
								]}
							/>
							<GroupList
								groups={hierarchy
									.getGroupsForCategory(navState.name)
									.filter(
										(g) =>
											!debouncedSearch ||
											g.toLowerCase().includes(debouncedSearch.toLowerCase())
									)}
								categories={categories}
								onSelectGroup={(name) =>
									setNavState({
										level: "group",
										name,
										parentCategory: navState.name,
									})
								}
								isPinned={hierarchy.isPinned}
								onTogglePin={(name) =>
									hierarchy.isPinned(name)
										? hierarchy.unpinGroup(name)
										: hierarchy.pinGroup(name)
								}
							/>
						</>
					)}
					{navState.level === "group" && (
						<Breadcrumb
							path={[
								...(navState.parentCategory
									? [
											{
												label: "All Categories",
												onClick: () => setNavState({ level: "home" }),
											},
											{
												label: navState.parentCategory,
												onClick: () =>
													setNavState({
														level: "category",
														name: navState.parentCategory!,
													}),
											},
										]
									: [
											{
												label: "All Categories",
												onClick: () => setNavState({ level: "home" }),
											},
										]),
								{ label: navState.name },
							]}
						/>
					)}
				</div>
			)}
 
			{/* Result count */}
			{activeTab !== "history" && !isLiveSearch && showChannelList && (
				<div className="shrink-0 px-3 pt-2 pb-1">
					<span className="text-xs text-muted-foreground">
						{filtered.length.toLocaleString()} {countLabel}
					</span>
				</div>
			)}
 
			{/* Sticky time-axis header — only when channel list is visible */}
			{activeTab === "live" && showChannelList && (
				<div className="shrink-0 flex items-center px-3 pb-1 border-b border-border/15">
					{/* Left spacer: matches ROW_CARD_LEFT_WIDTH in RowCard */}
					<div style={{ width: `${ROW_CARD_LEFT_WIDTH}px` }} className="shrink-0" />
					{/* Time label area: flex-1 matches the timeline flex-1 */}
					<div className="flex-1 relative h-5">
						{headerGridMarks.map((t) => {
							const p = toPct(t, windowStart, windowTotal);
							if (p < 2 || p > 98) return null;
							const isHour = t % 3600 === 0;
							return (
								<span
									key={t}
									className={`absolute -translate-x-1/2 tabular-nums select-none ${
										isHour
											? "text-[9px] text-muted-foreground/75 font-medium"
											: "text-[8px] text-muted-foreground/40"
									}`}
									style={{ left: `${p.toFixed(3)}%`, top: "4px" }}
								>
									{formatHHMM(t)}
								</span>
							);
						})}
						{/* "Now" arrow aligned with the red marker line */}
						<span
							className="absolute -translate-x-1/2 text-[9px] text-red-400/80 select-none"
							style={{
								left: `${toPct(nowSec, windowStart, windowTotal).toFixed(3)}%`,
								top: "2px",
							}}
						>						</span>
					</div>
					{/* Right spacer: matches RIGHT_BUTTONS_PX so percentages align with gridlines */}
					<div style={{ width: `${RIGHT_BUTTONS_PX}px` }} className="shrink-0" />
				</div>
			)}
 
			{/* Series loading overlay */}
			{seriesLoading && (
				<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm">
					<div className="flex items-center gap-3 bg-card rounded-2xl px-6 py-4 shadow-2xl">
						<Loader2 className="h-5 w-5 animate-spin text-primary" />
						<span className="text-sm font-medium">Loading episodes…</span>
					</div>
				</div>
			)}
 
			{seriesModalData && (
				<SeriesDetailModal
					showTitle={seriesModalData.showTitle}
					episodes={seriesModalData.episodes}
					onClose={() => setSeriesModalData(null)}
					onPlay={(ch) => {
						const sorted = [...seriesModalData.episodes].sort((a, b) => {
							const sa = a.season ?? 0,
								sb = b.season ?? 0;
							if (sa !== sb) return sa - sb;
							return (a.episode ?? 0) - (b.episode ?? 0);
						});
						navigate("/player", {
							state: {
								url: ch.url,
								channelName: ch.name,
								channel: ch,
								seriesEpisodes: sorted,
							},
						});
					}}
				/>
			)}
 
			{selectedMovie && (
				<MovieInfoDrawer
					movie={selectedMovie}
					onClose={() => setSelectedMovie(null)}
					onPlay={(ch) =>
						navigate("/player", {
							state: { url: ch.url, channelName: ch.name, channel: ch },
						})
					}
				/>
			)}
 
			{/* History tab */}
			{activeTab === "history" ? (
				<HistoryTab onPlay={handleHistoryPlay} />
			) : activeTab === "favorites" ? (
				<div className="flex-1 overflow-auto scrollbar-hide px-3 pb-3">
					{filtered.length === 0 ? (
						<div className="flex flex-col items-center justify-center h-full gap-2 text-center py-12">
							<Heart className="h-10 w-10 text-muted-foreground/30" />
							<p className="text-sm text-muted-foreground">
								No favorites yet — tap ♡ on any channel
							</p>
						</div>
					) : (
						<div className="space-y-4 pt-2">
							{favoritesByType.live.length > 0 && (
								<section>
									<h3 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2 px-0.5">
										Live
									</h3>
									<div className="flex flex-col">
										{favoritesByType.live.map((ch) => (
											<ChannelCard
												key={ch.id}
												channel={ch}
												onPlay={handlePlay}
												variant="row"
												onToggleFavorite={handleToggleFavorite}
												epgPrograms={getChannelPrograms(ch)}
												windowStart={windowStart}
												windowEnd={windowEnd}
											/>
										))}
									</div>
								</section>
							)}
							{favoritesByType.movie.length > 0 && (
								<section>
									<h3 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2 px-0.5">
										Movies
									</h3>
									<div
										className="grid gap-3"
										style={{
											gridTemplateColumns: `repeat(${columnsPerRow}, minmax(0, 1fr))`,
										}}
									>
										{favoritesByType.movie.map((ch) => (
											<ChannelCard
												key={ch.id}
												channel={ch}
												onPlay={handlePlay}
												variant="poster"
												onToggleFavorite={handleToggleFavorite}
											/>
										))}
									</div>
								</section>
							)}
							{favoritesByType.series.length > 0 && (
								<section>
									<h3 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2 px-0.5">
										Series
									</h3>
									<div
										className="grid gap-3"
										style={{
											gridTemplateColumns: `repeat(${columnsPerRow}, minmax(0, 1fr))`,
										}}
									>
										{favoritesByType.series.map((ch) => (
											<ChannelCard
												key={ch.id}
												channel={ch}
												onPlay={handlePlay}
												variant="poster"
												onToggleFavorite={handleToggleFavorite}
											/>
										))}
									</div>
								</section>
							)}
						</div>
					)}
				</div>
			) : isLiveSearch ? (
				/* Search results: channel name matches + EPG programme matches */
				<div className="flex-1 overflow-auto scrollbar-hide px-3 pb-3 pt-2">
					{filtered.length > 0 && (
						<>
							<p className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground px-1 mb-1">
								Channels
							</p>
							<div className="flex flex-col mb-3 relative">
								{/* Background gridlines — mirrors the virtualizer path */}
								<div
									className="absolute inset-0 pointer-events-none z-0"
									style={{
										left: `${ROW_CARD_LEFT_WIDTH}px`,
										right: `${RIGHT_BUTTONS_PX}px`,
									}}
								>
									{headerGridMarks.map((t) => (
										<div
											key={t}
											className={`absolute top-0 bottom-0 w-px ${
												t % 3600 === 0 ? "bg-border/30" : "bg-border/12"
											}`}
											style={{
												left: `${toPct(t, windowStart, windowTotal).toFixed(3)}%`,
											}}
										/>
									))}
									<div
										className="absolute top-0 bottom-0 w-px bg-red-400/20"
										style={{
											left: `${toPct(nowSec, windowStart, windowTotal).toFixed(3)}%`,
										}}
									/>
								</div>
								{filtered.slice(0, 80).map((ch) => (
									<ChannelCard
										key={ch.id}
										channel={ch}
										onPlay={handlePlay}
										variant="row"
										onToggleFavorite={handleToggleFavorite}
										epgPrograms={getChannelPrograms(ch)}
										windowStart={windowStart}
										windowEnd={windowEnd}
									/>
								))}
								{filtered.length > 80 && (
									<p className="text-[10px] text-muted-foreground/50 px-2 py-1">
										+{filtered.length - 80} more — narrow your search
									</p>
								)}
							</div>
						</>
					)}
 
					{epgSearchResults.length > 0 && (
						<>
							<p className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground px-1 mb-1">
								On Now / Upcoming
							</p>
							<div className="flex flex-col">
								{epgSearchResults.map((result, i) => (
									<button
										key={`${result.channelId}-${i}`}
										onClick={() => handleEpgResultPlay(result.channelId)}
										className="group flex items-center gap-3 w-full px-2 py-2 rounded-lg hover:bg-accent transition-colors text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
									>
										<EpgResultLogo url={result.channelLogoUrl} />
 
										<div className="flex-1 min-w-0">
											<p className="text-sm leading-tight truncate">
												{result.title}
											</p>
											<p className="text-[11px] text-muted-foreground truncate mt-0.5">
												{result.channelName}
											</p>
										</div>
										<span className="text-[10px] text-muted-foreground shrink-0 tabular-nums">
											{formatEpgTime(result.startTime, nowSec)}
										</span>
									</button>
								))}
							</div>
						</>
					)}
 
					{filtered.length === 0 && epgSearchResults.length === 0 && (
						<p className="text-sm text-muted-foreground text-center py-12">
							No results for "{debouncedSearch}"
						</p>
					)}
				</div>
			) : !showChannelList ? null : (
				/* Virtualised list — live/movie/series tabs */
				<div
					key={columnsPerRow}
					ref={parentRef}
					className="flex-1 overflow-auto scrollbar-hide px-3 pb-3"
				>
					{filtered.length === 0 && showFavoritesOnly ? (
						<div className="flex flex-col items-center justify-center h-full gap-2 text-center py-12">
							<Heart className="h-10 w-10 text-muted-foreground/30" />
							<p className="text-sm text-muted-foreground">
								No favorites yet — tap ♡ on any channel
							</p>
						</div>
					) : (
						<div
							style={{
								height: `${virtualizer.getTotalSize()}px`,
								width: "100%",
								position: "relative",
							}}
						>
							{/* Background gridlines spanning full virtual height — only on Live tab */}
							{activeTab === "live" && (
								<div
									className="absolute top-0 bottom-0 pointer-events-none z-0"
									style={{
										left: `${timelineLeft}px`,
										right: `${RIGHT_BUTTONS_PX}px`,
									}}
								>
									{headerGridMarks.map((t) => (
										<div
											key={t}
											className={`absolute top-0 bottom-0 w-px ${
												t % 3600 === 0 ? "bg-border/30" : "bg-border/12"
											}`}
											style={{
												left: `${toPct(t, windowStart, windowTotal).toFixed(3)}%`,
											}}
										/>
									))}
									{/* Full-height "now" line */}
									<div
										className="absolute top-0 bottom-0 w-px bg-red-400/20"
										style={{
											left: `${toPct(nowSec, windowStart, windowTotal).toFixed(3)}%`,
										}}
									/>
								</div>
							)}
 
							{/* Virtual rows */}
							{virtualizer.getVirtualItems().map((virtualRow) => {
								const startIdx = virtualRow.index * columnsPerRow;
								const rowChannels = filtered.slice(
									startIdx,
									startIdx + columnsPerRow
								);
								return (
									<div
										key={virtualRow.key}
										style={{
											position: "absolute",
											top: 0,
											left: 0,
											width: "100%",
											height: `${virtualRow.size}px`,
											transform: `translateY(${virtualRow.start}px)`,
										}}
									>
										{isGrid ? (
											<div
												className="grid gap-3 pt-1"
												style={{
													gridTemplateColumns: `repeat(${columnsPerRow}, minmax(0, 1fr))`,
												}}
											>
												{rowChannels.map((ch) => (
													<ChannelCard
														key={ch.id}
														channel={ch}
														onPlay={handlePlay}
														variant="poster"
														onToggleFavorite={handleToggleFavorite}
													/>
												))}
											</div>
										) : (
											<div className="flex flex-col">
												{rowChannels.map((ch) => (
													<ChannelCard
														key={ch.id}
														channel={ch}
														onPlay={handlePlay}
														variant="row"
														onToggleFavorite={handleToggleFavorite}
														epgPrograms={getChannelPrograms(ch)}
														windowStart={windowStart}
														windowEnd={windowEnd}
													/>
												))}
											</div>
										)}
									</div>
								);
							})}
						</div>
					)}
				</div>
			)}
 
			{showCategoryManager && activeProviderId && (
				<div className="absolute inset-0 z-50 bg-background">
					<CategoryManager
						providerId={activeProviderId}
						contentType={contentType}
						channels={channels}
						onClose={() => setShowCategoryManager(false)}
						onHierarchyChanged={() => hierarchy.reload()}
					/>
				</div>
			)}
		</div>
	);
};