import { useEffect } from "react";
import { useWidget } from "../context/WidgetContext";
import {
    applyFontSizeToElement,
    applyLineHeight,
    applyLineSpacing,
} from "../effects/text-effects";
import {disableHighlightedLinks, enableHighlightedLinks} from "../effects/highlighted-links";

export default function SPAObserver() {
    const {
        currentFontSizeMultiplier,
        currentLineHeight,
        currentSpacing,
        isLinksHighlighted,
    } = useWidget();

    useEffect(() => {
        // Throttle the observer to reduce performance impact
        let timeoutId = null;

        const observer = new MutationObserver((mutations) => {
            // Clear previous timeout
            if (timeoutId) {
                clearTimeout(timeoutId);
            }

            // Debounce the processing to reduce frequency
            timeoutId = setTimeout(() => {
                mutations.forEach((mutation) => {
                    mutation.addedNodes.forEach((node) => {
                        if (!(node instanceof HTMLElement)) return;

                        // Only process if the node is visible and has content
                        if (node.offsetHeight === 0 && node.offsetWidth === 0) return;

                        // Apply to new node
                        applyFontSizeToElement(node, 1, currentFontSizeMultiplier);
                        applyFontSizeToElement(node, currentFontSizeMultiplier, 1);
                        applyLineHeight(node, currentLineHeight);
                        applyLineSpacing(node, currentSpacing);


                        if (isLinksHighlighted) {
                            enableHighlightedLinks();
                        }

                        // Only process direct children, not all descendants
                        const children = Array.from(node.children);
                        children.forEach((child) => {
                            if (child instanceof HTMLElement) {
                                applyFontSizeToElement(child, 1, currentFontSizeMultiplier);
                                applyFontSizeToElement(child, currentFontSizeMultiplier, 1);
                                applyLineHeight(child, currentLineHeight);
                                applyLineSpacing(child, currentSpacing);
                            }
                        });
                    });
                });
            }, 100); // 100ms debounce
        });

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

        return () => {
            observer.disconnect();
        };
    }, [currentFontSizeMultiplier, currentLineHeight, currentSpacing]);

    return null; // this is a background effect, nothing to render
}
