/*
* AI Prescription Assistant - Frontend Logic
* Handles UI interactions, API calls, and data rendering.
*/
// --- Global State ---
let currentAnalysis = null;
let isScanning = false;
// --- Initialization ---
document.addEventListener('DOMContentLoaded', () => {
// Set initial state
document.body.classList.add('startup-mode');
// Attempt to load from cache immediately (optimistic UI)
loadHistory();
// Check auth state for header links
import('./auth.js').then(module => {
// Protect this route - true means redirect if not logged in
// module.initAuthObserver(true);
module.initAuthObserver(false); // DISABLED FOR DEMO
// Settings Modal Logic
const settingsBtn = document.getElementById('settings-btn');
const settingsModal = document.getElementById('settings-modal');
const modalLogoutBtn = document.getElementById('modal-logout-btn');
const themeSelect = document.getElementById('theme-select');
// Open Settings
if (settingsBtn) {
settingsBtn.addEventListener('click', () => {
settingsModal.classList.add('show');
});
}
// Close Settings (Global function for HTML onclick)
window.closeSettingsModal = () => {
settingsModal.classList.remove('show');
};
// Close on outside click
if (settingsModal) {
settingsModal.addEventListener('click', (e) => {
if (e.target === settingsModal) {
closeSettingsModal();
}
});
}
// Logout from Modal
if (modalLogoutBtn) {
modalLogoutBtn.addEventListener('click', () => {
module.logoutUser();
});
}
// Theme Handling
const applyTheme = (theme) => {
const root = document.documentElement;
if (theme === 'dark') {
document.body.classList.add('dark-mode');
// ChatGPT-like Dark Theme (Modern)
root.style.setProperty('--bg-body', '#212121');
root.style.setProperty('--bg-app', '#212121');
root.style.setProperty('--bg-panel', '#171717'); // Darker Sidebar
root.style.setProperty('--bg-surface', '#2F2F2F'); // Cards/Modals
root.style.setProperty('--text-primary', '#ECECF1');
root.style.setProperty('--text-secondary', '#C5C5D2');
root.style.setProperty('--border-color', '#333333');
root.style.setProperty('--bg-hover', '#424242');
// Dark Mode Alerts
root.style.setProperty('--success-bg', '#062F1A');
root.style.setProperty('--success-text', '#57D9A3');
root.style.setProperty('--success-border', '#216E4E');
root.style.setProperty('--warning-bg', '#332200');
root.style.setProperty('--warning-text', '#FFAB00');
root.style.setProperty('--warning-border', '#7F5F01');
root.style.setProperty('--danger-bg', '#290B0B');
root.style.setProperty('--danger-text', '#FF5630');
root.style.setProperty('--danger-border', '#BF2600');
} else if (theme === 'light') {
document.body.classList.remove('dark-mode');
root.removeAttribute('style'); // Revert to CSS defaults
} else {
// System - Check preference
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
applyTheme('dark');
} else {
applyTheme('light');
}
}
};
window.applyTheme = applyTheme;
if (themeSelect) {
// Load saved theme
const savedTheme = localStorage.getItem('appTheme') || 'system';
themeSelect.value = savedTheme;
applyTheme(savedTheme);
themeSelect.addEventListener('change', (e) => {
const theme = e.target.value;
localStorage.setItem('appTheme', theme);
applyTheme(theme);
});
}
// Initialize Custom Theme Dropdown
const savedTheme = localStorage.getItem('theme') || 'system';
const currentThemeText = document.getElementById('current-theme-text');
if (currentThemeText) {
currentThemeText.textContent = savedTheme.charAt(0).toUpperCase() + savedTheme.slice(1);
document.querySelectorAll('.custom-option').forEach(opt => {
opt.classList.remove('selected');
if (opt.dataset.value === savedTheme) opt.classList.add('selected');
});
applyTheme(savedTheme);
}
// Setup Sidebar Profile
const sidebarProfileBtn = document.getElementById('sidebar-profile-btn');
if (sidebarProfileBtn) {
sidebarProfileBtn.addEventListener('click', async () => {
const modal = document.getElementById('profile-modal');
modal.style.display = 'flex';
const renderProfile = (profile) => {
if (profile) {
document.getElementById('profile-email').textContent = profile.email;
document.getElementById('profile-uid').textContent = profile.uid;
// Format date
let dateStr = "N/A";
if (profile.createdAt) {
// Firestore timestamp or server timestamp
const date = profile.createdAt.toDate ? profile.createdAt.toDate() : new Date(profile.createdAt);
dateStr = date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
}
document.getElementById('profile-created').textContent = dateStr;
// Scan count
const count = profile.scanningHistory ? profile.scanningHistory.length : 0;
document.getElementById('profile-scans').textContent = count;
}
};
// 1. Try Cache
const cachedProfile = localStorage.getItem('cachedProfile');
if (cachedProfile) {
renderProfile(JSON.parse(cachedProfile));
} else {
// Show loading only if no cache
document.getElementById('profile-email').textContent = "Loading...";
document.getElementById('profile-uid').textContent = "...";
document.getElementById('profile-created').textContent = "...";
document.getElementById('profile-scans').textContent = "...";
}
// 2. Load Fresh Data
try {
const db = await import('./db.js');
const profile = await db.getUserProfile();
if (profile) {
localStorage.setItem('cachedProfile', JSON.stringify(profile));
renderProfile(profile);
}
} catch (e) {
console.error("Profile load error", e);
if (!cachedProfile) {
showError(`Failed to load profile data: ${e.message}`);
}
}
});
}
// Custom observer for header UI
import('./firebase-config.js').then(fb => {
fb.auth.onAuthStateChanged(user => {
const loginLink = document.getElementById('nav-login');
const signupLink = document.getElementById('nav-signup');
const dashboardLink = document.getElementById('nav-dashboard');
if (user) {
if (loginLink) loginLink.style.display = 'none';
if (signupLink) signupLink.style.display = 'none';
if (dashboardLink) dashboardLink.style.display = 'inline-block';
// Load history only when user is authenticated
loadHistory();
} else {
if (loginLink) loginLink.style.display = 'inline-block';
if (signupLink) signupLink.style.display = 'inline-block';
if (dashboardLink) dashboardLink.style.display = 'none';
// Clear history if logged out
const sidebarList = document.getElementById('sidebar-history-list');
if (sidebarList) sidebarList.innerHTML = '
Please log in to view history
';
}
});
});
}).catch(err => console.log("Auth module not loaded"));
console.log("Medical SaaS UI Initialized");
setupEventListeners();
});
// --- Event Listeners ---
function setupEventListeners() {
// Sidebar Toggle (Mobile)
const sidebarToggle = document.getElementById('sidebar-toggle');
const sidebar = document.getElementById('app-sidebar');
const overlay = document.getElementById('sidebar-overlay');
if (sidebarToggle && sidebar && overlay) {
sidebarToggle.addEventListener('click', () => {
sidebar.classList.add('show');
overlay.classList.add('show');
});
overlay.addEventListener('click', () => {
sidebar.classList.remove('show');
overlay.classList.remove('show');
});
}
// File Upload (Click & Drag)
const uploadZone = document.getElementById('upload-zone');
const fileInput = document.getElementById('file-input');
const selectFileBtn = document.getElementById('select-file-btn');
if (selectFileBtn) {
selectFileBtn.addEventListener('click', (e) => {
e.stopPropagation(); // Prevent bubbling to uploadZone
if (!navigator.onLine) {
showToast("You are offline. Please check your internet connection.", "error");
return;
}
fileInput.click();
});
}
if (uploadZone) {
uploadZone.addEventListener('click', () => {
if (!navigator.onLine) {
showToast("You are offline. Please check your internet connection.", "error");
return;
}
fileInput.click();
});
uploadZone.addEventListener('dragover', (e) => {
e.preventDefault();
uploadZone.classList.add('dragover');
});
uploadZone.addEventListener('dragleave', () => {
uploadZone.classList.remove('dragover');
});
uploadZone.addEventListener('drop', (e) => {
e.preventDefault();
uploadZone.classList.remove('dragover');
if (e.dataTransfer.files.length) {
handleFileSelect(e.dataTransfer.files[0]);
}
});
}
if (fileInput) {
fileInput.addEventListener('click', (e) => {
e.stopPropagation();
});
fileInput.addEventListener('change', (e) => {
if (e.target.files.length) {
handleFileSelect(e.target.files[0]);
}
});
}
// Reset App Listeners
const newScanBtn = document.getElementById('new-scan-btn');
const closeDetailsBtn = document.getElementById('close-details-btn');
if (newScanBtn) {
newScanBtn.addEventListener('click', resetApp);
}
if (closeDetailsBtn) {
closeDetailsBtn.addEventListener('click', resetApp);
}
// Panel Tab Listeners
const panelTabs = document.querySelectorAll('.panel-tab');
panelTabs.forEach(tab => {
tab.addEventListener('click', () => {
const tabId = tab.getAttribute('data-tab');
switchPanelTab(tabId);
});
});
}
// --- File Handling & UI State ---
function handleFileSelect(file) {
if (!file) return;
window.currentFile = file;
// Compress and store Base64 for history
compressImage(file).then(base64 => {
window.currentImageBase64 = base64;
analyzeFullPrescription();
}).catch(err => {
console.error("Image compression failed:", err);
// Proceed without base64 (history image won't work, but analysis will)
analyzeFullPrescription();
});
}
function compressImage(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = (event) => {
const img = new Image();
img.src = event.target.result;
img.onload = () => {
const canvas = document.createElement('canvas');
const MAX_WIDTH = 800;
const scaleSize = MAX_WIDTH / img.width;
canvas.width = MAX_WIDTH;
canvas.height = img.height * scaleSize;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
// Compress to JPEG with 0.7 quality
resolve(canvas.toDataURL('image/jpeg', 0.7));
};
img.onerror = (err) => reject(err);
};
reader.onerror = (err) => reject(err);
});
}
function resetApp() {
// Reset to Startup View
document.getElementById('startup-view').style.display = 'flex';
document.getElementById('results-view').style.display = 'none';
document.body.classList.add('startup-mode'); // Switch header to sidebar color
// Reset inputs
document.getElementById('file-input').value = '';
window.currentFile = null;
currentAnalysis = null;
}
function switchPanelTab(tabId) {
// Update Buttons
document.querySelectorAll('.panel-tab').forEach(btn => {
btn.classList.remove('active');
if (btn.dataset.tab === tabId) btn.classList.add('active');
});
// Update Panes
document.querySelectorAll('.panel-pane').forEach(pane => {
pane.classList.remove('active');
});
document.getElementById(`panel-${tabId}`).classList.add('active');
}
// --- Analysis Logic ---
async function analyzeFullPrescription() {
if (!navigator.onLine) {
showError("You are offline. Please check your internet connection.");
return;
}
if (!window.currentFile) {
showToast("Please select a file first.", "error");
return;
}
// Stepwise Loading
const loadingSteps = [
{ msg: "Reading prescription...", delay: 0 },
{ msg: "Extracting text...", delay: 1500 },
{ msg: "Identifying drugs...", delay: 3000 },
{ msg: "Checking interactions...", delay: 4500 },
{ msg: "Preparing report...", delay: 6000 }
];
showLoading(true, loadingSteps[0].msg);
// Simulate steps visually while waiting for API
let stepIndex = 1;
const stepInterval = setInterval(() => {
if (stepIndex < loadingSteps.length) {
updateLoadingMessage(loadingSteps[stepIndex].msg);
stepIndex++;
}
}, 1500);
const formData = new FormData();
formData.append('file', window.currentFile);
const options = {
ocr_engine: 'smart',
enhancement_level: 'heavy'
};
formData.append('options', JSON.stringify(options));
try {
const response = await fetch('/api/process', {
method: 'POST',
body: formData
});
clearInterval(stepInterval); // Stop simulated steps
if (!response.ok) throw new Error("Analysis failed");
const data = await response.json();
// Backend returns wrapped response, extract prescription_data
if (!data.success) throw new Error(data.error || "Processing failed");
// Check if it is a valid prescription
if (data.prescription_data && data.prescription_data.is_prescription === false) {
showError("The uploaded image does not appear to be a valid prescription. Please upload a clear medical prescription.");
return;
}
currentAnalysis = data.prescription_data; // Store structured data
// Add confidence score from top level
currentAnalysis.confidence_score = data.prescription_data.extraction_confidence || 0.95;
// Attach compressed image for history
if (window.currentImageBase64) {
currentAnalysis.image = window.currentImageBase64;
}
displayAnalysis(currentAnalysis);
saveToHistory(currentAnalysis);
} catch (error) {
clearInterval(stepInterval);
console.error("Analysis Error:", error);
showError("Failed to analyze prescription. Please try again.");
} finally {
showLoading(false);
}
}
// --- Display Logic ---
function displayAnalysis(data) {
// Switch Views
document.getElementById('startup-view').style.display = 'none';
document.getElementById('results-view').style.display = 'flex';
document.body.classList.remove('startup-mode'); // Switch header to white
// 1. Update Center Panel (Summary)
document.getElementById('header-confidence').textContent = `${Math.round((data.confidence_score || 0) * 100)}% Confidence`;
// 1. Update Center Panel (Summary)
document.getElementById('header-confidence').textContent = `${Math.round((data.confidence_score || 0) * 100)}% Confidence`;
// File Info - Removed as per layout change
// Update Image Viewer
const imgEl = document.getElementById('thumbnail-image');
if (data.image) {
imgEl.src = data.image;
} else if (window.currentFile) {
const reader = new FileReader();
reader.onload = (e) => { imgEl.src = e.target.result; };
reader.readAsDataURL(window.currentFile);
} else {
// Demo mode fallback
imgEl.src = "https://via.placeholder.com/400x500?text=Prescription+Image";
}
// Patient Info
const patientName = data.patient_name || data.patient_info?.name || "Not detected";
const doctorName = data.doctor_name || data.doctor_info?.name || "Not detected";
const date = data.date || "Not detected";
document.getElementById('patient-name').textContent = patientName;
document.getElementById('doctor-name').textContent = doctorName;
document.getElementById('prescription-date').textContent = date;
displayHealthTip(data.health_tip);
// 2. Update Right Panel (Medicines & Safety)
displayMedicines(data.medicines);
checkInteractions(data.medicines);
}
function displayHealthTip(tip) {
const section = document.getElementById('health-tip-section');
const content = document.getElementById('health-tip-content');
if (tip) {
content.textContent = tip;
section.style.display = 'flex';
} else {
section.style.display = 'none';
}
}
function displayMedicines(medicines) {
const list = document.getElementById('medicines-list');
list.innerHTML = '';
if (!medicines || medicines.length === 0) {
list.innerHTML = '';
return;
}
medicines.forEach((med, index) => {
const card = document.createElement('div');
let cardClass = 'card medicine-card';
// Confidence Logic
const conf = Math.round((med.confidence_score || med.confidence || 0) * 100);
let confColor = 'var(--success-text)';
let disclaimerHTML = '';
if (conf < 70) {
// Low Certainty (< 70%)
cardClass += ' med-low-certainty';
confColor = 'var(--danger-text)';
disclaimerHTML = `
Low AI certainty. Result likely inaccurate. Verify manually.
`;
} else if (conf < 95) {
// Moderate Certainty (< 95%) - As requested
confColor = 'var(--warning-text)';
disclaimerHTML = `
Verify this result. AI confidence is below 95%.
`;
}
card.className = cardClass;
card.innerHTML = `
Strength
${med.strength || '--'}
Frequency
${med.frequency || '--'}
${med.instructions ? `
` : ''}
${disclaimerHTML}
`;
list.appendChild(card);
});
}
function toggleDisclaimer(id) {
const el = document.getElementById(id);
if (el) el.classList.toggle('show');
}
async function checkInteractions(medicines) {
const list = document.getElementById('interactions-list');
list.innerHTML = ' Checking interactions...
';
if (!medicines || medicines.length < 2) {
list.innerHTML = `
Single medication detected.
`;
return;
}
try {
const medNames = medicines.map(m => m.name);
const response = await fetch('/api/check-interactions', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ medicines: medNames })
});
const data = await response.json();
list.innerHTML = '';
if (data.interactions && data.interactions.length > 0) {
data.interactions.forEach(interaction => {
const severityClass = getSeverityClass(interaction.severity);
const iconClass = getSeverityIcon(interaction.severity);
const card = document.createElement('div');
card.className = `card safety-card ${severityClass}`;
card.innerHTML = `
${interaction.medicine_a} + ${interaction.medicine_b}
${createExpandableText(interaction.description)}
`;
list.appendChild(card);
});
} else {
list.innerHTML = `
No known interactions found.
`;
}
} catch (error) {
console.error("Interaction Check Error:", error);
list.innerHTML = 'Could not verify interactions.
';
}
}
function createExpandableText(text, limit = 100) {
if (!text) return '';
if (text.length <= limit) return `${text}
`;
// Generate unique ID for toggle
const id = 'expand-' + Math.random().toString(36).substr(2, 9);
return `
`;
}
window.toggleExpand = function (id, btn) {
const p = document.getElementById(id);
if (p.classList.contains('line-clamp-2')) {
p.classList.remove('line-clamp-2');
btn.textContent = "Show less";
} else {
p.classList.add('line-clamp-2');
btn.textContent = "Show more";
}
}
function getSeverityClass(severity) {
if (!severity) return 'mild';
const s = severity.toLowerCase();
if (s.includes('major') || s.includes('severe') || s.includes('critical')) return 'critical';
if (s.includes('moderate')) return 'moderate';
return 'mild';
}
function getSeverityIcon(severity) {
if (!severity) return 'fa-info-circle';
const s = severity.toLowerCase();
if (s.includes('major') || s.includes('severe') || s.includes('critical')) return 'fa-exclamation-circle';
if (s.includes('moderate')) return 'fa-exclamation-triangle';
return 'fa-check-circle';
}
// --- Loading Overlay ---
function showLoading(show, msg = "Processing...") {
const overlay = document.getElementById('loading-overlay');
if (!overlay) return;
overlay.style.display = show ? 'flex' : 'none';
if (show) {
updateLoadingMessage(msg);
}
}
function updateLoadingMessage(msg) {
const el = document.getElementById('loading-subtitle');
if (el) el.textContent = msg;
}
// --- Demo Mode ---
function loadDemoSample() {
// Simulate File Selection
const demoFile = { name: "demo_prescription_sample.jpg" };
window.currentFile = demoFile;
// Show Loading
showLoading(true);
// Simulate Steps
const steps = ["Reading prescription...", "Extracting text...", "Identifying drugs...", "Checking interactions...", "Preparing report..."];
let step = 0;
const interval = setInterval(() => {
if (step < steps.length) {
updateLoadingMessage(steps[step]);
step++;
} else {
clearInterval(interval);
finishDemoLoad();
}
}, 800);
}
function finishDemoLoad() {
showLoading(false);
// Mock Data
const mockData = {
patient_name: "Arya Krishnan",
doctor_name: "Dr. S. P. Kumar",
date: "20/11/2025",
confidence_score: 0.98,
health_tip: "Keep the child hydrated and monitor breathing patterns closely.",
medicines: [
{
name: "Salbutamol Nebulisation",
strength: "2.5mg",
frequency: "STAT",
duration: "Once",
instructions: "Administer immediately via nebulizer.",
confidence: 0.99
},
{
name: "Acefylline",
strength: "100mg",
frequency: "BID",
duration: "3 Days",
instructions: "Take one tablet twice daily after food.",
confidence: 0.89
},
{
name: "Salbutamol Syrup",
strength: "5ml",
frequency: "TDS",
duration: "5 Days",
instructions: "5ml three times daily.",
confidence: 0.95
}
]
};
currentAnalysis = mockData;
displayAnalysis(mockData);
}
// --- Utilities ---
function getFriendlyErrorMessage(error) {
// Log full error
console.error("App Error:", error);
const errorCode = error && error.code ? error.code : null;
const errorMessage = error && error.message ? error.message : (typeof error === 'string' ? error : JSON.stringify(error));
if (errorCode) {
switch (errorCode) {
case 'auth/weak-password': return "Password is too weak. Please use at least 6 characters.";
case 'auth/email-already-in-use': return "This email is already registered.";
case 'auth/user-not-found': return "No account found with this email.";
case 'auth/wrong-password': return "Incorrect password.";
case 'auth/invalid-email': return "Please enter a valid email address.";
case 'auth/network-request-failed': return "Network error. Check your connection.";
case 'auth/too-many-requests': return "Too many attempts. Try again later.";
case 'auth/popup-closed-by-user': return "Sign-in popup was closed.";
case 'auth/internal-error': return "An internal error occurred.";
case 'auth/requires-recent-login': return "Please log in again.";
case 'auth/account-exists-with-different-credential': return "An account with this email already exists. Please use your original login method.";
case 'permission-denied': return "You do not have permission to perform this action.";
case 'unavailable': return "Service temporarily unavailable.";
}
}
// Clean up Firebase raw messages if they slip through
if (errorMessage && typeof errorMessage === 'string') {
if (errorMessage.includes("Firebase:")) {
return "An error occurred. Please try again.";
}
return errorMessage;
}
return "An unexpected error occurred.";
}
let errorTimeout;
function showError(error) {
const msg = getFriendlyErrorMessage(error);
const toast = document.getElementById('error-toast');
const toastMsg = document.getElementById('error-toast-msg');
if (toast && toastMsg) {
toastMsg.textContent = msg;
toast.classList.add('show');
// Clear previous timeout
if (errorTimeout) clearTimeout(errorTimeout);
// Auto-hide after 5 seconds
errorTimeout = setTimeout(() => {
toast.classList.remove('show');
}, 5000);
} else {
alert(msg); // Fallback
}
}
window.closeModal = function (id) {
const modal = document.getElementById(id);
if (modal) modal.style.display = 'none';
}
function showToast(msg, type = 'info') {
console.log(`[Toast]: ${msg}`);
}
// Global Error Handlers
window.onerror = function (message, source, lineno, colno, error) {
console.error("Global Error:", message, error);
showError(error || message);
return true; // Prevent default browser error handling
};
window.onunhandledrejection = function (event) {
console.error("Unhandled Promise Rejection:", event.reason);
showError(event.reason);
};
window.addEventListener('offline', () => {
showError("You are offline. Please check your internet connection.");
});
window.addEventListener('online', () => {
// Optional: Auto-dismiss or show "Back online" toast
console.log("Back online");
});
function switchTab(tabId) {
// Update Buttons
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.classList.remove('active');
if (btn.dataset.tab === tabId) btn.classList.add('active');
});
// Update Panes
document.querySelectorAll('.tab-pane').forEach(pane => {
pane.classList.remove('active');
});
document.getElementById(`tab-${tabId}`).classList.add('active');
}
async function loadHistory() {
const lastScanEl = document.getElementById('header-last-scan');
const sidebarList = document.getElementById('sidebar-history-list');
const sidebarEmail = document.getElementById('sidebar-email');
const sidebarAvatar = document.getElementById('sidebar-avatar');
// Helper to render sidebar content
const renderSidebar = (history, profile) => {
// Update Sidebar Profile
if (profile) {
if (sidebarEmail) sidebarEmail.textContent = profile.email;
if (sidebarAvatar) sidebarAvatar.textContent = profile.email.charAt(0).toUpperCase();
}
// Update Sidebar History
if (sidebarList) {
sidebarList.innerHTML = '';
if (!history || history.length === 0) {
sidebarList.innerHTML += 'No scans yet
';
} else {
history.forEach(item => {
const itemEl = document.createElement('div');
itemEl.className = 'history-item';
itemEl.innerHTML = `
${item.patientName || "Unknown Patient"}
`;
// Click handler for the main item (load details)
itemEl.querySelector('.history-content').addEventListener('click', () => {
if (item.data) {
currentAnalysis = item.data;
displayAnalysis(item.data);
document.getElementById('startup-view').style.display = 'none';
document.getElementById('results-view').style.display = 'flex';
document.querySelectorAll('.history-item').forEach(el => el.classList.remove('active'));
itemEl.classList.add('active');
// Close sidebar on mobile
if (window.innerWidth <= 768) {
document.getElementById('app-sidebar').classList.remove('show');
document.getElementById('sidebar-overlay').classList.remove('show');
}
} else {
showToast("Details not available for this older scan.", "warning");
}
});
// Menu Toggle
const menuBtn = itemEl.querySelector('.history-menu-btn');
const dropdown = itemEl.querySelector('.history-menu-dropdown');
menuBtn.addEventListener('click', (e) => {
e.stopPropagation();
// Close other open menus
document.querySelectorAll('.history-menu-dropdown.show').forEach(d => {
if (d !== dropdown) d.classList.remove('show');
});
// Toggle visibility
const isShowing = dropdown.classList.contains('show');
if (!isShowing) {
dropdown.classList.add('show');
// Dynamic Positioning
const rect = menuBtn.getBoundingClientRect();
dropdown.style.position = 'fixed';
dropdown.style.top = `${rect.bottom + 5}px`;
dropdown.style.left = `${rect.right - 120}px`; // Align right edge
dropdown.style.width = '120px';
dropdown.style.zIndex = '9999';
} else {
dropdown.classList.remove('show');
}
});
// Delete Handler
const deleteBtn = itemEl.querySelector('.delete-item');
deleteBtn.addEventListener('click', async (e) => {
e.stopPropagation();
// Close menu
dropdown.classList.remove('show');
showConfirmModal(async () => {
// Optimistic UI Update: Remove immediately
itemEl.style.opacity = '0';
setTimeout(() => itemEl.remove(), 300); // Smooth fade out
showToast("Scan deleted.");
try {
const db = await import('./db.js');
// Fire and forget (don't await for UI)
db.deleteHistoryItem(item.id).catch(err => {
console.error("Error deleting item:", err);
showToast("Failed to delete scan.", "error");
loadHistory(); // Revert on error
});
} catch (err) {
console.error("Import error:", err);
}
});
});
sidebarList.appendChild(itemEl);
});
}
}
if (history.length > 0) {
const lastDate = new Date(history[0].timestamp);
if (lastScanEl) lastScanEl.textContent = lastDate.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
} else {
if (lastScanEl) lastScanEl.textContent = "None";
}
};
// 1. Try to load from Cache first (Instant Load)
try {
const cachedHistory = localStorage.getItem('cachedHistory');
const cachedProfile = localStorage.getItem('cachedProfile');
if (cachedHistory || cachedProfile) {
if (lastScanEl) lastScanEl.textContent = "";
const history = cachedHistory ? JSON.parse(cachedHistory) : [];
const profile = cachedProfile ? JSON.parse(cachedProfile) : null;
renderSidebar(history, profile);
} else {
if (lastScanEl) lastScanEl.textContent = "Loading...";
}
} catch (e) {
console.error("Cache read error", e);
}
// 2. Fetch Fresh Data (Background Update)
try {
const db = await import('./db.js');
const history = await db.getUserHistory();
const profile = await db.getUserProfile();
// Update Cache
localStorage.setItem('cachedHistory', JSON.stringify(history));
if (profile) localStorage.setItem('cachedProfile', JSON.stringify(profile));
// Re-render with fresh data
renderSidebar(history, profile);
if (lastScanEl) lastScanEl.textContent = "";
} catch (error) {
console.error("Error loading history:", error);
if (lastScanEl) lastScanEl.textContent = "Error";
}
}
function showConfirmModal(onConfirm) {
const modal = document.getElementById('confirm-modal');
const cancelBtn = document.getElementById('confirm-cancel-btn');
const deleteBtn = document.getElementById('confirm-delete-btn');
modal.style.display = 'flex';
// One-time event listeners
const handleCancel = () => {
modal.style.display = 'none';
cleanup();
};
const handleConfirm = () => {
modal.style.display = 'none';
cleanup();
onConfirm();
};
const cleanup = () => {
cancelBtn.removeEventListener('click', handleCancel);
deleteBtn.removeEventListener('click', handleConfirm);
};
cancelBtn.addEventListener('click', handleCancel);
deleteBtn.addEventListener('click', handleConfirm);
}
function saveToHistory(data) {
// Save to Firestore (if logged in)
import('./db.js').then(module => {
module.saveScanToHistory(data);
// Reload history display to update "Last Scan"
setTimeout(loadHistory, 1000);
}).catch(err => console.log("Firestore save skipped (offline or module error)"));
}
window.zoomImage = function () {
const img = document.getElementById('thumbnail-image');
const modal = document.getElementById('image-modal');
const zoomedImg = document.getElementById('zoomed-image');
if (img.src && modal && zoomedImg) {
zoomedImg.src = img.src;
modal.style.display = 'flex'; // Flex to center
}
}
window.closeImageModal = function () {
const modal = document.getElementById('image-modal');
if (modal) {
modal.style.display = 'none';
document.getElementById('zoomed-image').src = ''; // Clear src
}
}
// Close on click outside
document.getElementById('image-modal')?.addEventListener('click', function (e) {
if (e.target === this) {
window.closeImageModal();
}
});
// --- Custom Theme Dropdown Logic ---
window.toggleThemeDropdown = function () {
const options = document.getElementById('theme-options');
options.classList.toggle('show');
}
window.selectTheme = function (theme) {
// Update UI
document.getElementById('current-theme-text').textContent = theme.charAt(0).toUpperCase() + theme.slice(1);
// Update Selected State
document.querySelectorAll('.custom-option').forEach(opt => {
opt.classList.remove('selected');
if (opt.dataset.value === theme) opt.classList.add('selected');
});
// Apply Theme
applyTheme(theme);
localStorage.setItem('theme', theme);
// Close Dropdown
document.getElementById('theme-options').classList.remove('show');
}
// Close dropdown when clicking outside
document.addEventListener('click', function (e) {
const container = document.getElementById('theme-dropdown');
if (container && !container.contains(e.target)) {
document.getElementById('theme-options').classList.remove('show');
}
});
// Initialize Dropdown State
// Export functions (Mock)
function hasLowConfidenceItems() {
if (!currentAnalysis || !currentAnalysis.medicines) return false;
return currentAnalysis.medicines.some(m => {
const conf = (m.confidence_score || m.confidence || 0) * 100;
return conf < 70;
});
}
async function downloadPDF() {
if (hasLowConfidenceItems()) {
if (!confirm("⚠️ Warning: Some items have low AI certainty (<70%).\n\nThese results are not medically usable. Do you still want to export?")) {
return;
}
}
showToast("Generating PDF report...");
try {
const response = await fetch('/api/generate-pdf', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(currentAnalysis)
});
if (!response.ok) throw new Error("PDF generation failed");
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `prescription_report_${new Date().toISOString().slice(0, 10)}.pdf`;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
showToast("PDF downloaded successfully!", "success");
} catch (error) {
console.error("PDF Export Error:", error);
showError("Failed to generate PDF report.");
}
}
function copyToClipboard() {
if (!currentAnalysis) return;
if (hasLowConfidenceItems()) {
if (!confirm("⚠️ Warning: Some items have low AI certainty (<70%).\n\nDo you still want to copy?")) {
return;
}
}
const text = JSON.stringify(currentAnalysis, null, 2);
navigator.clipboard.writeText(text).then(() => {
showToast("Copied to clipboard!", "success");
}).catch(err => {
console.error('Failed to copy: ', err);
showError("Failed to copy to clipboard.");
});
}
function downloadJSON() {
if (hasLowConfidenceItems()) {
if (!confirm("⚠️ Warning: Some items have low AI certainty (<70%).\n\nDo you still want to export?")) {
return;
}
}
const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(currentAnalysis, null, 2));
const downloadAnchorNode = document.createElement('a');
downloadAnchorNode.setAttribute("href", dataStr);
downloadAnchorNode.setAttribute("download", `prescription_data_${new Date().toISOString().slice(0, 10)}.json`);
document.body.appendChild(downloadAnchorNode); // required for firefox
downloadAnchorNode.click();
downloadAnchorNode.remove();
showToast("JSON file downloaded!", "success");
}