<?php
defined("ABSPATH") || exit;
/**
 * Forex Rates Base — shared config for currency-cross-rates & currency-heatmap
 * Dono widgets same view/presets/settings use karte hain, sirf slug + display_mode alag
 *
 * Usage: return vunelix_build_forex_rates_widget('currency-cross-rates', 'c');
 */

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

    $presets = [
        'overview' => [
            'label' => 'Overview', 'slug' => '', 'lang_key' => 'overview',
            'currencies' => ['EUR', 'GBP', 'JPY', 'CHF', 'AUD', 'CAD', 'NZD', 'CNY', 'HKD', 'SGD', 'INR', 'MXN']
        ],
        'major' => [
            'label' => 'Major Pairs', 'slug' => 'major-pairs', 'lang_key' => 'major_pairs',
            'currencies' => ['EUR', 'GBP', 'JPY', 'CHF', 'AUD', 'CAD', 'NZD', 'USD']
        ],
        'minor' => [
            'label' => 'Minor Pairs', 'slug' => 'minor-pairs', 'lang_key' => 'minor_pairs',
            'currencies' => ['EUR', 'GBP', 'AUD', 'NZD', 'CAD', 'CHF', 'JPY']
        ],
        'exotic' => [
            'label' => 'Exotic Pairs', 'slug' => 'exotic-pairs', 'lang_key' => 'exotic_pairs',
            'currencies' => ['TRY', 'ZAR', 'MXN', 'BRL', 'THB', 'PLN', 'SEK', 'NOK', 'DKK', 'HUF', 'CZK']
        ],
        'americas' => [
            'label' => 'Americas', 'slug' => 'americas', 'lang_key' => 'americas',
            'currencies' => ['USD', 'CAD', 'MXN', 'BRL', 'ARS', 'CLP', 'COP', 'PEN']
        ],
        'europe' => [
            'label' => 'Europe', 'slug' => 'europe', 'lang_key' => 'europe',
            'currencies' => ['EUR', 'GBP', 'CHF', 'SEK', 'NOK', 'DKK', 'PLN', 'CZK', 'HUF', 'RON', 'BGN']
        ],
        'asia' => [
            'label' => 'Asia Pacific', 'slug' => 'asia-pacific', 'lang_key' => 'asia_pacific',
            'currencies' => ['JPY', 'CNY', 'HKD', 'SGD', 'KRW', 'TWD', 'THB', 'INR', 'MYR', 'IDR', 'PHP', 'VND']
        ],
        'middle-east' => [
            'label' => 'Middle East', 'slug' => 'middle-east', 'lang_key' => 'middle_east',
            'currencies' => ['AED', 'SAR', 'QAR', 'KWD', 'BHD', 'OMR', 'JOD', 'ILS', 'EGP', 'LBP']
        ],
        'africa' => [
            'label' => 'Africa', 'slug' => 'africa', 'lang_key' => 'africa',
            'currencies' => ['ZAR', 'EGP', 'NGN', 'KES', 'GHS', 'MAD', 'TND', 'UGX', 'TZS']
        ],
    ];

    /**
     * Parse custom presets JSON — supports per-group exchange prefix
     * Format: {"Label":"EXCHANGE:CUR1,CUR2"} or {"Label":"CUR1,CUR2"} (no exchange)
     * Returns: ['key' => ['label'=>..., 'currencies'=>[...], 'exchange'=>'FX'|'']]
     */
    $parseCustomPresets = function(string $json, string $defaultExchange = 'FX'): array {
        $decoded = json_decode($json, true);
        if (!is_array($decoded) || empty($decoded)) return [];

        $result = [];
        foreach ($decoded as $label => $value) {
            $key = strtolower(preg_replace('/[^a-zA-Z0-9]+/', '-', trim($label)));
            if (!$key) continue;

            $exchange = '';
            $currStr = $value;

            // Check for exchange prefix — "FX:EUR,USD" or "ONA:ARS,AUD"
            if (preg_match('/^([A-Z]{2,5}):(.+)$/', $value, $m)) {
                $exchange = $m[1];
                $currStr = $m[2];
            }

            $currList = array_map('trim', array_filter(explode(',', strtoupper($currStr))));
            if (!$currList) continue;

            $result[$key] = [
                'label'      => trim($label),
                'slug'       => $key,
                'lang_key'   => $key,
                'currencies' => $currList,
                'exchange'   => $exchange ?: $defaultExchange,
            ];
        }
        return $result;
    };

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

        'view' => 'Fx_live/Views/components/forex_rates_table',

        'lang_key' => 'forex_rates',

        // Branding — floating badge + bottom bar
        'branding_position' => 'bottom-right',
        'branding_offset_x' => 10,
        'branding_offset_y' => 60,

        'defaults' => array_merge([
            'preset'               => 'overview',
            'presets'              => '',
            'exchange'             => 'FX',
            'time_period'          => '1d',
            'show_presets'         => true,
            'show_currency_select' => false,
            'show_time_period'     => false,
        ], $vunelix_shared['defaults']['links'], $vunelix_shared['defaults']['storage'], $displayMode === 'c' ? array_merge($vunelix_shared['defaults']['live_data'], [
            'animation_mode' => 'flash',
        ]) : []),

        'config_map' => array_merge([
            'preset'      => 'DEFAULT_PRESET',
            'exchange'    => 'EXCHANGE',
            'time_period' => 'PERIOD',
        ], $vunelix_shared['config_map']['links'], $vunelix_shared['config_map']['storage'], $displayMode === 'c' ? $vunelix_shared['config_map']['live_data'] : []),

        'view_aliases' => [],

        'buildViewData' => function(array $viewData, array $config) use ($presets, $displayMode, $parseCustomPresets): array {
            $activePresets = $presets;
            $presetKey = $config['preset'] ?? 'overview';
            $defaultExchange = strtoupper($config['exchange'] ?? 'FX');

            if (!empty($config['presets']) && is_string($config['presets'])) {
                $parsed = $parseCustomPresets($config['presets'], $defaultExchange);
                if (!empty($parsed)) {
                    $activePresets = $parsed;
                    if (!isset($activePresets[$presetKey])) {
                        $presetKey = array_key_first($activePresets) ?? 'overview';
                    }
                }
            }

            $viewData['presets'] = $activePresets;
            $viewData['active_preset_currencies'] = $activePresets[$presetKey]['currencies'] ?? $presets['overview']['currencies'];
            $viewData['display_mode'] = $displayMode;
            $viewData['page_slug'] = $activePresets[$presetKey]['slug'] ?? '';

            $viewData['enablePresetTabs'] = $config['show_presets'] ?? true;
            $viewData['enableCurrencySelect'] = $config['show_currency_select'] ?? true;
            $viewData['enableTimePeriodSelect'] = $config['show_time_period'] ?? true;
            $viewData['enableDisplayModeSelector'] = false;
            $viewData['defaultTimePeriod'] = strtolower($config['time_period'] ?? '1d');

            return $viewData;
        },

        'buildJsConfig' => function(array $config) use ($presets, $displayMode, $parseCustomPresets): array {
            $activePresets = $presets;
            $jsConfig = [];
            $defaultExchange = strtoupper($config['exchange'] ?? 'FX');

            if (!empty($config['presets']) && is_string($config['presets'])) {
                $parsed = $parseCustomPresets($config['presets'], $defaultExchange);
                if (!empty($parsed)) {
                    $activePresets = $parsed;
                    $userPreset = $config['preset'] ?? '';
                    $jsConfig['DEFAULT_PRESET'] = isset($activePresets[$userPreset]) ? $userPreset : array_key_first($activePresets);
                }
            }

            $lang = $config['lang'] ?? 'en';
            if ($lang !== 'en') {
                $langData = vunelix_load_lang('common');
                $translations = $langData['forex_rates'] ?? [];
                foreach ($activePresets as $key => &$preset) {
                    $langKey = $preset['lang_key'] ?? '';
                    if ($langKey && !empty($translations[$langKey])) {
                        $preset['label'] = $translations[$langKey];
                    }
                }
                unset($preset);
            }

            $jsConfig['DISPLAY_MODE'] = $displayMode;
            $jsConfig['EXCHANGE'] = strtoupper($config['exchange'] ?? 'FX');
            $jsConfig['PERIOD'] = strtoupper($config['time_period'] ?? '1D');
            $jsConfig['PRESETS'] = $activePresets;
            return $jsConfig;
        },

        'settings' => [
            'data' => [
                'label'  => 'Data',
                'pkg'    => 1,
                'fields' => array_merge([
                    'presets' => [
                        'type'            => 'preset-builder',
                        'full_width'      => true,
                        'label'           => 'Custom Tabs',
                        'description'     => 'Create your own tabs with custom currencies (minimum 3 per tab). Each tab loads data from the exchange selected when it was created. Drag to reorder tabs and currencies. The <b>active (selected)</b> tab will be the default shown on load.',
                        'default'         => '',
                        'key'             => 'presets',
                        'pkg'             => 1,
                        'item_label'      => 'Tab',
                        'add_label'       => 'Add Tab',
                        'name_field'      => [
                            'label'       => 'Tab Name',
                            'placeholder' => 'e.g. South Asian',
                        ],
                        'value_field'     => [
                            'type'        => 'ajax-select',
                            'label'       => 'Add Currencies',
                            'default'     => 'EUR',
                            'key'         => 'to',
                            'pkg'         => 1,
                            'multiple'    => false,
                            'searchable'  => true,
                            'placeholder' => 'Search currency...',
                            'api'         => 'forex/list',
                            'api_params'  => [
                                'type'    => 'forex',
                                'exchange'=> 'FX',
                                'merge'   => 'profile,meta',
                                'columns' => 'profile.currency,profile.base_logo,profile.curr_logo,meta.base_currency,meta.base_currency_desc,meta.currency_desc',
                            ],
                            'value_key'   => 'meta.base_currency',
                            'label_key'   => 'meta.base_currency_desc',
                            'icon_key'    => 'profile.base_logo',
                        ],
                    ],
                    'preset' => [
                        'type'        => 'select',
                        'label'       => 'Starting Tab',
                        'description' => 'Default tab shown when the widget first loads. Only applies when Custom Tabs above is empty.',
                        'default'     => 'overview',
                        'options'     => [
                            'overview' => 'Overview', 'major' => 'Major Pairs',
                            'minor' => 'Minor Pairs', 'exotic' => 'Exotic Pairs',
                            'americas' => 'Americas', 'europe' => 'Europe',
                            'asia' => 'Asia Pacific', 'middle-east' => 'Middle East',
                            'africa' => 'Africa',
                        ],
                        'key'         => 'preset',
                        'pkg'         => 1,
                    ],
                    'exchange' => [
                        'type'        => 'select',
                        'label'       => 'Exchange',
                        'description' => 'Where the currency rate data comes from. Different exchanges may show slightly different rates.',
                        'default'     => 'FX',
                        'key'         => 'exchange',
                        'pkg'         => 1,
                        'source'      => 'forex_exchanges',
                        'options'     => ['FX' => 'London Currency Banks'],
                    ],
                ], $displayMode === 'chp' ? [
                    'time_period' => [
                        'type'        => 'select',
                        'label'       => 'Time Period',
                        'description' => 'Default time range for data when the widget first loads (e.g. 1 Day = today\'s data).',
                        'default'     => '1d',
                        'key'         => 'time_period',
                        'pkg'         => 1,
                        'options'     => vunelix_time_period_list(),
                    ],
                ] : []),
            ],
            'display' => [
                'label'  => 'Display',
                'pkg'    => 1,
                'fields' => array_merge([
                    'show_presets' => [
                        'type'        => 'toggle',
                        'label'       => 'Show Tabs',
                        'description' => 'Display the currency group tabs (Major, Minor, Exotic, etc.) at the top of the widget.',
                        'default'     => true,
                        'key'         => 'show_presets',
                        'pkg'         => 1,
                    ],
                    'show_currency_select' => [
                        'type'        => 'toggle',
                        'label'       => 'Show Currency Picker',
                        'description' => 'Show a dropdown in the header that lets visitors pick a base currency (e.g. show all pairs against USD).',
                        'default'     => false,
                        'key'         => 'show_currency_select',
                        'pkg'         => 1,
                    ],
                ], $displayMode === 'chp' ? [
                    'show_time_period' => [
                        'type'        => 'toggle',
                        'label'       => 'Show Time Period Picker',
                        'description' => 'Show a time period selector (1D, 1W, 1M, etc.) in the widget header.',
                        'default'     => false,
                        'key'         => 'show_time_period',
                        'pkg'         => 1,
                    ],
                ] : []),
            ],
            'links'     => array_merge($vunelix_shared['groups']['links'], [
                'fields' => array_merge($vunelix_shared['groups']['links']['fields'], [
                    'link_url' => array_merge($vunelix_shared['fields']['link_url'], [
                        'tokens' => ['symbol', 'name', 'from', 'to', 'exchange'],
                    ]),
                ]),
            ]),
            'storage'   => $vunelix_shared['groups']['storage'],
        ] + ($displayMode === 'c' ? [
            'live_data' => array_merge($vunelix_shared['groups']['live_data'], [
                'fields' => array_merge($vunelix_shared['groups']['live_data']['fields'], [
                    'animation_mode' => array_merge($vunelix_shared['fields']['animation_mode'], [
                        'default' => 'flash',
                    ]),
                ]),
            ]),
        ] : []),
    ];
}
