export interface OfflineEntry {
  id: string;
  type: "feed" | "diaper" | "sleep";
  data: any;
  timestamp: number;
}

const KEY = "tia_offline_queue";

export function getOfflineQueue(): OfflineEntry[] {
  if (typeof window === "undefined") return [];
  try {
    const d = localStorage.getItem(KEY);
    return d ? JSON.parse(d) : [];
  } catch { return []; }
}

export function addToOfflineQueue(entry: Omit<OfflineEntry, "id" | "timestamp">) {
  const q = getOfflineQueue();
  q.push({ ...entry, id: crypto.randomUUID(), timestamp: Date.now() });
  localStorage.setItem(KEY, JSON.stringify(q));
}

export async function processOfflineQueue() {
  const q = getOfflineQueue();
  if (q.length === 0) return;
  const failed: OfflineEntry[] = [];
  for (const entry of q) {
    try {
      await fetch("/api/logs", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(entry.data),
      });
    } catch { failed.push(entry); }
  }
  localStorage.setItem(KEY, JSON.stringify(failed));
}
