// SVG Icon for the Support Button (Headset/Lifebuoy style)
const SUPPORT_ICON_SVG = `
<svg viewBox="0 0 24 24" width="24" height="24" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round" class="css-i6dzq1">
    <path d="M15.05 5A5 5 0 0 1 19 8.95M15.05 1A9 9 0 0 1 23 8.94m-1 7.98v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"></path>
</svg>
`;

const ADMIN_PHONE = "919118333331";

function createModal() {
    if (document.getElementById('kms-support-modal')) return;

    const modalOverlay = document.createElement('div');
    modalOverlay.id = 'kms-support-modal';
    modalOverlay.className = 'kms-modal-overlay';
    modalOverlay.style.display = 'none'; // Hidden by default

    const modalContent = document.createElement('div');
    modalContent.className = 'kms-modal-content';

    modalContent.innerHTML = `
        <div class="kms-modal-header">
            <h2 class="kms-modal-title">KMS WA CRM Support</h2>
            <button class="kms-modal-close">&times;</button>
        </div>
        <div class="kms-form-group">
            <label class="kms-form-label">Name</label>
            <input type="text" id="kms-name" class="kms-form-input" placeholder="Your Name" />
        </div>
        <div class="kms-form-group">
            <label class="kms-form-label">Email</label>
            <input type="email" id="kms-email" class="kms-form-input" placeholder="email@example.com" />
        </div>
        <div class="kms-form-group">
            <label class="kms-form-label">Phone</label>
            <input type="tel" id="kms-phone" class="kms-form-input" placeholder="Your Phone Number" />
        </div>
        <div class="kms-form-group">
            <label class="kms-form-label">Address</label>
            <input type="text" id="kms-address" class="kms-form-input" placeholder="Address" />
        </div>
        <div class="kms-form-group">
            <label class="kms-form-label">District</label>
            <input type="text" id="kms-district" class="kms-form-input" placeholder="District" />
        </div>
        <div class="kms-form-group">
            <label class="kms-form-label">State</label>
            <input type="text" id="kms-state" class="kms-form-input" placeholder="State" />
        </div>
        <button class="kms-submit-btn">Submit to WhatsApp</button>
    `;

    modalOverlay.appendChild(modalContent);
    document.body.appendChild(modalOverlay);

    // Event Listeners
    const closeBtn = modalContent.querySelector('.kms-modal-close');
    closeBtn.addEventListener('click', () => {
        modalOverlay.style.display = 'none';
    });

    modalOverlay.addEventListener('click', (e) => {
        if (e.target === modalOverlay) {
            modalOverlay.style.display = 'none';
        }
    });

    const submitBtn = modalContent.querySelector('.kms-submit-btn');
    submitBtn.addEventListener('click', handleSubmit);
}

function handleSubmit() {
    const name = document.getElementById('kms-name').value;
    const email = document.getElementById('kms-email').value;
    const phone = document.getElementById('kms-phone').value;
    const address = document.getElementById('kms-address').value;
    const district = document.getElementById('kms-district').value;
    const state = document.getElementById('kms-state').value;

    if (!name || !email || !phone || !address || !district || !state) {
        alert('Please fill in all fields');
        return;
    }

    // Close the modal first
    document.getElementById('kms-support-modal').style.display = 'none';

    // Build the message (using encodeURIComponent for proper encoding)
    const message = `*CRM Support Request*

*Name:* ${name}
*Email:* ${email}
*Phone:* ${phone}
*Address:* ${address}
*District:* ${district}
*State:* ${state}`;

    const encodedMessage = encodeURIComponent(message);
    const whatsappUrl = `https://web.whatsapp.com/send?phone=${ADMIN_PHONE}&text=${encodedMessage}`;

    // Navigate in the same tab (not new tab)
    window.location.href = whatsappUrl;

    // Wait for the chat to load and auto-send the message
    setTimeout(() => {
        autoSendMessage();
    }, 3000);
}

function autoSendMessage() {
    // Try to find and click the send button
    const checkForSendButton = setInterval(() => {
        // WhatsApp Web send button selectors (multiple fallbacks)
        const sendButton = document.querySelector('button[aria-label="Send"]') ||
            document.querySelector('span[data-icon="send"]')?.closest('button') ||
            document.querySelector('[data-testid="send"]') ||
            document.querySelector('button[data-testid="compose-btn-send"]');

        if (sendButton) {
            sendButton.click();
            console.log('[KMS Support] Message sent automatically!');
            clearInterval(checkForSendButton);
        }
    }, 500);

    // Stop trying after 10 seconds
    setTimeout(() => {
        clearInterval(checkForSendButton);
    }, 10000);
}

function injectSidebarButton() {
    console.log('[KMS Support] Starting injection...');

    let attempts = 0;
    const maxAttempts = 20; // 10 seconds (running every 500ms)

    const baseButton = document.createElement('div');
    baseButton.id = 'kms-support-btn';
    baseButton.innerHTML = SUPPORT_ICON_SVG;
    baseButton.title = "Contact Support";
    baseButton.style.cursor = 'pointer';
    baseButton.style.zIndex = '9999';

    baseButton.addEventListener('click', () => {
        const modal = document.getElementById('kms-support-modal');
        if (modal) modal.style.display = 'flex';
    });

    const checkForSidebar = setInterval(() => {
        attempts++;
        console.log(`[KMS Support] Attempt ${attempts} to find sidebar`);

        // Strategy 1: Find extension sidebar (more permissive)
        const allDivs = document.querySelectorAll('div');
        let sidebar = null;

        for (let div of allDivs) {
            // Check basic dimensions - Relaxed width constraint up to 300px just in case
            if (div.clientWidth > 40 && div.clientWidth < 300 && div.clientHeight > window.innerHeight * 0.8) {
                const style = window.getComputedStyle(div);
                // Check position and alignment
                if ((style.position === 'fixed' || style.position === 'absolute' || style.position === 'sticky') &&
                    (style.left === '0px' || parseInt(style.left) < 20) &&
                    style.display !== 'none' &&
                    // Ensure it's on top of other things or is a main container
                    style.zIndex !== 'auto') {
                    sidebar = div;
                    break;
                }
            }
        }

        if (sidebar && !document.getElementById('kms-support-btn')) {
            console.log('[KMS Support] Sidebar found!', sidebar);

            // Style for sidebar injection
            baseButton.style.width = '100%';
            baseButton.style.display = 'flex';
            baseButton.style.justifyContent = 'center';
            baseButton.style.alignItems = 'center';
            baseButton.style.padding = '10px 0';
            baseButton.style.color = 'inherit';
            baseButton.style.marginBottom = '10px'; // Add spacing

            // Insert position logic - Try to find a good spot
            const children = Array.from(sidebar.children);
            if (children.length >= 2) {
                sidebar.insertBefore(baseButton, children[children.length - 2]);
            } else {
                sidebar.appendChild(baseButton);
            }

            clearInterval(checkForSidebar);
            return;
        }

        // Fallback: If not found after timeout, inject PROMINENT floating button
        if (attempts >= 10) { // Reduced to 5 seconds (10 * 500ms)
            console.log('[KMS Support] Sidebar not found. Injecting fallback floating button.');

            if (!document.getElementById('kms-support-btn')) {
                // Style for floating button - MOVED TO RIGHT SIDE to avoid overlapping
                baseButton.style.position = 'fixed';
                baseButton.style.bottom = '80px'; // Higher up
                baseButton.style.right = '30px'; // RIGHT SIDE
                baseButton.style.width = '60px';
                baseButton.style.height = '60px';
                baseButton.style.borderRadius = '50%';
                baseButton.style.backgroundColor = '#25D366'; // WhatsApp Green Bright
                baseButton.style.color = '#fff';
                baseButton.style.display = 'flex';
                baseButton.style.justifyContent = 'center';
                baseButton.style.alignItems = 'center';
                baseButton.style.boxShadow = '0 8px 16px rgba(0,0,0,0.4)';
                baseButton.style.zIndex = '2147483647'; // MAX Z-INDEX
                baseButton.style.border = '3px solid white';

                document.body.appendChild(baseButton);
            }

            clearInterval(checkForSidebar);
        }

    }, 500);
}

// Initial setup
createModal();
injectSidebarButton();
