<?php

declare(strict_types=1);

// Test HTML Entity Escaping in HTMLDocument

// Test 1: Create HTML with escaped attributes
$json = json_encode(['id' => 'test:123', 'data' => 'value']);
echo "Original JSON:\n";
echo $json . "\n\n";

$htmlWithEscaped = sprintf('<div data-state="%s">Content</div>', htmlspecialchars($json, ENT_QUOTES, 'UTF-8'));
echo "HTML with htmlspecialchars:\n";
echo $htmlWithEscaped . "\n\n";

// Test 2: Parse with HTMLDocument
$dom = Dom\HTMLDocument::createFromString($htmlWithEscaped);
echo "After parsing with HTMLDocument:\n";
$serialized = $dom->saveHTML();
echo $serialized . "\n\n";

// Test 3: Check the attribute value
$div = $dom->body->firstChild;
if ($div) {
    echo "Attribute value from DOM:\n";
    echo $div->getAttribute('data-state') . "\n\n";
}

// Test 4: Create with wrapper div and extract
$wrappedHtml = '<div>' . $htmlWithEscaped . '</div>';
$dom2 = Dom\HTMLDocument::createFromString($wrappedHtml);
echo "With wrapper div:\n";
echo $dom2->saveHTML() . "\n\n";

// Test 5: Check if double escaping occurs
$innerHTML = $dom2->body->innerHTML;
echo "Body innerHTML:\n";
echo $innerHTML . "\n\n";

if (str_contains($innerHTML, '&amp;quot;')) {
    echo "❌ DOUBLE ESCAPING DETECTED!\n";
} else {
    echo "✅ No double escaping\n";
}
