export interface SmartGreeting {
  title: string
  subtitle: string
  label: string
}

const dailySubtitles = [
  '愿今天的课程与计划都清晰顺利。',
  '新的一天，从有序安排开始。',
  '把每一次学习，都变成看得见的进步。',
]

function lunarFestival(date: Date) {
  try {
    const parts = new Intl.DateTimeFormat('zh-CN-u-ca-chinese', {
      month: 'long',
      day: 'numeric',
    }).formatToParts(date)
    const month = parts.find((part) => part.type === 'month')?.value ?? ''
    const day = parts.find((part) => part.type === 'day')?.value ?? ''

    if (month === '正月' && ['1', '2', '3'].includes(day)) return '春节快乐'
    if (month === '正月' && day === '15') return '元宵节快乐'
    if (month === '五月' && day === '5') return '端午安康'
    if (month === '八月' && day === '15') return '中秋快乐'
  } catch {
    // 少数精简 WebView 不支持中国农历日历，继续使用公历与时段问候。
  }
  return ''
}

function festivalGreeting(date: Date) {
  const month = date.getMonth() + 1
  const day = date.getDate()
  const lunar = lunarFestival(date)
  if (lunar) return lunar
  if (month === 1 && day === 1) return '新年快乐'
  if (month === 5 && day >= 1 && day <= 5) return '劳动节愉快'
  if (month === 9 && day === 10) return '教师节快乐'
  if (month === 10 && day >= 1 && day <= 7) return '国庆节快乐'
  return ''
}

function timeGreeting(date: Date) {
  const hour = date.getHours()
  if (hour < 5) return '夜深了'
  if (hour < 11) return '早上好'
  if (hour < 14) return '中午好'
  if (hour < 18) return '下午好'
  return '晚上好'
}

export function getSmartGreeting(
  date = new Date(),
  displayName?: string | null,
): SmartGreeting {
  const greeting = festivalGreeting(date) || timeGreeting(date)
  const name = displayName?.trim()
  const weekday = new Intl.DateTimeFormat('zh-CN', { weekday: 'long' }).format(date)
  const label = new Intl.DateTimeFormat('zh-CN', {
    month: 'long',
    day: 'numeric',
  }).format(date)
  const index = Math.abs(date.getFullYear() * 372 + date.getMonth() * 31 + date.getDate())
    % dailySubtitles.length

  return {
    title: name ? `${name}，${greeting}` : `${greeting}，欢迎使用明序教务`,
    subtitle: date.getDay() === 0 || date.getDay() === 6
      ? '周末也要记得放松一下，查看安排后从容出发。'
      : dailySubtitles[index],
    label: `${label} · ${weekday}`,
  }
}
