<?php

declare(strict_types=1);

namespace App\Filament\Support;

use Filament\Navigation\NavigationGroup;

/**
 * 后台主导航分组顺序：与 App\Providers\Filament\AdminPanelProvider 注册的侧栏分组顺序一致，供常用功能候选分组与排序对齐。
 */
final class DberpAdminSidebarNavigationOrder
{
    /**
     * 与侧栏 {@see self::navigationGroups} 相同的 `dberp.nav.*` 键顺序（不含翻译）。
     *
     * @return list<string>
     */
    public static function navigationGroupTranslationKeyOrder(): array
    {
        $keys = [
            'workbench',
            'common_functions',
            'sales',
            'warehouse',
            'purchase',
            'settlement',
            'business_query',
            'product',
            'report_analysis',
            'basic_data',
            'organization_data',
        ];

        if (config('dberp.integration.nav_enabled')) {
            $keys[] = 'integration';
        }

        $keys[] = 'system';

        return $keys;
    }

    /**
     * @return list<NavigationGroup>
     */
    public static function navigationGroups(): array
    {
        $groups = [];
        foreach (self::navigationGroupTranslationKeyOrder() as $key) {
            $group = NavigationGroup::make(fn (): string => __('dberp.nav.'.$key));

            if ($key === 'common_functions') {
                $group = $group
                    ->collapsible()
                    ->extraSidebarAttributes([
                        'class' => 'dberp-sidebar-common-functions-sticky',
                    ]);
            }

            $groups[] = $group;
        }

        return $groups;
    }

    /**
     * 当前语言下侧栏分组标题列表，顺序与主导航一致。
     *
     * @return list<string>
     */
    public static function orderedResolvedSidebarGroupLabels(): array
    {
        return array_values(array_map(
            static fn (string $key): string => (string) __('dberp.nav.'.$key),
            self::navigationGroupTranslationKeyOrder(),
        ));
    }

    /**
     * 用于将「可固定」候选按侧栏业务分组排序；未知分组排在已定义分组之后，顺序稳定。
     */
    public static function rankForResolvedLabel(string $resolvedLabel): int
    {
        static $cachedLocale = null;

        /** @var array<string, int> $rankByLabel */
        static $rankByLabel = [];

        $locale = app()->getLocale();
        if ($cachedLocale !== $locale || $rankByLabel === []) {
            $cachedLocale = $locale;
            $rankByLabel = [];
            foreach (self::orderedResolvedSidebarGroupLabels() as $index => $label) {
                $rankByLabel[$label] = $index;
            }
        }

        return $rankByLabel[$resolvedLabel] ?? 900 + (int) (abs(crc32($resolvedLabel)) % 1000);
    }
}
