/** Full unambiguous date, per Nash: "shows a full date — day, month, year". */
export function formatFullDate(value: string | Date | null | undefined): string {
  if (!value) return '—'
  const d = typeof value === 'string' ? new Date(value) : value
  if (Number.isNaN(d.getTime())) return '—'
  return d.toLocaleDateString('en-US', { day: '2-digit', month: 'long', year: 'numeric' })
}

export function formatDateTime(value: string | Date | null | undefined): string {
  if (!value) return '—'
  const d = typeof value === 'string' ? new Date(value) : value
  if (Number.isNaN(d.getTime())) return '—'
  return d.toLocaleString('en-US', {
    day: '2-digit',
    month: 'short',
    year: 'numeric',
    hour: 'numeric',
    minute: '2-digit',
  })
}

/**
 * Today's date (YYYY-MM-DD) in the viewer's LOCAL timezone. Permit dates are
 * date-only strings; comparing them against the UTC date flips "valid today"
 * and "expired" up to 8 hours early for US drivers.
 */
export function localToday(): string {
  const d = new Date()
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}

export function formatInches(inches: number | null | undefined): string {
  if (inches == null) return '—'
  const ft = Math.floor(inches / 12)
  const rem = inches % 12
  return rem === 0 ? `${ft}'` : `${ft}'${rem}"`
}

export function formatWeight(lbs: number | null | undefined): string {
  if (lbs == null) return '—'
  return `${lbs.toLocaleString()} lbs`
}

/**
 * "City, ST" from a stored origin / destination (2026-09-08, broker feedback).
 *
 * Nash: "I would actually prefer to have only the city and state from and
 * city and state to instead of having full address, so we don't overload the
 * column with too much text." Used by the dashboard lane column and blocks;
 * the workspace and the driver header keep the full address.
 *
 *   "230 E C St, Wilmington, CA 90744" → "Wilmington, CA"
 *   "Tacoma, WA"                       → "Tacoma, WA"
 *   "California"                       → "California"
 *
 * Anything that does not look like "…, City, ST ZIP" is returned untouched —
 * never guess a city out of free text.
 */
export function cityState(address: string | null | undefined): string {
  const raw = (address ?? '').trim()
  if (!raw) return ''
  const parts = raw.split(',').map((p) => p.trim()).filter(Boolean)
  if (parts.length < 2) return raw
  const last = parts[parts.length - 1]
  // "CA 90744" / "CA" / "California" — keep the state, drop a trailing ZIP.
  const state = last.replace(/\s+\d{5}(-\d{4})?$/, '').trim()
  const city = parts[parts.length - 2]
  return city && state ? `${city}, ${state}` : raw
}
