import { ref, onUnmounted } from 'vue';

export function useTypewriter(speed = 20) {
  const displayedText = ref('');
  let interval: ReturnType<typeof setInterval> | null = null;

  function animate(text: string, onType?: () => void) {
    const safeText = text ?? '';
    let index = 0;
    displayedText.value = '';

    if (interval) clearInterval(interval);

    interval = setInterval(() => {
      displayedText.value = safeText.slice(0, index + 1);
      index++;
      onType?.();
      if (index >= safeText.length) {
        clearInterval(interval!);
        interval = null;
      }
    }, speed);
  }

  onUnmounted(() => {
    if (interval) clearInterval(interval);
  });

  return { displayedText, animate };
}
