// =========================================================
// FILE: bio-dashboard.js | TYPE: Biokineticist Dashboard Logic
// =========================================================

import { db } from "./firebase-config.js";
import { requireAuth, setupLogoutButton } from "./app-guard.js";
import { showLoader, hideLoader } from "./loader.js";
import { showToast } from "./toast.js";
import { createNotification } from "./notification-service.js";

import {
  collection,
  getDocs,
  query,
  where,
  doc,
  updateDoc
} from "https://www.gstatic.com/firebasejs/10.12.2/firebase-firestore.js";

const bioDashboardGreeting = document.getElementById("bioDashboardGreeting");

const bioActiveInjuries = document.getElementById("bioActiveInjuries");
const bioRecoveryPlayers = document.getElementById("bioRecoveryPlayers");
const bioClearedPlayers = document.getElementById("bioClearedPlayers");
const bioWellnessRisks = document.getElementById("bioWellnessRisks");

const bioInjuryList = document.getElementById("bioInjuryList");
const bioWellnessList = document.getElementById("bioWellnessList");
const bioPriorityList = document.getElementById("bioPriorityList");
const bioNotificationsList = document.getElementById("bioNotificationsList");
const heroBioMedicalReady = document.getElementById("heroBioMedicalReady");
const heroBioRiskLevel = document.getElementById("heroBioRiskLevel");
const heroBioRehabStatus = document.getElementById("heroBioRehabStatus");

const bioFocusTitle = document.getElementById("bioFocusTitle");
const bioFocusText = document.getElementById("bioFocusText");

const bioInsightsList = document.getElementById("bioInsightsList");

let activeProfile = null;
let bioNotificationRecords = [];
let bioDashboardIsLoading = false;
let bioInjuryChartInstance = null;
let bioWellnessChartInstance = null;
let bioRecoveryChartInstance = null;

const CHART_THEME = {
  ready: "rgba(34,197,94,0.85)",
  warning: "rgba(245,158,11,0.85)",
  danger: "rgba(239,68,68,0.85)",
  primary: "rgba(56,189,248,0.85)",
  primarySoft: "rgba(56,189,248,0.16)",
  text: "#ffffff",
  muted: "#cbd5e1",
  grid: "rgba(255,255,255,0.06)"
};

function setText(element, value) {
  if (!element) return;
  element.textContent = value;
}

function animateCounter(element, targetValue, duration = 750) {
  if (!element) return;

  const startValue = Number(element.textContent) || 0;
  const startTime = performance.now();

  function updateCounter(currentTime) {
    const elapsed = currentTime - startTime;
    const progress = Math.min(elapsed / duration, 1);
    const currentValue = Math.floor(progress * (targetValue - startValue) + startValue);

    element.textContent = currentValue;

    if (progress < 1) {
      requestAnimationFrame(updateCounter);
    } else {
      element.textContent = targetValue;
    }
  }

  requestAnimationFrame(updateCounter);
}

function animateRing(cardSelector, value) {

  const ring = document.querySelector(cardSelector);

  if (!ring) return;

  const safeValue = Math.max(
    0,
    Math.min(100, Number(value) || 0)
  );

  requestAnimationFrame(() => {
    ring.style.setProperty("--value", `${safeValue}%`);
  });
}

function getDateValue(record) {
  if (record?.date) return new Date(record.date);
  if (record?.sessionDate) return new Date(record.sessionDate);
  if (record?.createdDate) return new Date(record.createdDate);
  if (record?.createdAt?.toDate) return record.createdAt.toDate();
  if (record?.createdAt) return new Date(record.createdAt);

  return new Date(0);
}

function getBaseChartOptions(extraOptions = {}) {
  return {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      legend: {
        labels: {
          color: CHART_THEME.text
        }
      }
    },
    ...extraOptions
  };
}

function canAccessRecord(record) {
  if (!activeProfile || !record) return false;

  const role = activeProfile.role;
  const assignedTeamIds = activeProfile.assignedTeamIds || [];
  const assignedPlayerIds = activeProfile.assignedPlayerIds || [];

  if (role === "director") return true;

  if (role === "biokineticist") {
    const recordTeamIds = Array.isArray(record.teamIds)
      ? record.teamIds
      : record.teamId
        ? [record.teamId]
        : [];

    return (
      recordTeamIds.some((teamId) => assignedTeamIds.includes(teamId)) ||
      Boolean(record.playerId && assignedPlayerIds.includes(record.playerId))
    );
  }

  return false;
}

async function getRecords(collectionName) {
  if (!activeProfile?.organisationId) {
    throw new Error("No organisation linked to this user.");
  }
  
  const q = query(
    collection(db, collectionName),
    where("organisationId", "==", activeProfile.organisationId)
  );

  const snapshot = await getDocs(q);

  return snapshot.docs.map((docSnap) => ({
    id: docSnap.id,
    ...docSnap.data()
  }));
}

function hasBioAssignments() {
  const assignedTeamIds = activeProfile?.assignedTeamIds || [];
  const assignedPlayerIds = activeProfile?.assignedPlayerIds || [];

  return assignedTeamIds.length > 0 || assignedPlayerIds.length > 0;
}

async function loadBioNotifications() {
  if (!bioNotificationsList || !activeProfile?.organisationId) return;

  const notificationsQuery = query(
    collection(db, "notifications"),
    where("organisationId", "==", activeProfile.organisationId),
    where("userId", "==", activeProfile.uid)
  );

  const snapshot = await getDocs(notificationsQuery);

  bioNotificationRecords = snapshot.docs
    .map((docSnap) => ({
      id: docSnap.id,
      ...docSnap.data()
    }))
    .sort((a, b) => getDateValue(b) - getDateValue(a));

  renderBioNotifications();
}

function renderBioNotifications() {
  if (!bioNotificationsList) return;

  bioNotificationsList.innerHTML = "";

  if (!bioNotificationRecords.length) {
    bioNotificationsList.innerHTML = `
      <div class="list-item">
        <strong>No notifications yet.</strong>
        <p>Medical alerts will appear here when risks are detected.</p>
      </div>
    `;
    return;
  }

  bioNotificationRecords.slice(0, 6).forEach((notification) => {
    const item = document.createElement("div");
    item.className = `notification-item notification-${notification.severity || "info"}`;

    item.innerHTML = `
      <div class="notification-content">
        <div class="notification-header">
          <h3>${notification.title || "Notification"}</h3>
          <span class="status-pill notification-${notification.severity || "info"}">
            ${notification.severity || "info"}
          </span>
        </div>

        <p>${notification.message || ""}</p>

        <div class="record-actions">
          ${
            notification.link
              ? `<a href="${notification.link}" class="btn-secondary">Open</a>`
              : ""
          }

          ${
            notification.readBy && notification.readBy[activeProfile.uid]
              ? `<span class="status-pill">Read</span>`
              : `<button class="btn-primary bio-mark-notification-read-btn" data-id="${notification.id}">
                  Mark Read
                </button>`
          }
        </div>
      </div>
    `;

    bioNotificationsList.appendChild(item);
  });
}

function setupBioNotificationActions() {
  document.querySelectorAll(".bio-mark-notification-read-btn").forEach((button) => {
    button.addEventListener("click", async () => {
      const notificationId = button.dataset.id;

      if (!notificationId) return;

      button.disabled = true;
      button.textContent = "Updating...";

      try {
        await updateDoc(doc(db, "notifications", notificationId), {
          [`readBy.${activeProfile.uid}`]: true
        });

        const notification = bioNotificationRecords.find((item) => item.id === notificationId);

        if (notification) {
          notification.readBy = {
            ...(notification.readBy || {}),
            [activeProfile.uid]: true
          };
        }

        renderBioNotifications();
        setupBioNotificationActions();

        showToast("Notification marked as read.", "success");
      } catch (error) {
        console.error("Bio notification update error:", error);
        showToast("Could not update notification.", "error");
      } finally {
        button.disabled = false;
      }
    });
  });
}

async function createBioRiskNotifications({
  activeCount,
  recoveryCount,
  wellnessRiskCount
}) {
  if (!activeProfile?.uid || !activeProfile?.organisationId) return;

  const notificationJobs = [];

  if (activeCount > 0) {
    notificationJobs.push(
      createNotification({
        organisationId: activeProfile.organisationId,
        userId: activeProfile.uid,
        type: "bio_alert",
        title: "Active injury cases",
        message: `${activeCount} player(s) currently have active injury records.`,
        link: "injuries.html",
        severity: "danger",
        uniqueKey: `bio-active-injuries-${activeProfile.uid}`
      })
    );
  }

  if (recoveryCount > 0) {
    notificationJobs.push(
      createNotification({
        organisationId: activeProfile.organisationId,
        userId: activeProfile.uid,
        type: "bio_alert",
        title: "Recovery players need monitoring",
        message: `${recoveryCount} player(s) are currently in recovery.`,
        link: "injuries.html",
        severity: "warning",
        uniqueKey: `bio-recovery-${activeProfile.uid}`
      })
    );
  }

  if (wellnessRiskCount > 0) {
    notificationJobs.push(
      createNotification({
        organisationId: activeProfile.organisationId,
        userId: activeProfile.uid,
        type: "bio_alert",
        title: "Wellness risk alerts",
        message: `${wellnessRiskCount} player(s) show wellness risk indicators.`,
        link: "bio-wellness.html",
        severity: "warning",
        uniqueKey: `bio-wellness-risk-${activeProfile.uid}`
      })
    );
  }

  await Promise.allSettled(notificationJobs);
}

function renderNoAssignmentState() {
  setText(bioActiveInjuries, "0");
  setText(bioRecoveryPlayers, "0");
  setText(bioClearedPlayers, "0");
  setText(bioWellnessRisks, "0");
  
  setText(heroBioMedicalReady, "0%");
  setText(heroBioRiskLevel, "No Assignment");
  setText(heroBioRehabStatus, "No Data");

  animateRing(".premium-danger-ring", 0);
  animateRing(".premium-monitor-ring", 0);
  animateRing(".premium-ready-ring", 0);
  animateRing(".premium-wellness-ring", 0);

  setText(bioFocusTitle, "No Assignment Yet");
  setText(
    bioFocusText,
    "Ask the director to assign teams or players before medical data can be reviewed."
  );

  if (bioPriorityList) {
    bioPriorityList.innerHTML = `
      <div class="list-item access-empty-state">
        <strong>No teams or players assigned yet.</strong>
        <p>Please ask the director to assign access in User Management.</p>
      </div>
    `;
  }

  if (bioInjuryList) {
    bioInjuryList.innerHTML = `
      <div class="list-item access-empty-state">
        <strong>No injury data available yet.</strong>
        <p>Your dashboard will populate once teams or players are assigned.</p>
      </div>
    `;
  }

  if (bioWellnessList) {
    bioWellnessList.innerHTML = `
      <div class="list-item access-empty-state">
        <strong>No wellness data available yet.</strong>
        <p>Your wellness risk alerts will appear here.</p>
      </div>
    `;
  }
}

async function loadBioDashboard() {
  if (bioDashboardIsLoading) return;

  bioDashboardIsLoading = true;

  try {
    if (activeProfile.role === "biokineticist" && !hasBioAssignments()) {
      renderNoAssignmentState();

      hideLoader();

      loadBioNotifications()
        .then(() => setupBioNotificationActions())
        .catch((error) => {
        console.error("Bio notification load error:", error);
      });

      return;
    }

    if (bioInjuryList) {
      bioInjuryList.innerHTML = `<div class="list-item">Loading injury records...</div>`;
    }

    if (bioWellnessList) {
      bioWellnessList.innerHTML = `<div class="list-item">Loading wellness risks...</div>`;
    }

    if (bioPriorityList) {
      bioPriorityList.innerHTML = `<div class="list-item">Loading rehab priorities...</div>`;
    }

    const [injuryRecords, wellnessRecords, playerRecords, teamRecords] = await Promise.all([
      getRecords("injuries"),
      getRecords("wellness"),
      getRecords("players"),
      getRecords("teams")
    ]);
    
    const accessiblePlayers = playerRecords.filter((player) => canAccessRecord({
      playerId: player.id,
      teamId: player.teamId,
      teamIds: player.teamIds || []
    }));
    
    const playerNameById = new Map(
      accessiblePlayers.map((player) => [
        player.id,
        player.fullName || player.name || player.displayName || `${player.firstName || ""} ${player.lastName || ""}`.trim() || "Unknown Player"
      ])
    );
    
    const teamNameById = new Map(
      teamRecords.map((team) => [
        team.id,
        team.name || team.teamName || team.title || "No team"
      ])
    );

    const injuries = injuryRecords
      .filter((record) => canAccessRecord(record))
      .sort((a, b) => getDateValue(b) - getDateValue(a));

    const wellness = wellnessRecords
      .filter((record) => canAccessRecord(record))
      .sort((a, b) => getDateValue(b) - getDateValue(a));

    const active = injuries.filter((item) => {
      return String(item.status || "").toLowerCase() === "active";
    });

    const recovery = injuries.filter((item) => {
      return String(item.status || "").toLowerCase() === "recovery";
    });

    const cleared = injuries.filter((item) => {
      return String(item.status || "").toLowerCase() === "cleared";
    });

    const wellnessRisks = wellness.filter((item) => {
      const sleep = Number(item.sleep || 0);
      const fatigue = Number(item.fatigue || 0);
      const soreness = Number(item.soreness || 0);

      return sleep <= 2 || fatigue >= 4 || soreness >= 4;
    });

    animateCounter(bioActiveInjuries, active.length);
    animateCounter(bioRecoveryPlayers, recovery.length);
    animateCounter(bioClearedPlayers, cleared.length);
    animateCounter(bioWellnessRisks, wellnessRisks.length);
    
    const totalMedicalPlayers =
      active.length +
      recovery.length +
      cleared.length;
    
    const activePercent =
      totalMedicalPlayers
        ? Math.round((active.length / totalMedicalPlayers) * 100)
        : 0;
    
    const recoveryPercent =
      totalMedicalPlayers
        ? Math.round((recovery.length / totalMedicalPlayers) * 100)
        : 0;
    
    const clearedPercent =
      totalMedicalPlayers
        ? Math.round((cleared.length / totalMedicalPlayers) * 100)
        : 0;
    
    const wellnessPercent =
      accessiblePlayers.length
        ? Math.round((wellnessRisks.length / accessiblePlayers.length) * 100)
        : 0;
    
    animateRing(".premium-danger-ring", activePercent);
    animateRing(".premium-monitor-ring", recoveryPercent);
    animateRing(".premium-ready-ring", clearedPercent);
    animateRing(".premium-wellness-ring", wellnessPercent);
    
    const medicalReadyPercent =
      accessiblePlayers.length
        ? Math.max(0, Math.round(((accessiblePlayers.length - active.length - wellnessRisks.length) / accessiblePlayers.length) * 100))
        : 0;
    
    let bioRiskLevel = "Low";
    let bioRehabStatus = "Stable";
    
    if (active.length > 0 || wellnessRisks.length >= 5) {
      bioRiskLevel = "High";
      bioRehabStatus = "Needs Review";
    } else if (recovery.length > 0 || wellnessRisks.length > 0) {
      bioRiskLevel = "Moderate";
      bioRehabStatus = "Monitoring";
    }
    
    setText(heroBioMedicalReady, `${medicalReadyPercent}%`);
    setText(heroBioRiskLevel, bioRiskLevel);
    setText(heroBioRehabStatus, bioRehabStatus);
    
    if (active.length >= 5) {
    
      bioFocusTitle.textContent = "High Injury Load";
    
      bioFocusText.textContent =
        "Multiple active injuries require immediate recovery management.";
    
    } else if (wellnessRisks.length >= 5) {
    
      bioFocusTitle.textContent = "Wellness Monitoring Active";
    
      bioFocusText.textContent =
        "Several players are showing elevated wellness risk indicators.";
    
    } else {
    
      bioFocusTitle.textContent = "Recovery Progress Stable";
    
      bioFocusText.textContent =
        "Current recovery and wellness indicators are stable.";
    }

    renderPriorityPlayers(active, recovery, wellnessRisks, playerNameById, teamNameById);
    renderBioInjuryChart(active, recovery, cleared);
    renderBioWellnessChart(wellnessRisks);
    renderBioRecoveryChart(active, recovery);
    renderInjuries(
      injuries,
      playerNameById,
      teamNameById
    );
    renderWellnessRisks(
      wellnessRisks,
      playerNameById,
      teamNameById
    );
    renderBioInsights(active, recovery, wellnessRisks);

    /* Main dashboard is now visible, so do not keep loader waiting for notifications */
    hideLoader();

    createBioRiskNotifications({
      activeCount: active.length,
      recoveryCount: recovery.length,
      wellnessRiskCount: wellnessRisks.length
    })
      .then(() => loadBioNotifications())
      .then(() => setupBioNotificationActions())
      .catch((error) => {
      console.error("Bio notification refresh error:", error);
      });
  } finally {
    bioDashboardIsLoading = false;
  }
}

function renderPriorityPlayers(active, recovery, wellnessRisks, playerNameById, teamNameById) {
  if (!bioPriorityList) return;

  bioPriorityList.innerHTML = "";

  const priorityMap = new Map();

  [...active, ...recovery].forEach((record) => {
    priorityMap.set(record.playerId, {
      playerId: record.playerId,
      playerName:
        playerNameById.get(record.playerId) ||
        record.playerName ||
        "Unknown Player",
      teamName:
        teamNameById.get(record.teamId) ||
        record.teamName ||
        "No team",
      injuryStatus: "wellness risk",
      injuryType: "Wellness",
      severity: "Monitor",
      wellnessRisk: true
    });
  });

  wellnessRisks.forEach((record) => {
    const existing = priorityMap.get(record.playerId);

    if (existing) {
      existing.wellnessRisk = true;
    } else {
      priorityMap.set(record.playerId, {
        playerId: record.playerId,
        playerName:
          playerNameById.get(record.playerId) ||
          record.playerName ||
          "Unknown Player",
        teamName:
          teamNameById.get(record.teamId) ||
          record.teamName ||
          "No team",
        injuryStatus: "wellness risk",
        injuryType: "Wellness",
        severity: "Monitor",
        wellnessRisk: true
      });
    }
  });

  const priorityPlayers = Array.from(priorityMap.values()).filter((player) => {
    return player.injuryStatus === "active" || player.wellnessRisk;
  });

  if (!priorityPlayers.length) {
    bioPriorityList.innerHTML = `
      <div class="list-item">
        <strong>No rehab priority players found.</strong>
        <p>No active injury or wellness risk priorities are currently showing.</p>
      </div>
    `;
    return;
  }

  priorityPlayers.slice(0, 8).forEach((player) => {
    const item = document.createElement("div");
    item.className = "elite-injury-card bio-priority-card";

    item.innerHTML = `
      <div class="elite-injury-header">
        <div class="elite-injury-player">
          <h3>${player.playerName}</h3>
          <p>${player.teamName}</p>
        </div>

        <span class="status-pill ${player.wellnessRisk ? "readiness-monitor" : `injury-${player.injuryStatus}`}">
          ${player.wellnessRisk ? "Wellness Risk" : player.injuryStatus}
        </span>
      </div>

      <div class="elite-injury-grid">
        <div class="elite-injury-stat">
          <span>Injury Type</span>
          <strong>${player.injuryType}</strong>
        </div>

        <div class="elite-injury-stat">
          <span>Severity</span>
          <strong>${player.severity}</strong>
        </div>

        <div class="elite-injury-stat">
          <span>Wellness Risk</span>
          <strong>${player.wellnessRisk ? "Yes" : "No"}</strong>
        </div>
      </div>
    `;

    bioPriorityList.appendChild(item);
  });
}

function renderInjuries(injuries, playerNameById = new Map(), teamNameById = new Map()) {
  if (!bioInjuryList) return;

  bioInjuryList.innerHTML = "";

  if (!injuries.length) {
    bioInjuryList.innerHTML = `
      <div class="list-item">
        <strong>No injury records found.</strong>
        <p>Injury records will appear here once they are logged.</p>
      </div>
    `;
    return;
  }

  injuries.slice(0, 10).forEach((record) => {
    const item = document.createElement("div");
    item.className = "elite-injury-card bio-compact-injury-card";
    
    const daysInjured = Math.max(
      0,
      Math.floor((new Date() - getDateValue(record)) / (1000 * 60 * 60 * 24))
    );

    item.innerHTML = `
      <div class="elite-injury-header">
        <div class="elite-injury-player">
          <h3>${playerNameById.get(record.playerId) || record.playerName || "Unknown Player"}</h3>

          <p>
            ${teamNameById.get(record.teamId) || record.teamName || "No team"}
            •
            ${record.createdDate || "No date"}
          </p>
        </div>

        <span class="status-pill injury-${record.status || "active"}">
          ${record.status || "active"}
        </span>
      </div>

      <div class="elite-injury-grid">
        <div class="elite-injury-stat">
          <span>Injury Type</span>
          <strong>${record.type || "N/A"}</strong>
        </div>

        <div class="elite-injury-stat">
          <span>Severity</span>
          <strong>${record.severity || "N/A"}</strong>
        </div>

        <div class="elite-injury-stat">
          <span>Status</span>
          <strong>${record.status || "N/A"}</strong>
        </div>
      </div>
    `;

    bioInjuryList.appendChild(item);
  });
}

function renderWellnessRisks(records, playerNameById = new Map(), teamNameById = new Map()) {
  if (!bioWellnessList) return;

  bioWellnessList.innerHTML = "";

  if (!records.length) {
    bioWellnessList.innerHTML = `
      <div class="list-item">
        <strong>No wellness risk alerts found.</strong>
        <p>No elevated wellness risk indicators are currently showing.</p>
      </div>
    `;
    return;
  }

  records.slice(0, 10).forEach((record) => {
    const sleepRisk = Number(record.sleep || 0) <= 2;
    const fatigueRisk = Number(record.fatigue || 0) >= 4;
    const sorenessRisk = Number(record.soreness || 0) >= 4;

    const riskScore =
      (sleepRisk ? 1 : 0) +
      (fatigueRisk ? 1 : 0) +
      (sorenessRisk ? 1 : 0);

    const item = document.createElement("div");
    item.className = "wellness-card elite-wellness-risk-card";

    item.innerHTML = `
      <div class="wellness-card-header">
        <div>
          <h3>${playerNameById.get(record.playerId) || record.playerName || "Unknown Player"}</h3>

          <p>
            ${teamNameById.get(record.teamId) || record.teamName || "No team"}
            •
            ${record.createdDate || "No date"}
          </p>
        </div>

        <span class="wellness-score">${riskScore}/3 risks</span>
      </div>

      <div class="wellness-metrics">
        <div>
          <span>Sleep</span>
          <strong>${record.sleep || "-"}/5</strong>
        </div>

        <div>
          <span>Fatigue</span>
          <strong>${record.fatigue || "-"}/5</strong>
        </div>

        <div>
          <span>Soreness</span>
          <strong>${record.soreness || "-"}/5</strong>
        </div>
      </div>
    `;

    bioWellnessList.appendChild(item);
  });
}

function renderBioInjuryChart(active, recovery, cleared) {
  const canvas = document.getElementById("bioInjuryStatusChart");

  if (!canvas || typeof Chart === "undefined") return;

  if (bioInjuryChartInstance) {
    bioInjuryChartInstance.destroy();
  }

  bioInjuryChartInstance = new Chart(canvas, {
    type: "doughnut",
    data: {
      labels: ["Active", "Recovery", "Cleared"],
      datasets: [{
        data: [active.length, recovery.length, cleared.length],
        backgroundColor: [
          CHART_THEME.danger,
          CHART_THEME.warning,
          CHART_THEME.ready
        ],
        borderWidth: 0
      }]
    },
    options: getBaseChartOptions()
  });
}

function renderBioWellnessChart(wellnessRisks) {
  const canvas = document.getElementById("bioWellnessRiskChart");

  if (!canvas || typeof Chart === "undefined") return;

  if (bioWellnessChartInstance) {
    bioWellnessChartInstance.destroy();
  }

  const lowSleep = wellnessRisks.filter((r) => Number(r.sleep || 0) <= 2).length;
  const highFatigue = wellnessRisks.filter((r) => Number(r.fatigue || 0) >= 4).length;
  const highSoreness = wellnessRisks.filter((r) => Number(r.soreness || 0) >= 4).length;

  bioWellnessChartInstance = new Chart(canvas, {
    type: "bar",
    data: {
      labels: ["Sleep", "Fatigue", "Soreness"],
      datasets: [{
        data: [lowSleep, highFatigue, highSoreness],
        backgroundColor: [
          CHART_THEME.primary,
          CHART_THEME.warning,
          CHART_THEME.danger
        ],
        borderRadius: 12
      }]
    },
    options: getBaseChartOptions({
      plugins: {
        legend: { display: false }
      }
    })
  });
}

function renderBioRecoveryChart(active, recovery) {
  const canvas = document.getElementById("bioRecoveryChart");

  if (!canvas || typeof Chart === "undefined") return;

  if (bioRecoveryChartInstance) {
    bioRecoveryChartInstance.destroy();
  }

  bioRecoveryChartInstance = new Chart(canvas, {
    type: "line",
    data: {
      labels: ["Active", "Recovery"],
      datasets: [{
        label: "Players",
        data: [active.length, recovery.length],
        borderColor: "#38bdf8",
        backgroundColor: CHART_THEME.primarySoft,
        fill: true,
        tension: 0.35
      }]
    },
    options: getBaseChartOptions()
  });
}

function renderBioInsights(active, recovery, wellnessRisks) {

  if (!bioInsightsList) return;

  bioInsightsList.innerHTML = "";

  const insights = [];

  if (active.length >= 5) {
    insights.push({
      type: "danger",
      title: "High Injury Volume",
      text: `${active.length} active injury cases currently require management.`
    });
  }

  if (recovery.length >= 3) {
    insights.push({
      type: "warning",
      title: "Recovery Monitoring",
      text: `${recovery.length} players are currently progressing through recovery.`
    });
  }

  if (wellnessRisks.length >= 5) {
    insights.push({
      type: "warning",
      title: "Elevated Wellness Risk",
      text: `${wellnessRisks.length} players are showing wellness warning signs.`
    });
  }

  if (!insights.length) {
    insights.push({
      type: "good",
      title: "Medical Status Stable",
      text: "Current recovery and wellness indicators are within healthy ranges."
    });
  }

  insights.forEach((insight) => {

    const item = document.createElement("div");

    item.className = "insight-item";

    item.innerHTML = `
      <span class="insight-dot insight-${insight.type}"></span>

      <div>
        <strong>${insight.title}</strong>
        <p>${insight.text}</p>
      </div>
    `;

    bioInsightsList.appendChild(item);

  });
}

requireAuth(async function (user, profile) {
  activeProfile = profile;
  setupLogoutButton();
  
  if (bioDashboardGreeting) {
    const firstName = profile.fullName
      ? profile.fullName.split(" ")[0]
      : "Biokineticist";

    const currentHour = new Date().getHours();

    let greeting = "Welcome";

    if (currentHour < 12) {
      greeting = "Good Morning";
    } else if (currentHour < 18) {
      greeting = "Good Afternoon";
    } else {
      greeting = "Good Evening";
    }

    bioDashboardGreeting.textContent = `${greeting}, ${firstName}`;
  }
  
  if (profile.role !== "biokineticist" && profile.role !== "director") {
    window.location.href = "dashboard.html";
    return;
  }

  showLoader("Loading bio dashboard...");

  try {
    await loadBioDashboard();
  } catch (error) {
    console.error("Bio dashboard error:", error);

    if (bioInjuryList) {
      bioInjuryList.innerHTML = `
        <div class="list-item">
          <strong>Error loading bio dashboard.</strong>
          <p>${error.message}</p>
        </div>
      `;
    }

    if (bioWellnessList) {
      bioWellnessList.innerHTML = `<div class="list-item">Error loading wellness risks.</div>`;
    }

    showToast("Could not load bio dashboard: " + error.message, "error");
  } finally {
    hideLoader();
  }
});

setInterval(async () => {
  if (!activeProfile) return;

  try {
    await loadBioDashboard();
  } catch (error) {
    console.error("Bio dashboard auto refresh failed:", error);
  }
}, 60000);