import type { Email } from "@/lib/email-data"
import { effectiveLabels } from "@/lib/label-edits"
import type { LabelEditState } from "@/lib/stores/mail-store"

/** Libellés système exclus du picker « Ajouter le libellé ». */
export const LABEL_PICKER_EXCLUDE = new Set([
  "inbox",
  "sent",
  "drafts",
  "spam",
  "starred",
])

export function applyNavRenameToEdits(
  pool: Email[],
  prev: LabelEditState,
  from: string,
  to: string
): LabelEditState {
  const lcFrom = from.toLowerCase()
  const toTrim = to.trim()
  if (!toTrim) return prev
  const nextAdd = { ...prev.additions }
  const nextRem = { ...prev.removals }
  for (const e of pool) {
    const id = e.id
    const eff = effectiveLabels(e, prev.additions, prev.removals)
    if (!eff.some((l) => l.toLowerCase() === lcFrom)) continue
    const wanted = eff.map((l) => (l.toLowerCase() === lcFrom ? toTrim : l))
    delete nextAdd[id]
    delete nextRem[id]
    const base = e.labels ?? []
    const removals = base.filter(
      (b) => !wanted.some((w) => w.toLowerCase() === b.toLowerCase())
    )
    const additions = wanted.filter(
      (w) => !base.some((b) => b.toLowerCase() === w.toLowerCase())
    )
    if (removals.length) nextRem[id] = removals
    if (additions.length) nextAdd[id] = additions
  }
  return { additions: nextAdd, removals: nextRem }
}

export function applyNavRemoveLabelToEdits(
  pool: Email[],
  prev: LabelEditState,
  label: string
): LabelEditState {
  const lc = label.toLowerCase()
  const nextAdd = { ...prev.additions }
  const nextRem = { ...prev.removals }
  for (const e of pool) {
    const id = e.id
    const eff = effectiveLabels(e, prev.additions, prev.removals)
    if (!eff.some((l) => l.toLowerCase() === lc)) continue
    const wanted = eff.filter((l) => l.toLowerCase() !== lc)
    delete nextAdd[id]
    delete nextRem[id]
    const base = e.labels ?? []
    const removals = base.filter(
      (b) => !wanted.some((w) => w.toLowerCase() === b.toLowerCase())
    )
    const additions = wanted.filter(
      (w) => !base.some((b) => b.toLowerCase() === w.toLowerCase())
    )
    if (removals.length) nextRem[id] = removals
    if (additions.length) nextAdd[id] = additions
  }
  return { additions: nextAdd, removals: nextRem }
}
