"use client";

import { create } from "zustand";

// 颜色常量
export const ERROR_COLORS = {
  success: "#52c41a",
  error: "#ff4d4f",
  warning: "#faad14",
  neutral: "#d9d9d9",
} as const;

type ErrorType = "network" | "server" | null;

interface ErrorState {
  // 网络断开状态
  isOffline: boolean;
  setIsOffline: (value: boolean) => void;

  // 服务器错误状态 (500)
  isServerError: boolean;
  serverErrorMessage: string;
  setServerError: (isError: boolean, message?: string) => void;
  clearServerError: () => void;

  // 当前主要错误类型（优先级：server > network）
  currentErrorType: ErrorType;
}

export const useErrorStore = create<ErrorState>((set, get) => ({
  // 首屏与 SSR 一致为 false；真实离线状态由 useNetworkStatus 在 mount 后同步
  isOffline: false,
  isServerError: false,
  serverErrorMessage: "服务器暂时不可用，请稍后重试",
  currentErrorType: null,

  // Actions
  setIsOffline: (value: boolean) => {
    set({ isOffline: value });
    // 更新当前错误类型
    const { isServerError } = get();
    if (isServerError) {
      set({ currentErrorType: "server" });
    } else if (value) {
      set({ currentErrorType: "network" });
    } else {
      set({ currentErrorType: null });
    }
  },

  setServerError: (isError: boolean, message?: string) => {
    set({
      isServerError: isError,
      serverErrorMessage: message || "服务器暂时不可用，请稍后重试",
    });
    // 更新当前错误类型 - 服务器错误优先级更高
    if (isError) {
      set({ currentErrorType: "server" });
    } else {
      const { isOffline } = get();
      set({ currentErrorType: isOffline ? "network" : null });
    }
  },

  clearServerError: () => {
    const { isOffline } = get();
    set({
      isServerError: false,
      currentErrorType: isOffline ? "network" : null,
    });
  },
}));
