/**
* Blog Pre-Publication Analysis
* Framework-guided content review before publishing
*/
// Get auth token
function getAuthToken() {
return localStorage.getItem('admin_token');
}
// Analyze blog post
async function analyzePost() {
const title = document.getElementById('post-title').value.trim();
const content = document.getElementById('post-content').value.trim();
const category = document.getElementById('post-category').value;
const tags = document.getElementById('post-tags').value;
if (!title || !content) {
alert('Please enter both title and content');
return;
}
// Show loading state
const analyzeBtn = document.getElementById('analyze-btn');
analyzeBtn.disabled = true;
analyzeBtn.innerHTML = ' Analyzing...';
try {
const response = await fetch('/api/admin/blog/analyze', {
method: 'POST',
headers: {
'Authorization': `Bearer ${getAuthToken()}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ title, content, category, tags })
});
const data = await response.json();
if (data.success) {
displayResults(data.analysis);
} else {
alert('Analysis failed: ' + (data.error || 'Unknown error'));
}
} catch (error) {
console.error('Analysis error:', error);
alert('Failed to analyze post. Please try again.');
} finally {
analyzeBtn.disabled = false;
analyzeBtn.innerHTML = 'Analyze with Framework';
}
}
// Display analysis results
function displayResults(analysis) {
const resultsSection = document.getElementById('results-section');
resultsSection.classList.remove('hidden');
// Overall recommendation
const overallEl = document.getElementById('overall-recommendation');
const recommendationClass =
analysis.overall.decision === 'APPROVE' ? 'bg-green-50 border-green-300' :
analysis.overall.decision === 'REVIEW' ? 'bg-yellow-50 border-yellow-300' :
'bg-red-50 border-red-300';
const recommendationIcon =
analysis.overall.decision === 'APPROVE' ? '✅' :
analysis.overall.decision === 'REVIEW' ? '⚠️' : '🚫';
overallEl.className = `rounded-lg p-6 border-2 ${recommendationClass}`;
overallEl.innerHTML = `
${recommendationIcon}
${analysis.overall.title}
${analysis.overall.message}
${analysis.overall.action ? `
Recommended Action: ${analysis.overall.action}
` : ''}
`;
// Sensitivity check
const sensitivityEl = document.getElementById('sensitivity-result');
sensitivityEl.innerHTML = renderCheckResult(analysis.sensitivity);
// Compliance check
const complianceEl = document.getElementById('compliance-result');
complianceEl.innerHTML = renderCheckResult(analysis.compliance);
// Audience analysis
const audienceEl = document.getElementById('audience-result');
audienceEl.innerHTML = renderAudienceAnalysis(analysis.audience);
// Publication guidance
const publicationEl = document.getElementById('publication-result');
publicationEl.innerHTML = renderPublicationGuidance(analysis.publication);
// Response templates
const templatesEl = document.getElementById('response-templates');
templatesEl.innerHTML = renderResponseTemplates(analysis.responseTemplates);
// Apply dynamic widths using data attributes (CSP-compliant)
applyDynamicStyles();
// Setup template copy handlers
setupTemplateCopyHandlers();
// Scroll to results
resultsSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
// Apply dynamic styles using data attributes (CSP-compliant)
function applyDynamicStyles() {
document.querySelectorAll('[data-width]').forEach(el => {
const width = el.getAttribute('data-width');
el.style.width = width + '%';
});
}
// Render check result
function renderCheckResult(check) {
const statusIcon = check.status === 'PASS' ? '✅' : check.status === 'WARN' ? '⚠️' : '❌';
const statusColor = check.status === 'PASS' ? 'text-green-600' : check.status === 'WARN' ? 'text-yellow-600' : 'text-red-600';
let html = `
${statusIcon} ${check.summary}
`;
if (check.details && check.details.length > 0) {
html += '';
check.details.forEach(detail => {
html += `- ${detail}
`;
});
html += '
';
}
if (check.recommendation) {
html += `
Recommendation: ${check.recommendation}
`;
}
return html;
}
// Render audience analysis
function renderAudienceAnalysis(audience) {
let html = ``;
if (audience.engagement) {
html += `
Expected Engagement
${audience.engagement.level}%
${audience.engagement.description}
`;
}
if (audience.similarPosts && audience.similarPosts.length > 0) {
html += `
Similar Posts
${audience.similarPosts.map(post => `• ${post.title} (${post.views} views)`).join('
')}
`;
}
html += `
`;
return html;
}
// Render publication guidance
function renderPublicationGuidance(guidance) {
let html = ``;
if (guidance.timing) {
html += `
Recommended Timing
${guidance.timing}
`;
}
if (guidance.monitoring) {
html += `
Post-Publication Monitoring
${guidance.monitoring}
`;
}
if (guidance.actions && guidance.actions.length > 0) {
html += `
Recommended Actions
${guidance.actions.map(action => `- ${action}
`).join('')}
`;
}
html += `
`;
return html;
}
// Render response templates
function renderResponseTemplates(templates) {
if (!templates || templates.length === 0) {
return 'No response templates generated
';
}
return templates.map((template, index) => `
${template.scenario}
"${template.response}"
`).join('');
}
// Copy template to clipboard
function setupTemplateCopyHandlers() {
document.querySelectorAll('.copy-template-btn').forEach(btn => {
btn.addEventListener('click', function(e) {
e.stopPropagation();
const card = this.closest('.template-card');
const text = card.querySelector('.template-text').textContent.replace(/"/g, '');
navigator.clipboard.writeText(text).then(() => {
const originalText = this.textContent;
this.textContent = 'Copied!';
this.classList.add('text-green-600');
setTimeout(() => {
this.textContent = originalText;
this.classList.remove('text-green-600');
}, 2000);
});
});
});
}
// Save as draft
async function saveDraft() {
const title = document.getElementById('post-title').value.trim();
const content = document.getElementById('post-content').value.trim();
const category = document.getElementById('post-category').value;
const tags = document.getElementById('post-tags').value;
if (!title || !content) {
alert('Please enter both title and content');
return;
}
try {
const response = await fetch('/api/admin/blog/draft', {
method: 'POST',
headers: {
'Authorization': `Bearer ${getAuthToken()}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ title, content, category, tags, status: 'draft' })
});
const data = await response.json();
if (data.success) {
alert('Draft saved successfully!');
} else {
alert('Failed to save draft: ' + (data.error || 'Unknown error'));
}
} catch (error) {
console.error('Save draft error:', error);
alert('Failed to save draft. Please try again.');
}
}
// Publish post
async function publishPost() {
if (!confirm('Are you sure you want to publish this post?')) {
return;
}
const title = document.getElementById('post-title').value.trim();
const content = document.getElementById('post-content').value.trim();
const category = document.getElementById('post-category').value;
const tags = document.getElementById('post-tags').value;
try {
const response = await fetch('/api/admin/blog/publish', {
method: 'POST',
headers: {
'Authorization': `Bearer ${getAuthToken()}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ title, content, category, tags, status: 'published' })
});
const data = await response.json();
if (data.success) {
alert('Post published successfully!');
window.location.href = '/admin/blog-posts.html';
} else {
alert('Failed to publish: ' + (data.error || 'Unknown error'));
}
} catch (error) {
console.error('Publish error:', error);
alert('Failed to publish. Please try again.');
}
}
// Event listeners
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('analyze-btn').addEventListener('click', analyzePost);
document.getElementById('save-draft-btn')?.addEventListener('click', saveDraft);
document.getElementById('publish-btn')?.addEventListener('click', publishPost);
});