`).join('');
}
function buildPrompt(product, desc, type, keys) {
const isVídeo = type === 'video';
const fmt = isVídeo
? `Para cada angulo crie um roteiro de video curto (max 20s) com o campo "roteiro" assim:\n"[0-3s] Gancho: \n\n[4-10s] Desenvolvimento: \n\n[11-17s] Solucao: \n\n[18-20s] CTA: "`
: `Para cada angulo crie: título (headline, max 12 palavras), texto (2-3 frases, max 50 palavras), cta (3-6 palavras)`;
const schema = isVídeo
? keys.map(k => ` "${k}": {"roteiro": ""}`).join(',\n')
: keys.map(k => ` "${k}": {"titulo": "", "texto": "", "cta": ""}`).join(',\n');
return `Produto: ${product}\nDescrição: ${desc}\nTipo: ${isVídeo ? 'Roteiro de Vídeo' : 'Copy Estática'}\n\nAngulos:\n${keys.map(k => '- ' + angleDesc[k]).join('\n')}\n\n${fmt}\n\nRegras: use "${product}" naturalmente, linguagem brasileira fluida, cada copy única.\n\nRetorne APENAS JSON válido:\n{\n${schema}\n}`;
}
async function callGroq(product, desc, type, keys) {
const res = await fetch(GROQ_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${_k}` },
body: JSON.stringify({
model: GROQ_MODEL,
messages: [
{ role: 'system', content: 'Você é um copywriter especialista. Responda SEMPRE com JSON válido puro, sem markdown.' },
{ role: 'user', content: buildPrompt(product, desc, type, keys) }
],
temperature: 0.85,
max_tokens: 4096,
response_format: { type: 'json_object' }
})
});
if (!res.ok) {
const e = await res.json().catch(() => ({}));
throw new Error(e?.error?.message || `Erro ${res.status}`);
}
const data = await res.json();
return JSON.parse(data.choices[0].message.content);
}
async function generateCopies() {
const product = document.getElementById('productName').value.trim();
const desc = document.getElementById('description').value.trim();
const type = document.getElementById('creativeType').value;
if (!product || !desc || !type) { showToast('Preencha todos os campos.', 'error'); return; }
setLoading(true, 'Gerando scripts com IA...', 'Isso pode levar alguns segundos');
document.getElementById('resultsContainer').classList.add('show');
['c1Grid','c2Grid','c3Grid'].forEach(renderSkeletons);
const allKeys = ['conteudoDeValor','quebraDePadrao','dor','hardSell','demonstrativo','comparativo','provaSocial','objecao','urgencia'];
try {
generatedCopies = await callGroq(product, desc, type, allKeys);
renderCopies(type);
showToast('9 copies geradas com sucesso! 🎯');
} catch(err) {
console.error(err);
showToast('Erro ao gerar: ' + err.message, 'error');
document.getElementById('resultsContainer').classList.remove('show');
} finally {
setLoading(false);
}
}
async function regenerateCopy(key) {
const product = document.getElementById('productName').value.trim();
const desc = document.getElementById('description').value.trim();
const type = document.getElementById('creativeType').value;
if (!product || !desc || !type) { showToast('Preencha todos os campos.', 'error'); return; }
document.querySelectorAll(`.btn-regenerate[data-key="${key}"]`).forEach(b => { b.disabled = true; b.textContent = '...'; });
try {
const result = await callGroq(product, desc, type, [key]);
if (result[key]) { generatedCopies[key] = result[key]; renderCopies(type); showToast('Copy gerada novamente!'); }
} catch(err) {
showToast('Erro ao regerar.', 'error');
renderCopies(type);
}
}
async function copyToClipboard(text) {
try {
await navigator.clipboard.writeText(text);
showToast('Copiado!');
} catch {
const ta = Object.assign(document.createElement('textarea'), {value: text});
ta.style.cssText = 'position:fixed;left:-9999px';
document.body.appendChild(ta); ta.select(); document.execCommand('copy'); document.body.removeChild(ta);
showToast('Copiado!');
}
}
function esc(t='') {
return String(t).replace(/&/g,'&').replace(/,'<').replace(/>/g,'>').replace(/"/g,'"');
}
const refreshSvg = `
`;
const copySvg = `
`;
function renderCard(key, name, copy, type) {
if (!copy) return '';
if (type === 'estatico') {
const full = encodeURIComponent(`Título: ${copy.titulo}\n\nTexto: ${copy.texto}\n\nCTA: ${copy.cta}`);
return `
`;
}
if (type === 'video') {
const full = encodeURIComponent(copy.roteiro || '');
return `
`;
}
return '';
}
function renderCopies(type) {
['c1','c2','c3'].forEach(level => {
document.getElementById(`${level}Grid`).innerHTML =
sublanguages[level].map(sub => renderCard(sub.key, sub.name, generatedCopies[sub.key], type)).join('');
});
}
function clearFields() {
['productName','description'].forEach(id => document.getElementById(id).value = '');
document.getElementById('creativeType').value = '';
document.getElementById('resultsContainer').classList.remove('show');
generatedCopies = {};
}