<?php

namespace App\Framework\View\Processors;

use App\Framework\View\DomProcessor;
use App\Framework\View\DomWrapper;
use App\Framework\View\RenderContext;
use Dom\HTMLDocument;

/*

<component name="card">
   <slot name="header">Default Header</slot>
   <slot>Main Content</slot>
 </component>

*/


final readonly class SlotProcessor implements DomProcessor
{
    public function process(DomWrapper $dom, RenderContext $context): DomWrapper
    {
        foreach ($dom->querySelectorAll('slot[name]') as $slotNode) {
            $slotName = $slotNode->getAttribute('name');
            $html = $context->slots[$slotName] ?? null;

            $replacement = $dom->createDocumentFragment();

            if ($html !== null) {
                @$replacement->appendXML($html);
            } else {
                // Fallback-Inhalt erhalten (die inneren Nodes des slot-Tags)
                foreach ($slotNode->childNodes as $child) {
                    $replacement->appendChild($child->cloneNode(true));
                }
            }

            $slotNode->parentNode?->replaceChild($replacement, $slotNode);
        }

        return $dom;
    }
}
