import { useEffect, useRef } from 'react';
import { LoadingWrapper } from './styled';

export const ModelContentLoading = () => {
  const containerRef = useRef<any>(null);
  const scaleTargetRef = useRef<any>(null);
  const init = () => {
    const container = containerRef.current;
    const scaleTarget = scaleTargetRef.current;

    let resizeTimeout;

    function updateScale() {
      if (!container || !scaleTarget) {
        return;
      }
      const w = container.clientWidth;
      const scale = 0.5 * (w / 656);
      scaleTarget.style.setProperty(
        '--scale',
        w > 0 && scale > 0 ? scale : 0.5,
      );
    }

    // 首次 & 防抖监听尺寸变化
    updateScale();
    window.addEventListener('resize', function () {
      clearTimeout(resizeTimeout);
      resizeTimeout = setTimeout(updateScale, 100);
    });
  };
  useEffect(() => {
    init();
  }, []);

  return (
    <LoadingWrapper>
      <div className="loading-bar" ref={containerRef}>
        <div className="center-scale" ref={scaleTargetRef}>
          <div className="rotor" />
        </div>
        <span className="loading-bar__icon" aria-hidden="true" />
        <span className="loading-bar__text">AI 分析中…</span>
      </div>
    </LoadingWrapper>
  );
};
