import React, { useRef, useEffect, useState } from 'react';
import StatusLine from './status_line';

interface TerminalViewProps {
  lines: string[];
  maxLines?: number;
}

/**
 * Terminal-style scrolling container for status lines.
 * Auto-scrolls to bottom on new content unless user has scrolled up.
 */
const TerminalView: React.FC<TerminalViewProps> = ({ lines, maxLines = 30 }) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const [userScrolled, setUserScrolled] = useState(false);
  const bottomRef = useRef<HTMLDivElement>(null);

  // Auto-scroll to bottom when new lines arrive (unless user scrolled up)
  useEffect(() => {
    if (!userScrolled && bottomRef.current) {
      bottomRef.current.scrollIntoView({ behavior: 'smooth' });
    }
  }, [lines.length, userScrolled]);

  // Detect user scroll
  const handleScroll = () => {
    if (!containerRef.current) return;
    const { scrollTop, scrollHeight, clientHeight } = containerRef.current;
    const isAtBottom = scrollHeight - scrollTop - clientHeight < 20;
    setUserScrolled(!isAtBottom);
  };

  // Show only the most recent lines
  const visibleLines = lines.slice(-maxLines);

  return (
    <div className="ls-terminal" ref={containerRef} onScroll={handleScroll}>
      {visibleLines.map((line, i) => (
        <StatusLine key={i} line={line} />
      ))}
      <div ref={bottomRef} />
    </div>
  );
};

export default TerminalView;
