import { create } from 'zustand'

/** Preset thumbnail sizes (px) for grid views — Timeline, Memories,
 *  Duplicates. The preview filmstrip is intentionally NOT affected; it
 *  keeps its own fixed 72px tracks because its job is to be a narrow
 *  navigation rail, not a re-sizeable grid.
 *
 *  Values picked to roughly double the cell area between steps without
 *  breaking the existing 160px default — old sessions land back on
 *  "medium" with no visible jump. */
export const THUMBNAIL_SIZE_PRESETS = [96, 128, 160, 208, 272] as const
export type ThumbnailSizeLevel = typeof THUMBNAIL_SIZE_PRESETS[number]

export const DEFAULT_THUMBNAIL_SIZE: ThumbnailSizeLevel = 160

const STORAGE_KEY = 'muli.viewSettings.thumbnailSize'

function loadInitialSize(): ThumbnailSizeLevel {
  if (typeof window === 'undefined') return DEFAULT_THUMBNAIL_SIZE
  const raw = window.localStorage.getItem(STORAGE_KEY)
  const n = raw === null ? NaN : Number(raw)
  return (THUMBNAIL_SIZE_PRESETS as readonly number[]).includes(n)
    ? (n as ThumbnailSizeLevel)
    : DEFAULT_THUMBNAIL_SIZE
}

interface ViewSettingsStore {
  thumbnailSize: ThumbnailSizeLevel
  setThumbnailSize: (size: ThumbnailSizeLevel) => void
}

export const useViewSettingsStore = create<ViewSettingsStore>((set) => ({
  thumbnailSize: loadInitialSize(),
  setThumbnailSize: (thumbnailSize) => {
    if (typeof window !== 'undefined') {
      window.localStorage.setItem(STORAGE_KEY, String(thumbnailSize))
    }
    set({ thumbnailSize })
  },
}))
