<?php

namespace App\Framework\View;

use Dom\Element;

final readonly class DomComponentService
{
    public function replaceComponent(DomWrapper $dom, Element $component, string $html): void {
        $dom->replaceElementWithHtml($component, $html);
    }

    public function processSlots(DomWrapper $dom): void {
        $slots = $dom->getElementsByTagName('slot');

        $slots->forEach(function($slot) use ($dom) {
            $name = $slot->getAttribute('name') ?? 'default';
            $content = $this->getSlotContent($dom, $name);

            if ($content) {
                $dom->replaceElementWithHtml($slot, $content);
            }
        });
    }

    private function getSlotContent(DomWrapper $dom, string $name): ?string {
        $slotProviders = $dom->getElementsByAttribute('slot', $name);
        if ($slotProviders->isEmpty()) {
            return null;
        }

        return $slotProviders->first()->innerHTML;
    }
}
