const STORAGE_PREFIX = "flatrender-project-";

export interface LocalProjectSnapshot {
  scene_data: Record<string, unknown>;
  name?: string;
  savedAt: string;
}

export function localProjectStorageKey(projectId: string): string {
  return `${STORAGE_PREFIX}${projectId}`;
}

export function saveLocalProject(
  projectId: string,
  snapshot: Omit<LocalProjectSnapshot, "savedAt">
): void {
  if (typeof window === "undefined") return;

  const payload: LocalProjectSnapshot = {
    ...snapshot,
    savedAt: new Date().toISOString(),
  };

  window.localStorage.setItem(
    localProjectStorageKey(projectId),
    JSON.stringify(payload)
  );
}

export function loadLocalProject(projectId: string): LocalProjectSnapshot | null {
  if (typeof window === "undefined") return null;

  const raw = window.localStorage.getItem(localProjectStorageKey(projectId));
  if (!raw) return null;

  try {
    const parsed = JSON.parse(raw) as LocalProjectSnapshot;
    if (!parsed.scene_data || typeof parsed.scene_data !== "object") {
      return null;
    }
    return parsed;
  } catch {
    return null;
  }
}

export function isDevelopmentEnv(): boolean {
  return process.env.NODE_ENV === "development";
}
