@php
    // রুট/চাইল্ডে active থাকলে true
    $isTreeActive = function (array $node) use (&$isTreeActive): bool {
        if (!empty($node['route']) && \Illuminate\Support\Facades\Route::has($node['route'])) {
            if (request()->routeIs($node['route']) || request()->routeIs($node['route'].'.*')) return true;
        }
        if (!empty($node['children'])) {
            foreach ($node['children'] as $child) {
                if ($isTreeActive($child)) return true;
            }
        }
        return false;
    };

    $safeUrl = function (?string $route): string {
        return $route && \Illuminate\Support\Facades\Route::has($route) ? route($route) : '#';
    };

    $render = function (array $items, int $level = 0) use (&$render, $isTreeActive, $safeUrl) {
        echo $level === 0 ? '<ul class="arm-menu" role="tree">' : '<ul class="arm-sub" role="group">';
        foreach ($items as $it) {
            $has   = !empty($it['children']);
            $icon  = $it['icon'] ?? 'far fa-circle';
            $label = e($it['label'] ?? '');
            $route = $it['route'] ?? null;
            $badge = $it['badge'] ?? null;

            $activeSelf  = $route && \Illuminate\Support\Facades\Route::has($route)
                ? (request()->routeIs($route) || request()->routeIs($route.'.*'))
                : false;
            $activeChild = $has ? $isTreeActive($it) : false;

            $liClass = 'arm-item'.($has ? ' has-children' : '');
            if ($activeSelf || $activeChild) $liClass .= ' is-open';

            $title = $label . (!is_null($badge) ? " ({$badge})" : '');
            $visual = $label . (!is_null($badge) ? " ({$badge})" : '');

            echo '<li class="'.$liClass.'" role="treeitem" aria-expanded="'.(($activeSelf || $activeChild) ? 'true' : 'false').'">';

            if ($level === 0) {
                echo '<a href="'.e($safeUrl($route)).'" class="arm-link" title="'.e($title).'">';
                echo   '<span class="arm-ico"><i class="'.e($icon).'"></i></span>';
                echo   '<span>'.$visual.'</span>';
                if ($has) echo '<span class="arm-chev" aria-hidden="true"><i class="fas fa-angle-down"></i></span>';
                echo '</a>';
            } else {
                echo '<a href="'.e($safeUrl($route)).'" class="arm-sublink" title="'.e($title).'">';
                echo   '<span>'.$visual.'</span>';
                if ($has) echo '<span class="arm-chev" aria-hidden="true"><i class="fas fa-angle-down"></i></span>';
                echo '</a>';
            }

            if ($has) {
                $render($it['children'], $level + 1);
            }

            echo '</li>';
        }
        echo '</ul>';
    };
@endphp

<nav class="arm-sidebar" aria-label="Sidebar Navigation">
  {!! $render($ARM_MENU ?? []) !!}
</nav>

