'use client'

import { useEffect, useLayoutEffect, type ReactNode } from 'react'
import { resolveObsChatFontSizePx, type ObsChatEmbedOptions } from '@/lib/embed/obsChatEmbed'

type Props = {
    options: ObsChatEmbedOptions
    children: ReactNode
}

/** 設定 html/body 透明或色鍵背景，供 OBS Browser Source 去背 */
export default function ObsChatEmbedShell({ options, children }: Props) {
    useLayoutEffect(() => {
        const root = document.documentElement
        const isDark = options.theme === 'dark'
        root.classList.remove('obs-chat-embed--light', 'obs-chat-embed--dark')
        root.classList.add(isDark ? 'obs-chat-embed--dark' : 'obs-chat-embed--light')
        root.setAttribute('data-obs-embed-theme', options.theme)
        if (isDark) {
            root.classList.add('dark')
            root.setAttribute('data-theme', 'dark')
        } else {
            root.classList.remove('dark')
            root.setAttribute('data-theme', 'light')
        }
    }, [options.theme])

    useEffect(() => {
        const root = document.documentElement
        root.classList.add('obs-chat-embed')
        document.body.classList.add('obs-chat-embed-body')

        const prevHtmlBg = root.style.background
        const prevBodyBg = document.body.style.background

        if (options.chromaKey) {
            root.style.background = options.chromaKey
            document.body.style.background = options.chromaKey
        } else if (options.transparent) {
            root.style.background = 'transparent'
            document.body.style.background = 'transparent'
        }

        return () => {
            root.classList.remove('obs-chat-embed', 'obs-chat-embed--light', 'obs-chat-embed--dark')
            root.removeAttribute('data-obs-embed-theme')
            document.body.classList.remove('obs-chat-embed-body')
            root.style.background = prevHtmlBg
            document.body.style.background = prevBodyBg
        }
    }, [options.chromaKey, options.transparent])

    return (
        <div
            data-obs-chat-root
            data-obs-embed-theme={options.theme}
            className={`fixed inset-0 flex flex-col overflow-hidden ${
                options.theme === 'light' ? 'obs-chat-embed--light' : 'obs-chat-embed--dark'
            }`}
            style={{
                background: options.chromaKey
                    ? options.chromaKey
                    : options.transparent
                      ? 'transparent'
                      : undefined,
                ['--obs-chat-font-size' as string]: `${resolveObsChatFontSizePx(options, 4)}px`,
            }}
        >
            {children}
        </div>
    )
}
