(function() {
    // 1. Find configuration parameters
    const script = document.currentScript || document.querySelector('script[src*="wallet-widget.js"]');
    if (!script) return;

    const apiKey = script.getAttribute('data-api-key');
    const serverUrl = new URL(script.src).origin;
    const containerSelector = script.getAttribute('data-container');

    if (!apiKey) {
        console.error('Wallet Widget: data-api-key attribute is missing on the script tag.');
        return;
    }

    // Determine if we should render inline inside a specific container
    let container = containerSelector ? document.querySelector(containerSelector) : null;
    // Fallback: search for a placeholder element if no selector specified
    if (!container) {
        container = document.getElementById('wallet-widget') || document.querySelector('.wallet-widget-placeholder');
    }
    const isInline = !!container;

    // 2. Inject Styles
    const style = document.createElement('style');
    style.textContent = `
        @import url('https://fonts.googleapis.com/css2?family=Outfit:wght@400;500;600;700;800&display=swap');
        @import url('https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css');

        .dv-wallet-widget * {
            box-sizing: border-box;
            font-family: 'Outfit', sans-serif;
        }
        /* Floating styles (default when not inline) */
        .dv-wallet-widget:not(.dv-inline) .dv-wallet-btn {
            position: fixed;
            bottom: 24px;
            right: 24px;
            width: 60px;
            height: 60px;
            border-radius: 30px;
            background: linear-gradient(135deg, #4f46e5, #6366f1);
            color: white;
            box-shadow: 0 10px 25px -5px rgba(79, 70, 229, 0.4);
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            z-index: 99999;
            transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1);
            border: none;
        }
        .dv-wallet-widget:not(.dv-inline) .dv-wallet-btn:hover {
            transform: scale(1.05) translateY(-2px);
            box-shadow: 0 15px 30px -5px rgba(79, 70, 229, 0.6);
        }
        .dv-wallet-widget:not(.dv-inline) .dv-wallet-btn i {
            font-size: 24px;
        }
        .dv-wallet-widget:not(.dv-inline) .dv-wallet-modal {
            position: fixed;
            bottom: 96px;
            right: 24px;
            width: 380px;
            max-height: 520px;
            background: white;
            border-radius: 24px;
            box-shadow: 0 20px 50px -12px rgba(15, 23, 42, 0.15);
            border: 1px solid #f1f5f9;
            display: flex;
            flex-direction: column;
            overflow: hidden;
            z-index: 99999;
            opacity: 0;
            transform: translateY(20px) scale(0.95);
            pointer-events: none;
            transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1);
        }
        
        /* Inline / Header styles */
        .dv-wallet-widget.dv-inline {
            display: inline-block;
            position: relative;
            vertical-align: middle;
        }
        .dv-wallet-widget.dv-inline .dv-wallet-btn {
            position: relative;
            background: transparent;
            color: #0d6efd;
            border: 1px solid #0d6efd;
            padding: 6px 14px;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 500;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            cursor: pointer;
            transition: all 0.2s ease-in-out;
        }
        .dv-wallet-widget.dv-inline .dv-wallet-btn:hover {
            background: rgba(13, 110, 253, 0.08);
            border-color: #0b5ed7;
            color: #0b5ed7;
        }
        .dv-wallet-widget.dv-inline .dv-wallet-btn i {
            font-size: 14px;
        }
        .dv-wallet-widget.dv-inline .dv-wallet-modal {
            position: absolute;
            top: 100%;
            right: 0;
            bottom: auto;
            margin-top: 8px;
            width: 380px;
            max-height: 520px;
            background: white;
            border-radius: 24px;
            box-shadow: 0 20px 50px -12px rgba(15, 23, 42, 0.15);
            border: 1px solid #f1f5f9;
            display: flex;
            flex-direction: column;
            overflow: hidden;
            z-index: 99999;
            opacity: 0;
            transform: translateY(10px) scale(0.95);
            pointer-events: none;
            transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1);
        }

        .dv-wallet-widget .dv-wallet-modal.active {
            opacity: 1;
            transform: translateY(0) scale(1);
            pointer-events: auto;
        }
        /* Header styling */
        .dv-modal-header {
            background: linear-gradient(135deg, #18243c, #263655);
            color: white;
            padding: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .dv-modal-header h3 {
            margin: 0;
            font-size: 16px;
            font-weight: 700;
        }
        .dv-modal-header p {
            margin: 2px 0 0 0;
            font-size: 11px;
            color: #94a3b8;
        }
        .dv-close-btn {
            background: rgba(255,255,255,0.1);
            border: none;
            color: white;
            width: 28px;
            height: 28px;
            border-radius: 14px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: background 0.2s;
            font-size: 18px;
        }
        .dv-close-btn:hover {
            background: rgba(255,255,255,0.2);
        }
        /* Body styling */
        .dv-modal-body {
            padding: 20px;
            overflow-y: auto;
            flex: 1;
        }
        .dv-balance-card {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 16px;
            padding: 16px;
            text-align: center;
            margin-bottom: 20px;
        }
        .dv-balance-label {
            font-size: 11px;
            font-weight: 700;
            color: #94a3b8;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            margin-bottom: 4px;
        }
        .dv-balance-val {
            font-size: 28px;
            font-weight: 800;
            color: #0f172a;
        }
        /* Recharge form */
        .dv-recharge-section {
            margin-bottom: 20px;
        }
        .dv-input-group {
            position: relative;
            margin-bottom: 12px;
        }
        .dv-input-group span {
            position: absolute;
            left: 12px;
            top: 10px;
            font-weight: 700;
            color: #94a3b8;
            font-size: 14px;
        }
        .dv-recharge-input {
            width: 100%;
            padding: 10px 12px 10px 24px;
            border: 1.5px solid #e2e8f0;
            border-radius: 12px;
            font-size: 14px;
            outline: none;
            transition: border-color 0.2s;
        }
        .dv-recharge-input:focus {
            border-color: #6366f1;
        }
        .dv-pay-btn {
            width: 100%;
            background: linear-gradient(135deg, #18243c, #263655);
            color: white;
            border: none;
            padding: 12px;
            border-radius: 12px;
            font-size: 13px;
            font-weight: 700;
            cursor: pointer;
            box-shadow: 0 4px 12px rgba(15, 36, 60, 0.15);
            transition: opacity 0.2s;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
        }
        .dv-pay-btn:hover {
            opacity: 0.95;
        }
        /* Logs */
        .dv-history-title {
            font-size: 11px;
            font-weight: 700;
            color: #94a3b8;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            margin-bottom: 10px;
            border-bottom: 1px solid #f1f5f9;
            padding-bottom: 6px;
        }
        .dv-history-list {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
        .dv-history-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 12px;
        }
        .dv-hist-date {
            color: #64748b;
        }
        .dv-hist-amt {
            font-weight: 700;
            color: #10b981;
        }
        .dv-empty-state {
            color: #94a3b8;
            font-size: 12px;
            text-align: center;
            padding: 16px 0;
        }
        /* Toast style */
        .dv-toast {
            position: fixed;
            bottom: 24px;
            left: 24px;
            background: #0f172a;
            color: white;
            padding: 12px 20px;
            border-radius: 12px;
            font-size: 13px;
            font-weight: 600;
            box-shadow: 0 10px 25px rgba(0,0,0,0.15);
            z-index: 999999;
            display: flex;
            align-items: center;
            gap: 8px;
            opacity: 0;
            transform: translateY(20px);
            transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1);
            pointer-events: none;
        }
        .dv-toast.active {
            opacity: 1;
            transform: translateY(0);
        }
    `;
    document.head.appendChild(style);

    // 3. Create DOM Elements
    const root = document.createElement('div');
    root.className = 'dv-wallet-widget' + (isInline ? ' dv-inline' : '');
    if (isInline) {
        container.appendChild(root);
    } else {
        document.body.appendChild(root);
    }

    // Wallet Button
    const walletBtn = document.createElement('button');
    walletBtn.className = 'dv-wallet-btn';
    walletBtn.innerHTML = '<i class="bi bi-wallet2"></i>' + (isInline ? ' <span class="dv-btn-text">Wallet</span>' : '');
    root.appendChild(walletBtn);

    // Wallet Modal
    const walletModal = document.createElement('div');
    walletModal.className = 'dv-wallet-modal';
    root.appendChild(walletModal);

    // Toast Notification (always fixed to the page viewport)
    const toast = document.createElement('div');
    toast.className = 'dv-toast';
    document.body.appendChild(toast);

    // 4. State variables
    let balance = 0.00;
    let paymentWindow = null;

    // Toast Alert Helper
    function showToast(message, isSuccess = true) {
        toast.innerHTML = `<i class="bi ${isSuccess ? 'bi-check-circle-fill text-emerald-400' : 'bi-exclamation-triangle-fill text-rose-400'}"></i> ${message}`;
        toast.classList.add('active');
        setTimeout(() => {
            toast.classList.remove('active');
        }, 3500);
    }

    // Toggle Modal View
    walletBtn.addEventListener('click', function() {
        const isActive = walletModal.classList.contains('active');
        if (isActive) {
            walletModal.classList.remove('active');
        } else {
            fetchWalletData();
            walletModal.classList.add('active');
        }
    });

    // Close Modal when clicking outside the widget
    document.addEventListener('click', function(e) {
        if (!root.contains(e.target)) {
            walletModal.classList.remove('active');
        }
    });

    // Fetch Wallet Details via API
    function fetchWalletData() {
        walletModal.innerHTML = `
            <div class="dv-modal-header">
                <div>
                    <h3>Wallet Balance</h3>
                    <p>Fetching account status...</p>
                </div>
                <button class="dv-close-btn">&times;</button>
            </div>
            <div class="dv-modal-body" style="text-align:center; padding: 40px 0;">
                <div style="border: 2.5px solid #18243c; border-top-color: transparent; width: 24px; height: 24px; border-radius: 50%; display: inline-block; animation: spin 0.8s linear infinite;"></div>
            </div>
            <style>
                @keyframes spin { to { transform: rotate(360deg); } }
            </style>
        `;

        walletModal.querySelector('.dv-close-btn').addEventListener('click', () => {
            walletModal.classList.remove('active');
        });

        fetch(`${serverUrl}/api/v1/widget/wallet?api_key=${apiKey}`)
            .then(res => {
                if (!res.ok) throw new Error('Failed to fetch wallet info.');
                return res.json();
            })
            .then(data => {
                if (data.success) {
                    balance = parseFloat(data.client.wallet_balance);
                    if (isInline) {
                        const formattedBalance = balance.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
                        walletBtn.innerHTML = `<i class="bi bi-wallet2"></i> ₹${formattedBalance}`;
                    }
                    renderModalContent(data.client, data.recharges);
                } else {
                    renderError(data.message);
                }
            })
            .catch(err => {
                renderError(err.message);
            });
    }

    // Render Modal Contents
    function renderModalContent(client, recharges) {
        let historyHtml = '';
        if (recharges.length === 0) {
            historyHtml = '<div class="dv-empty-state"><i class="bi bi-folder-x"></i> No recent recharges</div>';
        } else {
            recharges.forEach(log => {
                historyHtml += `
                    <div class="dv-history-item">
                        <span class="dv-hist-date">${log.date}</span>
                        <span class="dv-hist-amt">+ ₹${log.amount}</span>
                    </div>
                `;
            });
        }

        walletModal.innerHTML = `
            <div class="dv-modal-header">
                <div>
                    <h3>${client.name}</h3>
                    <p>${client.email || 'Wallet Access Portal'}</p>
                </div>
                <button class="dv-close-btn">&times;</button>
            </div>
            <div class="dv-modal-body">
                <div class="dv-balance-card">
                    <div class="dv-balance-label">Current Balance</div>
                    <div class="dv-balance-val">₹${parseFloat(client.wallet_balance).toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</div>
                </div>

                <div class="dv-recharge-section">
                    <div class="dv-input-group">
                        <span>₹</span>
                        <input type="number" class="dv-recharge-input" id="recharge-amount" placeholder="Enter amount (INR)" min="1" value="500">
                    </div>
                    <button class="dv-pay-btn" id="initiate-pay">
                        <i class="bi bi-credit-card-2-front"></i> Pay with Innoversion
                    </button>
                </div>

                <div class="dv-history-title">Verification Rates</div>
                <div style="background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 12px; padding: 12px 14px; margin-bottom: 20px; display: grid; gap: 8px;">
                    <div style="display: flex; justify-content: space-between; font-size: 13px; color: #475569;">
                        <span>PAN Verification</span>
                        <span style="font-weight: 700; color: #0f172a;">₹${parseFloat(client.pan_charge).toFixed(2)}</span>
                    </div>
                    <div style="display: flex; justify-content: space-between; font-size: 13px; color: #475569;">
                        <span>Aadhaar OTP (Send)</span>
                        <span style="font-weight: 700; color: #0f172a;">₹${parseFloat(client.aadhaar_otp_charge).toFixed(2)}</span>
                    </div>
                    <div style="display: flex; justify-content: space-between; font-size: 13px; color: #475569;">
                        <span>Aadhaar OTP (Verify)</span>
                        <span style="font-weight: 700; color: #0f172a;">₹${parseFloat(client.aadhaar_submit_charge).toFixed(2)}</span>
                    </div>
                    <div style="display: flex; justify-content: space-between; font-size: 13px; color: #475569;">
                        <span>Aadhaar Basic API</span>
                        <span style="font-weight: 700; color: #0f172a;">₹${parseFloat(client.aadhaar_basic_charge).toFixed(2)}</span>
                    </div>
                    <div style="display: flex; justify-content: space-between; font-size: 13px; color: #475569;">
                        <span>Aadhaar-PAN Link Check</span>
                        <span style="font-weight: 700; color: #0f172a;">₹${parseFloat(client.aadhaar_pan_link_charge).toFixed(2)}</span>
                    </div>
                    <div style="display: flex; justify-content: space-between; font-size: 13px; color: #475569;">
                        <span>GST Verification</span>
                        <span style="font-weight: 700; color: #0f172a;">₹${parseFloat(client.gst_charge).toFixed(2)}</span>
                    </div>
                    <div style="display: flex; justify-content: space-between; font-size: 13px; color: #475569;">
                        <span>Bank Verification</span>
                        <span style="font-weight: 700; color: #0f172a;">₹${parseFloat(client.bank_charge).toFixed(2)}</span>
                    </div>
                </div>

                <div class="dv-history-title">Recharge History</div>
                <div class="dv-history-list">
                    ${historyHtml}
                </div>
            </div>
        `;

        walletModal.querySelector('.dv-close-btn').addEventListener('click', () => {
            walletModal.classList.remove('active');
        });

        walletModal.querySelector('#initiate-pay').addEventListener('click', () => {
            const amountInput = walletModal.querySelector('#recharge-amount');
            const amount = parseFloat(amountInput.value);

            if (isNaN(amount) || amount <= 0) {
                alert('Please enter a valid amount.');
                return;
            }

            initiatePayment(amount);
        });
    }

    // Render Connection Error Content
    function renderError(message) {
        walletModal.innerHTML = `
            <div class="dv-modal-header">
                <div>
                    <h3>Connection Error</h3>
                    <p>Failed to retrieve details</p>
                </div>
                <button class="dv-close-btn">&times;</button>
            </div>
            <div class="dv-modal-body" style="text-align: center; color: #f43f5e; padding: 24px;">
                <i class="bi bi-exclamation-triangle" style="font-size: 36px; display: block; margin-bottom: 8px;"></i>
                <div style="font-weight: 600; font-size: 13px;">${message || 'Network error occurred.'}</div>
            </div>
        `;
        walletModal.querySelector('.dv-close-btn').addEventListener('click', () => {
            walletModal.classList.remove('active');
        });
    }

    // Call API to start checkout
    function initiatePayment(amount) {
        const payBtn = walletModal.querySelector('#initiate-pay');
        const originalHtml = payBtn.innerHTML;
        
        payBtn.disabled = true;
        payBtn.innerHTML = '<div style="border: 2px solid white; border-top-color: transparent; width: 14px; height: 14px; border-radius: 50%; animation: spin 0.8s linear infinite; display: inline-block; margin-right: 6px;"></div> Loading Checkout...';

        fetch(`${serverUrl}/api/v1/widget/recharge/initiate?api_key=${apiKey}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ amount: amount })
        })
        .then(res => {
            if (!res.ok) throw new Error('Recharge initiation failed.');
            return res.json();
        })
        .then(data => {
            payBtn.disabled = false;
            payBtn.innerHTML = originalHtml;

            if (data.success && data.redirect_url) {
                // Open mock payment page in a pop-up window
                const width = 500;
                const height = 650;
                const left = (screen.width - width) / 2;
                const top = (screen.height - height) / 2;
                
                paymentWindow = window.open(
                    data.redirect_url,
                    'InnoversionCheckoutPopup',
                    `width=${width},height=${height},top=${top},left=${left},resizable=yes,scrollbars=yes`
                );
            } else {
                alert('Could not start checkout: ' + (data.message || 'Unknown error.'));
            }
        })
        .catch(err => {
            payBtn.disabled = false;
            payBtn.innerHTML = originalHtml;
            alert(err.message);
        });
    }

    // Listen to Innoversion mock/real callback message alerts
    window.addEventListener('message', function(event) {
        if (event.data && event.data.type === 'INNOVERSION_RECHARGE_COMPLETE') {
            const status = event.data.status;
            const amount = event.data.amount;

            if (status === 'completed') {
                showToast(`Success! ₹${amount} added to wallet.`, true);
                fetchWalletData(); // Refresh wallet UI
            } else {
                showToast(`Recharge failed or cancelled.`, false);
            }
        }
    });

    // If inline, fetch data on load to display the balance in the header button
    if (isInline) {
        fetch(`${serverUrl}/api/v1/widget/wallet?api_key=${apiKey}`)
            .then(res => {
                if (!res.ok) throw new Error('Failed to fetch wallet info.');
                return res.json();
            })
            .then(data => {
                if (data.success) {
                    balance = parseFloat(data.client.wallet_balance);
                    const formattedBalance = balance.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
                    walletBtn.innerHTML = `<i class="bi bi-wallet2"></i> ₹${formattedBalance}`;
                }
            })
            .catch(err => {
                console.error('Wallet Widget loading error:', err);
            });
    }

})();
