<?php if (!function_exists('matewa_admin_recover_clipped_chip_label')) : ?>
    <?php
    /**
     * Recover labels clipped by earlier admin chip-fit passes.
     * This is deliberately narrow: if a saved override is only a leading
     * fragment of the default label, render the default so the editor matches
     * the left preview and frontend widget again.
     */
    function matewa_admin_recover_clipped_chip_label($saved_label, $default_label) {
        $saved_label  = (string) $saved_label;
        $default_label = (string) $default_label;

        if ('' === trim($saved_label) || '' === trim($default_label)) {
            return '' === trim($saved_label) ? $default_label : $saved_label;
        }

        $normalise = static function ($value) {
            $value = html_entity_decode((string) $value, ENT_QUOTES, 'UTF-8');
            $value = str_replace(["\r\n", "\r", "\n", "\t"], ' ', $value);
            $value = preg_replace('/\s+/u', ' ', $value);
            $value = trim((string) $value);
            return function_exists('mb_strtolower') ? mb_strtolower($value, 'UTF-8') : strtolower($value);
        };

        $saved_plain  = $normalise($saved_label);
        $default_plain = $normalise($default_label);

        if ('' === $saved_plain || '' === $default_plain || $saved_plain === $default_plain) {
            return $saved_label;
        }

        $saved_len  = function_exists('mb_strlen') ? mb_strlen($saved_plain, 'UTF-8') : strlen($saved_plain);
        $default_len = function_exists('mb_strlen') ? mb_strlen($default_plain, 'UTF-8') : strlen($default_plain);

        if ($saved_len >= 4 && ($default_len - $saved_len) >= 2 && 0 === strpos($default_plain, $saved_plain)) {
            return $default_label;
        }

        return $saved_label;
    }
    ?>
<?php endif; ?>
<?php if ($chip_override_enabled && !empty($chip_items)) : ?>
    <div class="matewa-settings-card matewa-chip-studio-card">
        <style id="matewa-chip-studio-inline-hardlock">
        /* 247ChatMate — Visitor Button Studio FRONTEND CHIP PARITY HARDLOCK
           Scope: admin suggested/editable chip preview only.
           Source of truth: public/css/matewa-widget.css CHIPS contract.
           DO NOT ALTER during general admin polish, spacing passes, dashboard
           polish or helper-copy work. If this ever needs changing, change the
           frontend widget chip contract first, then mirror it here deliberately.
           Locked contract: 292px live grid, 3 equal columns, 8px gaps,
           52px chips, 6px/8px padding, 12px label, two-line clamp. */
        #matewa-chip-labels-section .matewa-chip-studio-card {
            padding: 22px !important;
            border-radius: 24px !important;
            box-sizing: border-box !important;
        }

        #matewa-chip-labels-section .matewa-chip-studio-card .matewa-chip-studio-layout {
            display: grid !important;
            grid-template-columns: repeat(2, minmax(0, 1fr)) !important;
            gap: 18px !important;
            align-items: stretch !important;
        }

        #matewa-chip-labels-section .matewa-chip-studio-card .matewa-chip-studio-business-panel,
        #matewa-chip-labels-section .matewa-chip-studio-card .matewa-chip-studio-editor-panel {
            display: flex !important;
            flex-direction: column !important;
            min-width: 0 !important;
            padding: 20px !important;
            border-radius: 20px !important;
            box-sizing: border-box !important;
        }

        #matewa-chip-labels-section .matewa-chip-studio-card .matewa-chip-studio-panel-header {
            min-height: 58px !important;
            margin-bottom: 14px !important;
            box-sizing: border-box !important;
        }

        #matewa-chip-labels-section .matewa-chip-studio-card .matewa-chip-studio-panel-header h3 {
            margin: 0 !important;
            line-height: 1.18 !important;
        }

        #matewa-chip-labels-section .matewa-chip-studio-card .matewa-chip-studio-panel-header p {
            margin: 4px 0 0 !important;
            line-height: 1.35 !important;
        }

        #matewa-chip-labels-section .matewa-chip-studio-card .matewa-selector-grid,
        #matewa-chip-labels-section .matewa-chip-studio-card .matewa-current-context {
            display: grid !important;
            grid-template-columns: 1fr !important;
            gap: 12px !important;
            width: 100% !important;
            min-height: 126px !important;
            margin: 0 0 32px !important;
            padding: 0 !important;
            align-items: stretch !important;
            box-sizing: border-box !important;
        }

        #matewa-chip-labels-section .matewa-chip-studio-card .matewa-selector-field:not(.matewa-selector-action),
        #matewa-chip-labels-section .matewa-chip-studio-card .matewa-current-context-item {
            min-height: 57px !important;
            box-sizing: border-box !important;
        }

        #matewa-chip-labels-section .matewa-chip-studio-card #matewa-manual-business-type-preview-wrap,
        #matewa-chip-labels-section .matewa-chip-studio-card .matewa-chip-studio-edit-column {
            width: 100% !important;
            max-width: 100% !important;
            margin-top: 0 !important;
            box-sizing: border-box !important;
        }

        #matewa-chip-labels-section .matewa-chip-studio-card .matewa-chip-preview-heading,
        #matewa-chip-labels-section .matewa-chip-studio-card .matewa-chip-editor-subtle {
            display: block !important;
            width: 292px !important;
            max-width: 292px !important;
            min-width: 292px !important;
            min-height: 19px !important;
            margin: 0 auto 10px !important;
            padding: 0 !important;
            color: #14532d !important;
            font-size: 12px !important;
            font-weight: 850 !important;
            line-height: 1.45 !important;
            text-align: left !important;
            box-sizing: border-box !important;
        }

        #matewa-chip-labels-section .matewa-chip-studio-card #matewa-manual-business-type-preview-wrap .matewa-chip-editor-frame {
            width: 292px !important;
            max-width: 292px !important;
            min-width: 292px !important;
            margin-left: auto !important;
            margin-right: auto !important;
            box-sizing: border-box !important;
        }

        #matewa-chip-labels-section .matewa-chip-studio-card .matewa-chip-studio-edit-column > .matewa-chip-editor-frame {
            width: 292px !important;
            max-width: 292px !important;
            min-width: 292px !important;
            margin-left: auto !important;
            margin-right: auto !important;
            box-sizing: border-box !important;
        }

        #matewa-chip-labels-section .matewa-chip-studio-card #matewa-manual-chip-preview-grid,
        #matewa-chip-labels-section .matewa-chip-studio-card .matewa-chip-studio-edit-grid {
            display: grid !important;
            grid-template-columns: repeat(3, minmax(0, 1fr)) !important;
            width: 292px !important;
            max-width: 292px !important;
            min-width: 292px !important;
            gap: 8px !important;
            margin: 0 auto !important;
            align-items: stretch !important;
            justify-items: stretch !important;
            justify-content: center !important;
            box-sizing: border-box !important;
        }

        #matewa-chip-labels-section .matewa-chip-studio-card #matewa-manual-chip-preview-grid .matewa-chip-editor-item,
        #matewa-chip-labels-section .matewa-chip-studio-card .matewa-chip-studio-edit-grid .matewa-chip-editor-item {
            display: flex !important;
            align-items: stretch !important;
            justify-content: stretch !important;
            width: 100% !important;
            min-width: 0 !important;
            max-width: 100% !important;
            margin: 0 !important;
            padding: 0 !important;
            box-sizing: border-box !important;
        }

        #matewa-chip-labels-section .matewa-chip-studio-card #matewa-manual-chip-preview-grid .matewa-chip-editor-chip,
        #matewa-chip-labels-section .matewa-chip-studio-card .matewa-chip-studio-edit-grid .matewa-chip-editor-chip {
            display: flex !important;
            align-items: center !important;
            justify-content: center !important;
            width: 100% !important;
            min-width: 0 !important;
            max-width: 100% !important;
            height: 52px !important;
            min-height: 52px !important;
            max-height: 52px !important;
            padding: 6px 8px !important;
            border-radius: 14px !important;
            border: 1.5px solid rgba(5, 122, 41, 0.28) !important;
            background: #ffffff !important;
            color: #057a29 !important;
            box-shadow: none !important;
            text-align: center !important;
            white-space: normal !important;
            word-break: normal !important;
            overflow-wrap: anywhere !important;
            overflow: hidden !important;
            box-sizing: border-box !important;
        }

        #matewa-chip-labels-section .matewa-chip-studio-card #matewa-manual-chip-preview-grid .matewa-chip-editor-chip span,
        #matewa-chip-labels-section .matewa-chip-studio-card .matewa-chip-studio-edit-grid .matewa-chip-editor-chip textarea,
        #matewa-chip-labels-section .matewa-chip-studio-card .matewa-chip-studio-edit-grid .matewa-chip-editor-measure {
            width: 100% !important;
            max-width: 100% !important;
            min-width: 0 !important;
            max-height: 34px !important;
            margin: 0 auto !important;
            padding: 0 !important;
            border: 0 !important;
            background: transparent !important;
            color: inherit !important;
            font-size: 12px !important;
            font-weight: 600 !important;
            line-height: 1.25 !important;
            font-family: inherit !important;
            text-align: center !important;
            white-space: normal !important;
            word-break: normal !important;
            overflow-wrap: normal !important;
            hyphens: none !important;
            overflow: hidden !important;
            box-shadow: none !important;
            resize: none !important;
            box-sizing: border-box !important;
        }

        #matewa-chip-labels-section .matewa-chip-studio-card #matewa-manual-chip-preview-grid .matewa-chip-editor-chip span {
            display: -webkit-box !important;
            -webkit-box-orient: vertical !important;
            -webkit-line-clamp: 2 !important;
        }

        #matewa-chip-labels-section .matewa-chip-studio-card .matewa-chip-studio-edit-grid .matewa-chip-editor-chip textarea {
            display: block !important;
            height: 34px !important;
            min-height: 34px !important;
            max-height: 34px !important;
            align-self: center !important;
            white-space: pre-wrap !important;
        }

        #matewa-chip-labels-section .matewa-chip-studio-card .matewa-chip-studio-edit-grid .matewa-chip-editor-chip.is-single-line textarea {
            height: 15px !important;
            min-height: 15px !important;
            max-height: 15px !important;
        }

        #matewa-chip-labels-section .matewa-chip-studio-card .matewa-chip-studio-edit-grid .matewa-chip-editor-measure {
            white-space: pre-wrap !important;
        }

        #matewa-chip-labels-section .matewa-chip-studio-card #matewa-manual-business-type-preview-wrap .matewa-chip-preview-subtle,
        #matewa-chip-labels-section .matewa-chip-studio-card .matewa-chip-studio-edit-column .matewa-chip-editor-helper,
        #matewa-chip-labels-section .matewa-chip-studio-card #matewa-manual-business-type-preview-wrap .matewa-chip-preview-final-actions,
        #matewa-chip-labels-section .matewa-chip-studio-card .matewa-chip-studio-edit-column .matewa-chip-studio-save-actions {
            width: 100% !important;
            max-width: 100% !important;
            box-sizing: border-box !important;
        }

        /* Keep helper/action boxes full-column width. The 292px hardlock applies
           only to chip grids/frames, not the boxes underneath. */
        #matewa-chip-labels-section .matewa-chip-studio-card .matewa-chip-studio-edit-column > .matewa-chip-editor-helper,
        #matewa-chip-labels-section .matewa-chip-studio-card .matewa-chip-studio-edit-column > .matewa-chip-studio-save-actions,
        #matewa-chip-labels-section .matewa-chip-studio-card #matewa-manual-business-type-preview-wrap > .matewa-chip-preview-subtle,
        #matewa-chip-labels-section .matewa-chip-studio-card #matewa-manual-business-type-preview-wrap > .matewa-chip-preview-final-actions {
            width: 100% !important;
            max-width: 100% !important;
            min-width: 0 !important;
            margin-left: 0 !important;
            margin-right: 0 !important;
            align-self: stretch !important;
            box-sizing: border-box !important;
        }

        #matewa-chip-labels-section .matewa-chip-studio-card .matewa-chip-studio-edit-column .matewa-chip-editor-helper {
            height: auto !important;
            min-height: 72px !important;
            max-height: none !important;
            overflow: visible !important;
            margin-top: 14px !important;
            border-radius: 14px !important;
            box-sizing: border-box !important;
        }

        #matewa-chip-labels-section .matewa-chip-studio-card #matewa-manual-business-type-preview-wrap .matewa-chip-preview-final-actions {
            padding-top: 53px !important;
            margin-top: 14px !important;
        }

        #matewa-chip-labels-section .matewa-chip-studio-card #matewa-manual-business-type-preview-wrap .matewa-chip-preview-final-actions .button-primary,
        #matewa-chip-labels-section .matewa-chip-studio-card .matewa-chip-studio-edit-column .matewa-chip-studio-save-actions .button-primary {
            width: 100% !important;
            min-height: 43px !important;
            justify-content: center !important;
            text-align: center !important;
        }



        #matewa-chip-labels-section .matewa-chip-studio-card #matewa-manual-business-type-preview-wrap .matewa-chip-preview-subtle,
        #matewa-chip-labels-section .matewa-chip-studio-card .matewa-chip-studio-edit-column .matewa-chip-editor-helper {
            height: auto !important;
            min-height: 72px !important;
            max-height: none !important;
            overflow: visible !important;
            white-space: normal !important;
            line-height: 1.38 !important;
        }

        #matewa-chip-labels-section .matewa-chip-studio-card #matewa-manual-business-type-preview-wrap,
        #matewa-chip-labels-section .matewa-chip-studio-card .matewa-chip-studio-edit-column {
            display: flex !important;
            flex-direction: column !important;
            flex: 1 1 auto !important;
        }

        #matewa-chip-labels-section .matewa-chip-studio-card #matewa-manual-business-type-preview-wrap .matewa-chip-preview-final-actions,
        #matewa-chip-labels-section .matewa-chip-studio-card .matewa-chip-studio-edit-column .matewa-chip-studio-save-actions {
            margin-top: auto !important;
        }

        @media (max-width: 860px) {
            #matewa-chip-labels-section .matewa-chip-studio-card .matewa-chip-studio-layout {
                grid-template-columns: 1fr !important;
            }

            #matewa-chip-labels-section .matewa-chip-studio-card #matewa-manual-business-type-preview-wrap .matewa-chip-preview-final-actions {
                padding-top: 0 !important;
            }
        }

        @media (max-width: 420px) {
            #matewa-chip-labels-section .matewa-chip-studio-card .matewa-chip-preview-heading,
            #matewa-chip-labels-section .matewa-chip-studio-card .matewa-chip-editor-subtle,
            #matewa-chip-labels-section .matewa-chip-studio-card #matewa-manual-business-type-preview-wrap .matewa-chip-editor-frame,
            #matewa-chip-labels-section .matewa-chip-studio-card .matewa-chip-studio-edit-column > .matewa-chip-editor-frame,
            #matewa-chip-labels-section .matewa-chip-studio-card #matewa-manual-chip-preview-grid,
            #matewa-chip-labels-section .matewa-chip-studio-card .matewa-chip-studio-edit-grid {
                width: 100% !important;
                max-width: 292px !important;
                min-width: 0 !important;
            }
        }
        </style>
        <div class="matewa-chip-studio-layout">
            <?php if ($show_vertical_selector) : ?>
                <section class="matewa-chip-studio-panel matewa-chip-studio-business-panel" aria-labelledby="matewa-chip-studio-business-title">
                    <div class="matewa-chip-studio-panel-header">
                        <span class="matewa-chip-studio-step-badge">1</span>
                        <div>
                            <h3 id="matewa-chip-studio-business-title">Choose business type</h3>
                            <p>Choose in order, then confirm to load the best starter buttons.</p>
                        </div>
                    </div>

                    <div class="matewa-selector-grid matewa-chip-studio-selector-grid">
                        <div class="matewa-selector-field">
                            <label for="matewa_vertical_category_selected">Category</label>
                            <select
                                id="matewa_vertical_category_selected"
                                name="matewa_vertical_category_selected"
                                data-saved-category="<?php echo esc_attr($saved_category_key); ?>"
                            >
                                <?php foreach ($vertical_selector_categories as $category_key => $category_data) : ?>
                                    <option
                                        value="<?php echo esc_attr($category_key); ?>"
                                        <?php selected($saved_category_key, $category_key); ?>
                                    >
                                        <?php echo esc_html(matewa_safe_scalar_text($category_data['label'] ?? '', 'General')); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="matewa-selector-field">
                            <label for="matewa_vertical_selected">Business type</label>
                            <select
                                id="matewa_vertical_selected"
                                name="matewa_vertical_selected"
                                data-saved-vertical="<?php echo esc_attr($active_vertical_key); ?>"
                            >
                                <?php foreach ($current_category_options as $vertical_key => $vertical_data) : ?>
                                    <option
                                        value="<?php echo esc_attr($vertical_key); ?>"
                                        <?php selected($active_vertical_key, $vertical_key); ?>
                                    >
                                        <?php echo esc_html(matewa_safe_scalar_text($vertical_data['display_label'] ?? '', matewa_format_vertical_key_label($vertical_key))); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                    </div>

                    <div
                        class="matewa-chip-preview-wrap matewa-chip-studio-default-preview"
                        id="matewa-manual-business-type-preview-wrap"
                        data-saved-vertical="<?php echo esc_attr($active_vertical_key); ?>"
                        data-previewed-vertical="<?php echo esc_attr($active_vertical_key); ?>"
                        data-previewed-label="<?php echo esc_attr($active_vertical_label); ?>"
                    >
                        <div class="matewa-chip-preview-heading">
                            Suggested buttons — <span id="matewa-manual-business-type-preview-label"><?php echo esc_html($active_vertical_label); ?></span>
                        </div>

                        <div class="matewa-chip-editor-frame">
                            <div
                                class="matewa-chip-editor-grid matewa-chip-studio-small-grid"
                                id="matewa-manual-chip-preview-grid"
                                data-loaded-vertical="<?php echo esc_attr($active_vertical_key); ?>"
                            >
                                <?php foreach ($preview_chip_items as $preview_item) : ?>
                                    <?php $preview_default_label = (string) ($preview_item['default_label'] ?? ''); ?>
                                    <div class="matewa-chip-editor-item">
                                        <div class="matewa-chip-editor-chip is-preview">
                                            <span><?php echo esc_html($preview_default_label); ?></span>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <div class="matewa-chip-preview-subtle matewa-chip-preview-action-note matewa-chip-editor-helper" id="matewa-manual-business-type-preview-note">
                            <strong>Choose business type</strong>
                            <ul>
                                <li>Choose a category.</li>
                                <li>Choose your business type.</li>
                                <li>Confirm to load the best starter buttons.</li>
                            </ul>
                        </div>

                        <div class="matewa-chip-editor-actions matewa-chip-preview-final-actions">
                            <div
                                class="matewa-industry-match-helper"
                                id="matewa-industry-match-helper"
                                role="status"
                                aria-live="polite"
                                hidden
                            ></div>

                            <button
                                type="submit"
                                class="button button-secondary matewa-chip-studio-wide-button matewa-business-confirm-button"
                                name="matewa_business_type_confirmed"
                                value="1"
                                data-matewa-confirm-action="business-type-save"
                                data-matewa-confirm-ready-label="Confirm business type"
                                data-matewa-confirm-saving-label="Saving…"
                                data-matewa-confirm-saved-label="Business confirmed"
                            >
                                Business confirmed
                            </button>
                        </div>
                    </div>
                </section>

                <script type="application/json" id="matewa-manual-vertical-selector-data">
                    <?php
                    $selector_payload = [];

                    foreach ($vertical_selector_categories as $category_key => $category_data) {
                        $safe_category_key = matewa_safe_key($category_key);

                        if ('' === $safe_category_key) {
                            continue;
                        }

                        $selector_payload[$safe_category_key] = [
                            'label'   => matewa_safe_scalar_text($category_data['label'] ?? '', 'General'),
                            'options' => [],
                        ];

                        $options = is_array($category_data['options'] ?? null) ? $category_data['options'] : [];

                        foreach ($options as $vertical_key => $vertical_data) {
                            $safe_vertical_key = matewa_safe_key($vertical_key);

                            if ('' === $safe_vertical_key) {
                                continue;
                            }

                            $display_label = matewa_safe_scalar_text(
                                $vertical_data['display_label'] ?? '',
                                matewa_format_vertical_key_label($safe_vertical_key)
                            );

                            $preview_labels = [];

                            foreach (matewa_get_chip_items_for_vertical_key($safe_vertical_key) as $preview_chip_item) {
                                $preview_label = matewa_safe_scalar_text($preview_chip_item['default_label'] ?? '');

                                if ('' !== $preview_label) {
                                    $preview_labels[] = $preview_label;
                                }
                            }

                            $selector_payload[$safe_category_key]['options'][] = [
                                'key'            => $safe_vertical_key,
                                'display_label'  => $display_label,
                                'preview_labels' => $preview_labels,
                            ];
                        }
                    }

                    echo wp_json_encode($selector_payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
                    ?>
                </script>

                <script>
                (function () {
                    const previewButton = document.getElementById('matewa-manual-preview-business-type');
                    const previewWrap = document.getElementById('matewa-manual-business-type-preview-wrap');
                    const previewGrid = document.getElementById('matewa-manual-chip-preview-grid');
                    const previewNote = document.getElementById('matewa-manual-business-type-preview-note');
                    const previewLabel = document.getElementById('matewa-manual-business-type-preview-label');
                    const verticalSelect = document.getElementById('matewa_vertical_selected');
                    const categorySelect = document.getElementById('matewa_vertical_category_selected');
                    const selectorDataEl = document.getElementById('matewa-manual-vertical-selector-data');

                    if (!previewWrap || !previewGrid || !verticalSelect || !categorySelect || !selectorDataEl) {
                        return;
                    }

                    const fixedPreviewNote = '<strong>Choose business type</strong><ul><li>Choose a category.</li><li>Choose your business type.</li><li>Confirm to load the best starter buttons.</li></ul>';

                    let selectorData = {};

                    try {
                        selectorData = JSON.parse(selectorDataEl.textContent || '{}');
                    } catch (e) {
                        selectorData = {};
                    }

                    function keepPreviewNoteFixed() {
                        if (previewNote) {
                            previewNote.innerHTML = fixedPreviewNote;
                        }
                    }

                    function getCategoryOptions(categoryKey) {
                        const categoryData = selectorData[String(categoryKey || '')] || {};
                        return Array.isArray(categoryData.options) ? categoryData.options : [];
                    }

                    function getAllOptions() {
                        const all = [];

                        Object.keys(selectorData || {}).forEach(function (categoryKey) {
                            const options = getCategoryOptions(categoryKey);

                            options.forEach(function (option) {
                                if (option && option.key) {
                                    all.push(option);
                                }
                            });
                        });

                        return all;
                    }

                    function getOptionByKey(verticalKey) {
                        const all = getAllOptions();

                        for (let i = 0; i < all.length; i++) {
                            if (String(all[i].key || '') === String(verticalKey || '')) {
                                return all[i];
                            }
                        }

                        return null;
                    }

                    function getSelectedOption() {
                        return getOptionByKey(String(verticalSelect.value || ''));
                    }

                    function getSelectedLabel() {
                        const selectedOption = getSelectedOption();

                        if (selectedOption && selectedOption.display_label) {
                            return String(selectedOption.display_label);
                        }

                        if (verticalSelect.options && verticalSelect.selectedIndex >= 0) {
                            return String(verticalSelect.options[verticalSelect.selectedIndex].text || '').trim();
                        }

                        return 'Selected business type';
                    }

                    function rebuildBusinessTypeOptionsForCategory() {
                        const selectedCategory = String(categorySelect.value || '');
                        const options = getCategoryOptions(selectedCategory);

                        /*
                         * Safety guard:
                         * If a category has no options, do not wipe the current Business Type dropdown.
                         */
                        if (!Array.isArray(options) || !options.length) {
                            keepPreviewNoteFixed();
                            return;
                        }

                        const previousValue = String(verticalSelect.value || '');

                        verticalSelect.innerHTML = '';

                        let matchedPrevious = false;

                        options.forEach(function (item) {
                            if (!item || !item.key) {
                                return;
                            }

                            const option = document.createElement('option');
                            option.value = String(item.key || '');
                            option.textContent = String(item.display_label || item.key || '');

                            if (previousValue && previousValue === option.value) {
                                option.selected = true;
                                matchedPrevious = true;
                            }

                            verticalSelect.appendChild(option);
                        });

                        if (!matchedPrevious && verticalSelect.options.length > 0) {
                            verticalSelect.selectedIndex = 0;
                        }

                        previewSelectedBusiness();
                        keepPreviewNoteFixed();
                    }

                    function renderPreviewLabels(labels) {
                        previewGrid.innerHTML = '';

                        if (!Array.isArray(labels) || !labels.length) {
                            const message = document.createElement('div');
                            message.className = 'matewa-chip-preview-subtle matewa-chip-preview-action-note';
                            message.textContent = 'No preview buttons are available for this business type yet.';
                            previewGrid.appendChild(message);
                            return;
                        }

                        labels.forEach(function (label) {
                            const item = document.createElement('div');
                            item.className = 'matewa-chip-editor-item';

                            const chip = document.createElement('div');
                            chip.className = 'matewa-chip-editor-chip is-preview';

                            const span = document.createElement('span');
                            span.textContent = String(label || '');

                            chip.appendChild(span);
                            item.appendChild(chip);
                            previewGrid.appendChild(item);
                        });
                    }

                    function previewSelectedBusiness() {
                        const selectedOption = getSelectedOption();

                        if (!selectedOption) {
                            keepPreviewNoteFixed();
                            return;
                        }

                        const selectedVertical = String(selectedOption.key || '');
                        const selectedLabel = selectedOption.display_label
                            ? String(selectedOption.display_label)
                            : getSelectedLabel();

                        const labels = Array.isArray(selectedOption.preview_labels)
                            ? selectedOption.preview_labels
                            : [];

                        previewWrap.setAttribute('data-previewed-vertical', selectedVertical);
                        previewWrap.setAttribute('data-previewed-label', selectedLabel);

                        if (previewLabel) {
                            previewLabel.textContent = selectedLabel;
                        }

                        previewGrid.setAttribute('data-loaded-vertical', selectedVertical);
                        renderPreviewLabels(labels);
                        keepPreviewNoteFixed();

                        previewWrap.style.display = '';
                    }

                    if (previewButton) {
                        previewButton.addEventListener('click', previewSelectedBusiness);
                    }

                    categorySelect.addEventListener('change', function () {
                        rebuildBusinessTypeOptionsForCategory();
                    });

                    verticalSelect.addEventListener('change', function () {
                        previewSelectedBusiness();
                        keepPreviewNoteFixed();
                    });

                    keepPreviewNoteFixed();
                    previewWrap.style.display = '';
                })();
                </script>
            <?php else : ?>
                <section class="matewa-chip-studio-panel matewa-chip-studio-business-panel" aria-labelledby="matewa-chip-studio-business-title">
                    <div class="matewa-chip-studio-panel-header">
                        <span class="matewa-chip-studio-step-badge">1</span>
                        <div>
                            <h3 id="matewa-chip-studio-business-title">Business type</h3>
                            <p>The active business type is <strong><?php echo esc_html($active_vertical_label); ?></strong>.</p>
                        </div>
                    </div>
                </section>
            <?php endif; ?>

            <section class="matewa-chip-studio-panel matewa-chip-studio-editor-panel" aria-labelledby="matewa-chip-studio-editor-title">
                <div class="matewa-chip-studio-panel-header">
                    <span class="matewa-chip-studio-step-badge">2</span>
                    <div>
                        <h3 id="matewa-chip-studio-editor-title">Edit buttons</h3>
                        <p>Edit the 6 quick-reply buttons that appear on your website.</p>
                    </div>
                </div>

                <div class="matewa-current-context" aria-label="Current visitor button context">
                    <div class="matewa-current-context-item">
                        <span>Current category</span>
                        <strong><?php echo esc_html(matewa_safe_scalar_text($vertical_selector_categories[$saved_category_key]['label'] ?? '', 'General')); ?></strong>
                    </div>
                    <div class="matewa-current-context-item">
                        <span>Current business type</span>
                        <strong><?php echo esc_html($active_vertical_label); ?></strong>
                    </div>
                </div>

                <div class="matewa-chip-editor-subtle">
                    Editable buttons — <strong><?php echo esc_html($active_vertical_label); ?></strong>
                </div>

                <input
                    type="hidden"
                    name="matewa_chip_editor_loaded_vertical"
                    value="<?php echo esc_attr($active_vertical_key); ?>"
                />

                <div class="matewa-chip-studio-edit-column">
                        <div class="matewa-chip-editor-frame">
                            <div class="matewa-chip-editor-grid matewa-chip-studio-edit-grid" aria-label="Editable visitor buttons">
                                <?php foreach ($chip_items as $item) : ?>
                                    <?php
                                    $intent_key    = (string) $item['intent_key'];
                                    $default_label = (string) $item['default_label'];
                                    $saved_label_candidate = isset($current_chip_overrides[$intent_key]) && '' !== trim((string) $current_chip_overrides[$intent_key])
                                        ? (string) $current_chip_overrides[$intent_key]
                                        : $default_label;
                                    $saved_label = matewa_admin_recover_clipped_chip_label($saved_label_candidate, $default_label);
                                    $position      = (int) $item['position'];
                                    $field_id      = 'matewa_chip_label_' . $position;
                                    $is_other      = !empty($item['is_other']);
                                    ?>
                                    <div class="matewa-chip-editor-item">
                                        <div
                                            class="matewa-chip-editor-chip"
                                            data-chip-wrap-for="<?php echo esc_attr($field_id); ?>"
                                        >
                                            <textarea
                                                id="<?php echo esc_attr($field_id); ?>"
                                                class="matewa-chip-label-input"
                                                name="matewa_chip_label_overrides[<?php echo esc_attr($active_vertical_key); ?>][<?php echo esc_attr($intent_key); ?>]"
                                                data-default-label="<?php echo esc_attr($default_label); ?>"
                                                data-is-other="<?php echo $is_other ? '1' : '0'; ?>"
                                                data-max-lines="<?php echo esc_attr(defined('MATEWA_CHIP_MAX_LINES') ? (int) MATEWA_CHIP_MAX_LINES : 2); ?>"
                                                data-max-line-chars="<?php echo esc_attr(defined('MATEWA_CHIP_MAX_LINE_CHARS') ? (int) MATEWA_CHIP_MAX_LINE_CHARS : 20); ?>"
                                                maxlength="<?php echo esc_attr(defined('MATEWA_CHIP_MAX_TOTAL_CHARS') ? (int) MATEWA_CHIP_MAX_TOTAL_CHARS : 34); ?>"
                                                rows="2"
                                                autocomplete="off"
                                                spellcheck="false"
                                            ><?php echo esc_textarea($saved_label); ?></textarea>
                                            <div class="matewa-chip-editor-measure" aria-hidden="true"></div>
                                        </div>
                                        <div
                                            class="matewa-chip-editor-note<?php echo $is_other ? ' is-helper' : ''; ?>"
                                            data-note-for="<?php echo esc_attr($field_id); ?>"
                                        ><?php echo $is_other ? esc_html('* Final button opens the notes box. Keep it as a custom request action.') : '&nbsp;'; ?></div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <!-- Keep this helper outside .matewa-chip-editor-frame.
                             The frame is deliberately locked to the frontend chip grid width;
                             helper/action boxes must keep the wider column dimensions. -->
                        <div class="matewa-chip-editor-helper">
                            <strong>Edit buttons</strong>
                            <ul>
                                <li>Edit any labels if needed.</li>
                                <li>Keep labels short — two lines max.</li>
                                <li>Save changes when the button says Ready to save.</li>
                                <li>If changes do not appear, clear your cache and try again.</li>
                                <li>Keep the final button for custom requests, such as “Something else”.</li>
                            </ul>
                        </div>

                        <div class="matewa-chip-editor-actions matewa-chip-studio-save-actions">
                            <button type="button" class="button button-secondary" id="matewa-reset-chip-labels-trigger">Revert to Defaults</button>
                            <button
                                type="submit"
                                name="submit"
                                id="submit"
                                class="button button-primary matewa-chip-save-confirm-button"
                                data-matewa-confirm-action="chip-save"
                                data-matewa-confirm-ready-label="Confirm and save buttons"
                                data-matewa-confirm-saving-label="Saving…"
                                data-matewa-confirm-saved-label="Visitor buttons saved"
                            >Visitor buttons saved</button>
                        </div>
                    </div>
            </section>

        </div>
    </div>
<?php elseif ('free' === $mode) : ?>
    <?php
    $matewa_is_agency_managed_client = function_exists('matewa_agency_client_entitlement_is_active') && matewa_agency_client_entitlement_is_active();
    $matewa_agency_client_entitlement = $matewa_is_agency_managed_client && defined('MATEWA_AGENCY_CLIENT_ENTITLEMENT_OPTION') ? get_option(MATEWA_AGENCY_CLIENT_ENTITLEMENT_OPTION, array()) : array();
    $matewa_agency_client_entitlement = is_array($matewa_agency_client_entitlement) ? $matewa_agency_client_entitlement : array();
    $matewa_agency_support_email = isset($matewa_agency_client_entitlement['agency_support_email']) ? sanitize_email((string) $matewa_agency_client_entitlement['agency_support_email']) : '';
    $matewa_agency_admin_email = isset($matewa_agency_client_entitlement['agency_admin_email']) ? sanitize_email((string) $matewa_agency_client_entitlement['agency_admin_email']) : '';
    ?>
    <div class="matewa-settings-card matewa-freemium-button-preview-card<?php echo $matewa_is_agency_managed_client ? ' is-agency-managed-client' : ''; ?>">
        <h2><?php echo $matewa_is_agency_managed_client ? esc_html('Agency-managed button set') : esc_html('Freemium Button Set'); ?></h2>
        <p class="description">
            <?php echo $matewa_is_agency_managed_client ? esc_html('This client site has been imported from an agency setup pack. Refresh the dashboard after import; if the live widget still shows Freemium, run another remote push with a fresh one-time setup key.') : esc_html('The free version includes the live button layout shown below so the admin preview matches the current widget presentation more closely.'); ?>
        </p>

        <div class="matewa-chip-grid matewa-freemium-chip-grid">
            <?php foreach ($free_chips as $chip) : ?>
                <div class="matewa-chip-editor-chip is-preview matewa-freemium-preview-chip">
                    <span><?php echo esc_html($chip); ?></span>
                </div>
            <?php endforeach; ?>
        </div>

        <?php if ($matewa_is_agency_managed_client && ('' !== $matewa_agency_support_email || '' !== $matewa_agency_admin_email)) : ?>
            <p class="matewa-note matewa-agency-client-support-note">
                <?php echo esc_html('Agency support: ' . ('' !== $matewa_agency_support_email ? $matewa_agency_support_email : $matewa_agency_admin_email)); ?>
            </p>
        <?php else : ?>
            <p class="matewa-note">
                This section is a visual preview only. It does not change the frontend runtime by itself.
            </p>
        <?php endif; ?>
    </div>
<?php endif; ?>