// API Configuration
const API_BASE_URL = '/api';
let userPersona = 'explorer'; // Default
const chatMessages = document.getElementById('chat-messages');
const userInput = document.getElementById('user-input');
const sendBtn = document.getElementById('send-btn');
const onboardingOverlay = document.getElementById('onboarding-overlay');
const appContainer = document.querySelector('.app-container');
const switchBtn = document.getElementById('switch-btn');
const profileStatus = document.getElementById('profile-status');
const attachBtn = document.getElementById('attach-btn');
const fileUpload = document.getElementById('file-upload');
const personaTooltip = document.getElementById('persona-tooltip');
const infoTrigger = document.getElementById('info-trigger');
let isRequestInProgress = false;
let currentDraftText = "";
let lastCustomFields = null;
let lastFormValues = null;
// Persona Capability Data
const personaCapabilities = {
lawyer: "Legal Professional Mode
Optimized for deep statutory analysis, procedural advice, and drafting formal legal documents with precise terminology.",
student: "Academic Mode
Focuses on legal theory, landmark Supreme Court cases, and historical context of Indian laws.",
citizen: "Empowerment Mode
Provides simple explanations of legal rights, RTI support, and step-by-step guidance for basic legal issues.",
explorer: "Orientation Mode
General overview of the Indian judicial hierarchy, history, and fundamental legal concepts."
};
function setLockdown(active) {
isRequestInProgress = active;
if (active) {
document.body.classList.add('lockdown-active');
userInput.placeholder = "Judicial Lockdown: Analysis in progress...";
sendBtn.disabled = true;
} else {
document.body.classList.remove('lockdown-active');
userInput.placeholder = "Enter your legal query here...";
sendBtn.disabled = false;
}
}
// Handle File Upload
attachBtn.addEventListener('click', () => fileUpload.click());
fileUpload.addEventListener('change', async (e) => {
const file = e.target.files[0];
if (!file) return;
addMessage(`Uploading ${file.name}...`, 'user');
const formData = new FormData();
formData.append('file', file);
try {
const response = await fetch(`${API_BASE_URL}/upload`, {
method: 'POST',
body: formData
});
const data = await response.json();
if (data.text) {
userInput.value = `Audit this document: \n\n ${data.text.substring(0, 1000)}...`;
addMessage(`Document ${file.name} processed. I have extracted the text. Click Execute to start the audit.`, 'system');
}
} catch (err) {
addMessage(`Error uploading file: ${err.message}`, 'system');
}
});
document.querySelectorAll('.persona-btn').forEach(btn => {
btn.addEventListener('click', () => {
userPersona = btn.getAttribute('data-persona');
onboardingOverlay.classList.add('hidden');
appContainer.classList.remove('blur-background');
// Update top bar status
profileStatus.innerText = userPersona.charAt(0).toUpperCase() + userPersona.slice(1) + " Dashboard";
// Apply Dynamic Theme
document.documentElement.setAttribute('data-theme', userPersona);
// Update Wisdom Tooltip
personaTooltip.innerHTML = personaCapabilities[userPersona];
addMessage(`Welcome! You are now connected as a **${userPersona.toUpperCase()}**. How can I help you navigate the legal system today?`, 'system');
});
});
function highlightCitations(text) {
// Regex to find common Indian legal citations (e.g., Section 302, Article 21, IPC 302)
const citationRegex = /\b(Section|Article|Act|Clause)\s+\d+[A-Z]?\b|\b(IPC|BNS|CRPC|CPC|DPDPA)\s+\d+[A-Z]?\b/gi;
return text.replace(citationRegex, (match) => {
return `${match}`;
});
}
switchBtn.addEventListener('click', () => {
onboardingOverlay.classList.remove('hidden');
appContainer.classList.add('blur-background');
});
// Motto Carousel Data
const mottos = [
{ text: "सत्यमेव जयते", lang: "Hindi" },
{ text: "সত্যমেব জয়তে", lang: "Bengali" },
{ text: "सत्यमेव जयते", lang: "Marathi" },
{ text: "సత్యమేవ జయతే", lang: "Telugu" },
{ text: "சத்யமேவ ஜெயதே", lang: "Tamil" },
{ text: "સત્યમેવ જયતે", lang: "Gujarati" },
{ text: "ستیہ میو جیتے", lang: "Urdu" },
{ text: "ಸತ್ಯಮೇವ ಜಯತೇ", lang: "Kannada" },
{ text: "ସତ୍ୟମେବ ଜୟତେ", lang: "Odia" },
{ text: "സത്യമേവ ജയതേ", lang: "Malayalam" }
];
let currentMottoIndex = 0;
const mottoText = document.getElementById('motto-text');
const mottoLang = document.getElementById('motto-lang');
function updateMotto() {
mottoText.classList.add('fade-out');
mottoLang.classList.add('fade-out');
setTimeout(() => {
currentMottoIndex = (currentMottoIndex + 1) % mottos.length;
mottoText.innerText = mottos[currentMottoIndex].text;
mottoLang.innerText = mottos[currentMottoIndex].lang;
mottoText.classList.remove('fade-out');
mottoLang.classList.remove('fade-out');
}, 500);
}
setInterval(updateMotto, 4000); // Change every 4 seconds
function addMessage(text, sender) {
if (text.includes('===REQUEST_NOTICE_FORM===')) {
try {
const parts = text.split('===REQUEST_NOTICE_FORM===');
const jsonStr = parts[1].trim();
const customFields = JSON.parse(jsonStr);
addNoticeForm(customFields);
} catch (e) {
console.error("Failed to parse custom fields from LLM", e);
addNoticeForm(["Sender Details (Name, Address)", "Receiver Details (Name, Address)", "Grievance / Cause of Action", "Relief / Demand"]);
}
return;
}
const msgDiv = document.createElement('div');
msgDiv.className = `message ${sender}`; // Explicitly set classes
// Highlight Citations
let highlightedText = highlightCitations(text);
// Add Spark Icon for System
if (sender === 'system') {
const spark = document.createElement('div');
spark.className = 'system-spark';
spark.innerHTML = '✨';
msgDiv.appendChild(spark);
}
const contentDiv = document.createElement('div');
contentDiv.className = 'message-content';
let renderText = highlightedText.replace('===DRAFT BEGIN===', '').replace('===DRAFT END===', '');
contentDiv.innerHTML = marked.parse(renderText);
msgDiv.appendChild(contentDiv);
// Action Button Detection (Proactive Agent Feature)
if (sender === 'system') {
const actionArea = document.createElement('div');
actionArea.classList.add('action-area');
let hasDraft = text.includes('===DRAFT BEGIN===');
if (hasDraft) {
// Helper function to extract just the draft
const extractDraft = (fullText) => {
const startMarker = '===DRAFT BEGIN===';
const endMarker = '===DRAFT END===';
let startIndex = fullText.indexOf(startMarker);
let endIndex = fullText.indexOf(endMarker);
if (startIndex !== -1 && endIndex !== -1) {
return fullText.substring(startIndex + startMarker.length, endIndex).trim();
}
return fullText; // Fallback
};
const draftText = extractDraft(text);
currentDraftText = draftText; // Store globally for editing
const copyBtn = createActionButton('copy', 'Copy Draft', () => {
navigator.clipboard.writeText(draftText);
alert('Draft copied to clipboard! (Satyameva Jayate)');
});
actionArea.appendChild(copyBtn);
const docBtn = createActionButton('file-text', 'Download DOC', () => exportToDoc(draftText));
actionArea.appendChild(docBtn);
const pdfBtn = createActionButton('download', 'Download PDF', () => exportToPdf(draftText));
actionArea.appendChild(pdfBtn);
const editBtn = createActionButton('edit-3', 'Edit Draft', () => {
if (lastCustomFields && lastFormValues) {
addNoticeForm(lastCustomFields, lastFormValues);
} else {
addNoticeForm([], []); // Show form with just Additional Instructions
}
});
actionArea.appendChild(editBtn);
} else {
if (text.toLowerCase().includes('rti query') || text.toLowerCase().includes('rti act')) {
const btn = createActionButton('scroll', 'Draft RTI Query', () => {
userInput.value = "Draft an RTI query for this matter.";
handleSendMessage();
});
actionArea.appendChild(btn);
}
if (text.toLowerCase().includes('legal notice')) {
const btn = createActionButton('file-text', 'Prepare Legal Notice', () => {
userInput.value = "Please draft a legal notice for this matter.";
handleSendMessage();
});
actionArea.appendChild(btn);
}
}
if (actionArea.children.length > 0) {
msgDiv.appendChild(actionArea);
}
}
const time = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
const timeSpan = document.createElement('span');
timeSpan.classList.add('message-time');
timeSpan.innerText = time;
msgDiv.appendChild(timeSpan);
chatMessages.appendChild(msgDiv);
setTimeout(scrollToBottom, 50); // Small delay for smooth rendering
lucide.createIcons();
}
function scrollToBottom() {
chatMessages.scrollTo({
top: chatMessages.scrollHeight,
behavior: 'smooth'
});
}
function exportToDoc(text) {
const header = "