import type { UserNotificationWsPayload } from '@/lib/notifications/userNotificationTypes'
import { resolveGroupNotificationText } from '@/lib/notifications/resolveGroupNotificationText'
import i18n from '@/i18n/config'

export function showDesktopNotificationIfAllowed(
    payload: UserNotificationWsPayload
): void {
    if (typeof window === 'undefined') return
    if (!('Notification' in window)) return
    if (Notification.permission !== 'granted') return

    const resolved = resolveGroupNotificationText(
        i18n.t.bind(i18n),
        payload.type,
        payload.content,
        payload.params
    )
    const title = resolved?.title || payload.title || 'NoiR'
    const body = resolved?.content || payload.content

    try {
        const notification = new Notification(title, {
            body,
            icon: '/favicon.ico',
            tag: payload.id,
        })
        if (payload.url) {
            notification.onclick = () => {
                window.focus()
                window.location.href = payload.url!
            }
        }
    } catch {
        // Safari / 權限邊界情況
    }
}
