import { useEffect, useRef } from "@wordpress/element";

export default function useCharacterWrap(content) {
  const textRef = useRef(null);

  useEffect(() => {
    if (!textRef.current) return;

    const textElement = textRef.current.querySelector('[contenteditable="true"]');
    if (!textElement) return;

    const wrapChars = () => {
      const tempDiv = document.createElement("div");
      tempDiv.innerHTML = textElement.innerHTML;
      const text = tempDiv.textContent || tempDiv.innerText || "";

      if (textElement.querySelector(".char")) return;

      textElement.innerHTML = "";

      Array.from(text).forEach((char, index) => {
        const span = document.createElement("span");
        span.className = "char";
        span.style.setProperty("--char-index", index);
        span.textContent = char === " " ? "\u00A0" : char;
        textElement.appendChild(span);
      });
    };

    const observer = new MutationObserver(wrapChars);
    wrapChars();
    observer.observe(textElement, { childList: true, subtree: true, characterData: true });

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

  return textRef;
}
