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

namespace MarkdownEditor.Views.Renderers;

/// <summary>
/// Renders markdown heading blocks (H1-H6).
/// </summary>
public class HeadingRenderer : IMarkdownBlockRenderer
{
    private readonly double _fontScale;

    /// <summary>
    /// Initializes a new instance of the <see cref="HeadingRenderer"/> class.
    /// </summary>
    /// <param name="fontScale">Font scale factor for text sizing.</param>
    public HeadingRenderer(double fontScale = 1.0)
    {
        _fontScale = fontScale;
    }

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

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

        var text = MarkdownTextHelper.ExtractText(heading.Inline);
        var fontSize = GetFontSizeForLevel(heading.Level) * _fontScale;

        return new TextBlock
        {
            Text = text,
            FontSize = fontSize,
            FontWeight = FontWeight.Bold,
            TextWrapping = TextWrapping.Wrap,
            Margin = new Thickness(0, 10, 0, 5)
        };
    }

    private static int GetFontSizeForLevel(int level) => level switch
    {
        1 => AppConstants.FontSizes.Heading1,
        2 => AppConstants.FontSizes.Heading2,
        3 => AppConstants.FontSizes.Heading3,
        4 => AppConstants.FontSizes.Heading4,
        5 => AppConstants.FontSizes.Heading5,
        _ => AppConstants.FontSizes.Heading6
    };
}

