"use client";

import { createContext, type ReactNode, useContext, useRef } from "react";
import { useStore } from "zustand";

import { AppUiStore, createAppUiStore } from "@/stores/app-ui-store";

export type AppUiStoreApi = ReturnType<typeof createAppUiStore>;

export const AppUiStoreContext = createContext<AppUiStoreApi | undefined>(
  undefined
);

export interface AppUiStoreProviderProps {
  children: ReactNode;
}

export const AppUiStoreProvider = ({ children }: AppUiStoreProviderProps) => {
  const storeRef = useRef<AppUiStoreApi | null>(null);
  if (storeRef.current === null) {
    storeRef.current = createAppUiStore();
  }

  return (
    <AppUiStoreContext.Provider value={storeRef.current}>
      {children}
    </AppUiStoreContext.Provider>
  );
};

export const useAppUiStore = <T,>(selector: (store: AppUiStore) => T): T => {
  const appUiStoreContext = useContext(AppUiStoreContext);

  if (!appUiStoreContext) {
    throw new Error(`useAppUiStore must be used within AppUiStoreProvider`);
  }

  return useStore(appUiStoreContext, selector);
};
