import type { AssignmentStatus, WorkMode } from './planning-types'

export const WORK_MODE_COLORS: Record<WorkMode, string> = {
  homeoffice: '#2563EB',
  onsite:     '#65A30D',
  remote:     '#166534',
}

export const WORK_MODE_LABELS: Record<WorkMode, string> = {
  homeoffice: 'Homeoffice',
  onsite:     'Vor Ort',
  remote:     'Remote',
}

export const STATUS_COLORS: Record<AssignmentStatus, string> = {
  fixed:     '#65A30D',
  tentative: '#EAB308',
  critical:  '#DC2626',
  cancelled: '#6B7280',
}

export const STATUS_LABELS: Record<AssignmentStatus, string> = {
  fixed:     'Fest',
  tentative: 'Vorläufig',
  critical:  'Kritisch',
  cancelled: 'Storniert',
}

export const DAY_ABBREV: Record<number, string> = {
  0: 'So', 1: 'Mo', 2: 'Di', 3: 'Mi', 4: 'Do', 5: 'Fr', 6: 'Sa',
}

export const MONTH_NAMES = [
  'Januar', 'Februar', 'März', 'April', 'Mai', 'Juni',
  'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember',
]

// ISO 8601 week number (week starts Monday)
export function getISOWeek(date: Date): number {
  const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()))
  const dayNum = d.getUTCDay() || 7          // Sunday = 7 for ISO
  d.setUTCDate(d.getUTCDate() + 4 - dayNum)  // Nearest Thursday
  const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1))
  return Math.ceil(((d.getTime() - yearStart.getTime()) / 86400000 + 1) / 7)
}

// All calendar days in a given month (1-indexed month)
export function getMonthDays(year: number, month: number): Date[] {
  const days: Date[] = []
  const d = new Date(year, month - 1, 1)
  while (d.getMonth() === month - 1) {
    days.push(new Date(d))
    d.setDate(d.getDate() + 1)
  }
  return days
}

// Group days into { kw, days[], showKw } segments for the grid header.
// ISO 8601: weeks run Mon–Sun. Sunday is the LAST day of its week, not the first.
// - If a Sunday falls in the middle/end of a month group it stays with its Mon–Sat.
// - If a month opens with a Sunday (its Monday is in the previous month), a lone
//   group is created but showKw=false so no label is rendered above it.
export function groupDaysByWeek(days: Date[]): { kw: number; days: Date[]; showKw: boolean }[] {
  const groups: { kw: number; days: Date[]; showKw: boolean }[] = []
  for (const day of days) {
    const dow  = day.getDay()  // 0 = Sunday
    const last = groups[groups.length - 1]

    if (dow === 0 && last) {
      // Sunday: always append to the preceding group (it ends the week, not starts it)
      last.days.push(day)
    } else {
      const kw = getISOWeek(day)
      if (last && last.kw === kw) {
        last.days.push(day)
      } else {
        // showKw=false when the group's first day is Sunday (month-boundary orphan)
        groups.push({ kw, days: [day], showKw: dow !== 0 })
      }
    }
  }
  return groups
}

export function isWeekend(date: Date): boolean {
  const d = date.getDay()
  return d === 0 || d === 6
}

export function isToday(date: Date): boolean {
  const t = new Date()
  return (
    date.getFullYear() === t.getFullYear() &&
    date.getMonth()    === t.getMonth()    &&
    date.getDate()     === t.getDate()
  )
}

// 'YYYY-MM-DD' from a local Date
export function formatDateKey(date: Date): string {
  const y = date.getFullYear()
  const m = String(date.getMonth() + 1).padStart(2, '0')
  const d = String(date.getDate()).padStart(2, '0')
  return `${y}-${m}-${d}`
}

// First and last day strings for a month (for Supabase range queries)
export function monthRange(year: number, month: number): { first: string; last: string } {
  const m = String(month).padStart(2, '0')
  const lastDate = new Date(year, month, 0).getDate()
  return {
    first: `${year}-${m}-01`,
    last:  `${year}-${m}-${String(lastDate).padStart(2, '0')}`,
  }
}

// All calendar days in a full year (Jan 1 – Dec 31)
export function getYearDays(year: number): Date[] {
  const days: Date[] = []
  const d = new Date(year, 0, 1)
  while (d.getFullYear() === year) {
    days.push(new Date(d))
    d.setDate(d.getDate() + 1)
  }
  return days
}

// First and last day strings for a full year
export function yearRange(year: number): { first: string; last: string } {
  return { first: `${year}-01-01`, last: `${year}-12-31` }
}
