import React from 'react';
import { describe, it, expect } from 'vitest';
import { createComponentRegistry, createFallbackComponent } from '../utils/component-registry';

type TestProps = { label: string };

describe('component-registry', () => {
	describe('createComponentRegistry', () => {
		it('returns null for unknown type with no fallback', () => {
			const reg = createComponentRegistry<TestProps>({
				registry: {},
			});
			expect(reg.getComponent('unknown')).toBeNull();
		});

		it('returns fallback for unknown type when provided', () => {
			const Fallback: React.FC<TestProps> = () => null;
			const reg = createComponentRegistry<TestProps>({
				registry: {},
				fallback: Fallback,
			});
			expect(reg.getComponent('unknown')).toBe(Fallback);
		});

		it('getTypes returns registered keys', () => {
			const reg = createComponentRegistry<TestProps>({
				registry: {
					typeA: React.lazy(() => Promise.resolve({ default: (() => null) as React.FC<TestProps> })),
					typeB: React.lazy(() => Promise.resolve({ default: (() => null) as React.FC<TestProps> })),
				},
			});
			expect(reg.getTypes()).toEqual(['typeA', 'typeB']);
		});

		it('hasType detects registered types', () => {
			const reg = createComponentRegistry<TestProps>({
				registry: {
					myType: React.lazy(() => Promise.resolve({ default: (() => null) as React.FC<TestProps> })),
				},
			});
			expect(reg.hasType('myType')).toBe(true);
			expect(reg.hasType('missing')).toBe(false);
		});

		it('caches memoized component on second call', () => {
			const reg = createComponentRegistry<TestProps>({
				registry: {
					cached: React.lazy(() => Promise.resolve({ default: (() => null) as React.FC<TestProps> })),
				},
			});
			const first = reg.getComponent('cached');
			const second = reg.getComponent('cached');
			expect(first).toBe(second);
		});
	});

	describe('createFallbackComponent', () => {
		it('returns a function component', () => {
			const Fallback = createFallbackComponent();
			expect(typeof Fallback).toBe('function');
		});
	});
});
