"use client";

import { LoadingState, ErrorState, EmptyState } from "@/components/ds";
import { SportsCenterApiError } from "@/modules/sports-center/services/sports-center-api";

export function SportsCenterPageLoader({ label = "در حال بارگذاری…" }: { label?: string }) {
  return <LoadingState label={label} />;
}

export function SportsCenterPageError({
  error,
  onRetry,
}: {
  error: unknown;
  onRetry?: () => void;
}) {
  if (error instanceof SportsCenterApiError && error.status === 403) {
    return (
      <EmptyState
        title="دسترسی محدود"
        description={error.message || "مجوز لازم برای این عملیات وجود ندارد."}
      />
    );
  }
  const message = error instanceof Error ? error.message : "خطا در دریافت داده‌ها";
  return <ErrorState message={message} onRetry={onRetry} />;
}

export function exportToCsv(title: string, rows: Record<string, unknown>[], columns: string[]) {
  if (rows.length === 0) return;
  const header = columns.join(",");
  const body = rows
    .map((r) => columns.map((c) => JSON.stringify(r[c] ?? "")).join(","))
    .join("\n");
  const blob = new Blob(["\uFEFF" + header + "\n" + body], { type: "text/csv;charset=utf-8" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = `${title}-export.csv`;
  a.click();
  URL.revokeObjectURL(url);
}
