<?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: 42px !important;
            margin-bottom: 6px !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 22px !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;
        }


        /* FINAL Visitor Buttons row alignment:
           Keep both card headings fixed, then pull the left selector content upward.
           Category on the left aligns with Current category on the right. */
        @media (min-width: 901px) {
            #matewa-chip-labels-section .matewa-chip-studio-card .matewa-chip-studio-selector-panel .matewa-smart-vertical-search {
                margin-top: -29px !important;
            }
        }

        #matewa-chip-labels-section .matewa-smart-vertical-search {
            margin: 0 0 4px !important;
            position: relative !important;
        }
        #matewa-chip-labels-section .matewa-smart-vertical-search > label {
            display: block !important;
            margin: 0 0 6px !important;
            font-weight: 700 !important;
        }
        #matewa-chip-labels-section .matewa-smart-vertical-search-box {
            display: flex !important;
            align-items: center !important;
            gap: 8px !important;
            min-height: 42px !important;
            padding: 0 11px !important;
            border: 1px solid #cbd5e1 !important;
            border-radius: 10px !important;
            background: #fff !important;
            box-sizing: border-box !important;
        }
        #matewa-chip-labels-section .matewa-smart-vertical-search-box:focus-within {
            border-color: #057a29 !important;
            box-shadow: 0 0 0 1px #057a29 !important;
        }
        #matewa-chip-labels-section .matewa-smart-vertical-search-box input {
            width: 100% !important;
            min-height: 40px !important;
            padding: 0 !important;
            border: 0 !important;
            outline: 0 !important;
            box-shadow: none !important;
            background: transparent !important;
        }
        #matewa-chip-labels-section .matewa-smart-vertical-results {
            position: absolute !important;
            z-index: 1000 !important;
            top: 70px !important;
            left: 0 !important;
            right: 0 !important;
            max-height: 280px !important;
            overflow-y: auto !important;
            padding: 6px !important;
            border: 1px solid #dbe3ea !important;
            border-radius: 12px !important;
            background: #fff !important;
            box-shadow: 0 14px 32px rgba(15, 23, 42, 0.14) !important;
        }
        #matewa-chip-labels-section .matewa-smart-vertical-result {
            display: flex !important;
            width: 100% !important;
            justify-content: space-between !important;
            gap: 12px !important;
            padding: 9px 10px !important;
            border: 0 !important;
            border-radius: 8px !important;
            background: transparent !important;
            text-align: left !important;
            cursor: pointer !important;
        }
        #matewa-chip-labels-section .matewa-smart-vertical-result:hover,
        #matewa-chip-labels-section .matewa-smart-vertical-result:focus {
            background: #f0fdf4 !important;
            outline: none !important;
        }
        #matewa-chip-labels-section .matewa-smart-vertical-result strong { color: #14532d !important; }
        #matewa-chip-labels-section .matewa-smart-vertical-result small { color: #64748b !important; }

        #matewa-chip-labels-section .matewa-free-vertical-catalogue {
            display: grid;
            gap: 8px;
            margin-top: 14px;
        }
        #matewa-chip-labels-section .matewa-free-vertical-category {
            border: 1px solid #e2e8f0;
            border-radius: 10px;
            background: #fff;
            overflow: hidden;
        }
        #matewa-chip-labels-section .matewa-free-vertical-category summary {
            cursor: pointer;
            padding: 10px 12px;
            font-weight: 700;
            color: #0f172a;
        }
        #matewa-chip-labels-section .matewa-free-vertical-category-list {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 7px 10px;
            padding: 0 12px 12px;
        }
        #matewa-chip-labels-section .matewa-free-vertical-preview-item {
            display: block;
            padding: 7px 9px;
            border-radius: 8px;
            background: #f8fafc;
            color: #475569;
            font-size: 13px;
        }
        #matewa-chip-labels-section .matewa-smart-vertical-result.is-preview-only {
            cursor: default;
        }
        @media (max-width: 720px) {
            #matewa-chip-labels-section .matewa-free-vertical-category-list {
                grid-template-columns: 1fr;
            }
        }

        #matewa-chip-labels-section .matewa-smart-vertical-help {
            margin: 6px 0 0 !important;
            color: #64748b !important;
            font-size: 12px !important;
            line-height: 1.4 !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;
            }
        }
        
        #matewa-chip-labels-section .matewa-free-catalogue-status {
            display: flex;
            flex-wrap: wrap;
            gap: 5px;
            align-items: center;
            margin: 12px 0 10px;
            padding: 9px 11px;
            border: 1px solid #dbe7df;
            border-radius: 9px;
            background: #f7fbf8;
            color: #475569;
            font-size: 12px;
        }
        #matewa-chip-labels-section .matewa-free-catalogue-status strong {
            color: #166534;
        }
        #matewa-chip-labels-section .matewa-free-catalogue-status span {
            color: #64748b;
        }
        #matewa-chip-labels-section .matewa-free-preview-smart-search {
            margin: 0 0 13px;
        }
        #matewa-chip-labels-section .matewa-free-preview-smart-search .matewa-smart-vertical-results {
            max-height: 320px;
            overflow-y: auto;
        }

</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-smart-vertical-search" data-matewa-smart-vertical-search-wrap>
                        <label for="matewa-vertical-smart-search">Find your business type</label>
                        <div class="matewa-smart-vertical-search-box">
                            <span class="dashicons dashicons-search" aria-hidden="true"></span>
                            <input
                                type="search"
                                id="matewa-vertical-smart-search"
                                autocomplete="off"
                                placeholder="Start typing, e.g. pool, boiler, yoga, haulage…"
                                aria-autocomplete="list"
                                aria-controls="matewa-vertical-smart-results"
                            />
                        </div>
                        <div id="matewa-vertical-smart-results" class="matewa-smart-vertical-results" role="listbox" hidden></div>
                        <p class="matewa-smart-vertical-help">Smart search finds close matches. Or browse the alphabetical category and business-type lists below.</p>
                    </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;
                                }
                            }

                            $search_terms = is_array($vertical_definitions[$safe_vertical_key]['search_terms'] ?? null)
                                ? array_values(array_filter(array_map('matewa_safe_scalar_text', $vertical_definitions[$safe_vertical_key]['search_terms'])))
                                : [];

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

                    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 types</h3>
                            <p>Browse the complete catalogue. Upgrade to Trial or Pro to select and use a business type.</p>
                        </div>
                    </div>

                    <div class="matewa-smart-vertical-search" data-matewa-free-vertical-search-wrap>
                        <label for="matewa-free-vertical-smart-search">Find your business type</label>
                        <div class="matewa-smart-vertical-search-box">
                            <span class="dashicons dashicons-search" aria-hidden="true"></span>
                            <input
                                type="search"
                                id="matewa-free-vertical-smart-search"
                                autocomplete="off"
                                placeholder="Start typing, e.g. pool, boiler, yoga, haulage…"
                                aria-autocomplete="list"
                                aria-controls="matewa-free-vertical-smart-results"
                            />
                        </div>
                        <div id="matewa-free-vertical-smart-results" class="matewa-smart-vertical-results" role="listbox" hidden></div>
                        <p class="matewa-smart-vertical-help">Preview only on Free. Search or browse the alphabetical catalogue below.</p>
                    </div>

                    <div class="matewa-free-vertical-catalogue" id="matewa-free-vertical-catalogue">
                        <?php foreach ($vertical_selector_categories as $category_key => $category_data) : ?>
                            <?php
                            $free_options = is_array($category_data['options'] ?? null) ? $category_data['options'] : [];
                            if (empty($free_options)) {
                                continue;
                            }
                            ?>
                            <details class="matewa-free-vertical-category">
                                <summary><?php echo esc_html(matewa_safe_scalar_text($category_data['label'] ?? '', 'General')); ?></summary>
                                <div class="matewa-free-vertical-category-list">
                                    <?php foreach ($free_options as $vertical_key => $vertical_data) : ?>
                                        <span class="matewa-free-vertical-preview-item">
                                            <?php echo esc_html(matewa_safe_scalar_text($vertical_data['display_label'] ?? '', matewa_format_vertical_key_label($vertical_key))); ?>
                                        </span>
                                    <?php endforeach; ?>
                                </div>
                            </details>
                        <?php endforeach; ?>
                    </div>

                    <script type="application/json" id="matewa-free-vertical-selector-data">
                    <?php
                    $free_search_payload = [];
                    foreach ($vertical_selector_categories as $category_key => $category_data) {
                        $category_label = matewa_safe_scalar_text($category_data['label'] ?? '', 'General');
                        $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;
                            }

                            $search_terms = is_array($vertical_definitions[$safe_vertical_key]['search_terms'] ?? null)
                                ? array_values(array_filter(array_map('matewa_safe_scalar_text', $vertical_definitions[$safe_vertical_key]['search_terms'])))
                                : [];

                            $free_search_payload[] = [
                                'key'          => $safe_vertical_key,
                                'label'        => matewa_safe_scalar_text($vertical_data['display_label'] ?? '', matewa_format_vertical_key_label($safe_vertical_key)),
                                'category'     => $category_label,
                                'search_terms' => $search_terms,
                            ];
                        }
                    }
                    echo wp_json_encode($free_search_payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
                    ?>
                    </script>

                    <script>
                    (function () {
                        const input = document.getElementById('matewa-free-vertical-smart-search');
                        const results = document.getElementById('matewa-free-vertical-smart-results');
                        const dataEl = document.getElementById('matewa-free-vertical-selector-data');
                        if (!input || !results || !dataEl) return;

                        let items = [];
                        try { items = JSON.parse(dataEl.textContent || '[]'); } catch (e) { items = []; }

                        function normalise(value) {
                            return String(value || '').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
                        }

                        function score(item, query) {
                            const label = normalise(item.label);
                            const category = normalise(item.category);
                            const terms = normalise((item.search_terms || []).join(' '));
                            const haystack = label + ' ' + category + ' ' + terms;

                            if (label === query) return 1000;
                            if (label.startsWith(query)) return 800;
                            if (label.includes(query)) return 650;
                            if (terms.includes(query)) return 500;
                            if (category.includes(query)) return 350;

                            const words = query.split(/\s+/).filter(Boolean);
                            let matched = 0;
                            words.forEach(function (word) {
                                if (haystack.includes(word)) matched += 1;
                            });
                            return matched ? (matched / Math.max(words.length, 1)) * 250 : 0;
                        }

                        function render() {
                            const query = normalise(input.value);
                            results.innerHTML = '';

                            if (!query) {
                                results.hidden = true;
                                return;
                            }

                            const matches = items
                                .map(function (item) { return { item: item, score: score(item, query) }; })
                                .filter(function (row) { return row.score > 0; })
                                .sort(function (a, b) {
                                    return b.score - a.score || String(a.item.label).localeCompare(String(b.item.label));
                                })
                                .slice(0, 10);

                            if (!matches.length) {
                                const empty = document.createElement('div');
                                empty.className = 'matewa-smart-vertical-result';
                                empty.setAttribute('aria-disabled', 'true');
                                empty.innerHTML = '<strong>No close match found</strong><small>Browse the alphabetical catalogue below.</small>';
                                results.appendChild(empty);
                                results.hidden = false;
                                return;
                            }

                            matches.forEach(function (row) {
                                const result = document.createElement('div');
                                result.className = 'matewa-smart-vertical-result is-preview-only';
                                result.setAttribute('aria-disabled', 'true');

                                const strong = document.createElement('strong');
                                strong.textContent = row.item.label || '';
                                const small = document.createElement('small');
                                small.textContent = (row.item.category || '') + ' · Preview only on Free';

                                result.appendChild(strong);
                                result.appendChild(small);
                                results.appendChild(result);
                            });

                            results.hidden = false;
                        }

                        input.addEventListener('input', render);
                        input.addEventListener('search', render);
                    })();
                    </script>
                </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 (in_array($mode, ['free', 'trial_expired'], true)) : ?>
    <?php
    $matewa_is_agency_managed_client = function_exists('matewa_agency_client_entitlement_is_active') && matewa_agency_client_entitlement_is_active();
    ?>
    <div class="matewa-settings-card matewa-freemium-button-preview-card<?php echo $matewa_is_agency_managed_client ? ' is-agency-managed-client' : ''; ?>">
        <div class="matewa-free-buttons-heading-row">
            <div>
                <h2><?php echo $matewa_is_agency_managed_client ? esc_html('Agency-managed button set') : esc_html('Free visitor buttons'); ?></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 the Free button set, run another remote push with a fresh one-time setup key.') : esc_html('Free uses four fixed visitor buttons in a clean 2 × 2 layout. These labels cannot be edited.'); ?>
                </p>
            </div>
            <?php if (!$matewa_is_agency_managed_client) : ?>
                <span class="matewa-free-plan-badge">FREE</span>
            <?php endif; ?>
        </div>

        <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) : ?>
            <?php
            $matewa_free_preview_categories = $vertical_selector_categories;
            $matewa_free_preview_payload = [];

            foreach ($matewa_free_preview_categories as $category_key => $category_data) {
                $safe_category_key = matewa_safe_key($category_key);
                if ('' === $safe_category_key) {
                    continue;
                }

                $matewa_free_preview_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;
                    }

                    $vertical_config = is_array($vertical_definitions[$safe_vertical_key] ?? null)
                        ? $vertical_definitions[$safe_vertical_key]
                        : [];

                    $matewa_free_preview_payload[$safe_category_key]['options'][] = [
                        'key'            => $safe_vertical_key,
                        'display_label'  => matewa_safe_scalar_text(
                            $vertical_data['display_label'] ?? '',
                            matewa_format_vertical_key_label($safe_vertical_key)
                        ),
                        'preview_labels' => matewa_admin_preview_labels_from_vertical_config($vertical_config),
                        'search_terms'   => is_array($vertical_config['search_terms'] ?? null)
                            ? array_values(array_filter(array_map('matewa_safe_scalar_text', $vertical_config['search_terms'])))
                            : [],
                    ];
                }
            }

            $matewa_free_preview_category_keys = array_keys($matewa_free_preview_payload);
            $matewa_free_preview_category = !empty($matewa_free_preview_category_keys)
                ? (string) $matewa_free_preview_category_keys[0]
                : '';
            $matewa_free_preview_options = isset($matewa_free_preview_payload[$matewa_free_preview_category]['options'])
                ? (array) $matewa_free_preview_payload[$matewa_free_preview_category]['options']
                : [];

            $matewa_free_preview_vertical_count = 0;
            foreach ($matewa_free_preview_payload as $matewa_preview_category_row) {
                $matewa_preview_category_options = is_array($matewa_preview_category_row['options'] ?? null)
                    ? $matewa_preview_category_row['options']
                    : [];
                $matewa_free_preview_vertical_count += count($matewa_preview_category_options);
            }
            $matewa_free_preview_category_count = count($matewa_free_preview_payload);
            ?>
            <style id="matewa-free-catalogue-search-style">
                #matewa-chip-labels-section .matewa-free-catalog-browser .matewa-free-catalogue-status {
                    display: flex;
                    flex-wrap: wrap;
                    align-items: center;
                    gap: 6px;
                    margin: 14px 0 12px;
                    padding: 10px 12px;
                    border: 1px solid #d9e7dd;
                    border-radius: 10px;
                    background: #f7fbf8;
                    color: #475569;
                    font-size: 12px;
                    line-height: 1.4;
                }
                #matewa-chip-labels-section .matewa-free-catalog-browser .matewa-free-catalogue-status strong {
                    color: #166534;
                    font-weight: 800;
                }
                #matewa-chip-labels-section .matewa-free-catalog-browser .matewa-free-preview-smart-search {
                    position: relative;
                    margin: 0 0 16px;
                }
                #matewa-chip-labels-section .matewa-free-catalog-browser .matewa-free-preview-smart-search > label {
                    display: block;
                    margin: 0 0 7px;
                    color: #172033;
                    font-size: 12px;
                    font-weight: 700;
                }
                #matewa-chip-labels-section .matewa-free-catalog-browser .matewa-smart-vertical-search-box {
                    display: flex;
                    align-items: center;
                    gap: 9px;
                    width: 100%;
                    min-height: 44px;
                    padding: 0 13px;
                    border: 1px solid #d7dee8;
                    border-radius: 12px;
                    background: #fff;
                    box-sizing: border-box;
                    transition: border-color .15s ease, box-shadow .15s ease;
                }
                #matewa-chip-labels-section .matewa-free-catalog-browser .matewa-smart-vertical-search-box:focus-within {
                    border-color: #2f974b;
                    box-shadow: 0 0 0 3px rgba(47,151,75,.10);
                }
                #matewa-chip-labels-section .matewa-free-catalog-browser .matewa-smart-vertical-search-box .dashicons {
                    width: 18px;
                    height: 18px;
                    color: #567063;
                    font-size: 18px;
                    line-height: 18px;
                    flex: 0 0 auto;
                }
                #matewa-chip-labels-section .matewa-free-catalog-browser .matewa-smart-vertical-search-box input {
                    width: 100%;
                    min-width: 0;
                    min-height: 42px;
                    margin: 0;
                    padding: 0;
                    border: 0;
                    border-radius: 0;
                    outline: 0;
                    box-shadow: none;
                    background: transparent;
                    color: #172033;
                    font-size: 14px;
                }
                #matewa-chip-labels-section .matewa-free-catalog-browser .matewa-smart-vertical-search-box input::placeholder {
                    color: #8a96a5;
                }
                #matewa-chip-labels-section .matewa-free-catalog-browser .matewa-smart-vertical-results {
                    position: absolute;
                    z-index: 50;
                    top: calc(100% - 29px);
                    left: 0;
                    right: 0;
                    display: block;
                    max-height: 330px;
                    overflow-y: auto;
                    padding: 6px;
                    border: 1px solid #dbe3ea;
                    border-radius: 12px;
                    background: #fff;
                    box-shadow: 0 16px 36px rgba(22, 34, 51, .14);
                    box-sizing: border-box;
                }
                #matewa-chip-labels-section .matewa-free-catalog-browser .matewa-smart-vertical-results[hidden] {
                    display: none !important;
                }
                #matewa-chip-labels-section .matewa-free-catalog-browser .matewa-smart-vertical-result {
                    display: grid;
                    grid-template-columns: minmax(0, 1fr) auto;
                    align-items: center;
                    gap: 12px;
                    width: 100%;
                    margin: 0;
                    padding: 10px 11px;
                    border: 0;
                    border-radius: 9px;
                    background: transparent;
                    color: #172033;
                    text-align: left;
                    cursor: pointer;
                    box-sizing: border-box;
                }
                #matewa-chip-labels-section .matewa-free-catalog-browser .matewa-smart-vertical-result:hover,
                #matewa-chip-labels-section .matewa-free-catalog-browser .matewa-smart-vertical-result:focus,
                #matewa-chip-labels-section .matewa-free-catalog-browser .matewa-smart-vertical-result.is-active {
                    background: #f1f8f3;
                    outline: none;
                }
                #matewa-chip-labels-section .matewa-free-catalog-browser .matewa-smart-vertical-result strong {
                    min-width: 0;
                    color: #176b32;
                    font-size: 13px;
                    font-weight: 700;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                }
                #matewa-chip-labels-section .matewa-free-catalog-browser .matewa-smart-vertical-result small {
                    color: #748091;
                    font-size: 11px;
                    white-space: nowrap;
                }
                #matewa-chip-labels-section .matewa-free-catalog-browser .matewa-smart-vertical-help {
                    margin: 7px 0 0;
                    color: #667085;
                    font-size: 11px;
                    line-height: 1.45;
                }
                @media (max-width: 700px) {
                    #matewa-chip-labels-section .matewa-free-catalog-browser .matewa-smart-vertical-result {
                        grid-template-columns: 1fr;
                        gap: 3px;
                    }
                    #matewa-chip-labels-section .matewa-free-catalog-browser .matewa-smart-vertical-result small {
                        white-space: normal;
                    }
                }
            </style>
            <section class="matewa-locked-vertical-library matewa-free-catalog-browser" aria-label="Pro business-specific setups preview">
                <div class="matewa-locked-vertical-library-head">
                    <div>
                        <div class="matewa-locked-vertical-eyebrow">PRO BUSINESS SETUPS</div>
                        <h3>Browse every business type</h3>
                        <p>Free keeps the fixed 2 × 2 buttons. You can browse the same business catalogue as Pro and preview what each setup unlocks.</p>
                        <p class="matewa-locked-vertical-helper"><strong>Pro:</strong> the suggested visitor buttons are fully editable within the character limit. <strong>Something else</strong> stays fixed and cannot be renamed.</p>
                    </div>
                    <span class="matewa-pro-plan-badge">PRO</span>
                </div>
                <div class="matewa-free-catalogue-status" role="status">
                    <strong><?php echo esc_html(number_format_i18n($matewa_free_preview_vertical_count)); ?> business types</strong>
                    across <?php echo esc_html(number_format_i18n($matewa_free_preview_category_count)); ?> categories.
                    <span>Complete remote catalogue · Preview only on Free.</span>
                    <?php if (!empty($catalog['version'])) : ?>
                        <span>Catalogue: <?php echo esc_html((string) $catalog['version']); ?></span>
                    <?php endif; ?>
                    <?php if ($matewa_high_value_count > 0) : ?>
                        <span>Remote expansion: <?php echo esc_html(number_format_i18n($matewa_high_value_count)); ?> loaded.</span>
                    <?php endif; ?>
                </div>

                <div class="matewa-smart-vertical-search matewa-free-preview-smart-search" data-matewa-free-preview-smart-search>
                    <label for="matewa-free-preview-smart-search-input">Find a business type</label>
                    <div class="matewa-smart-vertical-search-box">
                        <span class="dashicons dashicons-search" aria-hidden="true"></span>
                        <input
                            type="search"
                            id="matewa-free-preview-smart-search-input"
                            autocomplete="off"
                            placeholder="Search pool, boiler, yoga, haulage, loft…"
                            aria-autocomplete="list"
                            aria-controls="matewa-free-preview-smart-search-results"
                        />
                    </div>
                    <div
                        id="matewa-free-preview-smart-search-results"
                        class="matewa-smart-vertical-results"
                        role="listbox"
                        hidden
                    ></div>
                    <p class="matewa-smart-vertical-help">
                        Search the full catalogue or browse A–Z below. Free can preview every setup; activation remains locked.
                    </p>
                </div>

                <div class="matewa-selector-grid matewa-chip-studio-selector-grid matewa-free-preview-selector-grid">
                    <div class="matewa-selector-field">
                        <label for="matewa_free_preview_category">Category</label>
                        <select id="matewa_free_preview_category">
                            <?php foreach ($matewa_free_preview_payload as $category_key => $category_data) : ?>
                                <option value="<?php echo esc_attr($category_key); ?>">
                                    <?php echo esc_html((string) ($category_data['label'] ?? matewa_format_vertical_key_label($category_key))); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="matewa-selector-field">
                        <label for="matewa_free_preview_vertical">Business type <span class="matewa-vertical-lock">PRO</span></label>
                        <select id="matewa_free_preview_vertical">
                            <?php foreach ($matewa_free_preview_options as $option) : ?>
                                <option value="<?php echo esc_attr((string) ($option['key'] ?? '')); ?>">
                                    <?php echo esc_html((string) ($option['display_label'] ?? 'Business')); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <div class="matewa-chip-preview-wrap matewa-chip-studio-default-preview matewa-free-pro-preview">
                    <div class="matewa-chip-preview-heading">
                        Pro buttons — <span id="matewa-free-preview-business-label">Choose a business type</span>
                    </div>
                    <div class="matewa-chip-editor-frame">
                        <div class="matewa-chip-editor-grid matewa-chip-studio-small-grid" id="matewa-free-preview-chip-grid"></div>
                    </div>
                    <div class="matewa-chip-preview-subtle matewa-chip-preview-action-note">
                        <strong>Preview only.</strong> Activating a business-specific setup requires Pro. In Pro, the suggested buttons can be edited within the character limit; <strong>Something else</strong> remains fixed. Your Free widget stays on the four fixed buttons above.
                    </div>
                </div>

                <script type="application/json" id="matewa-free-preview-catalog-data"><?php
                    echo wp_json_encode($matewa_free_preview_payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
                ?></script>
                <script>
                (function () {
                    const category = document.getElementById('matewa_free_preview_category');
                    const vertical = document.getElementById('matewa_free_preview_vertical');
                    const dataEl = document.getElementById('matewa-free-preview-catalog-data');
                    const grid = document.getElementById('matewa-free-preview-chip-grid');
                    const label = document.getElementById('matewa-free-preview-business-label');
                    const searchInput = document.getElementById('matewa-free-preview-smart-search-input');
                    const searchResults = document.getElementById('matewa-free-preview-smart-search-results');

                    if (!category || !vertical || !dataEl || !grid || !label) {
                        return;
                    }

                    let data = {};
                    try {
                        data = JSON.parse(dataEl.textContent || '{}');
                    } catch (e) {
                        data = {};
                    }

                    function optionsForCategory(categoryKey) {
                        const row = data[String(categoryKey || category.value || '')] || {};
                        return Array.isArray(row.options) ? row.options : [];
                    }

                    function allOptions() {
                        const rows = [];
                        Object.keys(data || {}).forEach(function (categoryKey) {
                            const categoryRow = data[categoryKey] || {};
                            const categoryLabel = String(categoryRow.label || categoryKey || '');
                            const options = Array.isArray(categoryRow.options) ? categoryRow.options : [];
                            options.forEach(function (item) {
                                rows.push({
                                    categoryKey: categoryKey,
                                    categoryLabel: categoryLabel,
                                    key: String(item.key || ''),
                                    display_label: String(item.display_label || item.key || 'Business'),
                                    preview_labels: Array.isArray(item.preview_labels) ? item.preview_labels : [],
                                    search_terms: Array.isArray(item.search_terms) ? item.search_terms : []
                                });
                            });
                        });
                        return rows;
                    }

                    const flatOptions = allOptions();
                    let activeSearchIndex = -1;

                    function resultButtons() {
                        if (!searchResults) return [];
                        return Array.from(searchResults.querySelectorAll('.matewa-smart-vertical-result[role="option"]'));
                    }

                    function setActiveSearchIndex(nextIndex) {
                        const buttons = resultButtons();

                        if (!buttons.length) {
                            activeSearchIndex = -1;
                            return;
                        }

                        if (nextIndex < 0) nextIndex = buttons.length - 1;
                        if (nextIndex >= buttons.length) nextIndex = 0;

                        activeSearchIndex = nextIndex;

                        buttons.forEach(function (button, index) {
                            const active = index === activeSearchIndex;
                            button.classList.toggle('is-active', active);
                            button.setAttribute('aria-selected', active ? 'true' : 'false');

                            if (active) {
                                button.scrollIntoView({ block: 'nearest' });
                            }
                        });
                    }

                    function rebuildVerticals(preferredKey) {
                        const options = optionsForCategory(category.value);
                        vertical.innerHTML = '';

                        options.forEach(function (item) {
                            const option = document.createElement('option');
                            option.value = String(item.key || '');
                            option.textContent = String(item.display_label || item.key || 'Business');
                            vertical.appendChild(option);
                        });

                        if (preferredKey) {
                            vertical.value = String(preferredKey);
                        }

                        renderPreview();
                    }

                    function renderPreview() {
                        const options = optionsForCategory(category.value);
                        const current = options.find(function (item) {
                            return String(item.key || '') === String(vertical.value || '');
                        }) || options[0] || null;

                        grid.innerHTML = '';

                        if (!current) {
                            label.textContent = 'No preview available';
                            return;
                        }

                        label.textContent = String(current.display_label || current.key || 'Business');

                        const labels = Array.isArray(current.preview_labels) ? current.preview_labels : [];
                        labels.forEach(function (text) {
                            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(text || '');

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

                    function normalise(value) {
                        return String(value || '')
                            .toLowerCase()
                            .replace(/[^a-z0-9]+/g, ' ')
                            .replace(/\s+/g, ' ')
                            .trim();
                    }

                    function searchScore(item, query) {
                        const labelText = normalise(item.display_label);
                        const categoryText = normalise(item.categoryLabel);
                        const termsText = normalise((item.search_terms || []).join(' '));
                        const haystack = labelText + ' ' + categoryText + ' ' + termsText;

                        if (labelText === query) return 1000;
                        if (labelText.startsWith(query)) return 850;
                        if (labelText.includes(query)) return 700;
                        if (termsText.includes(query)) return 550;
                        if (categoryText.includes(query)) return 400;

                        const words = query.split(' ').filter(Boolean);
                        let found = 0;
                        words.forEach(function (word) {
                            if (haystack.includes(word)) found += 1;
                        });

                        return found ? Math.round((found / Math.max(words.length, 1)) * 300) : 0;
                    }

                    function choosePreview(item) {
                        if (!item) return;
                        category.value = String(item.categoryKey || '');
                        rebuildVerticals(String(item.key || ''));
                        if (searchResults) searchResults.hidden = true;
                    }

                    function renderSearch() {
                        if (!searchInput || !searchResults) return;

                        activeSearchIndex = -1;
                        const query = normalise(searchInput.value);
                        searchResults.innerHTML = '';

                        if (!query) {
                            searchResults.hidden = true;
                            return;
                        }

                        const matches = flatOptions
                            .map(function (item) {
                                return { item: item, score: searchScore(item, query) };
                            })
                            .filter(function (row) { return row.score > 0; })
                            .sort(function (a, b) {
                                return b.score - a.score
                                    || String(a.item.display_label).localeCompare(String(b.item.display_label));
                            })
                            .slice(0, 12);

                        if (!matches.length) {
                            const empty = document.createElement('div');
                            empty.className = 'matewa-smart-vertical-result';
                            empty.setAttribute('aria-disabled', 'true');

                            const strong = document.createElement('strong');
                            strong.textContent = 'No close match found';
                            const small = document.createElement('small');
                            small.textContent = 'Browse the alphabetical category list below.';

                            empty.appendChild(strong);
                            empty.appendChild(small);
                            searchResults.appendChild(empty);
                            searchResults.hidden = false;
                            return;
                        }

                        matches.forEach(function (row) {
                            const button = document.createElement('button');
                            button.type = 'button';
                            button.className = 'matewa-smart-vertical-result';
                            button.setAttribute('role', 'option');

                            const strong = document.createElement('strong');
                            strong.textContent = row.item.display_label;
                            const small = document.createElement('small');
                            small.textContent = row.item.categoryLabel + ' · Preview only';

                            button.appendChild(strong);
                            button.appendChild(small);
                            button.addEventListener('click', function () {
                                choosePreview(row.item);
                            });

                            searchResults.appendChild(button);
                        });

                        searchResults.hidden = false;
                    }

                    category.addEventListener('change', function () {
                        rebuildVerticals('');
                    });
                    vertical.addEventListener('change', renderPreview);

                    if (searchInput && searchResults) {
                        searchInput.addEventListener('input', renderSearch);
                        searchInput.addEventListener('search', renderSearch);

                        searchInput.addEventListener('keydown', function (event) {
                            if (event.key === 'ArrowDown') {
                                event.preventDefault();

                                if (searchResults.hidden) {
                                    renderSearch();
                                }

                                setActiveSearchIndex(activeSearchIndex + 1);
                                return;
                            }

                            if (event.key === 'ArrowUp') {
                                event.preventDefault();

                                if (searchResults.hidden) {
                                    renderSearch();
                                }

                                setActiveSearchIndex(activeSearchIndex - 1);
                                return;
                            }

                            if (event.key === 'Enter') {
                                const buttons = resultButtons();

                                if (!searchResults.hidden && activeSearchIndex >= 0 && buttons[activeSearchIndex]) {
                                    event.preventDefault();
                                    buttons[activeSearchIndex].click();
                                }
                                return;
                            }

                            if (event.key === 'Escape') {
                                if (!searchResults.hidden) {
                                    event.preventDefault();
                                    searchResults.hidden = true;
                                    activeSearchIndex = -1;
                                }
                            }
                        });

                        document.addEventListener('click', function (event) {
                            if (!event.target.closest('[data-matewa-free-preview-smart-search]')) {
                                searchResults.hidden = true;
                            }
                        });
                    }

                    rebuildVerticals('');
                })();
                </script>
            </section>
        <?php endif; ?>

        <?php if ($matewa_is_agency_managed_client) : ?>
            <p class="matewa-note matewa-agency-client-support-note">
                Agency-managed setup active.
            </p>
        <?php else : ?>
            <p class="matewa-note">
                These four Free visitor buttons are fixed and cannot be edited. Pro business setups are preview-only until Pro is activated.
            </p>
        <?php endif; ?>
    </div>
<?php endif; ?>