export interface OrderProcessStep {
  id: string
  label: string
  labelFa: string
  color: string
}

export const DEFAULT_ORDER_PROCESS_STEPS: OrderProcessStep[] = [
  {
    id: 'processing',
    label: 'Under processing',
    labelFa: 'در حال پردازش',
    color: '#3B82F6',
  },
  {
    id: 'ready-for-shipping',
    label: 'Ready for shipping',
    labelFa: 'آماده ارسال',
    color: '#F59E0B',
  },
  {
    id: 'shipped',
    label: 'Shipped',
    labelFa: 'ارسال‌شده',
    color: '#8B5CF6',
  },
  {
    id: 'delivered',
    label: 'Delivered',
    labelFa: 'تحویل‌شده',
    color: '#22C55E',
  },
]

function defaultFaForLabel(label: string | null | undefined) {
  const trimmed = label?.trim()
  if (!trimmed) return undefined
  return DEFAULT_ORDER_PROCESS_STEPS.find(
    (step) => step.label.toLowerCase() === trimmed.toLowerCase(),
  )?.labelFa
}

export function stepLabel(
  steps: OrderProcessStep[],
  processStepId: string,
  processStepLabel?: string | null,
  processStepLabelFa?: string | null,
  locale: 'en' | 'fa' = 'en',
) {
  const step =
    steps.find((item) => item.id === processStepId) ??
    DEFAULT_ORDER_PROCESS_STEPS.find((item) => item.id === processStepId)

  if (locale === 'fa') {
    let fa = processStepLabelFa?.trim() || step?.labelFa?.trim()

    // Older API payloads sometimes echoed the English label as labelFa.
    if (fa && processStepLabel?.trim() && fa === processStepLabel.trim()) {
      fa = undefined
    }

    fa =
      fa ||
      defaultFaForLabel(processStepLabel) ||
      defaultFaForLabel(step?.label)

    if (fa) return fa
  }

  if (processStepLabel?.trim()) return processStepLabel.trim()
  return step?.label ?? processStepId
}

export function stepColor(
  steps: OrderProcessStep[],
  processStepId: string,
  processStepColor?: string | null,
) {
  if (processStepColor?.trim()) return processStepColor.trim()

  const index = steps.findIndex((step) => step.id === processStepId)
  const step =
    (index >= 0 ? steps[index] : undefined) ??
    DEFAULT_ORDER_PROCESS_STEPS.find((item) => item.id === processStepId) ??
    steps[0]

  if (step?.color) return step.color

  if (typeof document !== 'undefined') {
    const themed = getComputedStyle(document.documentElement)
      .getPropertyValue('--primary')
      .trim()
    if (themed) return themed
  }

  return '#3b82f6'
}
