/**
 * Pure timer state machine for the pomodoro plugin.
 *
 * A running round stores only its absolute `endAt`; the remaining time is
 * derived from the wall clock, so tab throttling, sleep, or a page refresh
 * cannot accumulate drift. Paused/idle rounds store an exact `remainingMs`.
 */

export const STATE_VERSION = 1;

export const MODE_ORDER = Object.freeze(['focus', 'shortBreak', 'test']);

export const MODES = Object.freeze({
  focus: Object.freeze({ durationMs: 25 * 60 * 1000 }),
  shortBreak: Object.freeze({ durationMs: 5 * 60 * 1000 }),
  test: Object.freeze({ durationMs: 60 * 1000 }),
});

const STATUSES = new Set(['idle', 'running', 'paused', 'complete']);

function normalizeMode(mode) {
  return Object.prototype.hasOwnProperty.call(MODES, mode) ? mode : 'focus';
}

function clamp(value, min, max) {
  return Math.min(max, Math.max(min, value));
}

function finiteNumber(value) {
  return typeof value === 'number' && Number.isFinite(value);
}

/** Return the fixed duration of a mode, falling back to focus. */
export function durationOf(mode) {
  return MODES[normalizeMode(mode)].durationMs;
}

/** Build a fresh idle round in focus mode. */
export function createInitialState() {
  return {
    version: STATE_VERSION,
    mode: 'focus',
    durationMs: durationOf('focus'),
    status: 'idle',
    remainingMs: durationOf('focus'),
    endAt: null,
    completedAt: null,
    noticeDismissed: false,
    completionCount: 0,
  };
}

/**
 * Parse a persisted snapshot and repair anything that cannot be trusted.
 * A running round that expired while the page was closed completes here.
 */
export function hydrate(raw, now = Date.now()) {
  let value = raw;
  if (typeof raw === 'string') {
    try {
      value = JSON.parse(raw);
    } catch {
      return createInitialState();
    }
  }
  if (value === null || typeof value !== 'object' || value.version !== STATE_VERSION) {
    return createInitialState();
  }

  const mode = normalizeMode(value.mode);
  const durationMs = durationOf(mode);
  const status = STATUSES.has(value.status) ? value.status : 'idle';
  const completionCount = Number.isInteger(value.completionCount) && value.completionCount >= 0
    ? value.completionCount
    : 0;
  const noticeDismissed = value.noticeDismissed === true;
  const base = {
    version: STATE_VERSION,
    mode,
    durationMs,
    status: 'idle',
    remainingMs: durationMs,
    endAt: null,
    completedAt: null,
    noticeDismissed,
    completionCount,
  };

  if (status === 'running' && finiteNumber(value.endAt) && value.endAt > 0) {
    return sync({ ...base, status: 'running', endAt: value.endAt }, now);
  }
  if (status === 'paused') {
    const remainingMs = clamp(
      finiteNumber(value.remainingMs) ? value.remainingMs : durationMs,
      0,
      durationMs,
    );
    if (remainingMs <= 0) {
      return {
        ...base,
        status: 'complete',
        remainingMs: 0,
        completedAt: finiteNumber(value.completedAt) ? value.completedAt : now,
        noticeDismissed,
        completionCount,
      };
    }
    return { ...base, status: 'paused', remainingMs };
  }
  if (status === 'complete') {
    return {
      ...base,
      status: 'complete',
      remainingMs: 0,
      completedAt: finiteNumber(value.completedAt) ? value.completedAt : now,
    };
  }
  return base;
}

/** Remaining wall-clock time for a snapshot. */
export function remainingMs(state, now = Date.now()) {
  if (state.status === 'complete') return 0;
  if (state.status === 'running' && finiteNumber(state.endAt)) {
    return Math.max(0, state.endAt - now);
  }
  return clamp(state.remainingMs, 0, state.durationMs);
}

/**
 * Advance a running round. Completion happens exactly once: later calls on a
 * completed state return the same reference and do not add another notice.
 */
export function sync(state, now = Date.now()) {
  if (state.status !== 'running' || !finiteNumber(state.endAt)) return state;
  if (state.endAt > now) return state;
  return {
    ...state,
    status: 'complete',
    remainingMs: 0,
    endAt: null,
    completedAt: now,
    noticeDismissed: false,
    completionCount: state.completionCount + 1,
  };
}

/** Start a new round from idle or completed; paused rounds use resume(). */
export function start(state, now = Date.now()) {
  if (state.status !== 'idle' && state.status !== 'complete') return state;
  const durationMs = durationOf(state.mode);
  return {
    ...state,
    status: 'running',
    durationMs,
    remainingMs: durationMs,
    endAt: now + durationMs,
    completedAt: null,
    noticeDismissed: false,
  };
}

/** Freeze a running round at its wall-clock remaining time. */
export function pause(state, now = Date.now()) {
  if (state.status !== 'running' || !finiteNumber(state.endAt)) return state;
  const left = state.endAt - now;
  if (left <= 0) return sync(state, now);
  return {
    ...state,
    status: 'paused',
    remainingMs: left,
    endAt: null,
  };
}

/** Continue a paused round from exactly the frozen remaining time. */
export function resume(state, now = Date.now()) {
  if (state.status !== 'paused') return state;
  const left = clamp(state.remainingMs, 0, state.durationMs);
  if (left <= 0) return state;
  return {
    ...state,
    status: 'running',
    remainingMs: left,
    endAt: now + left,
  };
}

/** Reset the current mode to a fresh idle round. */
export function reset(state) {
  const durationMs = durationOf(state.mode);
  return {
    ...state,
    status: 'idle',
    durationMs,
    remainingMs: durationMs,
    endAt: null,
    completedAt: null,
    noticeDismissed: false,
  };
}

/** Switch mode and reset the countdown; the completion counter is retained. */
export function setMode(state, mode) {
  const nextMode = normalizeMode(mode);
  if (nextMode === state.mode && state.status === 'idle') return state;
  const durationMs = durationOf(nextMode);
  return {
    ...state,
    mode: nextMode,
    status: 'idle',
    durationMs,
    remainingMs: durationMs,
    endAt: null,
    completedAt: null,
    noticeDismissed: false,
  };
}

/** Mark the one completion notice as seen. */
export function dismissNotice(state) {
  if (state.status !== 'complete' || state.noticeDismissed) return state;
  return { ...state, noticeDismissed: true };
}

/** Format milliseconds as MM:SS, rounding up so a fresh 60s round says 01:00. */
export function formatClock(ms) {
  const totalSeconds = Math.max(0, Math.ceil(ms / 1000));
  const minutes = Math.floor(totalSeconds / 60).toString().padStart(2, '0');
  const seconds = (totalSeconds % 60).toString().padStart(2, '0');
  return `${minutes}:${seconds}`;
}

/** Fraction of the current round that has elapsed, from 0 to 1. */
export function progressOf(state, now = Date.now()) {
  if (state.durationMs <= 0) return 0;
  return clamp(1 - remainingMs(state, now) / state.durationMs, 0, 1);
}
