<?php

namespace App\Framework\View\Processors;

use App\Framework\View\DomProcessor;
use App\Framework\View\DomTemplateParser;
use App\Framework\View\DomWrapper;
use App\Framework\View\Loading\TemplateLoader;
use App\Framework\View\RenderContext;
use Dom\Element;

final readonly class LayoutTagProcessor implements DomProcessor
{
    public function __construct(
        private TemplateLoader $loader,
        private DomTemplateParser $parser = new DomTemplateParser()
    ) {
        #$this->loader = new TemplateLoader($this->pathProvider);
    }

    public function process(DomWrapper $dom, RenderContext $context): DomWrapper
    {
        $layoutTag = $this->findLayoutTag($dom);

        if (!$layoutTag) {
            return $dom;
        }

        return $this->applyLayout($layoutTag, $dom);
    }

    private function findLayoutTag(DomWrapper $dom): ?Element
    {
        $dom = $dom->document;
        $layoutTags = $dom->querySelectorAll('layout[src]');
        return $layoutTags->length > 0 ? $layoutTags->item(0) : null;
    }

    private function applyLayout(Element $layoutTag, DomWrapper $dom): DomWrapper
    {
        $layoutFile = $layoutTag->getAttribute('src');

        $layoutPath = $this->loader->getTemplatePath($layoutFile);

        $layoutDom = $this->parser->parseFileToWrapper($layoutPath);
        $slot = $layoutDom->document->querySelector('main');

        if (!$slot) {
            return $dom; // Kein Slot verfügbar
        }

        $slot->innerHTML = $layoutTag->innerHTML;

        return $layoutDom;
    }
}
