All files / src/components/channels ChannelList.tsx

97.36% Statements 333/342
97.07% Branches 332/342
98.16% Functions 107/109
97.6% Lines 285/292

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 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317                                                                                                                                    245x   4x                   24x     3097x     4x         4x           4x   4x 16x 16x 10x 8x 6x 6x 6x 6x 6x 6x 4x 2x           4x 620x   620x 620x 620x 620x 620x     620x 620x     620x   620x   620x 127x   620x 123x   620x     620x         620x   620x   620x 620x 620x 620x 620x         620x   620x 620x     620x       620x   620x   620x               620x 104x 104x 104x 8x   104x 104x         620x       224x 224x       224x 224x 224x 224x     620x     620x 123x 123x     620x 112x         112x 1127x 1127x     112x     620x 112x 112x 223x 223x 223x   112x           620x 112x 112x 223x 13x 13x 13x 9x   112x       620x   9x   13x 9x 13x   9x 9x 9x         620x   620x 133x 109x 100x 82x 66x     620x 133x           49x 84x     620x 21x 21x 21x 21x 21x 21x     620x       620x 620x 620x 620x 25x   620x 202x   620x 14x   620x 4x   620x                                 620x 620x       110x       620x 681x                   620x             620x               620x     620x 620x 119x 10x 10x 9x   8x       10x 10x 10x       620x 1028x   1028x           620x   10x 10x 10x 10x 10x 7x 7x   2x 1x     9x   9x 2x   9x           1x   10x               620x   19x 19x 10x 9x       2x   7x               620x   4x 2x         620x   2x         620x   12x   6x   8x 6x     6x 5x 5x 3x               2x 1x             6x 2x 2x   1x 2x   12x   6x 7x 3x 3x             7x 3x 2x               620x 197x 197x 818x 818x 818x               620x   620x 64x         620x   620x 620x 620x 620x       620x 620x           620x                 620x   496x 1208x           620x 123x       620x 620x     620x           620x 149x       620x 6x             614x 6x       1x             6354x       608x                 620x       620x   620x                                   3636x                     3636x     21x                                                                                 6x                                     2x                                                             1x           11x 11x         22x         11x         3x     1x   1x                                     1x                             1x                   18x         1x               2x                                     1x                 1x                                                           1839x 1839x 1535x 1535x                                                                                         1x   1x                             2x   1x                                       1x                                   159x                                                     31x                                             22x                                                                 42x                                     86x                                                       16x   2x                                                                                                 1x                                                     1719x                                           891x 891x       891x                                       189x                       783x                                                       1x 1x              
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 Max Boksem. See NOTICE for additional terms under GPLv3 section 7.
 
import { useState, useMemo, useCallback, useRef, useEffect } from "react";
import { useNavigate } from "react-router";
import { useVirtualizer } from "@tanstack/react-virtual";
import {
	LoaderCircle,
	TvMinimal,
	MonitorPlay,
	Heart,
	Clapperboard,
	RotateCcwClock,
	Download,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { SearchBar } from "./SearchBar";
import { CategoryFilter } from "./CategoryFilter";
import { ChannelCard, COMPACT_ROW_HEIGHT, ROW_CARD_LEFT_WIDTH } from "./ChannelCard";
import { ChannelLogo } from "./ChannelLogo";
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 { NoSearchResults } from "./NoSearchResults";
import { DownloadsTab } from "./DownloadsTab";
import { isMobilePlatform } from "@/lib/platform";
import { usePlatform } from "@/hooks/usePlatform";
import {
	coversWindow,
	formatHHMM,
	getGridMarks,
	guideRangeFor,
	toPct,
	type TimeRange,
} from "@/lib/epg-window";
import { useChannels } from "@/hooks/useChannels";
import { useDownloads } from "@/hooks/useDownloads";
import { useDelayedFlag } from "@/hooks/useDelayedFlag";
import { useNow } from "@/hooks/useNow";
import { useGuidePrograms, type GuideChannels } from "@/hooks/useGuidePrograms";
import { getXtreamSeriesEpisodes, getCachedSeriesEpisodes, searchEpgProgrammes } from "@/lib/tauri";
import { consumeBrowseState, saveBrowseSearch, saveBrowseTab } from "@/lib/browse-state";
import { findEpisode, sortEpisodes } from "@/lib/episodes";
import { categoriesByCount, channelCountFor, dedupeByTitle, seriesTitleOf } from "@/lib/channels";
import { nowSeconds } from "@/lib/date";
import { recordingChannel } from "@/lib/recordings";
import { formatCount } from "@/lib/format";
import type {
	Channel,
	Category,
	EpgProgram,
	EpgSearchResult,
	WatchHistoryEntry,
} from "@/lib/types";
 
type Tab = "live" | "movie" | "series" | "favorites" | "downloads" | "history";
 
/** Grouping key for series titles — tolerant of case and spacing differences. */
const seriesKey = (title: string): string => title.trim().toLowerCase().replace(/\s+/g, " ");
 
const ALL_TABS: { id: Tab; label: string; icon: React.ElementType }[] = [
	{ id: "live", label: "Live", icon: TvMinimal },
	{ id: "movie", label: "Movies", icon: Clapperboard },
	{ id: "series", label: "Series", icon: MonitorPlay },
	{ id: "favorites", label: "Favorites", icon: Heart },
	{ id: "downloads", label: "Downloads", icon: Download },
	{ id: "history", label: "History", icon: RotateCcwClock },
];
 
// The mobile apps have no downloads.
const TABS = ALL_TABS.filter((t) => t.id !== "downloads" || !isMobilePlatform());
 
/** Whether `v` names a tab this platform shows, such as one saved before playback. */
const isTab = (v: unknown): v is Tab => TABS.some((t) => t.id === v);
 
/** 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;
 
/**
 * The guide data of a channel that has none. One shared list keeps the prop
 * the same between renders, so the memoized rows don't re-render for it.
 */
const NO_PROGRAMS: EpgProgram[] = [];
 
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}`
	);
};
 
export const ChannelList = () => {
	const { channels, loading, toggleFavorite, providers, guideVersion } = useChannels();
	// A phone is too narrow for the EPG timeline, so live rows show what's on now.
	const { layoutMode } = usePlatform();
	const compactRows = layoutMode === "mobile";
	const rowVariant = compactRows ? "compact" : "row";
	const { byChannel, bySeries } = useDownloads();
	const navigate = useNavigate();
 
	// Tab and search are restored when coming back from the player (see lib/browse-state).
	const [initialBrowse] = useState(consumeBrowseState);
	const [activeTab, setActiveTab] = useState<Tab>(
		isTab(initialBrowse.tab) ? initialBrowse.tab : "live"
	);
	const [search, setSearch] = useState(initialBrowse.search);
	// Debounced search — updated 250ms after user stops typing to avoid per-keystroke re-renders
	const [debouncedSearch, setDebouncedSearch] = useState(initialBrowse.search);
 
	useEffect(() => {
		saveBrowseTab(activeTab);
	}, [activeTab]);
	useEffect(() => {
		saveBrowseSearch(search);
	}, [search]);
	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 [showDownloadsOnly, setShowDownloadsOnly] = useState(false);
	const [seriesModalData, setSeriesModalData] = useState<{
		showTitle: string;
		episodes: Channel[];
		seriesChannelId: string;
	} | null>(null);
	const [seriesLoading, setSeriesLoading] = useState(false);
	// Episode lists usually load in a moment; only show the overlay when they don't.
	const showSeriesLoading = useDelayedFlag(seriesLoading, 300);
	const [selectedMovie, setSelectedMovie] = useState<Channel | null>(null);
 
	// EPG search: one result per channel (earliest matching program)
	const [epgSearchResults, setEpgSearchResults] = useState<EpgSearchResult[]>([]);
 
	// The root div's width, which sets the guide's window and the grid
	// columns. It's null until the div has been measured.
	const [containerWidth, setContainerWidth] = useState<number | null>(null);
	// The guide's window and its red line for now follow this clock.
	const now = useNow();
	/** Virtualizer scroll ref — kept for TanStack Virtual scroll element. */
	const parentRef = useRef<HTMLDivElement>(null);
 
	/**
	 * Ref callback for the root div. While the channels load, or before any
	 * arrive, the list shows a spinner or a message in its place and the div
	 * loses this ref. This measures the div each time it gets the ref back,
	 * then follows its size.
	 */
	const measureRoot = useCallback((el: HTMLDivElement | null) => {
		Iif (!el) return;
		setContainerWidth(el.clientWidth);
		const observer = new ResizeObserver(([entry]) =>
			setContainerWidth(entry.contentRect.width)
		);
		observer.observe(el);
		return () => observer.disconnect();
	}, []);
 
	// The guide's window, PX_PER_HOUR pixels for each hour and never under 3
	// hours, with a third of it before now. It moves along with the clock.
	const { windowStart, windowEnd } = useMemo(() => {
		// containerWidth is the whole component's width. The scroll container
		// inside has px-3, 12px on each side, and each row has two fixed
		// columns, so the timeline gets what's left.
		const effectiveWidth = containerWidth || 400;
		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, now]);
 
	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 Emap.live.push(ch);
		}
		return map;
	}, [channels]);
 
	const seriesShows = useMemo(() => {
		const seen = new Map<string, Channel>();
		for (const ch of byType.series) {
			const title = seriesTitleOf(ch);
			const key = seriesKey(title);
			if (!seen.has(key)) seen.set(key, { ...ch, name: title, sources: [] });
		}
		return Array.from(seen.values());
	}, [byType.series]);
 
	// Xtream lists the same show as separate series entries (other categories,
	// languages, servers). They're shown as one card, so keep every entry per
	// title to load all their episodes — the duplicates become extra sources.
	const xtreamSeriesByTitle = useMemo(() => {
		const map = new Map<string, Channel[]>();
		for (const ch of byType.series) {
			if (!ch.url.startsWith("xtream://series/")) continue;
			const key = seriesKey(seriesTitleOf(ch));
			const list = map.get(key);
			if (list) list.push(ch);
			else map.set(key, [ch]);
		}
		return map;
	}, [byType.series]);
 
	/** Episodes of every Xtream series entry sharing this show's title. */
	const fetchXtreamShowEpisodes = useCallback(
		async (showName: string, container: Channel): Promise<Channel[]> => {
			const containers = xtreamSeriesByTitle.get(seriesKey(showName)) ?? [container];
			// The clicked entry first so its episodes stay the default source.
			const ordered = [container, ...containers.filter((c) => c.id !== container.id)];
			const results = await Promise.allSettled(
				ordered.map((c) => getXtreamSeriesEpisodes(c.id))
			);
			const first = results[0];
			if (first.status === "rejected") throw first.reason;
			return results.flatMap((r) => (r.status === "fulfilled" ? r.value : []));
		},
		[xtreamSeriesByTitle]
	);
 
	const movieTitles = useMemo(() => dedupeByTitle(byType.movie), [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" || activeTab === "downloads") return [];
		return byType[activeTab];
	}, [activeTab, seriesShows, movieTitles, byType, channels]);
 
	const categories = useMemo<Category[]>(() => {
		if (
			activeTab === "series" ||
			activeTab === "favorites" ||
			activeTab === "history" ||
			activeTab === "downloads"
		)
			return [];
		return categoriesByCount(byType[activeTab as "live" | "movie"]);
	}, [byType, activeTab]);
 
	const handleTabChange = (tab: Tab) => {
		setActiveTab(tab);
		setSelectedCategory(null);
		setShowFavoritesOnly(false);
		setShowDownloadsOnly(false);
		setEpgSearchResults([]);
		setNavState({ level: "home" });
	};
 
	const effectiveCategory = navState.level === "group" ? navState.name : selectedCategory;
 
	// Filtering uses the debounced search, so typing doesn't re-render the
	// list on every key. Spaces around the search don't count.
	const searchQuery = debouncedSearch.trim().toLowerCase();
	const filtered = useMemo(() => {
		let result = activeChannels;
		if (effectiveCategory && activeTab !== "series" && activeTab !== "favorites") {
			result = result.filter((ch) => ch.groupTitle === effectiveCategory);
		}
		if (searchQuery) {
			result = result.filter((ch) => ch.name.toLowerCase().includes(searchQuery));
		}
		if (showFavoritesOnly && activeTab !== "favorites") {
			result = result.filter((ch) => ch.isFavorite === true);
		}
		if (showDownloadsOnly && activeTab !== "downloads") {
			result = result.filter((ch) => byChannel.has(ch.id) || bySeries.has(ch.id));
		}
		return result;
	}, [
		activeChannels,
		effectiveCategory,
		searchQuery,
		activeTab,
		showFavoritesOnly,
		showDownloadsOnly,
		byChannel,
		bySeries,
	]);
 
	// The part of the guide to load, which covers the window. It waits for the
	// first measurement so a wide list doesn't load twice. After that it only
	// moves when the window leaves it, as the list gets wider or the clock
	// carries the window past its end. A narrower list or a clock tick doesn't
	// load the guide again.
	const [guideRange, setGuideRange] = useState<TimeRange | null>(null);
	if (
		containerWidth !== null &&
		!(guideRange && coversWindow(guideRange, windowStart, windowEnd))
	) {
		setGuideRange(guideRangeFor(now, windowStart, windowEnd));
	}
 
	// The guide ids of the live favorites, for the Favorites tab.
	const favoriteGuideIds = useMemo(
		() => byType.live.flatMap((ch) => (ch.isFavorite && ch.tvgId ? [ch.tvgId] : [])),
		[byType.live]
	);
 
	// The Live tab shows every channel's guide, and the Favorites tab only that
	// of its live favorites with a guide id. It loads when its range moves,
	// when the tab starts showing it, when the number of channels changes and
	// when a provider's guide finishes refreshing. Going from Live to Favorites
	// keeps what's loaded, and a new favorite loads only its own programs.
	const guideChannels: GuideChannels | null =
		channels.length === 0
			? null
			: activeTab === "live"
				? "all"
				: activeTab === "favorites" && favoriteGuideIds.length > 0
					? favoriteGuideIds
					: null;
	const { programs: epgMap, isPending: guidePending } = useGuidePrograms(
		guideRange,
		guideChannels,
		`${channels.length}:${guideVersion}`
	);
 
	// Debounced EPG programme search, 300ms since it's a backend round trip.
	// Only the live tab searches the guide.
	const epgQuery = activeTab === "live" ? search.trim() : "";
	// Clearing the search drops the results while rendering, so they don't
	// show for a frame after the box empties.
	if (!epgQuery && epgSearchResults.length > 0) setEpgSearchResults([]);
	useEffect(() => {
		if (!epgQuery) return;
		let current = true;
		const timer = setTimeout(() => {
			searchEpgProgrammes(epgQuery, nowSeconds())
				.then((results) => {
					if (current) setEpgSearchResults(results);
				})
				.catch(() => {});
		}, 300);
		return () => {
			current = false;
			clearTimeout(timer);
		};
	}, [epgQuery]);
 
	const getChannelPrograms = (ch: Channel): EpgProgram[] =>
		(ch.tvgId && epgMap.get(ch.tvgId)) || NO_PROGRAMS;
	// A row whose programs are on their way may only be waiting for them.
	const isGuidePending = (ch: Channel): boolean => Boolean(ch.tvgId && guidePending(ch.tvgId));
 
	/**
	 * Opens the episode list for a show. From Downloads, which has to work
	 * offline, the cached list stands in when the live one can't be had.
	 */
	const openSeries = useCallback(
		async (channel: Channel, cacheFallback: boolean) => {
			const showName = seriesTitleOf(channel);
			setSeriesLoading(true);
			try {
				let eps: Channel[] = [];
				if (channel.url.startsWith("xtream://series/")) {
					try {
						eps = await fetchXtreamShowEpisodes(showName, channel);
					} catch (e) {
						if (!cacheFallback) throw e;
						console.warn("[ChannelList] live episode fetch failed, using cache:", e);
					}
				} else {
					eps = byType.series.filter((ep) => seriesTitleOf(ep) === showName);
				}
				if (cacheFallback && eps.length === 0) {
					eps = await getCachedSeriesEpisodes(channel.id);
				}
				setSeriesModalData({
					showTitle: showName,
					episodes: eps,
					seriesChannelId: channel.id,
				});
			} catch (e) {
				console.error("[ChannelList] failed to load series episodes:", e);
			} finally {
				setSeriesLoading(false);
			}
		},
		[byType.series, fetchXtreamShowEpisodes]
	);
 
	// Shows open their episode list and movies with sources open their drawer.
	// Favorites and Downloads mix types, so there the channel's own type decides.
	const handlePlay = useCallback(
		(channel: Channel) => {
			const mixed = activeTab === "favorites" || activeTab === "downloads";
			if (activeTab === "series" || (mixed && channel.contentType === "series")) {
				void openSeries(channel, activeTab === "downloads");
			} else if (
				(activeTab === "movie" || (mixed && channel.contentType === "movie")) &&
				channel.sources.length > 0
			) {
				setSelectedMovie(channel);
			} else {
				navigate("/player", {
					state: { url: channel.url, channelName: channel.name, channel },
				});
			}
		},
		[activeTab, navigate, openSeries]
	);
 
	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") {
				// The history names the show the same way the Recently Played row does.
				const seriesName = entry.seriesTitle ?? seriesTitleOf({ name: entry.channelName });
				// Find the series container to handle Xtream lazy-load
				const seriesContainer = byType.series.find((s) => seriesTitleOf(s) === seriesName);
				const seriesChannelId = seriesContainer?.id ?? entry.channelId;
				// Play the watched episode directly; if it's no longer listed, fall
				// back to the series picker.
				const playOrPick = (eps: Channel[]) => {
					const ep = findEpisode(eps, entry.channelId, entry.channelName);
					if (ep) {
						navigate("/player", {
							state: {
								url: ep.url,
								channelName: ep.name,
								channel: ep,
								seriesEpisodes: sortEpisodes(eps),
							},
						});
					} else if (eps.length > 0) {
						setSeriesModalData({
							showTitle: seriesName,
							episodes: eps,
							seriesChannelId,
						});
					}
				};
				if (seriesContainer && seriesContainer.url.startsWith("xtream://series/")) {
					setSeriesLoading(true);
					fetchXtreamShowEpisodes(seriesName, seriesContainer)
						.then(playOrPick)
						.catch((e) => console.error("[Xtream] failed to fetch series episodes:", e))
						.finally(() => setSeriesLoading(false));
				} else {
					playOrPick(byType.series.filter((ep) => seriesTitleOf(ep) === seriesName));
				}
			} else if (entry.contentType === "movie") {
				const movie = byType.movie.find((ch) => ch.name === entry.channelName);
				if (movie) setSelectedMovie(movie);
			} else Iif (entry.contentType === "recording") {
				// A recording plays from its file for as long as the app keeps it.
				const rec = byChannel.get(entry.channelId);
				if (rec?.kind !== "recording" || rec.status !== "completed") return;
				const ch = recordingChannel(rec);
				navigate("/player", { state: { url: ch.url, channelName: ch.name, channel: ch } });
			} 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, byChannel, navigate, fetchXtreamShowEpisodes]
	);
 
	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]);
 
	// Number of downloaded items (movies + episodes + finished recordings).
	// `byChannel` is keyed per download channel, so a series' episodes count
	// individually; the series container itself has no download record and
	// must not be added. A recording counts once it has a file.
	const downloadCount = useMemo(
		() =>
			[...byChannel.values()].filter(
				(d) => d.kind !== "recording" || d.status === "completed"
			).length,
		[byChannel]
	);
 
	const isGrid = activeTab !== "live";
	// Dynamic grid columns: fit as many ~180 px-wide cards as possible, stretch via 1fr.
	const gridWidth = (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)
		: compactRows
			? COMPACT_ROW_HEIGHT
			: 48;
	const rowCount =
		activeTab === "favorites" || activeTab === "history"
			? 0
			: Math.ceil(filtered.length / columnsPerRow);
 
	// The compiler can't memoize what TanStack Virtual returns, so it skips this
	// whole component. That's the right call, and the app doesn't run the
	// compiler yet, but it also means the compiler rules don't check anything
	// else in ChannelList. To check it, rename useVirtualizer for one lint run.
	// eslint-disable-next-line react-hooks/incompatible-library -- see above
	const virtualizer = useVirtualizer({
		count: rowCount,
		getScrollElement: () => parentRef.current,
		estimateSize: () => gridRowHeight,
		overscan: 4,
	});
 
	// The virtualizer keeps row sizes until told otherwise, and the height
	// changes with the window width and layout.
	useEffect(() => {
		virtualizer.measure();
	}, [gridRowHeight, virtualizer]);
 
	// Use debouncedSearch for isLiveSearch to avoid expensive view-switch on every keystroke
	const hasSearch = searchQuery.length > 0;
	const isLiveSearch = activeTab === "live" && hasSearch;
	// 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";
 
	// 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">
				<LoaderCircle 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;
 
	// What the list counts, such as "channel" in "3 channels".
	const countNoun =
		activeTab === "live"
			? "channel"
			: activeTab === "movie"
				? "movie"
				: activeTab === "series"
					? "show"
					: activeTab === "downloads"
						? "download"
						: "favorite";
	const countLabel = `${countNoun}s`;
 
	// 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={measureRoot} className="flex flex-col h-full">
			{/* Tab bar. The tabs scroll sideways when they don't fit; on phones the
			    search and filters move to a row of their own below them. */}
			<div
				className={cn(
					"border-b border-border shrink-0",
					!compactRows && "flex items-center px-3"
				)}
			>
				<div
					className={cn(
						"flex items-center min-w-0 overflow-x-auto scrollbar-hide",
						compactRows ? "px-1" : "flex-1"
					)}
				>
					{TABS.map(({ id, label, icon: Icon }) => {
						const count =
							id === "history"
								? null
								: id === "favorites"
									? totalFavorites
									: id === "downloads"
										? downloadCount
										: 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 ${compactRows ? "px-3" : "px-4"} py-3 text-sm font-medium whitespace-nowrap shrink-0 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>
				<div
					className={cn(
						"flex items-center shrink-0",
						compactRows && "px-3 pt-2.5 pb-2 empty:hidden"
					)}
				>
					{activeTab !== "history" && activeTab !== "downloads" && (
						<SearchBar
							value={search}
							onChange={setSearch}
							className={compactRows ? "flex-1 w-auto" : undefined}
						/>
					)}
					{activeTab !== "favorites" &&
						activeTab !== "history" &&
						activeTab !== "downloads" && (
							<button
								onClick={() => setShowFavoritesOnly((v) => !v)}
								className={`h-8 w-8 flex items-center justify-center rounded-md ml-1 transition-colors focus-visible:outline-hidden 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>
						)}
					{activeTab !== "favorites" &&
						activeTab !== "history" &&
						activeTab !== "downloads" &&
						!isMobilePlatform() && (
							<button
								onClick={() => setShowDownloadsOnly((v) => !v)}
								className={`h-8 w-8 flex items-center justify-center rounded-md ml-1 transition-colors focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring ${
									showDownloadsOnly
										? "text-blue-400 bg-blue-400/10"
										: "text-muted-foreground hover:text-foreground hover:bg-accent"
								}`}
								aria-label={showDownloadsOnly ? "Show all" : "Show downloaded only"}
								aria-pressed={showDownloadsOnly}
							>
								<Download className="h-4 w-4" />
							</button>
						)}
				</div>
			</div>
 
			{/* Hierarchy navigation — replaces flat CategoryFilter */}
			{activeTab !== "favorites" &&
				activeTab !== "history" &&
				activeTab !== "downloads" &&
				hierarchy.loaded && (
					<div className={showChannelList ? "shrink-0" : "flex-1 overflow-y-auto"}>
						{navState.level === "home" && (
							<>
								<RecentlyPlayedRow
									contentType={contentType as "live" | "movie" | "series"}
									onPlay={handleHistoryPlay}
								/>
								<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 + channelCountFor(categories, g),
													0
												),
											};
										})}
										topLevelGroups={hierarchy.topLevelGroups.map((name) => ({
											name,
											channelCount: channelCountFor(categories, name),
										}))}
										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) =>
												!searchQuery ||
												g.toLowerCase().includes(searchQuery)
										)}
									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" &&
				activeTab !== "downloads" &&
				!isLiveSearch &&
				showChannelList && (
					<div className="shrink-0 px-3 pt-2 pb-1">
						<span className="text-xs text-muted-foreground">
							{formatCount(filtered.length, countNoun)}
						</span>
					</div>
				)}
 
			{/* Sticky time-axis header — only when channel list is visible */}
			{activeTab === "live" && showChannelList && !compactRows && (
				<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 whitespace-nowrap 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(now, 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 */}
			{showSeriesLoading && (
				<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-xs">
					<div className="flex items-center gap-3 bg-card rounded-2xl px-6 py-4 shadow-2xl">
						<LoaderCircle 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}
					seriesChannelId={seriesModalData.seriesChannelId}
					onClose={() => setSeriesModalData(null)}
					onPlay={(ch) => {
						navigate("/player", {
							state: {
								url: ch.url,
								channelName: ch.name,
								channel: ch,
								seriesEpisodes: sortEpisodes(seriesModalData.episodes),
							},
						});
					}}
				/>
			)}
 
			{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 === "downloads" ? (
				<div className="flex-1 overflow-auto scrollbar-hide">
					<DownloadsTab onPlay={handlePlay} onToggleFavorite={handleToggleFavorite} />
				</div>
			) : activeTab === "favorites" ? (
				<div className="flex-1 overflow-auto scrollbar-hide px-3 pb-3">
					{filtered.length === 0 && hasSearch ? (
						<NoSearchResults
							query={debouncedSearch}
							scope="favorites"
							onClear={() => setSearch("")}
						/>
					) : 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={rowVariant}
												onToggleFavorite={handleToggleFavorite}
												epgPrograms={getChannelPrograms(ch)}
												guidePending={isGuidePending(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 */}
								{!compactRows && (
									<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(now, windowStart, windowTotal).toFixed(3)}%`,
											}}
										/>
									</div>
								)}
								{filtered.slice(0, 80).map((ch) => (
									<ChannelCard
										key={ch.id}
										channel={ch}
										onPlay={handlePlay}
										variant={rowVariant}
										onToggleFavorite={handleToggleFavorite}
										epgPrograms={getChannelPrograms(ch)}
										guidePending={isGuidePending(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-hidden focus-visible:ring-1 focus-visible:ring-ring"
									>
										<ChannelLogo
											url={result.channelLogoUrl}
											className="h-8 w-8 rounded"
											fallback={
												<TvMinimal className="h-3.5 w-3.5 text-muted-foreground" />
											}
										/>
 
										<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, now)}
										</span>
									</button>
								))}
							</div>
						</>
					)}
 
					{filtered.length === 0 && epgSearchResults.length === 0 && (
						<NoSearchResults
							query={debouncedSearch}
							scope="channels or programmes"
							filtered={showFavoritesOnly}
							onClear={() => setSearch("")}
						/>
					)}
				</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 && hasSearch ? (
						<NoSearchResults
							query={debouncedSearch}
							scope={countLabel}
							filtered={showFavoritesOnly || effectiveCategory != null}
							onClear={() => setSearch("")}
						/>
					) : 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" && !compactRows && (
								<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(now, 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={rowVariant}
														onToggleFavorite={handleToggleFavorite}
														epgPrograms={getChannelPrograms(ch)}
														guidePending={isGuidePending(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>
	);
};