import {useContextSection} from '@hooks';
import {CSSProperties, useEffect, useRef, useState} from 'react';
import {context} from '../../context';
import {useStore} from 'zustand';
import {tabStore} from '@stores';

export function useIndicator() {
  const [style, setStyle] = useState<CSSProperties>({display: 'none'});
  const visibleTab = useRef<Set<string>>(new Set());
  const tabs = useContextSection(context, state => state[0]);
  const {key} = useStore(tabStore);

  useEffect(
    function () {
      const observer = new IntersectionObserver(
        function (entries) {
          entries.forEach(function ({intersectionRatio, target}) {
            const key = target.getAttribute('data-key')!;

            if (intersectionRatio >= 1) {
              visibleTab.current.add(key);
            } else {
              visibleTab.current.delete(key);
            }
          });
        },
        {
          root: document.querySelector('#p_tab_list'),
        },
      );

      document
        .querySelector('#p_tab_list')
        ?.querySelectorAll('li[role="tab"]')
        ?.forEach(function (el) {
          observer.observe(el);
        });

      return () => observer.disconnect();
    },
    [tabs],
  );

  useEffect(
    function () {
      const activeEl = document.getElementById(`p_tab_item_${key}`);
      if (!activeEl) return setStyle({display: 'none'});

      const {width} = activeEl.getBoundingClientRect();
      const left = activeEl.offsetLeft;

      setStyle({width, transform: `translate(${left}px)`});

      // 判断是否需要滚动到指定位置
      if (!visibleTab.current.has(key)) {
        document
          .querySelector('#p_tab_list')
          ?.querySelector(`#p_tab_item_${key}`)
          ?.scrollIntoView({
            behavior: 'smooth',
            inline: 'start',
            block: 'start',
          });
      }
    },
    [key, tabs],
  );

  return style;
}
