import type { HubScheduleItem } from './hubConfig';

const KOR_MONTHS = ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'];

export function parseScheduleDate(dateStr: string): Date | null {
  if (!dateStr || !/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) return null;
  const [y, m, d] = dateStr.split('-').map(Number);
  const dt = new Date(y, m - 1, d);
  if (dt.getFullYear() !== y || dt.getMonth() !== m - 1 || dt.getDate() !== d) return null;
  return dt;
}

export function startOfDay(date: Date): Date {
  return new Date(date.getFullYear(), date.getMonth(), date.getDate());
}

/** "6월 8일" */
export function formatScheduleDateLabel(dateStr: string): string {
  const parts = formatScheduleDateParts(dateStr);
  if (!parts) return dateStr;
  return `${parts.month} ${parts.day}`;
}

/** { month: "6월", day: "8일" } — 일정 목록 좌우 정렬용 */
export function formatScheduleDateParts(dateStr: string): { month: string; day: string } | null {
  const dt = parseScheduleDate(dateStr);
  if (!dt) return null;
  return {
    month: `${dt.getMonth() + 1}월`,
    day: `${dt.getDate()}일`,
  };
}

export function sortScheduleItems(items: HubScheduleItem[]): HubScheduleItem[] {
  return [...items].sort((a, b) => {
    const da = parseScheduleDate(a.date)?.getTime() ?? Number.MAX_SAFE_INTEGER;
    const db = parseScheduleDate(b.date)?.getTime() ?? Number.MAX_SAFE_INTEGER;
    return da - db;
  });
}

/** 3건 창에서 오늘(포커스) 일정이 가운데 오도록 시작 인덱스 */
export function scheduleWindowStart(total: number, focusIndex: number, visible = 3): number {
  if (total <= visible) return 0;
  const middle = Math.floor(visible / 2);
  let start = focusIndex - middle;
  start = Math.max(0, start);
  start = Math.min(start, total - visible);
  return start;
}

/** 오늘(또는 가장 가까운 일정) 기준 시작 인덱스 — 과거는 왼쪽, 미래는 오른쪽 */
export function findScheduleIndexForToday(items: HubScheduleItem[], today = new Date()): number {
  const sorted = sortScheduleItems(items.filter((i) => i.date && i.text.trim()));
  if (sorted.length === 0) return 0;

  const todayMs = startOfDay(today).getTime();

  const exact = sorted.findIndex((item) => {
    const d = parseScheduleDate(item.date);
    return d && startOfDay(d).getTime() === todayMs;
  });
  if (exact >= 0) return exact;

  const next = sorted.findIndex((item) => {
    const d = parseScheduleDate(item.date);
    return d && startOfDay(d).getTime() > todayMs;
  });
  if (next >= 0) return next;

  return sorted.length - 1;
}

export function isSchedulePast(dateStr: string, today = new Date()): boolean {
  const d = parseScheduleDate(dateStr);
  if (!d) return false;
  return startOfDay(d).getTime() < startOfDay(today).getTime();
}

export function isScheduleToday(dateStr: string, today = new Date()): boolean {
  const d = parseScheduleDate(dateStr);
  if (!d) return false;
  return startOfDay(d).getTime() === startOfDay(today).getTime();
}

/** 레거시 month 필드 → date (2026-Q2 가정) */
export function migrateScheduleItem(
  item: HubScheduleItem & { month?: string },
  defaultYear = 2026,
): HubScheduleItem {
  if (item.date && parseScheduleDate(item.date)) {
    return { id: item.id, date: item.date, text: item.text ?? '' };
  }
  const legacy = item.month?.trim() ?? '';
  const monthMatch = legacy.match(/(\d{1,2})\s*월/);
  if (monthMatch) {
    const m = Number(monthMatch[1]);
    if (m >= 1 && m <= 12) {
      return {
        id: item.id,
        date: `${defaultYear}-${String(m).padStart(2, '0')}-01`,
        text: item.text ?? '',
      };
    }
  }
  for (let i = 0; i < KOR_MONTHS.length; i++) {
    if (legacy.includes(KOR_MONTHS[i])) {
      return {
        id: item.id,
        date: `${defaultYear}-${String(i + 1).padStart(2, '0')}-01`,
        text: item.text ?? '',
      };
    }
  }
  return { id: item.id, date: item.date ?? '', text: item.text ?? '' };
}

export function todayIso(): string {
  const t = new Date();
  return `${t.getFullYear()}-${String(t.getMonth() + 1).padStart(2, '0')}-${String(t.getDate()).padStart(2, '0')}`;
}

/** 분기 문자열(2026-Q2) → date input min/max */
export function quarterDateBounds(quarter = '2026-Q2'): { min: string; max: string; year: number } {
  const m = quarter.match(/^(\d{4})-Q([1-4])$/);
  if (!m) {
    const y = new Date().getFullYear();
    return { min: `${y}-01-01`, max: `${y}-12-31`, year: y };
  }
  const year = Number(m[1]);
  const q = Number(m[2]);
  const startMonth = (q - 1) * 3 + 1;
  const endMonth = startMonth + 2;
  const lastDay = new Date(year, endMonth, 0).getDate();
  return {
    min: `${year}-${String(startMonth).padStart(2, '0')}-01`,
    max: `${year}-${String(endMonth).padStart(2, '0')}-${String(lastDay).padStart(2, '0')}`,
    year,
  };
}
