using System.Drawing;
using System.Windows.Forms;
using Elfisa.UI.Theming;

namespace Elfisa.UI.Controls
{
    /// <summary>
    /// Заголовок секции («Наименование», «Корзина»). Текст рисуется через OnPaint.
    /// </summary>
    public class ModernSectionHeader : Panel
    {
        private ThemeColors _theme;
        private bool _cartStyle;
        private string _headerText = string.Empty;

        public string HeaderText
        {
            get => _headerText;
            set
            {
                _headerText = value ?? string.Empty;
                Invalidate();
            }
        }

        public ModernSectionHeader()
        {
            Height = 34;
            Dock = DockStyle.Top;
            Padding = new Padding(10, 0, 10, 0);
            SetStyle(ControlStyles.AllPaintingInWmPaint |
                     ControlStyles.UserPaint |
                     ControlStyles.OptimizedDoubleBuffer |
                     ControlStyles.ResizeRedraw, true);
        }

        public void ApplyTheme(ThemeColors theme, bool cartStyle = false)
        {
            _theme = theme;
            _cartStyle = cartStyle;
            Invalidate();
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            var theme = _theme ?? ThemeManager.Colors;
            var g = e.Graphics;
            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
            var fill = _cartStyle ? theme.CartHeaderBackground : theme.SectionHeaderBackground;

            using (var brush = new SolidBrush(fill))
            {
                g.FillRectangle(brush, ClientRectangle);
            }

            using (var pen = new Pen(theme.Border))
            {
                g.DrawLine(pen, 0, Height - 1, Width, Height - 1);
            }

            if (!string.IsNullOrEmpty(_headerText))
            {
                var textRect = new Rectangle(Padding.Left, 0, Width - Padding.Horizontal, Height);
                TextRenderer.DrawText(
                    g,
                    _headerText,
                    theme.FontSemibold14,
                    textRect,
                    theme.TextPrimary,
                    TextFormatFlags.VerticalCenter | TextFormatFlags.Left | TextFormatFlags.SingleLine);
            }
        }

        protected override void OnPaintBackground(PaintEventArgs e)
        {
        }
    }
}
