using Avalonia;
using Avalonia.Controls;
using Avalonia.Media;
using Markdig.Syntax;
using MarkdownEditor.Constants;

namespace MarkdownEditor.Views.Renderers;

/// <summary>
/// Renders markdown code blocks (both fenced and indented).
/// </summary>
public class CodeBlockRenderer : IMarkdownBlockRenderer
{
    private readonly bool _isDarkMode;
    private readonly double _fontScale;

    /// <summary>
    /// Initializes a new instance of the <see cref="CodeBlockRenderer"/> class.
    /// </summary>
    /// <param name="isDarkMode">Whether the current theme is dark mode.</param>
    /// <param name="fontScale">Font scale factor for text sizing.</param>
    public CodeBlockRenderer(bool isDarkMode = true, double fontScale = 1.0)
    {
        _isDarkMode = isDarkMode;
        _fontScale = fontScale;
    }

    /// <inheritdoc/>
    public bool CanRender(Block block) => block is CodeBlock;

    /// <inheritdoc/>
    public Control? Render(Block block)
    {
        if (block is not CodeBlock code)
        {
            return null;
        }

        var text = code is FencedCodeBlock fenced
            ? fenced.Lines.ToString()
            : code.Lines.ToString();

        return new Border
        {
            Background = new SolidColorBrush(Color.Parse(_isDarkMode ? "#2D2D2D" : "#F0F0F0")),
            Padding = new Thickness(10),
            Margin = new Thickness(0, 5, 0, 5),
            CornerRadius = new CornerRadius(4),
            Child = new SelectableTextBlock
            {
                Text = text,
                FontFamily = new FontFamily("Consolas,Courier New,monospace"),
                FontSize = 14 * _fontScale,
                Foreground = new SolidColorBrush(Color.Parse(_isDarkMode ? "#E8E8E8" : "#333333")),
                TextWrapping = TextWrapping.Wrap
            }
        };
    }
}

