<?php

declare(strict_types=1);

namespace App\Filament\Support;

final class NormalizedSettingsSurface
{
    /**
     * @param  array<string, mixed>  $normalized
     * @return array<string, mixed>
     */
    public static function build(array $normalized, string $hostKind): array
    {
        $warnings = collect($normalized['warnings'] ?? [])
            ->filter(static fn (mixed $warning): bool => is_string($warning) && trim($warning) !== '')
            ->map(static fn (string $warning): string => trim($warning))
            ->values()
            ->all();

        $settingsTable = is_array($normalized['settings_table'] ?? null) ? $normalized['settings_table'] : null;
        $settingsTableRows = is_array($settingsTable['rows'] ?? null) ? $settingsTable['rows'] : [];
        $blocks = collect($normalized['settings'] ?? [])
            ->filter(static fn (mixed $block): bool => is_array($block))
            ->values()
            ->all();

        $context = is_string($normalized['context'] ?? null) && $normalized['context'] !== ''
            ? (string) $normalized['context']
            : 'policy';

        $variant = $settingsTableRows !== [] ? 'settings_catalog_table' : 'standard_blocks';

        return [
            'hostKind' => $hostKind,
            'context' => $context,
            'variant' => $variant,
            'warnings' => $warnings,
            'settingsTable' => $settingsTableRows !== [] ? $settingsTable : null,
            'blocks' => $blocks,
            'sectionBehavior' => [
                'preservesSectionOrder' => true,
                'supportsExpansion' => true,
                'ownsEmptyState' => true,
            ],
            'renderExpectations' => [
                'ownsWarningsInWrapper' => true,
                'ownsSubtypeDelegation' => true,
                'keepsHostFramingOutsideCore' => true,
            ],
            'emptyState' => $settingsTableRows === [] && $blocks === []
                ? [
                    'title' => 'No settings available.',
                    'message' => 'No normalized settings payload is available for this host.',
                ]
                : null,
            'titlePolicy' => [
                'showWrapperTitle' => false,
            ],
            'recordId' => $normalized['record_id'] ?? null,
            'policyType' => $normalized['policy_type'] ?? null,
        ];
    }
}
