<?php

declare(strict_types=1);

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

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

// Test 1: Basic DOM manipulation
echo "=== Test 1: Basic DOM Creation ===\n";
$html = '<html><body><x-counter id="demo" /></body></html>';
$dom = DomWrapper::fromString($html);
echo "Original HTML: " . $dom->document->saveHTML() . "\n\n";

// Test 2: Find x-counter element
echo "=== Test 2: Find x-counter Element ===\n";
$allElements = $dom->document->getElementsByTagName('*');
foreach ($allElements as $element) {
    if ($element instanceof \Dom\HTMLElement) {
        echo "Found element: {$element->tagName} (lowercase: " . strtolower($element->tagName) . ")\n";

        if (str_starts_with(strtolower($element->tagName), 'x-')) {
            echo "  -> This is an x-component!\n";
            $xComponent = $element;
        }
    }
}
echo "\n";

// Test 3: Try to replace element
echo "=== Test 3: Try replaceElementWithHtml ===\n";
if (isset($xComponent)) {
    $replacementHtml = '<div data-component-id="counter:demo">Counter HTML</div>';
    echo "Replacement HTML: {$replacementHtml}\n";

    try {
        $dom->replaceElementWithHtml($xComponent, $replacementHtml);
        echo "Replacement successful!\n";
        echo "New HTML: " . $dom->document->saveHTML() . "\n";
    } catch (\Throwable $e) {
        echo "ERROR: " . $e->getMessage() . "\n";
        echo "Stack trace:\n" . $e->getTraceAsString() . "\n";
    }
} else {
    echo "ERROR: xComponent not found!\n";
}
echo "\n";

// Test 4: Alternative approach - direct parent manipulation
echo "=== Test 4: Alternative - Direct Parent Manipulation ===\n";
$html2 = '<html><body><x-test /></body></html>';
$dom2 = DomWrapper::fromString($html2);
$allElements2 = $dom2->document->getElementsByTagName('*');

foreach ($allElements2 as $element) {
    if ($element instanceof \Dom\HTMLElement && strtolower($element->tagName) === 'x-test') {
        echo "Found x-test element\n";

        // Try direct HTML injection via innerHTML
        if ($element->parentNode) {
            echo "Has parent node: " . $element->parentNode->nodeName . "\n";

            // Create new element manually
            $newDiv = $dom2->document->createElement('div');
            $newDiv->setAttribute('data-test', 'replacement');
            $newDiv->textContent = 'Replacement Content';

            $element->parentNode->replaceChild($newDiv, $element);
            echo "Direct replacement successful!\n";
            echo "New HTML: " . $dom2->document->saveHTML() . "\n";
        }
    }
}
