<?php

namespace Ignite\Core\Models\Menu;

use Ignite\Core\Contracts\CanDisplayInMenu;
use Ignite\Core\Events\Menus\NavigationMenuPreCompile;
use Ignite\Core\Models\Menu\MenuExtended;
use Illuminate\Support\Str;
use Spatie\Menu\Laravel\Link;
use Spatie\Menu\Laravel\Menu as SpatieMenu;

class NavigationMenu extends Manager
{
    /** @var SpatieMenu */
    protected $menu;

    /** @var bool */
    protected $collapseSingleChildSubmenu = false;

    /**
     * Enable/disable collapsing submenu items with exactly one child.
     *
     * @param  bool $collapse
     * @return $this
     */
    public function setCollapseSingleChildSubmenu($collapse)
    {
        // This is a menu-level render preference, not persisted on individual items.
        $this->collapseSingleChildSubmenu = (bool) $collapse;

        return $this;
    }

    /**
     * Add a link to the menu.
     *
     * @param CanDisplayInMenu $item
     * @param SpatieMenu $menu
     */
    public function addLink(CanDisplayInMenu|array $item, $menu)
    {
        // Build and style the top-level/menu link output.
        $link = $menu->linkIf($item->canBeViewed(), $item->getUrl(), $this->buildLabel($item));
        $link->addItemParentClass('page-nav-item');
        $link->setActiveClass('page-nav-item--active');

        // Mark links active for exact URL matches and nested URL sections.
        $link->setActive(function ($link) use ($item, $menu) {
            /** @var \Spatie\Menu\Link $link */
            if ($link->url() === url()->current()) {
                return true;
            }

            $isNotHomepage = url($link->url()) !== url('/');
            $containsUrl = Str::contains(url()->current(), $link->url());

            if ($isNotHomepage && $containsUrl && ! $menu->isExactActive()) {
                return true;
            }

            return false;
        });
    }

    /**
     * Build the label for the link,
     *
     * @param  CanDisplayInMenu $item
     * @return string
     */
    protected function buildLabel(CanDisplayInMenu $item)
    {
        // return $item->getLabel() .'-'.$item->getPosition();
        return $item->getLabel() ?? 'N/A';
    }

    /**
     * Build a submenu link.
     *
     * @param  CanDisplayInMenu $item
     * @return Link
     */
    public function addSubmenuLink(CanDisplayInMenu $item)
    {
        return Link::to(
                '#' . $item->getUrl(),
                sprintf('%s <span class="caret"></span>', $this->buildLabel($item))
            )
            ->addClass('dropdown-toggle')
            ->setAttribute('data-toggle', 'dropdown')
            ->setAttribute('aria-haspopup', 'true')
            ->setAttribute('aria-expanded', 'false');
    }

    /**
     * Build the menu.
     *
     * @param  \Illuminate\Support\Collection|Iterator|array $links
     * @return SpatieMenu
     */
    public function buildMenu($links): SpatieMenu
    {
        return MenuExtended::build($links->toArray(), function ($menu, $item) {
            $item = $this->normalizeMenuItem($item);

            if (! $item->hasChildren()) {
                // Leaf items render as direct links.
                $this->addLink($item, $menu);
            } else {
                // When enabled, collapse single-child submenus into one direct link using parent ordering.
                if ($this->collapseSingleChildSubmenu && $item->getChildren()->count() === 1) {
                    $child = clone $item->getChildren()->first();
                    $child->setPosition($item->getPosition());
                    if ($item->isStickyLabel()) {
                        // apply label to the child so it remains visible when collapsed.
                        $child->setLabel($item->getLabel());
                        $child->setStickyLabel(true);
                    }
                    $this->addLink($child, $menu);
                    return;
                }

                // Render the standard dropdown parent + nested menu.
                $menu->submenu(
                    $this->addSubmenuLink($item),
                    $this->buildMenu($item->getChildren())
                         ->addClass('dropdown-menu page-nav-dropdown')
                         ->addParentClass('page-nav-item page-nav-item--has-dropdown dropdown')
                );
            }
        });
    }

    /**
     * Normalize array payloads into item objects for consistent rendering behavior.
     *
     * @param  CanDisplayInMenu|array $item
     * @return CanDisplayInMenu
     */
    protected function normalizeMenuItem($item)
    {
        if ($item instanceof CanDisplayInMenu) {
            return $item;
        }

        $menuItem = new Item(
            $item['url'],
            $item['label'],
            $item['position'],
            $item['allow'],
            $item['children'],
            $item['icon'],
            $item['badge'],
            $item['sticky_label'] ?? false
        );

        return $menuItem;
    }

    /**
     * Render the menu.
     */
    public function render(): string
    {
        // Let modules/listeners mutate menu items before we compile HTML.
        event(new NavigationMenuPreCompile($this));

        // Build the final menu tree and apply root-level classes.
        $this->menu = $this->buildMenu($this->getItems())
            ->addClass('page-nav-list page-nav--right');

        // Render the compiled Spatie menu into HTML.
        return $this->menu->render();
    }
}
