import { computed, onMounted, onUnmounted, ref, type Ref } from 'vue';

export interface TocItem {
  id: string;
  text: string;
  level: number;
  element?: HTMLElement;
}

export function useToc(contentRef: Ref<HTMLElement | null>) {
  const tocItems = ref<TocItem[]>([]);
  const activeId = ref<string>('');

  // Tạo TOC từ HTML content
  const generateToc = () => {
    if (!contentRef.value) return;

    const headings = contentRef.value.querySelectorAll('h1, h2, h3, h4, h5, h6');
    const items: TocItem[] = [];

    headings.forEach((heading, index) => {
      const level = parseInt(heading.tagName.charAt(1));
      const text = heading.textContent?.trim() || '';

      // Tạo ID nếu chưa có
      let id = heading.id;
      if (!id) {
        id = `heading-${index}`;
        heading.id = id;
      }

      items.push({
        id,
        text,
        level,
        element: heading as HTMLElement,
      });
    });

    tocItems.value = items;
  };

  // Cập nhật heading active dựa trên scroll position
  const updateActiveHeading = () => {
    if (!tocItems.value.length) return;

    const scrollPosition = window.scrollY + 200; // Offset 200px
    let current = '';

    for (const item of tocItems.value) {
      if (item.element) {
        const offsetTop = item.element.offsetTop;
        if (scrollPosition >= offsetTop) {
          current = item.id;
        }
      }
    }

    activeId.value = current;
  };

  // Smooth scroll đến heading
  const scrollToHeading = (id: string) => {
    const element = document.getElementById(id);
    if (element) {
      element.scrollIntoView({
        behavior: 'smooth',
        block: 'start',
      });
    }
  };

  // Setup scroll listener
  const handleScroll = () => {
    updateActiveHeading();
  };

  onMounted(() => {
    // Tạo TOC khi component mount
    generateToc();

    // Setup scroll listener
    window.addEventListener('scroll', handleScroll);

    // Cập nhật active heading lần đầu
    updateActiveHeading();
  });

  onUnmounted(() => {
    window.removeEventListener('scroll', handleScroll);
  });

  // Computed để group TOC items theo level
  const groupedTocItems = computed(() => {
    return tocItems.value.map((item) => ({
      ...item,
      isActive: activeId.value === item.id,
    }));
  });

  return {
    tocItems: groupedTocItems,
    activeId,
    scrollToHeading,
    generateToc,
  };
}
