import { create } from 'zustand'
import { createJSONStorage, persist, type StateStorage } from 'zustand/middleware'

export interface LocaleStore {
  locale: string
  setLocale: (locale: string) => void
}

export interface CreateLocaleStoreOptions {
  defaultLocale: string
  storageKey?: string
  storage?: StateStorage
}

export function createLocaleStore(options: CreateLocaleStoreOptions) {
  const { defaultLocale, storageKey = 'platform_locale', storage } = options
  return create<LocaleStore>()(
    persist(
      (set) => ({
        locale: defaultLocale,
        setLocale: (locale) => set({ locale }),
      }),
      {
        name: storageKey,
        ...(storage ? { storage: createJSONStorage(() => storage) } : {}),
      },
    ),
  )
}

/** Cookie-backed persist storage for hosts that prefer cookie over localStorage. */
export function createCookieStorage(cookieName: string): StateStorage {
  return {
    getItem: () => {
      if (typeof document === 'undefined') return null
      const match = document.cookie.match(new RegExp(`(?:^|;\\s*)${cookieName}=([^;]*)`))
      return match?.[1] ? decodeURIComponent(match[1]) : null
    },
    setItem: (_key, value) => {
      if (typeof document === 'undefined') return
      document.cookie = `${cookieName}=${encodeURIComponent(value)};path=/;max-age=31536000;samesite=lax`
    },
    removeItem: () => {
      if (typeof document === 'undefined') return
      document.cookie = `${cookieName}=;path=/;max-age=0`
    },
  }
}
