namespace YMhut.Box.Core.Tools;

public readonly record struct ToolboxGridLayout(
    int Columns,
    double CardWidth,
    double ItemWidth,
    bool ShowCategoryRail,
    bool IsCompact);

public static class ToolboxLayoutCalculator
{
    public const double MinCardWidth = 264;
    public const double MaxCardWidth = 360;
    public const double ItemGap = 14;

    public static ToolboxGridLayout Calculate(double availableWidth)
    {
        if (double.IsNaN(availableWidth) || double.IsInfinity(availableWidth) || availableWidth <= 0)
        {
            return new ToolboxGridLayout(3, 318, 332, ShowCategoryRail: true, IsCompact: false);
        }

        var showCategoryRail = availableWidth >= 900;
        var usable = Math.Max(MinCardWidth, availableWidth - 28);
        var columns = ColumnsFor(usable);
        var cardWidth = Math.Floor((usable - (columns - 1) * ItemGap) / columns);
        cardWidth = Math.Clamp(cardWidth, MinCardWidth, MaxCardWidth);

        return new ToolboxGridLayout(
            columns,
            cardWidth,
            cardWidth + ItemGap,
            showCategoryRail,
            IsCompact: availableWidth < 720);
    }

    private static int ColumnsFor(double usableWidth)
    {
        if (usableWidth < 620)
        {
            return 1;
        }

        if (usableWidth < 900)
        {
            return 2;
        }

        if (usableWidth < 1220)
        {
            return 3;
        }

        if (usableWidth < 1540)
        {
            return 4;
        }

        if (usableWidth < 1880)
        {
            return 5;
        }

        return 6;
    }
}
