import React from 'react';
import { cn } from '@/utils/cn';

interface HtmlProps {
  className?: string;
  content?: string;
}

// 注入脚本，拦截 iframe 中的 _blank 链接和 window.open
function injectInterceptScript(iframeWindow: Window) {
  try {
    // 检查是否可以访问 iframe 的 document（避免跨域错误）
    const iframeDocument = iframeWindow.document;
    if (!iframeDocument) {
      return;
    }

    // 保存父窗口的 window.open 引用
    const parentWindowOpen = window.open.bind(window);

    // 重写 iframe 内的 window.open
    iframeWindow.open = function (url, target, features) {
      return parentWindowOpen(url, target, features);
    };

    // 拦截所有 <a> 标签的点击事件
    iframeDocument.addEventListener(
      'click',
      (e: MouseEvent) => {
        const target = e.target as HTMLElement;
        const anchor = target.closest('a');

        if (anchor && anchor.target === '_blank') {
          e.preventDefault();
          const href = anchor.href;
          if (href) {
            parentWindowOpen(href, '_blank');
          }
        }
      },
      true,
    );

    // 监听动态添加的元素
    const observer = new MutationObserver(() => {
      // 重新绑定 window.open (防止被覆盖)
      if (iframeWindow.open !== parentWindowOpen) {
        iframeWindow.open = function (url, target, features) {
          return parentWindowOpen(url, target, features);
        };
      }
    });

    observer.observe(iframeDocument.documentElement, {
      childList: true,
      subtree: true,
    });
  } catch {
    // 跨域或沙箱限制，无法注入脚本，静默失败
    // 这种情况下需要依赖 sandbox 属性中的 allow-popups-to-escape-sandbox
  }
}

export const Html = React.forwardRef(
  (
    { className, content }: HtmlProps,
    _ref: React.ForwardedRef<HTMLIFrameElement>,
  ) => {
    // 当 iframe 加载完成后注入拦截脚本
    const handleIframeLoad = React.useCallback(
      (e: React.SyntheticEvent<HTMLIFrameElement, Event>) => {
        const iframe = e.currentTarget;
        if (iframe?.contentWindow) {
          injectInterceptScript(iframe.contentWindow);
        }
      },
      [],
    );

    // if (content) {
    //   // 在 content 中添加 base 标签，确保所有链接在 iframe 内部打开
    //   const contentWithBase = content.includes("<head>")
    //     ? content.replace("<head>", '<head><base href="about:srcdoc">')
    //     : content;

    //   return (
    //     <iframe
    //       ref={_ref}
    //       className={cn("w-full border-none", className)}
    //       srcDoc={contentWithBase}
    //       sandbox="allow-scripts allow-popups allow-popups-to-escape-sandbox"
    //       onLoad={handleIframeLoad}
    //     />
    //   );
    // }

    return (
      <iframe
        ref={_ref}
        className={cn('w-full border-none', className)}
        srcDoc={`${content}`}
        sandbox="allow-same-origin allow-scripts allow-popups allow-popups-to-escape-sandbox"
        onLoad={handleIframeLoad}
      />
    );
  },
);

// export function copyLink(path: string, taskId: string) {
//   const encodedPath = path
//     .split('/')
//     .map(segment => encodeURIComponent(segment))
//     .join('/')
//   const url = `${window.location.origin}/web/${taskId}${encodedPath}`
//   navigator.clipboard.writeText(url)
// }

// export function openHtml(path: string, taskId: string) {
//   const url = `/web/${taskId}${path}`
//   window.open(url, '_blank')
// }

// export async function zipHtml(path: string, taskId: string) {
//   const api = `${process.env.API_BASE_URL_SUB}/novakit/api/v1/webpage/zip?file=${encodeURIComponent(path)}&taskId=${taskId}`
//   download({ url: api, name: `${taskId}.zip` })
// }