import { memo } from 'react';
import type { ToastItemRendererProps } from './types';

/**
 * Memoized toast item component to prevent unnecessary re-renders
 * Only re-renders when the toast item itself changes
 */
export const ToastItemRenderer = memo(
  ({ toastItem, show, hide, index, total, heights, maxVisibleToasts }: ToastItemRendererProps) => {
    if (typeof toastItem.component !== 'function') {
      throw new Error('Toast component must be a function that receives ToastComponentProps');
    }

    const content = toastItem.component({
      id: toastItem.id,
      index,
      total,
      heights,
      maxVisibleToasts,
      show,
      hide,
    });

    return content;
  },
  (prevProps, nextProps) => {
    // Only re-render if the toast ID, component reference, index, or
    // pending-removal flag changed. `pendingRemoval` flips when the
    // provider marks a toast closed on web so the Toast component can
    // play its exit transition — the renderer must propagate that
    // change even though the id and component reference are unchanged.
    // show, hide, total, and heights are stable references.
    return (
      prevProps.toastItem.id === nextProps.toastItem.id &&
      prevProps.toastItem.component === nextProps.toastItem.component &&
      prevProps.toastItem.pendingRemoval === nextProps.toastItem.pendingRemoval &&
      prevProps.index === nextProps.index
    );
  },
);
