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

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

// Format hours so that values under 1h are shown in minutes.
// Examples: 0.06 -> "4 min"; 0.5 -> "30 min"; 1.25 -> "1,25 h" (pt-BR)
export function formatHoursCompact(value: number, locale: string = "pt-BR"): string {
  const hours = Number(value) || 0
  if (hours < 1 && hours > 0) {
    const mins = Math.round(hours * 60)
    return `${mins} min`
  }
  const nf = new Intl.NumberFormat(locale, { minimumFractionDigits: 2, maximumFractionDigits: 2 })
  return `${nf.format(hours)} h`
}

// Format minutes to h/m when reaching the 1h mark; below that keep 1 decimal minute precision.
// Examples: 45.3 -> "45,3 min"; 60 -> "1h"; 185 -> "3h5m"
export function formatMinutesHuman(value: number, locale: string = "pt-BR"): string {
  const minutes = Number.isFinite(value) ? Math.max(value, 0) : 0
  if (minutes < 60) {
    const nf = new Intl.NumberFormat(locale, { minimumFractionDigits: 1, maximumFractionDigits: 1 })
    return `${nf.format(minutes)} min`
  }
  const rounded = Math.round(minutes)
  const hours = Math.floor(rounded / 60)
  const remainingMinutes = rounded % 60
  return remainingMinutes === 0 ? `${hours}h` : `${hours}h${remainingMinutes}m`
}

// Format date to dd/MM or dd/MM/yyyy. Accepts Date or ISO-like string (YYYY-MM-DD).
export function formatDateDM(value: Date | string | number): string {
  const d = typeof value === "string" || typeof value === "number" ? new Date(value) : value
  const dd = String(d.getDate()).padStart(2, "0")
  const mm = String(d.getMonth() + 1).padStart(2, "0")
  return `${dd}/${mm}`
}

export function formatDateDMY(value: Date | string | number): string {
  const d = typeof value === "string" || typeof value === "number" ? new Date(value) : value
  const dd = String(d.getDate()).padStart(2, "0")
  const mm = String(d.getMonth() + 1).padStart(2, "0")
  const yyyy = d.getFullYear()
  return `${dd}/${mm}/${yyyy}`
}
