File size: 11,047 Bytes
1957858
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8990132
 
1957858
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8990132
1957858
8990132
1957858
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8990132
 
1957858
8990132
1957858
 
8990132
 
1957858
 
 
 
 
 
8990132
 
1957858
8990132
1957858
 
 
8990132
1957858
 
 
8990132
1957858
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b3ff308
 
 
1957858
 
8990132
 
1957858
 
 
 
 
b3ff308
 
1957858
 
 
 
 
 
 
 
 
8990132
1957858
 
 
 
 
8990132
1957858
 
b3ff308
 
1957858
 
 
 
 
 
 
 
 
 
b3ff308
1957858
 
b3ff308
 
1957858
8990132
1957858
8990132
1957858
 
 
 
 
8990132
 
1957858
8990132
 
1957858
 
 
 
8990132
 
 
1957858
8990132
1957858
 
 
 
8990132
1957858
 
 
 
 
 
 
8990132
1957858
8990132
1957858
8990132
1957858
 
 
8990132
1957858
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8990132
1957858
 
 
 
 
 
 
 
8990132
1957858
 
 
 
 
 
 
 
 
8990132
1957858
 
 
 
 
 
8990132
1957858
 
8990132
 
1957858
 
 
 
8990132
 
1957858
 
8990132
 
 
 
 
 
 
 
1957858
8990132
1957858
8990132
1957858
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
 /* ===========================================================
   Rxcheck β€” Drug Interaction Reference
   Data source: openFDA Drug Label API (api.fda.gov)
   Note: NIH/RxNav's dedicated drug-drug interaction API was
   discontinued, so this tool cross-references each drug's own
   FDA label text (warnings / drug_interactions / precautions)
   for mentions of the other drug, rather than claiming a
   verified real-time "interaction verdict".
   =========================================================== */

const COMMON_DRUGS = [
  "Paracetamol", "Acetaminophen", "Ibuprofen", "Aspirin", "Warfarin",
  "Metformin", "Amoxicillin", "Omeprazole", "Atorvastatin", "Amlodipine",
  "Losartan", "Metoprolol", "Sertraline", "Fluoxetine", "Ciprofloxacin",
  "Azithromycin", "Levothyroxine", "Prednisone", "Diazepam", "Alprazolam",
  "Tramadol", "Codeine", "Insulin", "Clopidogrel", "Simvastatin",
  "Alcohol", "Grapefruit", "Vitamin K", "Caffeine", "Milk"
];

const SEVERE_KEYWORDS = [
  "contraindicated", "should not be used", "should not be co-administered",
  "avoid concomitant", "fatal", "life-threatening", "increased risk of death",
  "do not use"
];

const MODERATE_KEYWORDS = [
  "caution", "monitor", "may increase", "may decrease", "adjust the dose",
  "adjust dose", "risk of", "concomitant use", "closely monitor"
];

let activeSuggestionIndex = -1;

/* ---------------- Theme ---------------- */

function toggleDarkMode() {
  const checked = document.getElementById("checkbox").checked;
  document.documentElement.setAttribute("data-theme", checked ? "dark" : "light");
}

/* ---------------- Autocomplete ---------------- */

function showSuggestions(inputEl, boxId) {
  const box = document.getElementById(boxId);
  const query = inputEl.value.trim().toLowerCase();
  box.innerHTML = "";
  activeSuggestionIndex = -1;

  if (!query) {
    box.classList.remove("active");
    return;
  }

  const matches = COMMON_DRUGS.filter(d => d.toLowerCase().includes(query)).slice(0, 6);

  if (matches.length === 0) {
    box.classList.remove("active");
    return;
  }

  matches.forEach(name => {
    const item = document.createElement("div");
    item.className = "suggestion-item";
    item.textContent = name;
    item.onclick = () => {
      inputEl.value = name;
      box.classList.remove("active");
      box.innerHTML = "";
    };
    box.appendChild(item);
  });

  box.classList.add("active");
}

document.addEventListener("click", (e) => {
  document.querySelectorAll(".suggestion-box").forEach(box => {
    if (!box.contains(e.target) && e.target.tagName !== "INPUT") {
      box.classList.remove("active");
    }
  });
});

/* ---------------- Data fetching ---------------- */

async function fetchDrugLabel(name) {
  const q = name.trim().replace(/"/g, "");
  if (!q) return null;

  const url = "https://api.fda.gov/drug/label.json?search=" +
    encodeURIComponent(`openfda.generic_name:"${q}" OR openfda.brand_name:"${q}" OR openfda.substance_name:"${q}"`) +
    "&limit=1";

  try {
    const res = await fetch(url);
    if (!res.ok) return { found: false };
    const data = await res.json();
    if (!data.results || data.results.length === 0) return { found: false };
    const r = data.results[0];
    return {
      found: true,
      name: q,
      route: (r.openfda && r.openfda.route) ? r.openfda.route.join(", ") : "Not specified",
      dosage: firstOrNull(r.dosage_and_administration),
      indications: firstOrNull(r.indications_and_usage),
      adverse: firstOrNull(r.adverse_reactions),
      warnings: firstOrNull(r.warnings) || firstOrNull(r.warnings_and_cautions),
      interactionsText: firstOrNull(r.drug_interactions),
      precautions: firstOrNull(r.precautions),
      boxedWarning: firstOrNull(r.boxed_warning)
    };
  } catch (err) {
    return { found: false, error: true };
  }
}

function firstOrNull(arr) {
  return (arr && arr.length > 0) ? arr[0] : null;
}

function trimText(text, maxLen = 320) {
  if (!text) return "";
  if (text.length <= maxLen) return text;
  const cut = text.slice(0, maxLen);
  return cut.slice(0, cut.lastIndexOf(" ")) + "…";
}

/* ---------------- Interaction analysis ---------------- */

function findMentions(labelData, otherName) {
  if (!labelData || !labelData.found || !otherName) return [];
  const fields = [
    ["Boxed warning", labelData.boxedWarning],
    ["Drug interactions", labelData.interactionsText],
    ["Warnings", labelData.warnings],
    ["Precautions", labelData.precautions]
  ];
  const needle = otherName.trim().toLowerCase();
  const hits = [];
  fields.forEach(([section, text]) => {
    if (text && text.toLowerCase().includes(needle)) {
      hits.push({ section, snippet: trimText(text) });
    }
  });
  return hits;
}

function classifySeverity(hits) {
  let severity = "none";
  hits.forEach(hit => {
    const lower = hit.snippet.toLowerCase();
    if (SEVERE_KEYWORDS.some(k => lower.includes(k))) {
      severity = "danger";
    } else if (severity !== "danger" && MODERATE_KEYWORDS.some(k => lower.includes(k))) {
      severity = "caution";
    } else if (severity === "none") {
      severity = "informational";
    }
  });
  return severity;
}

const SEVERITY_RANK = { danger: 3, caution: 2, informational: 1, none: 0 };

/* ---------------- Main flow ---------------- */

async function analyzePrescription() {
  const d1 = document.getElementById("drug1").value.trim();
  const d2 = document.getElementById("drug2").value.trim();
  const d3 = document.getElementById("drug3").value.trim();
  const errorEl = document.getElementById("inputError");

  if (!d1 || !d2) {
    errorEl.textContent = "Kripya kam se kam do dawaiyon ke naam daalein.";
    return;
  }
  errorEl.textContent = "";

  const names = [d1, d2];
  if (d3) names.push(d3);

  document.getElementById("inputPage").style.display = "none";
  document.getElementById("loadingScreen").style.display = "block";
  document.getElementById("resultPage").style.display = "none";

  const labels = {};
  for (const name of names) {
    labels[name] = await fetchDrugLabel(name);
  }

  const pairResults = [];
  for (let i = 0; i < names.length; i++) {
    for (let j = i + 1; j < names.length; j++) {
      const a = names[i], b = names[j];
      const hitsAB = findMentions(labels[a], b);
      const hitsBA = findMentions(labels[b], a);
      pairResults.push({ a, b, hitsAB, hitsBA });
    }
  }

  renderResults(names, labels, pairResults);

  document.getElementById("loadingScreen").style.display = "none";
  document.getElementById("resultPage").style.display = "block";
}

function renderResults(names, labels, pairResults) {
  const anyFetchFailed = names.some(n => labels[n] && labels[n].error);
  const anyNotFound = names.some(n => !labels[n] || !labels[n].found);

  let overallSeverity = "none";
  let totalHits = 0;
  pairResults.forEach(p => {
    const combined = [...p.hitsAB, ...p.hitsBA];
    totalHits += combined.length;
    const sev = classifySeverity(combined);
    if (SEVERITY_RANK[sev] > SEVERITY_RANK[overallSeverity]) overallSeverity = sev;
  });

  const statusBox = document.getElementById("statusResult");
  const alertsContainer = document.getElementById("adverseAlertsContainer");
  alertsContainer.innerHTML = "";

  if (anyFetchFailed) {
    statusBox.className = "result-box status-caution";
    statusBox.innerHTML = `<span class="status-title">FDA database tak connect nahi ho paaya</span>
      <span class="status-body">Internet ya API access check karein aur dubara try karein. Tab tak, kisi bhi dawai ko combine karne se pehle pharmacist se salaah lein.</span>`;
  } else if (overallSeverity === "danger") {
    statusBox.className = "result-box status-danger";
    statusBox.innerHTML = `<span class="status-title">Significant interaction FDA labeling mein documented hai</span>
      <span class="status-body">Neeche di gayi details dekhein aur is combination ke baare mein apne doctor ya pharmacist se turant baat karein.</span>`;
  } else if (overallSeverity === "caution" || overallSeverity === "informational") {
    statusBox.className = "result-box status-caution";
    statusBox.innerHTML = `<span class="status-title">Kuch mention mila hai β€” caution rakhein</span>
      <span class="status-body">FDA label mein is combination ka zikr mila hai. Apne pharmacist se confirm karein ki yeh aapki situation ke liye theek hai.</span>`;
  } else if (anyNotFound) {
    statusBox.className = "result-box status-caution";
    statusBox.innerHTML = `<span class="status-title">Poora data nahi mila</span>
      <span class="status-body">Ek ya zyada dawaiyon ka FDA label match nahi hua β€” ho sakta hai spelling alag ho ya yeh ek generic substance/food item ho. Iska matlab "safe" nahi hai; pharmacist se poochhna behtar rahega.</span>`;
  } else {
    statusBox.className = "result-box status-ok";
    statusBox.innerHTML = `<span class="status-title">In dawaiyon ke labels mein direct mention nahi mila</span>
      <span class="status-body">Iska matlab guaranteed safe nahi hai β€” FDA labels har interaction cover nahi karte. Naye combination se pehle hamesha pharmacist se confirm karein.</span>`;
  }

  pairResults.forEach(p => {
    const hits = [...p.hitsAB.map(h => ({ ...h, direction: `${p.a} ke label mein ${p.b} ka zikr` })),
                  ...p.hitsBA.map(h => ({ ...h, direction: `${p.b} ke label mein ${p.a} ka zikr` }))];
    hits.forEach(h => {
      const card = document.createElement("div");
      card.className = "alert-card";
      card.innerHTML = `<span class="alert-source">${h.direction} β€” ${h.section}</span>${h.snippet}`;
      alertsContainer.appendChild(card);
    });
  });

  const tbody = document.getElementById("tableBody");
  tbody.innerHTML = "";
  names.forEach(name => {
    const l = labels[name];
    const row = document.createElement("tr");
    if (!l || !l.found) {
      row.innerHTML = `<td>${escapeHtml(name)}</td><td colspan="4">FDA label database mein match nahi mila.</td>`;
    } else {
      row.innerHTML = `
        <td>${escapeHtml(name)}</td>
        <td>${escapeHtml(l.route || "β€”")}</td>
        <td>${escapeHtml(trimText(l.dosage, 160) || "Label mein specify nahi kiya gaya")}</td>
        <td>${escapeHtml(trimText(l.indications, 160) || "β€”")}</td>
        <td>${escapeHtml(trimText(l.adverse, 160) || "β€”")}</td>`;
    }
    tbody.appendChild(row);
  });
}

function escapeHtml(str) {
  const div = document.createElement("div");
  div.textContent = str == null ? "" : String(str);
  return div.innerHTML;
}

/* ---------------- Utility actions ---------------- */

function downloadPDF() {
  window.print();
}

function clearAll() {
  document.getElementById("drug1").value = "";
  document.getElementById("drug2").value = "";
  document.getElementById("drug3").value = "";
  document.getElementById("inputError").textContent = "";
  document.getElementById("resultPage").style.display = "none";
  document.getElementById("loadingScreen").style.display = "none";
  document.getElementById("inputPage").style.display = "block";
}