﻿'use client'

import { useEffect, useRef, useState } from 'react'
import Link from 'next/link'
import { Swiper, SwiperSlide } from 'swiper/react'
import { FreeMode, Thumbs, EffectFade, Navigation } from 'swiper/modules'
import type { Swiper as SwiperType } from 'swiper'
import Image from 'next/image'
import { FiChevronLeft, FiChevronRight } from 'react-icons/fi'
import { FaPlay, FaUser } from 'react-icons/fa'
import LiveBannerSkeleton from './Skeletons/LiveBannerSkeleton'
import StreamCover from './StreamCover'
import StreamSnapshotCover from './StreamSnapshotCover'
import { useTranslation } from 'react-i18next'

import 'swiper/css'
import 'swiper/css/free-mode'
import 'swiper/css/thumbs'
import 'swiper/css/effect-fade'
import 'swiper/css/navigation'

type LiveStreamBanner = {
    roomId: string
    userId: string
    title: string
    viewers: number
    thumbnail: string | null
    src: string | null
    isLive: boolean
    streamerName: string
    avatar: string | null
    category: string | null
}

interface LiveBannerProps {
    initialStreams?: LiveStreamBanner[]
}

export default function LiveBanner({ initialStreams = [] }: LiveBannerProps) {
    const [thumbsSwiper, setThumbsSwiper] = useState<SwiperType | null>(null)
    const mainSwiperRef = useRef<SwiperType | null>(null)
    const [isCompact, setIsCompact] = useState(false)
    const [isLoading, setIsLoading] = useState(false)
    const [currentIndex, setCurrentIndex] = useState(0)
    const { t } = useTranslation()

    const liveStreams = initialStreams

    const slideKey = (stream: LiveStreamBanner, index: number, prefix: string) =>
        `${prefix}-${index}-${stream.roomId || stream.userId || 'stream'}`

    const coverAlt = (stream: LiveStreamBanner) =>
        stream.title?.trim() || stream.streamerName?.trim() || t('liveBanner.placeholder')

    const avatarAlt = (stream: LiveStreamBanner) =>
        stream.streamerName?.trim() || t('liveBanner.placeholder')

    useEffect(() => {
        const mq = window.matchMedia('(max-width: 1199px)')
        const handler = (e: MediaQueryListEvent | MediaQueryList) => setIsCompact(e.matches)
        handler(mq)
        mq.addEventListener('change', handler)
        return () => mq.removeEventListener('change', handler)
    }, [])

    useEffect(() => {
        const swiper = mainSwiperRef.current
        if (!swiper || swiper.destroyed) return

        swiper.allowTouchMove = isCompact
        if (swiper.params) {
            swiper.params.simulateTouch = isCompact
        }

        if (isCompact && swiper.navigation) {
            swiper.navigation.init()
            swiper.navigation.update()
        }

        swiper.update()
    }, [isCompact])

    if (liveStreams.length === 0) {
        return null
    }

    if (isLoading) {
        return <LiveBannerSkeleton />
    }

    return (
        <section className="relative w-full h-[320px] md:h-[350px] mb-6 md:mb-8 overflow-hidden z-0 px-5">
            <div className="relative overflow-clip bg-[#181818] w-full h-full mx-auto rounded-[80px_20px] md:rounded-[80px_20px]">
                {/* ?????*/}
                <Swiper
                    modules={[FreeMode, Thumbs, EffectFade, Navigation]}
                    spaceBetween={0}
                    slidesPerView={1}
                    effect="fade"
                    fadeEffect={{
                        crossFade: true
                    }}
                    speed={500}
                    allowTouchMove={isCompact}
                    simulateTouch={isCompact}
                    navigation={
                        isCompact
                            ? {
                                nextEl: '.banner-next',
                                prevEl: '.banner-prev'
                            }
                            : false
                    }
                    thumbs={
                        !isCompact
                            ? { swiper: thumbsSwiper && !thumbsSwiper.destroyed ? thumbsSwiper : null }
                            : undefined
                    }
                    onSwiper={(swiper) => {
                        mainSwiperRef.current = swiper
                    }}
                    onSlideChange={(swiper) => {
                        setCurrentIndex(swiper.activeIndex)
                    }}
                    className="player-view h-full swiper-fade"
                >
                    {liveStreams.map((stream, index) => (
                        <SwiperSlide key={slideKey(stream, index, 'main')}>
                            <div
                                className="block relative w-full h-full"
                            >
                                {/* ?嗆?????????*/}
                                <div className={`absolute top-0 bottom-0 left-0 w-full pr-0 ${isCompact ? '' : 'lg:pr-[340px]'} flex justify-end`}>
                                    <div className={`relative overflow-hidden w-full ${isCompact ? '' : 'lg:w-[907px]'}`}>
                                        {/* ????獢? */}
                                        <div className="pointer-events-none absolute top-0 bottom-0 left-0 bg-gradient-to-r from-[#17191C] via-[#17191C]/0 to-transparent w-[191px] z-[5] hidden lg:block" />
                                        <div className="pointer-events-none absolute top-0 bottom-0 right-0 bg-gradient-to-l from-[#17191C] via-[#17191C]/0 to-transparent w-[191px] z-[5] hidden lg:block" />

                                        {/* ?嗆???????*/}
                                        <Link
                                            href={`/room/${stream.roomId || stream.userId}`}
                                            className="absolute top-1/2 block w-full aspect-video -translate-y-1/2 cursor-pointer"
                                        >
                                            <div className="relative w-full h-full bg-gray-800 rounded-lg overflow-hidden">
                                                <StreamCover
                                                    key={stream.roomId}
                                                    thumbnail={stream.thumbnail}
                                                    src={stream.src}
                                                    isLive={stream.isLive}
                                                    enablePlayback={
                                                        stream.roomId ===
                                                        liveStreams[currentIndex]?.roomId
                                                    }
                                                    alt={coverAlt(stream)}
                                                    placeholder={
                                                        <div className="absolute inset-0 flex items-center justify-center">
                                                            <span className="text-gray-500">
                                                                {t('liveBanner.placeholder')}
                                                            </span>
                                                        </div>
                                                    }
                                                />
                                            </div>
                                        </Link>
                                    </div>
                                </div>

                                {/* 主播資訊（不可點擊） */}
                                <div
                                    className={`pointer-events-none absolute z-10 transition-all duration-200 ${isCompact
                                        ? 'top-[28px] left-[60px]'
                                        : 'top-0 md:top-[28px] left-[20px] md:left-[60px]'
                                        }`}
                                >
                                    <div className="flex items-start">
                                        {/* ??? */}
                                        <div className="relative w-[50px] h-[50px] md:w-[54px] md:h-[54px] lg:w-16 lg:h-16 mr-3 md:mr-4 flex-shrink-0">
                                            {String(stream.avatar ?? '').trim() ? (
                                                <div className="relative h-full w-full">
                                                    <div className="pointer-events-none absolute inset-0 left-1/2 top-1/2 h-[58px] w-[58px] -translate-x-1/2 -translate-y-1/2 md:h-[62px] md:w-[62px] lg:h-[74px] lg:w-[74px]">
                                                        <div className="h-full w-full rounded-full bg-gradient-to-tr from-[#0082FF] via-[#0A96FF] via-40% via-[#05BCFF] via-56% via-[#00F0FF] via-76% via-[#24F4E8] via-89% via-[#82FFB0] to-[#82FFB0] p-[2px]">
                                                            <div className="h-full w-full rounded-full bg-transparent" />
                                                        </div>
                                                    </div>
                                                    <Image
                                                        src={stream.avatar!}
                                                        alt={avatarAlt(stream)}
                                                        width={64}
                                                        height={64}
                                                        className="relative w-full h-full rounded-full object-cover z-[5] pointer-events-none"
                                                        unoptimized
                                                    />
                                                </div>
                                            ) : (
                                                <div className="relative z-[5] flex h-full w-full items-center justify-center rounded-full bg-[#3a3d42]">
                                                    <FaUser className="h-5 w-5 text-[#9ca3af] md:h-6 md:w-6" aria-hidden />
                                                </div>
                                            )}
                                        </div>

                                        {/* ?? */}
                                        <div className="flex-1 min-w-0">
                                            <div className="flex items-center mb-1">
                                                <p className="text-white text-sm font-medium drop-shadow-[0_1px_3px_rgba(0,0,0,0.8)]">
                                                    {stream.streamerName}
                                                </p>
                                                <div className="flex items-center ml-4 md:ml-6 text-[#FF0051] text-sm">
                                                    <span className="w-1 h-1 bg-[#FF0051] rounded-full mr-1.5" />
                                                    {t('liveBanner.viewers', { count: stream.viewers })}
                                                </div>
                                            </div>
                                            <p className="text-white text-base md:text-xl lg:text-[26px] xl:text-[28px] font-semibold leading-tight mb-2 drop-shadow-[0_1px_3px_rgba(0,0,0,0.8)] line-clamp-2 max-w-[300px] md:max-w-[400px] lg:max-w-[460px]">
                                                {stream.title}
                                            </p>
                                            <span className="inline-flex items-center justify-center bg-[rgba(68,68,68,0.9)] px-2 h-5 rounded-full text-[#D5D7DC] text-xs">
                                                {stream.category || t('liveBanner.placeholder')}
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </SwiperSlide>
                    ))}
                </Swiper>

                {/* ??????????*/}
                {isCompact && (
                    <>
                        <button
                            type="button"
                            className="banner-prev absolute left-1 top-1/2 -translate-y-1/2 z-20 flex items-center justify-center text-white drop-shadow-[0_2px_4px_rgba(0,0,0,0.6)] w-14 h-14"
                            style={{ width: '56px', height: '56px' }}
                            aria-label={t('liveBanner.prev')}
                        >
                            <FiChevronLeft className="w-7 h-7" />
                        </button>
                        <button
                            type="button"
                            className="banner-next absolute right-1 top-1/2 -translate-y-1/2 z-20 flex items-center justify-center text-white drop-shadow-[0_2px_4px_rgba(0,0,0,0.6)] w-14 h-14"
                            style={{ width: '56px', height: '56px' }}
                            aria-label={t('liveBanner.next')}
                        >
                            <FiChevronRight className="w-7 h-7" />
                        </button>
                    </>
                )}

                {/* ??魂?謅????嚗孵??*/}
                <div
                    className={`absolute top-[31px] right-[30px] z-[15] w-[260px] ${
                        isCompact ? 'hidden' : 'hidden lg:block'
                    }`}
                >
                        <Swiper
                            modules={[FreeMode, Thumbs]}
                            onSwiper={setThumbsSwiper}
                            spaceBetween={2}
                            slidesPerView="auto"
                            freeMode={true}
                            watchSlidesProgress={true}
                            direction="vertical"
                            className="player-thumb-list h-[calc(100%-62px)]"
                        >
                            {liveStreams.map((stream, index) => (
                                <SwiperSlide
                                    key={slideKey(stream, index, 'thumb')}
                                    className="!h-auto relative overflow-hidden rounded-[14px] p-1.5 transition-all duration-200 hover:bg-white/10"
                                >
                                    <button
                                        type="button"
                                        className="flex w-full items-center text-left cursor-pointer"
                                        onClick={() => {
                                            mainSwiperRef.current?.slideTo(index)
                                        }}
                                    >
                                        <div className="relative overflow-hidden w-[106px] rounded-[10px] aspect-video flex-shrink-0">
                                            <StreamSnapshotCover
                                                key={stream.roomId}
                                                thumbnail={stream.thumbnail}
                                                src={stream.src}
                                                isLive={stream.isLive}
                                                captureWhenVisible
                                                alt={coverAlt(stream)}
                                                imageClassName="object-cover pointer-events-none transition-all duration-300"
                                                placeholder={<div className="absolute inset-0 bg-gray-700" />}
                                            />
                                            <div className="thumb-play absolute inset-0 flex items-center justify-center opacity-0 transition-opacity duration-200 text-white">
                                                <FaPlay className="w-4 h-4 fill-current" />
                                            </div>
                                        </div>
                                        <div className="ml-3 flex-1 min-w-0">
                                            <p className="text-[#9196A1] text-sm line-clamp-1 transition-colors duration-300">
                                                {stream.streamerName}
                                            </p>
                                            <span className="block mt-0.5 text-[#9196A1] text-xs transition-colors duration-300">
                                                {t('liveBanner.viewers', { count: stream.viewers })}
                                            </span>
                                        </div>
                                    </button>
                                </SwiperSlide>
                            ))}
                        </Swiper>
                </div>
            </div>

            {/* ????∟???銵???*/}
            <div className="md:hidden mt-4 flex gap-3 overflow-x-auto pb-2 -mx-4 px-4">
                {liveStreams.map((stream, index) => (
                    <Link
                        key={slideKey(stream, index, 'mobile')}
                        href={`/room/${stream.roomId || stream.userId}`}
                        className="flex-shrink-0 w-40 bg-gray-100 dark:bg-neutral-900 rounded-lg overflow-hidden cursor-pointer"
                    >
                        <div className="aspect-video bg-gray-200 dark:bg-gray-700 relative">
                            <StreamCover
                                thumbnail={stream.thumbnail}
                                src={stream.src}
                                isLive={stream.isLive}
                                lazyPlayback
                                alt={coverAlt(stream)}
                                placeholder={
                                    <div className="absolute inset-0 flex items-center justify-center">
                                        <span className="text-gray-500 text-xs">
                                            {t('liveBanner.thumbnailPlaceholder')}
                                        </span>
                                    </div>
                                }
                            />
                            <div className="absolute bottom-2 right-2 bg-black/70 text-white px-2 py-1 rounded text-xs">
                                {stream.viewers.toLocaleString()}
                            </div>
                        </div>
                        <div className="p-2">
                            <p className="text-black dark:text-white text-sm font-medium truncate">
                                {stream.streamerName}
                            </p>
                            <p className="text-gray-600 dark:text-gray-400 text-xs mt-1">
                                {t('liveBanner.viewers', { count: stream.viewers })}
                            </p>
                        </div>
                    </Link>
                ))}
            </div>
        </section>
    )
}




