import type { Email } from "@/lib/email-data"
import { navFolderIconColorFromBgClass } from "@/lib/label-pill-contrast"
import {
  emailMatchesFolder,
  type MailFolderFilterCtx,
  type MailNavFolderMaps,
} from "@/lib/mail-folder-filter"
import {
  DEFAULT_INBOX_TAB,
  INBOX_ALL_TAB,
  normalizeInboxTabSegment,
} from "@/lib/mail-url"
import {
  tabbedInboxLabelRows,
  type LabelRowItem,
} from "@/lib/sidebar-nav-data"

export type InboxCategoryTabIcon = {
  id: string
  label: string
  icon: string
  badgeColor: string
}

/** Couleur icône / libellé / soulignement de l’onglet boîte actif. */
export function inboxTabActiveAccentColor(
  tabId: string,
  badgeColor: string
): string {
  if (normalizeInboxTabSegment(tabId) === INBOX_ALL_TAB) return "var(--foreground)"
  return navFolderIconColorFromBgClass(badgeColor)
}

/** Onglets catégorie boîte (Principale + libellés tabbed), hors « Tous les messages ». */
export function buildInboxCategoryTabIcons(
  labelRows: readonly LabelRowItem[]
): InboxCategoryTabIcon[] {
  return [
    {
      id: DEFAULT_INBOX_TAB,
      label: "Principale",
      icon: "mdi:account",
      badgeColor: "bg-[#0b57d0]",
    },
    ...tabbedInboxLabelRows(labelRows).map((r) => ({
      id: r.id,
      label: r.label,
      icon: r.icon ?? "mdi:label-outline",
      badgeColor: r.color,
    })),
  ]
}

/** Onglets catégorie (hors Principale) auxquels le message appartient — pour la liste « Tous les messages ». */
export function resolveEmailInboxCategoryTabs(
  email: Email,
  ctx: MailFolderFilterCtx,
  maps: MailNavFolderMaps,
  tabs: readonly InboxCategoryTabIcon[],
  subtreeIdsCache?: Map<string, string[] | null>
): InboxCategoryTabIcon[] {
  const matched: InboxCategoryTabIcon[] = []
  for (const tab of tabs) {
    if (tab.id === INBOX_ALL_TAB || tab.id === DEFAULT_INBOX_TAB) continue
    if (
      emailMatchesFolder(email, "inbox", ctx, maps, subtreeIdsCache) &&
      emailMatchesFolder(email, tab.id, ctx, maps, subtreeIdsCache)
    ) {
      matched.push(tab)
    }
  }
  return matched
}
