import { useEffect, useRef } from "preact/hooks";
import type { JSX } from "preact/jsx-runtime"

import { useIsVisible } from '@common/hooks/useIsVisible';
import { DOMTools } from "../tools/dom";

export const AutoTextarea = (props: JSX.HTMLAttributes<HTMLTextAreaElement>) => {
    const { value } = props;
    const ref = useRef<HTMLTextAreaElement>(null);
    const isVisible = useIsVisible(ref);

    useEffect(() => {
        if (ref.current && isVisible) {
            const area = ref.current;

            const { height } = DOMTools.calculateNodeHeight(area);
            area.style.height = `${height}px`;
        }
    }, [value, isVisible]);

    return <textarea {...props} ref={ref} />
};
