<?php
    defined('_JEXEC') or die;
?>

<!DOCTYPE html>
<html lang="en-gb" dir="ltr">
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=0.5, maximum-scale=0.5, user-scalable=no">
        <meta charset="utf-8">
        <base href="<?php echo $this->baseUrl; ?>">
        <meta name="author" content="admin">
        <meta name="generator" content="Mefi's Asset Bridge">
        <title>Preview</title>
        <?php echo $this->getCss(); ?>

        <script src="<?php echo $this->baseUrl; ?>media/system/js/core.min.js"></script>
        <script src="<?php echo $this->baseUrl; ?>templates/yootheme/vendor/assets/uikit/dist/js/uikit.min.js"></script>
        <script src="<?php echo $this->baseUrl; ?>templates/yootheme/vendor/assets/uikit/dist/js/uikit-icons-design-escapes.min.js"></script>
        <script src="<?php echo $this->baseUrl; ?>templates/yootheme/js/theme.js"></script>
        <script src="<?php echo $this->baseUrl; ?>media/plg_system_mefisassetbridge/js/html2canvas.min.js"></script>
        <style type="text/css">
            body {
                margin: 0;
                padding: 0;
            }
            html, body {
                overflow: hidden;
            }
        </style>
    </head>
    <body><div id="___mefisassetbridge"></div>
<?php echo $this->renderedEl; ?>
<script>
// Screenshot capture functionality for iframe
// THIS SCRIPT RUNS INSIDE THE IFRAME, GENERATED BY JOOMLA (NOT BUNDLED WITH THIS APP)

(function () {
    'use strict';

    // Notify parent immediately that iframe initialization has started
    window.parent.postMessage({ type: 'IFRAME_INIT' }, '*');

    // Download status from server: { status: true } or { status: false, message: '...' }
    const downloadStatus = <?php echo json_encode($this->downloadStatus ?? ['status' => true]); ?>;

    // Unique capture token echoed back in IFRAME_READY so the parent can
    // reject signals that belong to a different, concurrent capture session.
    const captureId = <?php echo json_encode($this->captureId ?? ''); ?>;

    // Shared state to prevent multiple concurrent screenshot operations
    let _captureInProgress = null;

    /**
     * Replace video elements with static images before html2canvas capture
     * @returns {Array} Array of video data for restoration
     */
    function replaceVideosWithImages() {
        const videos = document.querySelectorAll('video');
        const videoData = [];

        videos.forEach(video => {
            const wasPlaying = !video.paused;
            if (wasPlaying) {
                video.pause();
            }
            if (video.videoWidth === 0 || video.videoHeight === 0) return;

            // Create canvas from video frame
            const canvas = document.createElement('canvas');
            canvas.width = video.videoWidth || video.clientWidth;
            canvas.height = video.videoHeight || video.clientHeight;

            const ctx = canvas.getContext('2d');
            try {
                ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
                const imgData = canvas.toDataURL('image/jpeg', 0.5);

                // Create replacement image element
                const img = document.createElement('img');
                img.src = imgData;
                img.style.cssText = window.getComputedStyle(video).cssText;
                img.style.display = video.style.display || 'inline-block';
                img.className = video.className;

                // Insert image before video and hide video
                video.parentNode.insertBefore(img, video);
                video.style.display = 'none';

                videoData.push({ video, img, wasPlaying });
            } catch (error) {
                console.warn('Could not capture video frame:', error);
            }
        });

        return videoData;
    }

    /**
     * Restore original video elements after screenshot
     * @param {Array} videoData - Array of video data from replaceVideosWithImages
     */
    function restoreVideos(videoData) {
        videoData.forEach(({ video, img, wasPlaying }) => {
            if (img && img.parentNode) {
                img.parentNode.removeChild(img);
            }
            video.style.display = '';
            if (wasPlaying) {
                video.play().catch(err => console.warn('Could not resume video playback:', err));
            }
        });
    }

    /**
     * Capture screenshot using html2canvas
     * Creates a JPEG screenshot of the iframe content at specified dimensions
     * @param {number} width - Target width
     * @param {number} height - Target height
     * @returns {Promise<string>} Base64 encoded JPEG image data URL
     */
    async function captureWithHtml2Canvas(width = 600, height = 1040) {
        if (typeof html2canvas === 'undefined') {
            throw new Error('html2canvas library not available');
        }

        let videoData = [];

        try {
            // Replace videos with static images
            videoData = replaceVideosWithImages();

            // Capture the entire document body at specified resolution
            const canvas = await html2canvas(document.body, {
                useCORS: false,
                allowTaint: false,
                scale: 1,
                width: width,
                height: height,
                windowWidth: width,
                windowHeight: height,
                x: 0,
                y: 0,
                backgroundColor: '#ffffff'
            });

            // Resize the canvas to 300x520
            const resizedCanvas = document.createElement('canvas');
            resizedCanvas.width = 300;
            resizedCanvas.height = 520;
            const resizedCtx = resizedCanvas.getContext('2d');
            resizedCtx.drawImage(canvas, 0, 0, 300, 520);

            // Convert to JPEG with 80% quality
            const screenshot = resizedCanvas.toDataURL('image/jpeg', 0.8);

            return screenshot;
        } catch (error) {
            throw error;
        } finally {
            // Always restore videos
            restoreVideos(videoData);
        }
    }

    /**
     * Main screenshot capture function
     * Called by parent window via postMessage
     * @param {number} width - Target width (default 600)
     * @param {number} height - Target height (default 1040)
     * @returns {Promise<string>} Base64 encoded JPEG image data URL
     */
    async function captureScreenshot(width = 600, height = 1040) {
        // Reuse in-flight capture to prevent multiple concurrent operations
        if (_captureInProgress) {
            try {
                return await _captureInProgress;
            } catch (err) {
                _captureInProgress = null;
                throw err;
            }
        }

        _captureInProgress = (async () => {
            try {
                // Use html2canvas for iframe screenshot
                return await captureWithHtml2Canvas(width, height);
            } finally {
                // Clear in-progress flag after completion
                _captureInProgress = null;
            }
        })();

        return await _captureInProgress;
    }

    /**
     * Handle all message events from parent window
     */
    window.addEventListener('message', async function (event) {
        switch (event.data.type) {
            case 'CAPTURE_SCREENSHOT':
                // Block screenshot only if status is false
                if (downloadStatus.status === false) {
                    window.parent.postMessage({
                        type: 'SCREENSHOT_RESPONSE',
                        messageId: event.data.messageId,
                        screenshot: null,
                        success: false,
                        error: downloadStatus.message || 'Screenshot capture blocked',
                        downloadStatus: downloadStatus
                    }, '*');
                    return;
                }

                // Get dimensions from message (default to 600x1040 for phone)
                const width = event.data.width || 600;
                const height = event.data.height || 1040;

                try {
                    const screenshot = await captureScreenshot(width, height);
                    window.parent.postMessage({
                        type: 'SCREENSHOT_RESPONSE',
                        messageId: event.data.messageId,
                        screenshot: screenshot,
                        success: true,
                        downloadStatus: downloadStatus
                    }, '*');
                } catch (error) {
                    window.parent.postMessage({
                        type: 'SCREENSHOT_RESPONSE',
                        messageId: event.data.messageId,
                        screenshot: null,
                        success: false,
                        error: error.message,
                        downloadStatus: downloadStatus
                    }, '*');
                }
                break;

            case 'ASSET_DATA_UPDATE':
                // Asset data received from parent
                break;

            default:
                // Unknown message type - ignore
                break;
        }
    });

    // Notify parent when iframe is fully loaded and ready
    // Wait 1 second after load to allow animations/transitions to complete
    function notifyReady() {
        setTimeout(function() {
            window.parent.postMessage({
                type: 'IFRAME_READY',
                captureId: captureId,
                downloadStatus: downloadStatus
            }, '*');
        }, 1000);
    }

    if (document.readyState === 'complete') {
        notifyReady();
    } else {
        window.addEventListener('load', notifyReady);
    }

})();

</script>
    </body>
</html>