<?php

declare(strict_types=1);

namespace App\Core;

class View
{
    public static function render(string $view, array $params = []): string
    {
        $viewPath = app()->basePath("app/Views/{$view}.php");

        if (!file_exists($viewPath)) {
            throw new \RuntimeException("View {$view} not found.");
        }

        extract($params, EXTR_SKIP);

        ob_start();
        include $viewPath;
        $content = ob_get_clean() ?: '';
        $base = app()->publicBasePath();

        if ($base === '') {
            return $content;
        }

        return (string) preg_replace_callback(
            '/\b(href|src|action)=(["\'])\/(?!\/)([^"\']*)\2/i',
            fn (array $match): string => $match[1] . '=' . $match[2] . $base . '/' . $match[3] . $match[2],
            $content
        );
    }
}
