// Get a list of all the wallets available
// Try to connect to window.solana and window.solflare

const solflareWallet = window.solflare;
const phantomWallet = window.solana;    

var wallets = [];
// Check which are valid
if (phantomWallet && phantomWallet.isPhantom) {
    console.log("Phantom wallet found");
    wallets.push("Phantom");
}
if (solflareWallet && solflareWallet.isSolflare) {
    console.log("Solflare wallet found");
    wallets.push("Solflare");
}

async function connectPhantomWallet() {
    try {
        const { publicKey } = await phantomWallet.connect();
        console.log("Connected to Phantom wallet with public key", publicKey.toBase58());
        return publicKey.toBase58();
    }
    catch (err) {
        console.error("Wallet connection failed", err);
    }
}

async function connectSolflareWallet() {
    try {
        await solflareWallet.connect();        
        const publicKey = solflareWallet.publicKey.toBase58();
        console.log("Connected to Solflare wallet with public key", publicKey);
        return publicKey;
    }
    catch (err) {
        console.error("Wallet connection failed", err);
    }
}


// Inject buttons to connect the wallets
function injectButtons() {
    // Get div to hold buttons
    var div = document.getElementById("wallet-buttons");
    if (!div) {
        return;
    }
    // Clear the div
    div.innerHTML = "";
    
    // If no wallets found, add message
    if (wallets.length == 0) {
        var p = document.createElement("p");
        p.innerText = "No wallets found";
        div.appendChild(p);
        return;
    }
    
    // Add buttons for each wallet
    for (var i = 0; i < wallets.length; i++) {
        var button = document.createElement("button");
        button.className = "btn btn-primary";
        button.style.margin = "5px";
        button.innerText = wallets[i];
        if (wallets[i] == "Phantom") {
            button.onclick = async function () {
                var publicKey = await connectPhantomWallet();
                if (publicKey) {
                    window.location.href = "/?publicKey=" + publicKey;
                }
            };
        };
        if (wallets[i] == "Solflare") {
            button.onclick = async function () {
                var publicKey = await connectSolflareWallet();
                if (publicKey) {
                    window.location.href = "/?publicKey=" + publicKey;
                }
            };
        };
        div.appendChild(button);
    }
    console.log("Wallet buttons injected");
}

// Wait for page to load
window.addEventListener("load", injectButtons);