const {
    $,
    showView,
    showFlash,
    flashCopyFeedback,
    formatAddressHtml,
    addressTitle,
    displaySymbol,
    attachCopyHandlers,
    goBack,
} = require("./helpers");
const { state, currentAddress, currentNetwork } = require("../../shared/state");
const QRCode = require("qrcode");

function show() {
    const addr = currentAddress();
    const address = addr ? addr.address : "";
    const title = address ? addressTitle(address, state.wallets) : null;
    const ensName = addr ? addr.ensName || null : null;
    $("receive-address-block").innerHTML = address
        ? formatAddressHtml(address, ensName, null, title)
        : "";
    $("receive-address-block").dataset.full = address;
    // Etherscan link is now included in formatAddressHtml via renderAddressHtml
    $("receive-etherscan-link").innerHTML = "";
    if (address) {
        QRCode.toCanvas($("receive-qr"), address, {
            width: 200,
            margin: 2,
            color: { dark: "#000000", light: "#ffffff" },
        });
    }
    const warningEl = $("receive-erc20-warning");
    if (state.selectedToken && state.selectedToken !== "ETH") {
        // Look up symbol from address token balances
        const addrObj = currentAddress();
        let symbol = state.selectedToken;
        if (addrObj) {
            const tb = (addrObj.tokenBalances || []).find(
                (t) =>
                    t.address.toLowerCase() ===
                    state.selectedToken.toLowerCase(),
            );
            if (tb) symbol = tb.symbol;
        }
        warningEl.textContent =
            "This is an ERC-20 token. Only send " +
            displaySymbol(symbol) +
            " on " +
            currentNetwork().name +
            " to this address. Sending tokens on other networks will result in permanent loss.";
        warningEl.style.visibility = "visible";
    } else {
        warningEl.textContent = "";
        warningEl.style.visibility = "hidden";
    }
    showView("receive");
    attachCopyHandlers("view-receive");
}

function init(_ctx) {
    $("btn-receive-copy").addEventListener("click", () => {
        const addr = $("receive-address-block").dataset.full;
        if (addr) {
            navigator.clipboard.writeText(addr);
            showFlash("Copied!");
            flashCopyFeedback($("receive-address-block"));
        }
    });

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

module.exports = { init, show };
