import crypto from "node:crypto";

/** CDP-002: normalise a phone number to E.164. Defaults to Bangladesh (+880) for local numbers. */
export function normalizePhone(raw: string | null | undefined, defaultCountry = "880"): string | null {
  if (!raw) return null;
  let s = String(raw).trim().replace(/[০-৯]/g, (d) => String(d.charCodeAt(0) - 0x09e6)); // Bangla digits
  const plus = s.startsWith("+");
  s = s.replace(/[^\d]/g, "");
  if (!s) return null;
  if (plus) return s.length >= 8 && s.length <= 15 ? `+${s}` : null;
  if (s.startsWith("00")) s = s.slice(2);
  else if (defaultCountry === "880" && /^01\d{9}$/.test(s)) s = `880${s.slice(1)}`;
  else if (defaultCountry === "880" && /^1\d{9}$/.test(s)) s = `880${s}`;
  else if (defaultCountry === "61" && /^0[2-9]\d{8}$/.test(s)) s = `61${s.slice(1)}`;
  else if (defaultCountry === "1" && /^\d{10}$/.test(s)) s = `1${s}`;
  else if (s.startsWith("0")) s = defaultCountry + s.slice(1);
  if (s.length < 8 || s.length > 15) return null;
  return `+${s}`;
}

/** PAGE-002: validation used client- and server-side */
export function isValidPhone(raw: string, defaultCountry = "880"): boolean {
  const p = normalizePhone(raw, defaultCountry);
  if (!p) return false;
  if (p.startsWith("+880")) return /^\+8801[3-9]\d{8}$/.test(p);
  return /^\+\d{8,15}$/.test(p);
}

export function normalizeEmail(raw: string | null | undefined): string | null {
  if (!raw) return null;
  const e = String(raw).trim().toLowerCase();
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e) ? e : null;
}

export const sha256 = (s: string) => crypto.createHash("sha256").update(s).digest("hex");
export const randomToken = (bytes = 24) => crypto.randomBytes(bytes).toString("base64url");
export const uuid = () => crypto.randomUUID();

export function slugify(s: string) {
  return s.toLowerCase().normalize("NFKD").replace(/[^\w\s-]/g, "").trim().replace(/[\s_]+/g, "-").replace(/-+/g, "-").slice(0, 60) || "item";
}

export const CURRENCY_DIGITS: Record<string, number> = { BDT: 2, USD: 2, AUD: 2 };

/** Money is stored in minor units (BRD §9) */
export function formatMoney(minor: number | null | undefined, currency = "BDT", locale = "en") {
  const v = (minor ?? 0) / 100;
  try {
    return new Intl.NumberFormat(locale === "bn" ? "bn-BD" : currency === "BDT" ? "en-BD" : "en-US", {
      style: "currency", currency, maximumFractionDigits: v >= 1000 ? 0 : 2,
    }).format(v);
  } catch {
    return `${currency} ${v.toFixed(2)}`;
  }
}

/** Compact money for tiles: ৳13.7L style for BDT (lakh/crore), $1.2M otherwise. */
export function formatMoneyShort(minor: number | null | undefined, currency = "BDT") {
  const v = (minor ?? 0) / 100;
  if (currency === "BDT") {
    const sym = "৳";
    if (Math.abs(v) >= 1e7) return `${sym}${(v / 1e7).toFixed(2)} Cr`;
    if (Math.abs(v) >= 1e5) return `${sym}${(v / 1e5).toFixed(1)} L`;
    return `${sym}${new Intl.NumberFormat("en-IN").format(Math.round(v))}`;
  }
  return new Intl.NumberFormat("en-US", { style: "currency", currency, notation: Math.abs(v) >= 1e5 ? "compact" : "standard", maximumFractionDigits: Math.abs(v) >= 1e5 ? 1 : 0 }).format(v);
}

export function formatNumber(n: number | null | undefined, locale = "en") {
  return new Intl.NumberFormat(locale === "bn" ? "bn-BD" : "en-US").format(n ?? 0);
}

/** ADM-006: all dates render in workspace timezone */
export function formatDate(d: Date | string | null | undefined, tz = "Asia/Dhaka", opts: Intl.DateTimeFormatOptions = { dateStyle: "medium", timeStyle: "short" }, locale = "en") {
  if (!d) return "—";
  const date = typeof d === "string" ? new Date(d) : d;
  if (Number.isNaN(date.getTime())) return "—";
  return new Intl.DateTimeFormat(locale === "bn" ? "bn-BD" : "en-GB", { ...opts, timeZone: tz }).format(date);
}

export function timeAgo(d: Date | string | null | undefined) {
  if (!d) return "—";
  const ms = Date.now() - new Date(d).getTime();
  const abs = Math.abs(ms);
  const fut = ms < 0;
  const m = Math.round(abs / 60000);
  let s: string;
  if (m < 1) s = "just now";
  else if (m < 60) s = `${m}m`;
  else if (m < 1440) s = `${Math.round(m / 60)}h`;
  else s = `${Math.round(m / 1440)}d`;
  if (s === "just now") return s;
  return fut ? `in ${s}` : `${s} ago`;
}

/** Hour/minute in a timezone — used for quiet hours (FLOW-007). */
export function localMinutes(date: Date, tz: string) {
  const parts = new Intl.DateTimeFormat("en-GB", { hour: "2-digit", minute: "2-digit", hour12: false, timeZone: tz }).formatToParts(date);
  const h = Number(parts.find((p) => p.type === "hour")?.value ?? 0) % 24;
  const m = Number(parts.find((p) => p.type === "minute")?.value ?? 0);
  return h * 60 + m;
}

export function localDateString(date: Date, tz: string) {
  return new Intl.DateTimeFormat("en-CA", { timeZone: tz, year: "numeric", month: "2-digit", day: "2-digit" }).format(date);
}

export function isoDay(offsetDays = 0, from = new Date()) {
  const d = new Date(from.getTime() + offsetDays * 86400000);
  return d.toISOString().slice(0, 10);
}

export const period = (d = new Date()) => d.toISOString().slice(0, 7);

/** Render {{variable|fallback}} placeholders (MSG-007) */
export function renderTemplate(body: string, vars: Record<string, unknown>) {
  return body.replace(/\{\{\s*([\w.]+)\s*(?:\|\s*([^}]*))?\}\}/g, (_m, key: string, fallback?: string) => {
    const v = key.split(".").reduce<unknown>((o, k) => (o && typeof o === "object" ? (o as Record<string, unknown>)[k] : undefined), vars);
    if (v === undefined || v === null || v === "") return (fallback ?? "").trim();
    return String(v);
  });
}

export function extractVariables(body: string) {
  return [...new Set([...body.matchAll(/\{\{\s*([\w.]+)/g)].map((m) => m[1]))];
}

export function fullName(c: { firstName?: string | null; lastName?: string | null; emails?: string[]; phones?: string[] }) {
  const n = [c.firstName, c.lastName].filter(Boolean).join(" ").trim();
  return n || c.emails?.[0] || c.phones?.[0] || "Unknown";
}

export function initials(name: string) {
  return name.split(/\s+/).filter(Boolean).slice(0, 2).map((p) => p[0]!.toUpperCase()).join("") || "?";
}

export function clamp(n: number, a: number, b: number) {
  return Math.max(a, Math.min(b, n));
}

export function safeJson<T = unknown>(s: string | null | undefined, fallback: T): T {
  try {
    return s ? (JSON.parse(s) as T) : fallback;
  } catch {
    return fallback;
  }
}

export function pct(a: number, b: number) {
  return b ? (a / b) * 100 : 0;
}

export const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
