<?php

namespace GriffinForms\Admin\App\Html\Traits;

trait ViewLayoutJs
{
    /**
     * Creates new JS events based on $js_events_views and $js_events_actions
     */
    private function initializeEventsJs()
    {
        $js_events = array_merge($this->js_events_views, $this->js_events_actions);

        foreach ($js_events as $event => $value) {
            echo '
            const ' . esc_js($event) .' = new Event("' . esc_js($value) . '")' . PHP_EOL;
        }
    }

    /**
     * Creates JS event listeners to show HTML elements based on their data-gf-context values.
     * When an event from array $js_events_views is dispatched, all HTML elements with the array value in their data-gf-context are displayed.
     */
    private function showContextItemsJs()
    {
        foreach ($this->js_events_views as $event => $value) {
            echo '
            document.addEventListener("' . esc_js($value) . '", () => {
                showContextItems("' . esc_js($value) . '");
            });' . PHP_EOL;
        }
    }

    /**
     * Sets height of textarea formcontrols based on rows of text in them.
     * This is called only after form layout HTML is received since textarea are used to live edit descriptions inside the form layout HTML.
     */
    private function formHtmlReceivedListnerJs()
    {
        echo '
        document.addEventListener("form-html-received", () => {

            $(document).find(".griffinforms-app-textarea_update_field").each(function(){
                this.style.height = "";
                this.style.height = this.scrollHeight + "px";
            });

            if (typeof window._gfFormAreaBgColor !== "undefined") {
                if (typeof griffinformsSetFormAreaBgColor === "function") {
                    griffinformsSetFormAreaBgColor(window._gfFormAreaBgColor);
                } else {
                    const formArea = document.getElementById("griffinforms-form-area");
                    if (formArea) {
                        if (window._gfFormAreaBgColor) {
                            formArea.style.setProperty("background-color", window._gfFormAreaBgColor, "important");
                        } else {
                            formArea.style.removeProperty("background-color");
                        }
                    }
                }
            }

        });
        ' . PHP_EOL;
    }
}
