'use client'

import { useState, useCallback, useRef, useEffect, useMemo } from 'react'
import Image from 'next/image'
import { useRouter } from 'next/navigation'
import { useTranslation } from 'react-i18next'
import Header from '@/components/Header'
import Sidebar from '@/components/Sidebar'
import RoomVideoPlayer from '@/app/room/_components/RoomVideoPlayer'
import ChatPopoutPageClient from '@/app/room/[id]/chat/ChatPopoutPageClient'
import { FiBookOpen, FiCopy, FiChevronDown, FiWifiOff } from 'react-icons/fi'
import DashboardWifiSignalIcon from '@/components/dashboard/DashboardWifiSignalIcon'
import type { WebRtcSignalSnapshot } from '@/lib/media/webrtcSignalMonitor'
import StreamSetupTutorialModal from '@/components/dashboard/StreamSetupTutorialModal'
import { FaUser } from 'react-icons/fa'
import { FaHeart, FaStar as FaSolidStar } from 'react-icons/fa6'
import {
    normalizeStreamToken,
    resolveStreamPublishUrl,
    resolveWhepVideoUid,
} from '@/lib/streams/cloudflareStreamUrls'
import { parseStreamStatusPayload } from '@/lib/streams/parseStreamStatusPayload'
import {
    buildStreamsWsUrl,
    findStreamStatusForRoom,
    getStreamsSnapshotList,
    isStreamPayloadLive,
    isStreamViewersUpdatePayload,
    parseStreamsWsMessage,
    sendStreamsSubscribe,
    sendStreamsUnsubscribe,
    type StreamStatusPayload,
} from '@/lib/streams/wsStreams'
import { isStreamOfflineByLifecycleStatus } from '@/lib/streams/lifecycleStatus'
import {
    formatLastStreamAtLabel,
    formatLiveDuration,
    formatStreamStartedAtDateTime,
} from '@/utils/format'
import {
    parseRoomStreamCategory,
    type RoomStreamCategory,
} from '@/lib/streams/roomStreamCategory'
import {
    resolveRoomStreamAttribute,
    type RoomStreamAttribute,
} from '@/lib/streams/roomStreamAttribute'

const dashboardPreviewStatDlClass =
    'relative w-full text-center before:absolute before:left-0 before:top-1/2 before:h-[26px] before:w-px before:-mt-[13px] before:bg-gray-100 dark:before:bg-gray-800'

type InitialData = {
    roomId: string
    roomPublicId: string
    title: string
    description: string
    streamToken: string
    liveInputIdentifier: string
    webrtcPublishUrl?: string | null
    createLiveInputHash: string
    thumbnail: string
    category: string
    attribute: string
    startedAt: string
    isLive: boolean
}

type Props = {
    initialData: InitialData
    currentUserId: string | null
    currentUserDisplayName: string | null
    currentUserAvatar: string | null
}

export default function DashboardPageClient({
    initialData,
    currentUserId,
    currentUserDisplayName,
    currentUserAvatar,
}: Props) {
    const { t } = useTranslation()
    const router = useRouter()
    const [sidebarOpen, setSidebarOpen] = useState(false)
    const [settingsOpenMobile, setSettingsOpenMobile] = useState(true)
    const [categoryOpen, setCategoryOpen] = useState(false)
    const [categorySearch, setCategorySearch] = useState('')
    const [activeCategoryGroupId, setActiveCategoryGroupId] = useState<string | null>(null)
    const categoryButtonRef = useRef<HTMLButtonElement | null>(null)
    const categoryMenuRef = useRef<HTMLDivElement | null>(null)

    const [title, setTitle] = useState(initialData.title)
    const [description, setDescription] = useState(initialData.description)
    const [streamKey, setStreamKey] = useState(initialData.liveInputIdentifier)
    const [publishUrlFromApi, setPublishUrlFromApi] = useState<string | null>(
        () => String(initialData.webrtcPublishUrl ?? '').trim() || null
    )

    useEffect(() => {
        const id = initialData.liveInputIdentifier.trim()
        if (id) setStreamKey(id)
        const url = String(initialData.webrtcPublishUrl ?? '').trim()
        if (url) setPublishUrlFromApi(url)
    }, [initialData.liveInputIdentifier, initialData.webrtcPublishUrl])

    useEffect(() => {
        setThumbnail(initialData.thumbnail)
    }, [initialData.thumbnail])

    const streamUrl = useMemo(() => {
        const trimmed = streamKey.trim()
        if (trimmed) return resolveStreamPublishUrl(trimmed)
        return publishUrlFromApi ?? ''
    }, [streamKey, publishUrlFromApi])

    /** DB 已有金鑰（SSR）或剛建立成功後，皆不顯示建立按鈕 */
    const hasStreamKey = Boolean(
        initialData.liveInputIdentifier.trim() || streamKey.trim()
    )
    const showStreamPublishUrl = Boolean(hasStreamKey && streamUrl)
    const [isCreatingStreamKey, setIsCreatingStreamKey] = useState(false)
    const [createStreamKeyError, setCreateStreamKeyError] = useState<string | null>(null)
    const [thumbnail, setThumbnail] = useState(initialData.thumbnail)
    const [thumbnailError, setThumbnailError] = useState<string | null>(null)
    const [isUploadingThumbnail, setIsUploadingThumbnail] = useState(false)
    const thumbnailInputRef = useRef<HTMLInputElement | null>(null)
    const [isSaving, setIsSaving] = useState(false)
    const [saveSuccess, setSaveSuccess] = useState(false)
    const [copiedUrl, setCopiedUrl] = useState(false)
    const [streamTutorialOpen, setStreamTutorialOpen] = useState(false)
    const [isLive, setIsLive] = useState(initialData.isLive)
    const [streamStartedAt, setStreamStartedAt] = useState(initialData.startedAt)
    const [streamPlaybackSessionId, setStreamPlaybackSessionId] = useState<string | null>(null)
    const [liveNowMs, setLiveNowMs] = useState(() => Date.now())
    const [viewerCount, setViewerCount] = useState(0)
    const [webrtcSignal, setWebrtcSignal] = useState<WebRtcSignalSnapshot | null>(null)

    useEffect(() => {
        if (!isLive) setWebrtcSignal(null)
    }, [isLive])
    const streamsWsRef = useRef<WebSocket | null>(null)
    const streamsReconnectTimeoutRef = useRef<number | null>(null)
    const streamsReconnectAttemptsRef = useRef(0)

    const categoryGroups = useMemo(
        () => [
            {
                id: 'life',
                label: t('dashboard.fields.category.groups.life'),
                items: [
                    { id: 'hobby', label: t('dashboard.fields.category.items.life_hobby') },
                    { id: 'daily', label: t('dashboard.fields.category.items.life_daily') },
                ],
            },
            {
                id: 'game',
                label: t('dashboard.fields.category.groups.game'),
                items: [
                    { id: 'fps', label: t('dashboard.fields.category.items.game_fps') },
                    { id: 'moba', label: t('dashboard.fields.category.items.game_moba') },
                ],
            },
            {
                id: 'talk',
                label: t('dashboard.fields.category.groups.talk'),
                items: [
                    { id: 'chat', label: t('dashboard.fields.category.items.talk_chat') },
                    { id: 'radio', label: t('dashboard.fields.category.items.talk_radio') },
                ],
            },
        ],
        [t]
    )

    const [selectedCategory, setSelectedCategory] = useState<RoomStreamCategory | null>(() =>
        parseRoomStreamCategory(initialData.category)
    )
    const [broadcastAttribute, setBroadcastAttribute] = useState<RoomStreamAttribute>(() =>
        resolveRoomStreamAttribute(initialData.attribute)
    )

    useEffect(() => {
        setSelectedCategory(parseRoomStreamCategory(initialData.category))
    }, [initialData.category])

    useEffect(() => {
        setBroadcastAttribute(resolveRoomStreamAttribute(initialData.attribute))
    }, [initialData.attribute])

    const selectedCategoryLabel = useMemo(() => {
        if (!selectedCategory) return null
        const group = categoryGroups.find((g) => g.id === selectedCategory.groupId)
        if (!group) return null
        const item = group.items.find((i) => i.id === selectedCategory.itemId)
        if (!item) return group.label
        return `${group.label} > ${item.label}`
    }, [selectedCategory, categoryGroups])

    const webrtcSignalTitle = useMemo(() => {
        if (!isLive) return undefined
        if (!webrtcSignal) return t('dashboard.preview.signal.unknown')
        return t('dashboard.preview.signal.title', {
            level: webrtcSignal.level,
            rtt: webrtcSignal.rttMs != null ? String(webrtcSignal.rttMs) : '—',
            loss:
                webrtcSignal.packetLossPercent != null
                    ? webrtcSignal.packetLossPercent.toFixed(1)
                    : '—',
        })
    }, [isLive, webrtcSignal, t])

    const playbackSessionKey = useMemo(() => {
        const uid = (streamPlaybackSessionId ?? '').trim().toLowerCase()
        const started = String(streamStartedAt ?? '').trim()
        if (uid && started) return `${uid}:${started}`
        if (uid) return uid
        if (started) return `started:${started}`
        return null
    }, [streamPlaybackSessionId, streamStartedAt])

    /** WHEP 須用 32 字元 video UID，不可用完整 live input 金鑰 */
    const playbackSrc = useMemo(() => {
        const fromWs = resolveWhepVideoUid(streamPlaybackSessionId ?? '')
        if (fromWs) return fromWs
        const fromToken = resolveWhepVideoUid(initialData.streamToken)
        if (fromToken) return fromToken
        return resolveWhepVideoUid(streamKey) ?? normalizeStreamToken(streamKey) ?? ''
    }, [streamPlaybackSessionId, initialData.streamToken, streamKey])

    const dashboardOfflineOverlay = useMemo(() => {
        if (isLive) return null
        return (
            <div className="flex flex-col items-center justify-center gap-2 px-6 text-center text-white">
                <p className="text-lg font-semibold">{t('dashboard.offline.title')}</p>
                <p className="text-sm text-white/80 max-w-md">
                    {t('dashboard.offline.description')}
                </p>
            </div>
        )
    }, [isLive, t])

    useEffect(() => {
        if (typeof window === 'undefined') return
        let cancelled = false

        const applyStreamStatus = (payload: StreamStatusPayload | null | undefined) => {
            if (!payload || payload.roomId !== initialData.roomId) return
            if (payload.cfHasHistory === true) {
                setIsLive(false)
                return
            }
            if (payload.startedAt != null && Number(payload.startedAt) > 0) {
                const nextStarted = String(payload.startedAt)
                setStreamStartedAt((prev) => (prev === nextStarted ? prev : nextStarted))
            }
            const uid = String(payload.videoUID ?? '')
                .trim()
                .toLowerCase()
            if (uid) {
                setStreamPlaybackSessionId(uid)
            }
            if (isStreamPayloadLive(payload)) {
                setIsLive(true)
                return
            }
            setIsLive(false)
        }

        const applyViewersUpdate = (payload: unknown) => {
            if (!isStreamViewersUpdatePayload(payload)) return
            if (payload.roomId !== initialData.roomId) return
            setViewerCount(Math.max(0, Math.floor(payload.viewers)))
        }

        const connectStreamsWebSocket = () => {
            if (cancelled) return
            try {
                const ws = new WebSocket(buildStreamsWsUrl())
                streamsWsRef.current = ws

                ws.onopen = () => {
                    streamsReconnectAttemptsRef.current = 0
                    sendStreamsSubscribe(ws, [initialData.roomId])
                }

                ws.onmessage = (event) => {
                    try {
                        const data = parseStreamsWsMessage(event.data as string)
                        if (!data) return

                        if (data.type === 'streams_snapshot') {
                            const streams = getStreamsSnapshotList(data.data)
                            const status = findStreamStatusForRoom(
                                streams,
                                initialData.roomId
                            )
                            if (status) applyStreamStatus(status)
                            return
                        }

                        if (data.type === 'stream_status') {
                            const status = parseStreamStatusPayload(data.data)
                            if (status) applyStreamStatus(status)
                            return
                        }

                        if (
                            data.type === 'viewers_update' &&
                            isStreamViewersUpdatePayload(data.data)
                        ) {
                            applyViewersUpdate(data.data)
                        }
                    } catch {
                        // ignore
                    }
                }

                ws.onclose = () => {
                    streamsWsRef.current = null
                    if (!cancelled && streamsReconnectAttemptsRef.current < 5) {
                        streamsReconnectAttemptsRef.current++
                        const delay = Math.min(
                            1000 * Math.pow(2, streamsReconnectAttemptsRef.current),
                            10000
                        )
                        streamsReconnectTimeoutRef.current = window.setTimeout(() => {
                            if (!cancelled) connectStreamsWebSocket()
                        }, delay)
                    }
                }
            } catch {
                // ignore
            }
        }

        connectStreamsWebSocket()

        return () => {
            cancelled = true
            if (streamsReconnectTimeoutRef.current != null) {
                window.clearTimeout(streamsReconnectTimeoutRef.current)
                streamsReconnectTimeoutRef.current = null
            }
            const ws = streamsWsRef.current
            streamsWsRef.current = null
            if (ws) {
                if (ws.readyState === WebSocket.OPEN) {
                    sendStreamsUnsubscribe(ws, [initialData.roomId])
                }
                ws.onopen = null
                ws.onmessage = null
                ws.onclose = null
                try {
                    ws.close()
                } catch {
                    // ignore
                }
            }
        }
    }, [initialData.roomId])

    useEffect(() => {
        setStreamStartedAt(initialData.startedAt)
    }, [initialData.startedAt])

    useEffect(() => {
        if (!streamStartedAt) return
        setLiveNowMs(Date.now())
        const id = window.setInterval(() => setLiveNowMs(Date.now()), 1000)
        return () => window.clearInterval(id)
    }, [streamStartedAt])

    const liveDurationLabel = useMemo(() => {
        if (!streamStartedAt) return ''
        if (isLive) {
            const duration = formatLiveDuration(streamStartedAt, liveNowMs) || '00:00:00'
            return t('dashboard.preview.liveDuration', { duration })
        }
        return formatLastStreamAtLabel(streamStartedAt, liveNowMs)
    }, [isLive, streamStartedAt, liveNowMs, t])

    const streamStartedAtTitle = useMemo(
        () => formatStreamStartedAtDateTime(streamStartedAt),
        [streamStartedAt]
    )

    useEffect(() => {
        if (!categoryOpen) return
        const handleClickOutside = (event: MouseEvent) => {
            const target = event.target as HTMLElement | null
            if (!target) return
            if (categoryButtonRef.current?.contains(target)) return
            if (categoryMenuRef.current?.contains(target)) return
            setCategoryOpen(false)
        }
        document.addEventListener('mousedown', handleClickOutside)
        return () => {
            document.removeEventListener('mousedown', handleClickOutside)
        }
    }, [categoryOpen])

    const handleCreateStreamKey = useCallback(async () => {
        setCreateStreamKeyError(null)
        setIsCreatingStreamKey(true)
        try {
            const hashToken = initialData.createLiveInputHash.trim()
            if (!hashToken) {
                setCreateStreamKeyError(t('dashboard.fields.streamKey.createFailed'))
                return
            }

            const response = await fetch('/api/room/dashboard/create-live-input', {
                method: 'POST',
                credentials: 'include',
                headers: {
                    'x-hash': hashToken,
                },
            })
            const data = (await response.json().catch(() => null)) as {
                ok?: boolean
                error?: string
            } | null
            if (response.status === 409) {
                router.refresh()
                return
            }
            if (!response.ok || !data?.ok) {
                const err = String(data?.error ?? '').trim()
                if (err === 'Invalid or expired x-hash') {
                    setCreateStreamKeyError(t('dashboard.fields.streamKey.createFailed'))
                } else if (err === 'Cloudflare API credentials are not configured') {
                    setCreateStreamKeyError(t('dashboard.fields.streamKey.createFailed'))
                } else {
                    setCreateStreamKeyError(
                        err || t('dashboard.fields.streamKey.createFailed')
                    )
                }
                return
            }
            router.refresh()
        } catch {
            setCreateStreamKeyError(t('dashboard.fields.streamKey.createFailed'))
        } finally {
            setIsCreatingStreamKey(false)
        }
    }, [t, initialData.createLiveInputHash, router])

    const handleSave = useCallback(async () => {
        setIsSaving(true)

        try {
            const response = await fetch('/api/room/dashboard/update', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    roomId: initialData.roomId,
                    title,
                    description,
                    category: selectedCategory,
                    attribute: broadcastAttribute,
                    thumbnail: thumbnail.trim(),
                }),
            })

            if (response.ok) {
                const data = (await response.json().catch(() => null)) as {
                    webrtcPublishUrl?: string | null
                    cloudflareError?: string | null
                } | null
                if (data?.webrtcPublishUrl) {
                    setPublishUrlFromApi(data.webrtcPublishUrl)
                }
                if (data?.cloudflareError) {
                    console.warn('[dashboard] Cloudflare sync:', data.cloudflareError)
                }
                setSaveSuccess(true)
                setTimeout(() => setSaveSuccess(false), 3000)
            } else {
                console.error('Failed to save settings: ', await response.text().catch(() => ''))
            }
        } catch (error) {
            console.error('Failed to save settings:', error)
        } finally {
            setIsSaving(false)
        }
    }, [title, description, selectedCategory, broadcastAttribute, thumbnail, initialData.roomId])

    const handleThumbnailUpload = useCallback(
        async (e: React.ChangeEvent<HTMLInputElement>) => {
            const file = e.target.files?.[0]
            if (!file) return

            if (!file.type.startsWith('image/')) {
                setThumbnailError(t('dashboard.fields.thumbnail.errors.invalidType'))
                e.target.value = ''
                return
            }

            const maxSize = 5 * 1024 * 1024
            if (file.size > maxSize) {
                setThumbnailError(t('dashboard.fields.thumbnail.errors.tooLarge'))
                e.target.value = ''
                return
            }

            setThumbnailError(null)
            setIsUploadingThumbnail(true)

            try {
                const formData = new FormData()
                formData.append('thumbnail', file)
                const response = await fetch('/api/room/dashboard/upload-thumbnail', {
                    method: 'POST',
                    body: formData,
                })
                const data = (await response.json().catch(() => null)) as {
                    ok?: boolean
                    thumbnailUrl?: string
                    error?: string
                } | null

                if (response.ok && data?.ok && data.thumbnailUrl) {
                    setThumbnail(data.thumbnailUrl)
                } else if (data?.error === 'File too large') {
                    setThumbnailError(t('dashboard.fields.thumbnail.errors.tooLarge'))
                } else if (data?.error === 'Invalid file type') {
                    setThumbnailError(t('dashboard.fields.thumbnail.errors.invalidType'))
                } else {
                    setThumbnailError(t('dashboard.fields.thumbnail.errors.uploadFailed'))
                }
            } catch {
                setThumbnailError(t('dashboard.fields.thumbnail.errors.uploadFailed'))
            } finally {
                setIsUploadingThumbnail(false)
                e.target.value = ''
            }
        },
        [t]
    )

    const handleRemoveThumbnail = useCallback(() => {
        setThumbnail('')
        setThumbnailError(null)
        if (thumbnailInputRef.current) {
            thumbnailInputRef.current.value = ''
        }
    }, [])

    const handleCopyStreamUrl = useCallback(() => {
        if (streamUrl) {
            navigator.clipboard.writeText(streamUrl)
            setCopiedUrl(true)
            setTimeout(() => setCopiedUrl(false), 2000)
        }
    }, [streamUrl])

    return (
        <div className="min-h-screen min-w-0 bg-white dark:bg-black text-gray-900 dark:text-gray-50 flex transition-colors">
            <Sidebar mode="drawer" isOpen={sidebarOpen} onClose={() => setSidebarOpen(false)} />

            <div className="flex-1 min-h-screen w-full max-w-full overflow-x-hidden">
                <Header onMenuClick={() => setSidebarOpen(!sidebarOpen)} />

                <main className="pt-[65px] pb-2 bg-gray-50 dark:bg-black">
                    <div className="w-full h-full px-4 lg:px-6 pt-2 lg:pt-2 max-w-[1900px] mx-auto">
                        <div className="mb-4 flex items-center justify-between gap-3">
                            <h1 className="text-xl lg:text-2xl font-semibold text-gray-900 dark:text-gray-50">
                                {t('dashboard.title')}
                            </h1>
                        </div>

                        <div className="grid gap-4 xl:gap-6 grid-cols-1 xl:grid-cols-[minmax(0,360px)_minmax(0,1fr)] min-w-0">
                            <section className="border border-gray-200 dark:border-gray-800 rounded-xl bg-white dark:bg-black flex flex-col xl:max-h-[calc(100vh-130px)]">
                                <div className="border-b border-gray-100 dark:border-gray-800 px-4 lg:px-5 py-2 flex items-center justify-between gap-2">
                                    <h2 className="text-[16px] font-semibold text-gray-900 dark:text-gray-50">
                                        {t('dashboard.basicSettings')}
                                    </h2>
                                    <button
                                        type="button"
                                        onClick={() => setSettingsOpenMobile((v) => !v)}
                                        className="xl:hidden inline-flex items-center justify-center w-7 h-7 rounded-full border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-950 text-gray-900 dark:text-gray-100 shrink-0"
                                        aria-label={t('dashboard.a11y.toggleSettings')}
                                    >
                                        <FiChevronDown
                                            className={`h-3.5 w-3.5 transition-transform ${settingsOpenMobile ? 'rotate-180' : 'rotate-0'
                                                }`}
                                        />
                                    </button>
                                </div>

                                <div
                                    className={`flex-1 overflow-y-auto p-5 text-sm text-gray-900 dark:text-gray-50 ${settingsOpenMobile ? 'block' : 'hidden'
                                        } xl:block`}
                                >
                                    <dl className="border-t-0 first:pt-0 pt-6 lg:pt-[30px]">
                                        <dt className="text-[16px] font-semibold text-gray-900 dark:text-gray-50">
                                            {t('dashboard.fields.title.label')}
                                        </dt>
                                        <dd className="mt-2">
                                            <div className="relative flex-1 w-full h-10 border rounded-lg px-3.5 flex items-center group border-gray-300 dark:border-gray-600">
                                                <input
                                                    type="text"
                                                    autoComplete="off"
                                                    maxLength={20}
                                                    placeholder={t('dashboard.fields.title.placeholder')}
                                                    value={title}
                                                    onChange={(e) => setTitle(e.target.value)}
                                                    className="flex-1 h-full pr-3.5 border-0 outline-none bg-transparent text-sm disabled:text-gray-400 dark:disabled:text-gray-500"
                                                />
                                            </div>
                                            <span className="mt-1 block text-[12px] text-gray-500 dark:text-gray-400">
                                                <em>{title.length}/</em>20
                                            </span>
                                        </dd>
                                    </dl>
                                    <dl className="pt-6 lg:pt-[30px]">
                                        <dt className="text-[16px] font-semibold text-gray-900 dark:text-gray-50">
                                            {t('dashboard.fields.description.label')}
                                        </dt>
                                        <dd className="mt-2">
                                            <div className="relative w-full rounded-lg border border-gray-300 px-3.5 py-2.5 dark:border-gray-600">
                                                <textarea
                                                    rows={4}
                                                    maxLength={500}
                                                    autoComplete="off"
                                                    placeholder={t('dashboard.fields.description.placeholder')}
                                                    value={description}
                                                    onChange={(e) => setDescription(e.target.value)}
                                                    className="block w-full resize-y min-h-[88px] border-0 outline-none bg-transparent text-sm text-gray-900 dark:text-gray-50 placeholder:text-gray-400 dark:placeholder:text-gray-500"
                                                />
                                            </div>
                                            <span className="mt-1 block text-[12px] text-gray-500 dark:text-gray-400">
                                                <em>{description.length}/</em>500
                                            </span>
                                        </dd>
                                    </dl>
                                    <dl className="pt-6 lg:pt-[30px]">
                                        <dt className="text-[16px] font-semibold text-gray-900 dark:text-gray-50">
                                            {t('dashboard.fields.category.label')}
                                        </dt>
                                        <dd className="mt-2 relative">
                                            <button
                                                type="button"
                                                ref={categoryButtonRef}
                                                className="relative flex-1 w-full h-10 border rounded-lg px-3.5 flex items-center group border-gray-300 dark:border-gray-600"
                                                onClick={() => {
                                                    if (categoryOpen) {
                                                        setCategoryOpen(false)
                                                    } else {
                                                        const firstGroupId =
                                                            selectedCategory?.groupId ||
                                                            (categoryGroups.length > 0 ? categoryGroups[0].id : null)
                                                        setActiveCategoryGroupId(firstGroupId)
                                                        setCategorySearch('')
                                                        setCategoryOpen(true)
                                                    }
                                                }}
                                            >
                                                <span className="flex-1 truncate text-left">
                                                    {selectedCategoryLabel ? (
                                                        <span className="inline-flex items-center gap-1">
                                                            {selectedCategoryLabel}
                                                        </span>
                                                    ) : (
                                                        <span className="text-gray-400 dark:text-gray-500">
                                                            {t('dashboard.fields.category.placeholder')}
                                                        </span>
                                                    )}
                                                </span>
                                                <FiChevronDown
                                                    className={`ml-2 h-4 w-4 text-gray-500 dark:text-gray-400 transition-transform ${categoryOpen ? 'rotate-180' : 'rotate-0'
                                                        }`}
                                                />
                                            </button>
                                            {categoryOpen && (
                                                <div
                                                    ref={categoryMenuRef}
                                                    className="absolute z-30 mt-2 w-full max-w-[360px] rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-black shadow-xl flex flex-col"
                                                >
                                                    <header className="px-4 pt-3">
                                                        <h2 className="text-[15px] font-semibold text-center text-gray-900 dark:text-gray-50">
                                                            {t('dashboard.fields.category.label')}
                                                        </h2>
                                                    </header>
                                                    <div className="flex-1 overflow-hidden pt-3">
                                                        <div className="px-4">
                                                            <div className="relative flex-1 w-full h-10 border rounded-lg px-3.5 flex items-center group border-gray-300 dark:border-gray-600">
                                                                <span
                                                                    className="pointer-events-none mr-2 h-4 w-4 bg-center bg-no-repeat"
                                                                    style={{
                                                                        backgroundImage:
                                                                            "url(\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%23525661' stroke-linecap='round' stroke-width='1.4' d='m14.106 13.366 2.894 2.8m-.933-7.467A6.533 6.533 0 1 1 3 8.7a6.533 6.533 0 0 1 13.067 0Z'/%3e%3c/svg%3e\")",
                                                                    }}
                                                                />
                                                                <input
                                                                    type="text"
                                                                    autoComplete="off"
                                                                    placeholder={t('dashboard.fields.category.placeholder')}
                                                                    className="flex-1 h-full pr-3.5 border-0 outline-none bg-transparent text-sm disabled:text-gray-400 dark:disabled:text-gray-500"
                                                                    value={categorySearch}
                                                                    onChange={(e) => setCategorySearch(e.target.value)}
                                                                />
                                                                {categorySearch && (
                                                                    <button
                                                                        type="button"
                                                                        onClick={() => setCategorySearch('')}
                                                                        className="absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 rounded-full bg-center bg-no-repeat"
                                                                        style={{
                                                                            backgroundImage:
                                                                                "url(\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 16 16'%3e%3ccircle cx='8' cy='8' r='8' fill='%23E2E4E9'/%3e%3cpath fill='%23525661' fill-rule='evenodd' d='M11.14 5.484a.4.4 0 0 0-.566-.566L8.057 7.435 5.54 4.918a.4.4 0 1 0-.566.566L7.49 8l-2.574 2.574a.4.4 0 0 0 .566.566l2.574-2.575 2.574 2.574a.4.4 0 0 0 .565-.565L8.622 8l2.518-2.517Z' clip-rule='evenodd'/%3e%3c/svg%3e\")",
                                                                        }}
                                                                        aria-label={t('common.clear')}
                                                                    />
                                                                )}
                                                            </div>
                                                        </div>
                                                        <div className="mt-3 max-h-72 overflow-y-auto px-4 pb-3">
                                                            <ul className="space-y-1">
                                                                {categoryGroups.map((group) => {
                                                                    const search = categorySearch.trim().toLowerCase()
                                                                    const groupMatch =
                                                                        !search ||
                                                                        group.label.toLowerCase().includes(search) ||
                                                                        group.items.some((item) =>
                                                                            item.label.toLowerCase().includes(search)
                                                                        )
                                                                    if (!groupMatch) return null
                                                                    const hasSub = group.items.length > 0
                                                                    const isActive = activeCategoryGroupId === group.id
                                                                    return (
                                                                        <li
                                                                            key={group.id}
                                                                            className={isActive ? 'active selected' : ''}
                                                                        >
                                                                            <button
                                                                                type="button"
                                                                                className="flex items-center w-full h-9 px-3 rounded-lg text-[13px] text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-900 transition-colors"
                                                                                onClick={() => {
                                                                                    if (hasSub) {
                                                                                        setActiveCategoryGroupId(
                                                                                            isActive ? null : group.id
                                                                                        )
                                                                                    } else {
                                                                                        setSelectedCategory({
                                                                                            groupId: group.id,
                                                                                            itemId: '',
                                                                                        })
                                                                                        setCategoryOpen(false)
                                                                                    }
                                                                                }}
                                                                            >
                                                                                <span>{group.label}</span>
                                                                                {hasSub && (
                                                                                    <span
                                                                                        className={`more ml-auto w-4 h-4 rounded bg-center bg-no-repeat transition-transform ${isActive ? 'rotate-180' : 'rotate-0'
                                                                                            }`}
                                                                                        style={{
                                                                                            backgroundImage:
                                                                                                "url(\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22' fill='none'%3e%3cg clip-path='url(%23a)'%3e%3cpath stroke='%23ACB0B9' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='m17.5 8-6.75 7L4 8'/%3e%3c/g%3e%3cdefs%3e%3cclipPath id='a'%3e%3cpath fill='%23fff' d='M18.75 16h-16V7h16z'/%3e%3c/clipPath%3e%3c/defs%3e%3c/svg%3e\")",
                                                                                        }}
                                                                                    />
                                                                                )}
                                                                            </button>
                                                                            {hasSub && isActive && (
                                                                                <div className="pt-1">
                                                                                    <ul className="flex flex-wrap gap-x-4 gap-y-1.5 px-3 py-2 border border-[hsla(223,8%,50%,0.2)] rounded-xl">
                                                                                        {group.items.map((item) => {
                                                                                            const isSelected =
                                                                                                selectedCategory?.groupId ===
                                                                                                group.id &&
                                                                                                selectedCategory?.itemId ===
                                                                                                item.id
                                                                                            return (
                                                                                                <li
                                                                                                    key={item.id}
                                                                                                    className="w-1/3"
                                                                                                >
                                                                                                    <button
                                                                                                        type="button"
                                                                                                        className={`block w-full h-8 text-left text-[12px] truncate ${isSelected
                                                                                                            ? 'text-black dark:text-white'
                                                                                                            : 'text-gray-600 dark:text-gray-300'
                                                                                                            }`}
                                                                                                        onClick={() => {
                                                                                                            setSelectedCategory(
                                                                                                                {
                                                                                                                    groupId:
                                                                                                                        group.id,
                                                                                                                    itemId:
                                                                                                                        item.id,
                                                                                                                }
                                                                                                            )
                                                                                                            setCategoryOpen(
                                                                                                                false
                                                                                                            )
                                                                                                        }}
                                                                                                    >
                                                                                                        {item.label}
                                                                                                    </button>
                                                                                                </li>
                                                                                            )
                                                                                        })}
                                                                                    </ul>
                                                                                </div>
                                                                            )}
                                                                        </li>
                                                                    )
                                                                })}
                                                            </ul>
                                                        </div>
                                                    </div>
                                                </div>
                                            )}
                                        </dd>
                                    </dl>


                                    <dl className="pt-6 lg:pt-[30px]">
                                        <dt className="text-[16px] font-semibold text-gray-900 dark:text-gray-50">
                                            {t('dashboard.fields.thumbnail.label')}
                                        </dt>
                                        <dd className="mt-2 space-y-3">
                                            <div className="relative aspect-video w-full max-w-[320px] overflow-hidden rounded-lg border border-gray-200 dark:border-gray-700 bg-gray-100 dark:bg-gray-900">
                                                {thumbnail.trim() ? (
                                                    <Image
                                                        src={thumbnail.trim()}
                                                        alt=""
                                                        fill
                                                        className="object-cover"
                                                        unoptimized
                                                    />
                                                ) : (
                                                    <div className="flex h-full w-full items-center justify-center px-4 text-center text-[12px] text-gray-500 dark:text-gray-400 dark:text-gray-500">
                                                        {t('dashboard.fields.thumbnail.empty')}
                                                    </div>
                                                )}
                                            </div>
                                            <div className="flex flex-wrap items-center gap-2">
                                                <input
                                                    ref={thumbnailInputRef}
                                                    type="file"
                                                    accept="image/*"
                                                    className="sr-only"
                                                    onChange={handleThumbnailUpload}
                                                />
                                                <button
                                                    type="button"
                                                    disabled={isUploadingThumbnail}
                                                    onClick={() => thumbnailInputRef.current?.click()}
                                                    className="px-3 py-1.5 rounded-lg text-[13px] font-medium border border-gray-300 dark:border-gray-600 text-gray-900 dark:text-gray-100 hover:bg-gray-100 dark:hover:bg-gray-900 disabled:opacity-50"
                                                >
                                                    {isUploadingThumbnail
                                                        ? t('dashboard.fields.thumbnail.uploading')
                                                        : t('dashboard.fields.thumbnail.upload')}
                                                </button>
                                                {thumbnail.trim() ? (
                                                    <button
                                                        type="button"
                                                        onClick={handleRemoveThumbnail}
                                                        className="px-3 py-1.5 rounded-lg text-[13px] font-medium text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100"
                                                    >
                                                        {t('dashboard.fields.thumbnail.remove')}
                                                    </button>
                                                ) : null}
                                            </div>
                                            <div className="relative flex-1 w-full h-10 border rounded-lg px-3.5 flex items-center group border-gray-300 dark:border-gray-600">
                                                <input
                                                    type="text"
                                                    autoComplete="off"
                                                    placeholder={t('dashboard.fields.thumbnail.placeholder')}
                                                    value={thumbnail}
                                                    onChange={(e) => {
                                                        setThumbnail(e.target.value)
                                                        setThumbnailError(null)
                                                    }}
                                                    className="flex-1 h-full pr-3.5 border-0 outline-none bg-transparent text-sm disabled:text-gray-400 dark:disabled:text-gray-500"
                                                />
                                            </div>
                                            <p className="text-[12px] text-gray-500 dark:text-gray-400">
                                                {t('dashboard.fields.thumbnail.note')}
                                            </p>
                                            {thumbnailError ? (
                                                <p className="text-[12px] text-gray-700 dark:text-gray-300">
                                                    {thumbnailError}
                                                </p>
                                            ) : null}
                                        </dd>
                                    </dl>

                                    <dl className="pt-6 lg:pt-[30px]">
                                        <dt className="text-[16px] font-semibold text-gray-900 dark:text-gray-50">
                                            {t('dashboard.fields.broadcastProps.label')}
                                        </dt>
                                        <dd>
                                            <ul className="mt-2 space-y-1">
                                                {(
                                                    [
                                                        {
                                                            id: 'hideBroadcast',
                                                            key: 'hideBroadcast' as const,
                                                            labelKey: 'dashboard.fields.broadcastProps.hideBroadcast.label',
                                                        },
                                                        {
                                                            id: 'preventExploration',
                                                            key: 'preventExploration' as const,
                                                            labelKey:
                                                                'dashboard.fields.broadcastProps.preventExploration.label',
                                                        },
                                                        {
                                                            id: 'passwordProtected',
                                                            key: 'passwordProtected' as const,
                                                            labelKey: 'dashboard.fields.broadcastProps.password.label',
                                                        },
                                                    ] as const
                                                ).map((item) => (
                                                    <li key={item.id}>
                                                        <label
                                                            htmlFor={item.id}
                                                            className="flex cursor-pointer items-center gap-2 py-1"
                                                        >
                                                            <input
                                                                id={item.id}
                                                                type="checkbox"
                                                                checked={Boolean(broadcastAttribute[item.key])}
                                                                onChange={() =>
                                                                    setBroadcastAttribute((prev) => ({
                                                                        ...prev,
                                                                        [item.key]: !prev[item.key],
                                                                    }))
                                                                }
                                                                className="h-[26px] w-[26px] shrink-0 rounded-[3.5px] border border-gray-300/60 dark:border-gray-600 bg-white dark:bg-gray-950 accent-black dark:accent-white"
                                                            />
                                                            <span className="text-[15px] text-gray-600 dark:text-gray-300">
                                                                {t(item.labelKey)}
                                                            </span>
                                                        </label>
                                                    </li>
                                                ))}
                                            </ul>
                                        </dd>
                                    </dl>

                                    <dl className="pt-6 lg:pt-[30px] mb-6 lg:mb-8">
                                        <dt className="text-[16px] font-semibold text-gray-900 dark:text-gray-50">
                                            {t('dashboard.fields.streamGroup.label')}
                                        </dt>
                                        <dd className="mt-2 space-y-3">
                                            {!hasStreamKey ? (
                                                <div className="space-y-1">
                                                    <button
                                                        type="button"
                                                        onClick={() => void handleCreateStreamKey()}
                                                        disabled={isCreatingStreamKey}
                                                        className="inline-flex items-center justify-center px-4 py-2 rounded-lg text-sm font-medium text-white bg-black hover:bg-gray-800 dark:bg-white dark:text-black dark:hover:bg-gray-200 disabled:opacity-60 disabled:cursor-not-allowed"
                                                    >
                                                        {isCreatingStreamKey
                                                            ? t('dashboard.fields.streamKey.creating')
                                                            : t('dashboard.fields.streamKey.create')}
                                                    </button>
                                                    {createStreamKeyError ? (
                                                        <p className="text-[12px] text-gray-700 dark:text-gray-300">
                                                            {createStreamKeyError}
                                                        </p>
                                                    ) : null}
                                                    <p className="text-[12px] text-gray-500 dark:text-gray-400">
                                                        {t('dashboard.fields.streamKey.createNote')}
                                                    </p>
                                                </div>
                                            ) : null}

                                            {showStreamPublishUrl ? (
                                                <div className="space-y-1">
                                                    <div className="flex items-center justify-between gap-2 text-[13px] text-gray-600 dark:text-gray-300">
                                                        <span className="shrink-0">{t('dashboard.fields.streamUrl.label')}</span>
                                                        <div className="flex shrink-0 items-center gap-3">
                                                            <button
                                                                type="button"
                                                                onClick={() => setStreamTutorialOpen(true)}
                                                                className="inline-flex items-center gap-1 text-[11px] font-medium text-gray-600 dark:text-gray-300 hover:text-black dark:hover:text-white"
                                                            >
                                                                <FiBookOpen className="h-3 w-3" />
                                                                <span>{t('dashboard.streamTutorial.button')}</span>
                                                            </button>
                                                            <button
                                                                type="button"
                                                                onClick={handleCopyStreamUrl}
                                                                className="inline-flex items-center gap-1 text-[11px] font-medium text-gray-900 dark:text-gray-100 hover:underline"
                                                            >
                                                                <FiCopy className="h-3 w-3" />
                                                                <span>
                                                                    {copiedUrl
                                                                        ? t('dashboard.common.copied')
                                                                        : t('dashboard.common.copy')}
                                                                </span>
                                                            </button>
                                                        </div>
                                                    </div>
                                                    <div className="relative flex-1 w-full h-10 border rounded-lg px-3.5 flex items-center group border-gray-300 dark:border-gray-600">
                                                        <input
                                                            type="url"
                                                            readOnly
                                                            value={streamUrl}
                                                            placeholder={t('dashboard.fields.streamUrl.placeholder')}
                                                            className="flex-1 h-full pr-3.5 border-0 outline-none bg-transparent text-sm text-gray-900 dark:text-gray-100 cursor-default"
                                                        />
                                                    </div>
                                                    <p className="text-[12px] text-gray-500 dark:text-gray-400">
                                                        {t('dashboard.fields.streamUrl.note')}
                                                    </p>
                                                </div>
                                            ) : null}

                                        </dd>
                                    </dl>

                                    <div className="border-t border-gray-100 dark:border-gray-800 pt-3 pb-1 lg:pb-2">
                                        <button
                                            type="button"
                                            onClick={handleSave}
                                            disabled={isSaving}
                                            className="px-4 py-2 rounded-lg text-sm font-medium text-white bg-black hover:bg-gray-800 dark:bg-white dark:text-black dark:hover:bg-gray-200"
                                        >
                                            {isSaving ? (
                                                <span>{t('dashboard.actions.saving')}</span>
                                            ) : saveSuccess ? (
                                                <span>{t('dashboard.messages.saveSuccess')}</span>
                                            ) : (
                                                <span>{t('dashboard.actions.save')}</span>
                                            )}
                                        </button>
                                    </div>
                                </div>
                            </section>

                            <div className="flex min-w-0 flex-col gap-4 min-[1400px]:flex-row min-[1400px]:gap-0">
                                <section className="border border-gray-200 dark:border-gray-800 min-[1400px]:border-r-0 rounded-xl min-[1400px]:rounded-r-none bg-white dark:bg-black flex flex-col min-w-0 w-full min-[1400px]:flex-1">
                                    <div className="border-b border-gray-100 dark:border-gray-800 px-4 lg:px-5 py-3 lg:py-4 flex items-center justify-between gap-3">
                                        <div className="text-sm text-gray-600 dark:text-gray-300 min-w-0">
                                            <span className="font-semibold text-gray-900 dark:text-white">
                                                {title || t('dashboard.preview.titleFallback')}
                                            </span>
                                            {liveDurationLabel ? (
                                                <>
                                                    <span className="mx-1.5 text-gray-500 dark:text-gray-400 dark:text-gray-500">
                                                        ·
                                                    </span>
                                                    <span
                                                        className="text-xs text-gray-500 dark:text-gray-400 cursor-default"
                                                        title={streamStartedAtTitle || undefined}
                                                    >
                                                        {liveDurationLabel}
                                                    </span>
                                                </>
                                            ) : null}
                                        </div>
                                    </div>

                                    <div className="flex flex-col h-full">
                                        <div className="flex shrink-0 items-center px-4 lg:px-5 py-3 lg:py-4 border-b border-gray-100 dark:border-gray-800 text-xs lg:text-sm">
                                            <dl
                                                className={`${dashboardPreviewStatDlClass} first:before:hidden`}
                                            >
                                                <dt className="m-0 flex h-5 items-center justify-center leading-none">
                                                    {isLive ? (
                                                        <DashboardWifiSignalIcon
                                                            level={webrtcSignal?.level ?? null}
                                                            title={webrtcSignalTitle}
                                                        />
                                                    ) : (
                                                        <FiWifiOff
                                                            className="mx-auto block h-5 w-5 text-gray-600 dark:text-gray-400"
                                                            aria-hidden
                                                        />
                                                    )}
                                                </dt>
                                                <dd className="mt-1 flex items-center justify-center">
                                                    <span
                                                        id="broadTime"
                                                        className={`inline-flex items-center justify-center text-[13px] lg:text-[15px] font-semibold leading-[1.4] ${
                                                            isLive
                                                                ? 'text-gray-900 dark:text-gray-50'
                                                                : 'text-gray-500 dark:text-gray-400'
                                                        }`}
                                                    >
                                                        {isLive
                                                            ? t('dashboard.preview.status.online')
                                                            : t('dashboard.preview.status.offline')}
                                                    </span>
                                                </dd>
                                            </dl>

                                            <dl className={dashboardPreviewStatDlClass}>
                                                <dt className="m-0 flex h-5 items-center justify-center leading-none">
                                                    <FaUser
                                                        className={`mx-auto block h-5 w-5 ${
                                                            isLive
                                                                ? 'text-[#b00020] dark:text-[#ff1744]'
                                                                : 'text-gray-600 dark:text-gray-300'
                                                        }`}
                                                        aria-hidden
                                                    />
                                                </dt>
                                                <dd className="mt-1 flex items-center justify-center">
                                                    <span
                                                        id="allCountViewer"
                                                        className={`inline-flex items-center justify-center text-[13px] lg:text-[15px] font-medium leading-[1.4] ${
                                                            isLive
                                                                ? 'text-gray-900 dark:text-gray-50'
                                                                : 'text-gray-500 dark:text-gray-400'
                                                        }`}
                                                    >
                                                        {viewerCount.toLocaleString()}
                                                    </span>
                                                </dd>
                                            </dl>

                                            <dl className={dashboardPreviewStatDlClass}>
                                                <dt className="m-0 flex h-5 items-center justify-center leading-none">
                                                    <FaHeart className="mx-auto block h-5 w-5 text-red-500 dark:text-red-400" />
                                                </dt>
                                                <dd className="mt-1 flex items-center justify-center">
                                                    <span className="inline-flex items-center justify-center text-[13px] lg:text-[15px] font-medium leading-[1.4] text-gray-900 dark:text-gray-50">
                                                        <span id="upCount">0</span>
                                                    </span>
                                                </dd>
                                            </dl>

                                            <dl className={dashboardPreviewStatDlClass}>
                                                <dt className="m-0 flex h-5 items-center justify-center leading-none">
                                                    <FaSolidStar className="mx-auto block h-5 w-5 text-yellow-500 dark:text-yellow-400" />
                                                </dt>
                                                <dd className="mt-1 flex items-center justify-center">
                                                    <span className="inline-flex items-center justify-center text-[13px] lg:text-[15px] font-medium leading-[1.4] text-gray-900 dark:text-gray-50">
                                                        <span id="favorCount">0</span>
                                                    </span>
                                                </dd>
                                            </dl>
                                        </div>

                                        <div className="relative flex-1 min-h-[min(50vw,280px)] sm:min-h-[320px] flex flex-col justify-center">
                                            <div
                                                id="player"
                                                className="relative mx-auto w-full aspect-video overflow-hidden rounded-[14px] bg-black"
                                            >
                                                <RoomVideoPlayer
                                                    src={playbackSrc}
                                                    isLive={isLive}
                                                    poster={thumbnail}
                                                    className="w-full"
                                                    isOwnStream
                                                    playbackSessionId={playbackSessionKey}
                                                    showTheaterToggle={false}
                                                    onWebRtcSignalChange={setWebrtcSignal}
                                                    dashboardPreviewOverlay={
                                                        dashboardOfflineOverlay
                                                    }
                                                    dashboardPreviewEnter={
                                                        isLive
                                                            ? {
                                                                  href: `/room/${initialData.roomPublicId}`,
                                                              }
                                                            : undefined
                                                    }
                                                    showNotLiveLabel={false}
                                                />
                                            </div>
                                        </div>
                                    </div>
                                </section>

                                <section className="bg-white dark:bg-black flex flex-col min-h-[280px] w-full min-[1400px]:w-[360px] min-[1400px]:max-h-[calc(100vh-130px)] min-[1400px]:flex-shrink-0">
                                    <ChatPopoutPageClient
                                        roomId={initialData.roomId}
                                        roomPublicId={initialData.roomPublicId}
                                        streamUserId={currentUserId ?? initialData.roomId}
                                        streamChannelName={currentUserDisplayName ?? (initialData.title || 'My Stream')}
                                        streamAvatar={currentUserAvatar ?? initialData.thumbnail}
                                        currentUserId={currentUserId}
                                        currentUserDisplayName={currentUserDisplayName}
                                        embed
                                    />
                                </section>
                            </div>
                        </div>
                    </div>
                </main>
            </div>

            <StreamSetupTutorialModal
                isOpen={streamTutorialOpen}
                onClose={() => setStreamTutorialOpen(false)}
            />
        </div>
    )
}

