import { useEffect, useMemo } from "react";
import getBodyElement from "../get-body-element";
import useUniqueId from "../use-unique-id";

export function getElementId({ contextId, uniqueId }) {
  return `rbd-hidden-text-${contextId}-${uniqueId}`;
}

export default function useHiddenTextElement({ contextId, text }) {
  const uniqueId = useUniqueId("hidden-text", {
    separator: "-"
  });
  const id = useMemo(
    () =>
      getElementId({
        contextId,
        uniqueId
      }),
    [uniqueId, contextId]
  );
  useEffect(
    function mount() {
      const el = document.createElement("div");

      // identifier
      el.id = id;

      // add the description text
      el.textContent = text;

      // Using `display: none` prevent screen readers from reading this element in the document flow
      el.style.display = "none";

      // Add to body
      getBodyElement().appendChild(el);
      return function unmount() {
        // checking if element exists as the body might have been changed by things like 'turbolinks'
        const body = getBodyElement();
        if (body.contains(el)) {
          body.removeChild(el);
        }
      };
    },
    [id, text]
  );
  return id;
}
