import { isDesktop } from "@/lib/platform";
import { listen } from "@tauri-apps/api/event";
import { checkActualVpnStatus, setupVpnStatusListener } from "vpn-plugin";
import { create } from "zustand";

interface VpnState {
  status: "idle" | "connecting" | "connected";
  setStatus: (status: "idle" | "connecting" | "connected") => void;
  init: () => Promise<void>;
  _unlisten: (() => void) | null;
}

export const useVpnStore = create<VpnState>((set, get) => ({
  status: "idle",
  _unlisten: null,

  setStatus: (status) => set({ status }),
  init: async () => {
    if (get()._unlisten) return;

    try {
      let unlistenFn: () => void;

      if (isDesktop) {
        console.log("--- [PLATFORM] Инициализация Windows (Global Listen)");
        // На Windows слушаем прямой эмит из Rust: app.emit("status-change")
        const unlisten = await listen<{ status: string }>(
          "status-change",
          (event) => {
            set({ status: event.payload.status as any });
          },
        );
        unlistenFn = unlisten;
      } else {
        console.log("--- [PLATFORM] Инициализация Mobile (Plugin Listener)");
        // На Android используем нативную прослойку плагина
        const listener = await setupVpnStatusListener((event: any) => {
          const payload = event?.payload || event;
          set({ status: (payload.status || payload) as any });
        });
        unlistenFn = () => listener.unregister();
      }

      set({ _unlisten: unlistenFn });
    } catch (e) {
      console.error("Init error:", e);
    }
  },
}));
