import React, { useCallback, useEffect, useRef } from 'react';

export default function TrainingDocumentViewer({ content, onProgress, onReachBottom, startTime, onStart }) {
  const ref = useRef(null);
  const started = useRef(false);

  const handleScroll = useCallback(() => {
    const el = ref.current;
    if (!el) return;
    if (!started.current) {
      started.current = true;
      onStart?.();
    }
    const { scrollTop, scrollHeight, clientHeight } = el;
    const progress = Math.min(100, Math.round((scrollTop / (scrollHeight - clientHeight || 1)) * 100));
    onProgress?.(progress);
    if (scrollTop + clientHeight >= scrollHeight - 8) {
      onReachBottom?.();
    }
  }, [onProgress, onReachBottom, onStart]);

  useEffect(() => {
    handleScroll();
  }, [handleScroll, content]);

  return (
    <div ref={ref} className="dt-document-viewer" onScroll={handleScroll}>
      {content}
    </div>
  );
}
