<?php

namespace Plainwork\UiWordPress\Renderer;

use Plainwork\Http\Request;
use Plainwork\Http\Uri;
use Plainwork\Ui\Ui;
use Plainwork\Ui\HtmlHelper;
use Plainwork\Ui\Component\TabMenu;
use Plainwork\Ui\Component\Link;
use Plainwork\Ui\Renderer\MenuRenderer;

class AdminTabMenuRenderer
{
    public $ui = Ui::class;
    public $uri = Uri::class;
    public $menuRenderer = MenuRenderer::class;

    public function __invoke(TabMenu $el, Request $request)
    {
        $ret = '';

        $isPrintView = $this->ui->isPrintView();
        if ($isPrintView) {
            return $ret;
        }

        $items = $el->getItems();
        $items = array_filter($items, fn($e) => $this->menuRenderer->isItemAllowed($e, $request));

        if (!$items) {
            return $ret;
        }

        $currentId = $el->getCurrent();

        $ret = [];

        $ret[] = '<div class="pw-header-tabmenu">';
        $ret[] = '<div class="nav-tab-wrapper">';
        foreach ($items as $itemId => $item) {
            $isOn = ($itemId == $currentId) ? true : false;
            if ($item instanceof Link) {
                $item->withAttr('class', 'nav-tab');
                if ($isOn) {
                    $item->withAttr('class', 'nav-tab-active');
                }

                $v = $this->ui->render($item, $request);
                if (!strlen($v)) {
                    continue;
                }

                $ret[] = $v;
            } else {
                $ret[] = '<span style="padding: .5em;">';
                $v = $this->ui->render($item, $request);
                $ret[] = $v;
                // $ret[] = '</span>';
            }
        }
        $ret[] = '</div>';
        $ret[] = '</div>';

        $ret = join('', $ret);

        return $ret;
    }
}
