using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using NyxCS2.Core;

namespace NyxCS2.UI;

// ============================================================================
//  NYX CS2 external cheat menu  (neon sidebar + dark panels)
//
//  Layout: 152px neon sidebar (VISUALS / AIM / TRIGGER / EXTRA tabs) on the
//  left, active section panel on the right. Dark #0d1117 background with
//  #00d4ff accent, Segoe UI. Every control writes straight into AppSettings
//  (the overlay re-reads it every tick), so toggles apply live - no reopen.
// ============================================================================
public class MenuForm : Form
{
    private readonly Engine _engine;
    private readonly AppSettings _s;
    private readonly OverlayForm _overlay;

    private readonly Label _status;
    private Label _valFov, _valSmooth, _valDist, _valTrig;

    private readonly Panel _sidebar;
    private readonly Panel _pVisuals, _pAim, _pTrig, _pExtra;
    private readonly Dictionary<Button, Panel> _tabMap = new();
    private readonly List<Button> _pending = new();
    private readonly System.Windows.Forms.Timer _statusTimer;

    // ---------------- theme ----------------
    private static readonly Color Bg = Color.FromArgb(13, 17, 23);          // #0d1117
    private static readonly Color Side = Color.FromArgb(22, 27, 34);        // #161b22
    private static readonly Color Accent = Color.FromArgb(0, 212, 255);     // #00d4ff
    private static readonly Color TextMain = Color.GainsboroCounty;
    private static readonly Color TextDim = Color.FromArgb(139, 148, 158);  // #8b969e

    public MenuForm(Engine engine, AppSettings s, OverlayForm overlay)
    {
        _engine = engine;
        _s = s;
        _overlay = overlay;

        Text = "NYX CS2 v" + NyxCS2.Program.Version + " - external";
        FormBorderStyle = FormBorderStyle.FixedSingle;
        MaximizeBox = false;
        ClientSize = new Size(604, 540);
        StartPosition = FormStartPosition.CenterScreen;
        BackColor = Bg;
        ForeColor = TextMain;
        Font = new Font("Segoe UI", 9f, FontStyle.Regular);

        // ---------------- sidebar ----------------
        _sidebar = new Panel
        {
            Bounds = new Rectangle(0, 0, 152, ClientSize.Height),
            BackColor = Side
        };
        Controls.Add(_sidebar);

        _sidebar.Controls.Add(new Label
        {
            Text = "NYX CS2",
            Location = new Point(14, 12),
            AutoSize = true,
            Font = new Font("Segoe UI", 13f, FontStyle.Bold),
            ForeColor = Accent
        });
        _sidebar.Controls.Add(new Label
        {
            Text = "v" + NyxCS2.Program.Version,
            Location = new Point(14, 34),
            AutoSize = true,
            ForeColor = TextDim
        });

        int by = 58;
        by = AddTab("VISUALS", by);
        by = AddTab("AIM", by);
        by = AddTab("TRIGGER", by);
        by = AddTab("EXTRA", byWeekly);
        WirePending();

        // ---------------- panels ----------------
        _pVisuals = NewSection();
        _pAim = NewSection();
        _pTrig = NewSection();
        _pExtra = NewSection();

        BuildVisuals(_pVisuals);
        BuildAim(_pAim);
        BuildTrig(_pTrig);
        BuildExtra(_pExtra);

        // ---------------- bottom bar ----------------
        AddBottom("Quit", 12, () => Application.Exit());
        AddBottom("Hide overlay", 96, () => _overlay.Toggle());
        var aim = AddBottom("Aim: ON/OFF", 200, () =>
        {
            _s.AimEnabled = !_s.AimEnabled;
            aim.Text = _s.AimEnabled ? "Aim: ON/OFF" : "Aim: OFF";
        });
        AddBottom("Re-fetch", 284, () => NyxCS2.Core.OffsetUpdater.RefetchNow());

        _statusTimer = new System.Windows.Forms.Timer { Interval = 1000 };
        _statusTimer.Tick += (_, _) => UpdateStatus();
        _statusTimer.Start();
        UpdateStatus();

        SelectTab(_pVisuals);
    }

    public void Toggle()
    {
        if (InvokeRequired) { BeginInvoke(new Action(Toggle)); return; }
        Visible = !Visible;
    }

    // ------------------------------------------------------------------
    private Panel NewSection() =>
        new Panel
        {
            Bounds = new Rectangle(152, 0, ClientSize.Width - 152, ClientSize.Height - 44),
            BackColor = Bg
        };

    private int AddTab(string text, int y)
    {
        var b = new Button
        {
            Text = text,
            Location = new Point(8, y),
            Size = new Size(136, 36),
            FlatStyle = FlatStyle.Flat,
            FlatAppearance = { BorderSize = 0, MouseOverBackColor = Color.FromArgb(30, 36, 48) },
            BackColor = Side,
            ForeColor = Color.Gainsboro,
            TextAlign = ContentAlignment.MiddleLeft
        };
        b.Click += (_, _) => SelectTab(SectionFor(b));
        Controls.Add(b);
        _tabMap[b] = null!;
        _pending.Add(b);
        return y + 40;
    }

    private void WirePending()
    {
        foreach (var b in _pending)
            _tabMap[b] = SectionFor(b);
        _pending.Clear();
    }

    private Panel SectionFor(Button b) =>
        b.Text switch
        {
            "VISUALS" => _pVisuals,
            "AIM" => _pAim,
            "TRIGGER" => _pTrig,
            "EXTRA" => _pExtra,
            _ => _pVisuals
        };

    private void SelectTab(Panel target)
    {
        foreach (var kv in _tabMap)
        {
            bool active = ReferenceEquals(kv.Value, target);
            kv.Key.BackColor = active ? Color.FromArgb(0, 120, 160) : Side;
            kv.Key.ForeColor = active ? Color.White : Color.Gainsboro;
        }
        foreach (var pr in new[] { _pVisuals, _pAim, _pTrig, _pExtra })
            pr.Visible = ReferenceEquals(pr, target);
    }

    private void UpdateStatus()
    {
        try
        {
            var snap = _engine.Snap;
            _status.Text = snap == null ? "not started" : snap.Status;
        }
        catch { }
    }

    // ------------------------------------------------------------------
    private int AddHeader(string text, int y, Panel p)
    {
        p.Controls.Add(new Label
        {
            Text = text,
            Location = new Point(14, y),
            AutoSize = true,
            Font = new Font("Segoe UI", 10f, FontStyle.Bold),
            ForeColor = Accent
        });
        return y + 24;
    }

    private int AddCheck(string text, bool init, Action<bool> set, int y, Panel p)
    {
        var c = new CheckBox
        {
            Text = text,
            Checked = init,
            Location = new Point(14, y),
            AutoSize = true,
            ForeColor = TextMain
        };
        c.CheckedChanged += (_, _) => set(c.Checked);
        p.Controls.Add(c);
        return y + 28;
    }

    private int AddCombo(string text, string[] items, int sel, Action<int> set, int y, Panel p)
    {
        p.Controls.Add(new Label
        {
            Text = text,
            Location = new Point(14, y),
            AutoSize = true,
            ForeColor = TextDim
        });
        var cb = new ComboBox
        {
            Location = new Point(140, y - 2),
            Width = 100,
            DropDownStyle = ComboBoxStyle.DropDownList
        };
        cb.Items.AddRange(items);
        cb.SelectedIndex = sel;
        cb.SelectedIndexChanged += (_, _) => set(cb.SelectedIndex);
        p.Controls.Add(cb);
        return y + 30;
    }

    private int AddSlider(string text, int init, int min, int max, Action<int> set,
        out Label valLabel, int y, Panel p)
    {
        valLabel = new Label { Text = init.ToString(), Location = new Point(186, y), AutoSize = true, ForeColor = TextDim };
        p.Controls.Add(valLabel);
        var t = new TrackBar { Location = new Point(186, y - 4), Width = 150, Minimum = min, Maximum = max, Value = init, TickStyle = TickStyle.None };
        t.ValueChanged += (_, _) => set(t.Value);
        p.Controls.Add(t);
        return y + 34;
    }

    // ------------------------------------------------------------------
    private void BuildVisuals(Panel p)
    {
        int y = 16;
        y = AddHeader("VISUALS", y, p);
        y = AddCheck("ESP enabled", _s.EspEnabled, v => _s.EspEnabled = v, y, p);
        y = AddCheck("Boxes", _s.Boxes, v => _s.Boxes = v, y, p);
        y = AddCheck("Health bar", _s.HealthBar, v => _s.HealthBar = v, y, p);
        y = AddCheck("Name + distance", _s.ShowName, v => _s.ShowName = v, y, p);
        y = AddCheck("Snapline", _s.Snapline, v => _s.Snapline = v, y, p);
        y = AddCheck("Enemies only", _s.EnemiesOnly, v => _s.EnemiesOnly = v, y, p);
        y = AddCheck("Crosshair", _s.Crosshair, v => _s.Crosshair = v, y, p);
        y = AddCheck("Skeleton", _s.Skeleton, v => _s.Skeleton = v, y, p);
        y = AddCheck("Show player list", _s.ShowPlayerList, v => _s.ShowPlayerList = v, y, p);
        y = AddCheck("Weapon name", _s.WeaponEsp, v => _s.WeaponEsp = v, y, p);
        y = AddCheck("Armor bar", _s.ArmorBar, v => _s.ArmorBar = v, y, p);
        y = AddCheck("Health text", _s.HealthText, v => _s.HealthText = v, y, p);
    }

    private void BuildAim(Panel p)
    {
        int y = 16;
        y = AddHeader("AIM", y, p);
        y = AddCheck("Aim enabled", _s.AimEnabled, v => _s.AimEnabled = v, y, p);
        y = AddCombo("Aim key", new[] { "Always", "Right mouse", "Alt" }, _s.AimKey - 1,
            i => _s.AimKey = i + 1, y, p);
        y = AddCombo("Aim position", new[] { "Head", "Chest", "Legs" }, _s.AimPos,
            i => _s.AimPos = i, y, p);
        y = AddSlider("FOV (deg)", _s.AimFov, 1, 60, v => { _s.AimFov = v; _valFov.Text = v.ToString(); }, out _valFov, y, p);
        y = AddSlider("Smooth", _s.AimSmooth, 1, 30, v => { _s.AimSmooth = v; _valSmooth.Text = v.ToString(); }, out _valSmooth, y, p);
        y = AddSlider("Max dist (m, 0=none)", _s.MaxDistance, 0, 400, v => { _s.MaxDistance = v; _valDist.Text = v.ToString(); }, out _valDist, y, p);
    }

    private void BuildTrig(Panel p)
    {
        int y = 16;
        y = AddHeader("TRIGGER", y, p);
        y = AddCheck("Triggerbot", _s.Triggerbot, v => _s.Triggerbot = v, y, p);
        y = AddCombo("Trigger key", new[] { "Always", "Right mouse", "Alt" }, _s.TriggerKey - 1,
            i => _s.TriggerKey = i + 1, y, p);
        y = AddSlider("Trigger delay (ms)", _s.TriggerDelay, 25, 400, v => { _s.TriggerDelay = v; _valTrig.Text = v.ToString(); }, out _valTrig, y, p);
    }

    private void BuildExtra(Panel p)
    {
        int y = 16;
        y = AddHeader("EXTRA", y, p);
        y = AddCheck("Aim enabled", _s.AimEnabled, v => _s.AimEnabled = v, y, p);
        y = AddCheck("Anti-flash", _s.AntiFlash, v => _s.AntiFlash = v, y, p);
    }

    private void AddBottom(string text, int x, Action onClick)
    {
        var b = new Button
        {
            Text = text,
            Location = new Point(x, ClientSize.Height - 42),
            Size = new Size(92, 30),
            FlatStyle = FlatStyle.Flat,
            FlatAppearance = { BorderSize = 0, MouseOverBackColor = Color.FromArgb(30, 36, 48) },
            BackColor = Side,
            ForeColor = Color.Gainsboro
        };
        b.Click += (_, _) => onClick();
        Controls.Add(b);
    }
}
