<?php

declare(strict_types=1);

require_once __DIR__ . '/../vendor/autoload.php';

use App\Framework\View\Dom\Parser\HtmlParser;
use App\Framework\View\Dom\Query\QuerySelector;
use App\Framework\View\Dom\Renderer\HtmlRenderer;
use App\Framework\View\Dom\Transformer\XComponentTransformer;

// Example HTML
$html = <<<HTML
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <title>Test Document</title>
    <script>
        console.log("Hello <world>");
    </script>
</head>
<body>
    <div class="container">
        <h1 id="title">Welcome</h1>
        <x-counter initial="5" />
        <p>Some text content</p>
        <!-- This is a comment -->
        <x-button color="primary">Click me</x-button>
    </div>
</body>
</html>
HTML;

// 1. Parse HTML to AST
$parser = new HtmlParser();
$document = $parser->parse($html);

echo "=== Parsed Document ===\n\n";

// 2. Query DOM
$querySelector = new QuerySelector();

// Find element by ID
$title = $querySelector->querySelector($document, '#title');
if ($title) {
    echo "Found title: " . $title->getTextContent() . "\n";
}

// Find elements by class
$containers = $querySelector->querySelectorAll($document, '.container');
echo "Found " . count($containers) . " container(s)\n";

// Find all x-components
$xComponents = $querySelector->querySelectorAll($document, 'x-counter');
echo "Found " . count($xComponents) . " x-counter component(s)\n\n";

// 3. Transform AST using Visitor
$transformer = new XComponentTransformer();
$document->accept($transformer);

$xComponents = $transformer->getXComponents();
echo "=== X-Components found ===\n";
foreach ($xComponents as $component) {
    echo "- <" . $component->getTagName() . ">";
    foreach ($component->getAttributes() as $attr) {
        echo " " . $attr;
    }
    echo "\n";
}
echo "\n";

// 4. Render back to HTML
$renderer = new HtmlRenderer(pretty: true);
$output = $renderer->render($document);

echo "=== Rendered HTML (pretty) ===\n\n";
echo $output;

// 5. Clone and modify
$cloned = $document->clone();
$clonedTitle = $querySelector->querySelector($cloned, '#title');
if ($clonedTitle instanceof \App\Framework\View\Dom\ElementNode) {
    $clonedTitle->setAttribute('class', 'modified');
}

echo "\n=== Modified Clone ===\n\n";
$modifiedOutput = $renderer->render($cloned);
echo substr($modifiedOutput, 0, 500) . "...\n";

echo "\n✅ DOM Parser working successfully!\n";
