
document.getElementById('sendCoverLetterPrompt')?.addEventListener('click', async function() {
    const button = document.getElementById('sendCoverLetterPrompt');
    const resultContainer = document.getElementById('cover-letter-result');

    // Button Loading Effect
    button.disabled = true;
    button.innerHTML = 'Generating... <span class="bwdcvs-coverletter-loading-dots"></span>'; 

    const userName = document.getElementById('userName').value.trim();
    const email = document.getElementById('userEmail').value.trim();
    const receiverName = document.getElementById('receiverName').value.trim();
    const companyName = document.getElementById('companyName').value.trim();
    const userDesignation = document.getElementById('userDesignation').value.trim();
    const tags = document.getElementById('tags').value.trim();
    const userInput = document.getElementById('userInput').value.trim();

    if (!userName || !email || !receiverName || !companyName || !userDesignation || !tags || !userInput) {
        alert('Please fill in all fields.');
        button.disabled = false;
        button.innerHTML = 'Generate Cover Letter';
        return;
    }

    try {
        const response = await fetch(bwdcv_openai_api_vars.api_url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: new URLSearchParams({
                action: 'bwdcv_openai_api_request',
                userName, email, receiverName, companyName, userDesignation, tags, userInput
            })
        });

        const data = await response.json();

        if (data.error) {
            resultContainer.innerText = data.error;
        } else {
            formatText(data.response || 'No response from API');
        }
    } catch (error) {
        console.error('Error fetching cover letter:', error);
        resultContainer.innerText = 'Something went wrong! Please try again.';
    }

    // Reset button after response
    button.disabled = false;
    button.innerHTML = 'Generate Cover Letter';
});

function formatText(text) {
    let formattedText = text.replace(/\n/g, "<br>"); 
    document.getElementById('cover-letter-result').innerHTML = formattedText;
}

function printCoverLetter() {
    let printContent = document.getElementById('cover-letter-result').innerHTML;
    let printWindow = window.open('', '_blank', 'width=1000,height=800,top=100,left=100');

    printWindow.document.write(`
        <html>
        <head>
            <title>Cover Letter</title>
            <style>
                @media print {
                    body {
                        visibility: hidden;
                    }
                    .print-container {
                        visibility: visible;
                        white-space: pre-wrap;
                        word-wrap: break-word;
                        font-size: 16px;
                        font-family: Arial, sans-serif;
                        margin: 20px;
                    }
                    
                    /* Page Number, URL, and Time Remove */
                    @page {
                        size: auto;
                        margin: 0;
                    }
                    
                    /* Hide Browser Default Headers and Footers */
                    ::-webkit-print-header,
                    ::-webkit-print-footer {
                        display: none;
                    }
                }
            </style>
        </head>
        <body onload="window.print();">
            <div class="print-container">${printContent}</div>
        </body>
        </html>
    `);

    printWindow.document.close();
}