<?php
defined("ABSPATH") || exit;
/**
 * Screener Table Base — shared config for crypto-screener, stock-screener
 * Same pattern as market_movers.php — slug + assetType alag, baqi sab same
 *
 * Usage: return vunelix_build_screener_widget('crypto-screener', 'crypto');
 */

function vunelix_build_screener_widget(string $slug, string $assetType, array $defaultPresets = []): array {
    $vunelix_shared = require __DIR__ . '/../_shared_fields.php';

    // Stock-like assets share the stock API endpoint, crypto-like share crypto
    $stockLike  = ['stock', 'dr', 'fund', 'index'];
    $cryptoLike = ['crypto', 'dex', 'coin'];

    $isStock  = in_array($assetType, $stockLike);
    $isCrypto = in_array($assetType, $cryptoLike);
    $isForex  = ($assetType === 'forex');

    // API base path — dr/fund/index → stock, dex → crypto
    $apiBasePath = $isStock ? 'stock' : ($isCrypto ? 'crypto' : $assetType);

    return [
        'slug'      => $slug,
        'component' => 'vunelix-' . $slug,
        'js'        => 'widgets/screener/vunelix-' . $slug . '.js',

        // View — same component as main site
        'view'     => 'Fx_live/Views/components/screener_table',
        'lang_key' => '',  // screener_table.php expects full lang array — buildViewData handles it

        // Branding
        'branding_position' => 'top-right',
        'branding_offset_x' => 20,

        // Icons used by screener table
        'icons' => [
            'chevron-left', 'chevron-right', 'star', 'settings', 'primary', 'magnifier-char',
            'filter-funnel', 'reset', 'trending-up', 'trending-down', 'plus', 'more-vertical', 'setup', 'remove', 'apply', 'greater-equal', 'less-equal', 'equal', 'between', 'not-equal', 'minus', 'chevron-up', 'strong-sell', 'strong-buy'
        ],

        // Default values
        'defaults' => array_merge([
            // Asset type sent as `type` param to API
            'asset_type'       => $assetType,
            'api_base_path'    => $apiBasePath,
            'per_page'         => 10,
            'default_preset'   => 'overview',
            'default_period'   => '1D',
            ...($isStock ? ['default_country' => 'US', 'is_primary' => true] : []),

            // Feature toggles
            'enable_filter'    => true,
            'enable_fav'           => true,
            'enable_color_groups'  => true,
            'enable_presets'   => true,
            'enable_period'    => true,
            'enable_search'    => true,
            'enable_settings'  => true,
            'enable_columns'   => true,
            'enable_sort'      => true,
            'enable_storage'    => false,
            'enable_infinite_scroll' => false,

            // Sort — combined "column_direction" format (e.g. "perf.rank_asc")
            'default_sort'      => '',

            // Custom presets — JSON: {"presetName":["col1","col2"]}
            'custom_presets'   => '',

            // Default filters — JSON: {"price.c_between":"10,500","marketcap.c_gt":1000000000}
            'default_filters'  => '',

            // Display
            'show_ticker'      => true,
            'show_description' => true,
            'show_logo'        => true,
            'show_currency'    => true,

        ], $vunelix_shared['defaults']['links'], $vunelix_shared['defaults']['live_data']),

        // View variable aliases — config key → PHP variable name(s)
        'view_aliases' => [
            'asset_type'      => 'asset_type',
            'enable_filter'   => 'enableFilter',
            'enable_fav'           => 'enableFavFilter',
            'enable_color_groups'  => 'enableColorGroups',
            'enable_presets'  => 'enablePresets',
            'enable_period'   => 'enablePeriod',
            'enable_search'   => 'enableSearch',
            'enable_settings' => 'enableSettings',
            'enable_columns'  => 'enableCustomColumns',
            'default_preset'  => 'defaultPreset',
        ],

        // Widget-specific view data builder
        'buildViewData' => function(array $viewData, array $config): array {
            // Language — screener_table.php expects $lang['screener_table']
            $screenerLang = vunelix_load_lang('screener');
            $viewData['lang'] = $screenerLang;

            // Custom presets — only set if user configured them, otherwise view uses its own lang-based defaults
            if (!empty($config['custom_presets']) && is_string($config['custom_presets'])) {
                $parsed = json_decode($config['custom_presets'], true);
                if (is_array($parsed) && !empty($parsed)) {
                    $viewData['customPresets'] = array_combine(array_keys($parsed), array_keys($parsed));
                }
            }
            $viewData['defaultPeriod'] = strtolower($config['default_period'] ?? '1d');
            $viewData['defaultPerPage'] = (int)($config['per_page'] ?? 50);
            $viewData['columnContainerFluid'] = false;
            $viewData['enableReload'] = false;

            return $viewData;
        },

        // Parse combined fields → proper JS config values
        'buildJsConfig' => function(array $config): array {
            $jsConfig = [];

            // Default sort — "perf.rank_asc" → column + direction
            if (!empty($config['default_sort']) && is_string($config['default_sort'])) {
                $pos = strrpos($config['default_sort'], '_');
                if ($pos !== false) {
                    $jsConfig['SORT_BY_COLUMN']    = substr($config['default_sort'], 0, $pos);
                    $jsConfig['SORT_BY_DIRECTION']  = substr($config['default_sort'], $pos + 1);
                }
            }

            // Custom presets — {"presetName":["col1","col2"]} → pass directly
            if (!empty($config['custom_presets']) && is_string($config['custom_presets'])) {
                $parsed = json_decode($config['custom_presets'], true);
                if (is_array($parsed) && !empty($parsed)) {
                    $jsConfig['CUSTOM_PRESETS'] = $parsed;
                    $jsConfig['DEFAULT_PRESET'] = array_key_first($parsed);
                }
            }

            // Default filters — {"price.c_between":"10,500"}
            if (!empty($config['default_filters']) && is_string($config['default_filters'])) {
                $parsed = json_decode($config['default_filters'], true);
                if (is_array($parsed) && !empty($parsed)) {
                    $jsConfig['DEFAULT_FILTERS'] = $parsed;
                }
            }

            return $jsConfig;
        },

        // Config map — PHP key → JS config key
        'config_map' => array_merge([
            'asset_type'            => 'CURRENT_ASSET_TYPE',
            'api_base_path'         => 'API_BASE_PATH',
            'per_page'              => 'PER_PAGE',
            'default_preset'        => 'DEFAULT_PRESET',
            'default_period'        => 'DEFAULT_TIME_PERIOD',
            'default_country'       => 'DEFAULT_COUNTRY',
            'is_primary'            => 'DEFAULT_IS_PRIMARY',

            'enable_filter'         => 'ENABLE_FILTER_MANAGER',
            'enable_fav'            => 'SHOW_FAVORITES_ADD_REMOVE',
            'enable_color_groups'   => 'ENABLE_COLOR_GROUPS',
            'enable_columns'        => 'SHOW_COLUMNS_BUTTON',
            'enable_sort'           => 'ENABLE_SORT',
            'enable_storage'        => 'ENABLE_STORAGE',
            'enable_infinite_scroll' => 'ENABLE_INFINITE_SCROLL',

            // default_sort, custom_presets, default_filters handled by buildJsConfig

            'show_ticker'           => 'SHOW_TICKER',
            'show_description'      => 'SHOW_DESCRIPTION',
            'show_logo'             => 'SHOW_LOGO',
            'show_currency'         => 'SHOW_CURRENCY',
        ], $vunelix_shared['config_map']['links'], $vunelix_shared['config_map']['live_data']),

        // Settings groups
        'settings' => [
            'data' => [
                'label' => 'Data',
                'pkg'   => 1,
                'fields' => array_merge(
                    $isStock ? [
                        'default_country' => [
                            'type'        => 'select',
                            'label'       => 'Country',
                            'description' => 'Show stocks from this country (e.g. US = NYSE, NASDAQ). Visitors can change it.',
                            'default'     => 'US',
                            'key'         => 'default_country',
                            'pkg'         => 1,
                            'searchable'  => true,
                            'icon'        => 'country',
                            'options'     => vunelix_load_lang('common')['countries'] ?? [],
                        ],
                        'is_primary' => [
                            'type'        => 'toggle',
                            'label'       => 'Primary Listing Only',
                            'description' => 'Avoid duplicate stocks. Some stocks trade on multiple exchanges — this shows only the main listing (e.g. AAPL on NASDAQ, not also on other exchanges).',
                            'default'     => true,
                            'key'         => 'is_primary',
                            'pkg'         => 1,
                        ],
                    ] : [], [
                    'per_page' => [
                        'type'        => 'select',
                        'label'       => 'Items Per Page',
                        'description' => 'How many rows to show per page. Visitors can change this from the bottom of the table.',
                        'default'     => '10',
                        'key'         => 'per_page',
                        'pkg'         => 1,
                        'options'     => ['10' => '10', '50' => '50', '100' => '100', '200' => '200', '300' => '300'],
                    ],
                    'default_preset' => [
                        'type'    => 'select',
                        'label'   => 'Starting Tab',
                        'description' => 'Which tab is shown when the widget first loads (e.g. Overview, Performance).',
                        'default' => 'overview',
                        'key'     => 'default_preset',
                        'pkg'     => 1,
                        'options' => $defaultPresets,
                    ],
                    'default_period' => [
                        'type'        => 'select',
                        'label'       => 'Time Period',
                        'description' => 'Time range for performance data (e.g. 1 Day = today\'s change). Visitors can change it from the toolbar.',
                        'default'     => '1d',
                        'key'         => 'default_period',
                        'pkg'         => 1,
                        'options'     => vunelix_time_period_list(),
                    ],
                    'default_sort' => [
                        'type'        => 'select',
                        'label'       => 'Sort By',
                        'description' => 'How the table is sorted when it first loads (e.g. by price, market cap). Visitors can change by clicking columns.',
                        'default'     => '',
                        'key'         => 'default_sort',
                        'pkg'         => 1,
                        'searchable'  => true,
                        'source'      => 'screener_sort',
                    ],
                    'default_filters' => [
                        'type'        => 'filter-builder',
                        'full_width'  => true,
                        'label'       => 'Filters',
                        'description' => 'Filters applied when the table first loads. E.g. show only stocks with price above $100 or market cap over 1B.',
                        'default'     => '',
                        'key'         => 'default_filters',
                        'pkg'         => 1,
                        'source'      => 'screener_filters',
                        'add_label'   => 'Add Filter',
                    ],
                    'custom_presets' => [
                        'type'            => 'preset-builder',
                        'full_width'      => true,
                        'label'           => 'Custom Tabs',
                        'description'     => 'Build your own tabs with custom columns. Give each tab a name and pick which columns to show.',
                        'default'         => '',
                        'key'             => 'custom_presets',
                        'pkg'             => 1,
                        'item_label'      => 'Tab',
                        'add_label'       => 'Add Tab',
                        'name_field'      => [
                            'label'       => 'Tab Name',
                            'placeholder' => 'e.g. My Overview',
                        ],
                        'value_field'     => [
                            'type'        => 'list',
                            'label'       => 'Columns',
                            'multiple'    => true,
                            'searchable'  => true,
                            'placeholder' => 'Search column...',
                            'source'      => 'screener_metrics',
                        ],
                    ],
                ]),
            ],
            'display' => [
                'label' => 'Display',
                'pkg'   => 1,
                'fields' => [
                    'show_ticker' => [
                        'type'        => 'toggle',
                        'label'       => 'Show Symbol',
                        'description' => 'Show the symbol code in the first column (e.g. BTCUSD, AAPL).',
                        'default'     => true,
                        'key'         => 'show_ticker',
                        'pkg'         => 1,
                    ],
                    'show_description' => [
                        'type'        => 'toggle',
                        'label'       => 'Show Description',
                        'description' => 'Show the full name below the symbol (e.g. Bitcoin, Apple Inc).',
                        'default'     => true,
                        'key'         => 'show_description',
                        'pkg'         => 1,
                    ],
                    'show_logo' => [
                        'type'        => 'toggle',
                        'label'       => 'Show Logo',
                        'description' => 'Show the coin logo or company icon next to the symbol.',
                        'default'     => true,
                        'key'         => 'show_logo',
                        'pkg'         => 1,
                    ],
                    'show_currency' => [
                        'type'        => 'toggle',
                        'label'       => 'Show Currency',
                        'description' => 'Show currency code next to prices (e.g. USD, EUR).',
                        'default'     => true,
                        'key'         => 'show_currency',
                        'pkg'         => 1,
                    ],
                    'enable_filter' => [
                        'type'        => 'toggle',
                        'label'       => 'Show Filters',
                        'description' => 'Show the filter button in the toolbar so visitors can filter by price, volume, market cap, etc.',
                        'default'     => true,
                        'key'         => 'enable_filter',
                        'pkg'         => 1,
                    ],
                    'enable_fav' => [
                        'type'        => 'toggle',
                        'label'       => 'Show Watchlist',
                        'description' => 'Show a star icon on each row so visitors can add items to their watchlist.',
                        'default'     => true,
                        'key'         => 'enable_fav',
                        'pkg'         => 1,
                    ],
                    'enable_color_groups' => [
                        'type'        => 'toggle',
                        'label'       => 'Watchlist Color Groups',
                        'description' => 'Let visitors organize watchlist items into color-coded groups. When off, a single click adds or removes from the watchlist.',
                        'default'     => true,
                        'key'         => 'enable_color_groups',
                        'pkg'         => 1,
                    ],
                    'enable_presets' => [
                        'type'        => 'toggle',
                        'label'       => 'Show Tabs',
                        'description' => 'Show tabs like Overview, Performance, etc. at the top of the table.',
                        'default'     => true,
                        'key'         => 'enable_presets',
                        'pkg'         => 1,
                    ],
                    'enable_period' => [
                        'type'        => 'toggle',
                        'label'       => 'Show Time Period Picker',
                        'description' => 'Show time period buttons (1D, 1W, 1M, etc.) in the toolbar.',
                        'default'     => true,
                        'key'         => 'enable_period',
                        'pkg'         => 1,
                    ],
                    'enable_search' => [
                        'type'        => 'toggle',
                        'label'       => 'Show Search',
                        'description' => 'Show a search box in the toolbar to quickly find items in the table.',
                        'default'     => true,
                        'key'         => 'enable_search',
                        'pkg'         => 1,
                    ],
                    'enable_settings' => [
                        'type'        => 'toggle',
                        'label'       => 'Show Settings',
                        'description' => 'Show a settings icon in the toolbar where visitors can change table view and animation options.',
                        'default'     => true,
                        'key'         => 'enable_settings',
                        'pkg'         => 1,
                    ],
                    'enable_columns' => [
                        'type'        => 'toggle',
                        'label'       => 'Show Column Editor',
                        'description' => 'Show a button in the toolbar that lets visitors choose which columns appear in the table.',
                        'default'     => true,
                        'key'         => 'enable_columns',
                        'pkg'         => 1,
                    ],
                    'enable_sort' => [
                        'type'        => 'toggle',
                        'label'       => 'Enable Sorting',
                        'description' => 'Let visitors sort the table by clicking any column header (e.g. click Price to sort by price).',
                        'default'     => true,
                        'key'         => 'enable_sort',
                        'pkg'         => 1,
                    ],
                    'enable_infinite_scroll' => [
                        'type'        => 'toggle',
                        'label'       => 'Infinite Scroll',
                        'description' => 'Load more rows automatically as the visitor scrolls down, instead of showing page numbers.',
                        'default'     => false,
                        'key'         => 'enable_infinite_scroll',
                        'pkg'         => 1,
                    ],
                ],
            ],
            'links'     => $vunelix_shared['groups']['links'],
            'storage'   => $vunelix_shared['groups']['storage'],
            'live_data' => $vunelix_shared['groups']['live_data'],
        ],
    ];
}
