`;
} finally {
showLoadingState(false);
}
}
function parseAndRenderCTAs(text) {
const lines = text.split('\n').filter(line => line.trim() !== '');
const parsedCTAs = [];
let html = '';
lines.forEach(line => {
const match = line.match(/\[(.*?)\]: "(.*)"/);
if (match && match[1] && match[2]) {
const type = match[1].replace(/-/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
const ctaText = match[2];
parsedCTAs.push({ type, ctaText });
html += `
`;
}
});
return { parsedCTAs, html };
}
function renderCTAs(text) {
const { parsedCTAs, html } = parseAndRenderCTAs(text);
if (parsedCTAs.length > 0) {
lastGeneratedCTAs = parsedCTAs;
previewPlaceholder.classList.add('hidden');
resultsPreview.innerHTML = html;
} else {
resultsPreview.innerHTML = ``;
}
}
function showLoadingState(isLoading) {
if (isLoading) {
previewPlaceholder.classList.add('hidden');
resultsPreview.innerHTML = '
${type}
"${ctaText}"
The AI could not generate CTAs in the expected format. Please try again.
';
generateBtn.disabled = true;
generateBtn.textContent = 'Optimizing...';
showFeedback('AI is optimizing your CTA...', false, 0);
} else {
generateBtn.disabled = false;
generateBtn.textContent = 'Optimize My CTA';
}
}
downloadPdfBtn.addEventListener('click', () => {
if (!lastGeneratedCTAs || lastGeneratedCTAs.length === 0) {
showFeedback('Please generate CTAs before downloading.', true, 3000);
return;
}
showFeedback('Generating PDF...', false, 2000);
try {
const { jsPDF } = window.jspdf;
const pdf = new jsPDF({ unit: 'pt', format: 'letter' });
const pageMargin = 72;
const pageWidth = pdf.internal.pageSize.getWidth();
const textWidth = pageWidth - (pageMargin * 2);
let cursorY = pageMargin;
// Add Title
pdf.setFont('Helvetica', 'bold');
pdf.setFontSize(22);
pdf.text('CTA Optimization Suggestions', pageWidth / 2, cursorY, { align: 'center' });
cursorY += 40;
// Add Original CTA
pdf.setFont('Helvetica', 'normal');
pdf.setFontSize(11);
pdf.text(`Original CTA: "${originalCtaEl.value}"`, pageMargin, cursorY);
cursorY += 40;
lastGeneratedCTAs.forEach(item => {
if (cursorY > pdf.internal.pageSize.getHeight() - pageMargin - 50) {
pdf.addPage();
cursorY = pageMargin;
}
pdf.setFont('Helvetica', 'bold');
pdf.setFontSize(14);
pdf.text(item.type, pageMargin, cursorY);
cursorY += 20;
pdf.setFont('Helvetica', 'normal');
pdf.setFontSize(11);
const lines = pdf.splitTextToSize(`"${item.ctaText}"`, textWidth);
pdf.text(lines, pageMargin, cursorY);
cursorY += (lines.length * 11 * 1.2) + 25;
});
pdf.save('cta-suggestions.pdf');
} catch(err) {
console.error("PDF Generation Error: ", err);
showFeedback("Error generating PDF.", true, 3000);
}
});
let feedbackTimeout;
function showFeedback(message, isError = false, duration = 3000) {
clearTimeout(feedbackTimeout);
feedbackMessage.innerHTML = message;
feedbackMessage.style.color = isError ? '#ef4444' : '#4a5568';
if (duration !== 0) {
feedbackTimeout = setTimeout(() => { feedbackMessage.innerHTML = ''; }, duration);
}
}
});
