<?php

namespace GriffinForms\Admin\App\Html\Widgets\TitleBar;

final class StructurePanelBtn extends \GriffinForms\Admin\App\Html\Widgets\TitleBar\Format
{
    public function getHtml()
    {
        echo '<button';
        echo ' id="griffinforms-titlebar-btn-structure"';
        echo ' class="gf-titlebar-panel-btn"';
        echo ' aria-pressed="false"';
        echo ' data-gf-panel="structure"';
        echo ' data-gf-context="form-layout"';
        echo ' aria-label="' . esc_attr__('Structure', 'griffinforms-form-builder') . '"';
        echo ' type="button"';
        echo '>';
        $icon_url = $this->config->getRootUrl() . 'admin/images/titlebar-icons/form-tree.svg';
        echo '<img src="' . esc_url($icon_url) . '" width="20" height="20" alt="" aria-hidden="true" class="gf-titlebar-panel-btn-icon" />';
        echo '</button>';
    }

    public function widgetJs()
    {
        echo '
        (function() {
            const btn = document.getElementById("griffinforms-titlebar-btn-structure");
            if (!btn) { return; }

            btn.addEventListener("click", function() {
                const isPressed = btn.getAttribute("aria-pressed") === "true";
                const panel = isPressed ? "fields" : "structure";
                document.dispatchEvent(new CustomEvent("gf-leftsidebar-panel", { detail: { panel: panel } }));
            });

            document.addEventListener("gf-leftsidebar-panel", function(event) {
                const panel = event && event.detail && event.detail.panel ? event.detail.panel : "fields";
                const active = panel === "structure";
                btn.setAttribute("aria-pressed", active ? "true" : "false");
                btn.classList.toggle("is-active", active);
            });
        })();
        ' . PHP_EOL;
    }

    public function __construct()
    {
        $this->setAll();
    }
}
