<?php

namespace App\View\Components\Ui\Layout;

use Illuminate\Support\Facades\Route;
use Illuminate\View\Component;
use Illuminate\View\View;

final class AppSidebar extends Component
{
    /**
     * @param  list<array<string, mixed>>  $groups
     */
    public function __construct(
        public array $groups = [],
    ) {}

    public function render(): View
    {
        return view('components.ui.layout.app-sidebar', [
            'sidebar' => $this,
            'navSidebarGroups' => $this->groups,
        ]);
    }

    public function resolveUrl(array $entry): ?string
    {
        if (! empty($entry['route'])) {
            if (! Route::has((string) $entry['route'])) {
                return null;
            }

            return route((string) $entry['route'], $entry['route_params'] ?? []);
        }

        $href = $entry['href'] ?? null;
        if ($href === null || $href === '') {
            return null;
        }

        if ($href === '#' || str_starts_with((string) $href, 'http://') || str_starts_with((string) $href, 'https://')) {
            return (string) $href;
        }

        return url((string) $href);
    }

    public function isItemActive(array $item): bool
    {
        $name = Route::currentRouteName();
        if ($name === null) {
            return false;
        }

        if (($item['nav_active_rule'] ?? null) === 'sales_orders_hub') {
            return request()->routeIs('sales.orders.show')
                || (request()->routeIs('sales.orders.index') && ! request()->filled('view'));
        }

        if (! empty($item['route']) && $name === (string) $item['route']) {
            if ($name === 'dashboard.ops.show' && isset($item['route_params']['persona'])) {
                return (string) request()->route('persona') === (string) $item['route_params']['persona'];
            }
            foreach ($item['active_query'] ?? [] as $key => $expected) {
                if ((string) request()->query($key) !== (string) $expected) {
                    return false;
                }
            }

            return true;
        }

        foreach ($item['active_routes'] ?? [] as $pattern) {
            if (request()->routeIs((string) $pattern)) {
                return true;
            }
        }

        return false;
    }

    /**
     * @param  array<string, mixed>  $group
     */
    public function groupHasActive(array $group): bool
    {
        foreach ($group['items'] ?? [] as $item) {
            if ($this->isItemActive($item)) {
                return true;
            }
        }

        return false;
    }
}
