// =========================================================
// FILE: match-readiness.js | TYPE: Match Readiness 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 {
  doc,
  getDoc,
  collection,
  addDoc,
  getDocs,
  query,
  where,
  updateDoc,
  serverTimestamp,
  setDoc
} from "https://www.gstatic.com/firebasejs/10.12.2/firebase-firestore.js";

const urlParams = new URLSearchParams(window.location.search);
const matchId = urlParams.get("id");

const matchTitle = document.getElementById("matchTitle");
const matchMeta = document.getElementById("matchMeta");

const matchTotalPlayers = document.getElementById("matchTotalPlayers");
const matchReadyPlayers = document.getElementById("matchReadyPlayers");
const matchMonitorPlayers = document.getElementById("matchMonitorPlayers");
const matchUnavailablePlayers = document.getElementById("matchUnavailablePlayers");
const matchReadinessList = document.getElementById("matchReadinessList");

const printMatchReadinessBtn = document.getElementById("printMatchReadinessBtn");
const exportMatchCsvBtn = document.getElementById("exportMatchCsvBtn");

const startingList = document.getElementById("startingList");
const benchList = document.getElementById("benchList");
const saveSquadBtn = document.getElementById("saveSquadBtn");
const autoSelectBtn = document.getElementById("autoSelectBtn");
const autoBenchBtn = document.getElementById("autoBenchBtn");
const clearSquadBtn = document.getElementById("clearSquadBtn");

const startingCounter = document.getElementById("startingCounter");
const benchCounter = document.getElementById("benchCounter");

const teamSheetLink = document.getElementById("teamSheetLink");
const selectionNotes = document.getElementById("selectionNotes");

let activeProfile = null;
let currentMatch = null;
let currentTeam = null;

let playersCache = [];
let attendanceCache = [];
let wellnessCache = [];
let injuriesCache = [];

let startingSquad = [];
let benchSquad = [];
let currentSelectionId = null;

function getPlayerName(player) {
  return `${player?.firstName || ""} ${player?.lastName || ""}`.trim() || "Unnamed Player";
}

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

function isActiveInjury(record) {
  const status = String(record.status || "").toLowerCase();
  return status !== "cleared" && status !== "closed" && status !== "resolved";
}

function canAccessMatch(match) {
  if (!activeProfile || !match) return false;

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

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

  if (
    role === "coach" ||
    role === "biokineticist" ||
    role === "player"
  ) {
    return assignedTeamIds.includes(match.teamId);
  }

  return false;
}

function recordBelongsToTeam(record, teamId) {
  const teamIds = Array.isArray(record.teamIds)
    ? record.teamIds
    : record.teamId
      ? [record.teamId]
      : [];

  return teamIds.includes(teamId);
}

async function getTeamRecords(collectionName) {
  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()
    }))
    .filter((record) => recordBelongsToTeam(record, currentMatch.teamId));
}

async function getMatchSelections() {
  const q = query(
    collection(db, "matchSelections"),
    where("matchId", "==", matchId),
    where("organisationId", "==", activeProfile.organisationId)
  );

  const snapshot = await getDocs(q);

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

async function loadMatch() {
  const matchRef = doc(db, "matches", matchId);
  const matchSnap = await getDoc(matchRef);

  if (!matchSnap.exists()) {
    matchTitle.textContent = "Match not found";
    return false;
  }

  currentMatch = {
    id: matchSnap.id,
    ...matchSnap.data()
  };

  if (currentMatch.organisationId !== activeProfile.organisationId) {
    showToast("This match does not belong to your organisation.", "error");
    window.location.href = "matches.html";
    return false;
  }

  if (!canAccessMatch(currentMatch)) {
    showToast("You do not have access to this match.", "error");
    window.location.href = "matches.html";
    return false;
  }

  if (currentMatch.teamId) {
    const teamRef = doc(db, "teams", currentMatch.teamId);
    const teamSnap = await getDoc(teamRef);

    if (teamSnap.exists()) {
      currentTeam = {
        id: teamSnap.id,
        ...teamSnap.data()
      };
    }
  }

  matchTitle.textContent = `${currentTeam?.name || "Team"} vs ${currentMatch.opponent || "Opponent"}`;

  matchMeta.textContent = `${currentMatch.date || "No date"} • ${currentMatch.venue || "No venue"} • ${currentMatch.type || "match"}`;

  if (teamSheetLink) {
    teamSheetLink.href = `team-sheet.html?id=${matchId}`;
  }

  return true;
}

async function loadReadinessData() {
  if (matchReadinessList) {
    matchReadinessList.innerHTML = `<div class="list-item">Loading match readiness...</div>`;
  }

  const [
    players,
    attendance,
    trainingAttendance,
    wellness,
    injuries
  ] = await Promise.all([
    getTeamRecords("players"),
    getTeamRecords("attendance"),
    getTeamRecords("trainingAttendance"),
    getTeamRecords("wellness"),
    getTeamRecords("injuries")
  ]);
  
  await setDoc(doc(db, "notifications", `selection-squad-${selectionId}`), {
    sourceId: selectionId,
    sourceCollection: "matchSelections",
    type: "selection",
    severity: "info",
    title: "Squad Announcement Published",
    message: `${selectionData.teamName || "Team"} squad has been published for the match vs ${selectionData.opponent || "Opponent"} on ${selectionData.matchDate || "match day"}.`,
    link: `team-sheet.html?id=${selectionData.matchId}`,
    playerId: "",
    playerName: "",
    teamId: selectionData.teamId || "",
    teamName: selectionData.teamName || "",
    organisationId: activeProfile.organisationId,
    readBy: {},
    createdAt: serverTimestamp(),
    updatedAt: serverTimestamp()
  });

  playersCache = players.sort((a, b) => {
    return getPlayerName(a).toLowerCase().localeCompare(getPlayerName(b).toLowerCase());
  });

  const playerIds = new Set(playersCache.map((player) => player.id));

  attendanceCache = [...attendance, ...trainingAttendance].filter((record) => {
    return playerIds.has(record.playerId);
  });

  wellnessCache = wellness.filter((record) => playerIds.has(record.playerId));
  injuriesCache = injuries.filter((record) => playerIds.has(record.playerId));
}

function buildPlayerRecordMap(records) {
  const map = new Map();

  records.forEach((record) => {
    if (!record.playerId) return;

    if (!map.has(record.playerId)) {
      map.set(record.playerId, []);
    }

    map.get(record.playerId).push(record);
  });

  return map;
}

function getReadinessRows() {
  const attendanceByPlayer = buildPlayerRecordMap(attendanceCache);
  const wellnessByPlayer = buildPlayerRecordMap(wellnessCache);
  const injuriesByPlayer = buildPlayerRecordMap(injuriesCache);

  return playersCache.map((player) => {
    const attendanceRecords = attendanceByPlayer.get(player.id) || [];

    const present = attendanceRecords.filter((record) => {
      return record.status === "present";
    }).length;

    const attendancePercentage = attendanceRecords.length
      ? Math.round((present / attendanceRecords.length) * 100)
      : 0;

    const wellnessRecords = wellnessByPlayer.get(player.id) || [];

    const latestWellness = [...wellnessRecords].sort((a, b) => {
      return getDateValue(b) - getDateValue(a);
    })[0];

    const sleep = Number(latestWellness?.sleep || 0);
    const fatigue = Number(latestWellness?.fatigue || 0);
    const soreness = Number(latestWellness?.soreness || 0);

    const wellnessTotal = sleep + fatigue + soreness;

    let wellnessScore = 100;

    if (wellnessTotal >= 12) {
      wellnessScore = 40;
    } else if (wellnessTotal >= 9) {
      wellnessScore = 65;
    } else if (wellnessTotal >= 6) {
      wellnessScore = 80;
    }

    const activeInjuries = (injuriesByPlayer.get(player.id) || []).filter((record) => {
      return isActiveInjury(record);
    });

    const injuryCount = activeInjuries.length;
    const playerStatus = String(player.status || "available").toLowerCase();

    let injuryScore = 100;

    if (playerStatus === "injured" || playerStatus === "rehab" || injuryCount > 0) {
      injuryScore = 15;
    }

    const readinessScore = Math.round(
      (attendancePercentage * 0.35) +
      (wellnessScore * 0.40) +
      (injuryScore * 0.25)
    );

    let readiness = "Ready";
    let readinessClass = "readiness-ready";

    if (readinessScore < 50) {
      readiness = "High Risk";
      readinessClass = "readiness-danger";
    } else if (readinessScore < 75) {
      readiness = "Monitor";
      readinessClass = "readiness-monitor";
    }

    return {
      player,
      attendancePercentage,
      wellnessTotal,
      injuryCount,
      readiness,
      readinessClass,
      readinessScore,
      sleep,
      fatigue,
      soreness
    };
  });
}

function getReadinessRowForPlayer(playerId) {
  return getReadinessRows().find((row) => row.player.id === playerId);
}

function getSortedAvailablePlayers() {
  return getReadinessRows()
    .filter((row) => row.readiness !== "High Risk")
    .sort((a, b) => b.readinessScore - a.readinessScore);
}

function renderReadiness() {
  const rows = getReadinessRows().sort((a, b) => {
    const positionOrder =
      getPositionSortOrder(a.player.position) -
      getPositionSortOrder(b.player.position);

    if (positionOrder !== 0) return positionOrder;

    return b.readinessScore - a.readinessScore;
  });

  const readyCount = rows.filter((row) => row.readiness === "Ready").length;
  const monitorCount = rows.filter((row) => row.readiness === "Monitor").length;
  const unavailableCount = rows.filter((row) => row.readiness === "High Risk").length;

  matchTotalPlayers.textContent = rows.length;
  matchReadyPlayers.textContent = readyCount;
  matchMonitorPlayers.textContent = monitorCount;
  matchUnavailablePlayers.textContent = unavailableCount;

  matchReadinessList.innerHTML = "";

  if (!rows.length) {
    matchReadinessList.innerHTML = `
      <div class="list-item">
        <strong>No players found.</strong>
        <p>No players are linked to this team yet. Check the player's selected teams in Player Profiles.</p>
      </div>
    `;
    return;
  }

  rows.forEach((row) => {
    const player = row.player;

    const item = document.createElement("div");
    item.className = "report-row elite-readiness-row";

    item.innerHTML = `
      <div>
        <h3>${getPlayerName(player)}</h3>
        <p>${player.position || "No position"} • ${player.ageGroup || "No group"}</p>
      </div>

      <div class="report-metrics">
        <span class="report-pill ${row.readinessClass}">
          ${row.readiness}
        </span>

        <span>Score: ${row.readinessScore}%</span>
        <span>Attendance: ${row.attendancePercentage}%</span>
        <span>Wellness: S:${row.sleep} F:${row.fatigue} SO:${row.soreness}</span>
        <span>Injuries: ${row.injuryCount}</span>

        ${
          activeProfile.role === "player"
            ? ""
            : `
              <button
                class="
                  ${row.readiness === "High Risk" ? "btn-danger" : "btn-primary"}
                  select-player-btn
                  ${
                    startingSquad.some((item) => item.id === player.id) ||
                    benchSquad.some((item) => item.id === player.id)
                      ? "player-selected-btn"
                      : ""
                  }
                "
                data-id="${player.id}"
                data-readiness="${row.readiness}"
                ${
                  startingSquad.some((item) => item.id === player.id) ||
                  benchSquad.some((item) => item.id === player.id)
                    ? "disabled"
                    : ""
                }
              >
                ${
                  startingSquad.some((item) => item.id === player.id) ||
                  benchSquad.some((item) => item.id === player.id)
                    ? "Selected"
                    : row.readiness === "High Risk"
                      ? "Override Select"
                      : "Select"
                }
              </button>
            `
        }
      </div>
    `;

    matchReadinessList.appendChild(item);
  });
}

function updateSquadCounters() {
  if (startingCounter) {
    startingCounter.textContent = startingSquad.length;
  }

  if (benchCounter) {
    benchCounter.textContent = benchSquad.length;
  }
}

function renderSquadLists() {
  startingList.innerHTML = "";
  benchList.innerHTML = "";

  if (!startingSquad.length) {
    startingList.innerHTML = `<div class="list-item">No starting players selected.</div>`;
  }

  if (!benchSquad.length) {
    benchList.innerHTML = `<div class="list-item">No bench players selected.</div>`;
  }

  startingSquad.forEach((player) => {
    const item = document.createElement("div");
    item.className = "squad-player-card";

    item.innerHTML = `
      <div>
        <strong>${getPlayerName(player)}</strong>
        <span>
          ${player.selectedRole || player.position || "No position"}
          ${player.readiness ? ` • ${player.readiness} (${player.readinessScore || 0}%)` : ""}
        </span>
      </div>

      <button class="btn-danger remove-squad-player" data-id="${player.id}">
        Remove
      </button>
    `;

    startingList.appendChild(item);
  });

  benchSquad.forEach((player) => {
    const item = document.createElement("div");
    item.className = "squad-player-card";

    item.innerHTML = `
      <div>
        <strong>${getPlayerName(player)}</strong>
        <span>
          ${player.selectedRole || player.position || "No position"}
          ${player.readiness ? ` • ${player.readiness} (${player.readinessScore || 0}%)` : ""}
        </span>
      </div>

      <button class="btn-danger remove-squad-player" data-id="${player.id}">
        Remove
      </button>
    `;

    benchList.appendChild(item);
  });

  updateSquadCounters();
}

function normalizePosition(position) {
  const value = String(position || "").toLowerCase().trim();

  if (value.includes("loosehead")) return "Loosehead Prop";
  if (value.includes("tighthead")) return "Tighthead Prop";
  if (value.includes("hooker")) return "Hooker";
  if (value.includes("lock")) return "Lock";
  if (value.includes("flanker")) return "Flanker";
  if (value.includes("eight") || value.includes("8")) return "Number Eight";
  if (value.includes("scrum")) return "Scrumhalf";
  if (value.includes("fly")) return "Flyhalf";
  if (value.includes("inside")) return "Inside Centre";
  if (value.includes("outside")) return "Outside Centre";
  if (value.includes("centre") || value.includes("center")) return "Centre";
  if (value.includes("wing")) return "Wing";
  if (value.includes("fullback")) return "Fullback";

  return position || "Unknown";
}

function getPositionSortOrder(position) {
  const normalized = normalizePosition(position);

  const order = {
    "Loosehead Prop": 1,
    "Hooker": 2,
    "Tighthead Prop": 3,
    "Lock": 4,
    "Flanker": 6,
    "Number Eight": 8,
    "Scrumhalf": 9,
    "Flyhalf": 10,
    "Wing": 11,
    "Inside Centre": 12,
    "Outside Centre": 13,
    "Centre": 13,
    "Fullback": 15
  };

  return order[normalized] || 99;
}

function getBestPlayerForPosition(rows, positionName, selectedIds) {
  const matchingRows = rows.filter((row) => {
    return normalizePosition(row.player.position) === positionName &&
      !selectedIds.has(row.player.id);
  });

  if (!matchingRows.length) return null;

  return matchingRows[0];
}

function mapRowToSelectedPlayer(row) {
  return {
    ...row.player,
    readiness: row.readiness,
    readinessScore: row.readinessScore
  };
}

function autoSelectStartingXV() {
  const sortedRows = getSortedAvailablePlayers();
  const selectedIds = new Set();

  const positionPlan = [
    "Loosehead Prop",
    "Hooker",
    "Tighthead Prop",
    "Lock",
    "Lock",
    "Flanker",
    "Flanker",
    "Number Eight",
    "Scrumhalf",
    "Flyhalf",
    "Wing",
    "Inside Centre",
    "Outside Centre",
    "Wing",
    "Fullback"
  ];

  const selectedRows = [];
  const missingPositions = [];

  positionPlan.forEach((positionName) => {
    let selectedRow = getBestPlayerForPosition(sortedRows, positionName, selectedIds);

    if (!selectedRow && (positionName === "Inside Centre" || positionName === "Outside Centre")) {
      selectedRow = getBestPlayerForPosition(sortedRows, "Centre", selectedIds);
    }

    if (selectedRow) {
      selectedRows.push({
        ...selectedRow,
        selectedRole: positionName
      });

      selectedIds.add(selectedRow.player.id);
    } else {
      missingPositions.push(positionName);
    }
  });

  if (selectedRows.length < 15) {
    const fallbackRows = sortedRows.filter((row) => !selectedIds.has(row.player.id));

    fallbackRows.forEach((row) => {
      if (selectedRows.length >= 15) return;

      selectedRows.push(row);
      selectedIds.add(row.player.id);
    });
  }

  startingSquad = selectedRows.map((row) => ({
    ...mapRowToSelectedPlayer(row),
    selectedRole: row.selectedRole || normalizePosition(row.player.position)
  }));

  renderSquadLists();

  if (missingPositions.length) {
    showToast(
      `Balanced XV created, but missing: ${missingPositions.join(", ")}. Best available players were used as fallback.`,
      "warning"
    );
    return;
  }

  showToast("Balanced Starting XV selected automatically.", "success");
}

function autoFillBench() {
  const sortedRows = getSortedAvailablePlayers();

  const selectedIds = new Set([
    ...startingSquad.map((player) => player.id),
    ...benchSquad.map((player) => player.id)
  ]);

  const benchPlan = [
    "Loosehead Prop",
    "Hooker",
    "Tighthead Prop",
    "Lock",
    "Flanker",
    "Scrumhalf",
    "Flyhalf",
    "Outside Back"
  ];

  const selectedRows = [];
  const missingPositions = [];

  function getBenchPlayer(positionName) {
    if (positionName === "Outside Back") {
      return sortedRows.find((row) => {
        const position = normalizePosition(row.player.position);

        return !selectedIds.has(row.player.id) &&
          (position === "Wing" || position === "Fullback");
      });
    }

    return getBestPlayerForPosition(sortedRows, positionName, selectedIds);
  }

  benchPlan.forEach((positionName) => {
    let selectedRow = getBenchPlayer(positionName);

    if (!selectedRow && positionName === "Flyhalf") {
      selectedRow =
        getBestPlayerForPosition(sortedRows, "Inside Centre", selectedIds) ||
        getBestPlayerForPosition(sortedRows, "Outside Centre", selectedIds) ||
        getBestPlayerForPosition(sortedRows, "Centre", selectedIds);
    }

    if (!selectedRow && positionName === "Flanker") {
      selectedRow = getBestPlayerForPosition(sortedRows, "Number Eight", selectedIds);
    }

    if (selectedRow) {
      selectedRows.push({
        ...selectedRow,
        selectedRole: positionName
      });

      selectedIds.add(selectedRow.player.id);
    } else {
      missingPositions.push(positionName);
    }
  });

  if (selectedRows.length < 8) {
    const fallbackRows = sortedRows.filter((row) => !selectedIds.has(row.player.id));

    fallbackRows.forEach((row) => {
      if (selectedRows.length >= 8) return;

      selectedRows.push({
        ...row,
        selectedRole: normalizePosition(row.player.position)
      });

      selectedIds.add(row.player.id);
    });
  }

  benchSquad = selectedRows.map((row) => ({
    ...mapRowToSelectedPlayer(row),
    selectedRole: row.selectedRole || normalizePosition(row.player.position)
  }));

  renderSquadLists();

  if (missingPositions.length) {
    showToast(
      `Bench selected, but missing cover for: ${missingPositions.join(", ")}. Best available fallback players were used.`,
      "warning"
    );
    return;
  }

  showToast("Bench selected with front-row cover.", "success");
}

function clearSquads() {
  const confirmed = confirm("Are you sure you want to clear the entire squad selection?");
  if (!confirmed) return;

  startingSquad = [];
  benchSquad = [];

  renderSquadLists();
  showToast("Squad cleared.", "success");
}

async function loadSavedSquad() {
  const savedSelections = await getMatchSelections();

  if (!savedSelections.length) {
    renderSquadLists();
    return;
  }

  savedSelections.sort((a, b) => getDateValue(b) - getDateValue(a));

  const latestSelection = savedSelections[0];

  currentSelectionId = latestSelection.id;

  if (selectionNotes) {
    selectionNotes.value = latestSelection.selectionNotes || "";
  }

  function rebuildPlayer(savedPlayer) {
    const existingPlayer = playersCache.find((player) => {
      return player.id === savedPlayer.playerId;
    });

    if (existingPlayer) {
      return {
        ...existingPlayer,
        selectedRole: savedPlayer.selectedRole || existingPlayer.position || "",
        jerseyNumber: savedPlayer.jerseyNumber || existingPlayer.jerseyNumber || ""
      };
    }

    return {
      id: savedPlayer.playerId,
      firstName: savedPlayer.name?.split(" ")[0] || savedPlayer.name || "",
      lastName: savedPlayer.name?.split(" ").slice(1).join(" ") || "",
      position: savedPlayer.position || "",
      selectedRole: savedPlayer.selectedRole || "",
      jerseyNumber: savedPlayer.jerseyNumber || ""
    };
  }

  startingSquad = (latestSelection.startingSquad || []).map(rebuildPlayer);
  benchSquad = (latestSelection.benchSquad || []).map(rebuildPlayer);

  renderSquadLists();
}

function exportMatchReadinessToCSV() {
  const rows = getReadinessRows();

  let csvContent = "Player,Team,Opponent,Match Date,Position,Attendance,Wellness,Injuries,Readiness\n";

  rows.forEach((row) => {
    const player = row.player;

    const csvRow = [
      `"${getPlayerName(player)}"`,
      `"${currentTeam?.name || "Team"}"`,
      `"${currentMatch?.opponent || "Opponent"}"`,
      `"${currentMatch?.date || ""}"`,
      `"${player.position || ""}"`,
      `"${row.attendancePercentage}%"`,
      `"${row.wellnessTotal || "-"}"`,
      `"${row.injuryCount}"`,
      `"${row.readiness}"`
    ];

    csvContent += csvRow.join(",") + "\n";
  });

  const blob = new Blob([csvContent], {
    type: "text/csv;charset=utf-8;"
  });

  const link = document.createElement("a");
  const url = URL.createObjectURL(blob);

  link.setAttribute("href", url);
  link.setAttribute("download", `match-readiness-${currentMatch?.date || "report"}.csv`);

  link.style.visibility = "hidden";

  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);

  URL.revokeObjectURL(url);
}

printMatchReadinessBtn?.addEventListener("click", function () {
  window.print();
});

exportMatchCsvBtn?.addEventListener("click", function () {
  exportMatchReadinessToCSV();
});

document.addEventListener("click", function (event) {
  const removeBtn = event.target.closest(".remove-squad-player");
  if (!removeBtn) return;

  const playerId = removeBtn.dataset.id;

  startingSquad = startingSquad.filter((player) => player.id !== playerId);
  benchSquad = benchSquad.filter((player) => player.id !== playerId);

  renderSquadLists();
  renderReadiness();
});

matchReadinessList?.addEventListener("click", function (event) {
  const selectBtn = event.target.closest(".select-player-btn");
  if (!selectBtn) return;

  const playerId = selectBtn.dataset.id;
  const player = playersCache.find((item) => item.id === playerId);

  if (!player) return;

  const readinessRow = getReadinessRowForPlayer(playerId);

  const alreadySelected =
    startingSquad.some((item) => item.id === playerId) ||
    benchSquad.some((item) => item.id === playerId);

  if (alreadySelected) {
    showToast("This player is already selected.", "warning");
    return;
  }

  if (readinessRow?.readiness === "High Risk") {
    const confirmed = confirm(
      `${getPlayerName(player)} is marked as High Risk with a readiness score of ${readinessRow.readinessScore}%. Do you want to override and select this player?`
    );

    if (!confirmed) return;
  }

  const selectedPlayer = {
    ...player,
    readiness: readinessRow?.readiness || "Unknown",
    readinessScore: readinessRow?.readinessScore || 0
  };

  if (startingSquad.length < 15) {
    startingSquad.push(selectedPlayer);
  } else {
    benchSquad.push(selectedPlayer);
  }

  renderSquadLists();
  renderReadiness();
});

autoSelectBtn?.addEventListener("click", autoSelectStartingXV);
autoBenchBtn?.addEventListener("click", autoFillBench);
clearSquadBtn?.addEventListener("click", clearSquads);

async function createSelectionNotifications(selectionId, selectionData) {
  const selectedPlayers = [
    ...selectionData.startingSquad.map((player) => ({
      ...player,
      squadRole: "Starting XV"
    })),
    ...selectionData.benchSquad.map((player) => ({
      ...player,
      squadRole: "Bench"
    }))
  ];

  await Promise.all(
    selectedPlayers.map((player) => {
      const notificationRef = doc(
        db,
        "notifications",
        `selection-${selectionId}-${player.playerId}`
      );

      return setDoc(notificationRef, {
        sourceId: selectionId,
        sourceCollection: "matchSelections",
        type: "selection",
        severity: "info",
        title: "You have been selected",
        message: `You have been selected for ${selectionData.teamName || "your team"} vs ${selectionData.opponent || "Opponent"} on ${selectionData.matchDate || "match day"} as ${player.squadRole}.`,
        link: `player-match-detail.html?id=${selectionData.matchId}`,
        playerId: player.playerId || "",
        playerName: player.name || "",
        teamId: selectionData.teamId || "",
        teamName: selectionData.teamName || "",
        organisationId: activeProfile.organisationId,
        readBy: {},
        createdAt: serverTimestamp(),
        updatedAt: serverTimestamp()
      });
    })
  );
}

saveSquadBtn?.addEventListener("click", async function () {
  if (activeProfile.role === "player") {
    showToast("Players can view readiness but cannot save squad selections.", "warning");
    return;
  }

  const selectionData = {
    matchId,
    teamId: currentMatch.teamId,
    teamName: currentTeam?.name || "",
    opponent: currentMatch.opponent || "",
    matchDate: currentMatch.date || "",
    selectionNotes: selectionNotes?.value.trim() || "",
    startingSquad: startingSquad.map((player) => ({
      playerId: player.id,
      name: getPlayerName(player),
      position: player.position || "",
      selectedRole: player.selectedRole || "",
      jerseyNumber: player.jerseyNumber || ""
    })),
    benchSquad: benchSquad.map((player) => ({
      playerId: player.id,
      name: getPlayerName(player),
      position: player.position || "",
      selectedRole: player.selectedRole || "",
      jerseyNumber: player.jerseyNumber || ""
    })),
    organisationId: activeProfile.organisationId,
    updatedAt: serverTimestamp()
  };

  saveSquadBtn.disabled = true;
  saveSquadBtn.textContent = "Saving...";

  try {
    if (currentSelectionId) {
      await updateDoc(doc(db, "matchSelections", currentSelectionId), selectionData);
    
      await createSelectionNotifications(currentSelectionId, selectionData);
    
      showToast("Match squad updated successfully.", "success");
    } else {
      const docRef = await addDoc(collection(db, "matchSelections"), {
        ...selectionData,
        createdBy: activeProfile.uid,
        createdAt: serverTimestamp()
      });
    
      currentSelectionId = docRef.id;
    
      await createSelectionNotifications(currentSelectionId, selectionData);
    
      showToast("Match squad saved successfully.", "success");
    }
  } catch (error) {
    console.error("Error saving squad:", error);
    showToast("Could not save squad: " + error.message, "error");
  } finally {
    saveSquadBtn.disabled = false;
    saveSquadBtn.textContent = "Save Match Squad";
  }
});

requireAuth(async function (user, profile) {
  activeProfile = profile;
  setupLogoutButton();

  if (!matchId) {
  matchTitle.textContent = "Invalid Match";

  if (matchReadinessList) {
    matchReadinessList.innerHTML = `
      <div class="list-item">
        <strong>Invalid match.</strong>
        <p>No match ID was found in the page URL.</p>
      </div>
    `;
  }

  return;
}

  showLoader("Loading match readiness...");

  try {
    const loaded = await loadMatch();

    if (!loaded || !currentMatch) return;

    await loadReadinessData();
    renderReadiness();
    await loadSavedSquad();
  } catch (error) {
    console.error("Match readiness page error:", error);

    matchTitle.textContent = "Could not load match readiness";

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

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