import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}

export function nonEmpty(value: FormDataEntryValue | null): string | null {
  if (typeof value !== "string") return null;
  const trimmed = value.trim();
  return trimmed.length > 0 ? trimmed : null;
}

export function asNumber(value: FormDataEntryValue | null, fallback = 0): number {
  if (typeof value !== "string" || value.trim() === "") return fallback;
  const parsed = Number(value);
  return Number.isFinite(parsed) ? parsed : fallback;
}

export function normalizePhone(value: string): string | null {
  const compact = value.trim().replace(/[()\s-]/g, "");
  if (!compact) return null;

  let normalized: string;
  if (compact.startsWith("+")) {
    normalized = `+${compact.slice(1).replace(/\D/g, "")}`;
  } else {
    const digits = compact.replace(/\D/g, "");
    if (digits.startsWith("00")) normalized = `+${digits.slice(2)}`;
    else if (digits.startsWith("0")) normalized = `+249${digits.slice(1)}`;
    else if (["249", "966", "971", "968"].some((prefix) => digits.startsWith(prefix))) {
      normalized = `+${digits}`;
    }
    else normalized = `+249${digits}`;
  }

  return /^\+[1-9]\d{7,14}$/.test(normalized) ? normalized : null;
}

export function absoluteAppUrl(path = "/"): string {
  const base = process.env.NEXT_PUBLIC_APP_URL?.replace(/\/$/, "") ?? "http://localhost:3000";
  return `${base}${path.startsWith("/") ? path : `/${path}`}`;
}
