<?php
defined("ABSPATH") || exit;
/**
 * Heatmap Base — shared config for crypto-heatmap, stock-heatmap, currency-heatmap
 * All heatmap widgets same view/icons/settings use karte hain, sirf slug + heatmapType alag
 *
 * Usage: return vunelix_build_heatmap_widget('crypto-heatmap', 'crypto');
 */

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

    $isStock = ($heatmapType === 'stock');

    // Get options from shared helper — same source as heatmap_canvas.php
    $hmOptions = vunelix_get_heatmap_options($heatmapType);

    // Settings panel needs simple key => label format
    $typeOptions = array_column($hmOptions['type'], 'label', 'value');
    $sortOptions = array_column($hmOptions['sort'], 'label', 'value');

    // Color options — value = "columns|period" for config_map parsing
    $colorSelectOptions = [];
    foreach ($hmOptions['color'] as $c) {
        $key = $c['params']['columns'] . '|' . $c['params']['period'];
        $colorSelectOptions[$key] = $c['label'];
    }

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

        'view'     => 'Fx_live/Views/components/heatmap_canvas',
        'lang_key' => '',  // heatmap_canvas.php expects full lang array — buildViewData handles it

        // Branding — bottom bar + badge
        'branding_position' => 'top-left',
        'branding_offset_x' => 20,
        'branding_offset_y' => 100,

        // Icons — heatmap_canvas.php uses all these
        'icons' => [
            'settings', 'camera', 'maximize-2',
            'reset', 'zoom-in', 'zoom-out',
            'primary', 'global',
            'magnifier-char'
        ],

        'defaults' => [
            'heatmap_type'            => $heatmapType,
            'default_type'            => $isStock ? 'stock' : 'coin',
            'enable_type_select'      => !$isStock,
            'enable_indices_select'   => $isStock,
            'enable_sector_select'    => $isStock,
            'link_target'             => '_blank',
            'auto_update'             => false,
        ],

        // Direct config_map — PHP key → JS config key (HEATMAP_INITIAL)
        'config_map' => [
            // Default selections
            'default_type'            => 'HEATMAP_INITIAL.TYPE',
            'default_sort'            => 'HEATMAP_INITIAL.DEFAULT_SORT',
            'default_color'           => 'HEATMAP_INITIAL.DEFAULT_COLOR',
            'default_per_page'        => 'HEATMAP_INITIAL.DEFAULT_PER_PAGE',
            'default_country'         => 'HEATMAP_INITIAL.DEFAULT_COUNTRY',
            'default_indices'         => 'HEATMAP_INITIAL.DEFAULT_INDICES',
            'default_indices_name'    => 'HEATMAP_INITIAL.DEFAULT_INDICES_NAME',
            'default_indices_logo'    => 'HEATMAP_INITIAL.DEFAULT_INDICES_LOGO',
            'default_sector'          => 'HEATMAP_INITIAL.DEFAULT_SECTOR',
            'default_is_primary'      => 'HEATMAP_INITIAL.DEFAULT_IS_PRIMARY',

            // Display settings
            'default_color_mode'      => 'HEATMAP_INITIAL.DEFAULT_COLOR_MODE',
            'default_show_logo'       => 'HEATMAP_INITIAL.DEFAULT_SHOW_LOGO',
            'default_display_name'    => 'HEATMAP_INITIAL.DEFAULT_DISPLAY_NAME',
            'default_display_value'   => 'HEATMAP_INITIAL.DEFAULT_DISPLAY_VALUE',
            'default_border_radius'   => 'HEATMAP_INITIAL.DEFAULT_BORDER_RADIUS',

            // Links
            'overview_url'            => 'HEATMAP_INITIAL.OVERVIEW_URL',
            'chart_url'               => 'HEATMAP_INITIAL.CHART_URL',
            'link_target'             => 'HEATMAP_INITIAL.LINK_TARGET',

            // Toolbar & controls
            'enable_settings'         => 'HEATMAP_INITIAL.ENABLE_SETTINGS',
            'enable_screenshot'       => 'HEATMAP_INITIAL.ENABLE_SCREENSHOT',
            'enable_fullscreen'       => 'HEATMAP_INITIAL.ENABLE_FULLSCREEN',
            'enable_zoom_controls'    => 'HEATMAP_INITIAL.ENABLE_ZOOM_CONTROLS',
            'enable_wheel_zoom'       => 'HEATMAP_INITIAL.ENABLE_WHEEL_ZOOM',
            'enable_legend'           => 'HEATMAP_INITIAL.ENABLE_LEGEND',

            // Selector visibility
            'enable_type_select'      => 'HEATMAP_INITIAL.ENABLE_TYPE_SELECT',
            'enable_sort_select'      => 'HEATMAP_INITIAL.ENABLE_SORT_SELECT',
            'enable_color_select'     => 'HEATMAP_INITIAL.ENABLE_COLOR_SELECT',
            'enable_per_page_select'  => 'HEATMAP_INITIAL.ENABLE_PER_PAGE_SELECT',
            'enable_indices_select'   => 'HEATMAP_INITIAL.ENABLE_INDICES_SELECT',
            'enable_sector_select'    => 'HEATMAP_INITIAL.ENABLE_SECTOR_SELECT',
            'enable_country_select'   => 'HEATMAP_INITIAL.ENABLE_COUNTRY_SELECT',
            'enable_primary_toggle'   => 'HEATMAP_INITIAL.ENABLE_PRIMARY_TOGGLE',

            // Tooltip
            'enable_hover_tooltip'    => 'HEATMAP_INITIAL.ENABLE_HOVER_TOOLTIP',
            'enable_click_tooltip'    => 'HEATMAP_INITIAL.ENABLE_CLICK_TOOLTIP',
            'enable_overview_link'    => 'HEATMAP_INITIAL.ENABLE_OVERVIEW_LINK',
            'enable_chart_link'       => 'HEATMAP_INITIAL.ENABLE_CHART_LINK',

            // Auto update
            'auto_update'             => 'HEATMAP_INITIAL.AUTO_UPDATE',

            // Storage
            'enable_storage'          => 'HEATMAP_INITIAL.ENABLE_STORAGE',
        ],

        'view_aliases' => [],

        // PHP view ke liye extra variables
        'buildViewData' => function(array $viewData, array $config) use ($heatmapType): array {
            // heatmap_canvas.php expects $lang['heatmap_canvas'] — same as HeatmapCtrl
            $viewData['lang'] = vunelix_load_lang('heatmap');

            // heatmap_canvas.php expects these variables
            $viewData['heatmap_type'] = $heatmapType;

            // Boolean enable/disable flags → view variables
            $boolMap = [
                'enable_type_select'     => 'enableTypeSelect',
                'enable_country_select'  => 'enableCountrySelect',
                'enable_indices_select'  => 'enableIndicesSelect',
                'enable_sector_select'   => 'enableSectorSelect',
                'enable_sort_select'     => 'enableSortSelect',
                'enable_color_select'    => 'enableColorSelect',
                'enable_per_page_select' => 'enablePerPageSelect',
                'enable_settings'        => 'enableSettings',
                'enable_screenshot'      => 'enableScreenshot',
                'enable_fullscreen'      => 'enableFullscreen',
                'enable_zoom_controls'   => 'enableZoomControls',
                'enable_hover_tooltip'   => 'enableHoverTooltip',
                'enable_click_tooltip'   => 'enableClickTooltip',
                'enable_overview_link'   => 'enableOverviewLink',
                'enable_chart_link'      => 'enableChartLink',
                'enable_legend'          => 'enableLegend',
            ];
            foreach ($boolMap as $cfgKey => $viewKey) {
                $viewData[$viewKey] = (bool)($config[$cfgKey] ?? $viewData[$viewKey] ?? true);
            }

            // Default selections → view expects these
            $viewData['defaultType']         = $config['default_type'] ?? null;
            $viewData['defaultSort']         = $config['default_sort'] ?? null;
            $viewData['defaultColor']        = $config['default_color'] ?? null;
            $viewData['defaultPerPage']      = $config['default_per_page'] ?? null;
            $viewData['defaultColorMode']    = $config['default_color_mode'] ?? 'fixed';
            $viewData['defaultShowLogo']     = (bool)($config['default_show_logo'] ?? true);
            $viewData['defaultDisplayName']  = $config['default_display_name'] ?? 'name';
            $viewData['defaultDisplayValue'] = $config['default_display_value'] ?? 'selected';
            $viewData['defaultBorderRadius'] = (bool)($config['default_border_radius'] ?? false);
            $viewData['defaultPrimaryListing'] = (bool)($config['default_is_primary'] ?? false);
            $viewData['defaultCountry']        = $config['default_country'] ?? 'US';
            $viewData['defaultIndices']        = $config['default_indices'] ?? '';
            $viewData['defaultIndicesName']    = $config['default_indices_name'] ?? '';
            $viewData['defaultIndicesLogo']    = $config['default_indices_logo'] ?? '';
            $viewData['defaultSector']         = $config['default_sector'] ?? '';

            return $viewData;
        },

        // JS config builder — heatmap-specific values
        'buildJsConfig' => function(array $config) use ($heatmapType): array {
            return [
                'HEATMAP_TYPE' => $heatmapType,
            ];
        },

        'settings' => [
            'data' => [
                'label'  => 'Data',
                'pkg'    => 1,
                'fields' => [
                    ...($isStock ? [
                        'default_country' => [
                            'type'        => 'select',
                            'label'       => 'Country',
                            'description' => 'Stocks from this country will be shown (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'] ?? [],
                        ],
                        'default_indices' => [
                            'type'        => 'ajax-select',
                            'label'       => 'Index',
                            'description' => 'Show stocks from a specific index (e.g. S&P 500, NASDAQ 100). "All Indices" shows everything.',
                            'default'     => '',
                            'empty_label' => 'All Indices',
                            'key'         => 'default_indices',
                            'pkg'         => 1,
                            'searchable'  => true,
                            'api'         => 'stock/indices',
                            'api_params'  => [
                                'country' => 'US',
                                'filters' => '{"profile.stocks_count_gt": 10}',
                                'columns' => 'profile.name,profile.self_logo',
                            ],
                            'value_key'   => 'ticker',
                            'label_key'   => 'profile.name',
                            'icon_key'    => 'profile.self_logo',
                            'depends_on'   => 'default-country',
                            'depend_param' => 'country',
                            'embed_extras' => true,
                        ],
                        'default_sector' => [
                            'type'        => 'select',
                            'label'       => 'Sector',
                            'description' => 'Filter by industry sector (e.g. Technology, Healthcare). "All Sectors" shows everything.',
                            'default'     => '',
                            'key'         => 'default_sector',
                            'pkg'         => 1,
                            'searchable'  => true,
                            'source'      => 'sectors',
                            'options'     => ['' => 'All Sectors'],
                        ],
                    ] : [
                        'default_type' => [
                            'type'        => 'select',
                            'label'       => 'Category',
                            'description' => 'Which type of crypto to show (e.g. all coins, DeFi only, meme coins). Visitors can change it.',
                            'default'     => 'coin',
                            'key'         => 'default_type',
                            'pkg'         => 1,
                            'options'     => $typeOptions,
                        ],
                    ]),
                    'default_sort' => [
                        'type'        => 'select',
                        'label'       => 'Sort By',
                        'description' => 'How items are arranged in the heatmap. Larger blocks appear first.',
                        'default'     => 'market_cap',
                        'key'         => 'default_sort',
                        'pkg'         => 1,
                        'options'     => $sortOptions,
                    ],
                    'default_color' => [
                        'type'        => 'select',
                        'label'       => 'Color Metric',
                        'description' => 'What determines each block\'s color. E.g. "Change 1D %" colors by today\'s price change.',
                        'default'     => 'active.chp|1d',
                        'key'         => 'default_color',
                        'pkg'         => 1,
                        'options'     => $colorSelectOptions,
                    ],
                    'default_per_page' => [
                        'type'        => 'select',
                        'label'       => 'Items Per Page',
                        'description' => 'How many blocks to show. More items = more data but slower load. Visitors can change this.',
                        'default'     => '100',
                        'key'         => 'default_per_page',
                        'pkg'         => 1,
                        'options'     => ['10' => '10', '25' => '25', '50' => '50', '100' => '100', '200' => '200'],
                    ],
                    'auto_update' => [
                        'type'        => 'toggle',
                        'label'       => 'Auto Update',
                        'description' => 'Automatically refresh data every 1 minute.',
                        'default'     => false,
                        'key'         => 'auto_update',
                        'pkg'         => 1,
                    ],
                    ...($isStock ? [
                        'default_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'     => 'default_is_primary',
                            'pkg'     => 1,
                        ],
                    ] : []),
                ],
            ],
            'display' => [
                'label'  => 'Display',
                'pkg'    => 1,
                'fields' => [
                    ...(!$isStock ? [
                        'enable_type_select' => [
                            'type'        => 'toggle',
                            'label'       => 'Show Type Picker',
                            'description' => 'Show a dropdown in the toolbar to switch between crypto categories (Coins, DeFi, etc.).',
                            'default'     => true,
                            'key'         => 'enable_type_select',
                            'pkg'         => 1,
                        ],
                    ] : []),
                    'enable_sort_select' => [
                        'type'        => 'toggle',
                        'label'       => 'Show Sort Picker',
                        'description' => 'Show a dropdown in the toolbar to change the sorting order.',
                        'default'     => true,
                        'key'         => 'enable_sort_select',
                        'pkg'         => 1,
                    ],
                    'enable_color_select' => [
                        'type'        => 'toggle',
                        'label'       => 'Show Color Picker',
                        'description' => 'Show a dropdown in the toolbar to change which metric colors the blocks.',
                        'default'     => true,
                        'key'         => 'enable_color_select',
                        'pkg'         => 1,
                    ],
                    'enable_per_page_select' => [
                        'type'        => 'toggle',
                        'label'       => 'Show Items Per Page Picker',
                        'description' => 'Show a dropdown in the toolbar to change how many items are displayed.',
                        'default'     => true,
                        'key'         => 'enable_per_page_select',
                        'pkg'         => 1,
                    ],
                    ...($isStock ? [
                        'enable_indices_select' => [
                            'type'        => 'toggle',
                            'label'       => 'Show Index Picker',
                            'description' => 'Show a dropdown in the toolbar to filter by stock index.',
                            'default'     => true,
                            'key'         => 'enable_indices_select',
                            'pkg'         => 1,
                        ],
                        'enable_sector_select' => [
                            'type'        => 'toggle',
                            'label'       => 'Show Sector Picker',
                            'description' => 'Show a dropdown in the toolbar to filter by market sector.',
                            'default'     => true,
                            'key'         => 'enable_sector_select',
                            'pkg'         => 1,
                        ],
                        'enable_country_select' => [
                            'type'        => 'toggle',
                            'label'       => 'Show Country Picker',
                            'description' => 'Show a dropdown in the toolbar to switch between country markets.',
                            'default'     => true,
                            'key'         => 'enable_country_select',
                            'pkg'         => 1,
                        ],
                        'enable_primary_toggle' => [
                            'type'        => 'toggle',
                            'label'       => 'Show Primary Listing Toggle',
                            'description' => 'Let visitors toggle primary-only listing on/off from the toolbar.',
                            'default'     => true,
                            'key'         => 'enable_primary_toggle',
                            'pkg'         => 1,
                        ],
                    ] : []),
                    'enable_settings' => [
                        'type'        => 'toggle',
                        'label'       => 'Show Settings',
                        'description' => 'Show a gear icon in the toolbar. Lets visitors change logo, color mode, and block labels.',
                        'default'     => true,
                        'key'         => 'enable_settings',
                        'pkg'         => 1,
                    ],
                    'enable_screenshot' => [
                        'type'        => 'toggle',
                        'label'       => 'Show Screenshot Button',
                        'description' => 'Show a camera button in the toolbar to download the heatmap as an image.',
                        'default'     => true,
                        'key'         => 'enable_screenshot',
                        'pkg'         => 1,
                    ],
                    'enable_fullscreen' => [
                        'type'        => 'toggle',
                        'label'       => 'Show Fullscreen Button',
                        'description' => 'Show a button in the toolbar to expand the heatmap to fullscreen.',
                        'default'     => true,
                        'key'         => 'enable_fullscreen',
                        'pkg'         => 1,
                    ],
                    'enable_zoom_controls' => [
                        'type'        => 'toggle',
                        'label'       => 'Show Zoom Controls',
                        'description' => 'Show zoom in, zoom out, and reset buttons in the toolbar.',
                        'default'     => true,
                        'key'         => 'enable_zoom_controls',
                        'pkg'         => 1,
                    ],
                    'enable_wheel_zoom' => [
                        'type'        => 'toggle',
                        'label'       => 'Scroll Wheel Zoom',
                        'description' => 'Allow visitors to zoom in and out of the heatmap using the mouse scroll wheel.',
                        'default'     => false,
                        'key'         => 'enable_wheel_zoom',
                        'pkg'         => 1,
                    ],
                    'enable_legend' => [
                        'type'        => 'toggle',
                        'label'       => 'Color Legend',
                        'description' => 'Show a color scale bar at the bottom of the heatmap explaining what the colors mean.',
                        'default'     => true,
                        'key'         => 'enable_legend',
                        'pkg'         => 1,
                    ],
                    'enable_hover_tooltip' => [
                        'type'        => 'toggle',
                        'label'       => 'Hover Info',
                        'description' => 'Show a small info box when the visitor hovers over a heatmap block.',
                        'default'     => true,
                        'key'         => 'enable_hover_tooltip',
                        'pkg'         => 1,
                    ],
                    'enable_click_tooltip' => [
                        'type'        => 'toggle',
                        'label'       => 'Click Info',
                        'description' => 'Show a detailed popup with price, change, and links when a visitor clicks on a heatmap block.',
                        'default'     => true,
                        'key'         => 'enable_click_tooltip',
                        'pkg'         => 1,
                    ],
                ],
            ],
            'layout' => [
                'label'  => 'Layout',
                'pkg'    => 1,
                'fields' => [
                    'default_show_logo' => [
                        'type'        => 'toggle',
                        'label'       => 'Show Logo',
                        'description' => 'Show the company or coin logo inside each colored block.',
                        'default'     => true,
                        'key'         => 'default_show_logo',
                        'pkg'         => 1,
                    ],
                    'default_border_radius' => [
                        'type'        => 'toggle',
                        'label'       => 'Rounded Corners',
                        'description' => 'Round the corners of each colored box in the heatmap grid.',
                        'default'     => false,
                        'key'         => 'default_border_radius',
                        'pkg'         => 1,
                    ],
                    'default_color_mode' => [
                        'type'        => 'select',
                        'label'       => 'Color Mode',
                        'description' => 'Fixed Steps: each range gets a solid color (e.g. -1% to 0% = light red). Gradient: colors blend smoothly based on exact value.',
                        'default'     => 'fixed',
                        'key'         => 'default_color_mode',
                        'pkg'         => 1,
                        'options'     => ['fixed' => 'Fixed Steps', 'gradient' => 'Gradient'],
                    ],
                    'default_display_name' => [
                        'type'        => 'select',
                        'label'       => 'Block Label',
                        'description' => 'Text shown inside each block. Symbol = short code (AAPL), Name = full name (Apple Inc).',
                        'default'     => $isStock ? 'symbol' : 'name',
                        'key'         => 'default_display_name',
                        'pkg'         => 1,
                        'options'     => ['symbol' => 'Symbol', 'name' => 'Name', 'none' => 'Hidden'],
                    ],
                    'default_display_value' => [
                        'type'        => 'select',
                        'label'       => 'Block Value',
                        'description' => 'Number shown below the label. "Selected Metric" shows the same value used for coloring (e.g. Change 1D %).',
                        'default'     => 'selected',
                        'key'         => 'default_display_value',
                        'pkg'         => 1,
                        'options'     => ['price' => 'Price', 'marketcap' => 'Market Cap', 'selected' => 'Selected Metric', 'none' => 'Hidden'],
                    ],
                ],
            ],
            'links' => [
                'label'  => 'Click Behavior',
                'pkg'    => 1,
                'fields' => [
                    'enable_overview_link' => array_merge($vunelix_shared['fields']['enable_links'], [
                        'label'       => 'Show Overview Link',
                        'description' => 'Show an overview link in the click popup for each heatmap block.',
                        'key'         => 'enable_overview_link',
                    ]),
                    'enable_chart_link' => array_merge($vunelix_shared['fields']['enable_links'], [
                        'label'       => 'Show Chart Link',
                        'description' => 'Show a chart link in the click popup for each heatmap block.',
                        'key'         => 'enable_chart_link',
                    ]),
                    'overview_url' => array_merge($vunelix_shared['fields']['link_url'], [
                        'label'       => 'Overview URL',
                        'description' => 'Your custom page URL for the overview link in the popup. E.g. yoursite.com/stocks/{{symbol}} becomes yoursite.com/stocks/AAPL. Leave empty for Vunelix page.',
                        'key'         => 'overview_url',
                        'placeholder' => 'https://yoursite.com/stocks/{{symbol}}',
                        'tokens'      => ['symbol', 'name', 'exchange', 'ticker', 'type'],
                    ]),
                    'chart_url' => array_merge($vunelix_shared['fields']['link_url'], [
                        'label'       => 'Chart URL',
                        'description' => 'Your custom chart page URL in the popup. E.g. yoursite.com/chart/{{ticker}} becomes yoursite.com/chart/NASDAQ:AAPL. Leave empty for Vunelix chart.',
                        'key'         => 'chart_url',
                        'placeholder' => 'https://yoursite.com/chart/{{ticker}}',
                        'tokens'      => ['symbol', 'name', 'exchange', 'ticker', 'type'],
                    ]),
                    'link_target' => array_merge($vunelix_shared['fields']['link_target'], [
                        'pkg'         => 1,
                        'description' => 'Applies to Overview URL only. Chart URL always opens in a new tab.',
                    ]),
                ],
            ],
            'storage' => $vunelix_shared['groups']['storage'],
        ],
    ];
}
