<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly


if(!function_exists("fast_fuzzy_search_register_settings_framework")) {
    /**
     * Register a settings page with section-grouped fields.
     *
     * Each field can carry:
     *  - id, label, type, default, options, description, placeholder
     *  - section  : slug identifying which card the field belongs to
     *  - pro      : true to render the Pro badge
     *  - order    : numeric ordering inside the section
     *
     * Each section can be registered via the second return value of the
     * framework (a section-configurator) and may include:
     *  - id, title, description, icon (dashicon name), order
     */
    function fast_fuzzy_search_register_settings_framework($page_title, $menu_title, $option_name) {
        $fields   = [];
        $sections = [];

        add_action('admin_menu', function() use ($page_title, $menu_title, $option_name, &$fields, &$sections) {
            fast_fuzzy_search_add_settings_page($page_title, $menu_title, $option_name, $fields, $sections);
        });

        add_action('admin_init', function() use ($option_name, &$fields) {
            fast_fuzzy_search_register_settings($option_name, $fields);
        });

        $add_field = function($field) use (&$fields) {
            $fields[] = $field;
        };

        $add_section = function($section) use (&$sections) {
            $sections[$section['id']] = $section;
        };

        // Allow consumers to register sections + fields via this filter.
        return [$add_field, $add_section];
    }
}

if(!function_exists("fast_fuzzy_search_add_settings_page")) {
    function fast_fuzzy_search_add_settings_page($page_title, $menu_title, $option_name, &$fields, &$sections = []) {
        add_menu_page(
            $page_title,
            $menu_title,
            'manage_options',
            $option_name,
            function() use ($page_title, $option_name, &$fields, &$sections) {
                fast_fuzzy_search_render_settings_page($page_title, $option_name, $fields, $sections);
            },
            'data:image/svg+xml;base64,' . base64_encode(fast_fuzzy_search_svg('icon')),
        );
    }
}

if(!function_exists("fast_fuzzy_search_register_settings")) {
    function fast_fuzzy_search_register_settings($option_name, &$fields) {

        register_setting($option_name, $option_name, function($input) use ($fields) {
            $output = [];
            foreach ($fields as $field) {
                $field_id = $field['id'];
                if (isset($input[$field_id])) {
                    $output[$field_id] = fast_fuzzy_search_sanitize_settings($input[$field_id], $field);
                } elseif (in_array($field['type'], ['checkbox', 'switch'], true)) {
                    $output[$field_id] = '0';
                } elseif ($field['type'] === 'checkbox_group') {
                    $output[$field_id] = [];
                }
            }

            // Pass through meta-fields that aren't registered field types
            if (isset($input['custom_css'])) {
                $output['custom_css'] = sanitize_textarea_field($input['custom_css']);
            }

            if (function_exists('fast_fuzzy_search_generate_custom_css')) {
                fast_fuzzy_search_generate_custom_css($output);
            }

            return $output;
        });

        foreach ($fields as $field) {
            add_settings_field(
                $field['id'],
                $field['label'],
                function() use ($field, $option_name) {
                    fast_fuzzy_search_render_field($field, $option_name);
                },
                $option_name,
                $option_name,
                $field
            );
        }

        add_settings_section($option_name, '', null, $option_name);
    }
};


if(!function_exists("fast_fuzzy_search_sanitize_settings")) {

    function fast_fuzzy_search_sanitize_settings($value, $field) {
        switch ($field['type']) {
            case 'text':
            case 'number':
                // For text and number fields, sanitize and return the value.
                return sanitize_text_field($value);

            case 'textarea':
                return sanitize_textarea_field($value);

            case 'checkbox':
                // For checkbox, check if the value is set to '1', otherwise '0'.
                return ($value === '1') ? '1' : '0';

            case 'checkbox_group':
                // For checkbox group, sanitize each selected option.
                if (is_array($value)) {
                    return array_map('sanitize_text_field', $value);
                }
                return [];

            case 'radio':
                // For radio buttons, return the selected option value.
                return sanitize_text_field($value);

            case 'select':
                // For select dropdown, return the selected option value.
                return sanitize_text_field($value);

            case 'color_picker':
                // For color picker, sanitize the color value (hex format).
                return sanitize_hex_color($value);

            case 'range':
                // For range, sanitize and return the value within the defined min/max range.
                $min = $field['min'] ?? 0;
                $max = $field['max'] ?? 100;
                $value = intval($value);
                return ($value >= $min && $value <= $max) ? $value : $min;

            case 'switch':
                // For switch (checkbox), sanitize value as a boolean.
                return ($value === '1') ? '1' : '0';

            case 'image_radio':
                // For image radio, return the selected option value.
                return sanitize_text_field($value);

            case 'tabbed_radio':
                // For tabbed radio, return the selected option value.
                return sanitize_text_field($value);

            case 'file':
                // For file input, sanitize the file URL or leave it empty if no file is uploaded.
                return sanitize_file_name($value);

            case 'date':
                // For date input, sanitize and validate the date format (Y-m-d).
                return (preg_match('/\d{4}-\d{2}-\d{2}/', $value)) ? $value : '';

            case 'repeater':
                // For repeater, sanitize each item in the repeater array.
                if (is_array($value)) {
                    return array_map(function($item) {
                        return sanitize_text_field($item);
                    }, $value);
                }
                return [];
        }

        return $value;
    }
}

if(!function_exists("fast_fuzzy_search_render_field")) {
    function fast_fuzzy_search_render_field($field, $option_name) {
        $opt = get_option($option_name, []);
        $value = isset($opt[$field['id']]) ? $opt[$field['id']] : ($field['default'] ?? '');
        $type = $field['type'] ?? 'text';

        switch ($type) {
            default:
                include plugin_dir_path(__FILE__) . 'advanced-fields.php';
                break;
        }
    }
}


if(!function_exists("fast_fuzzy_search_render_settings_page")) {

    function fast_fuzzy_search_render_settings_page($page_title, $option_name, &$fields, &$sections = []) {

        // Default sections if the plugin did not register any.
        if (empty($sections)) {
            $sections = [
                'display'  => [
                    'id'          => 'display',
                    'title'       => __('Display', 'fast-fuzzy-search'),
                    'description' => __('Configure the visual style of the search bar.', 'fast-fuzzy-search'),
                    'icon'        => 'admin-customizer',
                    'order'       => 10,
                ],
                'behavior' => [
                    'id'          => 'behavior',
                    'title'       => __('Behavior', 'fast-fuzzy-search'),
                    'description' => __('Control how the search behaves across your site.', 'fast-fuzzy-search'),
                    'icon'        => 'admin-settings',
                    'order'       => 20,
                ],
                'index'    => [
                    'id'          => 'index',
                    'title'       => __('Search Index', 'fast-fuzzy-search'),
                    'description' => __('Tune how content is indexed and cached.', 'fast-fuzzy-search'),
                    'icon'        => 'database',
                    'order'       => 30,
                ],
                'custom-styles' => [
                    'id'          => 'custom-styles',
                    'title'       => __('Custom Styles', 'fast-fuzzy-search'),
                    'description' => __('Add your own CSS. Loaded after the active theme.', 'fast-fuzzy-search'),
                    'icon'        => 'editor-code',
                    'order'       => 40,
                ],
            ];
        }

        // Group fields by section; anything without a section lands in 'display'.
        $grouped = [];
        foreach ($fields as $field) {
            $section_id = !empty($field['section']) ? $field['section'] : 'display';
            if (!isset($grouped[$section_id])) {
                $grouped[$section_id] = [];
            }
            $grouped[$section_id][] = $field;
        }

        // Stable order: by section.order, then by field.order / array order.
        uasort($sections, function($a, $b) {
            return ($a['order'] ?? 10) <=> ($b['order'] ?? 10);
        });

        $current_memory_limit = ini_get('memory_limit');
        $current_time_limit   = ini_get('max_execution_time');
        $current_memory_limit_in_bytes = fast_fuzzy_search_convert_hr_to_bytes($current_memory_limit);
        $posts_count = fast_fuzzy_search_get_post_type_counts();
        $recommended_limits = fast_fuzzy_search_get_recommended_limits($posts_count['total_count']);
        $recommended_memory_limit_in_bytes = fast_fuzzy_search_convert_hr_to_bytes($recommended_limits['memory_limit']);
        $options = get_option('fast_fuzzy_search_options');
        $color_shades = fast_fuzzy_search_generate_color_Shades($options['primary_color']);

        $has_memory_warning  = $current_memory_limit_in_bytes < $recommended_memory_limit_in_bytes;
        $has_timeout_warning = (int) $current_time_limit < (int) $recommended_limits['max_execution_time'];
        ?>

        <div class="wrap ffs-page">

            <header class="ffs-plugin-header">
                <div class="ffs-plugin-header__brand">
                    <span class="ffs-plugin-header__icon" aria-hidden="true">
                        <?php echo wp_kses(fast_fuzzy_search_svg('icon'), fast_fuzzy_search_allowed_svg_tags()); ?>
                    </span>
                    <div class="ffs-plugin-header__title">
                        <h1 class="ffs-plugin-header__name"><?php echo esc_html($page_title); ?></h1>
                        <p class="ffs-plugin-header__subtitle"><?php esc_html_e('Configure how visitors search your site.', 'fast-fuzzy-search'); ?></p>
                    </div>
                </div>
                <div class="ffs-plugin-header__actions">
                    <a class="ffs-plugin-header__action" href="<?php echo esc_url( admin_url( 'admin.php?page=fast_fuzzy_search_docs' ) ); ?>">
                        <span class="dashicons dashicons-book" aria-hidden="true"></span>
                        <?php esc_html_e('Documentation', 'fast-fuzzy-search'); ?>
                    </a>
                    <a class="ffs-plugin-header__action" href="https://redoxbird.com/support" target="_blank" rel="noopener">
                        <span class="dashicons dashicons-sos" aria-hidden="true"></span>
                        <?php esc_html_e('Support', 'fast-fuzzy-search'); ?>
                    </a>
                    <?php if (!fast_fuzzy_search_is_pro()): ?>
                        <a class="ffs-plugin-header__action ffs-plugin-header__action--upgrade" href="<?php echo esc_url( function_exists( 'ffs_fs' ) ? ffs_fs()->get_upgrade_url() : 'https://redoxbird.com/product/fast-fuzzy-search/' ); ?>"<?php if ( ! function_exists( 'ffs_fs' ) ): ?> target="_blank" rel="noopener"<?php endif; ?>>
                            <span class="dashicons dashicons-star-filled" aria-hidden="true"></span>
                            <?php esc_html_e( 'Upgrade to Pro', 'fast-fuzzy-search' ); ?>
                        </a>
                    <?php else: ?>
                        <span class="ffs-plugin-header__status" aria-label="<?php esc_attr_e('Pro active', 'fast-fuzzy-search'); ?>">
                            <span class="ffs-plugin-header__status-dot ffs-plugin-header__status-dot--success" aria-hidden="true"></span>
                            <?php esc_html_e('Pro', 'fast-fuzzy-search'); ?>
                        </span>
                    <?php endif; ?>
                </div>
            </header>

            <div id="ffs-notice-container" aria-live="polite"></div>

            <?php if ($has_memory_warning): ?>
                <div class="ffs-banner ffs-banner--warning" role="status">
                    <span class="ffs-banner__icon" aria-hidden="true">
                        <span class="dashicons dashicons-warning"></span>
                    </span>
                    <div class="ffs-banner__body">
                        <p class="ffs-banner__title"><?php esc_html_e('Server memory limit is low', 'fast-fuzzy-search'); ?></p>
                        <p class="ffs-banner__message">
                            <?php
                            echo sprintf(
                                esc_html__('Current limit is %1$s. We recommend at least %2$s for the index to build reliably.', 'fast-fuzzy-search'),
                                '<code>' . esc_html($current_memory_limit) . '</code>',
                                '<code>' . esc_html($recommended_limits['memory_limit']) . '</code>'
                            );
                            ?>
                        </p>
                    </div>
                </div>
            <?php endif; ?>

            <?php if ($has_timeout_warning): ?>
                <div class="ffs-banner ffs-banner--warning" role="status">
                    <span class="ffs-banner__icon" aria-hidden="true">
                        <span class="dashicons dashicons-clock"></span>
                    </span>
                    <div class="ffs-banner__body">
                        <p class="ffs-banner__title"><?php esc_html_e('Max execution time is low', 'fast-fuzzy-search'); ?></p>
                        <p class="ffs-banner__message">
                            <?php
                            echo sprintf(
                                wp_kses(
                                    __('Current limit is <strong>%1$s</strong> seconds. We recommend at least <strong>%2$s</strong> for large indexes.', 'fast-fuzzy-search'),
                                    ['strong' => []]
                                ),
                                esc_html((string) $current_time_limit),
                                esc_html((string) $recommended_limits['max_execution_time'])
                            );
                            ?>
                        </p>
                    </div>
                </div>
            <?php endif; ?>

            <?php
            $post_types = fast_fuzzy_search_get_searchable_post_types();
            $total_indexed = array_sum(array_map(function ($type) use ($posts_count) {
                return isset($posts_count[$type]) ? (int) $posts_count[$type] : 0;
            }, array_keys($post_types)));
            ?>

            <section class="ffs-content-card" x-data="stats" aria-labelledby="ffs-stats-title">
                <header class="ffs-content-card__header">
                    <span class="ffs-content-card__header-icon ffs-content-card__header-icon--accent" aria-hidden="true">
                        <span class="dashicons dashicons-database"></span>
                    </span>
                    <div class="ffs-content-card__header-text">
                        <h2 class="ffs-content-card__title" id="ffs-stats-title"><?php esc_html_e('Search Index', 'fast-fuzzy-search'); ?></h2>
                        <p class="ffs-content-card__subtitle"><?php esc_html_e('Live overview of what visitors can search.', 'fast-fuzzy-search'); ?></p>
                    </div>
                    <div class="ffs-content-card__header-actions">
                        <span
                            class="ffs-status-pill ffs-status-pill--<?php echo esc_attr(
                                $total_indexed > 0 ? 'success' : 'idle'
                            ); ?>"
                            x-bind:class="{
                                'ffs-status-pill--success': data.length > 0,
                                'ffs-status-pill--idle':    data.length === 0 && state === 'idle',
                                'ffs-status-pill--info':    state !== 'idle' && state !== 'error'
                            }"
                        >
                            <span class="ffs-status-pill__dot" aria-hidden="true"></span>
                            <span x-text="state !== 'idle' ? stateLabels[state] : (data.length > 0 ? '<?php echo esc_js(__('Indexed', 'fast-fuzzy-search')); ?>' : '<?php echo esc_js(__('Empty', 'fast-fuzzy-search')); ?>')"></span>
                        </span>
                        <button
                            type="button"
                            class="button button-secondary"
                            x-on:click.prevent="refreshIndex"
                            x-bind:disabled="state !== 'idle'"
                        >
                            <span class="dashicons dashicons-update" aria-hidden="true" style="margin-right:4px;"></span>
                            <?php esc_html_e('Refresh Index', 'fast-fuzzy-search'); ?>
                        </button>
                    </div>
                </header>

                <div class="ffs-content-card__body ffs-content-card__body--padded">
                    <div class="ffs-stats__subgrid" style="margin-bottom:var(--ffs-space-5);">
                        <div>
                            <p class="ffs-stats__subgrid-label"><?php esc_html_e('Indexed entries', 'fast-fuzzy-search'); ?></p>
                            <p class="ffs-stats__subgrid-value">
                                <span x-text="state !== 'idle' ? '—' : data.length.toLocaleString()">—</span>
                            </p>
                        </div>
                        <div>
                            <p class="ffs-stats__subgrid-label"><?php esc_html_e('Content types', 'fast-fuzzy-search'); ?></p>
                            <p class="ffs-stats__subgrid-value">
                                <span x-text="state !== 'idle' ? '—' : Object.keys(groupedData).length">—</span>
                            </p>
                        </div>
                        <div>
                            <p class="ffs-stats__subgrid-label"><?php esc_html_e('Index size', 'fast-fuzzy-search'); ?></p>
                            <p class="ffs-stats__subgrid-value">
                                <span x-text="state !== 'idle' ? '—' : size">—</span>
                                <span style="font-size:var(--ffs-font-size-small);color:var(--ffs-gray-700);font-weight:400;margin-left:4px;">MB</span>
                            </p>
                        </div>
                    </div>

                    <hr class="ffs-stats__divider" />

                    <div x-show="state === 'idle' && data.length === 0">
                        <div class="ffs-empty-state ffs-empty-state--inline">
                            <span class="ffs-empty-state__icon" aria-hidden="true">
                                <span class="dashicons dashicons-search"></span>
                            </span>
                            <h3 class="ffs-empty-state__title"><?php esc_html_e('Your search index is empty', 'fast-fuzzy-search'); ?></h3>
                            <p class="ffs-empty-state__description"><?php esc_html_e('Refresh the index to scan your posts, pages, and products so visitors can find them.', 'fast-fuzzy-search'); ?></p>
                            <div class="ffs-empty-state__actions">
                                <button type="button" class="button button-primary" x-on:click="refreshIndex">
                                    <span class="dashicons dashicons-update" aria-hidden="true" style="margin-right:4px;"></span>
                                    <?php esc_html_e('Build the index', 'fast-fuzzy-search'); ?>
                                </button>
                            </div>
                        </div>
                    </div>

                    <div x-show="state === 'idle' && data.length > 0">
                        <ul class="ffs-post-type-list">
                            <?php foreach ($post_types as $post_type => $post_type_label): ?>
                                <li>
                                    <strong><?php echo esc_html($post_type_label); ?></strong>
                                    <span class="ffs-text-mono">
                                        <span x-text="groupedData['<?php echo esc_attr($post_type); ?>']?.length || 0">0</span>
                                        <span style="color:var(--ffs-gray-500);"> / </span>
                                        <span><?php echo esc_html((string) (!empty($posts_count[$post_type]) ? $posts_count[$post_type] : 0)); ?></span>
                                    </span>
                                </li>
                            <?php endforeach; ?>
                            <li>
                                <strong><?php esc_html_e('Headings', 'fast-fuzzy-search'); ?></strong>
                                <span class="ffs-text-mono">
                                    <span x-text="groupedData['heading']?.length || 0">0</span>
                                    <span style="color:var(--ffs-gray-500);"> / </span>
                                    <span x-text="groupedData['heading']?.length || 0">0</span>
                                </span>
                            </li>
                        </ul>
                    </div>

                    <div x-show="state !== 'idle'" class="ffs-empty-state ffs-empty-state--inline">
                        <span class="ffs-empty-state__icon" aria-hidden="true">
                            <span class="dashicons dashicons-update"></span>
                        </span>
                        <h3 class="ffs-empty-state__title" x-text="stateLabels[state] || '<?php echo esc_js(__('Working…', 'fast-fuzzy-search')); ?>'"><?php esc_html_e('Working…', 'fast-fuzzy-search'); ?></h3>
                        <p class="ffs-empty-state__description"><?php esc_html_e('Hang tight while we update the search index.', 'fast-fuzzy-search'); ?></p>
                    </div>
                </div>
            </section>

            <nav class="ffs-tabs" role="tablist" aria-label="<?php esc_attr_e('Settings sections', 'fast-fuzzy-search'); ?>">
                <?php $first = true; foreach ($sections as $section_id => $section):
                    $is_active   = $first ? ' is-active' : '';
                    $tab_id      = 'ffs-tab-' . esc_attr($section_id);
                    $panel_id    = 'ffs-panel-' . esc_attr($section_id);
                    $field_count = isset($grouped[$section_id]) ? count($grouped[$section_id]) : 0;
                    if ($field_count === 0) continue;
                ?>
                    <button
                        type="button"
                        role="tab"
                        class="ffs-tab<?php echo $is_active; ?>"
                        id="<?php echo $tab_id; ?>"
                        aria-controls="<?php echo $panel_id; ?>"
                        aria-selected="<?php echo $first ? 'true' : 'false'; ?>"
                        data-tab-target="<?php echo esc_attr($section_id); ?>"
                    >
                        <?php echo esc_html($section['title']); ?>
                        <span class="ffs-tab__count" aria-label="<?php esc_attr_e('field count', 'fast-fuzzy-search'); ?>"><?php echo (int) $field_count; ?></span>
                    </button>
                <?php $first = false; endforeach; ?>
            </nav>

            <form
                class="ffs-settings"
                method="post"
                action="options.php"
            >
                <div x-cloak x-show="state === 'saved'" class="ffs-notice ffs-notice--success" role="status">
                    <span class="ffs-notice__icon" aria-hidden="true">
                        <span class="dashicons dashicons-yes"></span>
                    </span>
                    <div>
                        <p class="ffs-notice__title"><?php esc_html_e('Settings saved', 'fast-fuzzy-search'); ?></p>
                        <p class="ffs-notice__body" x-text="message || '<?php esc_html_e('Your changes have been saved successfully.', 'fast-fuzzy-search'); ?>'"></p>
                    </div>
                </div>

                <div x-cloak x-show="state === 'error'" class="ffs-notice ffs-notice--error" role="alert">
                    <span class="ffs-notice__icon" aria-hidden="true">
                        <span class="dashicons dashicons-dismiss"></span>
                    </span>
                    <div>
                        <p class="ffs-notice__title"><?php esc_html_e('Something went wrong', 'fast-fuzzy-search'); ?></p>
                        <p class="ffs-notice__body" x-text="message || '<?php esc_html_e('Please try again.', 'fast-fuzzy-search'); ?>'"></p>
                    </div>
                </div>

                <?php
                    // Output nonce, referer, and option_page fields required by options.php.
                    settings_fields($option_name);
                ?>

                <?php
                $first = true;
                foreach ($sections as $section_id => $section):
                    if (empty($grouped[$section_id])) continue;
                    $is_active = $first ? ' is-active' : '';
                    $panel_id  = 'ffs-panel-' . esc_attr($section_id);
                ?>
                    <section
                        class="ffs-tab-panel ffs-content-card<?php echo $is_active; ?>"
                        id="<?php echo $panel_id; ?>"
                        role="tabpanel"
                        aria-labelledby="ffs-tab-<?php echo esc_attr($section_id); ?>"
                        data-tab-panel="<?php echo esc_attr($section_id); ?>"
                    >
                        <header class="ffs-content-card__header">
                            <?php if (!empty($section['icon'])): ?>
                                <span class="ffs-content-card__header-icon ffs-content-card__header-icon--accent" aria-hidden="true">
                                    <span class="dashicons dashicons-<?php echo esc_attr($section['icon']); ?>"></span>
                                </span>
                            <?php endif; ?>
                            <div class="ffs-content-card__header-text">
                                <h2 class="ffs-content-card__title"><?php echo esc_html($section['title']); ?></h2>
                                <?php if (!empty($section['description'])): ?>
                                    <p class="ffs-content-card__subtitle"><?php echo esc_html($section['description']); ?></p>
                                <?php endif; ?>
                            </div>
                        </header>
                        <div class="ffs-content-card__body">
                            <?php
                            $render_index = 0;
                            $render_total = count($grouped[$section_id]);
                            foreach ($grouped[$section_id] as $field):
                                $render_index++;
                                $is_pro = !empty($field['pro']) && !fast_fuzzy_search_is_pro();
                                $has_description = !empty($field['description']) || !empty($field['placeholder']);
                            ?>
                                <div class="ffs-form-row">
                                    <div class="ffs-form-row__label">
                                        <span class="ffs-form-row__label-text">
                                            <?php echo esc_html($field['label'] ?? ''); ?>
                                            <?php if ($is_pro): ?>
                                                <span class="ffs-form-row__pro" title="<?php esc_attr_e('Pro feature', 'fast-fuzzy-search'); ?>"><?php esc_html_e('Pro', 'fast-fuzzy-search'); ?></span>
                                            <?php endif; ?>
                                        </span>
                                        <?php if (!empty($field['description'])): ?>
                                            <span class="ffs-form-row__label-desc"><?php echo esc_html($field['description']); ?></span>
                                        <?php endif; ?>
                                    </div>
                                    <div class="ffs-form-row__control">
                                        <?php fast_fuzzy_search_render_field($field, $option_name); ?>
                                        <?php if (!empty($field['help'])): ?>
                                            <p class="ffs-form-row__help"><?php echo wp_kses_post($field['help']); ?></p>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </section>
                <?php $first = false; endforeach; ?>

                <div class="ffs-sticky-save-bar" role="region" aria-label="<?php esc_attr_e('Save changes', 'fast-fuzzy-search'); ?>">
                    <div
                        class="ffs-sticky-save-bar__info"
                        x-bind:class="{
                            'ffs-sticky-save-bar__info--saved':  state === 'saved'  || state === 'ready',
                            'ffs-sticky-save-bar__info--dirty':  state === 'dirty'  || (isDirty && state === 'idle'),
                            'ffs-sticky-save-bar__info--saving': state === 'saving' || state === 'loading' || state === 'updating',
                            'ffs-sticky-save-bar__info--error':  state === 'error'
                        }"
                    >
                        <span class="ffs-sticky-save-bar__info-icon" aria-hidden="true">
                            <template x-if="state === 'saving' || state === 'loading' || state === 'updating'">
                                <span class="ffs-sticky-save-bar__spinner" aria-hidden="true"></span>
                            </template>
                            <template x-if="state === 'saved' || state === 'ready'">
                                <span class="dashicons dashicons-yes" aria-hidden="true"></span>
                            </template>
                            <template x-if="state === 'dirty' || (isDirty && state === 'idle')">
                                <span class="dashicons dashicons-marker" aria-hidden="true"></span>
                            </template>
                            <template x-if="state === 'error'">
                                <span class="dashicons dashicons-warning" aria-hidden="true"></span>
                            </template>
                        </span>
                        <span x-text="
                            state === 'loading' ? '<?php echo esc_js(__('Loading settings…', 'fast-fuzzy-search')); ?>' :
                            (state === 'saving' || state === 'updating') ? '<?php echo esc_js(__('Saving changes…', 'fast-fuzzy-search')); ?>' :
                            state === 'saved'   ? '<?php echo esc_js(__('All changes saved', 'fast-fuzzy-search')); ?>' :
                            state === 'error'   ? '<?php echo esc_js(__('Could not save changes', 'fast-fuzzy-search')); ?>' :
                            (isDirty && state === 'idle') ? '<?php echo esc_js(__('You have unsaved changes', 'fast-fuzzy-search')); ?>' :
                            '<?php echo esc_js(__('No changes to save', 'fast-fuzzy-search')); ?>'
                        "></span>
                    </div>
                    <div class="ffs-sticky-save-bar__actions">
                        <button
                            type="button"
                            class="button button-secondary"
                            x-on:click="discardChanges"
                            x-bind:disabled="!isDirty || state === 'saving'"
                        >
                            <?php esc_html_e('Discard', 'fast-fuzzy-search'); ?>
                        </button>
                        <button
                            type="submit"
                            class="button button-primary"
                            x-bind:disabled="state === 'saving' || state === 'loading'"
                        >
                            <span x-show="state !== 'saving' && state !== 'updating'">
                                <?php esc_html_e('Save Changes', 'fast-fuzzy-search'); ?>
                            </span>
                            <span x-cloak x-show="state === 'saving' || state === 'updating'">
                                <?php esc_html_e('Saving…', 'fast-fuzzy-search'); ?>
                            </span>
                        </button>
                    </div>
                </div>
            </form>

            <?php fast_fuzzy_search_get_template_part('template-parts/admin/pricing'); ?>

        </div>
        <?php
    }
}
