'use client'

import { useEffect, useMemo, useRef, useState } from 'react'
import Image from 'next/image'
import Link from 'next/link'
import Header from '@/components/Header'
import Sidebar from '@/components/Sidebar'
import BackToTop from '@/components/BackToTop'
import LiveCard, { LiveStream } from '@/components/LiveCard'
import { useTranslation } from 'react-i18next'
import { FiChevronLeft, FiChevronRight, FiChevronDown, FiSearch, FiX, FiPlay } from 'react-icons/fi'
import ExploreCategoryGridSkeleton from '@/components/Skeletons/ExploreCategoryGridSkeleton'
import PopularLiveGridSkeleton from '@/components/Skeletons/PopularLiveGridSkeleton'

type CategoryItem = {
    id: string
    name: string
    views: number
    thumb: string
    tags: string[]
    category: string
    createdAt: string
}

type NewStream = {
    id: string
    title: string
    views: number
    thumb: string
    startAt: string
    startTs: number
    allow?: string
    status?: 'adult'
    tags: string[]
    categoryLabel: string
    profile: string
    nickname: string
    type: 'live' | 'vod' | 'catch'
    link?: string
    thumbType?: '16_9'
}

const categoryData: CategoryItem[] = [
    {
        id: 'lol',
        name: '英雄聯盟',
        views: 51031,
        thumb: '',
        tags: ['MOBA', '策略', 'Riot Games'],
        category: 'all',
        createdAt: '2024-09-12',
    },
    {
        id: 'minecraft',
        name: '我的世界',
        views: 35291,
        thumb: '',
        tags: ['沙盒', '模擬', '生存'],
        category: 'new',
        createdAt: '2024-11-01',
    },
    {
        id: 'talkcam',
        name: '聊天/攝影',
        views: 32650,
        thumb: '',
        tags: ['紫色', '聊天'],
        category: '24h',
        createdAt: '2024-10-18',
    },
    {
        id: 'sc',
        name: '星際爭霸',
        views: 22062,
        thumb: '',
        tags: ['策略', '模擬', 'RTS'],
        category: 'all',
        createdAt: '2024-08-28',
    },
    {
        id: 'dokebi',
        name: '鬼怪',
        views: 10797,
        thumb: '',
        tags: ['劇情', '鬼怪', '一起看'],
        category: 'music',
        createdAt: '2025-01-05',
    },
]

// 新人區直播資料
const newStreams: NewStream[] = [
    {
        id: 'hubegung',
        title: '[홍엔터] 新成員合流！獎金對決 & 攻擊卡抽取',
        views: 931,
        thumb: '',
        startAt: '12-10 14:01',
        startTs: Date.parse('2024-12-10T14:01:00+09:00'),
        tags: ['聊天/攝影', '江南', 'Excel', '新人', '男/女', '洪娱乐'],
        categoryLabel: '聊天/攝影',
        profile: '',
        nickname: 'H_홍빠',
        type: 'live',
    },
]

const newCatchStreams: NewStream[] = [
    {
        id: 'catch-180304227',
        title: '있어?나쁘지 않아❤️❤️❤️',
        views: 477,
        thumb: '',
        startAt: '12-10 12:10',
        startTs: Date.parse('2024-12-10T12:10:00+09:00'),
        tags: ['catch'],
        categoryLabel: 'Catch',
        profile: '',
        nickname: '캐치1',
        type: 'catch',
        status: 'adult',
        link: '',
    },
]

// 新人區 VOD 資料
const newVodStreams: NewStream[] = [
    {
        id: 'vod-1',
        title: '[VOD] 昨晚的實況精華回顧',
        views: 1280,
        thumb: '',
        startAt: '12-09 23:10',
        startTs: Date.parse('2024-12-09T23:10:00+09:00'),
        tags: ['VOD', '精華', '重播'],
        categoryLabel: '精華剪輯',
        profile: '',
        nickname: '編輯者1',
        type: 'vod',
    },
]

// VTuber 區直播資料
const virtualStreams: NewStream[] = [
    {
        id: 'virtual-1',
        title: '[VTuber] 虛擬偶像日常聊天直播',
        views: 1523,
        thumb: '',
        startAt: '12-10 15:30',
        startTs: Date.parse('2024-12-10T15:30:00+09:00'),
        tags: ['VTuber', '聊天', '虛擬偶像'],
        categoryLabel: 'VTuber',
        profile: '',
        nickname: '虛擬偶像A',
        type: 'live',
    },
]

// VTuber 區 VOD 資料
const virtualVodStreams: NewStream[] = [
    {
        id: 'virtual-vod-1',
        title: '[VOD] VTuber 精華剪輯 - 搞笑時刻',
        views: 3456,
        thumb: '',
        startAt: '12-09 22:00',
        startTs: Date.parse('2024-12-09T22:00:00+09:00'),
        tags: ['VTuber', 'VOD', '精華'],
        categoryLabel: 'VTuber',
        profile: '',
        nickname: '虛擬偶像F',
        type: 'vod',
    },
]

// VTuber 區 Catch 資料
const virtualCatchStreams: NewStream[] = [
    {
        id: 'virtual-catch-1',
        title: ' VTuber 日常短影音',
        views: 892,
        thumb: '',
        startAt: '12-10 13:20',
        startTs: Date.parse('2024-12-10T13:20:00+09:00'),
        tags: ['VTuber', 'catch'],
        categoryLabel: 'VTuber',
        profile: '',
        nickname: '虛擬偶像I',
        type: 'catch',
        link: '',
    },
]

// 24小時區直播資料
const hour24Streams: NewStream[] = [
    {
        id: '24h-1',
        title: '[24小時] 深夜聊天室 - 與觀眾互動',
        views: 2156,
        thumb: '',
        startAt: '12-10 23:30',
        startTs: Date.parse('2024-12-10T23:30:00+09:00'),
        tags: ['24小時', '聊天', '互動'],
        categoryLabel: '24小時',
        profile: '',
        nickname: '深夜主播A',
        type: 'live',
    },
]

// 音樂區直播資料
const musicStreams: NewStream[] = [
    {
        id: 'music-1',
        title: '[音樂] 原創歌曲首播 - 新專輯發布',
        views: 3421,
        thumb: '',
        startAt: '12-10 20:00',
        startTs: Date.parse('2024-12-10T20:00:00+09:00'),
        tags: ['音樂', '原創', '新專輯'],
        categoryLabel: '音樂',
        profile: '',
        nickname: '音樂人A',
        type: 'live',
    },
]

// 音樂區 VOD 資料
const musicVodStreams: NewStream[] = [
    {
        id: 'music-vod-1',
        title: '[VOD] 音樂會完整重播 - 演唱會精華',
        views: 4567,
        thumb: '',
        startAt: '12-09 21:00',
        startTs: Date.parse('2024-12-09T21:00:00+09:00'),
        tags: ['音樂', 'VOD', '演唱會'],
        categoryLabel: '音樂',
        profile: '',
        nickname: '音樂人F',
        type: 'vod',
    },
]

// 音樂區 Catch 資料
const musicCatchStreams: NewStream[] = [
    {
        id: 'music-catch-1',
        title: ' 音樂短影音 - 30秒精華',
        views: 1234,
        thumb: '',
        startAt: '12-10 15:30',
        startTs: Date.parse('2024-12-10T15:30:00+09:00'),
        tags: ['音樂', 'catch'],
        categoryLabel: '音樂',
        profile: '',
        nickname: '音樂人I',
        type: 'catch',
        link: '',
    },
]

export default function ExploreCategoryPage({ params }: { params: { category: string; sub?: string } }) {
    const { t } = useTranslation()
    const categories = [
        { key: 'all', label: t('explore.tabs.type') },
        { key: 'new', label: t('explore.tabs.new') },
        { key: 'virtual', label: t('explore.tabs.virtual') },
        { key: '24h', label: t('explore.tabs.24h') },
        { key: 'music', label: t('explore.tabs.music') },
    ]

    const newSubTabs: Array<{ key: 'live' | 'vod' | 'catch'; label: string }> = [
        { key: 'live', label: t('explore.live') },
        { key: 'vod', label: t('explore.vod') },
        { key: 'catch', label: t('explore.catch') },
    ]

    const hour24SubTabs: Array<{ key: 'live'; label: string }> = [
        { key: 'live', label: t('explore.live') },
    ]

    const initialCat = (params?.category || 'all').toLowerCase()
    const initialSub = (params?.sub || '').toLowerCase()
    const [sidebarOpen, setSidebarOpen] = useState(false)
    const [activeCat, setActiveCat] = useState(
        categories.find((c) => c.key === initialCat) ? initialCat : 'all'
    )
    const [visibleCount, setVisibleCount] = useState(12)
    const [sortOpen, setSortOpen] = useState(false)
    const [sortKey, setSortKey] = useState<'popular' | 'recent'>('popular')
    const [searchExpanded, setSearchExpanded] = useState(false)
    const [searchQuery, setSearchQuery] = useState('')
    const [subTab, setSubTab] = useState<'live' | 'vod' | 'catch'>(
        (initialCat === 'new' || initialCat === 'virtual' || initialCat === '24h' || initialCat === 'music') && ['live', 'vod', 'catch'].includes(initialSub as any)
            ? (initialSub as 'live' | 'vod' | 'catch')
            : 'live'
    )
    const [isLoading, setIsLoading] = useState(true)
    const scrollRef = useRef<HTMLDivElement>(null)
    const [canScrollPrev, setCanScrollPrev] = useState(false)
    const [canScrollNext, setCanScrollNext] = useState(false)
    const sortRef = useRef<HTMLDivElement>(null)

    const filtered = useMemo(() => {
        const base =
            activeCat === 'all'
                ? categoryData
                : categoryData.filter((item) => item.category === activeCat)
        const searched = searchQuery
            ? base.filter(
                (item) =>
                    item.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
                    item.tags.some((t) => t.toLowerCase().includes(searchQuery.toLowerCase()))
            )
            : base
        const copied = [...searched]
        if (sortKey === 'popular') {
            copied.sort((a, b) => b.views - a.views)
        } else {
            copied.sort(
                (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
            )
        }
        return copied
    }, [activeCat, sortKey, searchQuery])

    const visibleList = filtered.slice(0, visibleCount)

    const filteredNewStreams = useMemo(() => {
        let list: NewStream[] = []
        if (activeCat === 'virtual') {
            if (subTab === 'vod') {
                list = virtualVodStreams
            } else if (subTab === 'catch') {
                list = virtualCatchStreams
            } else {
                list = virtualStreams
            }
        } else if (activeCat === '24h') {
            // 24h 只有直播
            list = hour24Streams
        } else if (activeCat === 'music') {
            // music 有直播、VOD、Catch
            if (subTab === 'vod') {
                list = musicVodStreams
            } else if (subTab === 'catch') {
                list = musicCatchStreams
            } else {
                list = musicStreams
            }
        } else {
            // activeCat === 'new'
            if (subTab === 'vod') {
                list = newVodStreams
            } else if (subTab === 'catch') {
                list = newCatchStreams
            } else {
                list = newStreams
            }
        }

        const searched = searchQuery
            ? list.filter(
                (item) =>
                    item.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
                    item.tags.some((t) => t.toLowerCase().includes(searchQuery.toLowerCase()))
            )
            : list
        const copied = [...searched]
        if (sortKey === 'popular') {
            copied.sort((a, b) => b.views - a.views)
        } else {
            copied.sort((a, b) => b.startTs - a.startTs)
        }
        return copied
    }, [activeCat, subTab, sortKey, searchQuery])

    const updateScrollState = () => {
        const el = scrollRef.current
        if (!el) return
        setCanScrollPrev(el.scrollLeft > 4)
        setCanScrollNext(el.scrollLeft + el.clientWidth < el.scrollWidth - 4)
    }

    useEffect(() => {
        const el = scrollRef.current
        if (!el) return
        const saved =
            typeof window !== 'undefined'
                ? Number(sessionStorage.getItem('explore-cat-scroll') || '0')
                : 0
        if (!Number.isNaN(saved)) el.scrollLeft = saved
        updateScrollState()
        const onScroll = () => {
            updateScrollState()
            sessionStorage.setItem('explore-cat-scroll', String(el.scrollLeft))
        }
        el.addEventListener('scroll', onScroll, { passive: true })
        const resize = () => updateScrollState()
        window.addEventListener('resize', resize)
        return () => {
            el.removeEventListener('scroll', onScroll)
            window.removeEventListener('resize', resize)
        }
    }, [])

    useEffect(() => {
        const handleClickOutside = (e: MouseEvent) => {
            if (sortRef.current && !sortRef.current.contains(e.target as Node)) {
                setSortOpen(false)
            }
        }
        document.addEventListener('mousedown', handleClickOutside)
        return () => document.removeEventListener('mousedown', handleClickOutside)
    }, [])

    useEffect(() => {
        updateScrollState()
    }, [activeCat])

    const scrollBy = (dir: 'prev' | 'next') => {
        const el = scrollRef.current
        if (!el) return
        const delta = dir === 'prev' ? -240 : 240
        el.scrollBy({ left: delta, behavior: 'smooth' })
    }

    useEffect(() => {
        const timer = setTimeout(() => setIsLoading(false), 800)
        return () => clearTimeout(timer)
    }, [])

    useEffect(() => {
        if (typeof window === 'undefined') return
        if (activeCat === 'new' || activeCat === 'virtual' || activeCat === '24h' || activeCat === 'music') {
            const path = `/explore/${activeCat}/${subTab}`
            if (window.location.pathname !== path) {
                window.history.replaceState({}, '', path)
            }
        } else {
            // 如果不是 new、virtual、24h 或 music，重置 URL 到主 category
            const path = `/explore/${activeCat}`
            if (window.location.pathname !== path && !window.location.pathname.startsWith(`/explore/${activeCat}/`)) {
                window.history.replaceState({}, '', path)
            }
        }
    }, [activeCat, subTab])

    useEffect(() => {
        if (activeCat !== 'new' && activeCat !== 'virtual' && activeCat !== '24h' && activeCat !== 'music') {
            setSubTab('live')
        } else if (activeCat === '24h') {
            setSubTab('live')
        }
    }, [activeCat])

    const isCatchTab = subTab === 'catch'
    const isListLayout = activeCat === 'new' || activeCat === 'virtual' || activeCat === '24h' || activeCat === 'music'

    const renderCatchList = (list: NewStream[]) => (
        <div className="grid gap-4 md:gap-5 grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-8 mt-4">
            {list.map((item, idx) => {
                const catchId = item.id.replace(/^catch-|^virtual-catch-|^music-catch-/, '')
                return (
                    <Link
                        key={`${item.id}-${idx}`}
                        href={`/catch/${catchId}`}
                        className="group relative flex flex-col"
                        title={item.title}
                    >
                        <div className="relative w-full h-[255px] overflow-hidden rounded-xl bg-gray-200 dark:bg-[#1f2024]">
                            <Image
                                src={item.thumb}
                                alt={item.title}
                                fill
                                className="transition-transform duration-200 group-hover:scale-[1.02]"
                                unoptimized
                            />
                            <div className="absolute inset-0 scale-110">
                                <Image
                                    src={item.thumb}
                                    alt={item.title}
                                    fill
                                    className="pointer-events-none"
                                    unoptimized
                                />
                            </div>
                            {item.status === 'adult' && (
                                <span className="absolute top-2 left-2 px-2 py-1 rounded-full text-[11px] font-semibold bg-black/70 text-white">
                                    {t('explore.ageRestricted')}
                                </span>
                            )}
                        </div>
                        <div className="mt-2 flex items-start gap-2">
                            <div className="flex-1 min-w-0">
                                <p className="text-[14px] leading-5 text-black dark:text-gray-100 line-clamp-2">
                                    {item.title}
                                </p>
                                <p className="mt-1 text-xs text-gray-500 dark:text-gray-400 flex items-center gap-1">
                                    <FiPlay className="w-3 h-3" />
                                    {item.views.toLocaleString()}
                                </p>
                            </div>
                            <button
                                type="button"
                                className="shrink-0 w-8 h-8 flex items-center justify-center rounded-md hover:bg-gray-100 dark:hover:bg-[#2b2d31] text-gray-500 dark:text-gray-400"
                                aria-label={t('explore.moreOptions')}
                            >
                                ⋮
                            </button>
                        </div>
                    </Link>
                )
            })}
        </div>
    )

    const renderCatchSkeleton = (count = 8) => (
        <div className="grid gap-4 md:gap-5 grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-8 mt-4">
            {Array.from({ length: count }).map((_, idx) => (
                <div key={idx} className="animate-pulse">
                    <div className="w-full h-[255px] bg-gray-200 dark:bg-[#1f2024] rounded-xl" />
                    <div className="mt-2 h-4 bg-gray-200 dark:bg-[#1f2024] rounded" />
                    <div className="mt-2 h-3 w-16 bg-gray-200 dark:bg-[#1f2024] rounded" />
                </div>
            ))}
        </div>
    )

    return (
        <>
            <Header onMenuClick={() => setSidebarOpen(!sidebarOpen)} />
            <div className="min-h-screen min-w-[375px] bg-white dark:bg-[#0c0d0e] flex overflow-x-auto md:overflow-x-hidden transition-colors">
                <Sidebar isOpen={sidebarOpen} onClose={() => setSidebarOpen(false)} />
                <main
                    className="main-content flex-1 lg:ml-64 pt-[6rem] md:pt-[6rem] min-h-screen w-full max-w-full overflow-x-hidden transition-all"
                    data-compact-open={sidebarOpen ? 'true' : 'false'}
                >
                    <div className="w-full max-w-full mx-auto px-5 py-5">
                        <div className="z-30 bg-white/90 dark:bg-transparent">
                            <div className="overflow-hidden">
                                <div
                                    ref={scrollRef}
                                    className="flex items-center gap-2 overflow-x-auto hide-scrollbar scroll-smooth"
                                >
                                    {categories.map((cat) => (
                                        <button
                                            key={cat.key}
                                            type="button"
                                            onClick={() => {
                                                setActiveCat(cat.key)
                                                if (typeof window !== 'undefined') {
                                                    if (cat.key === 'new' || cat.key === 'virtual' || cat.key === '24h' || cat.key === 'music') {
                                                        window.history.replaceState({}, '', `/explore/${cat.key}/${subTab}`)
                                                    } else {
                                                        window.history.replaceState({}, '', `/explore/${cat.key}`)
                                                    }
                                                }
                                            }}
                                            className={`flex items-center h-9 px-4 rounded-full text-sm border transition-all whitespace-nowrap ${activeCat === cat.key
                                                ? 'bg-[#17191C] text-white border-[#17191C] dark:bg-white dark:text-[#0c0d0e] dark:border-white'
                                                : 'bg-white dark:bg-[#0c0d0e] border-gray-200 dark:border-[#464A53] text-gray-600 dark:text-[#D5D7DC] hover:bg-gray-50 dark:hover:bg-[#2f3137]'
                                                }`}
                                        >
                                            {cat.label}
                                        </button>
                                    ))}
                                </div>
                            </div>
                            <div className="pointer-events-none absolute inset-y-0 left-0 w-8 bg-gradient-to-r from-white dark:from-[#0c0d0e] to-transparent" />
                            <div className="pointer-events-none absolute inset-y-0 right-0 w-8 bg-gradient-to-l from-white dark:from-[#0c0d0e] to-transparent" />
                            <button
                                type="button"
                                onClick={() => scrollBy('prev')}
                                className={`absolute left-0 top-1/2 -translate-y-1/2 w-9 h-9 rounded-full border border-gray-200 dark:border-[#464A53] bg-white dark:bg-[#0c0d0e] shadow-sm flex items-center justify-center transition-opacity ${canScrollPrev ? 'opacity-100 pointer-events-auto' : 'opacity-0 pointer-events-none'
                                    }`}
                                aria-label={t('explore.prevCategory')}
                            >
                                <FiChevronLeft className="w-5 h-5 text-black dark:text-gray-200" />
                            </button>
                            <button
                                type="button"
                                onClick={() => scrollBy('next')}
                                className={`absolute right-0 top-1/2 -translate-y-1/2 w-9 h-9 rounded-full border border-gray-200 dark:border-[#464A53] bg-white dark:bg-[#0c0d0e] shadow-sm flex items-center justify-center transition-opacity ${canScrollNext ? 'opacity-100 pointer-events-auto' : 'opacity-0 pointer-events-none'
                                    }`}
                                aria-label={t('explore.nextCategory')}
                            >
                                <FiChevronRight className="w-5 h-5 text-black dark:text-gray-200" />
                            </button>
                        </div>

                        {activeCat === 'all' && (
                            <div className="flex items-center flex-wrap gap-3 mt-4 title_wrap">
                                <h2 className="text-xl font-semibold text-black dark:text-gray-100">
                                    {t('explore.categorySearchTitle')}
                                </h2>
                                <div
                                    className={`searh_box relative flex items-center bg-white dark:bg-[#0c0d0e] rounded-full px-1 py-1 ${searchExpanded ? 'expanded' : ''
                                        }`}
                                >
                                    <button
                                        type="button"
                                        className="btn_expand relative w-9 h-9 flex items-center justify-center"
                                        onClick={() => setSearchExpanded((prev) => !prev)}
                                    >
                                        <span className="w-full h-full flex items-center justify-center">
                                            <FiSearch className="w-5 h-5 text-black dark:text-gray-300" />
                                        </span>
                                    </button>
                                    <div
                                        className={`search_from flex items-center bg-gray-100 dark:bg-[#232529] rounded-full transition-all ${searchExpanded ? 'w-60 px-2' : 'w-0 px-0'
                                            } overflow-hidden`}
                                    >
                                        <input
                                            type="text"
                                            className="search_inp w-full h-9 bg-transparent border-0 text-black dark:text-gray-100 px-2 text-sm focus:outline-none"
                                            placeholder={t('explore.placeholder')}
                                            value={searchQuery}
                                            onChange={(e) => setSearchQuery(e.target.value)}
                                        />
                                        {searchQuery && (
                                            <button
                                                type="button"
                                                className="del_text w-6 h-6 flex items-center justify-center text-gray-500"
                                                onClick={() => setSearchQuery('')}
                                            >
                                                <FiX className="w-4 h-4" />
                                            </button>
                                        )}
                                    </div>
                                </div>

                                <div className="right_area ml-auto relative" ref={sortRef}>
                                    <div className={`select_box_item ${sortOpen ? 'on' : ''}`}>
                                        <button
                                            type="button"
                                            className="selected flex items-center h-8 px-3 rounded-full text-sm text-black dark:text-gray-300 border border-transparent hover:bg-gray-50 dark:hover:bg-[#1f2024]"
                                            onClick={() => setSortOpen((prev) => !prev)}
                                        >
                                            {sortKey === 'popular' ? t('categoryGrid.popular') : t('categoryGrid.recent')}
                                            <FiChevronDown className={`w-4 h-4 ml-1 transition-transform ${sortOpen ? 'rotate-180' : ''}`} />
                                        </button>
                                        <ul
                                            className={`select_list absolute right-0 mt-1 w-44 rounded-lg border border-gray-200 dark:border-[#464A53] bg-white dark:bg-[#0c0d0e] shadow-lg overflow-hidden z-20 transition-all ${sortOpen ? 'opacity-100 visible' : 'opacity-0 invisible'
                                                }`}
                                        >
                                            <li className={sortKey === 'popular' ? 'on' : ''}>
                                                <button
                                                    type="button"
                                                    className="w-full text-left px-3 py-2 text-sm hover:bg-gray-50 dark:hover:bg-[#1f2024]"
                                                    onClick={() => {
                                                        setSortKey('popular')
                                                        setSortOpen(false)
                                                    }}
                                                >
                                                    {t('categoryGrid.popular')}
                                                </button>
                                            </li>
                                            <li className={sortKey === 'recent' ? 'on' : ''}>
                                                <button
                                                    type="button"
                                                    className="w-full text-left px-3 py-2 text-sm hover:bg-gray-50 dark:hover:bg-[#1f2024]"
                                                    onClick={() => {
                                                        setSortKey('recent')
                                                        setSortOpen(false)
                                                    }}
                                                >
                                                    {t('categoryGrid.recent')}
                                                </button>
                                            </li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        )}

                        {isListLayout ? (
                            <div className="mt-6">
                                <div className="flex items-center justify-between border-b border-gray-200 dark:border-[#2F3137]">
                                    <div className="flex items-center">
                                        {(activeCat === '24h' ? hour24SubTabs : newSubTabs).map((tab) => (
                                            <button
                                                key={tab.key}
                                                type="button"
                                                onClick={() => {
                                                    setSubTab(tab.key)
                                                    if (typeof window !== 'undefined' && (activeCat === 'new' || activeCat === 'virtual' || activeCat === '24h' || activeCat === 'music')) {
                                                        window.history.replaceState({}, '', `/explore/${activeCat}/${tab.key}`)
                                                    }
                                                }}
                                                className={`px-4 py-2 text-sm font-medium transition-colors ${subTab === tab.key
                                                    ? 'text-primary-600 dark:text-primary-400 border-b-2 border-primary-600 dark:border-primary-400'
                                                    : 'text-gray-500 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200'
                                                    }`}
                                            >
                                                {tab.label}
                                            </button>
                                        ))}
                                    </div>
                                    <div className="relative" ref={sortRef}>
                                        <button
                                            type="button"
                                            className="flex items-center gap-2 px-3 py-2 text-sm text-black dark:text-gray-200 transition-colors"
                                            onClick={() => setSortOpen((prev) => !prev)}
                                        >
                                            {sortKey === 'popular'
                                                ? t('categoryGrid.viewerDesc')
                                                : sortKey === 'recent'
                                                    ? t('categoryGrid.recent')
                                                    : t('categoryGrid.viewerAsc')}
                                            <FiChevronDown className={`w-4 h-4 ml-1 transition-transform ${sortOpen ? 'rotate-180' : ''}`} />
                                        </button>
                                        {sortOpen && (
                                            <ul className="absolute right-0 mt-1 w-44 rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-[#0c0d0e] shadow-lg text-sm text-black dark:text-gray-200 overflow-hidden z-20">
                                                <li>
                                                    <button
                                                        type="button"
                                                        className={`w-full text-left px-3 py-2 hover:bg-gray-50 dark:hover:bg-[#1a1c21] ${sortKey === 'popular' ? 'font-semibold text-primary-600 dark:text-primary-400' : ''}`}
                                                        onClick={() => {
                                                            setSortKey('popular')
                                                            setSortOpen(false)
                                                        }}
                                                    >
                                                        {t('categoryGrid.viewerDesc')}
                                                    </button>
                                                </li>
                                                <li>
                                                    <button
                                                        type="button"
                                                        className={`w-full text-left px-3 py-2 hover:bg-gray-50 dark:hover:bg-[#1a1c21] ${sortKey === 'recent' ? 'font-semibold text-primary-600 dark:text-primary-400' : ''}`}
                                                        onClick={() => {
                                                            setSortKey('recent')
                                                            setSortOpen(false)
                                                        }}
                                                    >
                                                        {t('categoryGrid.viewerAsc')}
                                                    </button>
                                                </li>
                                            </ul>
                                        )}
                                    </div>
                                </div>

                                {isLoading ? (
                                    isCatchTab ? (
                                        renderCatchSkeleton()
                                    ) : (
                                        <PopularLiveGridSkeleton count={visibleCount} />
                                    )
                                ) : isCatchTab ? (
                                    renderCatchList(filteredNewStreams)
                                ) : (
                                    <div className="grid-popular mt-4">
                                        {filteredNewStreams.map((item, idx) => {
                                            const stream: LiveStream = {
                                                id: `${item.id}-${idx}`,
                                                title: item.title,
                                                streamerName: item.nickname,
                                                category: item.categoryLabel,
                                                viewerCount: item.views,
                                                thumbnail: item.thumb,
                                                avatar: item.profile,
                                                tags: item.tags,
                                                startTime: item.startAt,
                                            }
                                            const badgeLabel = subTab === 'vod' ? t('explore.vod') : undefined
                                            return <LiveCard key={stream.id} stream={stream} t={t} badgeLabel={badgeLabel} />
                                        })}
                                    </div>
                                )}

                                {filteredNewStreams.length === 0 && (
                                    <div className="noList mt-6 text-center text-sm text-gray-500 dark:text-gray-400">
                                        {t('explore.noData')}
                                    </div>
                                )}
                                {!isLoading && filteredNewStreams.length > 0 && filteredNewStreams.length >= visibleCount && (
                                    <div className="show_more mt-6 flex items-center justify-center">
                                        <button
                                            type="button"
                                            className="flex items-center gap-2 px-4 py-2 rounded-md text-sm text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
                                            onClick={() =>
                                                setVisibleCount((prev) => Math.min(prev + 12, filteredNewStreams.length))
                                            }
                                        >
                                            {t('explore.showMore')}
                                        </button>
                                    </div>
                                )}
                            </div>
                        ) : (
                            <>
                                {isLoading ? (
                                    <ExploreCategoryGridSkeleton count={visibleCount} />
                                ) : (
                                    <>
                                        <div className="category_conts mt-4">
                                            <ul className="grid gap-5 grid-cols-2 sm:grid-cols-3 md:grid-cols-4 xl:grid-cols-6 2xl:grid-cols-7">
                                                {visibleList.map((item) => (
                                                    <li key={item.id} className="group">
                                                        <Link href="#" className="block relative">
                                                            <span className="views flex items-center absolute top-2 left-2 bg-black/70 rounded-full px-2 py-1 text-[11px] text-white z-10">
                                                                <span className="w-1.5 h-1.5 bg-red-500 rounded-full mr-1"></span>
                                                                <span className="font-semibold">{item.views.toLocaleString()}</span>
                                                            </span>
                                                            <div className="thumb relative overflow-hidden rounded-2xl aspect-[3/4] bg-gray-100 dark:bg-[#232529]">
                                                                <Image
                                                                    src={item.thumb}
                                                                    alt={item.name}
                                                                    fill
                                                                    className="transition-all duration-200 group-hover:p-1.5 group-hover:border-2 group-hover:border-[#0182ff] rounded-2xl"
                                                                    sizes="(min-width: 1280px) 180px, (min-width: 768px) 160px, 50vw"
                                                                />
                                                            </div>
                                                            <div className="info_wrap mt-2">
                                                                <p className="title text-[15px] md:text-[16px] font-semibold leading-5 text-black dark:text-gray-100 line-clamp-2">
                                                                    {item.name}
                                                                </p>
                                                            </div>
                                                        </Link>
                                                        <div className="tag_wrap flex flex-wrap gap-2 mt-2 overflow-visible h-auto">
                                                            {item.tags.map((tag) => (
                                                                <Link
                                                                    key={tag}
                                                                    href="#"
                                                                    className="flex items-center px-2 py-1 rounded-full bg-gray-100 dark:bg-[#232529] text-[12px] text-gray-600 dark:text-gray-300"
                                                                >
                                                                    {tag}
                                                                </Link>
                                                            ))}
                                                        </div>
                                                    </li>
                                                ))}
                                            </ul>
                                        </div>

                                        {visibleCount < filtered.length && (
                                            <div className="show_more mt-6 flex items-center justify-center">
                                                <button
                                                    type="button"
                                                    className="flex items-center gap-2 px-4 py-2 rounded-md text-sm text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
                                                    onClick={() => setVisibleCount((prev) => Math.min(prev + 12, filtered.length))}
                                                >
                                                    {t('explore.showMore')}
                                                </button>
                                            </div>
                                        )}
                                    </>
                                )}

                                {isLoading && (
                                    <div className="show_more mt-6 flex items-center justify-center">
                                        <div className="flex items-center gap-2 px-4 py-2 rounded-md text-sm text-gray-400 dark:text-gray-500">
                                            {t('explore.loading')}
                                        </div>
                                    </div>
                                )}
                            </>
                        )}
                    </div>
                </main>
            </div>
            <BackToTop />
        </>
    )
}


