/**
* Customer Support Agent — Dashboard JavaScript
* Handles navigation, compose form, inbox list, detail modal, and review queue.
*/
const API_BASE = '/api/v1';
// ── Navigation ──────────────────────────────────────────────────────
document.querySelectorAll('.nav-item').forEach(item => {
item.addEventListener('click', () => {
const viewId = item.dataset.view;
switchView(viewId);
});
});
function switchView(viewId) {
// Update nav
document.querySelectorAll('.nav-item').forEach(n => n.classList.remove('active'));
const navEl = document.querySelector(`[data-view="${viewId}"]`);
if (navEl) navEl.classList.add('active');
// Update views
document.querySelectorAll('.view').forEach(v => v.classList.remove('active'));
const viewEl = document.getElementById(`view-${viewId}`);
if (viewEl) viewEl.classList.add('active');
// Refresh data for target view
if (viewId === 'inbox') loadInbox();
if (viewId === 'review') loadReviewQueue();
}
// ── Sample Emails ───────────────────────────────────────────────────
const SAMPLES = [
{
sender: 'jane.smith@company.com',
subject: 'Double charge on my subscription',
body: 'Hi,\n\nI just checked my bank statement and it looks like I was charged twice for my Pro subscription this month — once on April 1st and again on April 3rd.\n\nThe amounts are $29.99 each. Can you please look into this and process a refund for the duplicate charge?\n\nThank you,\nJane'
},
{
sender: 'dev.team@startup.io',
subject: 'API returning 401 errors after key rotation',
body: 'Hello support,\n\nWe rotated our API keys yesterday following your documentation, but all our requests are now returning 401 Unauthorized errors.\n\nWe\'ve confirmed the new key is being sent in the Authorization header correctly. Our integration was working fine before the rotation.\n\nCan you help us debug this? It\'s blocking our production deployment.\n\nBest,\nMike from DevOps'
},
{
sender: 'alex.johnson@email.com',
subject: 'Cannot reset my password',
body: 'Hi there,\n\nI\'ve been trying to reset my password for the past hour but I never receive the reset email. I\'ve checked my spam folder and everything.\n\nMy account email is alex.johnson@email.com. I need to access my account urgently for a deadline.\n\nPlease help!\nAlex'
},
{
sender: 'sarah.miller@corp.net',
subject: 'What are your business hours?',
body: 'Hello,\n\nI wanted to know your customer support business hours and whether you offer support on weekends. Also, do you have a phone support line?\n\nThanks,\nSarah'
},
];
let sampleIndex = 0;
document.getElementById('btn-sample').addEventListener('click', () => {
const sample = SAMPLES[sampleIndex % SAMPLES.length];
document.getElementById('email-sender').value = sample.sender;
document.getElementById('email-subject').value = sample.subject;
document.getElementById('email-body').value = sample.body;
sampleIndex++;
showToast('Sample email loaded', 'info');
});
// ── Compose Form ────────────────────────────────────────────────────
document.getElementById('compose-form').addEventListener('submit', async (e) => {
e.preventDefault();
const sender = document.getElementById('email-sender').value.trim();
const subject = document.getElementById('email-subject').value.trim();
const body = document.getElementById('email-body').value.trim();
if (!sender || !subject || !body) {
showToast('Please fill in all fields', 'error');
return;
}
// Toggle loading state
setLoading(true);
try {
const response = await fetch(`${API_BASE}/process-email`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ sender, subject, body }),
});
if (!response.ok) {
const err = await response.json().catch(() => ({}));
throw new Error(err.detail || `Server error (${response.status})`);
}
const data = await response.json();
showResult(data);
showToast(`Email processed — Ticket ${data.ticket_id}`, 'success');
updateBadges();
} catch (err) {
showToast(`Error: ${err.message}`, 'error');
console.error('Process email failed:', err);
} finally {
setLoading(false);
}
});
function setLoading(loading) {
const btn = document.getElementById('btn-send');
const text = document.getElementById('btn-send-text');
const spinner = document.getElementById('btn-send-spinner');
btn.disabled = loading;
text.style.display = loading ? 'none' : 'inline-flex';
spinner.style.display = loading ? 'inline-flex' : 'none';
}
// ── Show Pipeline Result ────────────────────────────────────────────
function showResult(data) {
const panel = document.getElementById('result-panel');
panel.style.display = 'block';
// Status badge
const statusBadge = document.getElementById('result-status-badge');
const statusText = formatStatus(data.status);
statusBadge.textContent = statusText;
statusBadge.className = `badge badge-${data.status}`;
// Pipeline steps
const stepsEl = document.getElementById('pipeline-steps');
const category = typeof data.category === 'object' ? data.category : data.category;
const catName = typeof category === 'string' ? category : (category?.value || category || 'unknown');
const confidence = (data.confidence * 100).toFixed(0);
const confColor = data.confidence >= 0.8 ? 'var(--color-success)' :
data.confidence >= 0.5 ? 'var(--color-warning)' : 'var(--color-danger)';
stepsEl.innerHTML = `