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

/**
 * WebView 链接无效/加载失败时的兜底占位逻辑。
 * - 输入：effectiveUrl（当前生效的 URL）、onContentReady（用于关闭全局 Loading）、baseOnLoadStart（原始 onLoadStart）。
 * - 输出：fallbackActive（是否展示占位）、failInfo（失败信息）、handleLoadStart、onError、onHttpError、dismissFallback。
 */
export const useWebviewFallback = (effectiveUrl, onContentReady, baseOnLoadStart) => {
  const [failed, setFailed] = useState(false)
  const [failInfo, setFailInfo] = useState(null)

  const fallbackActive = !effectiveUrl || failed

  useEffect(() => {
    if (fallbackActive) {
      try { onContentReady && onContentReady() } catch (_) {}
    }
  }, [fallbackActive, onContentReady])

  const handleLoadStart = useCallback((...args) => {
    setFailed(false)
    setFailInfo(null)
    if (typeof baseOnLoadStart === 'function') baseOnLoadStart(...args)
  }, [baseOnLoadStart])

  const onError = useCallback((e) => {
    const desc = e?.nativeEvent?.description
    setFailed(true)
    setFailInfo({ type: 'error', desc })
  }, [])

  const onHttpError = useCallback((e) => {
    const status = e?.nativeEvent?.statusCode
    if (status >= 400) {
      setFailed(true)
      setFailInfo({ type: 'http', status, url: e?.nativeEvent?.url })
    }
  }, [])

  const dismissFallback = useCallback(() => {
    setFailed(false)
    setFailInfo(null)
  }, [])

  return { fallbackActive, failInfo, handleLoadStart, onError, onHttpError, dismissFallback }
}