<?php

declare(strict_types=1);

namespace App\Framework\Markdown;

/**
 * Complete Markdown renderer with styling and themes
 */
final readonly class MarkdownRenderer
{
    public function __construct(
        private MarkdownConverter $converter,
    ) {
    }

    public function render(string $markdown, string $theme = 'default', array $options = []): string
    {
        $html = $this->converter->toHtml($markdown);

        return $this->wrapWithLayout($html, $theme, $options);
    }

    public function renderFile(string $filePath, string $theme = 'default', array $options = []): string
    {
        if (! file_exists($filePath)) {
            throw new \InvalidArgumentException("Markdown file not found: {$filePath}");
        }

        $markdown = file_get_contents($filePath);

        return $this->render($markdown, $theme, $options);
    }

    public function renderToHtmlOnly(string $markdown): string
    {
        return $this->converter->toHtml($markdown);
    }

    private function wrapWithLayout(string $content, string $theme, array $options): string
    {
        $markdownTheme = new MarkdownTheme($theme);
        $styles = $markdownTheme->getStyles();

        $title = $options['title'] ?? 'Documentation';
        $viewport = $options['viewport'] ?? 'width=device-width, initial-scale=1.0';
        $extraStyles = $options['extraStyles'] ?? '';
        $extraScripts = $options['extraScripts'] ?? '';

        $syntaxHighlighting = $options['syntaxHighlighting'] ?? true;
        $syntaxHighlightingScript = $syntaxHighlighting ? $this->getSyntaxHighlightingScript() : '';

        return <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="{$viewport}">
    <title>{$title}</title>
    <style>{$styles}{$extraStyles}</style>
    {$syntaxHighlightingScript}
</head>
<body>
    <div class="markdown-content">
        {$content}
    </div>
    {$extraScripts}
</body>
</html>
HTML;
    }

    private function getSyntaxHighlightingScript(): string
    {
        return <<<HTML
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-php.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-javascript.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-json.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-bash.min.js"></script>
HTML;
    }
}
