const API_BASE = window.location.origin.includes('hf.space') ? '' : 'https://kush26-toneforge.hf.space'; document.addEventListener('DOMContentLoaded', () => { switchTab('formalize'); }); // --- Theme Management --- function toggleTheme() { const isDark = document.documentElement.classList.toggle('dark'); localStorage.setItem('theme', isDark ? 'dark' : 'light'); if (window.lucide) lucide.createIcons(); } function switchTab(tabId) { document.querySelectorAll('.tab-content').forEach(el => { el.classList.add('hidden'); }); const targetContent = document.getElementById(tabId); if (targetContent) { targetContent.classList.remove('hidden'); } // Toggle corresponding output container document.querySelectorAll('.task-output').forEach(el => el.classList.add('hidden')); const targetOutput = document.getElementById(`output-${tabId}`); if (targetOutput) { targetOutput.classList.remove('hidden'); // Re-calculate heights for hidden-then-visible textareas setTimeout(() => { targetOutput.querySelectorAll('textarea[oninput="autoResize(this)"]').forEach(ta => autoResize(ta)); }, 50); } document.querySelectorAll('.nav-link').forEach(el => { el.classList.remove('active'); }); const targetLink = document.getElementById(`tab-${tabId}`); if (targetLink) { targetLink.classList.add('active'); } } // --- Loading State --- function setLoading(type, isLoading) { const btn = document.getElementById(`btn-${type}`); const originalText = btn.dataset.originalText || btn.innerText; if (isLoading) { btn.disabled = true; btn.dataset.originalText = originalText; btn.innerHTML = `
Forging...
`; btn.classList.add('opacity-50', 'cursor-not-allowed'); } else { btn.disabled = false; btn.innerText = originalText; btn.classList.remove('opacity-50', 'cursor-not-allowed'); } } // --- Render Helpers --- function copyToClipboard(text, btn) { navigator.clipboard.writeText(text).then(() => { const originalHtml = btn.innerHTML; btn.innerHTML = `Copied`; setTimeout(() => { btn.innerHTML = originalHtml; }, 2000); }); } function autoResize(textarea) { textarea.style.height = 'auto'; textarea.style.height = textarea.scrollHeight + 'px'; } function renderEmailCard(emailObj, title) { const uniqueId = Math.random().toString(36).substr(2, 9); return `
${title}
Subject ${emailObj.subject}
Sender ${emailObj.sender}
Recipient ${emailObj.to}
${emailObj.cc ? `
CC ${emailObj.cc}
` : ''}
`; } function renderNegotiation(data) { const isSuccess = data.agreement_reached; let html = `

${data.topic}

${isSuccess ? 'Converged' : 'In Discussion'}
Intelligence Summary

${data.summary}

Communication Sequence
`; data.email_thread.forEach((msg, idx) => { const isProposer = msg.role === 'proposer'; const label = isProposer ? 'Internal Strategy' : 'Counterpart Response'; const uniqueId = Math.random().toString(36).substr(2, 9); html += `
${label}
RE: ${msg.subject}
`; }); html += `
`; return html; } function renderLegal(data) { const riskMap = { low: 'bg-emerald-500/10 border-emerald-500/20 text-emerald-600 dark:text-emerald-400', medium: 'bg-amber-500/10 border-amber-500/20 text-amber-600 dark:text-amber-400', high: 'bg-rose-500/10 border-rose-500/20 text-rose-600 dark:text-rose-400' }; let html = `

Legal Intelligence Report

${data.overall_risk} Risk Profile
Executive Interpretation

"${data.plain_summary}"

Key Obligations
    ${data.obligations.length ? data.obligations.map(o => `
  • ${o}
  • `).join('') : '
  • No obligations detected.
  • '}
Temporal Bounds
    ${data.deadlines.length ? data.deadlines.map(d => `
  • ${d}
  • `).join('') : '
  • No deadlines detected.
  • '}
Identified Risk Markers
${data.risk_flags.length ? data.risk_flags.map(f => ` ${f} `).join('') : 'Clear path identified.'}
Structured Clause Deconstruction
${data.clauses.map(c => `
${c.clause_type} ${c.risk_level}

${c.text}

`).join('')}
`; return html; } // --- API Execution --- async function submitForm(type) { let endpoint = ""; let payload = {}; const outputArea = document.getElementById('output-' + type); outputArea.innerHTML = `
Synthesizing Logic...
`; try { if (type === 'formalize') { endpoint = "/formalize_email"; payload = { raw_email: document.getElementById('form-raw').value, category: document.getElementById('form-cat').value, language: document.getElementById('form-lang').value || "English" }; if (!payload.raw_email) throw new Error("A prompt is required to forge."); } else if (type === 'reply') { endpoint = "/generate_reply"; payload = { original_email: document.getElementById('reply-raw').value, category: document.getElementById('reply-cat').value }; if (!payload.original_email) throw new Error("Input context is missing."); } else if (type === 'negotiate') { endpoint = "/negotiate_email"; payload = { topic: document.getElementById('neg-topic').value, our_position: document.getElementById('neg-our').value, their_position: document.getElementById('neg-their').value, category: document.getElementById('neg-cat').value, max_rounds: parseInt(document.getElementById('neg-rounds').value) || 3 }; if (!payload.topic || !payload.our_position) throw new Error("Define the strategic context first."); } else if (type === 'legal') { endpoint = "/parse_legal_email"; payload = { raw_email: document.getElementById('legal-raw').value }; if (!payload.raw_email) throw new Error("Legal artifacts required."); } setLoading(type, true); const response = await fetch(`${API_BASE}${endpoint}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }); if (!response.ok) { const errData = await response.json().catch(() => ({})); throw new Error(errData.detail || `Network error ${response.status}`); } const data = await response.json(); // Render Output if (type === 'formalize') { let html = renderEmailCard(data.email, `Formalized (${data.category})`); if (data.translated_email) { html += renderEmailCard(data.translated_email, `Translated (${data.translated_email.language})`); } outputArea.innerHTML = html; } else if (type === 'reply') { outputArea.innerHTML = renderEmailCard(data.smart_reply, `Contextual Synthesis`); } else if (type === 'negotiate') { outputArea.innerHTML = renderNegotiation(data); } else if (type === 'legal') { outputArea.innerHTML = renderLegal(data); } // Re-initialize icons and auto-resize textareas if (window.lucide) { lucide.createIcons(); } document.querySelectorAll('textarea[oninput="autoResize(this)"]').forEach(ta => autoResize(ta)); } catch (error) { outputArea.innerHTML = `

Synthesis Interrupted

${error.message}

Verify connection & re-forge
`; if (window.lucide) lucide.createIcons(); } finally { setLoading(type, false); } }