import { useEffect } from "react";

const toPersianDigits = (text: string): string => {
  return text.replace(/\d/g, (d) => "۰۱۲۳۴۵۶۷۸۹"[parseInt(d, 10)]);
};

const convertNumbersInDOM = (node: Node): void => {
  if (node.nodeType === Node.TEXT_NODE) {
    node.nodeValue = toPersianDigits(node.nodeValue || "");
  } else if (node.nodeType === Node.ELEMENT_NODE) {
    // Skip conversion if element has 'en' class
    if ((node as Element).classList?.contains("en")) {
      return;
    }
    node.childNodes.forEach(convertNumbersInDOM);
  }
};

const useConvertNumbers = (): void => {
  useEffect(() => {
    const observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        if (mutation.type === "childList") {
          mutation.addedNodes.forEach(convertNumbersInDOM);
        }
      });
    });

    observer.observe(document.body, { childList: true, subtree: true });

    // اجرای اولیه روی کل صفحه
    convertNumbersInDOM(document.body);

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

export default useConvertNumbers;
