import React, { ReactNode } from 'react';
import { ErrorBoundary } from 'react-error-boundary';
import { Box, Text, color, config } from 'folds';
import { useTranslation } from 'react-i18next';

function MessageRenderFallback() {
  const { t } = useTranslation('Room');
  return (
    <Box style={{ padding: `${config.space.S100} ${config.space.S400}` }}>
      <Text size="T200" priority="300" style={{ color: color.Critical.Main }}>
        {t('message_render_error')}
      </Text>
    </Box>
  );
}

/**
 * Isolates a single timeline row's render. A hostile event (e.g. a crafted
 * voice waveform or a non-string reply body) that throws during render is
 * contained to one "could not display message" row instead of unmounting the
 * whole React root (white-screen / persistent DoS). `resetKey` is the event id:
 * it stays constant across edits/redactions of the SAME event (so a row that
 * deterministically throws stays on the fallback rather than thrashing), and
 * changes only when a different event takes this row's slot.
 */
export function MessageErrorBoundary({
  children,
  resetKey,
}: {
  children: ReactNode;
  resetKey?: string;
}) {
  return (
    <ErrorBoundary FallbackComponent={MessageRenderFallback} resetKeys={[resetKey]}>
      {children}
    </ErrorBoundary>
  );
}
