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

const slideUp = keyframes`
  from { transform: translateY(100%); opacity: 0; }
  to   { transform: translateY(0);    opacity: 1; }
`;

const slideDown = keyframes`
  from { transform: translateY(0);    opacity: 1; }
  to   { transform: translateY(100%); opacity: 0; }
`;

const spin = keyframes`
  from { transform: rotate(0deg); }
  to   { transform: rotate(360deg); }
`;

const fadeIn = keyframes`
  from { opacity: 0; }
  to   { opacity: 1; }
`;

const Overlay = styled.div`
  position: fixed;
  inset: 0;
  z-index: 999999;
  display: flex;
  flex-direction: column;
  background: #fff;
  font-family: inherit;
  animation: ${({ $closing }) => $closing ? css`${slideDown} 0.25s ease-in forwards` : css`${slideUp} 0.3s ease-out`};
`;

const Header = styled.div`
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  padding: 0 16px;
  height: 52px;
  flex-shrink: 0;
  background: ${({ $color }) => $color};
  color: #fff;
  box-shadow: 0 2px 8px rgba(0,0,0,0.12);
  user-select: none;
  -webkit-tap-highlight-color: transparent;
`;

const HeaderTitle = styled.h1`
  flex: 1;
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
`;

const HeaderBtn = styled.button`
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
  height: 34px;
  padding: 0 14px;
  border: none;
  border-radius: 8px;
  background: rgba(255,255,255,0.18);
  color: #fff;
  font-size: 13px;
  font-weight: 500;
  cursor: pointer;
  transition: background 0.2s;
  flex-shrink: 0;
  &:hover { background: rgba(255,255,255,0.3); }
  &:active { background: rgba(255,255,255,0.1); }
`;

const IframeWrapper = styled.div`
  position: relative;
  flex: 1;
  overflow: hidden;
`;

const StyledIframe = styled.iframe`
  display: block;
  width: 100%;
  height: 100%;
  border: none;
  background: #fff;
`;

const LoadingOverlay = styled.div`
  position: absolute;
  inset: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 16px;
  background: #fff;
  animation: ${fadeIn} 0.15s ease-out;
  z-index: 2;
`;

const Spinner = styled.div`
  width: 36px;
  height: 36px;
  border: 3px solid #e5e7eb;
  border-top-color: ${({ $color }) => $color};
  border-radius: 50%;
  animation: ${spin} 0.7s linear infinite;
`;

const LoadingText = styled.p`
  margin: 0;
  font-size: 14px;
  color: #9ca3af;
`;

const ErrorOverlay = styled.div`
  position: absolute;
  inset: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 16px;
  background: #fff;
  z-index: 2;
  padding: 24px;
  text-align: center;
`;

const ErrorIcon = styled(FiAlertCircle)`
  color: #ef4444;
  font-size: 48px;
`;

const ErrorTitle = styled.h2`
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
`;

const ErrorDesc = styled.p`
  margin: 0;
  font-size: 14px;
  color: #6b7280;
  max-width: 320px;
  line-height: 1.5;
`;

const RetryButton = styled.button`
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 10px 24px;
  border: none;
  border-radius: 10px;
  background: linear-gradient(135deg, #4ade80 0%, #22c55e 100%);
  color: #fff;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: transform 0.15s, box-shadow 0.15s;
  &:hover { transform: translateY(-1px); box-shadow: 0 4px 12px rgba(74,222,128,0.35); }
`;

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(
    <Overlay $closing={closing}>
      <Header $color={headerColor}>
        <HeaderBtn onClick={handleClose} aria-label="返回">
          <FiArrowLeft size={16} />
          返回
        </HeaderBtn>
        <HeaderTitle>{title}</HeaderTitle>
        <HeaderBtn onClick={handleRetry} aria-label="刷新">
          <FiRefreshCw size={14} />
        </HeaderBtn>
      </Header>

      <IframeWrapper>
        <StyledIframe
          ref={iframeRef}
          src={url}
          title={title}
          allow={iframeAllow}
          allowFullScreen
          loading="eager"
          onLoad={handleIframeLoaded}
          onError={() => { clearTimeout(timerRef.current); setError(true); }}
        />

        {loading && !error && (
          <LoadingOverlay>
            <Spinner $color={headerColor} />
            <LoadingText>正在加载 {title}…</LoadingText>
          </LoadingOverlay>
        )}

        {error && (
          <ErrorOverlay>
            <ErrorIcon />
            <ErrorTitle>页面加载失败</ErrorTitle>
            <ErrorDesc>无法加载「{title}」，请检查网络连接后重试</ErrorDesc>
            <RetryButton onClick={handleRetry}>
              <FiRefreshCw size={14} />
              重新加载
            </RetryButton>
          </ErrorOverlay>
        )}
      </IframeWrapper>
    </Overlay>,
    document.body
  );
};

export default FullscreenEmbed;
