/* Calendar data layer — date utilities only. All events + groups come from
   Supabase (event_groups / calendar_events). No seed data. */

const WEEKDAYS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
const MONTHS = ['January','February','March','April','May','June','July','August','September','October','November','December'];

const pad = (n) => String(n).padStart(2, '0');
const keyOf = (y, m, d) => `${y}-${pad(m + 1)}-${pad(d)}`;
const dateKey = (dt) => keyOf(dt.getFullYear(), dt.getMonth(), dt.getDate());

function startOfMonth(y, m) { return new Date(y, m, 1); }
function daysInMonth(y, m) { return new Date(y, m + 1, 0).getDate(); }
function addMonths(dt, n) { return new Date(dt.getFullYear(), dt.getMonth() + n, 1); }
function addDays(dt, n) { const d = new Date(dt); d.setDate(d.getDate() + n); return d; }
function isSameDay(a, b) { return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate(); }

function mondayIndex(dt) { return (dt.getDay() + 6) % 7; }

function buildMonthGrid(y, m) {
  const first = startOfMonth(y, m);
  const lead = mondayIndex(first);
  const start = addDays(first, -lead);
  const cells = [];
  for (let i = 0; i < 42; i++) cells.push(addDays(start, i));
  return cells;
}

function startOfWeek(dt) { return addDays(dt, -mondayIndex(dt)); }

function fmtTime(mins, h24 = false) {
  let h = Math.floor(mins / 60);
  const mm = mins % 60;
  if (h24) return `${pad(h)}:${pad(mm)}`;
  const ap = h >= 12 ? 'PM' : 'AM';
  h = h % 12; if (h === 0) h = 12;
  return mm === 0 ? `${h} ${ap}` : `${h}:${pad(mm)} ${ap}`;
}

/* Palette for NEW groups the user creates (cycled). Existing groups keep their
   stored colour. These are the vibrant event-group hues from the design. */
const GROUP_PALETTE = ['#4D7CFE', '#FF7847', '#2EE6A8', '#C77DFF', '#FF4D6D', '#FFB454', '#5CE1E6', '#A0E548'];

/* Default groups seeded into a brand-new vault on first calendar open */
const DEFAULT_GROUPS = [
  { name: 'Work',      color: '#4D7CFE' },
  { name: 'Personal',  color: '#FF7847' },
  { name: 'Health',    color: '#2EE6A8' },
  { name: 'Social',    color: '#C77DFF' },
  { name: 'Deadlines', color: '#FF4D6D' },
];

Object.assign(window, {
  WEEKDAYS, MONTHS, pad, keyOf, dateKey, startOfMonth, daysInMonth,
  addMonths, addDays, isSameDay, mondayIndex, buildMonthGrid, startOfWeek,
  fmtTime, GROUP_PALETTE, DEFAULT_GROUPS,
});
