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

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

const DATE_PREFIX_PATTERN = /^(\d{4})-(\d{2})-(\d{2})/

function parseDateParts(value: string): [number, number, number] | null {
  const match = value.match(DATE_PREFIX_PATTERN)
  if (!match) return null
  return [Number(match[1]), Number(match[2]), Number(match[3])]
}

function asLocalDayDate(value: string, endOfDay: boolean): Date | null {
  const parts = parseDateParts(value)
  if (!parts) return null
  const [year, month, day] = parts
  return endOfDay
    ? new Date(year, month - 1, day, 23, 59, 59, 999)
    : new Date(year, month - 1, day, 0, 0, 0, 0)
}

export function parseSprintStart(startDate: string): Date {
  const localStart = asLocalDayDate(startDate, false)
  if (localStart) return localStart
  return new Date(startDate)
}

export function parseSprintEnd(endDate: string): Date {
  const localEnd = asLocalDayDate(endDate, true)
  if (localEnd) return localEnd
  const parsed = new Date(endDate)
  parsed.setHours(23, 59, 59, 999)
  return parsed
}

export function toLocalDateInputValue(date: Date = new Date()): string {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, "0")
  const day = String(date.getDate()).padStart(2, "0")
  return `${year}-${month}-${day}`
}
