using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;

namespace Davanci.Nexus.Editor
{
    // Captures App Store / Play Store marketing screenshots at exact required resolutions
    // while the game runs in Play Mode. Each resolution is saved into its own folder under
    // <project>/Screenshots/ with auto-incrementing file names.
    public class NexusScreenshotTool : EditorWindow
    {
        class Preset
        {
            public string FolderName;
            public string Label;
            public int Width, Height;
            public bool Selected;

            public Preset(string folderName, int w, int h, string label, bool selected)
            {
                FolderName = folderName; Width = w; Height = h; Label = label; Selected = selected;
            }
        }

        readonly List<Preset> _presets = new List<Preset>
        {
            new Preset("iPhone 6.9", 1320, 2868, "iPhone 6.9\"   1320 x 2868", true),
            new Preset("iPhone 6.5", 1242, 2688, "iPhone 6.5\"   1242 x 2688", true),
            new Preset("iPhone 5.5", 1242, 2208, "iPhone 5.5\"   1242 x 2208", true),
            new Preset("iPad 13",    2064, 2752, "iPad 13\"       2064 x 2752", true),
            new Preset("iPad 12.9",  2048, 2732, "iPad 12.9\"    2048 x 2732", true),
            new Preset("Play Phone", 1080, 1920, "Play phone    1080 x 1920", false),
            new Preset("Play Tablet", 1600, 2560, "Play tablet   1600 x 2560", false),
        };

        static readonly Color Bg      = new Color(0.10f, 0.11f, 0.14f);
        static readonly Color Panel   = new Color(0.13f, 0.14f, 0.18f);
        static readonly Color PanelHi = new Color(0.17f, 0.19f, 0.24f);
        static readonly Color Accent  = new Color(1f, 0.42f, 0.42f);
        static readonly Color OkGreen = new Color(0.40f, 0.80f, 0.45f);
        static readonly Color Muted   = new Color(0.62f, 0.64f, 0.70f);

        bool _running;
        Button _captureBtn;
        Label _statusLabel;
        HelpBox _playModeWarning;

        [MenuItem("Davanci Nexus/App Store Screenshots")]
        public static void Open()
        {
            var w = GetWindow<NexusScreenshotTool>();
            w.titleContent = new GUIContent("Screenshots",
                AssetDatabase.LoadAssetAtPath<Texture2D>("Assets/DavanciNexus/Art/logo-icon-cube.png"));
            w.minSize = new Vector2(380, 430);
            w.Show();
        }

        static string RootFolder =>
            Path.GetFullPath(Path.Combine(Application.dataPath, "../Screenshots"));

        void OnEnable()
        {
            EditorApplication.playModeStateChanged += OnPlayModeChanged;
            Build();
        }

        void OnDisable() => EditorApplication.playModeStateChanged -= OnPlayModeChanged;

        void OnPlayModeChanged(PlayModeStateChange _) => RefreshState();

        void Build()
        {
            var root = rootVisualElement;
            root.Clear();
            root.style.backgroundColor = Bg;
            root.style.paddingLeft = 14; root.style.paddingRight = 14;
            root.style.paddingTop = 12; root.style.paddingBottom = 12;

            var title = new Label("App Store Screenshots");
            title.style.fontSize = 16;
            title.style.unityFontStyleAndWeight = FontStyle.Bold;
            title.style.color = Accent;
            root.Add(title);

            var subtitle = new Label("Captures the running game at exact store resolutions. Each size goes to its own folder under /Screenshots/.");
            subtitle.style.fontSize = 11;
            subtitle.style.color = Muted;
            subtitle.style.whiteSpace = WhiteSpace.Normal;
            subtitle.style.marginTop = 2;
            subtitle.style.marginBottom = 10;
            root.Add(subtitle);

            var card = new VisualElement();
            card.style.backgroundColor = Panel;
            card.style.paddingLeft = 12; card.style.paddingRight = 12;
            card.style.paddingTop = 10; card.style.paddingBottom = 10;
            card.style.marginBottom = 10;
            Round(card, 8);

            foreach (var preset in _presets)
            {
                var toggle = new Toggle(preset.Label) { value = preset.Selected };
                toggle.style.marginBottom = 2;
                var captured = preset; // closure
                toggle.RegisterValueChangedCallback(e => captured.Selected = e.newValue);
                card.Add(toggle);
            }
            root.Add(card);

            _captureBtn = new Button(StartCapture) { text = "Capture screenshots" };
            _captureBtn.style.height = 34;
            _captureBtn.style.color = Color.white;
            _captureBtn.style.unityFontStyleAndWeight = FontStyle.Bold;
            _captureBtn.style.backgroundColor = Accent;
            Round(_captureBtn, 6); NoBorder(_captureBtn);
            root.Add(_captureBtn);

            _playModeWarning = new HelpBox("Enter Play Mode first. Screenshots capture the live game view.", HelpBoxMessageType.Warning);
            _playModeWarning.style.marginTop = 6;
            root.Add(_playModeWarning);

            var openBtn = new Button(OpenFolder) { text = "Open Screenshots folder" };
            openBtn.style.height = 26;
            openBtn.style.marginTop = 6;
            openBtn.style.color = Color.white;
            openBtn.style.backgroundColor = PanelHi;
            Round(openBtn, 6); NoBorder(openBtn);
            root.Add(openBtn);

            _statusLabel = new Label("");
            _statusLabel.style.fontSize = 11;
            _statusLabel.style.color = OkGreen;
            _statusLabel.style.whiteSpace = WhiteSpace.Normal;
            _statusLabel.style.marginTop = 8;
            root.Add(_statusLabel);

            RefreshState();
        }

        void RefreshState()
        {
            bool playing = EditorApplication.isPlaying;
            if (_captureBtn != null) _captureBtn.SetEnabled(playing && !_running);
            if (_playModeWarning != null)
                _playModeWarning.style.display = playing ? DisplayStyle.None : DisplayStyle.Flex;
        }

        void SetStatus(string text)
        {
            if (_statusLabel != null) _statusLabel.text = text;
        }

        void StartCapture()
        {
            var resolutions = new List<NexusScreenshotCapture.Resolution>();
            foreach (var preset in _presets)
            {
                if (!preset.Selected) continue;
                resolutions.Add(new NexusScreenshotCapture.Resolution
                {
                    FolderName = preset.FolderName,
                    Width      = preset.Width,
                    Height     = preset.Height,
                });
            }

            if (resolutions.Count == 0)
            {
                SetStatus("No resolutions selected.");
                return;
            }

            _running = true;
            SetStatus("Starting...");
            RefreshState();

            var capturer = NexusScreenshotCapture.Spawn();
            capturer.CaptureAll(
                resolutions,
                RootFolder,
                status => SetStatus(status),
                () =>
                {
                    _running = false;
                    SetStatus($"Done. {resolutions.Count} screenshot(s) saved to /Screenshots/.");
                    RefreshState();
                });
        }

        static void OpenFolder()
        {
            Directory.CreateDirectory(RootFolder);
            EditorUtility.RevealInFinder(RootFolder);
        }

        static void Round(VisualElement e, int r)
        {
            e.style.borderTopLeftRadius = r; e.style.borderTopRightRadius = r;
            e.style.borderBottomLeftRadius = r; e.style.borderBottomRightRadius = r;
        }

        static void NoBorder(VisualElement e)
        {
            e.style.borderTopWidth = 0; e.style.borderBottomWidth = 0;
            e.style.borderLeftWidth = 0; e.style.borderRightWidth = 0;
        }
    }
}
