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. Game ID is all you need: no certificates or Google project setup. Test Mode shows an offline sample in the Editor, and real server artwork on USB-installed devices. Neither earns credits or sends production tracking. New publishers’ public credits await server review. Turn Test Mode off for live delivery.", MessageType.None);
            if (GUILayout.Button("Select settings asset")) Selection.activeObject = settings;
            if (GUILayout.Button("Save settings")) AssetDatabase.SaveAssets();
            EditorGUILayout.EndScrollView();
        }
    }
}

