<?php

namespace PHPNative\Ui\Widget;

use PHPNative\Framework\TextRenderer;

class MenuBar extends Container
{
    /** @var Menu[] */
    private array $menus = [];
    private null|Menu $openMenu = null;

    public function __construct(string $style = 'w-full bg-gray-100 border-b border-gray-300')
    {
        parent::__construct('flex flex-row ' . $style);
    }

    public function addMenu(Menu $menu): Menu
    {
        $this->menus[] = $menu;
        $menu->setMenuBar($this);
        $this->addComponent($menu);

        return $menu;
    }

    public function closeAllMenus(): void
    {
        foreach ($this->menus as $menu) {
            $menu->close(false);
        }
        $this->openMenu = null;
    }

    public function notifyMenuOpened(Menu $menu): void
    {
        if ($this->openMenu !== null && $this->openMenu !== $menu) {
            $this->openMenu->close(false);
        }
        $this->openMenu = $menu;
    }

    public function notifyMenuClosed(Menu $menu): void
    {
        if ($this->openMenu === $menu) {
            $this->openMenu = null;
        }
    }

    public function handleMouseClick(float $mouseX, float $mouseY, int $button): bool
    {
        // First, let children handle the click (menus and their items)
        $handled = parent::handleMouseClick($mouseX, $mouseY, $button);

        // If no child handled the click and we have an open menu, close all menus
        if (!$handled && $this->openMenu !== null) {
            $this->closeAllMenus();
            return true;
        }

        return $handled;
    }
}
