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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
let barChart = null;
let radarChart = null;
let bigBarChartObj = null;
let bigRadarChartObj = null;
let fastaResults = [];

const API_BASE = ""; // same origin

//------------------ Safe Fetch ------------------
async function safeFetchJSON(url, options = {}) {
  const res = await fetch(url, options);
  const text = await res.text();

  let data;
  try {
    data = JSON.parse(text);
  } catch {
    throw new Error(text || `HTTP ${res.status}`);
  }
  if (!res.ok) {
    throw new Error(data.error || `HTTP ${res.status}`);  
  }
  return data;
}

// ------------------ INIT ------------------
document.addEventListener("DOMContentLoaded", () => {
  // Tabs
  const tabSeq = document.getElementById("tab-seq");
  const tabFasta = document.getElementById("tab-fasta");
  const panelSeq = document.getElementById("panel-seq");
  const panelFasta = document.getElementById("panel-fasta");
  const downloadBtn = document.getElementById("downloadCsvBtn");
  if (downloadBtn) {
    downloadBtn.addEventListener("click", downloadCSV);
  }

  if (tabSeq && tabFasta && panelSeq && panelFasta) {
    tabSeq.addEventListener("click", () => {
      tabSeq.classList.add("active");
      tabFasta.classList.remove("active");
      panelSeq.classList.remove("hidden");
      panelFasta.classList.add("hidden");
    });

    tabFasta.addEventListener("click", () => {
      tabFasta.classList.add("active");
      tabSeq.classList.remove("active");
      panelFasta.classList.remove("hidden");
      panelSeq.classList.add("hidden");
    });
  }

  // Buttons
  const predictBtn = document.getElementById("predictBtn");
  if (predictBtn) predictBtn.addEventListener("click", predictSequence);

  const predictFastaBtn = document.getElementById("predictFastaBtn");
  if (predictFastaBtn) predictFastaBtn.addEventListener("click", predictFasta);

  // FASTA modal close events
  const fastaBackdrop = document.getElementById("fastaModalBackdrop");
  const fastaClose = document.getElementById("fastaModalClose");
  if (fastaBackdrop) fastaBackdrop.addEventListener("click", closeFastaModal);
  if (fastaClose) fastaClose.addEventListener("click", closeFastaModal);

  // Big chart click
  const barCanvas = document.getElementById("barChart");
  const radarCanvas = document.getElementById("radarChart");
  if (barCanvas) barCanvas.addEventListener("click", openBigBar);
  if (radarCanvas) radarCanvas.addEventListener("click", openBigRadar);
});

// ------------------ HELPERS ------------------
function validateSequence(seq) {
  const s = seq.trim().toUpperCase();
  if (!s) return [false, "Sequence is empty."];
  const validAA = /^[ACDEFGHIKLMNPQRSTVWYUBZX*]+$/;
  if (!validAA.test(s)) return [false, "Invalid characters in sequence."];
  if (s.length < 15) return [false, "Sequence too short (min 15 AA)."];
  return [true, null];
}

// Capitalize class names
function pretty(name) {
  return name.charAt(0).toUpperCase() + name.slice(1);
}

// Probability severity
function getConfidenceMeta(maxProb) {
  if (maxProb >= 0.75) return { color: "#4ade80", text: "High confidence" };
  if (maxProb >= 0.6) return { color: "#facc15", text: "Medium confidence" };
  return { color: "#f87171", text: "Low confidence – interpret cautiously" };
}

// Bar chart colors
function buildBarColors(values) {
  const max = Math.max(...values);
  return values.map(v =>
    v === max ? "rgba(45,212,191,0.95)" : "rgba(166,184,184,0.9)"
  );
}

// Probability list builder
function updateProbList(container, probs) {
  if (!container) return;
  container.innerHTML = "";
  Object.entries(probs).forEach(([k, v]) => {
    const div = document.createElement("div");
    div.className = "prob-item";
    const left = document.createElement("span");
    left.textContent = pretty(k);        // CAPITALIZED
    const right = document.createElement("span");
    right.textContent = (v * 100).toFixed(2) + "%";   // PERCENT
    div.appendChild(left);
    div.appendChild(right);
    container.appendChild(div);
  });
}

// ------------------ CHART DRAWING ------------------
function drawCharts(classLabels, rawValues) {
  const barCanvas = document.getElementById("barChart");
  const radarCanvas = document.getElementById("radarChart");
  if (!barCanvas || !radarCanvas) return;

  const labels = classLabels.map(pretty);  // CAPITALIZE
  const values = rawValues;

  if (barChart) barChart.destroy();
  if (radarChart) radarChart.destroy();

  // Bar Chart
  barChart = new Chart(barCanvas.getContext("2d"), {
    type: "bar",
    data: {
      labels,
      datasets: [
        {
          data: values,
          backgroundColor: buildBarColors(values),
          borderRadius: 6
        }
      ]
    },
    options: {
      responsive: true,
      plugins: {
        legend: { display: false },
        tooltip: {
          callbacks: {
            label: ctx => (ctx.parsed.y * 100).toFixed(2) + "%"  // PERCENT
          }
        }
      },
      scales: {
        y: { beginAtZero: true, max: 1 },
        x: { ticks: { color: "#e5e7eb" } }
      }
    }
  });

  // Radar Chart
  radarChart = new Chart(radarCanvas.getContext("2d"), {
    type: "radar",
    data: {
      labels,
      datasets: [
        {
          data: values,
          backgroundColor: "rgba(45,212,191,0.18)",
          borderColor: "rgba(45,212,191,0.9)",
          borderWidth: 2
        }
      ]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: { display: false },
        tooltip: {
          callbacks: {
            label: ctx => (ctx.parsed.r * 100).toFixed(2) + "%"  // PERCENT
          }
        }
      },
      scales: {
        r: {
          beginAtZero: true,
          max: 1,
          grid: { color: "rgba(55,65,81,0.4)" },
          angleLines: { color: "rgba(55,65,81,0.4)" },
          pointLabels: { color: "#e5e7eb", font: { size: 16 } },
          ticks: { display: false }
        }
      }
    }
  });
}

// ------------------ SINGLE SEQUENCE ------------------
async function predictSequence() {
  const seqInput = document.getElementById("sequenceInput");
  const seq = seqInput.value.trim();

  const [ok, err] = validateSequence(seq);
  if (!ok) return alert(err);

  const loading = document.getElementById("loadingSeq");
  const resultCard = document.getElementById("seqResultCard");
  const resultHeader = document.getElementById("seqResultHeader");
  const warningEl = document.getElementById("seqConfidenceWarning");
  const probList = document.getElementById("seqProbList");

  loading.classList.remove("hidden");
  resultCard.classList.add("hidden");

  try {
    const res = await fetch(`${API_BASE}/api/predict_sequence`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ sequence: seq })
    });
    const data = await res.json();
    loading.classList.add("hidden");

    if (!res.ok || data.error) return alert(data.error || "Prediction failed.");

    const label = pretty(data.prediction_label);  // CAPITALIZED
    const probs = data.probabilities || {};
    const labels = Object.keys(probs);
    const values = labels.map(k => probs[k]);

    const maxProb = Math.max(...values);
    const meta = getConfidenceMeta(maxProb);

    resultHeader.innerHTML = `<span style="color:${meta.color}">Predicted Location: ${label}</span>`;
    warningEl.textContent = meta.text;
    warningEl.style.color = meta.color;

    updateProbList(probList, probs);
    drawCharts(labels, values);
    resultCard.classList.remove("hidden");

  } catch (e) {
    loading.classList.add("hidden");
    alert("Server error: " + e);
  }
}

// ------------------ FASTA ------------------
async function predictFasta() {
  const fileInput = document.getElementById("fastaFile");
  const file = fileInput.files[0];

  if (!file) return alert("Choose a FASTA file.");

  const loading = document.getElementById("loadingFasta");
  const wrapper = document.getElementById("fastaResultsWrapper");
  const tbody = document.getElementById("fastaTableBody");

  loading.classList.remove("hidden");
  wrapper.classList.add("hidden");
  tbody.innerHTML = "";
  fastaResults = [];

  try {
    const form = new FormData();
    form.append("file", file);

    const res = await fetch(`${API_BASE}/api/predict_fasta`, {
      method: "POST",
      body: form
    });
    const data = await res.json();

    loading.classList.add("hidden");

    if (!res.ok || data.error) return alert(data.error || "FASTA read error.");

    fastaResults = data.results;
    renderFastaTable();
    wrapper.classList.remove("hidden");

  } catch (e) {
    loading.classList.add("hidden");
    alert("Server error: " + e);
  }
}

function renderFastaTable() {
  const tbody = document.getElementById("fastaTableBody");
  tbody.innerHTML = "";

  fastaResults.forEach((r, idx) => {
    const probs = r.probabilities || {};
    const maxProb = Math.max(...Object.values(probs));

    const tr = document.createElement("tr");
    tr.dataset.index = idx;
    tr.innerHTML = `
      <td>${idx + 1}</td>
      <td>${r.sequence}</td>
      <td>${r.length}</td>
      <td>${pretty(r.prediction_label)}</td>
      <td>${(maxProb * 100).toFixed(2)}%</td>
    `;
    tr.addEventListener("click", () => openFastaModal(idx));
    tbody.appendChild(tr);
  });
}

// FASTA modal (no charts)
function openFastaModal(i) {
  const r = fastaResults[i];
  if (!r) return;

  document.getElementById("fastaModalTitle").textContent =
    `Sequence: ${r.sequence}`;

  document.getElementById("fastaModalMeta").textContent =
    `Length: ${r.length} | Predicted: ${pretty(r.prediction_label)}`;

  updateProbList(document.getElementById("fastaProbList"), r.probabilities);

  document.getElementById("fastaModal").classList.remove("hidden");
}

function closeFastaModal() {
  document.getElementById("fastaModal").classList.add("hidden");
}

// ------------------ BIG CHART MODALS ------------------
function openBigBar() {
  if (!barChart) return;
  const modal = document.getElementById("bigBarModal");
  const ctx = document.getElementById("bigBarChart").getContext("2d");

  if (bigBarChartObj) bigBarChartObj.destroy();

  bigBarChartObj = new Chart(ctx, {
    type: barChart.config.type,
    data: barChart.config.data,
    options: {
      responsive: false,
      animation: false,
      scales: {
        y: { beginAtZero: true, max: 1 },
        x: { ticks: { color: "#e5e7eb" } }
      }
    }
  });

  modal.classList.remove("hidden");
}

function closeBigBar() {
  document.getElementById("bigBarModal").classList.add("hidden");
}

function openBigRadar() {
  if (!radarChart) return;
  const modal = document.getElementById("bigRadarModal");
  const ctx = document.getElementById("bigRadarChart").getContext("2d");

  if (bigRadarChartObj) bigRadarChartObj.destroy();

  bigRadarChartObj = new Chart(ctx, {
    type: radarChart.config.type,
    data: radarChart.config.data,
    options: {
      responsive: false,
      animation: false,
      scales: {
        r: {
          beginAtZero: true,
          max: 1,
          grid: { color: "rgba(55,65,81,0.4)" },
          angleLines: { color: "rgba(55,65,81,0.4)" },
          pointLabels: { color: "#e4e4e4ff", font: { size: 18 } },
          ticks: { display: false }
        }
      }
    }
  });

  modal.classList.remove("hidden");
}

function closeBigRadar() {
  document.getElementById("bigRadarModal").classList.add("hidden");
}

// DOWNLOAD CSV

function downloadCSV() {
  if (!fastaResults || fastaResults.length === 0) {
    alert("No batch results available to download.");
    return;
  }

  fetch("/api/download_csv", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(fastaResults)
  })
    .then(res => {
      if (!res.ok) throw new Error("Failed to generate CSV");
      return res.blob();
    })
    .then(blob => {
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = "canloc_results.csv";
      document.body.appendChild(a);
      a.click();
      a.remove();
      window.URL.revokeObjectURL(url);
    })
    .catch(err => {
      alert("Download error: " + err.message);
    });
}