/**
 * Contentosapp Studio Admin — License and service plan page interactions.
 */
/* global CostudioData */
(function ($) {
    'use strict';

    var data = window.CostudioData || {};
    var ajax = data.ajax_url || '';
    var nonce = data.nonce || '';
    var i18n = data.i18n || {};
    function t(key, fallback) {
        return (typeof i18n[key] === 'string' && i18n[key].length) ? i18n[key] : fallback;
    }

    // Sprint B.1 — Extra Quotas card hooks. Run independently of the main
    // license form so the page works even on installs that haven't enabled
    // the addon feature yet.
    initAddonCard();

    if (!$('#fos-license-form').length && !$('#fos-license-deactivate-btn').length) {
        return;
    }

    // Force-clear license fields so browsers cannot autofill them
    setTimeout(function () {
        $('#fos-license-key-input').val('');
        $('[name="costudio_license_email"]').val('');
    }, 50);

    // License: toggle key visibility
    $(document).on('click', '.fos-lic-toggle-vis', function () {
        var $input = $(this).siblings('input');
        if ($input.attr('type') === 'password') {
            $input.attr('type', 'text');
            $(this).text('🙈');
        } else {
            $input.attr('type', 'password');
            $(this).text('👁');
        }
    });

    // License: deactivate
    $(document).on('click', '#fos-license-deactivate-btn', function () {
        if (!confirm(t('confirm_deactivate_license', 'Are you sure you want to deactivate the license? This will free up an activation slot.'))) {
            return;
        }
        var $btn = $(this);
        var orig = $btn.text();
        $btn.text('…').prop('disabled', true);
        $.post(ajax, { action: 'costudio_save_settings', nonce: nonce, costudio_deactivate_license: '1' })
            .done(function (res) {
                if (res.success) { location.reload(); }
                else { alert(res.data || t('error', 'Error')); $btn.text(orig).prop('disabled', false); }
            })
            .fail(function () { alert(t('error', 'Error')); $btn.text(orig).prop('disabled', false); });
    });

    /**
     * Sprint B.1 — Extra Quotas card.
     *
     *   - "Buy more credits" → placeholder until Sprint B.3 ships the modal.
     *   - "View purchase history" → lazy-loads via costudio_addon_history.
     *
     * Designed to be a no-op when the card is not on the page.
     */
    function initAddonCard() {
        var $card = $('#fos-addon-card');
        if (!$card.length) {
            return;
        }

        var historyLoaded = false;

        // Buy button — placeholder. Real modal lands in Sprint B.3.
        $card.on('click', '#fos-addon-buy-btn', function (e) {
            e.preventDefault();
            // Triggered by Sprint B.3's modal-buy-addon component.
            var ev = new CustomEvent('costudio:addon-buy-clicked');
            window.dispatchEvent(ev);
            // Until B.3 ships, surface a friendly hint so the button
            // doesn't appear broken on install.
            if (typeof window.costudioAddonModal !== 'function') {
                alert(t('addon_buy_coming_soon', 'The purchase modal is coming in the next release. For now, contact support to top up your account.'));
            } else {
                window.costudioAddonModal();
            }
        });

        // History toggle — lazy-load on first expand.
        $card.on('click', '#fos-addon-history-toggle', function () {
            var $btn      = $(this);
            var $panel    = $('#fos-addon-history');
            var expanded  = $btn.attr('aria-expanded') === 'true';

            if (expanded) {
                $btn.attr('aria-expanded', 'false');
                $panel.attr('hidden', 'hidden');
                return;
            }

            $btn.attr('aria-expanded', 'true');
            $panel.removeAttr('hidden');

            if (historyLoaded) {
                return;
            }

            $.post(ajax, {
                action: 'costudio_addon_history',
                nonce: nonce,
                force: '0'
            })
                .done(function (res) {
                    if (res && res.success) {
                        renderHistory($panel, (res.data && res.data.purchases) || []);
                        historyLoaded = true;
                    } else {
                        renderHistoryError($panel, (res && res.data) || t('error', 'Error'));
                    }
                })
                .fail(function () {
                    renderHistoryError($panel, t('error', 'Error'));
                });
        });
    }

    function renderHistory($panel, purchases) {
        if (!purchases.length) {
            $panel.html(
                '<div class="fos-lic-addon-history-empty">' +
                escapeHtml(t('addon_history_empty', 'No purchases yet.')) +
                '</div>'
            );
            return;
        }

        var rows = purchases.map(function (p) {
            var when = p.purchased_at ? new Date(p.purchased_at).toLocaleDateString() : '—';
            var qty  = parseInt(p.qty || 0, 10);
            var price = p.price_display || '—';
            var status = String(p.status || 'completed').toLowerCase();

            var statusLabel = status === 'refunded' ? t('addon_status_refunded', 'Refunded')
                : status === 'manual' ? t('addon_status_manual', 'Manual')
                : t('addon_status_completed', 'Paid');

            return (
                '<tr>' +
                '<td>' + escapeHtml(when) + '</td>' +
                '<td>' + escapeHtml(qty + ' ' + t('addon_credits_label', 'credits')) + '</td>' +
                '<td>' + escapeHtml(price) + '</td>' +
                '<td><span class="fos-lic-addon-history-status ' + escapeHtml(status) + '">' + escapeHtml(statusLabel) + '</span></td>' +
                '</tr>'
            );
        }).join('');

        var html = '<table>' +
            '<thead><tr>' +
            '<th>' + escapeHtml(t('addon_th_date', 'Date')) + '</th>' +
            '<th>' + escapeHtml(t('addon_th_qty', 'Quantity')) + '</th>' +
            '<th>' + escapeHtml(t('addon_th_amount', 'Amount')) + '</th>' +
            '<th>' + escapeHtml(t('addon_th_status', 'Status')) + '</th>' +
            '</tr></thead>' +
            '<tbody>' + rows + '</tbody>' +
            '</table>';

        $panel.html(html);
    }

    function renderHistoryError($panel, msg) {
        $panel.html(
            '<div class="fos-lic-addon-history-empty">' +
            escapeHtml('✕ ' + msg) +
            '</div>'
        );
    }

    function escapeHtml(s) {
        return String(s == null ? '' : s)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;');
    }

    $(document).on('submit', '#fos-license-form', function (e) {
        e.preventDefault();
        var $form = $(this);
        var $btn  = $form.find('button[type="submit"]');
        var $msg  = $('#fos-license-msg');
        var orig  = $btn.text();
        var key   = $.trim($('#fos-license-key-input').val() || '');
        var email = $.trim($form.find('[name="costudio_license_email"]').val() || '');

        if (!key) {
            $msg.text('✕ ' + t('license_key_required', 'License key is required.')).css('color', 'var(--fos-danger)');
            $('#fos-license-key-input').trigger('focus');
            return;
        }

        if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
            $msg.text('✕ ' + t('purchase_email_required', 'Enter the purchase email used for this license.')).css('color', 'var(--fos-danger)');
            $form.find('[name="costudio_license_email"]').trigger('focus');
            return;
        }

        $btn.text('…').prop('disabled', true);
        $msg.text('');

        $.post(ajax, {
            action: 'costudio_save_settings',
            nonce: nonce,
            costudio_pro_license_key: key,
            costudio_license_email: email,
        })
            .done(function (res) {
                if (res.success) {
                    $msg.text('✓ ' + t('saved', 'Saved!')).css('color', 'var(--fos-accent)');
                    setTimeout(function () { location.reload(); }, 800);
                } else {
                    $msg.text('✕ ' + (res.data || t('error', 'Error'))).css('color', 'var(--fos-danger)');
                }
                $btn.text(orig).prop('disabled', false);
            })
            .fail(function () {
                $msg.text('✕ ' + t('error', 'Error')).css('color', 'var(--fos-danger)');
                $btn.text(orig).prop('disabled', false);
            });
    });
    // License: open Stripe Customer Portal
    $(document).on('click', '#fos-manage-subscription-btn', function () {
        var $btn = $(this);
        if ($btn.prop('disabled')) return;

        var orig = $btn.text();
        $btn.text('…').prop('disabled', true);

        $.post(ajax, {
            action: 'costudio_license_portal',
            nonce: nonce,
            return_url: window.location.href
        })
            .done(function (res) {
                if (res && res.success && res.data && res.data.portal_url) {
                    window.location.href = res.data.portal_url;
                } else {
                    var msg = (res && res.data && res.data.message) ? res.data.message : t('error', 'Error');
                    alert('✕ ' + msg);
                    $btn.text(orig).prop('disabled', false);
                }
            })
            .fail(function (jqXHR) {
                // wp_send_json_error([...], 4xx/5xx) returns a non-2xx status, so
                // jQuery routes it here instead of .done(). Surface the server's
                // real message ({ data: { message } }) instead of a generic "Error"
                // so the user (and support) can see the actual cause — e.g.
                // "No Stripe billing account was found for this license email."
                var msg = t('error', 'Error');
                var body = jqXHR && jqXHR.responseJSON;
                if (body && body.data && body.data.message) {
                    msg = body.data.message;
                } else if (jqXHR && jqXHR.responseText) {
                    try {
                        var parsed = JSON.parse(jqXHR.responseText);
                        if (parsed && parsed.data && parsed.data.message) {
                            msg = parsed.data.message;
                        }
                    } catch (e) { /* keep generic message */ }
                }
                alert('✕ ' + msg);
                $btn.text(orig).prop('disabled', false);
            });
    });

    // License: sync with server
    $(document).on('click', '#fos-lic-sync-btn', function (e) {
        e.preventDefault();
        var $btn = $(this);
        if ($btn.hasClass('is-loading')) return;

        $btn.addClass('is-loading');

        $.post(ajax, {
            action: 'costudio_sync_license_quota',
            nonce: nonce
        })
            .done(function (res) {
                if (res && res.success) {
                    var d = res.data;
                    // Update Monthly Stats
                    if (d.usage_count !== undefined) {
                        $('#fos-lic-monthly-usage .fos-lic-usage-num').text(d.usage_count);
                        $('#fos-lic-monthly-usage .fos-lic-limit-num').text(d.limit || '0');
                    }
                    if (d.reset_date_format) {
                        $('#fos-lic-monthly-reset').text(d.reset_date_format);
                    }
                    // Update Addon Balance
                    if (d.addon_balance !== undefined) {
                        $('#fos-lic-addon-balance').text(d.addon_balance);
                    }
                    // Update Plan Badge
                    if (d.plan) {
                        $('#fos-plan-badge-header').text(d.plan);
                    }
                } else {
                    console.error('FOS Sync Error:', res.data || 'Unknown error');
                }
            })
            .always(function () {
                $btn.removeClass('is-loading');
            });
    });
}(jQuery));
