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

const observerOptions = {
  rootMargin: '200px 0px',
  threshold: 0,
};

// Global observer to reduce memory usage
let globalObserver: IntersectionObserver | null = null;
const observerCallbacks = new WeakMap<Element, (inView: boolean) => void>();

const getObserver = () => {
  if (typeof window === 'undefined') return null;
  if (!globalObserver) {
    globalObserver = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        const callback = observerCallbacks.get(entry.target);
        if (callback) {
          callback(entry.isIntersecting);
        }
      });
    }, observerOptions);
  }
  return globalObserver;
};

export const VirtualRow = React.forwardRef<any, any>((props, ref) => {
  const { className, style, children, ...restProps } = props;
  const [inView, setInView] = useState(true); // Default to true to render initially and let observer hide it if out of view
  const rowRef = useRef<HTMLTableRowElement>(null);

  useEffect(() => {
    if (typeof ref === 'function') ref(rowRef.current);
    else if (ref) (ref as any).current = rowRef.current;
  }, [ref, rowRef.current]);

  useEffect(() => {
    const target = rowRef.current;
    if (!target) return;

    const observer = getObserver();
    if (observer) {
      observerCallbacks.set(target, setInView);
      observer.observe(target);
    }

    return () => {
      if (observer && target) {
        observer.unobserve(target);
        observerCallbacks.delete(target);
      }
    };
  }, []);

  if (!inView) {
    return (
      <tr
        ref={rowRef}
        className={className}
        style={{ ...style, height: 38 }}
        {...restProps}
      />
    );
  }

  return (
    <tr ref={rowRef} className={className} style={style} {...restProps}>
      {children}
    </tr>
  );
});
