/**
 * CloudScale shared licence management module.
 *
 * Each plugin calls CloudScaleLicence.init(config) once per page load with:
 *   cardId       string  HTML ID of the card root element.
 *   actionPrefix string  AJAX action prefix, e.g. 'csbr_managed'.
 *   nonce        string  WP nonce value.
 *   manageBase   string  Portal base URL: 'https://api.cloudscale.consulting/manage'.
 *   licKey       string  Stored licence key (empty when not subscribed).
 *   ajaxUrl      string  Optional override for ajaxurl (defaults to window.ajaxurl).
 *
 * DO NOT EDIT THIS FILE in individual plugin directories.
 * Edit shared-admin-ui/cloudscale-licence.js and run sync-admin-css.sh.
 */
(function () {
    'use strict';

    window.CloudScaleLicence = {

        _cfg: null,
        _pollTimer: null,

        // ── Bootstrap ─────────────────────────────────────────────────────

        init: function (cfg) {
            this._cfg = cfg;
            this._bind();
            this._onLoad();
            if (cfg.paypalPlanId) { this._initPaypalButton(); }
        },

        // ── Helpers ───────────────────────────────────────────────────────

        _el: function (suffix) {
            return document.getElementById(this._cfg.cardId + (suffix ? '-' + suffix : ''));
        },

        _msg: function (text, ok) {
            var el = this._el('msg');
            if (!el) return;
            el.textContent = text;
            el.style.color = ok ? '#2e7d32' : '#c62828';
            el.style.display = text ? 'block' : 'none';
        },

        _ajax: function (suffix, data) {
            var cfg = this._cfg;
            var params = Object.assign({
                action: cfg.actionPrefix + '_' + suffix,
                nonce: cfg.nonce,
            }, data || {});
            return jQuery.post(cfg.ajaxUrl || window.ajaxurl || '/wp-admin/admin-ajax.php', params);
        },

        // ── Visibility toggles ────────────────────────────────────────────

        _showSubscribe: function () {
            var sub = this._el('subscribe');
            var kentry = this._el('key-entry');
            var pend = this._el('pending');
            if (sub) sub.style.display = 'flex';
            if (kentry) kentry.style.display = 'none';
            if (pend) pend.style.display = 'none';
        },

        _showKeyEntry: function () {
            var sub = this._el('subscribe');
            var kentry = this._el('key-entry');
            if (sub) sub.style.display = 'none';
            if (kentry) kentry.style.display = 'flex';
        },

        _showPending: function () {
            var sub = this._el('subscribe');
            var pend = this._el('pending');
            if (sub) sub.style.display = 'none';
            if (pend) pend.style.display = 'block';
        },

        // ── PayPal SDK button ─────────────────────────────────────────────

        _initPaypalButton: function () {
            var self = this;
            var cfg = self._cfg;
            var btnEl = self._el('paypal-btn');
            if (!btnEl) { return; }

            function renderBtn() {
                if (typeof paypal === 'undefined') { return; }
                paypal.Buttons({
                    style: { shape: 'rect', color: 'blue', layout: 'vertical', label: 'subscribe' },
                    createSubscription: function (data, actions) {
                        return actions.subscription.create({
                            plan_id: cfg.paypalPlanId,
                            application_context: {
                                shipping_preference: 'NO_SHIPPING',
                                user_action: 'SUBSCRIBE_NOW'
                            }
                        });
                    },
                    onApprove: function (data) {
                        self._msg('Activating subscription…', true);
                        self._ajax('paypal_subscription', { subscription_id: data.subscriptionID })
                            .done(function (r) {
                                if (r.success && r.data && r.data.status === 'active') {
                                    self._showWelcome();
                                } else if (r.success) {
                                    self._msg('Subscription received! Your licence will be activated shortly.', true);
                                } else {
                                    self._msg((r.data && r.data.message) ? r.data.message : 'Activation failed. Please contact support.', false);
                                }
                            })
                            .fail(function () { self._msg('Network error during activation.', false); });
                    },
                    onError: function () { self._msg('PayPal error. Please try again.', false); },
                    onCancel: function () { self._msg('', true); }
                }).render('#' + cfg.cardId + '-paypal-btn');
            }

            if (window.paypal) { renderBtn(); return; }

            var script = document.createElement('script');
            script.src = 'https://www.paypal.com/sdk/js?client-id=' + encodeURIComponent(cfg.paypalClientId) + '&vault=true&intent=subscription';
            script.setAttribute('data-sdk-integration-source', 'button-factory');
            script.onload = renderBtn;
            document.head.appendChild(script);
        },

        // ── Checkout ─────────────────────────────────────────────────────

        startCheckout: function (email) {
            var self = this;
            self._msg('', true);
            self._ajax(self._cfg.usePaypal ? 'paypal_checkout' : 'checkout', { email: email, site_url: window.location.href })
                .done(function (r) {
                    if (!r.success) {
                        self._msg((r.data && r.data.message) ? r.data.message : 'Checkout failed. Please try again.', false);
                        return;
                    }
                    if (r.data.already_subscribed) {
                        self._msg('Already subscribed — enter your licence key instead.', false);
                        self._showKeyEntry();
                        return;
                    }
                    window.open(r.data.checkout_url, '_blank');
                    self._showPending();
                    self._startPolling();
                })
                .fail(function () { self._msg('Network error. Please try again.', false); });
        },

        // ── Polling ───────────────────────────────────────────────────────

        _startPolling: function () {
            var self = this;
            if (self._pollTimer) clearInterval(self._pollTimer);
            var attempts = 0;
            self._pollTimer = setInterval(function () {
                attempts++;
                if (attempts > 120) { // 10 min
                    clearInterval(self._pollTimer);
                    self._showSubscribe();
                    self._msg('Payment not confirmed yet — use "Recover licence" below if you paid.', false);
                    return;
                }
                self._ajax('poll').done(function (r) {
                    if (r.success && r.data.status === 'active') {
                        clearInterval(self._pollTimer);
                        self._showWelcome();
                    }
                    if (!r.success && r.data && /no pending|not found/i.test(r.data.message || '')) {
                        clearInterval(self._pollTimer);
                        self._showSubscribe();
                        self._msg('Payment received — use "Recover licence" below if the key did not appear.', true);
                    }
                });
            }, 5000);
        },

        // ── Save key manually ─────────────────────────────────────────────

        _saveKey: function () {
            var self = this;
            var keyEl = self._el('key');
            if (!keyEl || !keyEl.value.trim()) { self._msg('Please paste your licence key.', false); return; }
            self._msg('Verifying…', true);
            self._ajax('save_key', { license_key: keyEl.value.trim() })
                .done(function (r) {
                    if (r.success) { window.location.reload(); }
                    else { self._msg((r.data && r.data.message) ? r.data.message : 'Invalid licence key.', false); }
                })
                .fail(function () { self._msg('Network error. Please try again.', false); });
        },

        // ── Cancel ───────────────────────────────────────────────────────

        _openCancel: function () {
            var self = this;
            var cfg = self._cfg;
            var params = [];
            if (cfg.licKey)   params.push('key='     + encodeURIComponent(cfg.licKey));
            if (cfg.product)  params.push('product=' + encodeURIComponent(cfg.product));
            var url = cfg.manageBase + (params.length ? '?' + params.join('&') : '');

            if (typeof csConfirm === 'function') {
                csConfirm(
                    '&#128683;',
                    'Cancel subscription',
                    'This will open your subscription management portal.',
                    '<p style="margin:0;font-size:0.92rem;color:#50575e;">You can cancel or review your subscription there. Return to this page to sync the updated status.</p>',
                    function () { self._openPortalAndSync(url); },
                    'Open portal',
                    'background:#1565c0;border-color:#0d47a1;color:#fff;'
                );
            } else {
                self._openPortalAndSync(url);
            }
        },

        _openPortalAndSync: function (url) {
            var self = this;
            var tab = window.open('', '_blank');
            tab.location.href = url;
            var onFocus = function () {
                window.removeEventListener('focus', onFocus);
                self._ajax('sync_status').always(function () { window.location.reload(); });
            };
            window.addEventListener('focus', onFocus);
        },

        // ── Disconnect ───────────────────────────────────────────────────

        _disconnect: function () {
            var self = this;
            if (typeof csConfirm === 'function') {
                csConfirm(
                    '&#128279;',
                    'Disconnect plugin',
                    'Disconnect this plugin from your CloudScale subscription?',
                    '<p style="margin:0;font-size:0.92rem;color:#50575e;">Your stored data remains safe. You can reconnect using your licence key at any time.</p>',
                    function () {
                        self._ajax('disconnect').done(function () { window.location.reload(); });
                    },
                    'Disconnect',
                    'background:#374151;border-color:#1f2937;color:#fff;'
                );
            } else {
                self._ajax('disconnect').done(function () { window.location.reload(); });
            }
        },

        // ── Recovery ─────────────────────────────────────────────────────

        _recoverMsg: function (text, color) {
            var el = this._el('recover-msg');
            if (!el) return;
            el.textContent = text;
            el.style.color = color;
            el.style.display = text ? '' : 'none';
        },

        _handleRecoverClick: function () {
            var self = this;
            var emailEl = self._el('recover-email');
            var codeEl  = self._el('recover-code');
            var btn     = self._el('recover-btn');
            var email   = emailEl ? emailEl.value.trim() : '';

            // Step 2 — verify code
            if (codeEl && codeEl.style.display !== 'none' && (codeEl.value || '').trim().length === 6) {
                btn.disabled = true; btn.textContent = 'Verifying…';
                self._recoverMsg('', '#6b7280');
                self._ajax('recover_verify', { email: email, code: codeEl.value.trim() })
                    .done(function (r) {
                        if (r.success) {
                            self._recoverMsg('Licence reconnected. Reloading…', '#15803d');
                            setTimeout(function () { window.location.reload(); }, 800);
                        } else {
                            self._recoverMsg((r.data && r.data.message) ? r.data.message : 'Incorrect code.', '#b91c1c');
                            btn.disabled = false; btn.textContent = 'Verify Code';
                        }
                    })
                    .fail(function () {
                        self._recoverMsg('Network error. Please try again.', '#b91c1c');
                        btn.disabled = false; btn.textContent = 'Verify Code';
                    });
                return;
            }

            // Step 1 — request code
            if (!email) { self._recoverMsg('Enter your email address.', '#b91c1c'); return; }
            btn.disabled = true; btn.textContent = 'Sending…';
            self._recoverMsg('', '#6b7280');
            self._ajax('recover', { email: email })
                .done(function (r) {
                    btn.disabled = false;
                    if (r.success) {
                        if (codeEl) { codeEl.style.display = ''; codeEl.focus(); }
                        if (emailEl) emailEl.readOnly = true;
                        btn.textContent = 'Verify Code';
                        self._recoverMsg('If that email has an active subscription, a 6-digit code has been sent.', '#15803d');
                    } else {
                        btn.textContent = 'Recover Licence';
                        self._recoverMsg((r.data && r.data.message) ? r.data.message : 'Could not send code. Try again.', '#b91c1c');
                    }
                })
                .fail(function () {
                    btn.disabled = false; btn.textContent = 'Recover Licence';
                    self._recoverMsg('Network error. Please try again.', '#b91c1c');
                });
        },

        // ── Welcome modal ────────────────────────────────────────────────

        _showWelcome: function () {
            var self = this;
            if (typeof csDialog !== 'function') {
                window.location.reload();
                return;
            }
            csDialog(
                '&#127881;',
                'Welcome to CloudScale!',
                'Your subscription is now active.',
                '<p style="margin:0 0 10px;font-size:0.9rem;line-height:1.6;color:#374151;">' +
                'Thank you for subscribing — we\'re glad to have you on board. ' +
                'Your licence has been activated and everything is ready to go.' +
                '</p>' +
                '<p style="margin:0;font-size:0.9rem;line-height:1.6;color:#374151;">' +
                'If you ever need help, you\'ll find support links inside the plugin. ' +
                'Enjoy the peace of mind.' +
                '</p>',
                '<button type="button" id="cs-dialog-ok" class="button button-primary" ' +
                'style="padding:7px 28px;font-size:0.92rem;border-radius:6px;background:#1565c0;border-color:#0d47a1;color:#fff;">' +
                'Get started</button>'
            );
            jQuery('#cs-dialog-ok').off('click').on('click', function () {
                jQuery('#cs-dialog-overlay, #cs-dialog-modal').hide();
                window.location.reload();
            });
            jQuery('#cs-dialog-overlay').off('click').on('click', function () {
                jQuery('#cs-dialog-overlay, #cs-dialog-modal').hide();
                window.location.reload();
            });
        },

        // ── Page load ────────────────────────────────────────────────────

        _onLoad: function () {
            var self = this;
            var pendEl = self._el('pending');
            // Restart poll if page reloads while pending
            if (pendEl && pendEl.style.display !== 'none') {
                self._startPolling();
            }
            // Resume poll when user returns to tab while pending
            window.addEventListener('focus', function () {
                var pe = self._el('pending');
                if (pe && pe.style.display !== 'none' && !self._pollTimer) {
                    self._startPolling();
                }
            });
            // Silently sync status when active
            var statsEl = self._el('stats');
            if (statsEl) {
                self._ajax('sync_status').done(function (r) {
                    if (r.success && r.data.status && r.data.status !== 'active') {
                        window.location.reload();
                    }
                });
            }
        },

        // ── Event binding ─────────────────────────────────────────────────

        _bind: function () {
            var self = this;
            var id = self._cfg.cardId;

            function on(suffix, event, fn) {
                var el = document.getElementById(id + '-' + suffix);
                if (el) el.addEventListener(event, fn);
            }

            // Cancel
            on('cancel', 'click', function () { self._openCancel(); });

            // Disconnect
            on('disconnect', 'click', function (e) { e.preventDefault(); self._disconnect(); });

            // Enter key link
            on('enter-key', 'click', function (e) { e.preventDefault(); self._showKeyEntry(); });
            on('back-to-subscribe', 'click', function (e) { e.preventDefault(); self._showSubscribe(); });

            // Save key
            on('save-key', 'click', function () { self._saveKey(); });

            // Recover toggle
            on('recover-toggle', 'click', function () {
                var form = self._el('recover-form');
                if (form) form.style.display = (form.style.display === 'none' ? '' : 'none');
            });

            // Recover btn
            on('recover-btn', 'click', function () { self._handleRecoverClick(); });

            // Cancel pending
            on('cancel-pending', 'click', function (e) {
                e.preventDefault();
                if (self._pollTimer) { clearInterval(self._pollTimer); self._pollTimer = null; }
                self._ajax('disconnect');
                self._showSubscribe();
                self._msg('', true);
            });
        },
    };
})();
