import { type CartCustomizationValue } from "@/lib/personalization";

export const FLOWER_EFFECT_SURCHARGE_CENTS = 10;

function normalizeText(value: string) {
  return value
    .normalize("NFD")
    .replace(/[\u0300-\u036f]/g, "")
    .toLowerCase()
    .trim();
}

export function isFlowerEffectField(input?: string | null) {
  const normalized = normalizeText(input || "");
  return normalized.includes("fleur") && normalized.includes("effet");
}

export function isSurchargedFlowerEffect(input?: string | null) {
  const normalized = normalizeText(input || "");
  return normalized.includes("paillet") || normalized.includes("metalis") || normalized.includes("metall");
}

export function getCustomizationSurchargePerUnitCents(
  customizations?: Record<string, { label?: string; value?: string; priceCents?: number }> | null,
): number {
  if (!customizations || typeof customizations !== "object") {
    return 0;
  }

  return Object.entries(customizations).reduce((total, [key, entry]) => {
    const label = typeof entry?.label === "string" ? entry.label : "";
    const value = typeof entry?.value === "string" ? entry.value : "";
    if (typeof entry?.priceCents === "number" && Number.isFinite(entry.priceCents)) {
      return total + Math.max(0, Math.round(entry.priceCents));
    }

    if (!isFlowerEffectField(key) && !isFlowerEffectField(label)) {
      return total;
    }

    return isSurchargedFlowerEffect(value) ? total + FLOWER_EFFECT_SURCHARGE_CENTS : total;
  }, 0);
}

export function getCustomizationSurchargePerUnitCentsFromEntries(entries?: CartCustomizationValue[] | null): number {
  if (!Array.isArray(entries) || entries.length === 0) {
    return 0;
  }

  return entries.reduce((total, entry) => {
    if (typeof entry.priceCents === "number" && Number.isFinite(entry.priceCents)) {
      return total + Math.max(0, Math.round(entry.priceCents));
    }

    if (!isFlowerEffectField(entry.key) && !isFlowerEffectField(entry.label)) {
      return total;
    }

    return isSurchargedFlowerEffect(entry.value) ? total + FLOWER_EFFECT_SURCHARGE_CENTS : total;
  }, 0);
}

export function getLineItemCustomizationSurchargeTotalCents(input: {
  quantity?: number | null;
  metadata?: Record<string, unknown> | null;
  customizations?: CartCustomizationValue[] | null;
}): number {
  const quantity = Math.max(1, input.quantity || 1);
  const storedPerUnit =
    typeof input.metadata?.customization_surcharge_cents === "number"
      ? Math.max(0, input.metadata.customization_surcharge_cents)
      : null;
  const computedPerUnit =
    storedPerUnit ??
    (Array.isArray(input.customizations)
      ? getCustomizationSurchargePerUnitCentsFromEntries(input.customizations)
      : getCustomizationSurchargePerUnitCents(
          input.metadata?.customizations as Record<string, { label?: string; value?: string }> | null | undefined,
        ));

  return computedPerUnit * quantity;
}
