"use client";

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

import {
  createRetainingStore,
  type RetainingStore,
} from "@/stores/retaining-store";

export type RetiningStoreApi = ReturnType<typeof createRetainingStore>;

export const RetainingStoreContext = createContext<
  RetiningStoreApi | undefined
>(undefined);

export interface RetainingStoreProviderProps {
  children: ReactNode;
}

export const RetainingStoreProvider = ({
  children,
}: RetainingStoreProviderProps) => {
  const storeRef = useRef<RetiningStoreApi | null>(null);
  if (storeRef.current === null) {
    storeRef.current = createRetainingStore();
  }

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

export const useRetainingStore = <T,>(
  selector: (store: RetainingStore) => T
): T => {
  const retainingStoreContext = useContext(RetainingStoreContext);

  if (!retainingStoreContext) {
    throw new Error(
      `useRetainingStore must be used within RetainingStoreProvider`
    );
  }

  return useStore(retainingStoreContext, selector);
};
