import type { WebAssetItem } from "../../types";

export type AssetLibraryCategory = WebAssetItem["type"];

export interface SavedAssetItem extends WebAssetItem {
  project: string;
  version: string;
  ratio: string;
  tags: string[];
  thumbClass: string;
}

const SAVED_ASSETS_STORAGE_KEY = "omniai-canvas-saved-assets";

export function getSavedAssets(): SavedAssetItem[] {
  if (typeof window === "undefined") return [];

  try {
    const rawAssets = window.localStorage.getItem(SAVED_ASSETS_STORAGE_KEY);
    if (!rawAssets) return [];
    const parsedAssets = JSON.parse(rawAssets);
    return Array.isArray(parsedAssets) ? parsedAssets : [];
  } catch {
    return [];
  }
}

export function saveAssetToLocalLibrary(asset: {
  type: AssetLibraryCategory;
  name: string;
  description?: string;
  url?: string;
  imageUrl?: string;
  tags?: string[];
}) {
  const savedAsset: SavedAssetItem = {
    id: `canvas-asset-${Date.now()}`,
    type: asset.type,
    name: asset.name,
    description: asset.description || "从画布保存的素材。",
    imageUrl: asset.imageUrl || asset.url || "",
    url: asset.url || asset.imageUrl || "",
    updatedAt: "刚刚更新",
    status: "ready",
    project: "画布",
    version: "V1",
    ratio: "1:1",
    tags: asset.tags?.length ? asset.tags : ["画布素材"],
    thumbClass: "is-uploaded",
  };

  if (typeof window !== "undefined") {
    const nextAssets = [savedAsset, ...getSavedAssets()];
    window.localStorage.setItem(SAVED_ASSETS_STORAGE_KEY, JSON.stringify(nextAssets));
  }

  return savedAsset;
}
