<?php

declare(strict_types=1);

namespace App\Framework\Template\Parser;

use App\Framework\View\DomWrapper;
use App\Framework\View\Lexer\HtmlLexer;
use Dom\HTMLDocument;

final readonly class DomTemplateParser
{
    public function parse(string $html): HTMLDocument
    {
        // Normalize self-closing x-components BEFORE HTML5 parsing
        // HTML5 parser doesn't respect self-closing syntax for custom elements
        // <x-counter /> becomes <x-counter></x-counter>
        $html = $this->normalizeXComponents($html);

        libxml_use_internal_errors(true);

        $dom = HTMLDocument::createFromString($html);

        libxml_clear_errors();

        return $dom;
    }

    /**
     * Normalize self-closing x-components to explicit closing tags
     *
     * HTML5 parser treats <x-counter /> as <x-counter> with no closing tag,
     * causing subsequent elements to be parsed as children.
     *
     * This method converts <x-counter /> to <x-counter></x-counter>
     */
    private function normalizeXComponents(string $html): string
    {
        $lexer = new HtmlLexer($html);
        return $lexer->normalizeXComponents();
    }

    /**
     * Erstellt einen DomWrapper aus HTML-String
     */
    public function parseToWrapper(string $html): DomWrapper
    {
        return DomWrapper::fromString($html);
    }

    /**
     * Erstellt einen DomWrapper aus Datei
     */
    public function parseFileToWrapper(string $path): DomWrapper
    {
        return DomWrapper::fromFile($path);
    }

    public function toHtml(HTMLDocument $dom): string
    {
        return $dom->saveHTML();
    }

    public function parseFile(string $path): HTMLDocument
    {
        return HTMLDocument::createFromFile($path);
    }
}
