export type PhaseConfigEntry = {
  phase_key: string
  label_de: string
  label_en: string | null
  color_hex: string
  sort_order: number
  is_active: boolean
}

export const INTAKE_STATUS_KEYS = [
  'backlog',
  'review',
  'promoted',
  'rejected',
  'archived',
] as const

export type IntakeStatusKey = (typeof INTAKE_STATUS_KEYS)[number]

export const INTAKE_PRIORITY_KEYS = ['low', 'normal', 'high', 'escalation'] as const

export type IntakePriorityKey = (typeof INTAKE_PRIORITY_KEYS)[number]

export type PhaseFamily = 'intake_status' | 'intake_priority'

export function phaseConfigKeyForIntakeStatus(status: IntakeStatusKey): string {
  return `intake_status_${status}`
}

export function phaseConfigKeyForIntakePriority(priority: IntakePriorityKey): string {
  return `intake_priority_${priority}`
}

export function cssVarNameForPhase(phaseKey: string): string {
  return `--phase-${phaseKey.replace(/_/g, '-')}`
}

export function cssVarRefForPhase(phaseKey: string, fallbackHex: string): string {
  return `var(${cssVarNameForPhase(phaseKey)}, ${fallbackHex})`
}

export function isValidHexColor(hex: string): boolean {
  return /^#[0-9A-Fa-f]{6}$/.test(hex)
}

export function buildPhaseConfigCss(entries: PhaseConfigEntry[]): string {
  const lines: string[] = [':root {']
  for (const e of entries) {
    if (!e.is_active) continue
    if (!isValidHexColor(e.color_hex)) continue
    lines.push(`  ${cssVarNameForPhase(e.phase_key)}: ${e.color_hex};`)
  }
  lines.push('}')
  return lines.join('\n')
}

export const FALLBACK_HEX: Record<string, string> = {
  intake_status_backlog: '#037493',
  intake_status_review: '#035970',
  intake_status_promoted: '#4CAF6A',
  intake_status_rejected: '#6B7A8D',
  intake_status_archived: '#1C1C1C',
  intake_priority_low: '#6B7A8D',
  intake_priority_normal: '#037493',
  intake_priority_high: '#FFE082',
  intake_priority_escalation: '#D93025',
}

export function resolvePhaseHex(
  entries: PhaseConfigEntry[],
  phaseKey: string,
): string {
  const match = entries.find((e) => e.phase_key === phaseKey && e.is_active)
  if (match && isValidHexColor(match.color_hex)) return match.color_hex
  return FALLBACK_HEX[phaseKey] ?? '#037493'
}

export function getPhaseEntry(
  entries: PhaseConfigEntry[],
  phaseKey: string,
): PhaseConfigEntry | null {
  return entries.find((e) => e.phase_key === phaseKey && e.is_active) ?? null
}
