<?php

declare(strict_types=1);

namespace App\Core;

final class View
{
    /** @param array<string, mixed> $data */
    public static function render(string $view, array $data = [], ?string $layout = 'layouts/main'): void
    {
        extract($data, EXTR_SKIP);

        $viewFile = \base_path('app/Views/' . $view . '.php');
        if (!is_file($viewFile)) {
            throw new \RuntimeException('View not found: ' . $view);
        }

        RequestTrace::begin('view_content_render');
        ob_start();
        require $viewFile;
        $content = ob_get_clean();
        RequestTrace::end('view_content_render');

        if ($layout === null) {
            echo $content;
            return;
        }

        $layoutFile = \base_path('app/Views/' . $layout . '.php');
        if (!is_file($layoutFile)) {
            throw new \RuntimeException('Layout not found: ' . $layout);
        }

        RequestTrace::begin('layout_render');
        ob_start();
        require $layoutFile;
        $html = (string) ob_get_clean();
        RequestTrace::end('layout_render');
        if (RequestTrace::enabled()) {
            $config = json_encode(RequestTrace::browserConfig(), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
            $probe = '<script src="assets/js/revenue-performance-trace.js?v=h11-0-p11-1-r45-p2-1" defer></script><script>window.DDB_REVENUE_TRACE=' . $config . ';</script>';
            $html = str_replace('</body>', $probe . '</body>', $html);
            RequestTrace::emitHeaders();
        }
        echo $html;
    }
}
