import type { StateCreator } from "zustand";
import type { AppState } from "../types";
import { SELF_DEVICE_KEY, readSelfDevice, readInjectedDeviceName } from "../helpers";

// 这一片把"设备"语义全部合到一起：本机设备名 + Hub（SSE 连接 / 在线列表）。
// 它们都围绕"我有哪些设备、谁在线"这一问题。
export type DevicesSlice = Pick<
    AppState,
    "selfDeviceName" | "setSelfDeviceName"
    | "sseConnected" | "sseReconnecting" | "devices"
    | "setSseConnected" | "setSseReconnecting" | "setDevices"
>;

export const createDevicesSlice: StateCreator<AppState, [], [], DevicesSlice> = (set) =>
({
    // 桌面壳优先用启动注入的设备名（localStorage 在 wails:// 下不跨重启存活）；
    // 浏览器回落到 localStorage。
    selfDeviceName: readInjectedDeviceName() ?? readSelfDevice(),
    setSelfDeviceName: (name) =>
    {
        if (typeof window !== "undefined")
        {
            if (name) { window.localStorage.setItem(SELF_DEVICE_KEY, name); }
            else { window.localStorage.removeItem(SELF_DEVICE_KEY); }
        }
        set({ selfDeviceName: name });
    },

    sseConnected: false,
    sseReconnecting: false,
    devices: [],
    setSseConnected: (v) => set({ sseConnected: v }),
    setSseReconnecting: (v) => set({ sseReconnecting: v }),
    setDevices: (d) => set({ devices: d }),
});
