import { useState } from 'react';

import IntersectionTrigger from '../IntersectionTrigger';
import { ClipRowWrapper } from './ClipElements';

// Renders the clip row if it's within 1000px of the viewport, otherwise renders a placeholder that should be the same height
const virtualizeClipRow = (
  ClipRowComponent: React.ComponentType<{
    clipId: string;
    onboardingRef?: React.RefObject<HTMLDivElement | null>;
    likeOnboardingRef?: React.RefObject<HTMLDivElement | null>;
    shareOnboardingRef?: React.RefObject<HTMLDivElement | null>;
  }>,
  SameHeightPlaceholder: React.ComponentType<any> = ClipRowWrapper
) => {
  const Result = ({
    clipId,
    onboardingRef,
    likeOnboardingRef,
    shareOnboardingRef,
  }: {
    clipId: string;
    onboardingRef?: React.RefObject<HTMLDivElement | null>;
    likeOnboardingRef?: React.RefObject<HTMLDivElement | null>;
    shareOnboardingRef?: React.RefObject<HTMLDivElement | null>;
  }) => {
    const [isOnScreen, setIsOnScreen] = useState(false);

    return (
      <IntersectionTrigger
        setIntersecting={setIsOnScreen}
        scrollMargin='1000px'
        threshold={0.000001}
      >
        {isOnScreen ? (
          <ClipRowComponent
            clipId={clipId}
            onboardingRef={onboardingRef}
            likeOnboardingRef={likeOnboardingRef}
            shareOnboardingRef={shareOnboardingRef}
          />
        ) : (
          <SameHeightPlaceholder />
        )}
      </IntersectionTrigger>
    );
  };
  Result.displayName = `virtualizeClipRow(${ClipRowComponent.displayName})`;
  return Result;
};

export default virtualizeClipRow;
