import { computed, ref } from "vue";
import { defineStore } from "pinia";
import type { Toast } from "@/types";

export const useAppStore = defineStore("app", () => {
  const sidebarCollapsed = ref(false);
  const mobileOpen = ref(false);
  const loadingCount = ref(0);
  const toasts = ref<Toast[]>([]);
  const siteName = ref("HWLAB Cloud Web");
  const siteLogo = ref("/favicon.svg");
  let toastCounter = 0;

  const loading = computed(() => loadingCount.value > 0);
  const hasActiveToasts = computed(() => toasts.value.length > 0);

  function setLoading(active: boolean): void {
    loadingCount.value = active ? loadingCount.value + 1 : Math.max(0, loadingCount.value - 1);
  }

  function showToast(type: Toast["type"], message: string, duration = 4000): string {
    const id = `toast-${++toastCounter}`;
    toasts.value.push({ id, type, message, duration });
    if (duration > 0) window.setTimeout(() => hideToast(id), duration);
    return id;
  }

  function showSuccess(message: string, duration = 3000): string {
    return showToast("success", message, duration);
  }

  function showError(message: string, duration = 5000): string {
    return showToast("error", message, duration);
  }

  function showInfo(message: string, duration = 4000): string {
    return showToast("info", message, duration);
  }

  function showWarning(message: string, duration = 5000): string {
    return showToast("warning", message, duration);
  }

  function hideToast(id: string): void {
    toasts.value = toasts.value.filter((toast) => toast.id !== id);
  }

  function initFromInjectedConfig(): void {
    const title = document.title.trim();
    if (title) siteName.value = title;
  }

  return { sidebarCollapsed, mobileOpen, loading, hasActiveToasts, toasts, siteName, siteLogo, setLoading, showToast, showSuccess, showError, showInfo, showWarning, hideToast, initFromInjectedConfig };
});
