import { useCallback, useState } from 'react'

/**
 * WebView 刷新与重挂载逻辑（统一菜单刷新/初始刷新）。
 * 提供：webViewKey, incognitoReload, manualUrl, setManualUrl, refreshCurrent(url), refreshInitial(initialUrl)
 * 依赖：startDetectWindow（来自 useWhiteScreenGuard）与 addCacheBuster（由外部传入）
 */
export const useWebviewReload = (startDetectWindow, addCacheBuster) => {
  const [manualUrl, setManualUrl] = useState(null)
  const [webViewKey, setWebViewKey] = useState(0)
  const [incognitoReload, setIncognitoReload] = useState(false)

  const refreshCurrent = useCallback((targetUrl) => {
    startDetectWindow('menu')
    setIncognitoReload(true)
    setWebViewKey((k) => k + 1)
    setManualUrl(addCacheBuster(targetUrl))
  }, [startDetectWindow, addCacheBuster])

  const refreshInitial = useCallback((initialUrl) => {
    startDetectWindow('menu')
    setWebViewKey((k) => k + 1)
    setManualUrl(addCacheBuster(initialUrl))
  }, [startDetectWindow, addCacheBuster])

  return {
    manualUrl,
    setManualUrl,
    webViewKey,
    incognitoReload,
    setIncognitoReload,
    refreshCurrent,
    refreshInitial,
  }
}