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

/**
 * 未保存提醒 hook
 * UX-01: 接受外部 confirm 函数，替代原生 confirm()
 */
export function useUnsavedWarning(
  hasUnsaved: () => boolean,
  confirmFn?: (message: string) => Promise<boolean>,
  // D5: 关闭前回调（flush 待保存数据）
  onBeforeForceClose?: () => Promise<void>
) {
  const confirmFnRef = useRef(confirmFn)
  confirmFnRef.current = confirmFn
  const onBeforeForceCloseRef = useRef(onBeforeForceClose)
  onBeforeForceCloseRef.current = onBeforeForceClose

  const doConfirm = useCallback(async (message: string): Promise<boolean> => {
    if (confirmFnRef.current) {
      return confirmFnRef.current(message)
    }
    // 后备方案：如果没有提供 confirmFn，使用 beforeunload 行为
    return true
  }, [])

  useEffect(() => {
    if (!window.electronAPI) {
      const handler = (e: BeforeUnloadEvent) => {
        if (hasUnsaved()) {
          e.preventDefault()
          e.returnValue = ''
        }
      }
      window.addEventListener('beforeunload', handler)
      return () => window.removeEventListener('beforeunload', handler)
    }

    const api = window.electronAPI

    const unsubscribe = api.onConfirmClose(async () => {
      if (!hasUnsaved()) {
        await onBeforeForceCloseRef.current?.()
        api.forceClose()
        return
      }
      const shouldClose = await doConfirm('有文件尚未保存，确定要关闭吗？')
      if (shouldClose) {
        await onBeforeForceCloseRef.current?.()
        api.forceClose()
      } else {
        api.cancelClose()
      }
    })

    return unsubscribe
  }, [hasUnsaved, doConfirm])
}
