/**
 * MotherShip 登录态官网硬约束（与 dashboard Create shipment 对齐）
 */
export const MOTHERSHIP_MAX_WEIGHT_EACH_LB = 5000;

/** YYYY-MM-DD → 本地 noon 解析，避免 UTC 偏移改星期 */
export function parseIsoDateLocal(iso: string): Date | null {
  const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(iso.trim());
  if (!m) return null;
  const d = new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]), 12, 0, 0);
  return Number.isNaN(d.getTime()) ? null : d;
}

export function toIsoDateLocal(d: Date): string {
  const yyyy = d.getFullYear();
  const mm = String(d.getMonth() + 1).padStart(2, "0");
  const dd = String(d.getDate()).padStart(2, "0");
  return `${yyyy}-${mm}-${dd}`;
}

/** 周六=6 / 周日=0 不可选 */
export function isMothershipWeekendIso(iso: string): boolean {
  const d = parseIsoDateLocal(iso);
  if (!d) return false;
  const day = d.getDay();
  return day === 0 || day === 6;
}

/** 若落在周末，拨到下一工作日（周一） */
export function snapMothershipReadyDateToWeekday(iso: string): string {
  const d = parseIsoDateLocal(iso);
  if (!d) return iso;
  const day = d.getDay();
  if (day === 6) d.setDate(d.getDate() + 2);
  else if (day === 0) d.setDate(d.getDate() + 1);
  return toIsoDateLocal(d);
}

/** 今天 YYYY-MM-DD（本地） */
export function todayIsoDateLocal(): string {
  return toIsoDateLocal(new Date());
}

/** 默认可提货日：今天若为周末则拨到周一 */
export function defaultMothershipReadyDateIso(): string {
  return snapMothershipReadyDateToWeekday(todayIsoDateLocal());
}

/** date input min：与官网一致，不可早于最近工作日 */
export function minMothershipReadyDateIso(): string {
  return defaultMothershipReadyDateIso();
}

/** 所有 MotherShip 日期字段统一规范化 */
export function normalizeMothershipReadyDateIso(iso: string | undefined): string | undefined {
  const trimmed = iso?.trim();
  if (!trimmed) return undefined;
  return snapMothershipReadyDateToWeekday(trimmed);
}

/** 单件重量（Weight each）不得超过 5000 lb */
export function isMothershipWeightEachAllowed(weightEachLb: number): boolean {
  return (
    Number.isFinite(weightEachLb) &&
    weightEachLb > 0 &&
    weightEachLb <= MOTHERSHIP_MAX_WEIGHT_EACH_LB
  );
}
