import { useEffect, useState, type RefObject } from 'react';
import type { TerminalViewHandle } from './TerminalView';

interface Props {
  terminalRef: RefObject<TerminalViewHandle>;
}

/**
 * Polls the terminal handle to detect scroll-up state and shows a FAB
 * that scrolls the buffer to the bottom on tap. Polling at 500ms is
 * cheaper than wiring an xterm onScroll forward through the handle and
 * accurate enough for human-facing UX.
 */
export function ScrollToBottomButton({ terminalRef }: Props) {
  const [scrolledUp, setScrolledUp] = useState(false);

  useEffect(() => {
    const id = window.setInterval(() => {
      setScrolledUp(terminalRef.current?.isScrolledUp() ?? false);
    }, 500);
    return () => window.clearInterval(id);
  }, [terminalRef]);

  if (!scrolledUp) return null;

  return (
    <button
      type="button"
      aria-label="最新へスクロール"
      onClick={() => terminalRef.current?.scrollToBottom()}
      className="absolute bottom-3 right-3 z-10 w-11 h-11 rounded-full bg-blue-600 text-white shadow-lg flex items-center justify-center active:bg-blue-700 transition-colors"
    >
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
        <line x1="12" y1="5" x2="12" y2="19" />
        <polyline points="19 12 12 19 5 12" />
      </svg>
    </button>
  );
}
