'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 LayoutState = {
  navbar: boolean
}
export type LayoutActions = {
  toggleNavbar: () => void
  setNavbar: (navbar: boolean) => void
}
export type LayoutStore = LayoutState & LayoutActions

export const createLayoutStore = () => {
  return createStore<LayoutStore>()(persist(
    setState => ({
      navbar: false,
      toggleNavbar: () => setState((state) => {
        return {navbar: !state.navbar}
      }),
      setNavbar: navbar => setState((_) => {
        return {navbar}
      }),
    }),
    {
      name: 'layout-store',
      partialize: state => ({
        navbar: state.navbar,
      }),
    },
  ))
}

// provider
const LayoutStoreContext = createContext<StoreApi<LayoutStore> | null>(null)

export const LayoutStoreProvider = (props: {children: ReactNode}) => {
  const [store] = useState(() => createLayoutStore())
  return (
    <LayoutStoreContext.Provider value={store}>
      {props.children}
    </LayoutStoreContext.Provider>
  )
}

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