import { useState, useRef, useEffect } from 'react';

interface UseOutputCaptureReturn {
  output: string;
  showOutput: boolean;
  outputEndRef: React.RefObject<HTMLDivElement>;
  setOutput: (output: string | ((prev: string) => string)) => void;
  setShowOutput: (show: boolean) => void;
  clearOutput: () => void;
  appendOutput: (text: string) => void;
  scrollToBottom: () => void;
}

/**
 * Custom hook for capturing and managing command output in setup wizard steps.
 * Provides output state, auto-scrolling, and utility functions for output management.
 */
export function useOutputCapture(): UseOutputCaptureReturn {
  const [output, setOutput] = useState<string>('');
  const [showOutput, setShowOutput] = useState(false);
  const outputEndRef = useRef<HTMLDivElement>(null);

  const clearOutput = () => {
    setOutput('');
  };

  const appendOutput = (text: string) => {
    setOutput((prev) => prev + text);
  };

  const scrollToBottom = () => {
    setTimeout(() => {
      outputEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    }, 100);
  };

  // Auto-scroll when output changes
  useEffect(() => {
    if (showOutput && output) {
      scrollToBottom();
    }
  }, [output, showOutput]);

  return {
    output,
    showOutput,
    outputEndRef,
    setOutput,
    setShowOutput,
    clearOutput,
    appendOutput,
    scrollToBottom
  };
}
