import { create } from "zustand";
import { createClient } from "@liveblocks/client";
import { liveblocks } from "@liveblocks/zustand";
import type { WithLiveblocks } from "@liveblocks/zustand";
import { api_endpoint } from "@/components/lib/utils";

type Cursor = { x: number; y: number } | null;

type State = {
  cursor: Cursor;
  name: string | null;
  id: string | null;
  profile_image: string | null;
};

type Actions = {
  reset: () => void;
  setCursor: (
    cursor: Cursor,
    name: string,
    id: string,
    profile_image: string
  ) => void;
};

// define the initial state
const initialState: State = {
  cursor: null,
  name: null,
  id: null,
  profile_image: null,
};

const client = createClient({
  publicApiKey:
    "pk_dev_OAz2s41ZtFEDmRbh2lmmJ41etqEJLxbtYNa3BNK32NQdv2RNDblrGCXxlFRyUyuU",
  // authEndpoint: `${api_endpoint}/system/realtime/${currentFlowId}?token=${token}`,
});

const useLiveblocks = create<WithLiveblocks<State & Actions>>()(
  liveblocks(
    (set) => ({
      ...initialState,
      setCursor: (
        _cursor: Cursor,
        _name: string,
        _id: string,
        _profile_image: string
      ) => {
        set({
          cursor: _cursor,
          name: _name,
          id: _id,
          profile_image: _profile_image,
        });
      },
      reset: () => {
        set(initialState);
      },
    }),
    {
      client,
      presenceMapping: {
        cursor: true,
        name: true,
        id: true,
        profile_image: true,
      },
    }
  )
);

export { useLiveblocks };
