import { useEffect, useRef } from 'react';

/**
 * 锚链接功能 Hook
 * 当开启锚链接时，自动滚动到当前步骤对应的锚点
 * 
 * @param currentStep - 当前步骤索引
 * @param enableAnchor - 是否启用锚链接
 * @param anchorContainer - 锚链接容器选择器或元素
 */
export function useAnchor(currentStep, enableAnchor, anchorContainer) {
  var previousStepRef = useRef(currentStep);
  useEffect(function () {
    // SSR 环境下不执行
    if (typeof window === 'undefined' || typeof document === 'undefined') {
      return;
    }

    // 未启用锚链接，直接返回
    if (!enableAnchor) {
      return;
    }

    // 步骤未发生变化，直接返回
    if (previousStepRef.current === currentStep) {
      return;
    }

    // 更新上一步记录
    previousStepRef.current = currentStep;

    // 查找锚点元素
    var anchorId = "pisell-steps-anchor-".concat(currentStep);
    var anchorElement = document.getElementById(anchorId);
    if (!anchorElement) {
      return;
    }

    // 获取滚动容器
    var scrollContainer = window;
    if (anchorContainer) {
      if (typeof anchorContainer === 'string') {
        var container = document.querySelector(anchorContainer);
        if (container instanceof HTMLElement) {
          scrollContainer = container;
        }
      } else if (anchorContainer instanceof HTMLElement) {
        scrollContainer = anchorContainer;
      }
    }

    // 滚动到锚点
    var scrollOptions = {
      behavior: 'smooth',
      block: 'start',
      inline: 'nearest'
    };
    anchorElement.scrollIntoView(scrollOptions);
  }, [currentStep, enableAnchor, anchorContainer]);
}