using System;

using System.Collections.Generic;

using System.Drawing;

using System.Windows.Forms;

using Elfisa.UI.Theming;



namespace Elfisa.UI.Controls

{

    public class ModernTopNav : Panel

    {

        private readonly FlowLayoutPanel _layout;

        private readonly Dictionary<string, ModernButton> _buttons = new Dictionary<string, ModernButton>();

        private ThemeColors _theme;

        private string _activeKey;



        public event EventHandler<string> ItemSelected;



        public ModernTopNav()

        {

            Height = 48;

            Dock = DockStyle.Top;

            Padding = new Padding(20, 0, 20, 0);

            _layout = new FlowLayoutPanel

            {

                Dock = DockStyle.Fill,

                FlowDirection = FlowDirection.LeftToRight,

                WrapContents = false,

                AutoSize = false,

                Margin = new Padding(0),

                Padding = new Padding(0)

            };

            Controls.Add(_layout);

        }



        public void SetItems(IEnumerable<SidebarItem> items)

        {

            _layout.Controls.Clear();

            _buttons.Clear();

            foreach (var item in items)

            {

                var button = new ModernButton

                {

                    TopNavMode = true,

                    Text = item.Text,

                    AutoSize = true,

                    Height = 48,

                    Margin = new Padding(0, 0, 28, 0),

                    Padding = new Padding(4, 0, 4, 0),

                    Tag = item.Key,

                    Font = new Font("Segoe UI Semibold", 12f)

                };

                button.Click += (_, __) => SetActive(item.Key);

                _buttons[item.Key] = button;

                _layout.Controls.Add(button);

            }

        }



        public void SetActive(string key)

        {

            _activeKey = key;

            RefreshStates();

            ItemSelected?.Invoke(this, key);

        }



        public void ApplyTheme(ThemeColors theme)

        {

            _theme = theme;

            BackColor = theme.NavBackground;

            RefreshStates();

        }



        protected override void OnPaint(PaintEventArgs e)

        {

            var theme = _theme ?? ThemeManager.Colors;

            using (var pen = new Pen(theme.BorderSubtle))

            {

                e.Graphics.DrawLine(pen, 0, Height - 1, Width, Height - 1);

            }

        }



        private void RefreshStates()

        {

            var theme = _theme ?? ThemeManager.Colors;

            foreach (var pair in _buttons)

            {

                pair.Value.ApplyTheme(theme);

                pair.Value.IsActiveItem = pair.Key == _activeKey;

            }

        }

    }

}


