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

const STORAGE_KEY = 'calctext-fontsize'
const DEFAULT_SIZE = 15
export const MIN_FONT_SIZE = 11
export const MAX_FONT_SIZE = 24

function getStoredFontSize(): number {
  try {
    const stored = localStorage.getItem(STORAGE_KEY)
    if (stored) {
      const n = parseInt(stored, 10)
      if (n >= MIN_FONT_SIZE && n <= MAX_FONT_SIZE) return n
    }
  } catch { /* localStorage unavailable */ }
  return DEFAULT_SIZE
}

export function useFontSize() {
  const [fontSize, setFontSizeState] = useState(getStoredFontSize)

  const setFontSize = useCallback((size: number) => {
    const clamped = Math.max(MIN_FONT_SIZE, Math.min(MAX_FONT_SIZE, size))
    setFontSizeState(clamped)
    try { localStorage.setItem(STORAGE_KEY, String(clamped)) } catch { /* */ }
    document.documentElement.style.setProperty('--editor-font-size', `${clamped}px`)
  }, [])

  const resetFontSize = useCallback(() => {
    setFontSize(DEFAULT_SIZE)
  }, [setFontSize])

  // Apply on mount
  useEffect(() => {
    document.documentElement.style.setProperty('--editor-font-size', `${fontSize}px`)
  }, []) // eslint-disable-line react-hooks/exhaustive-deps

  return { fontSize, setFontSize, resetFontSize, MIN_SIZE: MIN_FONT_SIZE, MAX_SIZE: MAX_FONT_SIZE }
}
