using System;
using System.Drawing;
using System.Windows.Forms;
using AutoIngest.Core;

namespace AutoIngest.App
{
    /// <summary>
    /// Branding editor opened from the tray (Options ▸ Branding ▸ Edit branding…). Hosts the
    /// shared <see cref="BrandingEditorPanel"/> with Save / Cancel. The panel edits the live
    /// config object; Save persists, Cancel reverts by reloading.
    /// </summary>
    public class BrandingForm : Form
    {
        readonly AppConfig _config;
        BrandingEditorPanel _panel = null!;

        public BrandingForm(AppConfig config)
        {
            _config = config;
            BuildUi();
        }

        void BuildUi()
        {
            Text = "AutoIngest — Branding";
            StartPosition = FormStartPosition.CenterParent;
            ClientSize = new Size(760, 620);
            FormBorderStyle = FormBorderStyle.FixedDialog;
            MaximizeBox = false;
            MinimizeBox = false;
            BackColor = Theme.BG;
            ForeColor = Theme.TEXT;
            Font = new Font("Segoe UI", 9F);

            _panel = new BrandingEditorPanel(_config);
            Controls.Add(_panel);

            var bottom = new Panel { Dock = DockStyle.Bottom, Height = 40, BackColor = Theme.BG };
            Controls.Add(bottom);

            var save = new Button
            {
                Text = "Save",
                FlatStyle = FlatStyle.Flat,
                BackColor = Theme.BG2,
                ForeColor = Theme.TEXT,
                Location = new Point(ClientSize.Width - 200, 8),
                Size = new Size(85, 26)
            };
            save.Click += (_, _) =>
            {
                _panel.Save();
                DialogResult = DialogResult.OK;
                Close();
            };

            var cancel = new Button
            {
                Text = "Cancel",
                FlatStyle = FlatStyle.Flat,
                BackColor = Theme.BG2,
                ForeColor = Theme.TEXT,
                Location = new Point(ClientSize.Width - 105, 8),
                Size = new Size(85, 26)
            };
            cancel.Click += (_, _) =>
            {
                DialogResult = DialogResult.Cancel;
                Close();
            };

            bottom.Controls.Add(save);
            bottom.Controls.Add(cancel);
            AcceptButton = save;
            CancelButton = cancel;

            // Kick off an initial preview once the form is on screen. This MUST run after the
            // window handle exists — BeginInvoke/Invoke throw before then, so doing it in the
            // constructor (where the handle isn't created yet) crashes the form on open. Load
            // fires once the handle is created but before first paint.
            Load += (_, _) => _panel.RenderPreview();
        }
    }
}
