// Client-sichere Präsenz-Definitionen (kein Prisma/Server-Import).
export type Presence = "online" | "away" | "offline" | "vacation";

export type PresenceInfo = { status: Presence; lastSeen: string | null };

export const PRESENCE_META: Record<Presence, { label: string; color: string }> = {
  online: { label: "Online", color: "#7ee787" },
  away: { label: "Abwesend", color: "#ffc36b" },
  offline: { label: "Offline", color: "#8aa0c8" },
  vacation: { label: "Urlaub / Abwesenheit", color: "#c8bcff" },
};

/** Relative Zeitangabe („vor 5 Min.", „vor 2 Std.", „vor 3 Tagen"). */
export function relTime(iso: string): string {
  const diff = Date.now() - new Date(iso).getTime();
  const m = Math.floor(diff / 60000);
  if (m < 1) return "gerade eben";
  if (m < 60) return `vor ${m} Min.`;
  const h = Math.floor(m / 60);
  if (h < 24) return `vor ${h} Std.`;
  const d = Math.floor(h / 24);
  return `vor ${d} ${d === 1 ? "Tag" : "Tagen"}`;
}

/** Anzeigetext für einen Präsenzstatus (mit „zuletzt vor …" bei abwesend/offline). */
export function presenceLabel(info: PresenceInfo | Presence | undefined): string {
  if (!info) return "Offline";
  const status = typeof info === "string" ? info : info.status;
  const lastSeen = typeof info === "string" ? null : info.lastSeen;
  if (status === "online") return "Online";
  if (status === "vacation") return "Urlaub / Abwesenheit";
  if (lastSeen) return `Zuletzt ${relTime(lastSeen)}`;
  return status === "away" ? "Abwesend" : "Offline";
}

const ONLINE_MS = 3 * 60 * 1000; // zuletzt aktiv < 3 min → online
const AWAY_MS = 15 * 60 * 1000; // < 15 min → abwesend, sonst offline

/** Leitet den Präsenzstatus aus letzter Aktivität + Abwesenheit ab. */
export function computePresence(
  lastSeenAt: Date | string | null | undefined,
  onLeave: boolean,
): Presence {
  if (onLeave) return "vacation";
  if (!lastSeenAt) return "offline";
  const t = typeof lastSeenAt === "string" ? new Date(lastSeenAt).getTime() : lastSeenAt.getTime();
  const age = Date.now() - t;
  if (age < ONLINE_MS) return "online";
  if (age < AWAY_MS) return "away";
  return "offline";
}
