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

class VunelivSingleTicker extends VunelivBase {
    static slug="single-ticker";
    static widgetCss=[ "widgets/single-ticker" ];
    getSkeletonHtml() {
        const showFlag = this.dataset.show_flag !== "false" && this.dataset.showFlag !== "false";
        const showSymbol = this.dataset.show_symbol !== "false" && this.dataset.showSymbol !== "false";
        const showName = this.dataset.show_full_name !== "false" && this.dataset.showFullName !== "false";
        const showChange = this.dataset.show_change !== "false" && this.dataset.showChange !== "false";
        return `\n            <div id="single-ticker-widget" class="single-ticker-widget">\n                <div class="st-header" aria-hidden="true">\n                    ${showFlag ? `\n                        <div class="st-logo">\n                            <div class="search-result-icon-container">\n                                <span class="skeleton skeleton-circle"></span>\n                            </div>\n                        </div>` : ""}\n                    <div class="st-info">\n                        ${showName ? '<div class="st-name-row"><span class="skeleton skeleton-text-lg" style="width:140px"></span></div>' : ""}\n                        ${showSymbol ? '<div class="st-symbol-row"><span class="skeleton skeleton-text-sm" style="width:80px"></span></div>' : ""}\n                        <div class="st-price-row">\n                            <span class="skeleton skeleton-text" style="width:120px;height:2em"></span>\n                            ${showChange ? '<span class="skeleton skeleton-text" style="width:60px"></span><span class="skeleton skeleton-text-sm" style="width:70px"></span>' : ""}\n                        </div>\n                    </div>\n                </div>\n            </div>`;
    }
    onReady(root, config) {
        this._root = root;
        this._config = config;
        this._symbol = config.symbol || "CRYPTO:BTCUSD";
        if (typeof this._symbol === "string") {
            this._symbol = this._symbol.split(",")[0].trim();
        }
        this._els = {
            widget: root.querySelector("#single-ticker-widget"),
            header: root.querySelector(".st-header")
        };
        if (!this._els.widget) return;
        this.#fetchSymbolData();
    }
    async #fetchSymbolData() {
        try {
            const result = await this.widgetSendPostRequest(`${this._config.API_ENDPOINT}forex/advance/`, {
                symbol: this._symbol,
                type: "global",
                columns: "active.c,active.ch,active.chp,profile,ticker",
                period: "1d",
                per_page: 1
            });
            if (result?.status && result.response?.length) {
                this.#renderHeader(result.response[0]);
            }
        } catch (error) {
            console.error("SingleTicker: Failed to load symbol data", error);
        }
    }
    #renderHeader(data) {
        const config = this._config;
        const showFlag = config.showFlag !== false;
        const showSymbol = config.showSymbol !== false;
        const showName = config.showFullName !== false;
        const showChange = config.showChange !== false;
        const price = data.active?.c;
        const change = data.active?.ch;
        const chp = data.active?.chp;
        const priceChangeClass = typeof window.getValueStyle === "function" ? window.getValueStyle(change, "class") : change > 0 ? "fx-positive" : change < 0 ? "fx-negative" : "fx-neutral";
        const changeSign = change > 0 ? "+" : change < 0 ? "−" : "";
        const shortForm = typeof window.convertNumberToShortForm === "function" ? window.convertNumberToShortForm(Math.abs(change)) : Math.abs(change);
        const chpSign = chp > 0 ? "+" : chp < 0 ? "−" : "";
        const chpFormatted = typeof window.convertNumberToShortForm === "function" ? window.convertNumberToShortForm(Math.abs(chp), true, 2) : Math.abs(chp).toFixed(2);
        const priceFormatted = price ? addThousandSeparator(String(price)) : "—";
        let logoHtml = "";
        if (showFlag && typeof window.generateCoinLogoHtml === "function") {
            logoHtml = `<div class="st-logo"><div class="search-result-icon-container">${window.generateCoinLogoHtml(data.profile)}</div></div>`;
        }
        const ticker = data.ticker || this._symbol;
        const displaySymbol = ticker.includes(":") ? ticker.split(":")[1] : ticker;
        const fullName = data.profile?.name || displaySymbol;
        const currency = data.profile?.currency || "";
        const wsClass = ticker.replace(/[^a-zA-Z0-9]/g, "_");
        this._els.header.removeAttribute("aria-hidden");
        this._els.header.innerHTML = `\n            ${logoHtml}\n            <div class="st-info" data-ticker="${ticker}">\n                ${showName ? `<div class="st-name-row"><h3 class="st-full-name">${fullName}</h3></div>` : ""}\n                ${showSymbol ? `<div class="st-symbol-row"><span class="st-symbol">${displaySymbol}</span></div>` : ""}\n                <div class="st-price-row">\n                    <div class="st-price-main">\n                        <span class="st-price ${wsClass}_C_1D">${priceFormatted}</span>\n                        ${currency ? `<span class="st-currency">${currency}</span>` : ""}\n                    </div>\n                    ${showChange && change != null ? `\n                        <div class="st-price-change">\n                            <span class="st-change ${priceChangeClass} ${wsClass}_CH_1D">\n                                <span class="sign">${changeSign}</span>${shortForm}\n                            </span>\n                            <span class="st-change ${priceChangeClass} ${wsClass}_CHP_1D">\n                                <span class="sign">${chpSign}</span>${chpFormatted}%\n                            </span>\n                        </div>` : ""}\n                </div>\n            </div>`;
        if (this._webSocket) {
            this._webSocket.subscribeAllSymbols();
        }
    }
}

customElements.define("vunelix-single-ticker", VunelivSingleTicker);