"use client"

import { create } from "zustand"

interface MailUiState {
  sidebarCollapsed: boolean
  mobileSearchOpen: boolean
  folderUnreadCounts: Record<string, number>
  /** Skip split-view auto-open of first row once (back, sidebar folder change). */
  suppressSplitAutoOpenOnce: boolean
}

interface MailUiActions {
  setSidebarCollapsed: (collapsed: boolean) => void
  toggleSidebarCollapsed: () => void
  setMobileSearchOpen: (open: boolean) => void
  setFolderUnreadCounts: (counts: Record<string, number>) => void
  requestSuppressSplitAutoOpen: () => void
  consumeSuppressSplitAutoOpen: () => boolean
}

export const useMailUiStore = create<MailUiState & MailUiActions>()((set, get) => ({
  sidebarCollapsed: true,
  mobileSearchOpen: false,
  folderUnreadCounts: {},
  suppressSplitAutoOpenOnce: false,

  setSidebarCollapsed: (collapsed) => set({ sidebarCollapsed: collapsed }),
  toggleSidebarCollapsed: () =>
    set((s) => ({ sidebarCollapsed: !s.sidebarCollapsed })),
  setMobileSearchOpen: (open) => set({ mobileSearchOpen: open }),
  setFolderUnreadCounts: (counts) => set({ folderUnreadCounts: counts }),
  requestSuppressSplitAutoOpen: () => set({ suppressSplitAutoOpenOnce: true }),
  consumeSuppressSplitAutoOpen: () => {
    if (!get().suppressSplitAutoOpenOnce) return false
    set({ suppressSplitAutoOpenOnce: false })
    return true
  },
}))
