import React, { useEffect } from 'react';
import helpsUrl from '@/pages/help/helps.html?url';
import jqueryUrl from './helps/jquery.js?url';
import bootstrapUrl from './helps/bootstrap.js?url';
import pluginUrl from './helps/plugin.js?url';
import xformUrl from './helps/xform.js?url';
import bootstrapCssUrl from './helps/bootstrap.css?url';
import pluginCssUrl from './helps/plugin.css?url';

const HelpPage: React.FC = () => {
  const iframeRef = React.useRef<HTMLIFrameElement>(null);

  useEffect(() => {
    const iframe = iframeRef.current;
    if (!iframe) return;

    const onLoad = () => {
      try {
        const doc = iframe.contentDocument || iframe.contentWindow?.document;
        if (!doc) return;

        // 注入脚本和样式的完整路径
        const scripts = doc.querySelectorAll('script[src*="helps/"]');
        scripts.forEach((script: any) => {
          const src = script.getAttribute('src');
          if (src?.includes('jquery.js')) {
            script.setAttribute('src', jqueryUrl);
          } else if (src?.includes('bootstrap.js')) {
            script.setAttribute('src', bootstrapUrl);
          } else if (src?.includes('plugin.js')) {
            script.setAttribute('src', pluginUrl);
          } else if (src?.includes('xform.js')) {
            script.setAttribute('src', xformUrl);
          }
        });

        // 修复样式路径
        const links = doc.querySelectorAll('link[rel="stylesheet"]');
        links.forEach((link: any) => {
          const href = link.getAttribute('href');
          if (href?.includes('bootstrap.css')) {
            link.setAttribute('href', bootstrapCssUrl);
          } else if (href?.includes('plugin.css')) {
            link.setAttribute('href', pluginCssUrl);
          }
        });
      } catch (error) {
        console.error('Failed to update iframe resources:', error);
      }
    };

    iframe.addEventListener('load', onLoad);
    return () => iframe.removeEventListener('load', onLoad);
  }, []);

  return (
    <div style={{ width: '100%', height: '100vh', overflow: 'hidden' }}>
      <iframe
        ref={iframeRef}
        src={helpsUrl}
        style={{ width: '100%', height: '100%', border: 'none' }}
        title="Help Content"
      />
    </div>
  );
};

export default HelpPage;