/**
 * Contentosapp Studio Admin — Confirm Extra Credit Use modal (Sprint B.4.2 — Caso A).
 *
 * Public API:
 *   window.costudioConfirmExtra(extrasBalance) → Promise<boolean>
 *     resolves true when the user confirms, false when they cancel/dismiss.
 *
 * Triggered by the production submit handler (costudio-admin-production.js)
 * BEFORE submitting, when the user's monthly quota is exhausted but they
 * still have addon balance. Prevents silent extras consumption.
 *
 * Distinct from window.costudioAddonModal (B.3):
 *   - costudioAddonModal = "buy" flow (Stripe redirect, multi-state)
 *   - costudioConfirmExtra = "confirm consumption" flow (in-page, single yes/no)
 *
 * Graceful no-op if the partial isn't present on the page: resolves true
 * so the production flow continues (server still processes correctly,
 * user just doesn't see the confirmation prompt).
 */
/* global CostudioData */
(function ($) {
    'use strict';

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

    var $modal         = null;
    var isOpen         = false;
    var currentResolve = null;
    var lastFocused    = null;

    function init() {
        $modal = $('#fos-confirm-extra-modal');
        if (!$modal.length) {
            $modal = null;
            return;
        }

        // Cancel paths — close button, Cancel button, overlay click, Escape.
        $modal.on('click', '#fos-confirm-extra-close, #fos-confirm-extra-cancel', function (e) {
            e.preventDefault();
            close(false);
        });
        $modal.on('click', function (e) {
            // Click on overlay (the .fos-modal element itself) cancels.
            if (e.target === $modal[0]) { close(false); }
        });
        $(document).on('keydown.fosConfirmExtra', function (e) {
            if ((e.key === 'Escape' || e.keyCode === 27) && isOpen) { close(false); }
        });

        // Confirm path — resolves the Promise true so the caller proceeds.
        $modal.on('click', '#fos-confirm-extra-confirm', function (e) {
            e.preventDefault();
            close(true);
        });
    }

    /**
     * Open the modal and return a Promise that resolves true on confirm,
     * false on any cancel/dismiss. Idempotent: re-opening while already
     * open is a no-op (the original Promise stays in flight).
     */
    function open(extrasBalance) {
        // No partial on this page → graceful skip. Returning true keeps the
        // production flow going (server has its own checks), the user just
        // doesn't see the confirmation prompt. Better than blocking.
        if (!$modal) {
            return Promise.resolve(true);
        }
        if (isOpen) {
            // Already open — ignore the duplicate call. Caller will see
            // the resolution from the original prompt.
            return Promise.resolve(false);
        }

        // Populate the dynamic "X remaining after this" line. Showing the
        // post-deduction count makes the cost concrete: "you'll go from 5
        // to 4" is more visceral than "you have 5".
        var balance  = parseInt(extrasBalance, 10);
        if (isNaN(balance) || balance < 0) { balance = 0; }
        var afterUse = Math.max(0, balance - 1);
        var template = t('confirm_extra_remaining', "You'll have {count} extras remaining after this.");
        $('#fos-confirm-extra-remaining').text(template.replace('{count}', afterUse));

        lastFocused = document.activeElement;
        $modal.show();
        $('body').addClass('fos-modal-open');
        isOpen = true;

        // Focus the confirm button — primary action, matches user intent
        // (they just clicked Start Production, the modal is just a guard).
        $('#fos-confirm-extra-confirm').trigger('focus');

        return new Promise(function (resolve) {
            currentResolve = resolve;
        });
    }

    function close(result) {
        if (!isOpen) { return; }
        $modal.hide();
        $('body').removeClass('fos-modal-open');
        isOpen = false;

        if (lastFocused && typeof lastFocused.focus === 'function') {
            try { lastFocused.focus(); } catch (e) {}
        }
        lastFocused = null;

        if (currentResolve) {
            var r = currentResolve;
            currentResolve = null;
            r(!!result);
        }
    }

    // Public API
    window.costudioConfirmExtra = open;

    $(function () { init(); });
})(jQuery);
