/**
 * Zeno Chatbot AI — Extension SDK
 *
 * Provides a simple API for extensions to register settings pages
 * (and in the future, dashboard widgets) that mount inside the
 * free plugin's admin SPA.
 *
 * Usage:
 *
 *   new ZenoChatbotExtension('my-ext', {
 *       createApp: createApp,  // from the extension's own Vue
 *       settings: [
 *           { slug: 'config', title: 'My Config', icon: 'settings-line', component: ConfigComponent },
 *       ],
 *       setup(app) {
 *           app.use(SomePlugin)
 *       },
 *       api: {
 *           url: window.my_ext_admin?.api_url || '',
 *           nonce: window.my_ext_admin?.nonce || '',
 *       },
 *   })
 *
 * The SDK handles:
 *   - Event listening (mount/unmount/ready)
 *   - Race condition handshake with the host SPA
 *   - Vue app creation, setup, and API context injection
 *   - Cleanup on unmount
 *   - Duplicate registration guard
 *
 * Components receive API context via inject('api'):
 *   api.self  — { url, nonce } for the extension's own REST API
 *   api.free  — { url, nonce } for the free plugin's REST API
 */
(function () {
    'use strict';

    var registry = {};

    function ZenoChatbotExtension(slug, options) {
        if (registry[slug]) {
            console.warn('[ZenoChatbot SDK] Extension "' + slug + '" already registered.');
            return registry[slug];
        }

        this.slug = slug;
        this.options = options || {};
        this.settings = {};
        this.currentApp = null;
        this.createApp = options.createApp || null;
        this.setupFn = options.setup || null;
        this.api = options.api || {};

        var settingsList = options.settings || [];
        for (var i = 0; i < settingsList.length; i++) {
            this.settings[settingsList[i].slug] = settingsList[i].component;
        }

        registry[slug] = this;

        this._listen();
        this._checkPending();
        this._announceReady();
    }

    ZenoChatbotExtension.prototype._listen = function () {
        var self = this;

        window.addEventListener('zenochatbot:ext:mount', function (e) {
            if (e.detail && e.detail.extension === self.slug) {
                self._mount(e.detail);
            }
        });

        window.addEventListener('zenochatbot:ext:unmount', function (e) {
            if (e.detail && e.detail.extension === self.slug) {
                self._unmount();
            }
        });
    };

    ZenoChatbotExtension.prototype._checkPending = function () {
        var mounts = window.__zenochatbot_ext_pending_mounts;
        if (mounts && mounts[this.slug]) {
            var pending = mounts[this.slug];
            delete mounts[this.slug];
            this._mount(pending);
        }
    };

    ZenoChatbotExtension.prototype._announceReady = function () {
        window.dispatchEvent(new CustomEvent('zenochatbot:ext:ready', {
            detail: { extension: this.slug }
        }));
    };

    ZenoChatbotExtension.prototype._mount = function (detail) {
        var page = detail.page;
        var mountId = detail.mountId;

        var component = this.settings[page];
        if (!component) {
            console.warn('[ZenoChatbot SDK] No settings page "' + page + '" in extension "' + this.slug + '".');
            return;
        }

        this._unmount();

        var el = document.getElementById(mountId);
        if (!el) return;

        el.classList.add('zc-ext-app', 'zc-ext-' + this.slug);

        if (!this.createApp) {
            console.error('[ZenoChatbot SDK] No createApp provided for "' + this.slug + '".');
            return;
        }

        try {
            this.currentApp = this.createApp(component);

            this.currentApp.provide('api', {
                self: this.api,
                free: {
                    url: (window.zenochatbot_admin && window.zenochatbot_admin.api_url) || '',
                    nonce: (window.zenochatbot_admin && window.zenochatbot_admin.nonce) || '',
                },
            });

            if (this.setupFn) {
                this.setupFn(this.currentApp);
            }

            this.currentApp.mount('#' + mountId);

            window.dispatchEvent(new CustomEvent('zenochatbot:ext:mounted', {
                detail: { extension: this.slug }
            }));
        } catch (err) {
            console.error('[ZenoChatbot SDK] Mount failed for "' + this.slug + '/' + page + '":', err);
            this._unmount();
        }
    };

    ZenoChatbotExtension.prototype._unmount = function () {
        if (this.currentApp) {
            try { this.currentApp.unmount(); } catch (e) { /* ignore */ }
            this.currentApp = null;
        }
    };

    ZenoChatbotExtension.get = function (slug) {
        return registry[slug] || null;
    };

    window.ZenoChatbotExtension = ZenoChatbotExtension;
})();
