'use client'
import {createStore, StoreApi} from 'zustand/vanilla'
import {persist} from 'zustand/middleware'
import {createContext, ReactNode, useContext, useState} from 'react'
import {useStore} from 'zustand/react'

// store
export type ClientState = {
  breakpoint: {
    sm: boolean
    md: boolean
    lg: boolean
    xl: boolean
  }
}
export type ClientActions = {
  setBreakpoints: (breakpoints: Partial<ClientState['breakpoint']>) => void
}
export type ClientStore = ClientState & ClientActions

export const createClientStore = () => {
  return createStore<ClientStore>()(persist(
    setState => ({
      breakpoint: {
        sm: false,
        md: false,
        lg: false,
        xl: false,
      },
      setBreakpoints: breakpoints => setState(state => ({
        breakpoint: {
          ...state.breakpoint,
          ...breakpoints,
        },
      })),
    }),
    {
      name: 'client-store',
      partialize: state => ({
        device: state.breakpoint,
      }),
    },
  ))
}

// provider
const ClientStoreContext = createContext<StoreApi<ClientStore> | null>(null)

export const ClientStoreProvider = (props: {children: ReactNode}) => {
  const [store] = useState(() => createClientStore())
  return (
    <ClientStoreContext.Provider value={store}>
      {props.children}
    </ClientStoreContext.Provider>
  )
}

// consumer
export function useClientStore<T>(selector: (state: ClientStore) => T) {
  const store = useContext(ClientStoreContext)
  if (!store) {
    throw new Error('ClientStoreContext 没有正确初始化')
  }
  return useStore(store, selector)
}
