// Agenda — date utilities, categories.
// Dates are RELATIVE to the real "today" so the app always feels alive.
// All display strings are looked up live via window.t() so they follow the
// current user language (see src/i18n/).

const TODAY = (() => { const d = new Date(); d.setHours(0,0,0,0); return d; })();

function stripTime(d) { const x = new Date(d); x.setHours(0,0,0,0); return x; }
function addDays(d, n) { const x = stripTime(d); x.setDate(x.getDate() + n); return x; }
function daysBetween(a, b) { return Math.round((stripTime(b) - stripTime(a)) / 86400000); }
function isSameDay(a, b) { return stripTime(a).getTime() === stripTime(b).getTime(); }
function startOfWeek(d) {                                       // Monday as week start
  const x = stripTime(d);
  const wd = (x.getDay() + 6) % 7;
  return addDays(x, -wd);
}
function startOfMonth(d) { const x = stripTime(d); x.setDate(1); return x; }
function endOfMonth(d)   { const x = stripTime(d); x.setMonth(x.getMonth()+1, 0); return x; }
function fmtShort(d)     { return `${d.getDate()} ${t('monthsShort')[d.getMonth()]}`; }
function fmtWeekday(d)   { return t('weekdaysLong')[d.getDay()]; }
function fmtLongDate(d)  {
  const joiner = t('dateJoiner');
  return `${t('weekdaysLong')[d.getDay()]} ${d.getDate()} ${joiner}${t('monthsLong')[d.getMonth()]}`;
}
function fmtDayMonth(d) {
  const joiner = t('dateJoiner');
  return `${d.getDate()} ${joiner}${t('monthsLong')[d.getMonth()]}`;
}
function fmtMonthYear(d) { return `${t('monthsLong')[d.getMonth()]} ${d.getFullYear()}`; }
function toISODate(d)    { const x = stripTime(d); return `${x.getFullYear()}-${String(x.getMonth()+1).padStart(2,'0')}-${String(x.getDate()).padStart(2,'0')}`; }
function fromISODate(s)  { if (!s) return null; const [y,m,dd] = s.split('-').map(Number); return new Date(y, m-1, dd); }

function relativeLabel(d) {
  const n = daysBetween(TODAY, d);
  if (n < -1) return t('relative.daysAgo', { n: -n });
  if (n === -1) return t('relative.yesterday');
  if (n === 0) return t('relative.today');
  if (n === 1) return t('relative.tomorrow');
  if (n < 7) return t('relative.inDays', { n });
  if (n < 14) return t('relative.nextWeek');
  if (n < 31) return t('relative.inDays', { n });
  const months = Math.round(n / 30);
  return months === 1 ? t('relative.inMonth') : t('relative.inMonths', { n: months });
}

// Categories — warm, calm, ~equal chroma. Stable keys; labels are translated at render time via t('cat.<key>').
const CATEGORIES = {
  feina:    { dot: 'oklch(0.58 0.12 255)' },
  estudi:   { dot: 'oklch(0.62 0.11 200)' },
  personal: { dot: 'oklch(0.62 0.13 35)'  },
  salut:    { dot: 'oklch(0.6 0.10 155)'  },
  casa:     { dot: 'oklch(0.6 0.09 325)'  },
  social:   { dot: 'oklch(0.7 0.13 75)'   },
};
const CAT_KEYS = Object.keys(CATEGORIES);
function catLabel(key) { return t('cat.' + key); }

// A brand new account starts completely empty — no seeded demo data.
function makeDemo() {
  return [];
}

// Bucket items by urgency. Past items go into `overdue`.
function bucketize(items, today = TODAY) {
  const out = { overdue: [], today: [], tomorrow: [], thisWeek: [], later: [] };
  const sunEnd = addDays(startOfWeek(today), 6);
  items.forEach(it => {
    const d = fromISODate(it.date);
    if (!d) return;
    const n = daysBetween(today, d);
    if (n < 0) out.overdue.push(it);
    else if (n === 0) out.today.push(it);
    else if (n === 1) out.tomorrow.push(it);
    else if (d <= sunEnd) out.thisWeek.push(it);
    else out.later.push(it);
  });
  Object.values(out).forEach(arr => arr.sort((a, b) => {
    const dateDiff = fromISODate(a.date) - fromISODate(b.date);
    if (dateDiff !== 0) return dateDiff;
    if (a.time && b.time) return a.time.localeCompare(b.time);
    if (a.time) return -1;
    if (b.time) return 1;
    return 0;
  }));
  return out;
}

Object.assign(window, {
  TODAY,
  stripTime, addDays, daysBetween, isSameDay, startOfWeek, startOfMonth, endOfMonth,
  fmtShort, fmtWeekday, fmtLongDate, fmtDayMonth, fmtMonthYear, toISODate, fromISODate, relativeLabel,
  CATEGORIES, CAT_KEYS, catLabel, makeDemo, bucketize,
});
