<?php

namespace App\Modules\Navigation\Services;

/**
 * Orders primary nav groups for desktop mega menus and merges platform admin
 * links into the Administration panel when both groups are visible.
 */
final class NavigationMegaGroupComposer
{
    /** @var list<string> */
    private const ORDER = [
        'dashboard',
        'hr',
        'inventory',
        'procurement',
        'sales',
        'accounting',
        'reports',
        'operations',
        'administration',
    ];

    /**
     * @param  list<array<string, mixed>>  $filteredGroups
     * @return list<array<string, mixed>>
     */
    public function compose(array $filteredGroups): array
    {
        /** @var array<string, array<string, mixed>> $map */
        $map = [];
        foreach ($filteredGroups as $group) {
            $key = (string) ($group['key'] ?? '');
            if ($key === '') {
                continue;
            }
            $map[$key] = $group;
        }

        $adminGroup = $map['admin'] ?? null;
        $adminItems = (is_array($adminGroup) && isset($adminGroup['items'])) ? array_values((array) $adminGroup['items']) : [];
        unset($map['admin']);

        if ($adminItems !== [] && isset($map['administration'])) {
            $map['administration']['items'] = array_merge(
                $map['administration']['items'] ?? [],
                $adminItems,
            );
        } elseif ($adminItems !== [] && ! isset($map['administration'])) {
            $map['administration'] = [
                'key' => 'administration',
                'label' => __('nav.group.administration'),
                'icon' => ($adminGroup['icon'] ?? null) ?: 'fe fe-settings',
                'items' => $adminItems,
            ];
        }

        $out = [];
        foreach (self::ORDER as $key) {
            if (! isset($map[$key])) {
                continue;
            }
            $items = $map[$key]['items'] ?? [];
            if ($items === []) {
                continue;
            }
            $out[] = $map[$key];
        }

        return $out;
    }
}
