<?php
declare(strict_types=1);

namespace PpPhp\Core\Designer\Navigation;

final class DesignerNavigationRenderer
{
    public function render(array $menuComponent): string
    {
        $props = (array) ($menuComponent['props'] ?? $menuComponent);
        $placement = (string) ($props['placement'] ?? 'sidebar');
        $items = (array) ($props['items'] ?? []);

        return '<nav class="ppd-navigation ppd-navigation-' . $this->e($placement) . '" data-menu-id="' . $this->e((string) ($props['menuId'] ?? $props['id'] ?? 'menu')) . '">' .
            '<div class="ppd-navigation-title">' . $this->e((string) ($props['label'] ?? 'Menu')) . '</div>' .
            $this->renderItems($items) .
            '</nav>';
    }

    private function renderItems(array $items): string
    {
        $html = '<ul class="ppd-nav-list">';
        foreach ($items as $item) {
            $children = (array) ($item['children'] ?? []);
            $html .= '<li class="ppd-nav-item" data-nav-id="' . $this->e((string) ($item['id'] ?? 'item')) . '">';
            $html .= '<a href="#' . $this->e((string) ($item['target'] ?? $item['route'] ?? '')) . '">';
            $html .= '<i class="' . $this->e((string) ($item['icon'] ?? 'bi-circle')) . '"></i>';
            $html .= '<span>' . $this->e((string) ($item['label'] ?? 'Item')) . '</span>';
            $html .= '</a>';
            if ($children !== []) {
                $html .= $this->renderItems($children);
            }
            $html .= '</li>';
        }
        return $html . '</ul>';
    }

    private function e(string $value): string
    {
        return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
    }
}
