const DRAFT_KEY = "qa-draft";
const LAST_PLACEHOLDER_KEY = "qa-last-placeholder";
const relativeTime = new Intl.RelativeTimeFormat(undefined, {
  numeric: "auto",
});

function getValidDate(dateString: string): Date | null {
  const date = new Date(dateString);
  return Number.isNaN(date.getTime()) ? null : date;
}

export function readQuestionDraft(): string {
  try {
    return localStorage.getItem(DRAFT_KEY) ?? "";
  } catch {
    return "";
  }
}

export function writeQuestionDraft(value: string) {
  try {
    localStorage.setItem(DRAFT_KEY, value);
  } catch {
    // Ignore storage failures.
  }
}

export function clearQuestionDraft() {
  try {
    localStorage.removeItem(DRAFT_KEY);
  } catch {
    // Ignore storage failures.
  }
}

export function formatDateOnly(dateString: string): string {
  const date = getValidDate(dateString);
  if (!date) return dateString;

  return date.toISOString().slice(0, 10);
}

export function formatFriendlyDate(dateString: string): string {
  const date = getValidDate(dateString);
  if (!date) return dateString;

  const now = Date.now();
  const diffMs = date.getTime() - now;
  const diffMinutes = Math.round(diffMs / 60000);
  const diffHours = Math.round(diffMs / 3600000);
  const diffDays = Math.round(diffMs / 86400000);

  if (Math.abs(diffMinutes) < 60)
    return relativeTime.format(diffMinutes, "minute");
  if (Math.abs(diffHours) < 24) return relativeTime.format(diffHours, "hour");
  if (Math.abs(diffDays) < 14) return relativeTime.format(diffDays, "day");

  return formatDateOnly(dateString);
}

export function pickPlaceholder<T>(items: readonly T[]): T {
  if (items.length === 1) return items[0]!;

  let lastIndex = -1;
  try {
    lastIndex = Number.parseInt(
      sessionStorage.getItem(LAST_PLACEHOLDER_KEY) ?? "",
      10,
    );
  } catch {
    lastIndex = -1;
  }

  let nextIndex = Math.floor(Math.random() * items.length);
  if (nextIndex === lastIndex) {
    nextIndex =
      (nextIndex + 1 + Math.floor(Math.random() * (items.length - 1))) %
      items.length;
  }

  try {
    sessionStorage.setItem(LAST_PLACEHOLDER_KEY, String(nextIndex));
  } catch {
    // Ignore storage failures.
  }

  return items[nextIndex]!;
}
