using System.IO;
using UnityEditor;
using UnityEngine;

namespace IndieExchange.Editor
{
    public sealed class IndieAdsSetup : EditorWindow
    {
        private IndieAdsSettings settings;
        private UnityEditor.Editor inspector;
        private Vector2 scroll;

        [MenuItem("Tools/Indie Exchange/Setup")]
        public static void Open() => GetWindow<IndieAdsSetup>("Indie Exchange");

        private void OnEnable()
        {
            settings = Resources.Load<IndieAdsSettings>("IndieAdsSettings");
            if (settings != null) inspector = UnityEditor.Editor.CreateEditor(settings);
        }
        private void OnDisable() { if (inspector != null) DestroyImmediate(inspector); }
        private void OnGUI()
        {
            GUILayout.Label("Indie Exchange", EditorStyles.boldLabel);
            EditorGUILayout.HelpBox("Your game keeps its existing paid-ad code. This package never installs or calls AdMob. Paste your Game ID and use Test Mode to check the integration. Configure percentages and personal ads on the website.", MessageType.Info);
            if (settings == null)
            {
                if (GUILayout.Button("Create settings"))
                {
                    Directory.CreateDirectory("Assets/Resources");
                    settings = CreateInstance<IndieAdsSettings>();
                    AssetDatabase.CreateAsset(settings, "Assets/Resources/IndieAdsSettings.asset");
                    AssetDatabase.SaveAssets();
                    inspector = UnityEditor.Editor.CreateEditor(settings);
                }
                return;
            }
            scroll = EditorGUILayout.BeginScrollView(scroll);
            inspector.OnInspectorGUI();
            EditorGUILayout.HelpBox("Call IndieAds.Initialize() after your consent flow permits requests. Settings download once at launch; website changes apply next launch. Eligible opportunities use your website percentages; no ready ad returns false immediately. Live ads require an approved app identity and Google Play Integrity or Apple App Attest setup. The Editor supports local Test Mode only. Test Mode must be off before release.", MessageType.None);
            if (GUILayout.Button("Select settings asset")) Selection.activeObject = settings;
            if (GUILayout.Button("Save settings")) AssetDatabase.SaveAssets();
            EditorGUILayout.EndScrollView();
        }
    }
}

