import { ref, watch, nextTick } from 'vue';

export function useInputAutogrow(input: ReturnType<typeof ref<string>>) {
    const inputEl = ref<HTMLTextAreaElement | null>(null);
    const isShaking = ref(false);

    function autoGrow() {
        const el = inputEl.value;
        if (!el) return;
        el.style.height = 'auto';

        el.style.height = el.scrollHeight + 'px';
        el.style.overflowY = el.scrollHeight > 160 ? 'auto' : 'hidden';
    }

    function triggerShake() {
        isShaking.value = true;
        setTimeout(() => { isShaking.value = false; }, 400);
    }

    watch(input, (val) => {
        if (!val) nextTick(() => autoGrow());
    });

    return { inputEl, isShaking, autoGrow, triggerShake };
}
