jQuery(function($){
    let $modal, $overlay, $closeBtn, $instanceSelect, $msgArea;
    let userId = 0;

    // 1) Define placeholders
    const placeholders = {
        '{{id}}': 'Order ID',
        '{{order_key}}': 'Order Key',
        '{{order_date}}': 'Order Date',
        '{{order_link}}': 'Order Summary Link',
        '{{product}}': 'Product List',
        '{{product_name}}': 'Product Name',
        '{{order_discount}}': 'Order Discount',
        '{{cart_discount}}': 'Cart Discount',
        '{{order_tax}}': 'Tax',
        '{{currency}}': 'Currency Symbol',
        '{{order_subtotal}}': 'Subtotal Amount',
        '{{order_total}}': 'Total Amount',
        '{{billing_first_name}}': 'First Name',
        '{{billing_last_name}}': 'Last Name',
        '{{billing_company}}': 'Company',
        '{{billing_address_1}}': 'Address 1',
        '{{billing_address_2}}': 'Address 2',
        '{{billing_city}}': 'City',
        '{{billing_postcode}}': 'Postcode',
        '{{billing_country}}': 'Country',
        '{{billing_state}}': 'Province',
        '{{billing_email}}': 'Email',
        '{{billing_phone}}': 'Phone',
        '{{shop_name}}': 'Shop Name',
        '{{site_link}}': 'Site Link',
        '{{transaction_id}}': 'Transaction ID',
        '{{note}}': 'Order Note'
    };

    // 2) On DOM ready, build the popup + attach events
    $(document).ready(function(){
        // Insert the popup markup inside #wpwrap
        $('#wpwrap').append(`
            <div id="wawp-send-msg-overlay" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.6); z-index:9998;"></div>
            <div id="wawp-send-msg-modal" style="display:none; position:fixed; top:50%; left:50%; width:400px; transform:translate(-50%,-50%); background:#fff; padding:20px; border-radius:8px; z-index:9999; box-shadow: 0 4px 12px rgba(0,0,0,0.15);">
              <h3 style="margin-top:0; border-bottom: 1px solid #eee; padding-bottom: 10px;">Send WhatsApp Message</h3>
              <div style="margin-bottom:15px;">
                <label style="display:block; margin-bottom:5px; font-weight:600;">Instance:</label>
                <select id="wawp-instance-select" style="width:100%;"></select>
              </div>

              <div style="margin-bottom:15px;">
                <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:5px;">
                    <label style="font-weight:600;">Message:</label>
                    <div class="placeholder-containerlogin"></div>
                </div>
                <textarea id="wawp-message-text" rows="5" style="width:100%; padding:10px; border:1px solid #ddd; border-radius:4px;"></textarea>
                <p style="font-size:11px; color:#666; margin-top:5px;">Emojis are supported using your system's emoji picker (Win + . or Cmd + Ctrl + Space)</p>
              </div>

              <div style="margin-top:20px; text-align:right;">
                <button type="button" id="wawp-send-msg-cancel" class="button button-secondary">Cancel</button>
                <button type="button" id="wawp-send-msg-confirm" class="button button-primary">Send Message</button>
              </div>
            </div>
        `);

        // Cache references
        $overlay = $('#wawp-send-msg-overlay');
        $modal   = $('#wawp-send-msg-modal');
        $closeBtn= $('#wawp-send-msg-cancel');
        $instanceSelect = $('#wawp-instance-select');
        $msgArea = $('#wawp-message-text');

        // 4) Populate instance dropdown
        $instanceSelect.empty();
        if (wawpSendMsgData.onlineInstances && wawpSendMsgData.onlineInstances.length > 0) {
            wawpSendMsgData.onlineInstances.forEach(function(obj){
                $instanceSelect.append(`<option value="${obj.instance_id}">${obj.name} (${obj.instance_id})</option>`);
            });
        } else {
            $instanceSelect.append(`<option value="">${wawpSendMsgData.noOnlineInstance}</option>`);
        }

        // 5) Create the placeholders dropdown
        buildPlaceholderDropdown('.placeholder-containerlogin', placeholders);

        // 6) Cancel button
        $closeBtn.on('click', function(){
            hideModal();
        });

        // 7) "Send" button
        $('#wawp-send-msg-confirm').on('click', function(){
            const instance_id = $instanceSelect.val();
            const text = $msgArea.val().trim();

            if (!instance_id) {
                alert('No instance selected.');
                return;
            }
            if (!text) {
                alert('Please enter a message.');
                return;
            }

            // Do AJAX
            $.ajax({
                url: wawpSendMsgData.ajaxUrl,
                method: 'POST',
                data: {
                    action: 'wawp_send_user_custom_message',
                    security: wawpSendMsgData.security,
                    user_id: userId,
                    instance_id: instance_id,
                    text: text
                },
                success: function(resp){
                    if (resp && resp.success) {
                        alert(resp.data);
                        hideModal();
                    } else {
                        alert((resp && resp.data) || 'Error sending message.');
                    }
                },
                error: function(){
                    alert('AJAX error occurred.');
                }
            });
        });

        // 8) When user clicks "Send" in the table row
        $(document).on('click', '.wawp-send-msg-btn', function(e){
            e.preventDefault();
            userId = $(this).data('user-id') || 0;
            $msgArea.val('');
            showModal();
        });
    });

    // Show/hide modal
    function showModal(){
        $overlay.show();
        $modal.show();
    }
    function hideModal(){
        $overlay.hide();
        $modal.hide();
    }

    // 9) Utility: Build a <select> with placeholders, insert into container
    function buildPlaceholderDropdown(containerSelector, placeholdersObj) {
        let dropdownHTML = `<select class="placeholder-dropdown" style="width:120px; font-size:12px;">
                                <option value="">-- Placeholders --</option>`;
        Object.entries(placeholdersObj).forEach(([token, label]) => {
            dropdownHTML += `<option value="${token}">${label}</option>`;
        });
        dropdownHTML += `</select>`;

        $(containerSelector).html(dropdownHTML);

        $(containerSelector).on('change', 'select.placeholder-dropdown', function(){
            let selected = $(this).val();
            if (!selected) return;

            let currentText = $msgArea.val();
            $msgArea.val(currentText + ' ' + selected);

            $(this).val('');
            $msgArea.focus();
        });
    }
});
