"use client"

import { useCallback, useState } from "react"

/**
 * 文本文件预览 hook：封装 fetch + 错误处理 + 状态机。
 *
 * 与 TextPreview 组件解耦，便于复用与测试。
 * 错误消息保留原始字符串，由组件层用 i18n 翻译。
 */
export interface UseFilePreviewReturn {
  content: string | null
  error: string | null
  loading: boolean
  load: (url: string) => Promise<void>
}

export function useFilePreview(): UseFilePreviewReturn {
  const [content, setContent] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [loading, setLoading] = useState(false)

  const load = useCallback(
    async (url: string): Promise<void> => {
      setLoading(true)
      setError(null)
      try {
        const res = await fetch(url)
        if (!res.ok) throw new Error(`HTTP ${res.status}`)
        const text = await res.text()
        setContent(text)
      } catch (e) {
        setError(e instanceof Error ? e.message : "Failed to load text")
      } finally {
        setLoading(false)
      }
    },
    []
  )

  return { content, error, loading, load }
}

/**
 * 图片预览缩放控制 hook
 */
export function useImageZoom(initial = 1, min = 0.25, max = 4): {
  zoom: number
  zoomIn: () => void
  zoomOut: () => void
  canZoomIn: boolean
  canZoomOut: boolean
} {
  const [zoom, setZoom] = useState(initial)
  const zoomIn = useCallback(() => setZoom((z) => Math.min(max, z + 0.25)), [max])
  const zoomOut = useCallback(() => setZoom((z) => Math.max(min, z - 0.25)), [min])
  return {
    zoom,
    zoomIn,
    zoomOut,
    canZoomIn: zoom < max,
    canZoomOut: zoom > min,
  }
}
