import { VunelivBase } from "./vunelix-base.js";

import { CustomModal } from "../components/custom-modal.js";

import { MenuSearch } from "../components/menu-search.js";

if (!window.CustomModal) window.CustomModal = CustomModal;

class VunelivSymbolSearch extends VunelivBase {
    static slug="symbol-search";
    static useSocket=false;
    static showLoading=false;
    static branding_bar=false;
    static branding_path="symbol-search";
    static widgetCss=[];
    getSkeletonHtml() {
        return "";
    }
    onReady(root, config) {
        const searchConfig = config.SEARCH || {};
        const widget = this;
        const modalRoot = root;
        const triggerSelector = searchConfig.trigger || "";
        const triggerEl = triggerSelector ? document.querySelector(triggerSelector) : root.querySelector(".vnx-sw-demo-trigger");
        const modalId = "vnxSymSearch_" + Math.random().toString(36).slice(2, 8);
        const returnMode = searchConfig.enable_return_data === true;
        const showOverview = !returnMode && searchConfig.enable_overview_link !== false;
        const showChart = !returnMode && searchConfig.enable_chart_link === true;
        const showBtns = showOverview || showChart;
        const menuOpts = {
            rootNode: modalRoot,
            iconPath: config.ICON_PATH || "",
            iconType: config.ICON_TYPE || ".svg",
            useStorage: config.enableStorage !== false,
            storagePrefix: "vnxSymSearch",
            closeOnClick: true,
            placeholder: searchConfig.placeholder || "",
            showHoverButtons: showBtns,
            showOverviewButton: showOverview,
            showChartButton: showChart,
            onItemClick: function(data, clickedAction) {
                const profile = data.profile || {};
                const iconBase = "https://vunelix.com/assets/icons/";
                const iconType = ".svg";
                const baseLogo = profile.self_logo || profile.base_logo || "";
                const currLogo = profile.curr_logo || "";
                const excLogo = profile.exc_logo || "";
                const buildUrl = path => path ? path.startsWith("http") ? path : iconBase + path + iconType : "";
                const detail = {
                    ticker: data.ticker || "",
                    symbol: profile.symbol || "",
                    name: profile.name || "",
                    exchange: profile.exchange || "",
                    type: profile.type || "",
                    sub_type: profile.sub_type || "",
                    currency: profile.currency || "",
                    logo: buildUrl(baseLogo),
                    logo_quote: buildUrl(currLogo),
                    logo_exchange: buildUrl(excLogo),
                    logo_path: baseLogo,
                    logo_quote_path: currLogo,
                    logo_exchange_path: excLogo,
                    icon_base: iconBase
                };
                if (profile.sector) detail.sector = profile.sector;
                if (profile.isin) detail.isin = profile.isin;
                const target = searchConfig.link_target || "_blank";
                const replacePlaceholders = url => url.replace(/\{\{symbol\}\}/gi, detail.symbol).replace(/\{\{name\}\}/gi, encodeURIComponent(detail.name)).replace(/\{\{exchange\}\}/gi, detail.exchange).replace(/\{\{type\}\}/gi, detail.type).replace(/\{\{ticker\}\}/gi, detail.ticker);
                if (searchConfig.enable_return_data !== false) {
                    widget.dispatchEvent(new CustomEvent("vunelix-symbol-select", {
                        bubbles: true,
                        composed: true,
                        detail: detail
                    }));
                }
                if (clickedAction === "chart" && showChart) {
                    const chartUrl = searchConfig.chart_url ? replacePlaceholders(searchConfig.chart_url) : `https://vunelix.com/${detail.type}/${detail.exchange}/${detail.symbol}`;
                    window.open(chartUrl, "_blank");
                    return;
                }
                if (showOverview && searchConfig.overview_url) {
                    window.open(replacePlaceholders(searchConfig.overview_url), target);
                }
            }
        };
        if (searchConfig.filter_type) {
            menuOpts.filterTypes = [ searchConfig.filter_type ];
        }
        if (searchConfig.show_filters === false) {
            menuOpts.showFilterPills = false;
            menuOpts.showDropdownFilters = false;
            if (!searchConfig.filter_type) menuOpts.filterTypes = [ "global" ];
        }
        const filterKeys = [ "exchange", "country", "sub_type", "sector", "type" ];
        const defaults = {};
        filterKeys.forEach(key => {
            const val = searchConfig["default_" + key];
            if (val) defaults[key] = val;
        });
        if (Object.keys(defaults).length) {
            menuOpts.defaultDropdownFilters = defaults;
        }
        const search = new MenuSearch("#" + modalId, menuOpts);
        if (triggerEl) {
            triggerEl.addEventListener("click", () => search.open());
        }
    }
}

customElements.define("vunelix-symbol-search", VunelivSymbolSearch);