#if UDONSHARP && UNITY_EDITOR
using UdonSharp;
using UdonSharpEditor;
using UnityEditor;
using UnityEditor.Events;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.UI;
using VRC.Core;
using VRC.SDKBase;
using VRC.SDK3.Components;
using VRC.Udon;
using Object = UnityEngine.Object;

// UdonSharp needs one program asset (.asset) per behaviour, and that asset has
// to point at this project's own UdonSharp installation. Shipping those .asset
// files inside a package would mean guessing UdonSharp's own script GUID, so
// this editor script creates them instead: on import, and from the
// ZeroInventory menu at any time.
//
// It can also build the in-world UI: canvas, URL input field, buttons and the
// HUD references, wired up. Udon cannot call Button.onClick.AddListener, so the
// buttons need persistent listeners recorded here in the editor.
[InitializeOnLoad]
public static class ZeroInventorySetup
{
    private const string ScriptsFolder = "Assets/ZeroInventory/Scripts";
    private const string RootName = "ZeroInventory";
    private static readonly string[] ScriptNames = { "ZeroInventoryClient", "ZeroInventoryHud" };

    private static readonly Color PanelColor = new Color(0.055f, 0.063f, 0.078f, 0.96f);
    private static readonly Color FieldColor = new Color(1f, 1f, 1f, 0.07f);
    private static readonly Color AccentColor = new Color(0.16f, 0.44f, 0.93f, 1f);
    private static readonly Color QuietColor = new Color(1f, 1f, 1f, 0.13f);
    private static readonly Color TextColor = new Color(0.93f, 0.95f, 0.98f, 1f);
    private static readonly Color MutedColor = new Color(0.62f, 0.66f, 0.74f, 1f);

    static ZeroInventorySetup()
    {
        // AssetDatabase is not ready inside the static constructor.
        EditorApplication.delayCall += EnsureProgramAssets;
    }

    // ---------- program assets ----------

    [MenuItem("ZeroInventory/Create UdonSharp program assets")]
    public static void CreateProgramAssets()
    {
        EnsureProgramAssets();
    }

    private static void EnsureProgramAssets()
    {
        bool changed = false;

        foreach (string name in ScriptNames)
        {
            string scriptPath = ScriptsFolder + "/" + name + ".cs";
            string assetPath = ScriptsFolder + "/" + name + ".asset";

            MonoScript script = AssetDatabase.LoadAssetAtPath<MonoScript>(scriptPath);
            if (script == null)
            {
                continue;
            }

            UdonSharpProgramAsset existing =
                AssetDatabase.LoadAssetAtPath<UdonSharpProgramAsset>(assetPath);
            if (existing != null)
            {
                // Re-importing the package can hand the script a new GUID, which
                // leaves an older program asset pointing at nothing.
                if (existing.sourceCsScript == null)
                {
                    existing.sourceCsScript = script;
                    EditorUtility.SetDirty(existing);
                    changed = true;
                }

                continue;
            }

            UdonSharpProgramAsset program =
                ScriptableObject.CreateInstance<UdonSharpProgramAsset>();
            program.sourceCsScript = script;
            AssetDatabase.CreateAsset(program, assetPath);
            changed = true;
        }

        if (!changed)
        {
            return;
        }

        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
        UdonSharpProgramAsset.CompileAllCsPrograms(true);
        Debug.Log("[ZeroInventory] Created UdonSharp program assets for the world viewer.");
    }

    // ---------- world UI ----------

    [MenuItem("ZeroInventory/Build world UI")]
    public static void BuildWorldUi()
    {
        if (EditorApplication.isPlaying)
        {
            Debug.LogWarning("[ZeroInventory] Exit play mode before building the UI.");
            return;
        }

        if (PrefabStageUtility.GetCurrentPrefabStage() != null)
        {
            Debug.LogWarning("[ZeroInventory] Close the prefab stage before building the UI.");
            return;
        }

        // The program assets have to exist before UdonSharp can set up the
        // backing UdonBehaviour the buttons will call.
        EnsureProgramAssets();

        ZeroInventoryClient client = Object.FindObjectOfType<ZeroInventoryClient>();
        GameObject root;
        if (client != null)
        {
            root = client.gameObject;
        }
        else
        {
            root = new GameObject(RootName);
            Undo.RegisterCreatedObjectUndo(root, "Build ZeroInventory UI");
            client = root.AddComponent<ZeroInventoryClient>();
        }

        ZeroInventoryHud hud = root.GetComponent<ZeroInventoryHud>();
        if (hud == null)
        {
            hud = root.AddComponent<ZeroInventoryHud>();
        }

        DetectWorldIdentity(client);

        Transform previous = root.transform.Find("UI");
        if (previous != null)
        {
            Undo.DestroyObjectImmediate(previous.gameObject);
        }

        GameObject uiObject = new GameObject(
            "UI",
            typeof(RectTransform),
            typeof(Canvas),
            typeof(CanvasScaler),
            typeof(GraphicRaycaster),
            typeof(BoxCollider));
        RectTransform ui = (RectTransform)uiObject.transform;
        ui.SetParent(root.transform, false);
        ui.sizeDelta = new Vector2(900f, 700f);
        ui.localScale = Vector3.one * 0.001f;
        ui.localPosition = new Vector3(0f, 1.4f, 1.6f);

        Canvas canvas = uiObject.GetComponent<Canvas>();
        canvas.renderMode = RenderMode.WorldSpace;

        CanvasScaler scaler = uiObject.GetComponent<CanvasScaler>();
        scaler.uiScaleMode = CanvasScaler.ScaleMode.ConstantPixelSize;
        scaler.scaleFactor = 1f;

        // VRC Ui Shape is what connects VRChat's pointer to Unity UI. Without it
        // the panel is clickable in the editor and dead in VRChat. It expects a
        // Box Collider and resizes it to the canvas at runtime.
        uiObject.AddComponent<VRCUiShape>();
        BoxCollider shape = uiObject.GetComponent<BoxCollider>();
        shape.center = Vector3.zero;
        shape.size = new Vector3(900f, 700f, 1f);
        shape.isTrigger = false;

        // One EventSystem per scene is what distributes the clicks.
        if (Object.FindObjectOfType<EventSystem>() == null)
        {
            GameObject events = new GameObject(
                "EventSystem",
                typeof(EventSystem),
                typeof(StandaloneInputModule));
            events.GetComponent<EventSystem>().sendNavigationEvents = false;
            Undo.RegisterCreatedObjectUndo(events, "Build ZeroInventory UI");
        }

        RectTransform panel = ChildRect("Panel", ui);
        Stretch(panel);
        Image background = panel.gameObject.AddComponent<Image>();
        background.color = PanelColor;

        Text title = Label(panel, "Title", "ZeroInventory", 26, TextAnchor.MiddleLeft, TextColor, FontStyle.Bold);
        Place(title.rectTransform, 24f, -24f, -68f, -24f);

        Text status = Label(panel, "Status", "Not connected", 19, TextAnchor.MiddleLeft, MutedColor, FontStyle.Normal);
        Place(status.rectTransform, 24f, -24f, -110f, -70f);

        VRCUrlInputField urlField = UrlInput(panel);

        Button connect = MakeButton(panel, "Connect", "Connect", new Vector2(-24f, -160f), new Vector2(110f, 48f), AccentColor);
        Button disconnect = MakeButton(panel, "Disconnect", "Disconnect", new Vector2(-142f, -160f), new Vector2(110f, 48f), QuietColor);

        Button previousButton = MakeButton(panel, "Previous", "Previous", new Vector2(-232f, -222f), new Vector2(96f, 44f), QuietColor);
        Button refresh = MakeButton(panel, "Refresh", "Refresh", new Vector2(-128f, -222f), new Vector2(96f, 44f), QuietColor);
        Button nextButton = MakeButton(panel, "Next", "Next", new Vector2(-24f, -222f), new Vector2(96f, 44f), QuietColor);

        Text inventory = Label(panel, "Inventory", "Paste your world URL and press Connect.", 19, TextAnchor.UpperLeft, TextColor, FontStyle.Normal);
        RectTransform inventoryRect = inventory.rectTransform;
        inventoryRect.anchorMin = new Vector2(0f, 0f);
        inventoryRect.anchorMax = new Vector2(1f, 1f);
        inventoryRect.offsetMin = new Vector2(24f, 104f);
        inventoryRect.offsetMax = new Vector2(-320f, -296f);

        // Everyone currently in the instance, filled by the client every couple
        // of seconds from VRCPlayerApi. The header folds the list away, and the
        // rows exist up front because Udon cannot create UI at runtime.
        RectTransform playersSection = ChildRect("PlayersSection", panel);
        playersSection.anchorMin = new Vector2(1f, 0f);
        playersSection.anchorMax = new Vector2(1f, 1f);
        playersSection.offsetMin = new Vector2(-296f, 104f);
        playersSection.offsetMax = new Vector2(-24f, -296f);

        Button peopleButton = MakeButton(
            playersSection,
            "People",
            "People (0)",
            new Vector2(0f, 0f),
            new Vector2(272f, 40f),
            QuietColor);
        Text peopleLabel = peopleButton.transform.Find("Label").GetComponent<Text>();
        peopleLabel.alignment = TextAnchor.MiddleLeft;
        RectTransform peopleRect = (RectTransform)peopleLabel.transform;
        peopleRect.offsetMin = new Vector2(14f, 0f);

        RectTransform playersList = ChildRect("PlayersList", playersSection);
        playersList.anchorMin = new Vector2(0f, 0f);
        playersList.anchorMax = new Vector2(1f, 1f);
        playersList.offsetMin = new Vector2(0f, 0f);
        playersList.offsetMax = new Vector2(0f, -48f);

        const int rowCount = 9;
        const float rowHeight = 26f;
        Text[] playerRows = new Text[rowCount];
        for (int index = 0; index < rowCount; index++)
        {
            Text row = Label(
                playersList,
                "Player" + (index + 1),
                "",
                17,
                TextAnchor.MiddleLeft,
                TextColor,
                FontStyle.Normal);
            RectTransform rowRect = row.rectTransform;
            rowRect.anchorMin = new Vector2(0f, 1f);
            rowRect.anchorMax = new Vector2(1f, 1f);
            rowRect.offsetMin = new Vector2(14f, -rowHeight * (index + 1));
            rowRect.offsetMax = new Vector2(-8f, -rowHeight * index);
            row.gameObject.SetActive(false);
            playerRows[index] = row;
        }

        Text feedback = Label(panel, "Feedback", "", 18, TextAnchor.MiddleLeft, MutedColor, FontStyle.Normal);
        RectTransform feedbackRect = feedback.rectTransform;
        feedbackRect.anchorMin = new Vector2(0f, 0f);
        feedbackRect.anchorMax = new Vector2(1f, 0f);
        feedbackRect.offsetMin = new Vector2(24f, 52f);
        feedbackRect.offsetMax = new Vector2(-24f, 92f);

        Text hint = Label(
            panel,
            "Hint",
            "Your URL is typed in VRChat and stays on your client. Items are managed on the website.",
            15,
            TextAnchor.MiddleLeft,
            MutedColor,
            FontStyle.Normal);
        RectTransform hintRect = hint.rectTransform;
        hintRect.anchorMin = new Vector2(0f, 0f);
        hintRect.anchorMax = new Vector2(1f, 0f);
        hintRect.offsetMin = new Vector2(24f, 18f);
        hintRect.offsetMax = new Vector2(-24f, 44f);

        Undo.RecordObject(client, "Build ZeroInventory UI");
        Undo.RecordObject(hud, "Build ZeroInventory UI");

        client.urlInput = urlField;
        hud.client = client;
        hud.statusText = status;
        hud.inventoryText = inventory;
        hud.feedbackText = feedback;
        hud.playerListPanel = playersList.gameObject;
        hud.playerHeaderText = peopleLabel;
        hud.playerRows = playerRows;
        // The HUD hides this panel on Start and opens it with the toggle key
        // (I on desktop). VR players do not get it for now.
        hud.panel = uiObject;

        // Wiring waits for UdonSharp to create its backing UdonBehaviour, see
        // QueueButtonWiring: VRChat only allows SendCustomEvent from UI events.
        QueueButtonWiring(root);

        EditorUtility.SetDirty(client);
        EditorUtility.SetDirty(hud);
        Undo.RegisterCreatedObjectUndo(uiObject, "Build ZeroInventory UI");

        EditorSceneManager.MarkSceneDirty(root.scene);
        Selection.activeGameObject = root;
        Debug.Log("[ZeroInventory] Built the world UI under " + RootName + "/UI.");
    }

    // ---------- world identity ----------

    [MenuItem("ZeroInventory/Detect world id")]
    public static void DetectWorldId()
    {
        ZeroInventoryClient client = Object.FindFirstObjectByType<ZeroInventoryClient>();
        if (client == null)
        {
            Debug.LogWarning("[ZeroInventory] No ZeroInventoryClient in the scene. Run ZeroInventory > Build world UI first.");
            return;
        }

        DetectWorldIdentity(client);
    }

    /**
     * Reads the world's blueprint id from the VRChat pipeline manager and bakes
     * the registration URL. Udon cannot build a URL at runtime, so this is the
     * only place the id can be attached to the request.
     */
    private static void DetectWorldIdentity(ZeroInventoryClient client)
    {
        PipelineManager pipeline = Object.FindFirstObjectByType<PipelineManager>();
        string blueprintId = pipeline != null ? pipeline.blueprintId : string.Empty;
        if (string.IsNullOrEmpty(blueprintId))
        {
            Debug.LogWarning(
                "[ZeroInventory] This scene has no VRChat world id yet. Attach it to a world in the VRChat SDK control panel, then run ZeroInventory > Detect world id.");
            return;
        }

        string baseUrl = (client.apiBaseUrl ?? string.Empty).TrimEnd('/');
        if (baseUrl.Length == 0)
        {
            Debug.LogWarning("[ZeroInventory] The client has no API base URL. Import the package from the world installer.");
            return;
        }

        string label = client.worldName ?? string.Empty;
        if (label.Length == 0 || label.Contains("__"))
        {
            // The package fills in a name, but a hand-imported copy may still
            // carry the placeholder; the scene name is a good label instead.
            label = UnityEngine.SceneManagement.SceneManager.GetActiveScene().name;
        }

        client.worldBlueprintId = blueprintId;
        client.worldRegisterUrl = new VRCUrl(
            baseUrl
            + "/api/world/v1/register?wid="
            + System.Uri.EscapeDataString(blueprintId)
            + "&name="
            + System.Uri.EscapeDataString(label));
        EditorUtility.SetDirty(client);
        Debug.Log(
            "[ZeroInventory] World "
            + blueprintId
            + " detected. It registers itself the first time the world loads.");
    }

    // ---------- button wiring ----------

    // VRChat's UnityEventFilter removes any UI event that does not target a
    // whitelisted type. For Udon the only allowed call is
    // UdonBehaviour.SendCustomEvent("<public method name>"), which is exactly
    // how UdonSharp's own event editor records inspector wiring.
    private static readonly string[] HudButtonNames =
    {
        "Connect",
        "Disconnect",
        "Previous",
        "Refresh",
        "Next",
        "People",
    };

    private static readonly string[] HudEventNames =
    {
        "OnConnectClicked",
        "OnDisconnectClicked",
        "OnPreviousCharacterClicked",
        "OnRefreshClicked",
        "OnNextCharacterClicked",
        "OnPlayersToggled",
    };

    private static GameObject _pendingWiringRoot;
    private static int _pendingWiringAttempts;

    private static void QueueButtonWiring(GameObject root)
    {
        _pendingWiringRoot = root;
        _pendingWiringAttempts = 0;
        EditorApplication.update -= TryWireButtons;
        EditorApplication.update += TryWireButtons;
    }

    private static void TryWireButtons()
    {
        GameObject root = _pendingWiringRoot;
        _pendingWiringAttempts++;

        if (root == null || _pendingWiringAttempts > 600)
        {
            if (root != null)
            {
                Debug.LogWarning("[ZeroInventory] Could not wire the buttons: UdonSharp never created the backing UdonBehaviour.");
            }

            StopWaitingForWiring();
            return;
        }

        ZeroInventoryHud hud = root.GetComponent<ZeroInventoryHud>();
        UdonBehaviour backing = hud == null ? null : UdonSharpEditorUtility.GetBackingUdonBehaviour(hud);
        if (backing == null)
        {
            // UdonSharp adds the backing behaviour on its next editor update.
            return;
        }

        StopWaitingForWiring();
        WireButtons(root, backing);
    }

    private static void StopWaitingForWiring()
    {
        EditorApplication.update -= TryWireButtons;
        _pendingWiringRoot = null;
    }

    private static void WireButtons(GameObject root, UdonBehaviour target)
    {
        Transform panel = root.transform.Find("UI/Panel");
        if (panel == null)
        {
            Debug.LogWarning("[ZeroInventory] No UI/Panel to wire.");
            return;
        }

        int wired = 0;
        for (int index = 0; index < HudButtonNames.Length; index++)
        {
            Transform child = FindDeep(panel, HudButtonNames[index]);
            Button button = child == null ? null : child.GetComponent<Button>();
            if (button == null)
            {
                continue;
            }

            // Replace anything from an earlier run so re-building does not stack
            // several calls on the same button.
            button.onClick = new Button.ButtonClickedEvent();
            UnityEventTools.AddStringPersistentListener(
                button.onClick,
                new UnityAction<string>(target.SendCustomEvent),
                HudEventNames[index]);
            EditorUtility.SetDirty(button);
            wired++;
        }

        EditorSceneManager.MarkSceneDirty(root.scene);
        Debug.Log("[ZeroInventory] Wired " + wired + " buttons to " + target.name + " via SendCustomEvent.");
    }

    // The people header lives in a nested section, so the wiring has to look
    // deeper than the panel's direct children.
    private static Transform FindDeep(Transform parent, string name)
    {
        Transform direct = parent.Find(name);
        if (direct != null) return direct;
        for (int index = 0; index < parent.childCount; index++)
        {
            Transform found = FindDeep(parent.GetChild(index), name);
            if (found != null) return found;
        }
        return null;
    }

    // ---------- UI helpers ----------

    private static Font UIFont()
    {
        return Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
    }

    private static RectTransform ChildRect(string name, Transform parent)
    {
        GameObject go = new GameObject(name, typeof(RectTransform));
        go.layer = parent.gameObject.layer;
        go.transform.SetParent(parent, false);
        return (RectTransform)go.transform;
    }

    private static void Stretch(RectTransform rect)
    {
        rect.anchorMin = Vector2.zero;
        rect.anchorMax = Vector2.one;
        rect.offsetMin = Vector2.zero;
        rect.offsetMax = Vector2.zero;
    }

    private static void Place(RectTransform rect, float left, float right, float bottom, float top)
    {
        rect.anchorMin = new Vector2(0f, 1f);
        rect.anchorMax = new Vector2(1f, 1f);
        rect.offsetMin = new Vector2(left, bottom);
        rect.offsetMax = new Vector2(right, top);
    }

    private static Text Label(
        Transform parent,
        string name,
        string value,
        int size,
        TextAnchor align,
        Color color,
        FontStyle style)
    {
        RectTransform rect = ChildRect(name, parent);
        Text text = rect.gameObject.AddComponent<Text>();
        text.font = UIFont();
        text.text = value;
        text.fontSize = size;
        text.fontStyle = style;
        text.alignment = align;
        text.color = color;
        text.supportRichText = false;
        text.horizontalOverflow = HorizontalWrapMode.Wrap;
        text.verticalOverflow = VerticalWrapMode.Overflow;
        text.raycastTarget = false;
        return text;
    }

    private static Button MakeButton(
        Transform parent,
        string name,
        string caption,
        Vector2 topRight,
        Vector2 size,
        Color color)
    {
        RectTransform rect = ChildRect(name, parent);
        rect.anchorMin = new Vector2(1f, 1f);
        rect.anchorMax = new Vector2(1f, 1f);
        rect.pivot = new Vector2(1f, 1f);
        rect.anchoredPosition = topRight;
        rect.sizeDelta = size;

        Image image = rect.gameObject.AddComponent<Image>();
        image.color = color;

        Button button = rect.gameObject.AddComponent<Button>();
        button.targetGraphic = image;
        // No arrow-key navigation: in VRChat that would move the selection while
        // the player walks around.
        button.navigation = new Navigation { mode = Navigation.Mode.None };

        ColorBlock colors = button.colors;
        colors.normalColor = Color.white;
        colors.highlightedColor = new Color(1f, 1f, 1f, 0.86f);
        colors.pressedColor = new Color(1f, 1f, 1f, 0.7f);
        colors.selectedColor = Color.white;
        colors.disabledColor = new Color(1f, 1f, 1f, 0.3f);
        colors.fadeDuration = 0.08f;
        button.colors = colors;

        Text captionText = Label(rect, "Label", caption, 18, TextAnchor.MiddleCenter, TextColor, FontStyle.Normal);
        Stretch(captionText.rectTransform);
        return button;
    }

    private static VRCUrlInputField UrlInput(Transform parent)
    {
        RectTransform rect = ChildRect("UrlField", parent);
        rect.anchorMin = new Vector2(0f, 1f);
        rect.anchorMax = new Vector2(1f, 1f);
        rect.offsetMin = new Vector2(24f, -208f);
        rect.offsetMax = new Vector2(-260f, -160f);

        Image background = rect.gameObject.AddComponent<Image>();
        background.color = FieldColor;

        Text value = Label(rect, "Text", "", 19, TextAnchor.MiddleLeft, TextColor, FontStyle.Normal);
        InsetText(value.rectTransform);

        Text placeholder = Label(
            rect,
            "Placeholder",
            "Paste your world URL",
            19,
            TextAnchor.MiddleLeft,
            MutedColor,
            FontStyle.Normal);
        InsetText(placeholder.rectTransform);

        VRCUrlInputField field = rect.gameObject.AddComponent<VRCUrlInputField>();
        field.targetGraphic = background;
        field.navigation = new Navigation { mode = Navigation.Mode.None };
        field.textComponent = value;
        field.placeholder = placeholder;
        return field;
    }

    private static void InsetText(RectTransform rect)
    {
        Stretch(rect);
        rect.offsetMin = new Vector2(14f, 0f);
        rect.offsetMax = new Vector2(-14f, 0f);
    }
}
#endif
