const { $, showView, showFlash, escapeHtml, goBack } = require("./helpers");
const { getTopTokens } = require("../../shared/tokenList");
const { state, saveState } = require("../../shared/state");
const { lookupTokenInfo } = require("../../shared/balances");
const { isScamAddress } = require("../../shared/scamlist");
const { log } = require("../../shared/log");

function show() {
    $("add-token-address").value = "";
    $("add-token-info").textContent = "";
    $("add-token-info").style.visibility = "hidden";
    const list = $("common-token-list");
    list.innerHTML = getTopTokens(25)
        .map(
            (t) =>
                `<button class="common-token border border-border px-1 hover:bg-fg hover:text-bg cursor-pointer text-xs" data-address="${escapeHtml(t.address)}" data-symbol="${escapeHtml(t.symbol)}" data-decimals="${escapeHtml(t.decimals)}">${escapeHtml(t.symbol)}</button>`,
        )
        .join("");
    list.querySelectorAll(".common-token").forEach((btn) => {
        btn.addEventListener("click", () => {
            $("add-token-address").value = btn.dataset.address;
        });
    });
    showView("add-token");
}

function init(ctx) {
    $("btn-add-token-confirm").addEventListener("click", async () => {
        const contractAddr = $("add-token-address").value.trim();
        if (!contractAddr || !contractAddr.startsWith("0x")) {
            showFlash(
                "Please enter a valid contract address starting with 0x.",
            );
            return;
        }
        const already = state.trackedTokens.find(
            (t) => t.address.toLowerCase() === contractAddr.toLowerCase(),
        );
        if (already) {
            showFlash(already.symbol + " is already being tracked.");
            return;
        }
        if (isScamAddress(contractAddr)) {
            showFlash("This address is on a known scam/fraud list.");
            return;
        }
        const infoEl = $("add-token-info");
        infoEl.textContent = "Looking up token...";
        infoEl.style.visibility = "visible";
        log.debugf("Looking up token contract", contractAddr);
        try {
            const info = await lookupTokenInfo(
                contractAddr,
                state.rpcUrl,
                state.networkId,
            );
            log.infof("Adding token", info.symbol, contractAddr);
            state.trackedTokens.push({
                address: contractAddr,
                symbol: info.symbol,
                decimals: info.decimals,
                name: info.name,
            });
            await saveState();
            ctx.doRefreshAndRender();
            // Pop the stack (back to address detail) and re-render it
            // so the newly added token is visible immediately.
            if (state.viewStack.length > 0) {
                state.viewStack.pop();
            }
            require("./addressDetail").show();
        } catch (e) {
            const detail = e.shortMessage || e.message || String(e);
            log.errorf("Token lookup failed for", contractAddr, detail);
            showFlash(detail);
            infoEl.textContent = "";
            infoEl.style.visibility = "hidden";
        }
    });

    $("btn-add-token-back").addEventListener("click", () => {
        goBack();
    });
}

module.exports = { init, show };
