import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import { useRef, useState, useEffect } from 'react';

/**
 * React hook that returns the current language direction ('ltr' or 'rtl')
 * from the HTML element's 'dir' attribute and updates when it changes.
 *
 * @returns {string} The current language direction ('ltr' or 'rtl')
 */
function useLangDirection() {
  var isServerSide = useRef(typeof window === 'undefined' || typeof document === 'undefined');
  var observer = useRef(null);

  // Lazy initialize direction
  var _useState = useState(function () {
      if (isServerSide.current) {
        return null;
      }
      // Target the HTML element
      var element = document.getElementsByTagName('html')[0];
      // Set initial direction
      return element.getAttribute('dir') || 'ltr';
    }),
    _useState2 = _slicedToArray(_useState, 2),
    direction = _useState2[0],
    setDirection = _useState2[1];
  useEffect(function () {
    // Return early if in server environment
    if (isServerSide.current) {
      return;
    }
    // Target the HTML element
    var element = document.getElementsByTagName('html')[0];
    // Callback function to execute when mutations are observed
    var callback = function callback(mutationsList) {
      // Use traditional for loop for better compatibility
      for (var i = 0; i < mutationsList.length; i += 1) {
        var mutation = mutationsList[i];
        // Check if the mutation was for the 'dir' attribute
        if (mutation.type === 'attributes' && mutation.attributeName === 'dir' && mutation.oldValue !== element.getAttribute('dir')) {
          // Update the direction state
          setDirection(element.getAttribute('dir'));
        }
      }
    };

    // Disconnect any existing observer
    if (observer.current) {
      observer.current.disconnect();
    }

    // Configure the observer to watch for attribute changes
    var config = {
      attributes: true,
      attributeOldValue: true,
      attributeFilter: ['dir']
    };

    // Create a new MutationObserver
    observer.current = new MutationObserver(callback);

    // Start observing the HTML element
    observer.current.observe(element, config);

    // Cleanup function to disconnect the observer on unmount
    // eslint-disable-next-line consistent-return
    return function () {
      if (observer.current) {
        observer.current.disconnect();
      }
    };
  }, []); // No dependencies needed as element is constant

  // Return the current direction, defaulting to 'ltr' if not set or in server environment
  return isServerSide.current ? 'ltr' : direction || 'ltr';
}

// Made with Bob

export { useLangDirection };
