// #region dashboard-helpers [C:1] [TYPE Module]
// @BRIEF Shared helper functions for dashboard views — date formatting, pagination, sort indicators.
// @LAYER lib

export function formatDate(value: string | number | Date | null | undefined): string {
  if (!value) return "-";
  const parsed = new Date(value);
  if (Number.isNaN(parsed.getTime())) return "-";
  return `${parsed.toLocaleDateString()} ${parsed.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}`;
}

export function getPaginationRange(currentPage: number, totalPages: number): (number | "...")[] {
  if (totalPages <= 7) {
    return Array.from({ length: totalPages }, (_, i) => i + 1);
  }

  const pages: (number | "...")[] = [];

  pages.push(1);

  if (currentPage > 3) {
    pages.push("...");
  }

  const start = Math.max(2, currentPage - 1);
  const end = Math.min(totalPages - 1, currentPage + 1);

  for (let i = start; i <= end; i++) {
    pages.push(i);
  }

  if (currentPage < totalPages - 2) {
    pages.push("...");
  }

  pages.push(totalPages);

  return pages;
}

export function getSortIndicator(
  sortColumn: string | null,
  columnName: string,
  sortDirection: "asc" | "desc" | null,
): string {
  if (sortColumn !== columnName || !sortDirection) return "";
  return sortDirection === "asc" ? " ▲" : " ▼";
}

export function normalizeOwners(owners: unknown): string[] {
  if (!owners) return [];
  if (Array.isArray(owners)) {
    return owners.map((o: unknown) => {
      if (typeof o === "string") return o;
      if (o && typeof o === "object" && "name" in (o as Record<string, unknown>)) return String((o as Record<string, unknown>).name);
      return String(o);
    });
  }
  if (typeof owners === "string") {
    return owners.split(",").map((s: string) => s.trim()).filter(Boolean);
  }
  return [];
}

export function normalizeTaskStatus(status: unknown): string {
  if (!status) return "unknown";
  const s = String(status).toLowerCase().trim();
  const map: Record<string, string> = {
    pending: "pending",
    running: "running",
    success: "success",
    completed: "completed",
    failed: "failed",
    cancelled: "cancelled",
    skipped: "skipped",
    error: "error",
  };
  return map[s] || s;
}

export function normalizeValidationStatus(status: unknown): string {
  if (!status) return "unknown";
  const s = String(status).toLowerCase().trim();
  const map: Record<string, string> = {
    passed: "passed",
    failed: "failed",
    warning: "warning",
    pending: "pending",
    running: "running",
    error: "error",
    not_run: "not_run",
    skipped: "skipped",
  };
  return map[s] || s;
}
// #endregion dashboard-helpers
