"use client";

// Fetch helper untuk client components. Selalu sertakan cookie (default same-origin).
// Jika access token kadaluarsa (401), coba "Lanjutkan" senyap lewat remember-token
// (lihat /api/auth/continue) sebelum mengarahkan ke /login — supaya Admin
// Cabang/Kurir tidak perlu login manual ulang di tengah pemakaian.
export async function api<T = any>(
  path: string,
  opts: RequestInit = {},
  _isRetry = false
): Promise<T> {
  const res = await fetch(path, {
    headers: { "Content-Type": "application/json", ...(opts.headers || {}) },
    ...opts,
  });
  if (res.status === 401 && typeof window !== "undefined" && !window.location.pathname.startsWith("/login")) {
    if (!_isRetry) {
      const resumed = await fetch("/api/auth/continue", { method: "POST" })
        .then((r) => r.ok)
        .catch(() => false);
      if (resumed) return api<T>(path, opts, true);
    }
    // Sesi tersimpan juga sudah habis — arahkan ke login alih-alih melempar
    // error tak tertangani ke setiap halaman yang polling data.
    window.location.href = `/login?next=${encodeURIComponent(window.location.pathname)}`;
    return new Promise<T>(() => {}); // tunda selamanya; halaman akan unload karena redirect
  }
  const json = await res.json().catch(() => ({}));
  if (!res.ok) throw new Error(json.error || `Error ${res.status}`);
  return json.data as T;
}

export const rupiah = (n: number) =>
  new Intl.NumberFormat("id-ID", { style: "currency", currency: "IDR", maximumFractionDigits: 0 }).format(n || 0);

// --- Penanda "pesan sudah dibaca" (per user, per perangkat) -----------------
// Dipakai lonceng notifikasi: pesan yang lebih baru dari timestamp ini dihitung
// sebagai belum dibaca. Cukup localStorage — tidak perlu tabel baru di DB.
const msgReadKey = (userId: string) => `msgReadAt:${userId}`;

export function getMsgReadAt(userId: string): string {
  if (typeof window === "undefined") return new Date(0).toISOString();
  return localStorage.getItem(msgReadKey(userId)) ?? new Date(0).toISOString();
}

export function markMsgRead(userId: string) {
  if (typeof window === "undefined") return;
  localStorage.setItem(msgReadKey(userId), new Date().toISOString());
}
