// 自动保存的纯逻辑：防抖调度器 + 时间格式化。与 React 解耦，便于单测。

export const AUTOSAVE_DELAY_MS = 1200;

export type SaveFn = (text: string) => Promise<void>;

export interface DebouncedSaver {
  schedule: (text: string) => void;
  flush: () => void;
  cancel: () => void;
}

// 防抖：最后一次输入静默 delayMs 后才真正保存。flush 立即触发待保存项。
export function createDebouncedSaver(
  save: SaveFn,
  delayMs: number = AUTOSAVE_DELAY_MS,
): DebouncedSaver {
  let timer: ReturnType<typeof setTimeout> | null = null;
  let pending: string | null = null;

  const run = (): void => {
    if (pending === null) return;
    const text = pending;
    pending = null;
    timer = null;
    void save(text);
  };

  return {
    schedule(text: string): void {
      pending = text;
      if (timer !== null) clearTimeout(timer);
      timer = setTimeout(run, delayMs);
    },
    flush(): void {
      if (timer !== null) clearTimeout(timer);
      run();
    },
    cancel(): void {
      if (timer !== null) clearTimeout(timer);
      timer = null;
      pending = null;
    },
  };
}

// 「保存于 hh:mm」标签。
export function formatSavedAt(date: Date): string {
  const hh = String(date.getHours()).padStart(2, "0");
  const mm = String(date.getMinutes()).padStart(2, "0");
  return `保存于 ${hh}:${mm}`;
}
