'use client';
import { FunctionComponent, useEffect } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { Stack, Typography } from '@mui/material';
import { AppButton } from '@/components';
import AppIcon from '@/components/common/AppIcon';
import BrandMark from '@/components/auth/BrandMark';
import { ROUTES } from '@/constants';

interface ErrorPageProps {
  error: Error & { digest?: string };
  reset: () => void;
}

/**
 * The branded, per-locale error boundary — Next.js mounts this in place of the segment tree below
 * `[locale]/layout.tsx` whenever a render throws. It sits *inside* the locale layout's providers (next-intl,
 * theme, auth), so — unlike `global-error.tsx` — it can render fully localized copy. `reset()` re-renders
 * the segment (the standard recovery path); "go home" is the unconditional escape hatch. The raw error is
 * logged for diagnostics but never shown to the user (see `ErrorBoundary` for the same rule at the
 * component-subtree level).
 */
const ErrorPage: FunctionComponent<ErrorPageProps> = ({ error, reset }) => {
  const t = useTranslations('routeChrome');
  const locale = useLocale();

  useEffect(() => {
    console.error(error);
  }, [error]);

  return (
    <Stack
      sx={{ alignItems: 'center', justifyContent: 'center', minHeight: '70vh', gap: 2, px: 2, textAlign: 'center' }}
    >
      <BrandMark />
      <AppIcon icon="warning" size={40} color="var(--bal-warning)" />
      <Typography variant="h6" component="h1">
        {t('error_title')}
      </Typography>
      <Typography variant="body2" sx={{ color: 'text.secondary', maxWidth: 360 }}>
        {t('error_body')}
      </Typography>
      <Stack direction="row" sx={{ gap: 1.5 }}>
        <AppButton color="primary" variant="contained" onClick={reset}>
          {t('error_retry')}
        </AppButton>
        <AppButton color="primary" variant="outlined" to={`/${locale}${ROUTES.HOME}`}>
          {t('go_home')}
        </AppButton>
      </Stack>
    </Stack>
  );
};

export default ErrorPage;
