<?php

declare(strict_types=1);

namespace App\Framework\View;

use Dom\Element;

final readonly class DomComponentService
{
    public function replaceComponent(DomWrapper $dom, Element $component, string $html): void
    {
        file_put_contents('/tmp/debug.log', "DomComponentService::replaceComponent - Component name: " . $component->getAttribute('name') . "\n", FILE_APPEND | LOCK_EX);
        file_put_contents('/tmp/debug.log', "DomComponentService::replaceComponent - HTML length: " . strlen($html) . "\n", FILE_APPEND | LOCK_EX);
        file_put_contents('/tmp/debug.log', "DomComponentService::replaceComponent - HTML starts: " . substr($html, 0, 200) . "\n", FILE_APPEND | LOCK_EX);

        $dom->replaceElementWithHtml($component, $html);

        file_put_contents('/tmp/debug.log', "DomComponentService::replaceComponent - Replacement completed\n", FILE_APPEND | LOCK_EX);
    }

    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;
    }
}
