<?php

namespace App\Framework\View\Processors;

use App\Framework\View\RenderContext;
use App\Framework\View\StringProcessor;

final readonly class EscapeProcessor implements StringProcessor
{
    public function process(string $html, RenderContext $context): string
    {
        // Erst rohe Inhalte einsetzen (drei geschweifte Klammern)
        $html = preg_replace_callback('/{{{\s*(\w+)\s*}}}/', function ($matches) use ($context) {
            return $context->data[$matches[1]] ?? '';
        }, $html);

        // Dann alle übrigen Variablen escapen
        $html = preg_replace_callback('/{{\s*(\w+)\s*}}/', function ($matches) use ($context) {
            $value = $context->data[$matches[1]] ?? '';
            return htmlspecialchars((string)$value, ENT_QUOTES | ENT_HTML5);
        }, $html);

        return $html;
    }
}
