import type { FolderTreeNode } from "@/lib/sidebar-nav-maps"
import type { LabelRowItem } from "@/lib/sidebar-nav-data"
import { labelRowById } from "@/lib/sidebar-nav-data"
import { findFolderPath } from "@/lib/sidebar-nav-folder-ids"

export type LabelPickerVisual =
  | { kind: "iconify"; icon: string }
  | { kind: "dot"; colorClass: string }

function findFolderNodeByLabel(
  nodes: FolderTreeNode[],
  labelText: string
): FolderTreeNode | undefined {
  const lower = labelText.toLowerCase()
  for (const n of nodes) {
    if (n.label === labelText || n.label.toLowerCase() === lower) return n
    if (n.children?.length) {
      const hit = findFolderNodeByLabel(n.children, labelText)
      if (hit) return hit
    }
  }
  return undefined
}

function labelRowByLabelText(
  rows: readonly LabelRowItem[],
  labelText: string
): LabelRowItem | undefined {
  const lower = labelText.toLowerCase()
  return rows.find((r) => r.label === labelText || r.label.toLowerCase() === lower)
}

/** Icône nav ou pastille couleur pour une entrée du sélecteur de libellés. */
export function resolveLabelPickerVisual(
  labelText: string,
  opts: {
    folderTree: FolderTreeNode[]
    labelRows: readonly LabelRowItem[]
    emailLabelToSidebarFolderId: Record<string, string>
  }
): LabelPickerVisual {
  const { folderTree, labelRows, emailLabelToSidebarFolderId } = opts
  const fid = emailLabelToSidebarFolderId[labelText]
  if (fid) {
    const row = labelRowById(labelRows, fid)
    if (row?.icon) return { kind: "iconify", icon: row.icon }
    if (row?.color) return { kind: "dot", colorClass: row.color }
    const path = findFolderPath(folderTree, fid)
    if (path?.length) {
      const leaf = path[path.length - 1]!
      return { kind: "dot", colorClass: leaf.color ?? "bg-gray-400" }
    }
  }

  const row = labelRowByLabelText(labelRows, labelText)
  if (row?.icon) return { kind: "iconify", icon: row.icon }
  if (row?.color) return { kind: "dot", colorClass: row.color }

  const folder = findFolderNodeByLabel(folderTree, labelText)
  if (folder?.color) return { kind: "dot", colorClass: folder.color }

  return { kind: "dot", colorClass: "bg-gray-400" }
}
