"use client"

import { create } from "zustand"
import { persist } from "zustand/middleware"
import { debouncedPersistJSONStorage } from "@/lib/stores/debounced-json-storage"

export type DriveViewMode = "list" | "grid"
export type DriveSortField = "name" | "size" | "date"
export type DriveFolderPlacement = "top" | "mixed"

interface DriveSettingsState {
  viewMode: DriveViewMode
  sortField: DriveSortField
  sortDir: "asc" | "desc"
  folderPlacement: DriveFolderPlacement
  setViewMode: (mode: DriveViewMode) => void
  setSort: (field: DriveSortField, dir: "asc" | "desc") => void
  setSortField: (field: DriveSortField) => void
  setSortDir: (dir: "asc" | "desc") => void
  setFolderPlacement: (placement: DriveFolderPlacement) => void
}

export const useDriveSettingsStore = create<DriveSettingsState>()(
  persist(
    (set) => ({
      viewMode: "list",
      sortField: "name",
      sortDir: "asc",
      folderPlacement: "top",
      setViewMode: (viewMode) => set({ viewMode }),
      setSort: (sortField, sortDir) => set({ sortField, sortDir }),
      setSortField: (sortField) => set({ sortField }),
      setSortDir: (sortDir) => set({ sortDir }),
      setFolderPlacement: (folderPlacement) => set({ folderPlacement }),
    }),
    {
      name: "ultidrive-settings",
      storage: debouncedPersistJSONStorage,
      merge: (persisted, current) => ({
        ...current,
        ...(persisted as Partial<DriveSettingsState>),
        folderPlacement:
          (persisted as Partial<DriveSettingsState>)?.folderPlacement ?? "top",
      }),
    }
  )
)
