"use client"

import { useEffect, useMemo, useState } from "react"
import { useSearchParams } from "next/navigation"

export default function DocumentationCapturePage() {
  const searchParams = useSearchParams()
  const path = searchParams.get("path") || "/"
  const [loaded, setLoaded] = useState(false)
  const [timeoutReached, setTimeoutReached] = useState(false)
  const [loadError, setLoadError] = useState<string | null>(null)

  const src = useMemo(() => {
    if (!path.startsWith("/")) return `/${path}`
    return path
  }, [path])

  useEffect(() => {
    setLoaded(false)
    setTimeoutReached(false)
    setLoadError(null)

    const timer = window.setTimeout(() => {
      if (!loaded) {
        setTimeoutReached(true)
      }
    }, 60000)

    return () => window.clearTimeout(timer)
  }, [src, loaded])

  const handleLoad = () => {
    setLoaded(true)
    setTimeoutReached(false)
  }

  const handleError = () => {
    setLoadError("页面加载失败")
  }

  return (
    <main className="min-h-screen bg-white flex items-center justify-center">
      <div className="w-[430px] h-[932px] border border-gray-200 bg-white relative overflow-hidden">
        <iframe
          data-doc-iframe="true"
          data-loaded={loaded ? "true" : "false"}
          src={src}
          className="w-full h-full border-0"
          onLoad={handleLoad}
          onError={handleError}
          title={`Capture: ${path}`}
          sandbox="allow-scripts allow-same-origin allow-forms allow-popups"
        />

        {!loaded && !timeoutReached && !loadError && (
          <div className="absolute inset-0 bg-white flex items-center justify-center">
            <div className="text-center">
              <div className="w-8 h-8 border-2 border-gray-300 border-t-gray-600 rounded-full animate-spin mx-auto mb-2" />
              <p className="text-sm text-gray-500">加载中...</p>
            </div>
          </div>
        )}
      </div>

      {(timeoutReached || loadError) && (
        <div className="fixed left-0 top-0 right-0 bg-red-600 text-white text-sm px-3 py-2 text-center">
          {loadError || "页面加载超时"}
        </div>
      )}

      {loaded && (
        <div className="fixed left-0 bottom-0 right-0 bg-green-600 text-white text-xs px-3 py-1 text-center">
          页面已加载: {path}
        </div>
      )}
    </main>
  )
}
