'use client'

import type { GiftMessagePayload } from '@/lib/gifts/types'

export type MentionInfo = {
    userId: string
    userName: string
    startIndex: number
    endIndex: number
}

export type EmojiInfo = {
    code: string
    src: string
    startIndex: number
    endIndex: number
}

export type ChatMessage = {
    id: string
    author?: string
    text: string
    time?: string
    isSystem?: boolean
    isModeratorOnly?: boolean
    isPinned?: boolean
    pinnedBy?: {
        userId?: string
        author?: string
        userType?: 'streamer' | 'manager' | 'superAdmin'
    }
    isDeleted?: boolean
    deletedBy?: {
        userId?: string
        author?: string
        userType?: 'streamer' | 'manager' | 'superAdmin'
    }
    userId?: string | null
    /** WS 廣播：發送者 /api/users 用公開 key（有 display_id 則為 display_id，否則為 user_id） */
    authorPublicPathKey?: string | null
    userType?: 'streamer' | 'manager' | 'superAdmin' | 'vip' | 'subscribe' | 'fan' | 'support'
    badge?: string
    badgeTip?: string
    mentions?: MentionInfo[]
    emojis?: EmojiInfo[]
    bannedUserId?: string
    unbannedUserId?: string
    adminUserId?: string
    adminUserType?: 'streamer' | 'manager' | 'superAdmin'
    moddedUserId?: string
    unmoddedUserId?: string
    systemMessageType?: 'modAdded' | 'modRemoved' | 'banAdded' | 'banRemoved' | 'chatDisabled' | 'chatEnabled' | 'userEntered'
    systemMessageData?: {
        userName?: string
        adminName?: string
        durationMs?: number | null
        isPermanent?: boolean
        reason?: string | null
        targetUserType?: 'streamer' | 'manager' | 'superAdmin' | 'viewer'
    }
    /** 送禮訊息（WebSocket gift 廣播） */
    gift?: GiftMessagePayload
}

export type ParticipantItem = {
    role: string
    name: string
    id: string
    /** 資料庫 users.display_id（前端有帶入時才會出現；否則 ViewerCard 再打 API 取） */
    displayId?: string | null
    /** 呼叫 /api/users/:key 時用：有 display_id 則為自訂 id，否則為 user_id */
    profileApiKey?: string | null
    avatarUrl?: string
    userType?: 'streamer' | 'manager' | 'superAdmin' | 'vip' | 'subscribe' | 'fan' | 'support'
    isBanned?: boolean
}

export type GiftRecipient = {
    name: string
    userId: string
    displayId?: string | null
    /** WS publicPathKey：有 display_id 時為自訂 id，否則為 user_id */
    profileApiKey?: string | null
    avatarUrl?: string
}

/** 收禮對象括號內顯示：有 display_id 用 display_id，否則 user_id */
export function formatGiftRecipientPublicId(
    recipient: Pick<GiftRecipient, 'userId' | 'displayId' | 'profileApiKey'>,
): string {
    const displayId = String(recipient.displayId ?? '').trim()
    if (displayId) return displayId

    const profileKey = String(recipient.profileApiKey ?? '').trim()
    if (profileKey && profileKey !== recipient.userId) return profileKey

    return recipient.userId
}

export function participantToGiftRecipient(u: ParticipantItem): GiftRecipient {
    return {
        name: u.name,
        userId: u.id,
        displayId: u.displayId,
        profileApiKey: u.profileApiKey,
        avatarUrl: u.avatarUrl,
    }
}

/** WS publicPathKey：有 users.display_id 時為自訂 id，否則與 user_id 相同 */
export function displayIdFromPublicPathKey(userId: string, publicPathKey?: string | null): string | null {
    const pk = String(publicPathKey ?? '').trim()
    if (pk && pk !== userId) return pk
    return null
}

export function buildParticipantIdentity(
    userId: string,
    publicPathKey?: string | null,
    explicitDisplayId?: string | null,
): Pick<ParticipantItem, 'id' | 'displayId' | 'profileApiKey'> {
    const displayId =
        String(explicitDisplayId ?? '').trim() || displayIdFromPublicPathKey(userId, publicPathKey) || null
    const profileApiKey = displayId || String(publicPathKey ?? '').trim() || userId
    return {
        id: userId,
        displayId,
        profileApiKey,
    }
}

/** 參與者列表括號內：有 display_id 顯示 display_id，否則 user_id */
export function formatParticipantPublicId(u: Pick<ParticipantItem, 'id' | 'displayId'>): string {
    const displayId = String(u.displayId ?? '').trim()
    if (displayId) return displayId
    return u.id
}

/** 從 /api/users/:id?lite=1 補上 DB 的 display_id（聊天 WS 常只有 user_id） */
export async function resolveGiftRecipientDisplayId(recipient: GiftRecipient): Promise<GiftRecipient> {
    const existing = String(recipient.displayId ?? '').trim()
    if (existing) return recipient

    const profileKey = String(recipient.profileApiKey ?? '').trim()
    if (profileKey && profileKey !== recipient.userId) {
        return { ...recipient, displayId: profileKey }
    }

    try {
        const res = await fetch(`/api/users/${encodeURIComponent(recipient.userId)}?lite=1`)
        if (!res.ok) return recipient
        const json = (await res.json()) as {
            ok?: boolean
            data?: { user?: { displayId?: string | null } }
        }
        const displayId = String(json.data?.user?.displayId ?? '').trim()
        if (displayId) return { ...recipient, displayId }
    } catch {
        // ignore
    }

    return recipient
}

export type ParticipantSection = {
    title: string
    items: ParticipantItem[]
}

export type ViewerCardState = {
    mode: 'desktop' | 'mobile'
    user: ParticipantItem
    top: number
    left: number
}

export type UserAdminInfo = {
    userId: string
    userName: string
    avatarUrl?: string
    createdAt: string
    isMod?: boolean
    isSuperAdmin?: boolean
    chatMessages: Array<{
        id: string
        text: string
        createdAt: string
    }>
    banHistory: Array<{
        id: string
        reason?: string
        durationMs?: number | null
        bannedAt: string
        bannedBy: string
        expiresAt?: number | null
        isPermanent: boolean
    }>
    adminNotes: Array<{
        id: string
        note: string
        createdAt: string
        createdBy: string
    }>
}

import type { RoomStreamCategory } from '@/lib/streams/roomStreamCategory'

export type RoomStream = {
    id: string
    userId: string
    /** 主播 users.display_id（有設定時） */
    ownerDisplayId?: string | null
    title: string
    description?: string
    category?: RoomStreamCategory | null
    channelName: string
    avatar: string
    viewers: number
    likes: number
    followers: number
    startedAt: string
    tags: string[]
    isVerified?: boolean
    vipLevel?: 'none' | 'vip' | 'vvip' | 'svip' | 'royal'
    avatarFrame?: {
        id: string
        image: string
        type: 'LOTTIE' | 'IMG'
    } | null
}


