<?php

declare(strict_types=1);

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

use App\Framework\DI\DefaultContainer;
use App\Framework\Meta\MetaData;
use App\Framework\View\DomWrapper;
use App\Framework\View\Processors\ForProcessor;
use App\Framework\View\RenderContext;

// Create minimal container for testing
$container = new DefaultContainer();

// Test ForProcessor directly
$forProcessor = new ForProcessor($container);
echo "=== Testing ForProcessor Directly ===\n";

// Test data
$testData = [
    'title' => 'Test Title',
    'items' => [
        ['name' => 'Item 1', 'value' => 'Value 1'],
        ['name' => 'Item 2', 'value' => 'Value 2'],
        ['name' => 'Item 3', 'value' => 'Value 3'],
    ],
];

// Create test template content
$templateContent = '<div><ul><for var="item" in="items"><li>{{ item.name }}: {{ item.value }}</li></for></ul></div>';

echo "Template Content: $templateContent\n\n";
echo "Test Data:\n";
print_r($testData);
echo "\n";

try {
    // Create DomWrapper from template content
    $dom = DomWrapper::fromString($templateContent);

    // Create render context
    $context = new RenderContext(
        template: 'test',
        metaData: new MetaData('Test', 'Test Description'),
        data: $testData,
        controllerClass: null
    );

    echo "Before ForProcessor:\n";
    echo $dom->document->saveHTML() . "\n\n";

    // Process with ForProcessor
    $result = $forProcessor->process($dom, $context);

    echo "After ForProcessor:\n";
    echo $result->document->saveHTML() . "\n\n";

    // Check if for loop was processed
    $html = $result->document->saveHTML();
    if (strpos($html, '<for') !== false) {
        echo "❌ ERROR: <for> tags not processed!\n";
    } else {
        echo "✅ SUCCESS: <for> tags processed!\n";
    }

    // Check if placeholders were replaced
    if (strpos($html, '{{') !== false) {
        echo "⚠️  WARNING: Some placeholders remain:\n";
        preg_match_all('/{{[^}]+}}/', $html, $matches);
        foreach ($matches[0] as $placeholder) {
            echo "  - $placeholder\n";
        }
    } else {
        echo "✅ SUCCESS: All placeholders replaced!\n";
    }

} catch (Exception $e) {
    echo "❌ ERROR: " . $e->getMessage() . "\n";
    echo "Stack trace:\n" . $e->getTraceAsString() . "\n";
}
