<?php

namespace GriffinForms\Admin\App\Html\Containers;

final class LeftSideBar extends \GriffinForms\Admin\App\Html\Containers\Format
{

    protected function setWidgets()
    {
        $this->widgets = array(
            'field_selection',
            'form_tree',
        );
    }

    public function getHtml()
    {
        echo '<div id="' . esc_html($this->getHtmlId()) . '" class="griffinforms-app-sidebar bg-white">';
        $this->widgets['field_selection']->getHtml();
        echo '<div data-gf-leftsidebar-panel="structure" class="gf-leftsidebar-panel" style="display:none;">';
        $this->widgets['form_tree']->getHtml();
        echo '</div>';
        echo '</div>';
    }

    public function getJs()
    {
        $this->widgets['field_selection']->getJs();
        $this->widgets['form_tree']->getJs();
        $this->leftSidebarPanelControllerJs();
    }

    private function leftSidebarPanelControllerJs()
    {
        echo '
        (function() {
            let gfLeftSidebarCurrentPanel = "fields";

            const showPanel = (panelName) => {
                $("[data-gf-leftsidebar-panel]").each(function() {
                    $(this).toggle($(this).attr("data-gf-leftsidebar-panel") === panelName);
                });
                gfLeftSidebarCurrentPanel = panelName;
            };

            showPanel("fields");

            document.addEventListener("gf-leftsidebar-panel", function(event) {
                const requestedPanel = event && event.detail && event.detail.panel ? event.detail.panel : "fields";
                if (requestedPanel === gfLeftSidebarCurrentPanel && requestedPanel !== "fields") {
                    showPanel("fields");
                } else {
                    showPanel(requestedPanel);
                }
            });
        })();
        ' . PHP_EOL;
    }
}