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

import { MarketMovers } from "../../components/market-movers.js";

export class VunelivMarketMoversBase extends VunelivBase {
    static widgetCss=[ "components/market-movers" ];
    static marketType="crypto";
    static branding_bar=true;
    getSkeletonHtml() {
        const symbols = this.dataset.symbols;
        let perPage = symbols ? symbols.split(",").filter(s => s.trim()).length : parseInt(this.dataset.per_page || this.dataset.perPage) || 12;
        const gridCols = parseInt(this.dataset.grid_cols || this.dataset.gridCols) || this.constructor.defaultGridCols || 3;
        if (perPage > 12) {
            perPage = 12;
        }
        const showLogo = (this.dataset.show_logo ?? this.dataset.showLogo ?? "true") !== "false";
        let cards = "";
        for (let i = 0; i < perPage; i++) {
            cards += `\n                <div class="market-mover-card skeleton-card" aria-hidden="true">\n                    <div class="mover-left">\n                        ${showLogo ? '<span class="skeleton skeleton-circle"></span>' : ""}\n                        <div class="mover-info">\n                            <span class="skeleton skeleton-mover-symbol"></span>\n                            <span class="skeleton skeleton-mover-name"></span>\n                        </div>\n                    </div>\n                    <div class="mover-right">\n                        <span class="skeleton skeleton-mover-price"></span>\n                        <span class="skeleton skeleton-mover-change"></span>\n                    </div>\n                </div>`;
        }
        return `<div class="market-movers-container" id="widget-market-movers" aria-busy="true"><div class="market-movers-grid${gridCols ? " grid-cols-" + gridCols : ""}">${cards}</div></div>`;
    }
    onReady(root, config) {
        const container = root.querySelector("#widget-market-movers");
        if (!container) return;
        if (config.showBorder === false) {
            container.style.border = "none";
        }
        const marketType = this.constructor.marketType;
        const hasSymbols = !!config.symbols;
        const assetType = config.assetType || marketType;
        const metrics = config.metrics ? config.metrics.split(",").map(m => m.trim()) : [ "active.c", "active.chp" ];
        const baseColumns = "profile.currency,profile.self_logo,active.c,active.ch,active.chp,active.v,active.a,active.b,profile.name,profile.symbol,profile.curr_logo,profile.base_logo,profile.exchange";
        const extraCols = new Set;
        for (const m of metrics) {
            if (m.startsWith("perf.")) extraCols.add(m);
            if (m.startsWith("premarket.")) extraCols.add("premarket");
            if (m.startsWith("postmarket.")) extraCols.add("postmarket");
            if (m.startsWith("earnings.")) extraCols.add(m);
        }
        const sortBy = config.sortBy || "";
        if (sortBy.startsWith("perf.")) extraCols.add(sortBy.replace(/_(?:desc|asc)$/, ""));
        if (sortBy.startsWith("premarket.")) extraCols.add("premarket");
        if (sortBy.startsWith("postmarket.")) extraCols.add("postmarket");
        if (sortBy.startsWith("earnings.")) extraCols.add(sortBy.replace(/_(?:desc|asc)$/, ""));
        const apiParams = {
            columns: baseColumns + (extraCols.size ? "," + [ ...extraCols ].join(",") : ""),
            type: assetType,
            per_page: Math.min(parseInt(config.perPage) || 6, 12)
        };
        if (config.sortBy && config.sortBy !== "none") apiParams.sort_by = config.sortBy;
        if (hasSymbols) apiParams.symbol = config.symbols;
        if (config.country) apiParams.country = config.country;
        if (config.isPrimary) apiParams.is_primary = 1;
        if (config.filters) apiParams.filters = config.filters;
        const gridCols = parseInt(config.gridCols) || 0;
        const gridEl = container.querySelector(".market-movers-grid");
        if (gridEl && gridCols > 0) {
            gridEl.classList.add(`grid-cols-${gridCols}`);
        }
        new MarketMovers({
            CONTAINER: container,
            ROOT_NODE: root,
            API_TYPE: marketType,
            API_PARAMS: apiParams,
            METRICS: metrics,
            SHOW_SYMBOL: config.showSymbol !== false,
            SHOW_NAME: config.showName !== false,
            SHOW_LOGO: config.showLogo !== false,
            SHOW_CURRENCY: config.showCurrency !== false,
            CHANGE_BADGE: !!config.changeBadge,
            CARD_STYLE: config.cardStyle || "borderless",
            ENABLE_LINKS: config.enableLinks !== false,
            LINK_URL: config.linkUrl || null,
            LINK_TARGET: config.linkTarget || "_blank",
            webSocketInstance: this._webSocket,
            addThousandSeparator: addThousandSeparator,
            getValueStyle: window.getValueStyle,
            generateCoinLogoHtml: window.generateCoinLogoHtml,
            buildDynamicUrl: window.buildDynamicUrl,
            apiEndpoint: config.API_ENDPOINT || ""
        });
    }
}