/**
 * NeoPay Single HTML Web Kit
 * Include this one script tag on any page - no matter what backend
 * language the site runs on (PHP, Node, Python, plain static HTML) - to
 * accept payments and get live success/failed/timeout callbacks.
 *
 * Usage:
 *   <script src="https://yourdomain.com/single-html-web-kit.js"></script>
 *   <script>
 *     NeoPay.setPaymentCallbacks({
 *       onSuccess: function(orderId) { ... },
 *       onFailed:  function(orderId) { ... },
 *       onTimeout: function(orderId) { ... },
 *     });
 *
 *     NeoPay.createOrder({
 *       user_token: 'your_token',
 *       order_id: 'ORD' + Date.now(),
 *       amount: '100',
 *       customer_mobile: '9876543210',
 *       remark1: 'note'
 *     }, {
 *       onResponse: function(url, orderId) { NeoPay.loadPayment(url); },
 *       onError: function(err) { alert(err); }
 *     });
 *   </script>
 */
(function (window, document) {
    'use strict';

    // Auto-detects its own origin from the <script> tag's src, so no base
    // URL needs to be hardcoded/configured by the integrating site.
    var API_BASE = (function () {
        var scripts = document.getElementsByTagName('script');
        for (var i = 0; i < scripts.length; i++) {
            var src = scripts[i].src || '';
            if (src.indexOf('single-html-web-kit.js') !== -1) {
                var a = document.createElement('a');
                a.href = src;
                return a.protocol + '//' + a.host;
            }
        }
        return window.location.protocol + '//' + window.location.host;
    })();

    var callbacks = { onSuccess: null, onFailed: null, onTimeout: null };
    var modalOverlay = null;
    var modalIframe = null;

    function postForm(path, params, cb) {
        var body = new URLSearchParams();
        for (var key in params) {
            if (params[key] !== undefined && params[key] !== null) {
                body.append(key, params[key]);
            }
        }
        fetch(API_BASE + path, { method: 'POST', body: body })
            .then(function (r) { return r.json(); })
            .then(function (data) { cb(null, data); })
            .catch(function (err) { cb(err.message || 'Network error', null); });
    }

    function closeModal() {
        if (modalOverlay) {
            modalOverlay.remove();
            modalOverlay = null;
            modalIframe = null;
        }
    }

    function openModal(url) {
        closeModal();

        modalOverlay = document.createElement('div');
        modalOverlay.style.cssText = 'position:fixed;inset:0;z-index:999999;background:rgba(10,10,20,.7);' +
            'display:flex;align-items:center;justify-content:center;padding:16px;';

        var box = document.createElement('div');
        box.style.cssText = 'position:relative;width:100%;max-width:420px;height:min(90vh,720px);' +
            'background:#fff;border-radius:16px;overflow:hidden;box-shadow:0 20px 60px rgba(0,0,0,.4);';

        var closeBtn = document.createElement('button');
        closeBtn.innerHTML = '&times;';
        closeBtn.setAttribute('aria-label', 'Close');
        closeBtn.style.cssText = 'position:absolute;top:8px;right:8px;z-index:2;width:30px;height:30px;' +
            'border-radius:50%;border:none;background:rgba(0,0,0,.55);color:#fff;font-size:20px;' +
            'line-height:1;cursor:pointer;';
        closeBtn.onclick = closeModal;

        modalIframe = document.createElement('iframe');
        modalIframe.src = url;
        modalIframe.style.cssText = 'width:100%;height:100%;border:0;';
        modalIframe.setAttribute('allow', 'payment');

        box.appendChild(closeBtn);
        box.appendChild(modalIframe);
        modalOverlay.appendChild(box);
        document.body.appendChild(modalOverlay);
    }

    // The payment page (loaded in the iframe) posts a message here once
    // the customer's payment finishes - this is what actually fires the
    // onSuccess/onFailed/onTimeout callbacks.
    window.addEventListener('message', function (event) {
        var data = event.data;
        if (!data || !(data._neopay || data._zapupi)) return; // _zapupi kept for pages using the older key name

        var status = data.type;
        var orderId = data.orderId;

        if (status === 'success' && typeof callbacks.onSuccess === 'function') {
            callbacks.onSuccess(orderId);
        } else if (status === 'failed' && typeof callbacks.onFailed === 'function') {
            callbacks.onFailed(orderId);
        } else if (status === 'timeout' && typeof callbacks.onTimeout === 'function') {
            callbacks.onTimeout(orderId);
        }

        // Give the customer a moment to see the result animation inside the
        // iframe before the modal disappears, rather than closing instantly.
        setTimeout(closeModal, 1200);
    });

    window.NeoPay = {
        setPaymentCallbacks: function (cbs) {
            callbacks.onSuccess = cbs.onSuccess || null;
            callbacks.onFailed = cbs.onFailed || null;
            callbacks.onTimeout = cbs.onTimeout || null;
        },

        createOrder: function (params, handlers) {
            handlers = handlers || {};
            postForm('/api/create-order', params, function (err, data) {
                if (err) {
                    if (handlers.onError) handlers.onError(err);
                    return;
                }
                if (!data || data.status !== true) {
                    if (handlers.onError) handlers.onError((data && data.message) || 'Order creation failed');
                    return;
                }
                var result = data.result || {};
                if (handlers.onResponse) handlers.onResponse(result.payment_url, result.orderId || result.order_id || params.order_id);
            });
        },

        orderStatus: function (params, handlers) {
            handlers = handlers || {};
            postForm('/api/check-order-status', params, function (err, data) {
                if (err) {
                    if (handlers.onError) handlers.onError(err);
                    return;
                }
                if (!data) {
                    if (handlers.onError) handlers.onError('No response from server');
                    return;
                }
                if (data.status === false) {
                    if (handlers.onError) handlers.onError(data.message || 'Could not fetch status');
                    return;
                }
                if (handlers.onResponse) handlers.onResponse(params.order_id, data);
            });
        },

        /** Opens the given payment_url in an embedded modal/iframe on the current page. */
        loadPayment: function (url) {
            openModal(url);
        },

        closePayment: function () {
            closeModal();
        },

        // Kept for parity with pages that call window.parent.NeoPay._trigger(...)
        // directly instead of postMessage (same-origin embeds).
        _trigger: function (status, orderId, reason) {
            window.postMessage({ _neopay: true, type: status, orderId: orderId, reason: reason }, '*');
        }
    };
})(window, document);
