// Shared toast store. Pages call `pushToast(message, variant?)`; a single
// <ToastHost /> mounted in +layout.svelte renders the result. Replacing a
// live toast cancels its timer so the new message gets the full duration,
// and bumps `id` so the host's {#key} block re-mounts the node — important
// for screen readers, which won't re-announce text changes inside an
// already-live region.

type ToastVariant = 'info' | 'error';

interface Toast {
  id: number;
  message: string;
  variant: ToastVariant;
}

let _toast = $state<Toast | null>(null);
let _timer: ReturnType<typeof setTimeout> | null = null;
let _next = 0;

export const toast = {
  get value(): Toast | null {
    return _toast;
  }
};

export function pushToast(
  message: string,
  variant: ToastVariant = 'info',
  durationMs = 5000
): void {
  if (_timer) clearTimeout(_timer);
  _toast = { id: ++_next, message, variant };
  _timer = setTimeout(() => {
    _toast = null;
    _timer = null;
  }, durationMs);
}

export function clearToast(): void {
  if (_timer) clearTimeout(_timer);
  _timer = null;
  _toast = null;
}
