<?php
/**
 * Hyva-compatible Checkout Modal Template
 * This template is simpler as it's mainly used in checkout
 */

use Magento\Framework\Escaper;

/** @var $block \TbiBank\FusionPay\Block\Frontend\CheckoutModal */
/** @var Escaper $escaper */

$calculatorUrl = $block->getCalculatorUrl();
$calculatorOrigin = $block->getOrigin();
$loadingImg = $block->getLoadingImg();

// Only render if we have valid calculator data
if (empty($calculatorUrl) || empty($calculatorOrigin)) {
    return;
}
?>

<div id="tbi_popup_container" 
     x-data="tbiCheckoutModal()"
     x-init="init()"
     x-show="isOpen"
     x-cloak
     class="fixed inset-0 z-50 overflow-y-auto"
     style="display: none;"
     data-calculator="<?= $escaper->escapeHtmlAttr($calculatorUrl) ?>"
     data-tbi="<?= $escaper->escapeHtmlAttr($calculatorOrigin) ?>">
    
    <!-- Backdrop -->
    <div class="fixed inset-0 bg-black bg-opacity-50 transition-opacity"
         @click="closeModal()"></div>
    
    <!-- Modal Content -->
    <div class="flex min-h-full items-center justify-center p-4">
        <div class="relative bg-white rounded-lg shadow-xl w-full max-w-4xl"
             @click.stop>
            
            <!-- Close Button -->
            <button type="button"
                    @click="closeModal()"
                    class="absolute top-4 right-4 z-10 text-gray-400 hover:text-gray-600 transition-colors">
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                </svg>
            </button>
            
            <!-- Loading Indicator -->
            <div x-show="isLoading"
                 id="tbi_loading"
                 class="absolute inset-0 flex flex-col items-center justify-center bg-white rounded-lg z-20">
                <img src="<?= $escaper->escapeUrl($loadingImg) ?>" 
                     alt="Loading" 
                     class="w-32 h-32">
                <div class="mt-4 text-gray-600 font-medium">
                    <?= $escaper->escapeHtml(__('please wait')) ?>
                </div>
            </div>
            
            <!-- Iframe Container -->
            <div id="iframe_container" class="relative bg-white rounded-lg overflow-hidden">
                <iframe id="tbi_popup_iframe"
                        x-bind:src="iframeSrc"
                        @load="onIframeLoad()"
                        scrolling="auto"
                        frameborder="0"
                        class="w-full h-[600px]"></iframe>
            </div>
        </div>
    </div>
</div>

<script>
function tbiCheckoutModal() {
    return {
        isOpen: false,
        isLoading: true,
        iframeSrc: '',
        allowedOrigin: atob('<?= $escaper->escapeJs($calculatorOrigin) ?>'),
        resizeHelper: window.FusionPayTbiRoIframeResize,
        
        init() {
            window.addEventListener('message', (event) => this.handleMessage(event));
            this.resizeHelper.bindHostSurfaceSync(this.getIframe(), this.allowedOrigin);
            // CKT-4091: on a short viewport the popup can overflow the
            // screen with no way to scroll it into view, so Esc needs to
            // close it too - an outside click shouldn't be the only way out.
            window.addEventListener('keydown', (event) => {
                if (event.key === 'Escape' && this.isOpen) {
                    this.closeModal();
                }
            });
        },

        getFrameContainer() {
            return document.getElementById('iframe_container');
        },

        getIframe() {
            return document.getElementById('tbi_popup_iframe');
        },

        resetIframe() {
            this.resizeHelper.resetReadyState(this.getFrameContainer(), this.getIframe());
        },
        
        openModal(url) {
            this.isOpen = true;
            this.isLoading = true;
            this.resetIframe();
            this.iframeSrc = this.resizeHelper.appendHostSurface(url);
            document.body.style.overflow = 'hidden';
            document.getElementById('tbi_popup_container').classList.add('show');
        },
        
        closeModal() {
            this.isOpen = false;
            this.isLoading = true;
            this.iframeSrc = '';
            document.body.style.overflow = 'auto';
            document.getElementById('tbi_popup_container').classList.remove('show');
        },
        
        onIframeLoad() {
            this.isLoading = false;
        },

        handleMessage(event) {
            if (event.origin !== this.allowedOrigin) {
                return;
            }

            try {
                const data = this.resizeHelper.parseMessage(event.data);

                if (this.resizeHelper.handleMessage(data, this.getFrameContainer(), this.getIframe())) {
                    return;
                }

                if (data.command === 'close' || data.command === 'close_calculator') {
                    this.closeModal();
                }
            } catch (error) {
                console.error('Invalid JSON:', error);
            }
        }
    }
}
</script>
