import { popoutChatFontSizePx } from '@/lib/chat/chatFontLevel'

/** OBS Browser Source 聊天疊層選項 */
export type ObsChatEmbedOptions = {
    /** 頁面背景透明（OBS 可直接疊在畫面上） */
    transparent: boolean
    /** 使用色鍵去背（例如 #00FF00，OBS 套用「色度鍵」） */
    chromaKey: string | null
    hideHeader: boolean
    hideInput: boolean
    theme: 'dark' | 'light'
    fontSizePx: number | null
}

const DEFAULT_FONT_SIZE = 16
const CHROMA_GREEN = '#00FF00'

export const DEFAULT_OBS_CHAT_EMBED_OPTIONS: ObsChatEmbedOptions = {
    transparent: true,
    chromaKey: null,
    hideHeader: true,
    hideInput: true,
    theme: 'dark',
    fontSizePx: null,
}

function parseBool(value: string | null, defaultValue: boolean): boolean {
    if (value == null || value === '') return defaultValue
    const v = value.trim().toLowerCase()
    if (v === '1' || v === 'true' || v === 'yes') return true
    if (v === '0' || v === 'false' || v === 'no') return false
    return defaultValue
}

/** 從 URL searchParams 解析 OBS 聊天疊層設定 */
export function parseObsChatEmbedSearchParams(
    params: Pick<URLSearchParams, 'get'>
): ObsChatEmbedOptions {
    const chromaRaw = params.get('chroma')?.trim().toLowerCase() ?? ''
    const useChroma = chromaRaw === '1' || chromaRaw === 'true' || chromaRaw === 'green'
    const chromaCustom = params.get('chromaColor')?.trim()
    const chromaKey = useChroma
        ? chromaCustom && /^#?[0-9a-f]{6}$/i.test(chromaCustom)
            ? chromaCustom.startsWith('#')
                ? chromaCustom
                : `#${chromaCustom}`
            : CHROMA_GREEN
        : null

    const transparent = chromaKey
        ? false
        : parseBool(params.get('transparent'), DEFAULT_OBS_CHAT_EMBED_OPTIONS.transparent)

    const fontRaw = params.get('fontSize') ?? params.get('font')
    let fontSizePx: number | null = null
    if (fontRaw) {
        const n = Number(fontRaw)
        if (Number.isFinite(n) && n >= 10 && n <= 32) fontSizePx = Math.round(n)
    }

    const themeRaw = params.get('theme')?.trim().toLowerCase()
    const theme: 'dark' | 'light' = themeRaw === 'light' ? 'light' : 'dark'

    return {
        transparent,
        chromaKey,
        hideHeader:
            params.get('header') != null
                ? !parseBool(params.get('header'), true)
                : DEFAULT_OBS_CHAT_EMBED_OPTIONS.hideHeader,
        hideInput:
            params.get('input') != null
                ? !parseBool(params.get('input'), true)
                : DEFAULT_OBS_CHAT_EMBED_OPTIONS.hideInput,
        theme,
        fontSizePx,
    }
}

export function buildEmbedChatUrl(
    origin: string,
    publicRoomId: string,
    options?: Partial<ObsChatEmbedOptions>
): string {
    const base = String(origin ?? '').trim().replace(/\/$/, '')
    const id = String(publicRoomId ?? '').trim()
    if (!base || !id) return ''

    const o: ObsChatEmbedOptions = {
        ...DEFAULT_OBS_CHAT_EMBED_OPTIONS,
        ...options,
    }
    const q = new URLSearchParams()
    if (o.chromaKey) {
        q.set('chroma', '1')
        if (o.chromaKey.toUpperCase() !== CHROMA_GREEN) {
            q.set('chromaColor', o.chromaKey.replace(/^#/, ''))
        }
    } else if (!o.transparent) {
        q.set('transparent', '0')
    }
    if (!o.hideHeader) q.set('header', '1')
    if (!o.hideInput) q.set('input', '1')
    q.set('theme', o.theme)
    if (o.fontSizePx != null) q.set('fontSize', String(o.fontSizePx))

    const qs = q.toString()
    return `${base}/embed/chat/${encodeURIComponent(id)}${qs ? `?${qs}` : ''}`
}

export function resolveObsChatFontSizePx(
    options: ObsChatEmbedOptions,
    chatFontLevel: number
): number {
    if (options.fontSizePx != null) return options.fontSizePx
    return popoutChatFontSizePx(chatFontLevel, DEFAULT_FONT_SIZE)
}

/**
 * OBS Browser Source「カスタム CSS」範例（貼到 OBS 來源屬性即可覆寫顏色）。
 * 選擇器定義於 app/globals.css（html.obs-chat-embed）。
 */
export const OBS_BROWSER_SOURCE_CUSTOM_CSS_EXAMPLE = `body {
  background-color: rgba(0, 0, 0, 0);
  margin: 0;
  overflow: hidden;
}

/* 全部聊天文字 */
.obs-chat-messages {
  color: #ffffff;
  font-size: 18px;
}

/* 訊息內文 */
.obs-chat-message__body {
  color: #e8e8e8;
}

/* 暱稱：依角色 */
.obs-chat-message--streamer .obs-chat-message__author {
  color: #fb923c;
}
.obs-chat-message--mod .obs-chat-message__author {
  color: #60a5fa;
}
.obs-chat-message--viewer .obs-chat-message__author {
  color: #ffffff;
}

/* 系統訊息、連結、@提及 */
.obs-chat-system {
  color: #9ca3af;
}
.obs-chat-link {
  color: #93c5fd;
}
.obs-chat-mention {
  color: #fde68a;
}
`
