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

    // URL 파라미터에서 요청 정보 가져오기
    const params = new URLSearchParams(window.location.search)
    const requestId = params.get('requestId')
    const method = params.get('method')
    const origin = params.get('origin') || '알 수 없음'
    const paramsData = params.get('params') ? JSON.parse(decodeURIComponent(params.get('params'))) : []

    // 저장된 계정 가져오기
    const stored = await chrome.storage.local.get(['worldland_keyring', 'accounts'])
    const wallets = stored.worldland_keyring?.wallets || []
    const accounts = wallets.map(w => w.address)

    // 계정이 없으면 지갑 생성/가져오기 화면 표시
    if (accounts.length === 0 && (method === 'eth_requestAccounts' || method === 'wallet_requestPermissions')) {
        renderSetup()
        return
    }

    // 메서드별 UI 렌더링
    switch (method) {
        case 'eth_requestAccounts':
        case 'wallet_requestPermissions':
            renderAccountSelect(accounts)
            break
        case 'personal_sign':
            renderSignRequest(paramsData)
            break
        case 'eth_signTypedData_v4':
            renderTypedDataSign(paramsData)
            break
        case 'eth_sendTransaction':
            renderTxApproval(paramsData)
            break
        default:
            renderGenericApproval()
    }

    // ──── 렌더링 함수들 ─────

    function renderSetup() {
        app.innerHTML = `
      <div class="setup">
        <div style="font-size:2.5rem;margin-bottom:12px">🌍</div>
        <h2>WorldLand Wallet</h2>
        <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-approve" id="btn-import" style="width:100%">가져오기</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;font-family:monospace;font-size:.85rem" placeholder="12개 또는 24개 단어를 입력하세요"></textarea>
          <button class="btn btn-approve" id="btn-mnemonic-import" style="width:100%">가져오기</button>
        </div>
        <div id="result-section" class="hidden"></div>
      </div>
    `

        document.getElementById('btn-create').addEventListener('click', async () => {
            const res = await chrome.runtime.sendMessage({
                source: 'worldland-wallet-approval',
                action: 'createWallet',
            })
            if (res.success) {
                document.getElementById('result-section').classList.remove('hidden')
                document.getElementById('result-section').innerHTML =
                    '<div class="mnemonic-box">' +
                    '<h4>⚠️ 복구 구문을 안전하게 보관하세요!</h4>' +
                    '<p>' + res.mnemonic + '</p>' +
                    '</div>' +
                    '<p style="color:#94a3b8;font-size:.82rem;margin-bottom:10px">주소: <span style="color:#a78bfa">' + res.address + '</span></p>' +
                    '<button class="btn btn-approve" id="btn-connect-after-create" style="width:100%">연결하기</button>'
                document.getElementById('btn-connect-after-create').addEventListener('click', () => {
                    sendApproval([res.address])
                })
            }
        })

        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').classList.remove('hidden')
                document.getElementById('result-section').innerHTML =
                    '<p style="color:#4ade80;margin-bottom:10px">✅ 지갑을 가져왔습니다</p>' +
                    '<p style="color:#94a3b8;font-size:.82rem;margin-bottom:10px">주소: <span style="color:#a78bfa">' + res.address + '</span></p>' +
                    '<button class="btn btn-approve" id="btn-connect-after-import" style="width:100%">연결하기</button>'
                document.getElementById('btn-connect-after-import').addEventListener('click', () => {
                    sendApproval([res.address])
                })
            } else {
                alert(res.error || '가져오기 실패')
            }
        })

        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').classList.remove('hidden')
                document.getElementById('result-section').innerHTML =
                    '<p style="color:#4ade80;margin-bottom:10px">✅ 복구구문으로 지갑을 가져왔습니다</p>' +
                    '<p style="color:#94a3b8;font-size:.82rem;margin-bottom:10px">주소: <span style="color:#a78bfa">' + res.address + '</span></p>' +
                    '<button class="btn btn-approve" id="btn-connect-after-mnemonic" style="width:100%">연결하기</button>'
                document.getElementById('btn-connect-after-mnemonic').addEventListener('click', () => {
                    sendApproval([res.address])
                })
            } else {
                alert(res.error || '복구구문이 올바르지 않습니다')
            }
        })
    }

    function renderAccountSelect(accounts) {
        let accountsHTML = ''
        for (let i = 0; i < accounts.length; i++) {
            const addr = accounts[i]
            accountsHTML +=
                '<label class="account-item ' + (i === 0 ? 'selected' : '') + '" data-addr="' + addr + '">' +
                '<input type="radio" name="account" value="' + addr + '" ' + (i === 0 ? 'checked' : '') + '>' +
                '<span class="addr">' + addr.slice(0, 8) + '...' + addr.slice(-6) + '</span>' +
                '</label>'
        }

        app.innerHTML =
            '<div class="header"><span class="icon">🔗</span><h1>사이트 연결 요청</h1></div>' +
            '<div class="origin"><div class="label">요청 사이트</div><div class="url">' + origin + '</div></div>' +
            '<span class="method-badge">' + method + '</span>' +
            '<div class="account-select"><h3>연결할 계정을 선택하세요</h3>' + accountsHTML + '</div>' +
            '<div class="buttons">' +
            '<button class="btn btn-reject" id="btn-reject">거부</button>' +
            '<button class="btn btn-approve" id="btn-approve">연결 승인</button>' +
            '</div>'

        document.querySelectorAll('.account-item').forEach(function (item) {
            item.addEventListener('click', function () {
                document.querySelectorAll('.account-item').forEach(function (el) { el.classList.remove('selected') })
                item.classList.add('selected')
                item.querySelector('input').checked = true
            })
        })

        document.getElementById('btn-approve').addEventListener('click', function () {
            const selected = document.querySelector('input[name=account]:checked')
            sendApproval(selected ? [selected.value] : [accounts[0]])
        })

        document.getElementById('btn-reject').addEventListener('click', sendRejection)
    }

    function renderSignRequest(params) {
        const message = params[0] || ''
        let decoded = message
        try {
            if (message.startsWith('0x')) {
                const bytes = []
                for (let i = 2; i < message.length; i += 2) bytes.push(parseInt(message.slice(i, i + 2), 16))
                decoded = new TextDecoder().decode(new Uint8Array(bytes))
            }
        } catch (e) { }

        app.innerHTML =
            '<div class="header"><span class="icon">✍️</span><h1>메시지 서명 요청</h1></div>' +
            '<div class="origin"><div class="label">요청 사이트</div><div class="url">' + origin + '</div></div>' +
            '<span class="method-badge">personal_sign</span>' +
            '<div class="detail"><h3>서명할 메시지</h3><pre>' + decoded + '</pre></div>' +
            '<div class="warn">⚠️ 메시지 서명은 자산 이동 없이 본인 인증에 사용됩니다.</div>' +
            '<div class="buttons">' +
            '<button class="btn btn-reject" id="btn-reject">거부</button>' +
            '<button class="btn btn-approve" id="btn-approve">서명</button>' +
            '</div>'

        document.getElementById('btn-approve').addEventListener('click', function () { sendApproval('approved') })
        document.getElementById('btn-reject').addEventListener('click', sendRejection)
    }

    function renderTypedDataSign(params) {
        let typedData = {}
        try { typedData = JSON.parse(params[1] || '{}') } catch (e) { }

        app.innerHTML =
            '<div class="header"><span class="icon">📋</span><h1>구조화 데이터 서명</h1></div>' +
            '<div class="origin"><div class="label">요청 사이트</div><div class="url">' + origin + '</div></div>' +
            '<span class="method-badge">eth_signTypedData_v4</span>' +
            '<div class="detail"><h3>데이터</h3><pre>' + JSON.stringify(typedData.message || typedData, null, 2) + '</pre></div>' +
            '<div class="buttons">' +
            '<button class="btn btn-reject" id="btn-reject">거부</button>' +
            '<button class="btn btn-approve" id="btn-approve">서명</button>' +
            '</div>'

        document.getElementById('btn-approve').addEventListener('click', function () { sendApproval('approved') })
        document.getElementById('btn-reject').addEventListener('click', sendRejection)
    }

    function renderTxApproval(params) {
        const tx = params[0] || {}
        const valueWei = tx.value ? BigInt(tx.value) : 0n
        const valueEth = Number(valueWei) / 1e18

        app.innerHTML =
            '<div class="header"><span class="icon">💰</span><h1>트랜잭션 승인</h1></div>' +
            '<div class="origin"><div class="label">요청 사이트</div><div class="url">' + origin + '</div></div>' +
            '<span class="method-badge">eth_sendTransaction</span>' +
            '<div class="detail">' +
            '<h3>전송 금액</h3><div class="value">' + valueEth.toFixed(6) + ' WLC</div>' +
            '<h3 style="margin-top:12px">받는 주소</h3><div class="addr">' + (tx.to || '(컨트랙트 생성)') + '</div>' +
            '<h3 style="margin-top:12px">보내는 주소</h3><div class="addr">' + (tx.from || '-') + '</div>' +
            '</div>' +
            (valueEth > 0 ? '<div class="warn">⚠️ 이 트랜잭션은 실제 자산을 전송합니다. 신중히 확인하세요.</div>' : '') +
            '<div class="buttons">' +
            '<button class="btn btn-reject" id="btn-reject">거부</button>' +
            '<button class="btn btn-approve" id="btn-approve">승인</button>' +
            '</div>'

        document.getElementById('btn-approve').addEventListener('click', function () { sendApproval('approved') })
        document.getElementById('btn-reject').addEventListener('click', sendRejection)
    }

    function renderGenericApproval() {
        app.innerHTML =
            '<div class="header"><span class="icon">🔐</span><h1>요청 승인</h1></div>' +
            '<div class="origin"><div class="label">요청 사이트</div><div class="url">' + origin + '</div></div>' +
            '<span class="method-badge">' + method + '</span>' +
            '<div class="detail"><h3>파라미터</h3><pre>' + JSON.stringify(paramsData, null, 2) + '</pre></div>' +
            '<div class="buttons">' +
            '<button class="btn btn-reject" id="btn-reject">거부</button>' +
            '<button class="btn btn-approve" id="btn-approve">승인</button>' +
            '</div>'

        document.getElementById('btn-approve').addEventListener('click', function () { sendApproval('approved') })
        document.getElementById('btn-reject').addEventListener('click', sendRejection)
    }

    // ──── 응답 전송 ─────

    function sendApproval(data) {
        chrome.runtime.sendMessage({
            source: 'worldland-wallet-approval',
            action: 'approvalResult',
            requestId: requestId,
            approved: true,
            data: data,
        }).then(function () {
            window.close()
        })
    }

    function sendRejection() {
        chrome.runtime.sendMessage({
            source: 'worldland-wallet-approval',
            action: 'approvalResult',
            requestId: requestId,
            approved: false,
        }).then(function () {
            window.close()
        })
    }
})()
