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, options?: { title?: string; copyText?: string }) {
      const item: ToastItem = {
        id: nextId++,
        type,
        title: options?.title || typeTitle(type),
        message,
        copyText: options?.copyText,
        duration: 5000,
      };
      if (this.visible.length < 3) this.visible.push(item);
      else this.queued.push(item);
      return item.id;
    },
    success(message: string) {
      return this.show("success", message);
    },
    warning(message: string) {
      return this.show("warning", message);
    },
    error(message: string, copyText?: string) {
      return this.show("error", message, { copyText });
    },
    remove(id: number) {
      this.visible = this.visible.filter((item) => item.id !== id);
      const next = this.queued.shift();
      if (next) this.visible.push(next);
    },
  },
});

function typeTitle(type: ToastType) {
  return { success: "操作成功", warning: "请注意", error: "操作失败", info: "提示" }[type];
}
