    // =========================================================
    // FILE: matches.js | TYPE: Match Management 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 {
      collection,
      addDoc,
      getDocs,
      serverTimestamp,
      query,
      where,
      doc,
      updateDoc,
      deleteDoc,
      setDoc
    } from "https://www.gstatic.com/firebasejs/10.12.2/firebase-firestore.js";
    
    const matchForm = document.getElementById("matchForm");
    const matchTeam = document.getElementById("matchTeam");
    const matchTeamFilter = document.getElementById("matchTeamFilter");
    const matchList = document.getElementById("matchList");
    
    const opponent = document.getElementById("opponent");
    const matchDate = document.getElementById("matchDate");
    const matchTime = document.getElementById("matchTime");
    const venue = document.getElementById("venue");
    const matchType = document.getElementById("matchType");
    
    const matchStatusFilter = document.getElementById("matchStatusFilter");
    const matchResultFilter = document.getElementById("matchResultFilter");
    const matchSearchInput = document.getElementById("matchSearchInput");
    const clearMatchFiltersBtn = document.getElementById("clearMatchFiltersBtn");
    
    const completedReportsCount = document.getElementById("completedReportsCount");
    const draftReportsCount = document.getElementById("draftReportsCount");
    const winsCount = document.getElementById("winsCount");
    const lossesCount = document.getElementById("lossesCount");
    const drawsCount = document.getElementById("drawsCount");
    const winRateCount = document.getElementById("winRateCount");
    
    let activeProfile = null;
    let teamsCache = [];
    let matchesCache = [];
    let editingMatchId = null;
    
    const submitButton = matchForm
      ? matchForm.querySelector("button[type='submit']")
      : null;
    
    function setButtonLoading(isLoading, text = "Saving...") {
      if (!submitButton) return;
    
      submitButton.disabled = isLoading;
      submitButton.textContent = isLoading
        ? text
        : editingMatchId
          ? "Update Match"
          : "Save Match";
    }
    
    function getTeamName(teamId) {
      const team = teamsCache.find((item) => item.id === teamId);
      return team ? team.name : "Unassigned";
    }
    
    function resetFormMode() {
      editingMatchId = null;
    
      if (matchForm) matchForm.reset();
      if (submitButton) {
        submitButton.textContent = "Save Match";
        submitButton.disabled = false;
      }
    }
    
    function canAccessTeam(teamId) {
      if (!activeProfile) 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(teamId);
      }
    
      return false;
    }
    
    function sortMatchesCache() {
      matchesCache.sort((a, b) => {
        return new Date(a.date || "9999-12-31") - new Date(b.date || "9999-12-31");
      });
    }
    
    async function createMatchNotification(matchId, matchData) {
      const notificationRef = doc(db, "notifications", `match-${matchId}`);
    
      if (!matchData.date) {
        await deleteDoc(notificationRef).catch(() => {});
        return;
      }
    
      const matchDateValue = new Date(matchData.date);
      const today = new Date();
    
      today.setHours(0, 0, 0, 0);
      matchDateValue.setHours(0, 0, 0, 0);
    
      const daysUntil = Math.ceil(
        (matchDateValue - today) / (1000 * 60 * 60 * 24)
      );
    
      if (daysUntil < 0) {
        await deleteDoc(notificationRef).catch(() => {});
        return;
      }
    
      await setDoc(notificationRef, {
        sourceId: matchId,
        sourceCollection: "matches",
        type: "match",
        severity: daysUntil <= 2 ? "monitor" : "info",
        title: editingMatchId ? "Match Fixture Updated" : "New Match Scheduled",
        message: `${matchData.teamName || "Team"} vs ${matchData.opponent || "Opponent"} ${editingMatchId ? "has been updated" : "has been scheduled"} for ${matchData.date || "No date"}${matchData.time ? " at " + matchData.time : ""} at ${matchData.venue || "No venue"}.`,
        link: `player-match-detail.html?id=${matchId}`,
        teamId: matchData.teamId || "",
        teamName: matchData.teamName || "",
        playerId: "",
        playerName: "",
        organisationId: activeProfile.organisationId,
        readBy: {},
        createdAt: serverTimestamp(),
        updatedAt: serverTimestamp()
      });
    }
    
    async function createMatchReminderNotifications(matchId, matchData) {
      if (!matchData.date) return;
    
      const matchDateValue = new Date(matchData.date);
      const today = new Date();
    
      today.setHours(0, 0, 0, 0);
      matchDateValue.setHours(0, 0, 0, 0);
    
      const daysUntil = Math.ceil(
        (matchDateValue - today) / (1000 * 60 * 60 * 24)
      );
    
      const tomorrowRef = doc(db, "notifications", `match-reminder-tomorrow-${matchId}`);
      const todayRef = doc(db, "notifications", `match-reminder-today-${matchId}`);
    
      if (daysUntil === 1) {
        await setDoc(tomorrowRef, {
          sourceId: matchId,
          sourceCollection: "matches",
          type: "match",
          severity: "monitor",
          title: "Match Tomorrow",
          message: `${matchData.teamName || "Team"} plays ${matchData.opponent || "Opponent"} tomorrow${matchData.time ? " at " + matchData.time : ""} at ${matchData.venue || "No venue"}.`,
          link: `player-match-detail.html?id=${matchId}`,
          teamId: matchData.teamId || "",
          teamName: matchData.teamName || "",
          playerId: "",
          playerName: "",
          organisationId: activeProfile.organisationId,
          readBy: {},
          createdAt: serverTimestamp(),
          updatedAt: serverTimestamp()
        });
      } else {
        await deleteDoc(tomorrowRef).catch(() => {});
      }
    
      if (daysUntil === 0) {
        await setDoc(todayRef, {
          sourceId: matchId,
          sourceCollection: "matches",
          type: "match",
          severity: "monitor",
          title: "Match Today",
          message: `${matchData.teamName || "Team"} plays ${matchData.opponent || "Opponent"} today${matchData.time ? " at " + matchData.time : ""} at ${matchData.venue || "No venue"}.`,
          link: `player-match-detail.html?id=${matchId}`,
          teamId: matchData.teamId || "",
          teamName: matchData.teamName || "",
          playerId: "",
          playerName: "",
          organisationId: activeProfile.organisationId,
          readBy: {},
          createdAt: serverTimestamp(),
          updatedAt: serverTimestamp()
        });
      } else {
        await deleteDoc(todayRef).catch(() => {});
      }
    }
    
    async function loadPageData() {
      const teamsQuery = query(
        collection(db, "teams"),
        where("organisationId", "==", activeProfile.organisationId)
      );
    
      const matchesQuery = query(
        collection(db, "matches"),
        where("organisationId", "==", activeProfile.organisationId)
      );
    
      const [teamsSnapshot, matchesSnapshot] = await Promise.all([
        getDocs(teamsQuery),
        getDocs(matchesQuery)
      ]);
    
      teamsCache = teamsSnapshot.docs
        .map((docSnap) => ({
          id: docSnap.id,
          ...docSnap.data()
        }))
        .filter((team) => canAccessTeam(team.id));
    
      matchesCache = matchesSnapshot.docs
        .map((docSnap) => ({
          id: docSnap.id,
          ...docSnap.data()
        }))
        .filter((match) => canAccessTeam(match.teamId));
    
      sortMatchesCache();
    }
    
    function renderTeamDropdowns() {
      if (!matchTeam || !matchTeamFilter) return;
    
      matchTeam.innerHTML = `<option value="">Select team</option>`;
      matchTeamFilter.innerHTML = `<option value="all">All Teams</option>`;
    
      teamsCache.forEach((team) => {
        const option = document.createElement("option");
        option.value = team.id;
        option.textContent = `${team.name || "Unnamed Team"} • ${team.ageGroup || "No age group"}`;
        matchTeam.appendChild(option);
    
        const filterOption = document.createElement("option");
        filterOption.value = team.id;
        filterOption.textContent = `${team.name || "Unnamed Team"} • ${team.ageGroup || "No age group"}`;
        matchTeamFilter.appendChild(filterOption);
      });
    }
    
    function renderReportCounters() {
      if (!completedReportsCount || !draftReportsCount) return;
    
      const selectedTeam = matchTeamFilter?.value || "all";
    
      const counterMatches = matchesCache.filter((match) => {
        return selectedTeam === "all" || match.teamId === selectedTeam;
      });
    
      const completedCount = counterMatches.filter((match) => {
        return match.postMatchReportStatus === "complete";
      }).length;
    
      const draftCount = counterMatches.filter((match) => {
        return match.postMatchReportStatus !== "complete";
      }).length;
    
      const wins = counterMatches.filter((match) => match.result === "win").length;
      const losses = counterMatches.filter((match) => match.result === "loss").length;
      const draws = counterMatches.filter((match) => match.result === "draw").length;
    
      const completedResults = wins + losses + draws;
    
      const winRate = completedResults
        ? Math.round((wins / completedResults) * 100)
        : 0;
    
      completedReportsCount.textContent = completedCount;
      draftReportsCount.textContent = draftCount;
    
      if (winsCount) winsCount.textContent = wins;
      if (lossesCount) lossesCount.textContent = losses;
      if (drawsCount) drawsCount.textContent = draws;
      if (winRateCount) winRateCount.textContent = `${winRate}%`;
    }
    
    function updateActiveSummaryCard() {
      document.querySelectorAll(".report-summary-card").forEach((card) => {
        card.classList.remove("active-summary-card");
    
        if (
          card.dataset.reportFilter &&
          card.dataset.reportFilter === matchStatusFilter?.value
        ) {
          card.classList.add("active-summary-card");
        }
    
        if (
          card.dataset.resultFilter &&
          card.dataset.resultFilter === matchResultFilter?.value
        ) {
          card.classList.add("active-summary-card");
        }
      });
    }
    
    function getResultClass(result) {
      if (result === "win") return "match-result-win";
      if (result === "loss") return "match-result-loss";
      if (result === "draw") return "match-result-draw";
      return "";
    }
    
    function getReportStatus(match) {
      return match.postMatchReportStatus === "complete" ? "complete" : "draft";
    }
    
    function renderMatches() {
      if (!matchList) return;
    
      renderReportCounters();
      updateActiveSummaryCard();
    
      const selectedTeam = matchTeamFilter?.value || "all";
      const selectedStatus = matchStatusFilter?.value || "all";
      const selectedResult = matchResultFilter?.value || "all";
      const searchTerm = (matchSearchInput?.value || "").toLowerCase().trim();
    
      const filteredMatches = matchesCache.filter((match) => {
        const teamMatch = selectedTeam === "all" || match.teamId === selectedTeam;
    
        const reportStatus = getReportStatus(match);
        const statusMatch = selectedStatus === "all" || reportStatus === selectedStatus;
    
        const resultMatch = selectedResult === "all" || match.result === selectedResult;
    
        const searchableText = `
          ${getTeamName(match.teamId)}
          ${match.opponent || ""}
          ${match.venue || ""}
          ${match.date || ""}
          ${match.time || ""}
          ${match.type || ""}
          ${match.status || ""}
        `.toLowerCase();
    
        const searchMatch = !searchTerm || searchableText.includes(searchTerm);
    
        return teamMatch && statusMatch && resultMatch && searchMatch;
      });
    
      matchList.innerHTML = "";
    
      if (!filteredMatches.length) {
        matchList.innerHTML = `
          <div class="app-card">
            <strong>No matches found.</strong>
            <p>Create a fixture or adjust your filters.</p>
          </div>
        `;
        return;
      }
    
      filteredMatches.forEach((match) => {
        const resultClass = getResultClass(match.result);
        const reportStatus = getReportStatus(match);
    
        const item = document.createElement("div");
        item.className = `match-card elite-match-card ${resultClass}`;
    
        item.innerHTML = `
          <div class="elite-match-header">
            <div>
              <span class="match-date-pill">
                ${match.date || "No date"}
              </span>
    
              <h3>
                ${getTeamName(match.teamId)}
                <span>vs</span>
                ${match.opponent || "Unknown Opponent"}
              </h3>
    
              <p>
                ${match.time ? match.time + " • " : ""}
                ${match.venue || "No venue"}
                <span class="record-separator">&bull;</span>
                ${match.type || "match"}
              </p>
            </div>
    
            <div class="elite-match-score">
              <strong>${match.homeScore ?? "-"}</strong>
              <span>:</span>
              <strong>${match.awayScore ?? "-"}</strong>
            </div>
          </div>
    
          <div class="elite-match-meta-grid">
            <div>
              <span>Status</span>
              <strong>${match.status || "Not Started"}</strong>
            </div>
    
            <div>
              <span>Report</span>
              <strong>${reportStatus === "complete" ? "Complete" : "Draft"}</strong>
            </div>
    
            <div>
              <span>Result</span>
              <strong>${match.result || "Pending"}</strong>
            </div>
          </div>
    
          <div class="elite-match-footer">
            <div class="match-status-row">
              <span class="match-status-badge">
                ${match.status || "Not Started"}
              </span>
    
              <span class="report-status-badge ${
                reportStatus === "complete" ? "report-complete" : "report-draft"
              }">
                ${reportStatus === "complete" ? "Report Complete" : "Report Draft"}
              </span>
            </div>
    
            <div class="record-actions">
              <a href="match-readiness.html?id=${match.id}" class="btn-secondary">
                Readiness
              </a>
    
              <a href="match-centre.html?id=${match.id}" class="btn-primary">
                Match Centre
              </a>
    
              <a href="post-match-report.html?id=${match.id}" class="btn-secondary">
                Report
              </a>
    
              <button class="btn-secondary edit-match-btn" data-id="${match.id}" type="button">
                Edit
              </button>
    
              <button class="btn-danger delete-match-btn" data-id="${match.id}" type="button">
                Delete
              </button>
            </div>
          </div>
        `;
    
        matchList.appendChild(item);
      });
    }
    
    matchForm?.addEventListener("submit", async function (event) {
      event.preventDefault();
    
      const teamId = matchTeam?.value;
    
      if (!teamId) {
        showToast("Please select a team.", "warning");
        return;
      }
    
      if (!opponent?.value.trim()) {
        showToast("Please enter an opponent.", "warning");
        return;
      }
    
      if (!matchDate?.value) {
        showToast("Please select a match date.", "warning");
        return;
      }
    
      if (!canAccessTeam(teamId)) {
        showToast("You do not have access to this team.", "error");
        return;
      }
    
      const matchData = {
        teamId,
        teamName: getTeamName(teamId),
        opponent: opponent.value.trim(),
        date: matchDate.value,
        time: matchTime?.value || "",
        kickoffTime: matchTime?.value || "",
        venue: venue?.value.trim() || "",
        type: matchType?.value || "league",
        organisationId: activeProfile.organisationId,
        updatedAt: serverTimestamp()
      };
    
      setButtonLoading(true, editingMatchId ? "Updating..." : "Saving...");
    
      try {
        if (editingMatchId) {
          await updateDoc(doc(db, "matches", editingMatchId), matchData);
          await createMatchNotification(editingMatchId, matchData);
          await createMatchReminderNotifications(editingMatchId, matchData);
    
          matchesCache = matchesCache.map((match) =>
            match.id === editingMatchId
              ? {
                  ...match,
                  ...matchData,
                  updatedAt: new Date()
                }
              : match
          );
    
          showToast("Match updated successfully.", "success");
        } else {
          const matchRef = await addDoc(collection(db, "matches"), {
            ...matchData,
            createdBy: activeProfile.uid,
            createdAt: serverTimestamp()
          });
    
          await createMatchNotification(matchRef.id, matchData);
          await createMatchReminderNotifications(matchRef.id, matchData);
    
          matchesCache.push({
            id: matchRef.id,
            ...matchData,
            createdBy: activeProfile.uid,
            createdAt: new Date()
          });
    
          showToast("Match saved successfully.", "success");
        }
    
        sortMatchesCache();
        resetFormMode();
        renderMatches();
      } catch (error) {
        console.error("Error saving match:", error);
        showToast("Could not save match: " + error.message, "error");
      } finally {
        setButtonLoading(false);
      }
    });
    
    matchList?.addEventListener("click", async function (event) {
      const editBtn = event.target.closest(".edit-match-btn");
      const deleteBtn = event.target.closest(".delete-match-btn");
    
      if (editBtn) {
        const matchId = editBtn.dataset.id;
        const match = matchesCache.find((item) => item.id === matchId);
    
        if (!match) return;
    
        editingMatchId = match.id;
    
        if (matchTeam) matchTeam.value = match.teamId || "";
        if (opponent) opponent.value = match.opponent || "";
        if (matchDate) matchDate.value = match.date || "";
        if (matchTime) matchTime.value = match.time || match.kickoffTime || "";
        if (venue) venue.value = match.venue || "";
        if (matchType) matchType.value = match.type || "league";
        if (submitButton) submitButton.textContent = "Update Match";
    
        window.scrollTo({ top: 0, behavior: "smooth" });
      }
    
      if (deleteBtn) {
        const matchId = deleteBtn.dataset.id;
    
        const confirmed = confirm("Are you sure you want to delete this match?");
        if (!confirmed) return;
    
        deleteBtn.disabled = true;
        deleteBtn.textContent = "Deleting...";
    
        try {
          await deleteDoc(doc(db, "matches", matchId));
          await deleteDoc(doc(db, "notifications", `match-${matchId}`)).catch(() => {});
          await deleteDoc(doc(db, "notifications", `match-status-${matchId}`)).catch(() => {});
          await deleteDoc(doc(db, "notifications", `match-reminder-tomorrow-${matchId}`)).catch(() => {});
          await deleteDoc(doc(db, "notifications", `match-reminder-today-${matchId}`)).catch(() => {});
    
          matchesCache = matchesCache.filter((match) => match.id !== matchId);
    
          renderMatches();
          showToast("Match deleted.", "success");
        } catch (error) {
          console.error("Error deleting match:", error);
          showToast("Could not delete match: " + error.message, "error");
        } finally {
          deleteBtn.disabled = false;
          deleteBtn.textContent = "Delete";
        }
      }
    });
    
    document.querySelectorAll(".report-summary-card").forEach((card) => {
      card.addEventListener("click", function () {
        const reportFilter = card.dataset.reportFilter;
        const resultFilter = card.dataset.resultFilter;
        const clearFilters = card.dataset.clearFilters;
    
        if (reportFilter && matchStatusFilter && matchResultFilter) {
          matchStatusFilter.value = reportFilter;
          matchResultFilter.value = "all";
        }
    
        if (resultFilter && matchResultFilter && matchStatusFilter) {
          matchResultFilter.value = resultFilter;
          matchStatusFilter.value = "all";
        }
    
        if (clearFilters && matchStatusFilter && matchResultFilter) {
          matchStatusFilter.value = "all";
          matchResultFilter.value = "all";
        }
    
        renderMatches();
      });
    });
    
    clearMatchFiltersBtn?.addEventListener("click", function () {
      if (matchTeamFilter) matchTeamFilter.value = "all";
      if (matchStatusFilter) matchStatusFilter.value = "all";
      if (matchResultFilter) matchResultFilter.value = "all";
      if (matchSearchInput) matchSearchInput.value = "";
    
      renderMatches();
    });
    
    matchTeamFilter?.addEventListener("change", renderMatches);
    matchStatusFilter?.addEventListener("change", renderMatches);
    matchResultFilter?.addEventListener("change", renderMatches);
    matchSearchInput?.addEventListener("input", renderMatches);
    
    requireAuth(async function (user, profile) {
      activeProfile = profile;
      setupLogoutButton();
    
      showLoader("Loading matches...");
    
      if (matchList) {
        matchList.innerHTML = `<div class="app-card">Loading matches...</div>`;
      }
    
      try {
        await loadPageData();
        renderTeamDropdowns();
        renderMatches();
      } catch (error) {
        console.error("Error loading matches:", error);
    
        if (matchList) {
          matchList.innerHTML = `
            <div class="app-card">
              <strong>Error loading matches.</strong>
              <p>${error.message}</p>
            </div>
          `;
        }
    
        showToast("Could not load matches: " + error.message, "error");
      } finally {
        hideLoader();
      }
    });