import { defineStore } from "pinia";

export type ToastType = "success" | "warning" | "error" | "info";
export interface ToastItem {
  id: number;
  type: ToastType;
  title: string;
  message: string;
  copyText?: string;
  duration: number;
}
let nextId = 1;
export const useToastStore = defineStore("toast", {
  state: () => ({ visible: [] as ToastItem[], queued: [] as ToastItem[] }),
  actions: {
    show(type: ToastType, message: string, copyText?: string, title?: string) {
      const item = {
        id: nextId++,
        type,
        title: title || ({ success: "操作成功", warning: "请注意", error: "请求失败", info: "提示" } as const)[type],
        message,
        copyText,
        duration: 5000,
      };
      if (this.visible.length >= 3) this.visible.shift();
      this.visible.push(item);
    },
    success(message: string) {
      this.show("success", message);
    },
    warning(message: string) {
      this.show("warning", message);
    },
    info(message: string) {
      this.show("info", message);
    },
    error(message: string, copyText?: string, title?: string) {
      this.show("error", message, copyText, title);
    },
    remove(id: number) {
      this.visible = this.visible.filter((item) => item.id !== id);
      const next = this.queued.shift();
      if (next) this.visible.push(next);
    },
  },
});
