import type { NavItem } from './acAssets'
import type { MemberMeData } from '../types/api'

export type NavGroup = {
  label: string
  items: NavItem[]
}

const ROLE_LABELS: Record<string, string> = {
  admin: '管理員',
  member: '一般會員',
}

const STATUS_LABELS: Record<string, string> = {
  active: '使用中',
  inactive: '已停用',
}

const ORIGIN_LABELS: Record<string, string> = {
  native: '本站註冊',
  email: '電子郵件',
}

export function formatMemberRoles(roles: string[] | undefined): string {
  if (!roles?.length) return ROLE_LABELS.member
  return roles.map((role) => ROLE_LABELS[role] ?? role).join('、')
}

export function formatMemberStatus(status: string | undefined): string {
  if (!status) return '—'
  return STATUS_LABELS[status] ?? status
}

export function formatMemberOrigin(origin: string | undefined): string {
  if (!origin) return '—'
  return ORIGIN_LABELS[origin] ?? origin
}

const CJK_CHAR_RE = /\p{Script=Han}/u

/** 頂欄圓形頭像內文字：優先顯示名稱首字，否則依角色顯示中文。 */
export function memberAvatarGlyph(
  member: Pick<MemberMeData, 'display_name' | 'roles'> | null | undefined,
): string {
  const displayName = member?.display_name?.trim()
  if (displayName) {
    const cjk = displayName.match(CJK_CHAR_RE)
    if (cjk) return cjk[0]
  }
  const roles = member?.roles ?? []
  if (roles.includes('admin')) return '管'
  return '員'
}

export function isAdminMember(member: MemberMeData | null | undefined): boolean {
  const roles = member?.roles ?? []
  if (roles.length === 0) return false
  return roles.includes('admin')
}

export function filterAdminOnlyNavGroups(groups: NavGroup[], isAdmin: boolean): NavGroup[] {
  return groups
    .map((group) => ({
      ...group,
      items: group.items.filter((item) => !item.adminOnly || isAdmin),
    }))
    .filter((group) => group.items.length > 0)
}