// Testable clock. In dev/test mode, callers can shift time forward to exercise
// the scheduler without waiting for real wall-clock hours/days.

let offsetMs = 0;

export function now() {
  return new Date(Date.now() + offsetMs);
}

export function nowIso() {
  return now().toISOString();
}

export function advance(ms) {
  offsetMs += ms;
  return offsetMs;
}

export function reset() {
  offsetMs = 0;
}

// Set the simulated clock to a specific moment. `target` can be an ISO 8601
// string or a Date. Used by the dev demo UI's date+time pickers.
export function setTime(target) {
  const date = target instanceof Date ? target : new Date(target);
  if (isNaN(date.getTime())) throw new Error(`setTime: invalid target ${target}`);
  offsetMs = date.getTime() - Date.now();
  return offsetMs;
}

export function getOffsetMs() {
  return offsetMs;
}

export function zurichParts(d = now()) {
  const fmt = new Intl.DateTimeFormat('en-GB', {
    timeZone: 'Europe/Zurich',
    year: 'numeric', month: '2-digit', day: '2-digit',
    hour: '2-digit', minute: '2-digit', hour12: false,
  });
  const parts = Object.fromEntries(fmt.formatToParts(d).map(p => [p.type, p.value]));
  return {
    date: `${parts.year}-${parts.month}-${parts.day}`,
    hour: Number(parts.hour),
    minute: Number(parts.minute),
  };
}
