{% extends "base.html.twig" %}

{% block head %}
<style>
    html, body {
        margin: 0;
        width: 100%;
        height: 100%;
    }

    iframe {
        border: 0;
        overflow: hidden;
        display: none;
    }

    .message {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        height: 100%;
        width: 100%;
        font-family: sans-serif;
        font-size: 14px;
        font-weight: 600;
        color: #4c4c4c;
    }

    .error-display {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        height: 100%;
        width: 100%;
        font-family: sans-serif;
        text-align: center;
        color: #d32f2f;
        padding: 20px;
    }

    .error-display h3 {
        margin-bottom: 10px;
        font-size: 18px;
    }

    .error-display p {
        margin: 0;
        font-size: 14px;
        color: #666;
    }
</style>
{% endblock %}

{% block content %}
{% if show_error %}
    <div class="error-display">
        <h3>Unable to Load Content</h3>
        <p>{{ error_message|default('An error occurred while loading the provisioner content.') }}</p>
    </div>
{% else %}
    <div id="plugin-loader" class="message">Loading content...</div>

    <script>
        const provisioner_url = "{{ provisioner_url }}";
        const plugin_id = "{{ plugin.getId() }}";
        const config_url = `/crm/system/plugins/${plugin_id}/configuration`;
        const public_url = "{{ plugin.getPublicUrl() }}";
        const route = "{{ path|default('logs') }}";

        let message = "Loading content...";

        function updateMessage(message) {
            document.getElementById("plugin-loader").innerHTML = message;
        }

        function hideWidget() {
            top.$("iframe").parent().hide();
        }

        function showWidget() {
            top.$("iframe").parent().show();
        }
    </script>

    <iframe
        id="plugin-iframe"
        src="{{ provisioner_url }}/{{ path }}?{{ signature }}"
        width="100%"
        height="100%">
    </iframe>
{% endif %}
{% endblock %}

{% block scripts %}
{% if hide_parent %}
<script>
    // Hide parent panel if requested
    if (typeof hideWidget === 'function') {
        hideWidget();
    }
</script>
{% endif %}

{% if not show_error %}
<!--suppress HtmlUnknownTarget -->
<script src="{{ plugin_url }}/js/iframe-resizer.parent.js"></script>

<script>
    const $this = top.$(".plugin-iframe, .card--plugin-widget > iframe");

    /** cSpell:ignore HTMLIFrameElement
    /** @var {HTMLIFrameElement} iframe */
    const iframe = $this[0];

    // Shortcut for selecting elements in this script's context
    const $$ = (selector) => top.$(selector, iframe.contentDocument);

    const $loader = $$("#plugin-loader");
    const $iframe = top.$("#plugin-iframe", iframe.contentDocument);

    /** @var {import("./node_modules/@types/iframe-resizer")} iframeResize */
    iframeResize({
        license: "GPLv3",
        waitForLoad: true,
        onResized: function (e) {
            if (e.height < 38)
                e.height = 38
            $this.css("height", e.height)
        }
    }, "#plugin-iframe");

    // Swap Loader for IFrame when content loads
    $iframe.on("load", function () {
        $loader.remove();
        $iframe.show();
    });
</script>

{#  PostMessage Functionality - Keep all existing functionality #}
<script>
    // Listen for messages from the provisioner
    window.addEventListener("message", function (e) {
        // IF the origin is not the provisioner URL,
        // OR the data is NOT an object,
        // OR a function is NOT specified,
        // OR the specified function is not defined in this context,
        // THEN return immediately!
        if (e.origin !== "{{ provisioner_url }}" ||
            typeof e.data !== "object" ||
            !e.data.func ||
            this[e.data.func] === undefined)
            return;

        // OTHERWISE, call the specified function with any provided arguments!
        this[e.data.func](...e.data?.args);
    });

    // #region PostMessage Functions

    /**
     * Redirects the parent window to the given URL.
     * @param {string} url - The URL to redirect the parent window.
     */
    function redirectParent(url) {
        parent.location.href = url;
    }

    /**
     * Redirects the iframe to the given URL.
     * @param {string} url - The URL to redirect the iframe.
     */
    function redirectIframe(url) {
        window.location.href = url;
    }

    /**
     * Toggles the modal mask (background overlay) outside of the iframe.
     * @param {boolean} show - Whether to show or hide the modal mask.
     */
    function toggleModalMask(show) {
        const $ = top.$;

        if (show) {
            console.log("show");
            const $style = $(`
            <style>
                .modal-bar {
                    position:absolute;
                    left:0;
                    background: rgba(21, 23, 37, 0.4);
                    z-index: 1000;
                }
                .modal-bar-t {
                    top:0;
                    width: 100%;
                    height: 50px;
                }
                .modal-bar-l {
                    top:50px;
                    width: 50px;
                    height: calc(100% - 50px);
                }
            </style>
            `);
            $style.prependTo(top.document.head);

            const $div = $(`
            <div class="modal-bar modal-bar-t"></div>
            <div class="modal-bar modal-bar-l"></div>
            `);
            $div.prependTo(top.document.body);
        } else {
            console.log("hide");
            $(".modal-bar").remove();
        }
    }

    /**
     * Displays a toast notification using the built-in Toastr library.
     * @param {string} type - The type of toast to display.
     * @param {string} message - The message to display in the toast.
     * @param {string} title - The title of the toast.
     * @param {Object} options - The options for the toast.
     */
    function toast(type, message, title, options) {
        switch (type) {
            case "success":
                top.toastr.success(message, title, options);
                break;
            case "error":
                top.toastr.error(message, title, options);
                break;
            case "info":
                top.toastr.info(message, title, options);
                break;
            case "warning":
                top.toastr.warning(message, title, options);
                break;
            default:
                console.error("Invalid toast type: " + type);
                break;
        }
    }

    // TODO: Add any other functions here...

    // #endregion

</script>
{% endif %}
{% endblock %}
