'use client'

import { useState, useEffect, useCallback } from 'react'

type CardSizeMode = 'variable' | 'uniform'

export function useCardSizeMode(): CardSizeMode {
  const [mode, setMode] = useState<CardSizeMode>('variable')

  useEffect(() => {
    // Check localStorage first (for immediate UI response)
    const stored = localStorage.getItem('card-size-mode') as CardSizeMode | null
    if (stored && (stored === 'variable' || stored === 'uniform')) {
      setMode(stored)
    }

    // Listen for storage changes (when user changes setting in another tab)
    const handleStorageChange = (e: StorageEvent) => {
      if (e.key === 'card-size-mode') {
        const newMode = e.newValue as CardSizeMode | null
        if (newMode && (newMode === 'variable' || newMode === 'uniform')) {
          setMode(newMode)
        }
      }
    }

    window.addEventListener('storage', handleStorageChange)
    return () => window.removeEventListener('storage', handleStorageChange)
  }, [])

  return mode
}

export function useIsUniformSize(): boolean {
  const mode = useCardSizeMode()
  return mode === 'uniform'
}
