import type { TFunction } from "i18next";

export const TIMED_MESSAGE_SECONDS = [
  null,
  10,
  30,
  60,
  300,
  3600,
] as const;

const TIMED_MESSAGE_KEYS = [
  "chats.timed.off",
  "chats.timed.10s",
  "chats.timed.30s",
  "chats.timed.1m",
  "chats.timed.5m",
  "chats.timed.1h",
] as const;

export function getTimedMessageOptions(t: TFunction) {
  return TIMED_MESSAGE_SECONDS.map((value, index) => ({
    value,
    label: t(TIMED_MESSAGE_KEYS[index]),
  }));
}

export function formatTimedLabel(seconds: number | null, t: TFunction): string {
  const index = TIMED_MESSAGE_SECONDS.indexOf(
    seconds as (typeof TIMED_MESSAGE_SECONDS)[number]
  );
  if (index >= 0) return t(TIMED_MESSAGE_KEYS[index]);
  return t("chats.timed.off");
}

export function getRemainingSeconds(expiresAt?: string | null): number | null {
  if (!expiresAt) return null;
  const ms = new Date(expiresAt).getTime() - Date.now();
  if (Number.isNaN(ms) || ms <= 0) return 0;
  return Math.ceil(ms / 1000);
}

export function formatCountdown(totalSeconds: number): string {
  if (totalSeconds >= 3600) {
    const h = Math.floor(totalSeconds / 3600);
    const m = Math.floor((totalSeconds % 3600) / 60);
    return `${h}:${String(m).padStart(2, "0")}`;
  }
  const m = Math.floor(totalSeconds / 60);
  const s = totalSeconds % 60;
  return `${m}:${String(s).padStart(2, "0")}`;
}

export function buildExpiresAtIso(seconds: number | null): string | undefined {
  if (!seconds) return undefined;
  return new Date(Date.now() + seconds * 1000).toISOString();
}
