<div class="text-center" id="marketplace-installation-in-progress">
    <p>{{ 'marketplace.package.install.html.in.progress'|trans({'%packagename%' : packageDetail.packageBase.getHumanPackageName()})|purify }}</p>
    <div class="spinner">
        <i class="ri-loader-3-line ri-spin"></i>
    </div>
</div>
<div style="display: none" class="text-center" id="marketplace-installation-failed">
    <p>{{ 'marketplace.package.install.html.failed'|trans({'%packagename%' : packageDetail.packageBase.getHumanPackageName()})|purify }}</p>
    <textarea class="form-control" readonly id="marketplace-installation-failed-details"></textarea>
</div>
<div style="display: none" class="text-center" id="marketplace-installation-success">
    <p>{{ 'marketplace.package.install.html.success'|trans({'%packagename%' : packageDetail.packageBase.getHumanPackageName()})|purify }}</p>
    <p><a class="btn btn-primary" href="{{ path('mautic_plugin_reload') }}">{% trans %}marketplace.package.install.html.success.continue{% endtrans %}</a></p>
</div>

<script>
    const installPackageResetView = () => {
        mQuery('#marketplace-installation-in-progress').show();
        mQuery('#marketplace-installation-success').hide();
        mQuery('#marketplace-installation-failed').hide();
    }

    installPackageResetView();

    Mautic.Marketplace.installPackage(
        '{{ packageDetail.packageBase.getVendorName()|escape }}',
        '{{ packageDetail.packageBase.getPackageName()|escape }}',
        (response) => {
            if (response.success) {
                mQuery('#marketplace-installation-in-progress').hide();
                mQuery('#marketplace-installation-success').show();
            } else if (response.redirect) {
                window.location = response.redirect;
            }
        },
        (request, textStatus, errorThrown) => {
            let error;

            try {
                const res = JSON.parse(request.responseText);
                if (res.error) {
                    error = res.error;
                } else {
                    error = res.errors[0].message ?? 'Unknown error';
                }
            } catch (e) {
                error = 'An unknown error occurred. Please check the logs for more details.';
                console.error(request.responseText);
                console.error(e);
            }

            mQuery('#marketplace-installation-in-progress').hide();
            mQuery('#marketplace-installation-failed').show();
            mQuery('#marketplace-installation-failed-details').text(error);
        }
    );
</script>
