<?php
defined("ABSPATH") || exit;
/**
 * Market Movers Base — shared config for crypto-market-movers, forex-market-movers, stock-market-movers
 * Same pattern as heatmap.php — slug + marketType alag, baqi sab same
 *
 * Usage: return vunelix_build_market_movers_widget('crypto-market-movers', 'crypto');
 */

function vunelix_build_market_movers_widget(string $slug, string $marketType): array {
    $vunelix_shared = require __DIR__ . '/../_shared_fields.php';

    $isStock  = ($marketType === 'stock');
    $isForex  = ($marketType === 'forex');
    $isCrypto = ($marketType === 'crypto');

    // Sort options — common + market-specific
    $commonSortOptions = [
        'none'            => 'No Sort (default order)',
        'active.chp_desc' => 'Top Gainers',
        'active.chp_asc'  => 'Top Losers',
        'active.c_desc'   => 'Price High → Low',
        'active.c_asc'    => 'Price Low → High',
    ];

    $forexSortOptions = [
        'active.v_desc' => 'Volume High → Low',
        'active.a_desc' => 'Ask High → Low',
        'active.a_asc'  => 'Ask Low → High',
        'active.b_desc' => 'Bid High → Low',
        'active.b_asc'  => 'Bid Low → High',
    ];

    $cryptoSortOptions = [
        'perf.rank_asc'         => 'Rank (Top First)',
        'perf.24h_vol_cmc_desc' => 'Volume High → Low',
        'perf.market_cap_desc'  => 'Market Cap High → Low',
    ];

    $stockSortOptions = [
        'active.v_desc'            => 'Volume High → Low',
        'earnings.market_cap_desc' => 'Market Cap High → Low',
    ];

    $sortOptions = $commonSortOptions + ($isForex ? $forexSortOptions : ($isCrypto ? $cryptoSortOptions : $stockSortOptions));

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

        // View — same component as main site
        'view' => 'Fx_live/Views/components/market_movers',

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

        // Max symbols per plan
        'limits' => [
            'symbols' => [2 => 14, 3 => 50],
        ],

        // Default values
        'defaults' => array_merge([
            // Data — market type hardcoded per slug
            'symbols'          => '',
            'api_type'         => $isCrypto ? 'coin' : $marketType,
            'asset_type'       => $isCrypto ? 'coin' : ($isStock ? 'stock' : $marketType),
            'sort_by'          => 'active.chp_desc',
            'per_page'         => 12,
            ...($isStock ? ['country' => 'US', 'is_primary' => true] : []),

            // Display
            'metrics'          => 'active.c,active.chp',
            'show_symbol'      => true,
            'show_name'        => true,
            'show_logo'        => true,
            'show_currency'    => true,
            'change_badge'     => false,
            'card_style'       => 'borderless',
            'grid_cols'        => 0,
            'show_border'      => false,

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

        // View variable aliases
        'view_aliases' => [
            'per_page'  => 'perPage',
            'grid_cols' => 'gridCols',
            'show_logo' => 'showLogo',
        ],

        // Widget-specific view data builder
        'buildViewData' => function(array $viewData, array $config): array {
            $viewData['containerId'] = 'widget-market-movers';

            // Custom symbols → perPage = symbol count (max 12)
            $symbols = trim($config['symbols'] ?? '');
            if ($symbols !== '') {
                $count = count(array_filter(explode(',', $symbols)));
                if ($count > 0) {
                    $viewData['perPage'] = min($count, 12);
                }
            }

            return $viewData;
        },

        // Config map — PHP key → JS config key
        'config_map' => array_merge([
            'symbols'          => 'symbols',
            'api_type'         => 'apiType',
            'asset_type'       => 'assetType',
            'sort_by'          => 'sortBy',
            'per_page'         => 'perPage',
            'country'          => 'country',
            'is_primary'       => 'isPrimary',
            'filters'          => 'filters',
            'metrics'          => 'metrics',
            'show_symbol'      => 'showSymbol',
            'show_name'        => 'showName',
            'show_logo'        => 'showLogo',
            'show_currency'    => 'showCurrency',
            'change_badge'     => 'changeBadge',
            'card_style'       => 'cardStyle',
            'grid_cols'        => 'gridCols',
            'show_border'      => 'showBorder',
        ], $vunelix_shared['config_map']['links'], $vunelix_shared['config_map']['live_data']),

        // Settings groups
        'settings' => [
            'data' => [
                'label' => 'Data',
                'pkg'   => 1,
                'fields' => [
                    'symbols' => [
                        'type'        => 'symbol-picker',
                        'full_width'  => true,
                        'label'       => 'Custom Symbols',
                        'description' => 'When set, only these symbols will be shown instead of the category list above. Sort By still applies to custom symbols.',
                        'default'     => '',
                        'key'         => 'symbols',
                        'pkg'         => 1,
                        'multiple'    => true,
                        'search_type' => $marketType,
                        ...($isCrypto ? ['search_exchange' => 'crypto'] : []),
                    ],
                    ...($isCrypto ? [
                        'filters' => [
                            'type'        => 'select',
                            'label'       => 'Category',
                            'description' => 'Filter by crypto category (coins, DeFi, memes, stablecoins, etc.).',
                            'default'     => '',
                            'key'         => 'filters',
                            'pkg'         => 1,
                            'options' => [
                                ''                                          => 'Crypto Coins',
                                '{"ticker_neq":"CRYPTO:BTCUSD"}'           => 'Crypto Coins (Excluding Bitcoin)',
                                '{"perf.category_neq":"stablecoins"}'      => 'Crypto Coins (Excluding Stablecoins)',
                                '{"perf.category_eq":"defi"}'              => 'Coins DeFi',
                                '{"perf.category_eq":"memes"}'             => 'Coins Memes',
                                '{"perf.category_eq":"gaming"}'            => 'Coins Gaming',
                                '{"perf.category_eq":"stablecoins"}'       => 'Stablecoins',
                            ],
                        ],
                    ] : []),
                    'sort_by' => [
                        'type'        => 'select',
                        'label'       => 'Sort By',
                        'description' => 'How items are ordered when the widget first loads. Visitors can\'t change this from the widget.',
                        'default'     => 'active.chp_desc',
                        'key'         => 'sort_by',
                        'pkg'         => 1,
                        'options'     => $sortOptions,
                    ],
                    'per_page' => [
                        'type'        => 'number',
                        'label'       => 'Number of Items',
                        'description' => [1 => 'How many items to show in the widget. Maximum 20.', 2 => 'How many items to show in the widget. Free plan: max 20, Paid: max 50.'],
                        'default'     => '12',
                        'key'         => 'per_page',
                        'pkg'         => 1,
                        'min'         => 1,
                        'max'         => [1 => 20, 2 => 50],
                    ],
                    ...($isStock ? [
                        'country' => [
                            'type'        => 'select',
                            'label'       => 'Country',
                            'description' => 'Show stocks from this country. E.g. United States shows NYSE and NASDAQ stocks.',
                            'default'     => 'US',
                            'key'         => '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,
                        ],
                    ] : []),
                ],
            ],
            'display' => [
                'label' => 'Display',
                'pkg'   => 1,
                'fields' => [
                    'show_symbol' => [
                        'type'        => 'toggle',
                        'label'       => 'Show Symbol',
                        'description' => 'Display the ticker symbol (e.g. BTCUSD, EURUSD).',
                        'default'     => true,
                        'key'         => 'show_symbol',
                        'pkg'         => 1,
                    ],
                    'show_name' => [
                        'type'        => 'toggle',
                        'label'       => 'Show Full Name',
                        'description' => 'Display the full asset name (e.g. Bitcoin / US Dollar).',
                        'default'     => true,
                        'key'         => 'show_name',
                        'pkg'         => 1,
                    ],
                    'show_logo' => [
                        'type'        => 'toggle',
                        'label'       => 'Show Flag/Logo',
                        'description' => 'Display the currency flag or coin logo.',
                        'default'     => true,
                        'key'         => 'show_logo',
                        'pkg'         => 1,
                    ],
                    'show_currency' => [
                        'type'        => 'toggle',
                        'label'       => 'Show Currency',
                        'description' => 'Show currency code next to the price (e.g. USD, IRR).',
                        'default'     => true,
                        'key'         => 'show_currency',
                        'pkg'         => 1,
                    ],
                    'change_badge' => [
                        'type'        => 'toggle',
                        'label'       => 'Change as Badge',
                        'description' => 'Show the price change inside a colored green/red badge. Cards switch to a horizontal layout when enabled.',
                        'default'     => false,
                        'key'         => 'change_badge',
                        'pkg'         => 1,
                    ],
                    'card_style' => [
                        'type'        => 'select',
                        'label'       => 'Card Style',
                        'description' => 'Borderless gives a clean flat look. Bordered adds an outline around each card.',
                        'default'     => 'borderless',
                        'key'         => 'card_style',
                        'pkg'         => 1,
                        'options' => [
                            'borderless' => 'Borderless (clean)',
                            'bordered'   => 'Bordered (card outline)',
                        ],
                    ],
                    'grid_cols' => [
                        'type'        => 'select',
                        'label'       => 'Grid Columns',
                        'description' => 'Choose a fixed number of columns, or Auto to let the widget adjust based on available space. Even with a fixed choice, columns will reduce on smaller screens.',
                        'default'     => '0',
                        'key'         => 'grid_cols',
                        'pkg'         => 1,
                        'options' => [
                            '0' => 'Auto (responsive)',
                            '1' => '1 Column',
                            '2' => '2 Columns',
                            '3' => '3 Columns',
                            '4' => '4 Columns',
                        ],
                    ],
                    'metrics' => [
                        'type'       => 'sortable-select',
                        'full_width' => true,
                        'label'      => 'Data Fields',
                        'description' => 'Choose which values to show on each card (e.g. Price, Change). Drag to reorder. Max 2.',
                        'default'  => 'active.c,active.chp',
                        'key'      => 'metrics',
                        'pkg'      => 1,
                        'max'      => 2,
                        'options'  => array_merge([
                            'active.c'   => 'Price',
                            'active.ch'  => 'Change',
                            'active.chp' => 'Change %',
                        ], $isForex ? [
                            'active.v'  => 'Volume',
                            'active.a'  => 'Ask',
                            'active.b'  => 'Bid',
                            'spread'    => 'Spread',
                        ] : ($isCrypto ? [
                            'perf.market_cap'  => 'Market Cap',
                            'perf.24h_vol_cmc' => '24h Volume',
                        ] : ($isStock ? [
                            'active.v'       => 'Volume',
                            'premarket.c'    => 'Pre-Market Price',
                            'premarket.ch'   => 'Pre-Market Change',
                            'premarket.chp'  => 'Pre-Market Change %',
                            'premarket.v'    => 'Pre-Market Volume',
                            'postmarket.c'   => 'Post-Market Price',
                            'postmarket.ch'  => 'Post-Market Change',
                            'postmarket.chp' => 'Post-Market Change %',
                            'postmarket.v'   => 'Post-Market Volume',
                        ] : []))),
                    ],
                ],
            ],
            'links'     => $vunelix_shared['groups']['links'],
            'live_data' => $vunelix_shared['groups']['live_data'],
        ],
    ];
}
