Spaces:
Sleeping
Sleeping
File size: 45,694 Bytes
e2a1a46 87f7912 e2a1a46 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 | /*
* 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 = '<div style="padding: 12px; color: var(--text-secondary); font-size: 13px;">Please log in to view history</div>';
}
});
});
}).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 = '<div class="empty-state"><p>No medicines detected.</p></div>';
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 = `
<div class="med-disclaimer med-disclaimer-bg">
<i class="fas fa-exclamation-triangle"></i>
<div>
<strong>Low AI certainty.</strong> Result likely inaccurate. Verify manually.
</div>
</div>`;
} else if (conf < 95) {
// Moderate Certainty (< 95%) - As requested
confColor = 'var(--warning-text)';
disclaimerHTML = `
<div class="med-disclaimer med-disclaimer-bg warning">
<i class="fas fa-info-circle"></i>
<div>
<strong>Verify this result.</strong> AI confidence is below 95%.
</div>
</div>`;
}
card.className = cardClass;
card.innerHTML = `
<div class="med-header">
<div class="med-name">${med.name}</div>
<div style="font-size: 10px; font-weight: 700; color: ${confColor}; background: var(--bg-panel); padding: 2px 6px; border-radius: 4px;">
${conf}%
</div>
</div>
<div class="med-grid">
<div class="med-field">
<span class="med-label">Strength</span>
<span class="med-value">${med.strength || '--'}</span>
</div>
<div class="med-field">
<span class="med-label">Frequency</span>
<span class="med-value">${med.frequency || '--'}</span>
</div>
</div>
${med.instructions ? `
<div class="med-footer">
<i class="fas fa-info-circle"></i>
<div style="flex: 1;">${createExpandableText(med.instructions)}</div>
</div>` : ''}
${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 = '<div style="text-align:center; padding: 2rem; color: var(--text-secondary);"><i class="fas fa-circle-notch fa-spin"></i> Checking interactions...</div>';
if (!medicines || medicines.length < 2) {
list.innerHTML = `
<div class="card safety-card mild">
<div class="safety-icon-box"><i class="fas fa-check-circle"></i></div>
<div class="safety-content">
<div class="safety-header"><span class="safety-title">No Interactions</span></div>
<p>Single medication detected.</p>
</div>
</div>`;
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 = `
<div class="safety-icon-box"><i class="fas ${iconClass}"></i></div>
<div class="safety-content">
<div class="safety-header"><span class="safety-title">${interaction.severity} Interaction</span></div>
<p><strong>${interaction.medicine_a} + ${interaction.medicine_b}</strong></p>
${createExpandableText(interaction.description)}
</div>
`;
list.appendChild(card);
});
} else {
list.innerHTML = `
<div class="card safety-card mild">
<div class="safety-icon-box"><i class="fas fa-check-circle"></i></div>
<div class="safety-content">
<div class="safety-header"><span class="safety-title">Safe Combination</span></div>
<p>No known interactions found.</p>
</div>
</div>`;
}
} catch (error) {
console.error("Interaction Check Error:", error);
list.innerHTML = '<div class="card safety-card moderate"><p>Could not verify interactions.</p></div>';
}
}
function createExpandableText(text, limit = 100) {
if (!text) return '';
if (text.length <= limit) return `<p>${text}</p>`;
// Generate unique ID for toggle
const id = 'expand-' + Math.random().toString(36).substr(2, 9);
return `
<div>
<p id="${id}" class="line-clamp-2" style="margin-bottom: 0;">${text}</p>
<button class="expand-btn" onclick="toggleExpand('${id}', this)">Show more</button>
</div>
`;
}
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 += '<div style="padding: 0 12px; font-size: 13px; color: var(--text-secondary);">No scans yet</div>';
} else {
history.forEach(item => {
const itemEl = document.createElement('div');
itemEl.className = 'history-item';
itemEl.innerHTML = `
<div class="history-content">
<i class="fas fa-file-medical-alt"></i>
<span class="history-text">${item.patientName || "Unknown Patient"}</span>
</div>
<div class="history-menu-container">
<button class="history-menu-btn"><i class="fas fa-ellipsis-v"></i></button>
<div class="history-menu-dropdown">
<div class="history-menu-item delete-item">
<i class="fas fa-trash-alt"></i> Delete
</div>
</div>
</div>
`;
// 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");
}
|