import React from 'react';
import { render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';

import { LayoutRenderer } from '../src/platform/components/runtime/LayoutRenderer';

// Mirrors the shape LayoutRenderer actually reads -- hostApps.apps keyed by the
// policy scope, with the shell components it looks up. A thinner double would
// throw before reaching the branch under test, and a more generous one would
// prove a path production does not have.
vi.mock('@nexuscrm/host-sdk', async () => {
    const ReactModule = await import('react');
    return {
        hostApps: {
            apps: new Map([
                ['empty-state-test', {
                    shellComponents: {
                        layoutFieldItemResolver: () => null,
                        layoutInlineEditField: () => ReactModule.createElement('div'),
                    },
                }],
            ]),
        },
    };
});

// The projection omits a section once everything in it has gone absent
// (app-packs#679), so "this layout renders nothing" stopped being a malformed
// response and became an ordinary one -- most often for a caller whose
// field-level security hides every field on the page.
//
// The guard that used to speak for that case tested truthiness, and the API
// client coerces a null sections key to [] before anything sees it
// (decodeLayoutLabels), so it could not fire. A real render is the honest
// instrument here: a source pin would have passed against the broken version.
const metadata = { name: 'Account', label: 'Account', fields: [] };

const renderLayout = (sections: unknown) =>
    render(
        <LayoutRenderer
            layout={{ id: 'l1', objectApiName: 'Account', sections } as never}
            record={{ Id: 'a1' }}
            objectMetadata={metadata as never}
            onUpdate={async () => undefined}
            fieldSurfacePolicyScope="empty-state-test"
        />,
    );

describe('a layout with nothing left to render says so', () => {
    it('shows the empty state for an empty section list', () => {
        renderLayout([]);
        expect(screen.getByText(/No layout sections/i)).toBeInTheDocument();
    });

    it('shows it for a missing section list too', () => {
        renderLayout(undefined);
        expect(screen.getByText(/No layout sections/i)).toBeInTheDocument();
    });

    it('does not show it when a section survives', () => {
        renderLayout([{ id: 's1', heading: 'Info', columns: 1, layoutRows: [] }]);
        expect(screen.queryByText(/No layout sections/i)).not.toBeInTheDocument();
    });
});
