<?php

namespace App\Livewire;

use App\Models\Settings;
use App\Services\AddonService\IAddonService;
use App\Services\Menu\IMenuRegistrarService;
use Illuminate\Support\Facades\Route;
use Livewire\Component;

class SidebarMenu extends Component
{
    /**
     * Current route name for active state detection.
     */
    public string $currentRoute = '';

    /**
     * Mount the component.
     */
    public function mount(): void
    {
        $this->currentRoute = Route::currentRouteName() ?? '';
    }

    /**
     * Get menu items for the current user.
     *
     * @return array<int, object>
     */
    public function getMenuProperty(): array
    {
        // Get menu directly from the menu registrar service
        if (! auth()->check()) {
            return [];
        }

        $menuService = app(IMenuRegistrarService::class);
        $menu = $menuService->getForUser(auth()->user());

        // Convert array to objects for compatibility with existing Blade templates
        return json_decode(json_encode($menu));
    }

    /**
     * Get settings for branding.
     */
    public function getSettingsProperty(): Settings
    {
        return Settings::first() ?? new Settings;
    }

    /**
     * Get addon service for checking enabled addons.
     */
    public function getAddonServiceProperty(): IAddonService
    {
        return app(IAddonService::class);
    }

    /**
     * Check if a menu item is active.
     *
     * @param  object  $menu  Menu item object
     */
    public function isActive(object $menu): bool
    {
        if ($this->currentRoute === ($menu->slug ?? '')) {
            return true;
        }

        // Check if slug is an array
        if (isset($menu->slug) && is_array($menu->slug)) {
            foreach ($menu->slug as $slug) {
                if (str_starts_with($this->currentRoute, $slug)) {
                    return true;
                }
            }
        } elseif (isset($menu->slug) && str_starts_with($this->currentRoute, $menu->slug)) {
            return true;
        }

        return false;
    }

    /**
     * Check if a menu item should be visible.
     *
     * @param  object  $menu  Menu item object
     */
    public function isVisible(object $menu): bool
    {
        // Check addon availability
        if (isset($menu->addon) && ! $this->addonService->isAddonEnabled($menu->addon)) {
            return false;
        }

        // Hide SaaS-only menus from tenant context
        if (isset($menu->addon) && $menu->addon === 'MultiTenancyCore') {
            if (function_exists('isTenant') && isTenant()) {
                return false;
            }
        }

        return true;
    }

    /**
     * Render the component.
     */
    public function render()
    {
        return view('livewire.sidebar-menu', [
            'configData' => \Helper::appClasses(),
        ]);
    }
}
