(async () => {
    const app = document.getElementById('app')

    // 상태 로드
    const stored = await chrome.storage.local.get(['worldland_keyring', 'accounts', 'chainId'])
    const wallets = stored.worldland_keyring?.wallets || []
    const accounts = wallets.map(w => w.address)
    const chainId = stored.chainId || '0x67'

    if (accounts.length === 0) {
        renderSetup()
    } else {
        renderWallet(accounts, chainId)
    }

    // storage 변경 감지 → 자동 업데이트
    chrome.storage.onChanged.addListener((changes) => {
        if (changes.accounts || changes.worldland_keyring || changes.chainId) {
            location.reload()
        }
    })

    // ──── 지갑 설정 (계정 없을 때) ────

    function renderSetup() {
        app.innerHTML =
            '<div class="wallet-header">' +
            '<div class="wallet-logo">🌍</div>' +
            '<div class="wallet-title">WorldLand Wallet</div>' +
            '<div class="wallet-subtitle">v1.0.0</div>' +
            '</div>' +
            '<div class="setup-section">' +
            '<p>지갑을 생성하거나 개인키를 가져와서 시작하세요</p>' +
            '<button class="setup-btn" id="btn-create">' +
            '<span class="emoji">✨</span> 새 지갑 생성' +
            '</button>' +
            '<button class="setup-btn" id="btn-import-toggle">' +
            '<span class="emoji">📥</span> 개인키로 가져오기' +
            '</button>' +
            '<div id="import-section" class="hidden">' +
            '<input class="import-input" id="pk-input" type="password" placeholder="개인키를 입력하세요 (0x...)">' +
            '<button class="btn btn-primary" id="btn-import">가져오기</button>' +
            '</div>' +
            '<button class="setup-btn" id="btn-mnemonic-toggle">' +
            '<span class="emoji">🔑</span> 복구구문으로 가져오기' +
            '</button>' +
            '<div id="mnemonic-section" class="hidden">' +
            '<textarea class="import-input" id="mnemonic-input" rows="3" style="resize:vertical" placeholder="12개 또는 24개 단어를 입력하세요"></textarea>' +
            '<button class="btn btn-primary" id="btn-mnemonic-import">가져오기</button>' +
            '</div>' +
            '<div id="result-section"></div>' +
            '</div>'

        document.getElementById('btn-create').addEventListener('click', async () => {
            const btn = document.getElementById('btn-create')
            btn.disabled = true
            btn.textContent = '생성 중...'
            const res = await chrome.runtime.sendMessage({
                source: 'worldland-wallet-approval',
                action: 'createWallet',
            })
            if (res.success) {
                document.getElementById('result-section').innerHTML =
                    '<div class="mnemonic-box">' +
                    '<h4>⚠️ 복구 구문을 안전하게 보관하세요!</h4>' +
                    '<p>' + res.mnemonic + '</p>' +
                    '</div>' +
                    '<div class="message success">✅ 지갑이 생성되었습니다</div>' +
                    '<p style="font-size:.78rem;color:#6b7280;margin-bottom:8px">주소: <span style="color:#667eea">' + res.address + '</span></p>'
                // 자동으로 상태 갱신
                setTimeout(() => location.reload(), 1500)
            } else {
                btn.disabled = false
                btn.textContent = '✨ 새 지갑 생성'
            }
        })

        document.getElementById('btn-import-toggle').addEventListener('click', () => {
            document.getElementById('import-section').classList.toggle('hidden')
        })

        document.getElementById('btn-import').addEventListener('click', async () => {
            const pk = document.getElementById('pk-input').value.trim()
            if (!pk) return
            const res = await chrome.runtime.sendMessage({
                source: 'worldland-wallet-approval',
                action: 'importWallet',
                privateKey: pk,
            })
            if (res.success) {
                document.getElementById('result-section').innerHTML =
                    '<div class="message success">✅ 지갑을 가져왔습니다</div>'
                setTimeout(() => location.reload(), 1000)
            } else {
                document.getElementById('result-section').innerHTML =
                    '<div class="message error">❌ ' + (res.error || '가져오기 실패') + '</div>'
            }
        })

        document.getElementById('btn-mnemonic-toggle').addEventListener('click', () => {
            document.getElementById('mnemonic-section').classList.toggle('hidden')
        })

        document.getElementById('btn-mnemonic-import').addEventListener('click', async () => {
            const mnemonic = document.getElementById('mnemonic-input').value.trim()
            if (!mnemonic) return
            const res = await chrome.runtime.sendMessage({
                source: 'worldland-wallet-approval',
                action: 'importFromMnemonic',
                mnemonic: mnemonic,
            })
            if (res.success) {
                document.getElementById('result-section').innerHTML =
                    '<div class="message success">✅ 복구구문으로 지갑을 가져왔습니다</div>'
                setTimeout(() => location.reload(), 1000)
            } else {
                document.getElementById('result-section').innerHTML =
                    '<div class="message error">❌ ' + (res.error || '가져오기 실패') + '</div>'
            }
        })
    }

    // ──── 메인 지갑 UI ────

    async function renderWallet(accounts, chainId) {
        const addr = accounts[0]
        const networkName = getNetworkName(chainId)

        app.innerHTML =
            '<div class="wallet-header">' +
            '<div class="wallet-logo">🌍</div>' +
            '<div class="wallet-title">WorldLand Wallet</div>' +
            '<span class="status-badge connected">● 연결됨</span>' +
            '</div>' +

            '<div class="network-bar">' +
            '<span class="network-name">' + networkName + '</span>' +
            '<span class="network-chain">' + chainId + '</span>' +
            '</div>' +

            '<div class="account-section">' +
            '<div class="account-label">내 계정</div>' +
            '<div class="account-addr" id="addr-copy" title="클릭하여 복사">' + addr + '</div>' +
            '<div class="copy-hint">클릭하여 주소 복사</div>' +
            '</div>' +

            '<div class="balance-section">' +
            '<div class="balance-label">잔액</div>' +
            '<div id="balance-display"><span class="balance-value">조회 중...</span></div>' +
            '</div>' +

            '<div class="btn-group">' +
            '<button class="btn btn-secondary btn-sm" id="btn-refresh">🔄 새로고침</button>' +
            '<button class="btn btn-secondary btn-sm" id="btn-network">🌐 네트워크</button>' +
            '</div>' +

            '<div class="divider"></div>' +

            '<button class="btn btn-primary" id="btn-add-wallet" style="margin-bottom:8px">' +
            '➕ 지갑 추가' +
            '</button>' +

            '<div id="add-wallet-section" class="hidden">' +
            '<button class="setup-btn" id="btn-create-more"><span class="emoji">✨</span> 새 지갑 생성</button>' +
            '<button class="setup-btn" id="btn-import-more-toggle"><span class="emoji">📥</span> 개인키로 가져오기</button>' +
            '<div id="import-more-section" class="hidden">' +
            '<input class="import-input" id="pk-input-more" type="password" placeholder="개인키 (0x...)">' +
            '<button class="btn btn-primary btn-sm" id="btn-import-more">가져오기</button>' +
            '</div>' +
            '<button class="setup-btn" id="btn-mnemonic-more-toggle"><span class="emoji">🔑</span> 복구구문으로 가져오기</button>' +
            '<div id="mnemonic-more-section" class="hidden">' +
            '<textarea class="import-input" id="mnemonic-input-more" rows="3" style="resize:vertical" placeholder="12개 또는 24개 단어를 입력하세요"></textarea>' +
            '<button class="btn btn-primary btn-sm" id="btn-mnemonic-more">가져오기</button>' +
            '</div>' +
            '<div id="add-result"></div>' +
            '<button class="btn btn-secondary btn-sm" id="btn-close-add" style="margin-top:8px">← 닫기</button>' +
            '</div>' +
            '</div>' +

            (accounts.length > 1 ?
                '<div class="divider"></div>' +
                '<div class="account-label" style="margin-bottom:8px">전체 계정 (' + accounts.length + ')</div>' +
                accounts.map(function (a, i) {
                    return '<div class="account-section" style="margin-bottom:6px;padding:10px 14px;cursor:pointer" data-switch="' + a + '">' +
                        '<span style="font-size:.72rem;color:#9ca3af">계정 ' + (i + 1) + '</span>' +
                        '<div class="account-addr" style="font-size:.72rem">' + a.slice(0, 10) + '...' + a.slice(-8) + '</div>' +
                        '</div>'
                }).join('')
                : ''
            )

        // 주소 복사
        document.getElementById('addr-copy').addEventListener('click', () => {
            navigator.clipboard.writeText(addr).then(() => {
                const el = document.getElementById('addr-copy')
                const orig = el.textContent
                el.textContent = '✅ 복사됨!'
                el.style.color = '#10b981'
                setTimeout(() => { el.textContent = orig; el.style.color = '' }, 1500)
            })
        })

        // 잔액 조회
        fetchBalance(addr, chainId)

        // 새로고침
        document.getElementById('btn-refresh').addEventListener('click', () => {
            fetchBalance(addr, chainId)
        })

        // 네트워크 전환
        document.getElementById('btn-network').addEventListener('click', () => {
            const current = chainId
            const next = current === '0x67' ? '0x289b' : '0x67'
            chrome.runtime.sendMessage({
                source: 'worldland-wallet-content-script',
                type: 'provider-request',
                payload: { method: 'wallet_switchEthereumChain', params: [{ chainId: next }], id: Date.now() },
                origin: 'sidepanel',
            })
        })

        // 지갑 추가
        document.getElementById('btn-add-wallet').addEventListener('click', () => {
            var section = document.getElementById('add-wallet-section')
            var btn = document.getElementById('btn-add-wallet')
            section.classList.toggle('hidden')
            if (section.classList.contains('hidden')) {
                btn.innerHTML = '➕ 지갑 추가'
            } else {
                btn.innerHTML = '✕ 닫기'
            }
        })

        document.getElementById('btn-close-add').addEventListener('click', () => {
            document.getElementById('add-wallet-section').classList.add('hidden')
            document.getElementById('btn-add-wallet').innerHTML = '➕ 지갑 추가'
        })

        var btnCreateMore = document.getElementById('btn-create-more')
        if (btnCreateMore) {
            btnCreateMore.addEventListener('click', async () => {
                const res = await chrome.runtime.sendMessage({
                    source: 'worldland-wallet-approval',
                    action: 'createWallet',
                })
                if (res.success) {
                    document.getElementById('add-result').innerHTML =
                        '<div class="mnemonic-box"><h4>⚠️ 복구 구문 저장!</h4><p>' + res.mnemonic + '</p></div>' +
                        '<div class="message success">✅ ' + res.address.slice(0, 10) + '... 생성됨</div>'
                    setTimeout(() => location.reload(), 2000)
                }
            })
        }

        var btnImportMoreToggle = document.getElementById('btn-import-more-toggle')
        if (btnImportMoreToggle) {
            btnImportMoreToggle.addEventListener('click', () => {
                document.getElementById('import-more-section').classList.toggle('hidden')
            })
        }

        var btnImportMore = document.getElementById('btn-import-more')
        if (btnImportMore) {
            btnImportMore.addEventListener('click', async () => {
                const pk = document.getElementById('pk-input-more').value.trim()
                if (!pk) return
                const res = await chrome.runtime.sendMessage({
                    source: 'worldland-wallet-approval',
                    action: 'importWallet',
                    privateKey: pk,
                })
                if (res.success) {
                    document.getElementById('add-result').innerHTML =
                        '<div class="message success">✅ 가져오기 완료</div>'
                    setTimeout(() => location.reload(), 1000)
                } else {
                    document.getElementById('add-result').innerHTML =
                        '<div class="message error">❌ ' + (res.error || '실패') + '</div>'
                }
            })
        }

        var btnMnemonicMoreToggle = document.getElementById('btn-mnemonic-more-toggle')
        if (btnMnemonicMoreToggle) {
            btnMnemonicMoreToggle.addEventListener('click', () => {
                document.getElementById('mnemonic-more-section').classList.toggle('hidden')
            })
        }

        var btnMnemonicMore = document.getElementById('btn-mnemonic-more')
        if (btnMnemonicMore) {
            btnMnemonicMore.addEventListener('click', async () => {
                const mnemonic = document.getElementById('mnemonic-input-more').value.trim()
                if (!mnemonic) return
                const res = await chrome.runtime.sendMessage({
                    source: 'worldland-wallet-approval',
                    action: 'importFromMnemonic',
                    mnemonic: mnemonic,
                })
                if (res.success) {
                    document.getElementById('add-result').innerHTML =
                        '<div class="message success">✅ 복구구문으로 가져오기 완료</div>'
                    setTimeout(() => location.reload(), 1000)
                } else {
                    document.getElementById('add-result').innerHTML =
                        '<div class="message error">❌ ' + (res.error || '실패') + '</div>'
                }
            })
        }
    }

    // ──── 유틸리티 ────

    async function fetchBalance(address, chainId) {
        const display = document.getElementById('balance-display')
        if (!display) return
        display.innerHTML = '<span class="balance-value" style="font-size:1rem;color:#9ca3af">조회 중...</span>'

        try {
            const rpcUrl = getRpcUrl(chainId)
            const response = await fetch(rpcUrl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    jsonrpc: '2.0', id: 1,
                    method: 'eth_getBalance',
                    params: [address, 'latest'],
                }),
            })
            const data = await response.json()
            if (data.result) {
                const wei = BigInt(data.result)
                const eth = Number(wei) / 1e18
                display.innerHTML =
                    '<div class="balance-value">' + eth.toFixed(4) + '<span class="balance-symbol">WL</span></div>'
            } else {
                display.innerHTML = '<span class="balance-value" style="font-size:.9rem;color:#ef4444">조회 실패</span>'
            }
        } catch (e) {
            display.innerHTML = '<span class="balance-value" style="font-size:.9rem;color:#ef4444">네트워크 오류</span>'
        }
    }

    function getRpcUrl(chainId) {
        var urls = {
            '0x67': 'https://seoul.worldland.foundation',
            '0x501': 'https://rpc.worldland.foundation',
            '0x289b': 'https://rpc-test.worldland.foundation',
        }
        return urls[chainId] || 'https://seoul.worldland.foundation'
    }

    function getNetworkName(chainId) {
        var names = {
            '0x67': 'WorldLand Mainnet',
            '0x501': 'WorldLand Legacy',
            '0x289b': 'WorldLand Testnet',
        }
        return names[chainId] || 'Custom (' + chainId + ')'
    }
})()
