<?php
namespace FuseCommerce\Views\Frontend;

use FuseCommerce\Config\IndexingConfig;
use FuseCommerce\Models\IndexingState;
use FuseCommerce\Helpers\FilterConfigHelper;
use FuseCommerce\Services\CurrencyService;

if ( ! defined( 'ABSPATH' ) ) exit;

class CommerceView {

    // used by [ftlcommerce] shortcode
    static function render(array $atts = [], mixed $content = null) {
        
        $is_woocommerce_active = is_plugin_active('woocommerce/woocommerce.php');
        if (!$is_woocommerce_active) {
            ob_start();
            ?>
                <div style="color: rgb(186, 8, 26);" class="fuse-missing-woo">
                    <strong><?php esc_html_e('WooCommerce Required', 'ftlcommerce-instant-product-search'); ?></strong>
                    <?php esc_html_e('This plugin requires WooCommerce to be installed and activated. Please install WooCommerce to use FtlCommerce.', 'ftlcommerce-instant-product-search'); ?>
                </div>
            <?php
            return ob_get_clean();
        }
        // Parse shortcode attributes with defaults
        $atts = shortcode_atts([
            'tag_limit' => 10,
            'category_limit' => 5,
            'free_search_debounce_delay' => 1000,
            'fuse_threshold' => 0.3,
            'fuse_name_weight' => 2,
            'fuse_short_description_weight' => 1,
            'initial_products_load_no' => 12,
            'load_more_products_no' => 12
        ], $atts, 'ftlcommerce');

        // Sanitize and validate
        $config = [
            'tag_limit' => absint($atts['tag_limit']),
            'category_limit' => absint($atts['category_limit']),
            'debounce_delay' => absint($atts['free_search_debounce_delay']),
            'fuse_threshold' => floatval($atts['fuse_threshold']),
            'fuse_weights' => [
                'name' => floatval($atts['fuse_name_weight']),
                'short_description' => floatval($atts['fuse_short_description_weight'])
            ],
            'initial_products_load_no' => max(1, absint($atts['initial_products_load_no'])),
            'load_more_products_no' => max(1, absint($atts['load_more_products_no']))
        ];

        // Ensure threshold is between 0.0 and 1.0
        $config['fuse_threshold'] = max(0.0, min(1.0, $config['fuse_threshold']));

        $categories = self::loadCategories();
        $tags = self::loadTags();
        $attributes = self::loadAttributes();
        $priceRange = self::getPriceRange();

        // Get filter configuration
        $filterConfig = FilterConfigHelper::getVisibleFilters();

        ob_start();
        ?>
        <div class="fusecommerce-main">
            <div class="mb-4 fuse-commerce-top">
                <button class="flex md:hidden items-center border-solid border-2 border-black hover:border-[#000000] bg-white text-black 
                hover:bg-[#ebebeb] hover:text-[#000000] transition-colors duration-200 text-center 
                rounded-full px-5 py-1 font-semibold relative fuse-popup-btn fuse-open-mobile-filters">
                    <!-- Filter Icon -->
                    <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <line x1="3" y1="6" x2="21" y2="6" stroke-width="2" stroke-linecap="round"/>
                        <line x1="3" y1="12" x2="21" y2="12" stroke-width="2" stroke-linecap="round"/>
                        <line x1="3" y1="18" x2="21" y2="18" stroke-width="2" stroke-linecap="round"/>
                        <circle cx="7" cy="6" r="2" fill="currentColor"/>
                        <circle cx="15" cy="12" r="2" fill="currentColor"/>
                        <circle cx="10" cy="18" r="2" fill="currentColor"/>
                    </svg>
                    <?php esc_html_e('Filters', 'ftlcommerce-instant-product-search'); ?>
                    <div class="absolute top-[-40%] right-[-5px] py-0 px-2 bg-black border-solid border-2 border-[#FFFFFF] rounded-full text-white fuse-filters-count"></div>
                </button>

            </div>
            <div class="flex flex-row gap-6 fusecommerce-content">

                <div class="hidden md:block w-64 flex-shrink-0 fusecommerce-filters-background">
                    <div class="fusecommerce-filters-background-black"></div>
                    <div class="fusecommerce-filters-content">
                        <div class="hidden fusecommerce-filters-mobile-top">
                            <div class="font-semibold text-xl"><?php esc_html_e('Filters', 'ftlcommerce-instant-product-search'); ?></div>
                            <button class="absolute top-1/2 right-[10px] -translate-y-1/2 w-9 h-9 flex items-center justify-center rounded-full text-black !hover:text-black transition-colors duration-200 hover:bg-[#F2F2F2] fuse-popup-btn close-filters-popup-btn"><?php esc_html_e('✕', 'ftlcommerce-instant-product-search'); ?></button>
                        </div>

                        <div class="fusecommerce-scroll-content-ui">
                            <div class="fusecommerce-scroll-content">
                                <aside class="fusecommerce-filters">
                                    <?php
                                    // Render filters in configured order
                                    if (!empty($filterConfig)) {
                                        foreach ($filterConfig as $filter) {
                                            switch ($filter['type']) {
                                                case 'search':
                                                    self::renderSearchFilter($config);
                                                    break;
                                                case 'category':
                                                    self::renderCategories($categories, $config['category_limit']);
                                                    break;
                                                case 'tag':
                                                    self::renderTags($tags, $config['tag_limit']);
                                                    break;
                                                case 'attribute':
                                                    self::renderAttribute($attributes, $filter['id']);
                                                    break;
                                                case 'price':
                                                    self::renderPriceRange($priceRange);
                                                    break;
                                            }
                                        }
                                    } else {
                                        // Fallback to default order if no configuration exists
                                        self::renderSearchFilter($config);
                                        self::renderCategories($categories, $config['category_limit']);
                                        self::renderTags($tags, $config['tag_limit']);
                                        self::renderAllAttributes($attributes);
                                        self::renderPriceRange($priceRange);
                                    }
                                    ?>
                                </aside>
                                <div>
                                    <button class="hidden md:block border-solid mb-5 border-2 border-black hover:border-[#000000] bg-white text-black hover:bg-[#ebebeb] hover:text-[#000000] transition-colors duration-200 text-center rounded-full px-5 py-1 font-semibold relative fuse-popup-btn fuse-clear-all-filters">
                                        <?php esc_html_e('Clear All', 'ftlcommerce-instant-product-search'); ?>
                                        <div class="absolute top-[-40%] right-[-5px] py-0 px-2 bg-black border-solid border-2 border-[#FFFFFF] rounded-full text-white fuse-filters-count"></div>
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="hidden fusecommerce-filters-mobile-bottom">
                            <div>
                                <button class="text-black hover:bg-[#e1e0e0] text-center rounded px-5 py-2 font-semibold 
                                fuse-popup-btn fuse-clear-filters-popup-btn"><?php esc_html_e('Clear all', 'ftlcommerce-instant-product-search'); ?></button>
                            </div>
                            <div>
                            </div>
                            <button class="bg-black text-white hover:bg-[#2d2d2d] hover:text-[#FFFFFF] text-center rounded px-5 py-2 font-semibold
                             flex items-center justify-center fuse-popup-btn fuse-apply-filters-popup-btn">
                             <div class="hidden fuse-loader-ui">
                                <div class="flex space-x-2 mr-4 fuse-loader">
                                    <span class="w-2 h-2 bg-white rounded-full animate-dot1"></span>
                                    <span class="w-2 h-2 bg-white rounded-full animate-dot2"></span>
                                    <span class="w-2 h-2 bg-white rounded-full animate-dot3"></span>
                                </div>
                             </div>
                             <span class="fuse-info"><?php esc_html_e('Show', 'ftlcommerce-instant-product-search'); ?> <span class="fuse-show-products-count"></span></span>
                            </button>
                        </div>
                    </div>
                </div>


                <main class="fusecommerce-products-wrapper flex-1"
                      data-initial-load="<?php echo esc_attr($config['initial_products_load_no']); ?>"
                      data-load-more-count="<?php echo esc_attr($config['load_more_products_no']); ?>">
                    <div class="fusecommerce-products-header mb-1">
                        <div class="product-count"></div>
                    </div>
                    <div class="grid gap-7 sm:grid-cols-2 md:grid-cols-3 [grid-template-columns:repeat(auto-fit,minmax(350px,1fr))] fusecommerce-products"></div>
                    <div class="products-loading">
                        <div class="py-10 fuse-products-loader-ui">
                            <div class="flex space-x-2 mr-4 items-center justify-center fuse-product-loader">
                                <span class="w-3 h-3 bg-gray-500 rounded-full animate-dot1"></span>
                                <span class="w-3 h-3 bg-gray-500 rounded-full animate-dot2"></span>
                                <span class="w-3 h-3 bg-gray-500 rounded-full animate-dot3"></span>
                            </div>
                        </div>
                    </div>
                    <div class="hidden my-5 load-more-ui">
                        <div class="flex items-center justify-center">
                            <button class="flex items-center border-solid border-2 border-black hover:border-[#000000] bg-white text-black 
                            hover:bg-[#ebebeb] hover:text-[#000000] transition-colors duration-200 text-center 
                            rounded-full px-6 py-1 font-semibold relative fuse-load-more">
                                <?php esc_html_e('Load more', 'ftlcommerce-instant-product-search'); ?>
                            </button>
                        </div>

                    </div>
                </main>
            </div>
        </div>
        <?php
        return ob_get_clean();
    }

    /**
     * Render categories filter with hierarchical support
     */
    private static function renderCategories(array $categories, int $parentLimit = 5): void {
        if (empty($categories)) {
            return;
        }

        $filterContent = apply_filters('fusecommerce_filter_render_categories', $categories, $parentLimit);
        if ($filterContent && is_string($filterContent)) {
            echo wp_kses_post($filterContent);
            return;
        }

        $displayCategories = $categories; // Already hierarchical from CategoryIndexerService

        ?>
        <div class="mb-5 filter-group" data-filter-type="category">
            <h4 class="filter-group-title"><?php esc_html_e('Categories', 'ftlcommerce-instant-product-search'); ?></h4>
            <div class="filter-group-content" data-parent-limit="<?php echo esc_attr($parentLimit); ?>">
                <?php
                $index = 0;
                foreach ($displayCategories as $category) {
                    $isHidden = $index >= $parentLimit;
                    self::renderCategoryItem($category, 0, $isHidden);
                    $index++;
                }

                if (count($displayCategories) > $parentLimit) {
                    ?>
                    <button class="w-full mt-2 py-2 px-3 text-sm text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded transition-colors category-show-all-btn" type="button">
                        <?php esc_html_e('Show All Categories', 'ftlcommerce-instant-product-search'); ?>
                    </button>
                    <?php
                }
                ?>
            </div>
        </div>
        <?php
    }

    /**
     * Render a single category item with hierarchical support
     */
    private static function renderCategoryItem(array $category, int $level, bool $hidden = false): void {
        $hasChildren = !empty($category['children']);

        // Get all descendant IDs for parent selection logic
        $allChildIds = self::getAllDescendantIds($category);
        $allChildIdsJson = !empty($allChildIds) ? json_encode($allChildIds) : '[]';

        $hiddenClass = $hidden ? ' hidden-initially' : '';
        $paddingLeft = $level * 1.5 + 0.5; // rem units

        ?>
        <div class="category-item-wrapper<?php echo esc_attr($hiddenClass); ?>" data-level="<?php echo esc_attr($level); ?>">
            <div class="w-full gap-2 py-1.5 px-2 rounded transition-colors category-item-row"
                 style="padding-left: <?php echo esc_attr($paddingLeft); ?>rem;">

                <!-- Left: Checkbox -->
                <button
                    class="filter-category-checkbox flex-shrink-0 w-5 h-5 border-2 border-gray-300 rounded transition-colors"
                    data-category-id="<?php echo esc_attr($category['id']); ?>"
                    data-category-slug="<?php echo esc_attr($category['slug']); ?>"
                    data-child-ids="<?php echo esc_attr($allChildIdsJson); ?>"
                    data-is-parent="<?php echo $hasChildren ? 'true' : 'false'; ?>"
                    type="button"
                    aria-label="<?php
                        /* translators: %s: Category name */
                        echo esc_attr(sprintf(__('Filter by %s', 'ftlcommerce-instant-product-search'), $category['name']));
                    ?>">
                    <!-- Checkmark SVG (hidden by default, shown when .checked class added) -->
                    <svg class="checkmark hidden w-full h-full text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M5 13l4 4L19 7"></path>
                    </svg>
                </button>

                <!-- Middle: Category Label (full-width clickable) -->
                <button
                    class="flex-1 text-left text-sm text-gray-700 filter-category-label"
                    data-category-id="<?php echo esc_attr($category['id']); ?>"
                    data-category-slug="<?php echo esc_attr($category['slug']); ?>"
                    data-child-ids="<?php echo esc_attr($allChildIdsJson); ?>"
                    data-is-parent="<?php echo $hasChildren ? 'true' : 'false'; ?>"
                    type="button">
                    <span class="font-medium"><?php echo esc_html($category['name']); ?></span>
                    <?php if (isset($category['count']) && $category['count'] > 0): ?>
                        <span class="text-xs text-gray-500 ml-1">(<?php echo esc_html($category['count']); ?>)</span>
                    <?php endif; ?>
                </button>

                <!-- Right: Expand/Collapse Arrow (only for parents) -->
                <?php if ($hasChildren): ?>
                    <button
                        class="category-expand-toggle flex-shrink-0 w-6 h-6 flex items-center justify-center text-gray-500 transition-colors"
                        data-category-id="<?php echo esc_attr($category['id']); ?>"
                        type="button"
                        aria-label="<?php
                            /* translators: %s: Category name */
                            echo esc_attr(sprintf(__('Expand %s subcategories', 'ftlcommerce-instant-product-search'), $category['name']));
                        ?>">
                        <!-- Chevron right icon (rotates 90deg when expanded) -->
                        <svg class="chevron-icon w-4 h-4 transition-transform duration-200" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
                        </svg>
                    </button>
                <?php else: ?>
                    <div class="w-6"></div> <!-- Spacer for alignment -->
                <?php endif; ?>
            </div>

            <!-- Children container (hidden by default) -->
            <?php if ($hasChildren): ?>
                <div class="category-children hidden" data-parent-id="<?php echo esc_attr($category['id']); ?>">
                    <?php foreach ($category['children'] as $child): ?>
                        <?php self::renderCategoryItem($child, $level + 1, false); ?>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
        <?php
    }

    /**
     * Get all descendant category IDs recursively
     */
    private static function getAllDescendantIds(array $category): array {
        $ids = [];
        if (!empty($category['children'])) {
            foreach ($category['children'] as $child) {
                $ids[] = $child['id'];
                $ids = array_merge($ids, self::getAllDescendantIds($child));
            }
        }
        return $ids;
    }

    /**
     * Render all attributes (fallback when no configuration exists)
     */
    private static function renderAllAttributes(array $attributes): void {
        if (empty($attributes)) {
            return;
        }

        $filterContent = apply_filters('fusecommerce_filter_render_all_attributes', $attributes);
        if ($filterContent && is_string($filterContent)) {
            echo wp_kses_post($filterContent);
            return;
        }

        foreach ($attributes as $attribute) {
            $attributeName = $attribute['name'] ?? '';
            self::renderAttribute($attributes, $attributeName);
        }
    }

    /**
     * Render a specific attribute filter by attribute name
     */
    private static function renderAttribute(array $attributes, string $attributeName): void {
        if (empty($attributes)) {
            return;
        }

        // Find the attribute in the attributes array
        $attribute = null;
        foreach ($attributes as $attr) {
            if ($attr['name'] === $attributeName) {
                $attribute = $attr;
                break;
            }
        }

        if (!$attribute) {
            return; // Attribute not found (may have been removed from WooCommerce)
        }

        $attributeLabel = $attribute['label'] ?? ucfirst(str_replace('pa_', '', $attributeName));
        $terms = $attribute['terms'] ?? [];

        if (empty($terms)) {
            return;
        }
        ?>
        <div class="mb-5 filter-group" data-filter-type="attribute" data-attribute-name="<?php echo esc_attr($attributeName); ?>">
            <h4 class="filter-group-title"><?php echo esc_html($attributeLabel); ?></h4>
            <div class="flex flex-wrap filter-group-content">
                <?php foreach ($terms as $term): ?>
                    <button
                        class="py-1 px-3 mr-3 mb-3 filter-item filter-attribute"
                        data-attribute-key="<?php echo esc_attr($attributeName); ?>"
                        data-attribute-value="<?php echo esc_attr($term['slug'] ?? $term['name']); ?>"
                        type="button">
                        <span class="filter-item-label"><?php echo esc_html($term['name']); ?></span>
                    </button>
                <?php endforeach; ?>
            </div>
        </div>
        <?php
    }

    /**
     * Render price range filter
     */
    private static function renderPriceRange(array $priceRange): void {
        if (empty($priceRange)) {
            return;
        }

        $filterContent = apply_filters('fusecommerce_filter_render_price_range', $priceRange);
        if ($filterContent && is_string($filterContent)) {
            echo wp_kses_post($filterContent);
            return;
        }

        // Get currency settings
        $currencyService = new CurrencyService();
        $formattedMin = $currencyService->formatPrice($priceRange['min']);
        $formattedMax = $currencyService->formatPrice($priceRange['max']);
        ?>
        <div class="mb-5 filter-group" data-filter-type="price">
            <h4 class="filter-group-title"><?php esc_html_e('Price Range', 'ftlcommerce-instant-product-search'); ?></h4>
            <div class="filter-group-content">
                <div class="price-range-filter"
                    data-min="<?php echo esc_attr($priceRange['min']); ?>"
                    data-max="<?php echo esc_attr($priceRange['max']); ?>">

                    <div class="price-range-values">
                        <span class="price-range-value-min"><?php echo wp_kses_post($formattedMin); ?></span>
                        <span class="price-range-separator">-</span>
                        <span class="price-range-value-max"><?php echo wp_kses_post($formattedMax); ?></span>
                    </div>

                    <div class="price-range-slider-container">
                        <div class="price-range-track">
                            <div class="price-range-track-active"></div>
                        </div>
                        <input
                            type="range"
                            class="price-range-slider price-range-slider-min"
                            min="<?php echo esc_attr($priceRange['min']); ?>"
                            max="<?php echo esc_attr($priceRange['max']); ?>"
                            value="<?php echo esc_attr($priceRange['min']); ?>"
                            step="1"
                        />
                        <input
                            type="range"
                            class="price-range-slider price-range-slider-max"
                            min="<?php echo esc_attr($priceRange['min']); ?>"
                            max="<?php echo esc_attr($priceRange['max']); ?>"
                            value="<?php echo esc_attr($priceRange['max']); ?>"
                            step="1"
                        />
                    </div>
                </div>
            </div>
        </div>
        <?php
    }

    /**
     * - @param array $config          Full configuration array (debounce_delay, fuse_threshold, fuse_weights)
     * @return void
     */
    private static function renderSearchFilter(array $config = []): void {
        // Configuration with defaults
        $debounceDelay = $config['debounce_delay'] ?? 1000;
        $fuseThreshold = $config['fuse_threshold'] ?? 0.3;
        $fuseWeights = $config['fuse_weights'] ?? [
            'name' => 2,
            'short_description' => 1
        ];

        $fileterContent = apply_filters('fusecommerce_filter_render_free_search', $config, $debounceDelay, $fuseThreshold, $fuseWeights);

        if ($fileterContent && is_string($fileterContent)) {
            echo wp_kses_post($fileterContent);
            return;
        }

        ?>
        <div class="mb-5 filter-group fuse-search-filter-container"
             data-filter-type="search"
             data-debounce-delay="<?php echo esc_attr($debounceDelay); ?>"
             data-fuse-threshold="<?php echo esc_attr($fuseThreshold); ?>"
             data-fuse-weights="<?php echo esc_attr(json_encode($fuseWeights)); ?>">
            <div class="filter-group-content">
                <div class="relative">
                    <input
                        type="text" 
                        class="w-full px-4 py-2 pr-10 focus:outline-none focus:border-black transition-colors hover:text-black rounded-full border-solid border-2 border-black fuse-search-filter-input"
                        placeholder="<?php esc_attr_e('Search anything...', 'ftlcommerce-instant-product-search'); ?>"
                        data-debounce-delay="<?php echo esc_attr($debounceDelay); ?>"
                        aria-label="<?php esc_attr_e('Search products', 'ftlcommerce-instant-product-search'); ?>"
                    />
                    
                    <button
                        type="button"
                        class="absolute right-3 top-1/2 -translate-y-1/2 w-6 h-6 hidden items-center justify-center rounded-full text-black !hover:text-black duration-200 hover:bg-[#F2F2F2] transition-colors fuse-search-clear-btn"
                        aria-label="<?php esc_attr_e('Clear search', 'ftlcommerce-instant-product-search'); ?>"
                    >
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                        </svg>
                    </button>
                </div>
            </div>
        </div>
        <?php
    }

    /**
     * Render tags filter
     */
    private static function renderTags(array $tags, int $tagLimit = 10): void {
        if (empty($tags)) {
            return;
        }

        $filterContent = apply_filters('fusecommerce_filter_render_tags', $tags, $tagLimit);
        if ($filterContent && is_string($filterContent)) {
            echo wp_kses_post($filterContent);
            return;
        }

        ?>
        <div class="mb-5 filter-group" data-filter-type="tag">
            <h4 class="filter-group-title"><?php esc_html_e('Tags', 'ftlcommerce-instant-product-search'); ?></h4>
            <div class="flex flex-wrap filter-group-content" data-tag-limit="<?php echo esc_attr($tagLimit); ?>">
                <?php
                $index = 0;
                foreach ($tags as $tag):
                    $isHidden = $index >= $tagLimit;
                    $hiddenClass = $isHidden ? ' hidden tag-hidden' : '';
                ?>
                    <button
                        class="py-1 px-3 mr-3 mb-3 filter-item filter-tag<?php echo esc_attr($hiddenClass); ?>"
                        data-tag-id="<?php echo esc_attr($tag['id']); ?>"
                        data-tag-slug="<?php echo esc_attr($tag['slug']); ?>"
                        type="button">
                        <span class="filter-item-label"><?php echo esc_html($tag['name']); ?></span>
                        <?php if (isset($tag['count']) && $tag['count'] > 0): ?>
                            <span class="text-xs text-gray-500 ml-1">(<?php echo esc_html($tag['count']); ?>)</span>
                        <?php endif; ?>
                    </button>
                <?php
                    $index++;
                endforeach;

                if (count($tags) > $tagLimit): ?>
                    <button class="w-full mt-2 py-2 px-3 text-sm text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded transition-colors tag-show-all-btn" type="button">
                        <?php esc_html_e('Show All Tags', 'ftlcommerce-instant-product-search'); ?>
                    </button>
                <?php endif; ?>
            </div>
        </div>
        <?php
    }

    private static function loadCategories(): array {
        $file_path = IndexingConfig::getFilePath(IndexingConfig::CATEGORIES_JSON_FILE);

        if (!file_exists($file_path)) {
            return [];
        }

        $json_content = file_get_contents($file_path);
        if ($json_content === false) {
            return [];
        }

        $data = json_decode($json_content, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            return [];
        }

        return $data['categories'] ?? $data ?? [];
    }

    private static function loadAttributes(): array {
        $file_path = IndexingConfig::getFilePath(IndexingConfig::ATTRIBUTES_JSON_FILE);

        if (!file_exists($file_path)) {
            return [];
        }

        $json_content = file_get_contents($file_path);
        if ($json_content === false) {
            return [];
        }

        $data = json_decode($json_content, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            return [];
        }

        return $data['attributes'] ?? $data ?? [];
    }

    private static function loadTags(): array {
        $file_path = IndexingConfig::getFilePath(IndexingConfig::TAGS_JSON_FILE);

        if (!file_exists($file_path)) {
            return [];
        }

        $json_content = file_get_contents($file_path);
        if ($json_content === false) {
            return [];
        }

        $data = json_decode($json_content, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            return [];
        }

        return $data['tags'] ?? $data ?? [];
    }

    private static function getPriceRange(): array {
        return IndexingState::getPriceRange();
    }

    static function getFeLabels(): array {
        return [
            // Product Card Labels
            'product_card_price' => __('Price:', 'ftlcommerce-instant-product-search'),
            'product_card_sku' => __('SKU:', 'ftlcommerce-instant-product-search'),
            'product_card_untitled' => __('Untitled Product', 'ftlcommerce-instant-product-search'),
            'product_card_view_product' => __('View Product', 'ftlcommerce-instant-product-search'),

            // Product List Messages
            'product_list_empty' => __('No products found matching your filters.', 'ftlcommerce-instant-product-search'),
            'product_list_error' => __('Error loading products. Please try again later.', 'ftlcommerce-instant-product-search'),
            'product_list_count_singular' => __('product found', 'ftlcommerce-instant-product-search'),
            'product_list_count_plural' => __('products found', 'ftlcommerce-instant-product-search'),
        ];
    }
}
