import type { Meta, StoryObj } from '@storybook/react';
import React from 'react';
import { ErrorBoundary } from './ErrorBoundary';

// Component that throws an error for testing
const ErrorThrower = ({ shouldThrow }: { shouldThrow?: boolean }) => {
    if (shouldThrow) {
        throw new Error('This is a test error for demonstrating ErrorBoundary');
    }
    return <div className="p-4 bg-green-100 text-green-800 rounded">Content rendered successfully!</div>;
};

const meta: Meta<typeof ErrorBoundary> = {
    title: 'Docs/Failures/ErrorBoundary',
    component: ErrorBoundary,
    parameters: {
        layout: 'fullscreen',
        chromatic: { disableSnapshot: true },
    },
    tags: ['autodocs'],
};

export default meta;
type Story = StoryObj<typeof ErrorBoundary>;

export const NoError: Story = {
    render: () => (
        <ErrorBoundary>
            <ErrorThrower shouldThrow={false} />
        </ErrorBoundary>
    ),
};

// Helper to silence console.error during expected error tests
const ConsoleSilencer = ({ children }: { children: React.ReactNode }) => {
    React.useEffect(() => {
        const originalError = console.error;
        console.error = (...args) => {
            const msg = args[0]?.toString() || '';
            // Suppress the specific test error and React's error boundary noise
            if (msg.includes('This is a test error') || msg.includes('The above error occurred')) {
                return;
            }
            originalError(...args);
        };
        return () => {
            console.error = originalError;
        };
    }, []);
    return <>{children}</>;
};

export const WithError: Story = {
    parameters: { storybookAudit: { expectConsoleErrors: true } },
    render: () => (
        <ConsoleSilencer>
            <ErrorBoundary>
                <ErrorThrower shouldThrow={true} />
            </ErrorBoundary>
        </ConsoleSilencer>
    ),
};

export const WithCustomFallback: Story = {
    parameters: { storybookAudit: { expectConsoleErrors: true } },
    render: () => (
        <ConsoleSilencer>
            <ErrorBoundary
                fallback={
                    <div className="p-8 text-center bg-amber-100 text-amber-800 rounded-lg">
                        <h2 className="text-xl font-bold mb-2">Custom Fallback</h2>
                        <p>Something went wrong, but we have a custom fallback UI.</p>
                    </div>
                }
            >
                <ErrorThrower shouldThrow={true} />
            </ErrorBoundary>
        </ConsoleSilencer>
    ),
};
