<?php

declare(strict_types=1);

namespace App\Framework\View\Components;

use App\Framework\Core\ValueObjects\HtmlLink;
use App\Framework\Core\ValueObjects\LinkCollection;
use App\Framework\View\Attributes\ComponentName;
use App\Framework\View\Contracts\StaticComponent;
use App\Framework\View\Dom\ElementNode;
use App\Framework\View\Dom\Node;
use App\Framework\View\Dom\TextNode;

#[ComponentName('breadcrumbs')]
final readonly class Breadcrumbs implements StaticComponent
{
    private LinkCollection $links;

    /**
     * @param string $content Inner content (unused for this component)
     * @param array<string, string> $attributes Component attributes
     *                                          - items: JSON array [{"url": "/", "text": "Home"}]
     */
    public function __construct(
        string $content = '',
        array $attributes = []
    ) {
        // Parse items from JSON attribute
        $items = $attributes['items'] ?? '[]';
        $this->links = $this->parseLinksFromJson($items);
    }

    public function getRootNode(): Node
    {
        $nav = new ElementNode('nav');
        $nav->setAttribute('class', 'admin-breadcrumbs');
        $nav->setAttribute('aria-label', 'Breadcrumb');

        // Use TextNode for HTML content
        $content = new TextNode($this->buildBreadcrumbsContent());
        $nav->appendChild($content);

        return $nav;
    }

    private function parseLinksFromJson(string $items): LinkCollection
    {
        try {
            $decoded = json_decode($items, true, 512, JSON_THROW_ON_ERROR);
            if (!is_array($decoded)) {
                return $this->getDefaultLinks();
            }

            // Use LinkCollection::fromUrlsAndTexts() for clean creation
            return LinkCollection::fromUrlsAndTexts($decoded);
        } catch (\JsonException) {
            return $this->getDefaultLinks();
        }
    }

    private function getDefaultLinks(): LinkCollection
    {
        return new LinkCollection(
            HtmlLink::create(href: '/admin', text: 'Admin')
                ->withClass('admin-breadcrumbs__link')
        );
    }

    private function buildBreadcrumbsContent(): string
    {
        if ($this->links->isEmpty()) {
            return '';
        }

        $listItems = [];
        $totalLinks = $this->links->count();

        foreach ($this->links as $index => $link) {
            $isLast = ($index === $totalLinks - 1);
            $listItems[] = $this->renderBreadcrumbItem($link, $isLast);
        }

        $listItemsHtml = implode("\n", $listItems);

        return <<<HTML
            <ol class="admin-breadcrumbs__list" role="list">
                {$listItemsHtml}
            </ol>
        HTML;
    }

    private function renderBreadcrumbItem(HtmlLink $link, bool $isLast): string
    {
        $text = htmlspecialchars($link->text ?? 'Link', ENT_QUOTES, 'UTF-8');

        if ($isLast) {
            // Current page - no link
            return <<<HTML
                <li class="admin-breadcrumbs__item">
                    <span class="admin-breadcrumbs__current" aria-current="page">{$text}</span>
                </li>
            HTML;
        }

        // Render link with admin breadcrumb class
        $linkWithClass = $link->withClass('admin-breadcrumbs__link');
        $linkHtml = $linkWithClass->toHtml();

        return <<<HTML
            <li class="admin-breadcrumbs__item">
                {$linkHtml}
                <span class="admin-breadcrumbs__separator" aria-hidden="true">›</span>
            </li>
        HTML;
    }
}
