<?php

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

/**
 * Renders the form builder's options dropdown menu located in the title bar.
 * Includes grouped menu sections for view settings, export options, and external links.
 * Handles related JavaScript functionality for UI toggles like fullscreen and compact mode.
 */
final class OptionsMenu extends \GriffinForms\Admin\App\Html\Widgets\TitleBar\Format
{
    /**
     * Outputs the full HTML structure for the dropdown menu.
     */
    public function getHtml()
    {
        echo '<div class="griffinforms-dropdown">';
        $this->getSvgIcon();
        echo '<div class="griffinforms-dropdown-popover">';
        $this->getMenuItems();
        echo '</div>';
        echo '</div>';
    }

    /**
     * Renders the three-dot toggle button SVG icon.
     */
    private function getSvgIcon() {
        echo '<button type="button" 
                    aria-haspopup="true" 
                    aria-expanded="false" 
                    class="griffinforms-dropdown-toggle" 
                    aria-label="Options">';
        echo '<svg xmlns="http://www.w3.org/2000/svg" 
                    viewBox="0 0 24 24" 
                    width="24" 
                    height="24" 
                    aria-hidden="true" 
                    focusable="false">';
        echo '<path d="M13 19h-2v-2h2v2zm0-6h-2v-2h2v2zm0-6h-2V5h2v2z"></path>';
        echo '</svg>';
        echo '</button>';
    }

    /**
     * Renders all menu groups and their items.
     */
    private function getMenuItems()
    {
        $this->renderFormGroup();
        $this->renderViewGroup();
        //$this->renderImportExportGroup();
        $this->renderExternalLinksGroup();
    }

    /**
     * Displays the 'Form' group with Conditional Logic, Integrations, and Accounts.
     */
    private function renderFormGroup()
    {
        echo '<div class="griffinforms-dropdown-group border-bottom">';
        echo '<div class="griffinforms-dropdown-group-heading">' . esc_html__('Form', 'griffinforms-form-builder') . '</div>';
        echo '<div class="griffinforms-dropdown-group-items">';
        $this->renderFormThemesItem();
        $this->renderFormNotificationsItem();
        $this->renderConditionalLogicItem();
        $this->renderIntegrationsItem();
        $this->renderAccountsItem();
        echo '</div></div>';
    }

    private function renderFormThemesItem()
    {
        $form_id = isset($_GET['form_id']) ? absint(wp_unslash($_GET['form_id'])) : 0;
        if (!$form_id) {
            return;
        }

        $button_id = 'griffinforms-options-menu-button-form-themes';
        $icon_url  = $this->getImg('form_theme', 'icon', 'url');
        $icon      = '<img src="' . esc_url($icon_url) . '" alt="" class="griffinforms-options-menu-icon" width="18" height="18" />';

        echo '<button id="' . esc_attr($button_id) . '" type="button" role="menuitem"';
        echo ' class="griffinforms-dropdown-item-button d-flex align-items-center justify-content-between px-2 py-1"';
        echo ' data-close-menu="true"';
        echo ' data-bs-toggle="modal" data-bs-target="#griffinforms-builder-modal-formthemes"';
        echo '>';
        echo '<div class="griffinforms-dropdown-item-content flex-column flex-fill me-4">';
        echo '<div class="griffinforms-dropdown-item-label">' . esc_html__('Form Theme', 'griffinforms-form-builder') . '</div>';
        echo '<div class="griffinforms-dropdown-item-info small text-muted">' . esc_html__('Colours, fonts and style', 'griffinforms-form-builder') . '</div>';
        echo '</div>';
        echo '<div class="griffinforms-dropdown-item-icon d-flex align-items-end"><div class="mt-3 p-1">';
        echo '<span class="griffinforms-menu-icon-indicator" style="visibility:visible;">' . wp_kses_post($icon) . '</span>';
        echo '</div></div>';
        echo '</button>';
    }

    private function renderFormNotificationsItem()
    {
        $form_id = isset($_GET['form_id']) ? absint(wp_unslash($_GET['form_id'])) : 0;
        if (!$form_id) {
            return;
        }

        $button_id = 'griffinforms-options-menu-button-form-notifications';
        $icon_url  = $this->getImg('mail', 'icon', 'url');
        $icon      = '<img src="' . esc_url($icon_url) . '" alt="" class="griffinforms-options-menu-icon" width="18" height="18" />';

        echo '<button id="' . esc_attr($button_id) . '" type="button" role="menuitem"';
        echo ' class="griffinforms-dropdown-item-button d-flex align-items-center justify-content-between px-2 py-1"';
        echo ' data-close-menu="true"';
        echo ' data-bs-toggle="modal" data-bs-target="#griffinforms-builder-modal-formnotifications"';
        echo '>';
        echo '<div class="griffinforms-dropdown-item-content flex-column flex-fill me-4">';
        echo '<div class="griffinforms-dropdown-item-label">' . esc_html__('Notifications', 'griffinforms-form-builder') . '</div>';
        echo '<div class="griffinforms-dropdown-item-info small text-muted">' . esc_html__('Confirmation and alert emails', 'griffinforms-form-builder') . '</div>';
        echo '</div>';
        echo '<div class="griffinforms-dropdown-item-icon d-flex align-items-end"><div class="mt-3 p-1">';
        echo '<span class="griffinforms-menu-icon-indicator" style="visibility:visible;">' . wp_kses_post($icon) . '</span>';
        echo '</div></div>';
        echo '</button>';
    }

    private function renderConditionalLogicItem()
    {
        $form      = $this->utility->getForm();
        $count     = $form ? (int) $form->getRulesCount() : 0;
        $badge     = '<span id="griffinforms-app-rules-btn-badge-count" class="badge small rounded-pill bg-dark text-white ms-1' . ( $count === 0 ? ' d-none' : '' ) . '">' . $count . '</span>';
        $button_id = 'griffinforms-options-menu-button-conditional-logic';
        $icon_url  = $this->getImg('conditional_logic', 'icon', 'url');
        $icon      = '<img src="' . esc_url($icon_url) . '" alt="" class="griffinforms-options-menu-icon" width="18" height="18" />';

        echo '<button id="' . esc_attr($button_id) . '" type="button" role="menuitem"';
        echo ' class="griffinforms-dropdown-item-button d-flex align-items-center justify-content-between px-2 py-1"';
        echo ' data-close-menu="true"';
        echo ' data-bs-toggle="modal" data-bs-target="#griffinforms-builder-modal-conditionallogic"';
        echo '>';
        echo '<div class="griffinforms-dropdown-item-content flex-column flex-fill me-4">';
        echo '<div class="griffinforms-dropdown-item-label d-flex align-items-center">';
        echo esc_html__('Conditional Logic', 'griffinforms-form-builder');
        echo wp_kses_post($badge);
        echo '</div>';
        echo '<div class="griffinforms-dropdown-item-info small text-muted">' . esc_html__('Rules for fields, pages and calculations', 'griffinforms-form-builder') . '</div>';
        echo '</div>';
        echo '<div class="griffinforms-dropdown-item-icon d-flex align-items-end"><div class="mt-3 p-1">';
        echo '<span class="griffinforms-menu-icon-indicator" style="visibility:visible;">' . wp_kses_post($icon) . '</span>';
        echo '</div></div>';
        echo '</button>';
    }

    private function renderIntegrationsItem()
    {
        $button_id = 'griffinforms-options-menu-button-integrations';
        $icon_url  = $this->getImg('integrations', 'icon', 'url');
        $icon      = '<img src="' . esc_url($icon_url) . '" alt="" class="griffinforms-options-menu-icon" width="18" height="18" />';

        echo '<button id="' . esc_attr($button_id) . '" type="button" role="menuitem"';
        echo ' class="griffinforms-dropdown-item-button d-flex align-items-center justify-content-between px-2 py-1"';
        echo ' data-close-menu="true"';
        echo ' data-bs-toggle="modal" data-bs-target="#griffinforms-builder-modal-integrations"';
        echo '>';
        echo '<div class="griffinforms-dropdown-item-content flex-column flex-fill me-4">';
        echo '<div class="griffinforms-dropdown-item-label">' . esc_html__('Integrations', 'griffinforms-form-builder') . '</div>';
        echo '<div class="griffinforms-dropdown-item-info small text-muted">' . esc_html__('Webhooks and service connections', 'griffinforms-form-builder') . '</div>';
        echo '</div>';
        echo '<div class="griffinforms-dropdown-item-icon d-flex align-items-end"><div class="mt-3 p-1">';
        echo '<span class="griffinforms-menu-icon-indicator" style="visibility:visible;">' . wp_kses_post($icon) . '</span>';
        echo '</div></div>';
        echo '</button>';
    }

    private function renderAccountsItem()
    {
        $button_id = 'griffinforms-options-menu-button-accounts';
        $icon_url  = $this->getImg('accounts', 'icon', 'url');
        $icon      = '<img src="' . esc_url($icon_url) . '" alt="" class="griffinforms-options-menu-icon" width="18" height="18" />';

        echo '<button id="' . esc_attr($button_id) . '" type="button" role="menuitem"';
        echo ' class="griffinforms-dropdown-item-button d-flex align-items-center justify-content-between px-2 py-1"';
        echo ' data-close-menu="true"';
        echo ' data-bs-toggle="modal" data-bs-target="#griffinforms-builder-modal-accounts"';
        echo '>';
        echo '<div class="griffinforms-dropdown-item-content flex-column flex-fill me-4">';
        echo '<div class="griffinforms-dropdown-item-label">' . esc_html__('Accounts', 'griffinforms-form-builder') . '</div>';
        echo '<div class="griffinforms-dropdown-item-info small text-muted">' . esc_html__('Create or update users on submit', 'griffinforms-form-builder') . '</div>';
        echo '</div>';
        echo '<div class="griffinforms-dropdown-item-icon d-flex align-items-end"><div class="mt-3 p-1">';
        echo '<span class="griffinforms-menu-icon-indicator" style="visibility:visible;">' . wp_kses_post($icon) . '</span>';
        echo '</div></div>';
        echo '</button>';
    }

    /**
     * Displays the 'View' group with fullscreen and compact layout toggles.
     */
    private function renderViewGroup()
    {
        echo '<div class="griffinforms-dropdown-group border-bottom">';
        echo '<div class="griffinforms-dropdown-group-heading">' . esc_html__('View', 'griffinforms-form-builder') . '</div>';
        echo '<div class="griffinforms-dropdown-group-items">';
        $this->renderFullscreenToggle();
        $this->renderCompactLayoutToggle();
        echo '</div></div>';
    }

    // Legacy alias kept for safety — callers outside this file should not exist.
    private function renderFormActionsGroup()
    {
        $this->renderViewGroup();
    }

    /**
     * Adds the fullscreen/compact mode menu item with tick icon and toggle behavior.
     */
    private function renderFullscreenToggle()
    {
        $this->renderMenuButton(
            label: __('Fullscreen Mode', 'griffinforms-form-builder'),
            description: __('Show or hide the admin chrome', 'griffinforms-form-builder'),
            icon: 'tick',
            args: [
                'close_menu' => false,
                'role' => 'menuitemcheckbox',
                'aria_checked' => false,
            ]
        );
    }

    /**
     * Adds the fullscreen/compact mode menu item with tick icon and toggle behavior.
     */
    private function renderCompactLayoutToggle()
    {
        $this->renderMenuButton(
            label: __('Compact Layout', 'griffinforms-form-builder'),
            description: __('Hide labels for a cleaner view', 'griffinforms-form-builder'),
            icon: 'tick',
            args: [
                'close_menu' => false,
                'role' => 'menuitemcheckbox',
                'aria_checked' => false,
            ]
        );
    }

    /**
     * Outputs the export-related menu group, such as download form option.
     */
    private function renderImportExportGroup()
    {
        echo '<div class="griffinforms-dropdown-group border-bottom">';
        echo '<div class="griffinforms-dropdown-group-heading">' . esc_html__('Export Options', 'griffinforms-form-builder') . '</div>';
        echo '<div class="griffinforms-dropdown-group-items">';
        $this->renderDownloadFormButton();
        echo '</div></div>';
    }

    private function renderDownloadFormButton()
    {
        $this->renderMenuButton(
            label: __('Download Form', 'griffinforms-form-builder'),
            description: __('Export this form as a downloadable file', 'griffinforms-form-builder'),
            icon: 'download',
            args: [
                'close_menu' => true,
                'role' => 'menuitem',
            ]
        );
    }

    /**
     * Outputs the advanced settings group (currently disabled).
     */
    private function renderLayoutGroup()
    {
        echo '<div class="griffinforms-dropdown-group">';
        echo '<div class="griffinforms-dropdown-group-heading">' . esc_html__('Advanced Settings', 'griffinforms-form-builder') . '</div>';
        echo '<div class="griffinforms-dropdown-group-items">';
        $this->renderConditionalLogicButton();
        echo '</div></div>';
    }

    /**
     * Adds the Conditional Logic menu item to the advanced settings group.
     */
    private function renderConditionalLogicButton()
    {
        $this->renderMenuButton(
            label: __('Conditional Logic', 'griffinforms-form-builder'),
            description: __('Add logic to show or hide fields based on user input', 'griffinforms-form-builder'),
            icon: 'conditional_logic',
            args: [
                'close_menu' => true,
                'role' => 'menuitem',
            ]
        );
    }

    /**
     * Renders external links like Settings with dynamic form ID.
     */
    private function renderExternalLinksGroup()
    {
        $form_id = isset($_GET['form_id']) ? absint(wp_unslash($_GET['form_id'])) : 0;

        echo '<div class="griffinforms-dropdown-group">';
        echo '<div class="griffinforms-dropdown-group-heading">' . esc_html__('Navigate', 'griffinforms-form-builder') . '</div>';
        echo '<div class="griffinforms-dropdown-group-items">';

        if ($form_id > 0) {
            $submissions_url = 'admin.php?page=griffinforms-submissions&form_id=' . $form_id . '&paged=1';
            $this->renderExternalLink(__('Submissions', 'griffinforms-form-builder'), $submissions_url);
        }

        echo '</div></div>';
    }

    /**
     * Outputs a styled anchor link in the menu with an external icon.
     *
     * @param string $label The text label for the menu item.
     * @param string $url Relative admin URL for redirection.
     */
    private function renderExternalLink($label, $url)
    {
        $button_id = 'griffinforms-options-menu-button-' . sanitize_title_with_dashes($label);
        $icon_url = $this->getImg('external', 'icon', 'url');
        $icon = '<img src="' . esc_url($icon_url) . '" alt="' . esc_attr($label) . '" class="griffinforms-options-menu-icon" width="18" height="18" />';

        echo '<a id="' . esc_attr($button_id) . '" href="' . esc_url(admin_url($url)) . '" role="menuitem" target="_blank" rel="noopener noreferrer"';
        echo ' class="griffinforms-dropdown-item-button d-flex align-items-center justify-content-between p-2 text-decoration-none">';
        echo '<div class="griffinforms-dropdown-item-content flex-column flex-fill me-4">';
        echo '<div class="griffinforms-dropdown-item-label">' . esc_html($label) . '</div>';
        echo '</div>';
        echo '<div class="griffinforms-dropdown-item-icon d-flex align-items-end">';
        echo '<div class="p-1">';
        echo wp_kses_post($icon);
        echo '</div>';
        echo '</div>';
        echo '</a>';
    }

    /**
     * Renders a menu item button with optional description, icon, and toggle state.
     *
     * @param string $label        The visible label text.
     * @param string $description  Subtext for the item.
     * @param string $icon         Icon slug to use.
     * @param array  $args         Additional options like role, aria-checked, etc.
     */
    private function renderMenuButton($label, $description = '', $icon = '', $args = [])
    {
        $button_id = 'griffinforms-options-menu-button-' . sanitize_title_with_dashes($label);

        $close_menu = isset($args['close_menu']) ? $args['close_menu'] : true;
        $role = isset($args['role']) ? $args['role'] : 'menuitem';
        $custom_svg = isset($args['custom_svg']) ? $args['custom_svg'] : '';
        $icon_url = $this->getImg($icon, 'icon', 'url');
        $icon = '<img src="' . esc_url($icon_url) . '" alt="' . esc_attr($label) . '" class="griffinforms-options-menu-icon" width="18" height="18" />';

        $aria_checked_value = isset($args['aria_checked']) ? ($args['aria_checked'] ? 'true' : 'false') : null;
        $data_attr_value = $close_menu ? 'true' : 'false';

        echo '<button id="' . esc_attr($button_id) . '" type="button" role="' . esc_attr($role) . '"';
        if ($aria_checked_value !== null) {
            echo ' aria-checked="' . esc_attr($aria_checked_value) . '"';
        }
        echo ' class="griffinforms-dropdown-item-button d-flex align-items-center justify-content-between px-2 py-1"';
        echo ' data-close-menu="' . esc_attr($data_attr_value) . '"';
        echo '>';
        echo '<div class="griffinforms-dropdown-item-content flex-column flex-fill me-4">';
        echo '<div class="griffinforms-dropdown-item-label">' . esc_html($label) . '</div>';
        echo '<div class="griffinforms-dropdown-item-info small text-muted">' . esc_html($description) . '</div>';
        echo '</div>';
        echo '<div class="griffinforms-dropdown-item-icon d-flex align-items-end">';
        echo '<div class="mt-3 p-1">';
        $visibility = (isset($args['aria_checked']) && $args['aria_checked']) ? 'visible' : 'hidden';
        $icon_html = $custom_svg ? $custom_svg : $icon;
        echo '<span class="griffinforms-menu-icon-indicator" style="visibility:' . esc_attr($visibility) . ';">' . wp_kses_post($icon_html) . '</span>';
        echo '</div>';
        echo '</div>';
        echo '</button>';
    }

    /**
     * Outputs JavaScript logic for dropdown behavior and menu interaction.
     */
    protected function widgetJs()
    {
        $this->updateRulesBadgeCountJs();
        echo "
        $('.griffinforms-dropdown-toggle').on('click', function(e) {
            e.stopPropagation();
            this.focus(); // Force button to receive focus for visual outline

            const dropdown = $(this).closest('.griffinforms-dropdown');
            const popover = dropdown.find('.griffinforms-dropdown-popover');

            const isOpen = popover.hasClass('is-open');
            $('.griffinforms-dropdown-popover').removeClass('is-open');
            if (!isOpen) {
                popover.addClass('is-open');
            }
        });

        $(document).on('click', function(e) {
            if (!$(e.target).closest('.griffinforms-dropdown').length) {
                $('.griffinforms-dropdown-popover').removeClass('is-open');
            }
        });

        $('.griffinforms-dropdown-item-button').on('click', function(e) {
            this.focus(); // Ensure button receives focus on click
            const shouldClose = $(this).data('close-menu');
            if (shouldClose) {
                $('.griffinforms-dropdown-popover').removeClass('is-open');
            }
        });
    ";

        $this->toggleFullscreenJs();
        $this->toggleCompactLayoutJs();
    }

    /**
     * Handles fullscreen/compact mode toggle state and related UI changes.
     */
    private function toggleFullscreenJs()
    {
        echo '
        function griffinformsToggleFullscreen() {
            const btn = $("#griffinforms-options-menu-button-fullscreen-mode");
            const isChecked = btn.attr("aria-checked") === "true";
            btn.attr("aria-checked", !isChecked);
            const wrapper = $("#griffinforms-app-wrapper");
            wrapper.toggleClass("gf-fullscreen", !isChecked);
            wrapper.toggleClass("gf-no-fullscreen", isChecked);
            // toggle icon visibility
            btn.find(".griffinforms-menu-icon-indicator").css("visibility", !isChecked ? "visible" : "hidden");
            // toggle additional UI elements
            $(".edit-form-fullscreen-mode-close").toggle(!isChecked);
        }

        griffinformsToggleFullscreen();
        $("#griffinforms-options-menu-button-fullscreen-mode").on("click", function () {
            griffinformsToggleFullscreen();
        });';
    }

    /**
     * Handles fullscreen/compact mode toggle state and related UI changes.
     */
    private function toggleCompactLayoutJs()
    {
        echo '
        function griffinformsToggleCompactMode() {
            const btn = $("#griffinforms-options-menu-button-compact-layout");
            const isChecked = btn.attr("aria-checked") === "true";
            btn.attr("aria-checked", !isChecked);
            const wrapper = $("#griffinforms-app-wrapper");
            wrapper.toggleClass("gf-compact-mode", !isChecked);
            btn.find(".griffinforms-menu-icon-indicator").css("visibility", !isChecked ? "visible" : "hidden");
        }

        $("#griffinforms-options-menu-button-compact-layout").on("click", function () {
            griffinformsToggleCompactMode();
        });';
    }

    private function updateRulesBadgeCountJs()
    {
        $nonce   = wp_create_nonce('update_rules_badge_count');
        $form_id = (int) $this->utility->getFormId();

        echo '
        function updateRulesBadgeCount() {
            const badge = document.getElementById("griffinforms-app-rules-btn-badge-count");
            const formId = ' . $form_id . ';
            if (!badge || !formId) { return; }
            jQuery.post(ajaxurl, {
                action: "griffinformsGetRulesCount",
                form_id: formId,
                nonce: "' . esc_js($nonce) . '"
            }).done(function(response) {
                if (response && typeof response === "object" && response.success) {
                    const count = parseInt(response.data.count || 0, 10);
                    badge.textContent = count;
                    badge.classList.toggle("d-none", count === 0);
                }
            });
        }

        jQuery(document).on("griffinforms:rule-saved griffinforms:rule-deleted", function() {
            if (typeof updateRulesBadgeCount === "function") { updateRulesBadgeCount(); }
        });
        ';
    }
}
