import { create } from 'zustand'
import { persist } from 'zustand/middleware'
import client from '../api/client'

const SETTINGS_KEY = 'waiter-favorites'

// itemFavorites shape: { [productId]: { quick: id[], ingredients: id[], options: id[], prefs: id[] } }
// Each array is an ordered list of IDs to show in that product's Favorites tab.
// If a product has no entry here, falls back to manager's is_favorite flags.

const useWaiterFavoritesStore = create(
  persist(
    (set, get) => ({
      favorites:     [],   // ordered product id list (which products appear in FAVORITES chip)
      quickNotes:    [],   // custom quick note strings
      itemFavorites: {},   // per-product attribute overrides (see shape above)

      toggleFavorite(productId) {
        set(state => {
          const exists = state.favorites.includes(productId)
          const favorites = exists
            ? state.favorites.filter(id => id !== productId)
            : [...state.favorites, productId]
          return { favorites }
        })
        get()._sync()
      },

      reorderFavorites(newOrder) {
        set({ favorites: newOrder })
        get()._sync()
      },

      // Replace the attribute favorites for a single product.
      // Pass null to clear (fall back to manager defaults).
      setItemFavorites(productId, attrFavs) {
        set(state => {
          const next = { ...state.itemFavorites }
          if (attrFavs == null) {
            delete next[productId]
          } else {
            next[productId] = attrFavs
          }
          return { itemFavorites: next }
        })
        get()._sync()
      },

      addQuickNote(note) {
        if (!note.trim()) return
        set(state => ({ quickNotes: [...state.quickNotes, note.trim()] }))
        get()._sync()
      },

      removeQuickNote(idx) {
        set(state => ({ quickNotes: state.quickNotes.filter((_, i) => i !== idx) }))
        get()._sync()
      },

      resetAll() {
        set({ favorites: [], quickNotes: [], itemFavorites: {} })
        get()._sync()
      },

      loadFromServer: async () => {
        try {
          const res = await client.get('/api/auth/me/settings')
          const raw = res.data?.settings
          if (!raw || raw === '{}') return
          const parsed = JSON.parse(raw)
          const slice = parsed[SETTINGS_KEY]
          if (slice) {
            set({
              favorites:     slice.favorites     ?? [],
              quickNotes:    slice.quickNotes    ?? [],
              itemFavorites: slice.itemFavorites ?? {},
            })
          }
          return parsed
        } catch { /* offline / not authed */ }
      },

      _sync: async () => {
        try {
          let existing = {}
          try {
            const res = await client.get('/api/auth/me/settings')
            existing = JSON.parse(res.data?.settings || '{}')
          } catch {}

          const { favorites, quickNotes, itemFavorites } = get()
          const merged = { ...existing, [SETTINGS_KEY]: { favorites, quickNotes, itemFavorites } }
          await client.put('/api/auth/me/settings', { settings: JSON.stringify(merged) })
        } catch { /* best-effort */ }
      },
    }),
    { name: SETTINGS_KEY }
  )
)

export default useWaiterFavoritesStore
