import React, { useState, useEffect, useCallback, useRef } from 'react';
import { createPortal } from 'react-dom';
import { FiArrowLeft, FiRefreshCw, FiAlertCircle } from 'react-icons/fi';
import clsx from 'clsx';

const LOAD_TIMEOUT_MS = 20000;

/**
 * 全屏网页嵌入组件
 *
 * @param {string}   title        - 顶栏标题
 * @param {string}   url          - 嵌入的网页地址
 * @param {function} onClose      - 关闭回调
 * @param {string}   headerColor  - 顶栏背景色 (默认 #4ade80)
 * @param {string}   iframeAllow  - iframe allow 属性
 * @param {function} onIframeLoad - iframe 加载完成的额外回调
 * @param {boolean}  autoFocus    - 加载完成后自动聚焦 iframe (游戏场景)
 * @param {boolean}  injectToken  - 自动向 iframe 注入 localStorage token
 */
const FullscreenEmbed = ({
  title,
  url,
  onClose,
  headerColor = '#4ade80',
  iframeAllow = 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share',
  onIframeLoad,
  autoFocus = false,
  injectToken = false,
}) => {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);
  const [closing, setClosing] = useState(false);
  const iframeRef = useRef(null);
  const timerRef = useRef(null);

  const handleClose = useCallback(() => {
    setClosing(true);
    setTimeout(() => onClose(), 230);
  }, [onClose]);

  useEffect(() => {
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';

    const onKey = (e) => { if (e.key === 'Escape') handleClose(); };
    document.addEventListener('keydown', onKey);

    timerRef.current = setTimeout(() => {
      if (loading) setError(true);
    }, LOAD_TIMEOUT_MS);

    return () => {
      document.body.style.overflow = prev;
      document.removeEventListener('keydown', onKey);
      clearTimeout(timerRef.current);
    };
  }, [handleClose, loading]);

  const handleIframeLoaded = useCallback((e) => {
    clearTimeout(timerRef.current);
    setLoading(false);
    setError(false);

    if (injectToken) {
      try {
        const token = localStorage.getItem('token');
        if (token && e.target.contentWindow) {
          e.target.contentWindow.localStorage.setItem('token', token);
        }
      } catch { /* cross-origin, ignore */ }
    }

    if (autoFocus && e.target) e.target.focus();
    if (onIframeLoad) onIframeLoad(e);
  }, [autoFocus, injectToken, onIframeLoad]);

  const handleRetry = useCallback(() => {
    setLoading(true);
    setError(false);
    clearTimeout(timerRef.current);
    timerRef.current = setTimeout(() => {
      if (loading) setError(true);
    }, LOAD_TIMEOUT_MS);
    if (iframeRef.current) {
      iframeRef.current.src = url;
    }
  }, [url, loading]);

  return createPortal(
    <div
      className={clsx(
        'fixed inset-0 z-[999999] flex flex-col bg-white font-[inherit]',
        closing
          ? 'animate-[slideDown_0.25s_ease-in_forwards]'
          : 'animate-[slideUp_0.3s_ease-out]',
      )}
      style={{
        '--tw-animate-slideUp': 'slideUp 0.3s ease-out',
        '--tw-animate-slideDown': 'slideDown 0.25s ease-in forwards',
      }}
    >
      <style>{`
        @keyframes slideUp { from { transform: translateY(100%); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
        @keyframes slideDown { from { transform: translateY(0); opacity: 1; } to { transform: translateY(100%); opacity: 0; } }
        @keyframes spinOnce { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
        @keyframes fIn { from { opacity: 0; } to { opacity: 1; } }
        .embed-overlay-enter { animation: slideUp 0.3s ease-out; }
        .embed-overlay-exit { animation: slideDown 0.25s ease-in forwards; }
        .embed-spinner { animation: spinOnce 0.7s linear infinite; }
        .embed-fade { animation: fIn 0.15s ease-out; }
      `}</style>

      {/* Header */}
      <div
        className="flex items-center justify-between gap-3 px-4 h-[52px] flex-shrink-0 text-white shadow-[0_2px_8px_rgba(0,0,0,0.12)] select-none"
        style={{ background: headerColor }}
      >
        <button
          onClick={handleClose}
          aria-label="返回"
          className="flex items-center justify-center gap-1.5 h-[34px] px-3.5 border-none rounded-lg bg-white/[0.18] text-white text-sm font-medium cursor-pointer transition-colors flex-shrink-0 hover:bg-white/30 active:bg-white/10"
        >
          <FiArrowLeft size={16} />
          返回
        </button>
        <h1 className="flex-1 m-0 text-base font-semibold whitespace-nowrap overflow-hidden text-ellipsis">
          {title}
        </h1>
        <button
          onClick={handleRetry}
          aria-label="刷新"
          className="flex items-center justify-center gap-1.5 h-[34px] px-3.5 border-none rounded-lg bg-white/[0.18] text-white text-sm font-medium cursor-pointer transition-colors flex-shrink-0 hover:bg-white/30 active:bg-white/10"
        >
          <FiRefreshCw size={14} />
        </button>
      </div>

      {/* Iframe Wrapper */}
      <div className="relative flex-1 overflow-hidden">
        <iframe
          ref={iframeRef}
          src={url}
          title={title}
          allow={iframeAllow}
          allowFullScreen
          loading="eager"
          onLoad={handleIframeLoaded}
          onError={() => { clearTimeout(timerRef.current); setError(true); }}
          className="block w-full h-full border-none bg-white"
        />

        {loading && !error && (
          <div className="absolute inset-0 flex flex-col items-center justify-center gap-4 bg-white embed-fade z-[2]">
            <div
              className="embed-spinner w-9 h-9 border-[3px] border-gray-200 rounded-full"
              style={{ borderTopColor: headerColor }}
            />
            <p className="m-0 text-sm text-gray-400">正在加载 {title}…</p>
          </div>
        )}

        {error && (
          <div className="absolute inset-0 flex flex-col items-center justify-center gap-4 bg-white z-[2] p-6 text-center">
            <FiAlertCircle className="text-red-500 text-5xl" />
            <h2 className="m-0 text-lg font-semibold text-gray-800">页面加载失败</h2>
            <p className="m-0 text-sm text-gray-500 max-w-[320px] leading-relaxed">
              无法加载「{title}」，请检查网络连接后重试
            </p>
            <button
              onClick={handleRetry}
              className="flex items-center gap-1.5 px-6 py-2.5 border-none rounded-[10px] bg-gradient-to-br from-[#4ade80] to-[#22c55e] text-white text-sm font-semibold cursor-pointer transition-all hover:-translate-y-px hover:shadow-[0_4px_12px_rgba(74,222,128,0.35)]"
            >
              <FiRefreshCw size={14} />
              重新加载
            </button>
          </div>
        )}
      </div>
    </div>,
    document.body,
  );
};

export default FullscreenEmbed;
