/**
 * index.js - Wallet connection and character selection interface
 *
 * IMPORTANT: This file is hosted on Vercel (externally), NOT served from the extension.
 * Therefore, it does NOT have access to Chrome extension APIs (chrome.runtime, etc.).
 *
 * Communication with the extension happens via window.postMessage:
 *   index.js <-> dapp_content_script.js (injected by extension) <-> background.js
 *
 * When updating this file, deploy to Vercel for changes to take effect.
 */

document.addEventListener('DOMContentLoaded', () => {
    // --- Elements ---
    const connectWalletBtn = document.getElementById('connect-wallet-btn');
    const networkBadge = document.getElementById('network-badge');
    const accountBadge = document.getElementById('account-badge');
    const accountDisplay = document.getElementById('account-display');
    const accountTooltip = document.getElementById('account-tooltip');
    const statusCard = document.getElementById('status-card');
    const statusIcon = document.getElementById('status-icon');
    const statusTitle = document.getElementById('status-title');
    const statusMessage = document.getElementById('status-message');
    const statusActionBtn = document.getElementById('status-action-btn');
    const characterSection = document.getElementById('character-section');
    const characterGrid = document.getElementById('character-grid');
    const refreshBtn = document.getElementById('refresh-btn');

    // --- State ---
    let provider;
    let signer;
    let currentAccount = null;
    let currentCharacter = 'shimeji';
    let unlockedCharacters = { shimeji: true };

    // --- Constants ---
    const ARBITRUM_MAINNET_CHAIN_ID = 42161;

    const CHARACTERS = {
        shimeji: { name: 'Shimeji', icon: 'characters/shimeji/icon.png', alwaysUnlocked: true }
    };

    // --- Message Communication with Extension ---
    function sendMessageToExtension(type, payload) {
        console.log('[Index] Sending message via postMessage:', type, payload);
        window.postMessage({ type: 'DAPP_MESSAGE', payload: { type, payload } }, '*');
    }

    window.addEventListener('message', (event) => {
        if (event.source !== window) return;

        const data = event.data;
        if (!data || !data.type) return;

        console.log('[Index] Received message:', data);

        if (data.type === 'EXTENSION_RESPONSE') {
            if (data.payload) {
                if (data.payload.character) {
                    currentCharacter = data.payload.character;
                    renderCharacterGrid();
                }
                if (data.payload.payload && data.originalType === 'getUnlockedCharacters') {
                    console.log('[Index] Processing getUnlockedCharacters response:', data.payload.payload);
                    unlockedCharacters = data.payload.payload;
                    renderCharacterGrid();
                }
            }
        } else if (data.type === 'EXTENSION_MESSAGE') {
            if (data.payload) {
                if (data.payload.type === 'disconnectFromBackground' || data.payload.type === 'revokePermissionsFromBackground') {
                    disconnectWallet();
                } else if (data.payload.type === 'updateUnlockedCharacters') {
                    console.log('[Index] Processing updateUnlockedCharacters push:', data.payload.payload);
                    unlockedCharacters = data.payload.payload;
                    renderCharacterGrid();
                }
            }
        }
    });

    // --- Character Grid ---
    function renderCharacterGrid() {
        characterGrid.innerHTML = '';

        Object.entries(CHARACTERS).forEach(([id, char]) => {
            const isUnlocked = char.alwaysUnlocked || unlockedCharacters[id];
            const isSelected = currentCharacter === id;

            const card = document.createElement('div');
            card.className = 'character-card';
            if (isSelected) card.classList.add('selected');
            if (!isUnlocked) card.classList.add('locked');
            card.dataset.character = id;

            card.innerHTML = `
                <img src="${char.icon}" alt="${char.name}">
                <span class="name">${char.name}</span>
                <span class="status">${isSelected ? 'Active' : (isUnlocked ? 'Owned' : 'Locked')}</span>
            `;

            if (isUnlocked) {
                card.addEventListener('click', () => selectCharacter(id));
            } else {
                card.addEventListener('click', () => {
                    alert('This character is locked. Visit the marketplace to mint the NFT and unlock it!');
                });
            }

            characterGrid.appendChild(card);
        });
    }

    function selectCharacter(characterId) {
        currentCharacter = characterId;
        sendMessageToExtension('setCharacter', { character: characterId });
        renderCharacterGrid();
    }

    // --- Refresh Button ---
    refreshBtn.addEventListener('click', () => {
        refreshBtn.classList.add('spinning');

        // Re-check NFT ownership by re-sending wallet connected message
        if (currentAccount && provider) {
            provider.getNetwork().then(network => {
                sendMessageToExtension('walletConnected', {
                    account: currentAccount,
                    chainId: network.chainId
                });
            });
        }

        // Also request fresh data
        sendMessageToExtension('getUnlockedCharacters', null);
        sendMessageToExtension('getCharacter', null);

        // Stop spinning after a delay
        setTimeout(() => {
            refreshBtn.classList.remove('spinning');
        }, 1000);
    });

    // --- Wallet Connection ---
    async function connectWallet() {
        console.log('[Index] connectWallet called');

        if (typeof window.ethereum === 'undefined') {
            alert('Please install MetaMask or another Ethereum wallet to connect.');
            window.open('https://metamask.io/download/', '_blank');
            return;
        }

        try {
            const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
            console.log('[Index] Accounts received:', accounts);

            if (accounts.length === 0) {
                throw new Error('No accounts returned');
            }

            currentAccount = accounts[0];
            provider = new ethers.providers.Web3Provider(window.ethereum);
            signer = provider.getSigner();
            const network = await provider.getNetwork();

            // Check if on Arbitrum
            if (network.chainId !== ARBITRUM_MAINNET_CHAIN_ID) {
                alert('Please switch to Arbitrum One network.');
                try {
                    await window.ethereum.request({
                        method: 'wallet_switchEthereumChain',
                        params: [{ chainId: '0x' + ARBITRUM_MAINNET_CHAIN_ID.toString(16) }]
                    });
                    // Retry connection after switch
                    await connectWallet();
                    return;
                } catch (switchError) {
                    if (switchError.code === 4902) {
                        alert('Arbitrum One network not found. Please add it to your wallet.');
                    }
                    return;
                }
            }

            // Update UI to connected state
            showConnectedUI(currentAccount, network.chainId);

            // Notify extension
            sendMessageToExtension('walletConnected', {
                account: currentAccount,
                chainId: network.chainId
            });

        } catch (error) {
            console.error('[Index] Connection error:', error);
            if (error.code === 4001) {
                alert('Connection rejected by user.');
            } else {
                alert('Failed to connect wallet: ' + (error.message || error));
            }
        }
    }

    async function disconnectWallet() {
        try {
            await window.ethereum.request({
                method: 'wallet_revokePermissions',
                params: [{ eth_accounts: {} }]
            });
        } catch (e) {
            console.error('[Index] Revoke error:', e);
        }

        currentAccount = null;
        provider = null;
        signer = null;
        unlockedCharacters = { shimeji: true };

        showDisconnectedUI();
        sendMessageToExtension('walletDisconnected', null);
    }

    function showConnectedUI(account, chainId) {
        const shortAddress = `${account.substring(0, 6)}...${account.substring(account.length - 4)}`;

        // Header
        accountDisplay.textContent = shortAddress;
        accountTooltip.textContent = account;
        accountBadge.classList.remove('hidden');

        if (chainId === ARBITRUM_MAINNET_CHAIN_ID) {
            networkBadge.classList.remove('hidden');
        } else {
            networkBadge.classList.add('hidden');
        }

        connectWalletBtn.textContent = 'Disconnect';
        connectWalletBtn.classList.add('connected');

        // Status card - hide it when connected
        statusCard.classList.add('connected');

        // Show character section
        characterSection.style.display = 'block';
    }

    function showDisconnectedUI() {
        // Header
        accountDisplay.textContent = '';
        accountTooltip.textContent = '';
        accountBadge.classList.add('hidden');
        networkBadge.classList.add('hidden');
        connectWalletBtn.textContent = 'Connect Wallet';
        connectWalletBtn.classList.remove('connected');

        // Status card - show it
        statusCard.classList.remove('connected');

        // Reset character grid
        renderCharacterGrid();
    }

    // --- Event Listeners ---
    connectWalletBtn.addEventListener('click', () => {
        if (connectWalletBtn.textContent === 'Connect Wallet') {
            connectWallet();
        } else {
            disconnectWallet();
        }
    });

    statusActionBtn.addEventListener('click', () => {
        connectWallet();
    });

    // --- Ethereum Event Listeners ---
    if (typeof window.ethereum !== 'undefined') {
        window.ethereum.on('accountsChanged', (accounts) => {
            if (accounts.length > 0) {
                currentAccount = accounts[0];
                if (provider) {
                    provider.getNetwork().then(network => {
                        showConnectedUI(currentAccount, network.chainId);
                        sendMessageToExtension('walletConnected', {
                            account: currentAccount,
                            chainId: network.chainId
                        });
                    });
                }
            } else {
                disconnectWallet();
            }
        });

        window.ethereum.on('chainChanged', (chainId) => {
            const numericChainId = parseInt(chainId, 16);
            if (currentAccount) {
                showConnectedUI(currentAccount, numericChainId);
                sendMessageToExtension('walletConnected', {
                    account: currentAccount,
                    chainId: numericChainId
                });
            }
        });

        // Auto-connect if already connected
        window.ethereum.request({ method: 'eth_accounts' }).then(accounts => {
            if (accounts.length > 0) {
                currentAccount = accounts[0];
                provider = new ethers.providers.Web3Provider(window.ethereum);
                signer = provider.getSigner();
                provider.getNetwork().then(network => {
                    showConnectedUI(currentAccount, network.chainId);
                    sendMessageToExtension('walletConnected', {
                        account: currentAccount,
                        chainId: network.chainId
                    });
                });
            }
        }).catch(err => console.error('[Index] Auto-connect error:', err));
    }

    // --- Initial Load ---
    sendMessageToExtension('getUnlockedCharacters', null);
    sendMessageToExtension('getCharacter', null);
    renderCharacterGrid();
});
