import { defineStore, acceptHMRUpdate } from 'pinia';

type FolderItemType = 'icon' | 'widget';
type FolderSize = '1x1' | '1x2' | '2x1' | '2x2' | '2x4';

export interface FolderItem {
  id: string;
  type: FolderItemType;
}

export interface Folder {
  id: string;
  name: string;
  items: FolderItem[];
  groupId?: string;
  size?: FolderSize;
}

interface FolderState {
  folders: Folder[];
}

const DEFAULT_GROUP_ID = 'home';
const STORAGE_KEY = 'itab_folders';

const normalizeFolderName = (name?: string) => {
  const trimmed = (name ?? '').trim();
  if (!trimmed || trimmed === '组') return '文件夹';
  return trimmed;
};

const normalizeFolder = (folder: Folder): Folder => ({
  id: folder.id,
  name: normalizeFolderName(folder.name),
  groupId: folder.groupId ?? DEFAULT_GROUP_ID,
  size: folder.size ?? '1x1',
  items: Array.isArray(folder.items)
    ? folder.items
        .filter(item => item && typeof item.id === 'string' && (item.type === 'icon' || item.type === 'widget'))
        .map(item => ({ id: item.id, type: item.type }))
    : []
});

const loadFolders = (): Folder[] => {
  const raw = localStorage.getItem(STORAGE_KEY);
  if (!raw) return [];
  try {
    const parsed = JSON.parse(raw) as Folder[];
    if (!Array.isArray(parsed)) return [];
    return parsed.map(normalizeFolder);
  } catch {
    return [];
  }
};

export const useFoldersStore = defineStore('folders', {
  state: (): FolderState => ({
    folders: loadFolders(),
  }),
  actions: {
    persist() {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(this.folders));
    },
    addFolder(payload: { name?: string; items?: FolderItem[]; groupId?: string; size?: FolderSize }) {
      const nextId = `folder-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
      const folder: Folder = normalizeFolder({
        id: nextId,
        name: normalizeFolderName(payload.name),
        items: payload.items ?? [],
        groupId: payload.groupId ?? DEFAULT_GROUP_ID,
        size: payload.size ?? '1x1',
      });
      this.folders.push(folder);
      this.persist();
      return folder;
    },
    renameFolder(folderId: string, name: string) {
      const folder = this.folders.find(item => item.id === folderId);
      if (!folder) return;
      folder.name = normalizeFolderName(name);
      this.persist();
    },
    updateFolderSize(folderId: string, size: FolderSize) {
      const folder = this.folders.find(item => item.id === folderId);
      if (!folder) return;
      folder.size = size;
      this.persist();
    },
    addItem(folderId: string, item: FolderItem) {
      const folder = this.folders.find(f => f.id === folderId);
      if (!folder) return;
      const exists = folder.items.some(it => it.id === item.id && it.type === item.type);
      if (!exists) {
        folder.items.push({ id: item.id, type: item.type });
        this.persist();
      }
    },
    removeItem(folderId: string, itemId: string, itemType: FolderItemType) {
      const folder = this.folders.find(f => f.id === folderId);
      if (!folder) return;
      folder.items = folder.items.filter(item => !(item.id === itemId && item.type === itemType));
      if (!folder.items.length) {
        this.deleteFolder(folderId);
      } else {
        this.persist();
      }
    },
    deleteFolder(folderId: string) {
      const idx = this.folders.findIndex(f => f.id === folderId);
      if (idx !== -1) {
        this.folders.splice(idx, 1);
        this.persist();
      }
    },
    clearEmptyFolders() {
      const before = this.folders.length;
      this.folders = this.folders.filter(folder => folder.items.length > 0);
      if (this.folders.length !== before) {
        this.persist();
      }
    },
  }
});

if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(useFoldersStore, import.meta.hot));
}
