import type { ProjectFormData } from "@/contexts/ProjectFormContext";

export type ProjectDraft = {
  id: string;
  step: number;
  formData: ProjectFormData;
  updatedAt: number;
  title: string;
};

const STORAGE_KEY = "projectDrafts";

function makeId() {
  if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
    return crypto.randomUUID();
  }
  return `draft-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
}

export function listProjectDrafts(): ProjectDraft[] {
  if (typeof window === "undefined") return [];
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return [];
    const parsed = JSON.parse(raw) as ProjectDraft[];
    return Array.isArray(parsed)
      ? parsed.sort((a, b) => b.updatedAt - a.updatedAt)
      : [];
  } catch {
    return [];
  }
}

export function getProjectDraft(id: string): ProjectDraft | null {
  return listProjectDrafts().find((d) => d.id === id) || null;
}

export function saveProjectDraft(input: {
  id?: string | null;
  step: number;
  formData: ProjectFormData;
}): ProjectDraft {
  const drafts = listProjectDrafts();
  const id = input.id || makeId();
  const next: ProjectDraft = {
    id,
    step: input.step,
    formData: input.formData,
    updatedAt: Date.now(),
    title: input.formData.projTitle?.trim() || "پیش‌نویس بدون عنوان",
  };
  const idx = drafts.findIndex((d) => d.id === id);
  if (idx >= 0) drafts[idx] = next;
  else drafts.unshift(next);
  localStorage.setItem(STORAGE_KEY, JSON.stringify(drafts.slice(0, 30)));
  return next;
}

export function removeProjectDraft(id: string) {
  const drafts = listProjectDrafts().filter((d) => d.id !== id);
  localStorage.setItem(STORAGE_KEY, JSON.stringify(drafts));
}
