// =========================================================
// FILE: match-centre.js | TYPE: Match Centre 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,
  serverTimestamp,
  updateDoc,
  deleteDoc,
  setDoc,
  deleteField
} 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 matchCentreTitle = document.getElementById("matchCentreTitle");
const matchCentreMeta = document.getElementById("matchCentreMeta");

const homeScore = document.getElementById("homeScore");
const awayScore = document.getElementById("awayScore");
const homeTeamName = document.getElementById("homeTeamName");
const awayTeamName = document.getElementById("awayTeamName");

const matchEventForm = document.getElementById("matchEventForm");
const eventMinute = document.getElementById("eventMinute");
const eventTeam = document.getElementById("eventTeam");
const eventType = document.getElementById("eventType");
const conversionResultGroup = document.getElementById("conversionResultGroup");
const conversionResult = document.getElementById("conversionResult");
const eventPlayer = document.getElementById("eventPlayer");
const eventNotes = document.getElementById("eventNotes");
const matchTimeline = document.getElementById("matchTimeline");

const matchStatus = document.getElementById("matchStatus");
const matchStatusButtons = document.querySelectorAll(".match-status-btn");
const matchHalf = document.getElementById("matchHalf");
const matchHalfSelect = document.getElementById("matchHalfSelect");

const exportTimelineCsvBtn = document.getElementById("exportTimelineCsvBtn");
const saveFinalScoreBtn = document.getElementById("saveFinalScoreBtn");
const matchMinute = document.getElementById("matchMinute");
const matchTries = document.getElementById("matchTries");
const matchConversions = document.getElementById("matchConversions");
const matchPenalties = document.getElementById("matchPenalties");
const matchCards = document.getElementById("matchCards");

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

const scrumsWonInput = document.getElementById("scrumsWon");
const scrumsLostInput = document.getElementById("scrumsLost");
const lineoutsWonInput = document.getElementById("lineoutsWon");
const lineoutsLostInput = document.getElementById("lineoutsLost");
const ruckTurnoversForInput = document.getElementById("ruckTurnoversFor");
const ruckTurnoversAgainstInput = document.getElementById("ruckTurnoversAgainst");
const tacklesMadeInput = document.getElementById("tacklesMade");
const tacklesMissedInput = document.getElementById("tacklesMissed");

const scrumSuccessRate = document.getElementById("scrumSuccessRate");
const scrumsWonDisplay = document.getElementById("scrumsWonDisplay");
const scrumsLostDisplay = document.getElementById("scrumsLostDisplay");

const lineoutSuccessRate = document.getElementById("lineoutSuccessRate");
const lineoutsWonDisplay = document.getElementById("lineoutsWonDisplay");
const lineoutsLostDisplay = document.getElementById("lineoutsLostDisplay");

const ruckTurnoverBalance = document.getElementById("ruckTurnoverBalance");
const ruckTurnoversForDisplay = document.getElementById("ruckTurnoversForDisplay");
const ruckTurnoversAgainstDisplay = document.getElementById("ruckTurnoversAgainstDisplay");

const tackleCompletionRate = document.getElementById("tackleCompletionRate");
const tacklesMadeDisplay = document.getElementById("tacklesMadeDisplay");
const tacklesMissedDisplay = document.getElementById("tacklesMissedDisplay");

const coachAnnouncementForm = document.getElementById("coachAnnouncementForm");
const coachAnnouncementType = document.getElementById("coachAnnouncementType");
const coachAnnouncementTitle = document.getElementById("coachAnnouncementTitle");
const coachAnnouncementMessage = document.getElementById("coachAnnouncementMessage");

let activeProfile = null;
let currentMatch = null;
let currentTeam = null;
let playersCache = [];
let eventsCache = [];
let matchSelectionCache = null;
let matchClockTimer = null;
let editingEventId = null;

const submitButton = matchEventForm?.querySelector("button[type='submit']");

function setButtonLoading(isLoading, text = "Saving...") {
  if (!submitButton) return;

  submitButton.disabled = isLoading;
  submitButton.textContent = isLoading
    ? text
    : editingEventId
      ? "Update Event"
      : "Save Event";
}

function numberValue(input) {
  return Math.max(Number(input?.value || 0), 0);
}

function getPercentage(success, failed) {
  const total = Number(success || 0) + Number(failed || 0);

  if (!total) return "0%";

  return `${Math.round((Number(success || 0) / total) * 100)}%`;
}

function getTeamStatsFromForm() {
  return {
    scrumsWon: numberValue(scrumsWonInput),
    scrumsLost: numberValue(scrumsLostInput),

    lineoutsWon: numberValue(lineoutsWonInput),
    lineoutsLost: numberValue(lineoutsLostInput),

    ruckTurnoversFor: numberValue(ruckTurnoversForInput),
    ruckTurnoversAgainst: numberValue(ruckTurnoversAgainstInput),

    tacklesMade: numberValue(tacklesMadeInput),
    tacklesMissed: numberValue(tacklesMissedInput)
  };
}

function setTeamStatsForm(stats = {}) {
  if (scrumsWonInput) scrumsWonInput.value = stats.scrumsWon || 0;
  if (scrumsLostInput) scrumsLostInput.value = stats.scrumsLost || 0;

  if (lineoutsWonInput) lineoutsWonInput.value = stats.lineoutsWon || 0;
  if (lineoutsLostInput) lineoutsLostInput.value = stats.lineoutsLost || 0;

  if (ruckTurnoversForInput) ruckTurnoversForInput.value = stats.ruckTurnoversFor || 0;
  if (ruckTurnoversAgainstInput) ruckTurnoversAgainstInput.value = stats.ruckTurnoversAgainst || 0;

  if (tacklesMadeInput) tacklesMadeInput.value = stats.tacklesMade || 0;
  if (tacklesMissedInput) tacklesMissedInput.value = stats.tacklesMissed || 0;
}

function getEventPoints(event) {
  if (event.type === "try") return 5;

  if (event.type === "conversion") {
    return event.conversionResult === "successful" ? 2 : 0;
  }

  if (event.type === "penalty") return 3;
  if (event.type === "drop_goal") return 3;

  return 0;
}

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

function getPlayerTeamIds(player) {
  if (!player) return [];

  const teamIds = Array.isArray(player.teamIds)
    ? [...player.teamIds]
    : [];

  if (player.teamId && !teamIds.includes(player.teamId)) {
    teamIds.push(player.teamId);
  }

  return teamIds.filter(Boolean);
}

function getSelectedPlayerName() {
  const selectedOption = eventPlayer?.options[eventPlayer.selectedIndex];

  if (!selectedOption || !eventPlayer.value) return "";

  return selectedOption.textContent
    .split("—")[0]
    .trim();
}

function resetEventForm() {
  editingEventId = null;

  if (matchEventForm) {
    matchEventForm.reset();
  }

  if (submitButton) {
    submitButton.textContent = "Save Event";
    submitButton.disabled = false;
  }

  updateConversionFieldVisibility();
  updateMatchMinuteDisplay();
}

function updateConversionFieldVisibility() {
  if (!conversionResultGroup || !conversionResult || !eventType) return;

  const isConversion = eventType.value === "conversion";

  conversionResultGroup.classList.toggle("hidden", !isConversion);

  if (!isConversion) {
    conversionResult.value = "successful";
  }
}

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") {
    return assignedTeamIds.includes(match.teamId);
  }

  return false;
}

function sortEvents() {
  eventsCache.sort((a, b) => Number(a.minute || 0) - Number(b.minute || 0));
}

function getActiveHalf() {
  return currentMatch?.half || "1st";
}

function getCurrentMatchMinute() {
  if (!currentMatch) return 0;

  const status = currentMatch.status || "Not Started";
  const activeHalf = getActiveHalf();

  if (status === "Full Time") return 80;
  if (status === "Half Time") return 40;
  if (status !== "Live") return 0;

  const startedAtValue =
    activeHalf === "2nd"
      ? currentMatch.secondHalfStartedAt
      : currentMatch.firstHalfStartedAt;

  if (!startedAtValue) return activeHalf === "2nd" ? 40 : 0;

  const startedAtDate = startedAtValue.toDate
    ? startedAtValue.toDate()
    : new Date(startedAtValue);

  const elapsedMinutes = Math.floor((Date.now() - startedAtDate.getTime()) / 60000);

  if (activeHalf === "2nd") {
    return Math.min(80, 40 + Math.max(0, elapsedMinutes));
  }

  return Math.min(40, Math.max(0, elapsedMinutes));
}

function updateMatchMinuteDisplay() {
  const minute = getCurrentMatchMinute();

  if (matchMinute) {
    matchMinute.textContent = `${minute}'`;
  }

  if (eventMinute && !editingEventId) {
    eventMinute.value = minute;
  }
}

function startMatchClock() {
  if (matchClockTimer) {
    clearInterval(matchClockTimer);
    matchClockTimer = null;
  }

  updateMatchMinuteDisplay();

  if (currentMatch?.status !== "Live") return;

  matchClockTimer = setInterval(() => {
    updateMatchMinuteDisplay();
  }, 30000);
}

function updateStatusVisual(status) {
  if (!matchStatus) return;

  matchStatus.textContent = status || "Not Started";

  const statusCard = matchStatus.closest(".stat-card");

  if (statusCard) {
    statusCard.classList.remove("stat-ready", "stat-monitor", "stat-warning", "stat-danger");

    if (status === "Live") {
      statusCard.classList.add("stat-ready");
    } else if (status === "Half Time") {
      statusCard.classList.add("stat-warning");
    } else if (status === "Full Time") {
      statusCard.classList.add("stat-monitor");
    } else {
      statusCard.classList.add("stat-monitor");
    }
  }
}

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

  if (!matchSnap.exists()) {
    matchCentreTitle.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 teamSnap = await getDoc(doc(db, "teams", currentMatch.teamId));

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

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

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

  homeTeamName.textContent = currentTeam?.name || "Team";
  awayTeamName.textContent = currentMatch.opponent || "Opponent";

  updateStatusVisual(currentMatch.status || "Not Started");

  matchHalf.textContent = currentMatch.half || "1st";

  if (matchHalfSelect) {
    matchHalfSelect.value = currentMatch.half || "1st";
  }

  return true;
}

async function loadMatchData() {
  const playersQuery = query(
    collection(db, "players"),
    where("organisationId", "==", activeProfile.organisationId)
  );

  const eventsQuery = query(
    collection(db, "matchEvents"),
    where("matchId", "==", matchId),
    where("organisationId", "==", activeProfile.organisationId)
  );

  const selectionsQuery = query(
    collection(db, "matchSelections"),
    where("matchId", "==", matchId),
    where("organisationId", "==", activeProfile.organisationId)
  );

  const [playersSnapshot, eventsSnapshot, selectionsSnapshot] = await Promise.all([
    getDocs(playersQuery),
    getDocs(eventsQuery),
    getDocs(selectionsQuery)
  ]);

  playersCache = playersSnapshot.docs
    .map((docSnap) => ({
      id: docSnap.id,
      ...docSnap.data()
    }))
    .filter((player) => {
      return getPlayerTeamIds(player).includes(currentMatch.teamId);
    })
    .sort((a, b) => {
      return getPlayerName(a).toLowerCase().localeCompare(getPlayerName(b).toLowerCase());
    });

  eventsCache = eventsSnapshot.docs.map((docSnap) => ({
    id: docSnap.id,
    ...docSnap.data()
  }));

  const selections = selectionsSnapshot.docs.map((docSnap) => ({
    id: docSnap.id,
    ...docSnap.data()
  }));

  selections.sort((a, b) => {
    const dateA = a.updatedAt?.toDate ? a.updatedAt.toDate() : new Date(0);
    const dateB = b.updatedAt?.toDate ? b.updatedAt.toDate() : new Date(0);

    return dateB - dateA;
  });

  matchSelectionCache = selections[0] || null;

  sortEvents();
}

function renderPlayerDropdown() {
  if (!eventPlayer) return;

  eventPlayer.innerHTML = `<option value="">Select player</option>`;

  if (matchSelectionCache) {
    const startingSquad = matchSelectionCache.startingSquad || [];
    const benchSquad = matchSelectionCache.benchSquad || [];

    if (startingSquad.length) {
      const group = document.createElement("optgroup");
      group.label = "Starting XV";

      startingSquad.forEach((player) => {
        const option = document.createElement("option");
        option.value = player.playerId;
        option.textContent = `${player.name || "Unknown Player"} — ${player.selectedRole || player.position || "No role"}`;
        group.appendChild(option);
      });

      eventPlayer.appendChild(group);
    }

    if (benchSquad.length) {
      const group = document.createElement("optgroup");
      group.label = "Bench";

      benchSquad.forEach((player) => {
        const option = document.createElement("option");
        option.value = player.playerId;
        option.textContent = `${player.name || "Unknown Player"} — ${player.selectedRole || player.position || "No role"}`;
        group.appendChild(option);
      });

      eventPlayer.appendChild(group);
    }

    if (startingSquad.length || benchSquad.length) {
      return;
    }
  }

  playersCache.forEach((player) => {
    const option = document.createElement("option");
    option.value = player.id;
    option.textContent = getPlayerName(player);
    eventPlayer.appendChild(option);
  });
}

async function saveCurrentScoreToMatch() {
  if (!currentMatch) return;

  const home = Number(currentMatch.homeScore || 0);
  const away = Number(currentMatch.awayScore || 0);

  let result = "pending";

  if (currentMatch.status === "Full Time") {
    if (home > away) result = "win";
    if (home < away) result = "loss";
    if (home === away) result = "draw";
  }

  await updateDoc(doc(db, "matches", matchId), {
    homeScore: home,
    awayScore: away,
    result,
    updatedAt: serverTimestamp()
  });

  currentMatch.result = result;
  currentMatch.homeScore = home;
  currentMatch.awayScore = away;
}

function renderScore() {
  let home = 0;
  let away = 0;

  eventsCache.forEach((event) => {
    const points = getEventPoints(event);

    if (event.team === "home") home += points;
    if (event.team === "away") away += points;
  });

  homeScore.textContent = home;
  awayScore.textContent = away;

  currentMatch.homeScore = home;
  currentMatch.awayScore = away;
}

function getEventLabel(type) {
  return String(type || "")
    .replace("_", " ")
    .toUpperCase();
}

function renderTimeline() {
  if (!matchTimeline) return;

  matchTimeline.innerHTML = "";

  if (!eventsCache.length) {
    matchTimeline.innerHTML = `
      <div class="list-item">
        <strong>No match events yet.</strong>
        <p>Add the first event using the form above.</p>
      </div>
    `;
    return;
  }

  eventsCache.forEach((event) => {
    const item = document.createElement("div");
    item.className = "timeline-event elite-timeline-event";

    item.innerHTML = `
      <div class="timeline-minute">
        ${event.minute}'
      </div>

      <div class="timeline-content">
        <span class="activity-type">
          ${event.team === "home" ? currentTeam?.name || "Team" : currentMatch.opponent || "Opponent"}
        </span>

        <h3>
          ${getEventLabel(event.type)}
          ${
            event.type === "conversion"
              ? ` • ${event.conversionResult === "missed" ? "MISSED" : "SUCCESSFUL"}`
              : ""
          }
        </h3>

        <p>
          ${event.playerName || "No player selected"}
          ${event.notes ? " • " + event.notes : ""}
        </p>
      </div>

      <div class="record-actions">
        <button class="btn-secondary edit-event-btn" data-id="${event.id}">
          Edit
        </button>

        <button class="btn-danger delete-event-btn" data-id="${event.id}">
          Delete
        </button>
      </div>
    `;

    matchTimeline.appendChild(item);
  });
}

function renderMatchStatsSummary() {
  const homeEvents = eventsCache.filter((event) => event.team === "home");

  const tries = homeEvents.filter((event) => event.type === "try").length;

  const conversions = homeEvents.filter((event) => {
    return (
      event.type === "conversion" &&
      event.conversionResult === "successful"
    );
  }).length;

  const penalties = homeEvents.filter((event) => {
    return event.type === "penalty";
  }).length;

  const cards = homeEvents.filter((event) => {
    return event.type === "yellow_card" || event.type === "red_card";
  }).length;

  if (matchTries) matchTries.textContent = tries;
  if (matchConversions) matchConversions.textContent = conversions;
  if (matchPenalties) matchPenalties.textContent = penalties;
  if (matchCards) matchCards.textContent = cards;
}

function renderTeamStatsSummary() {
  const stats = currentMatch?.teamStats || {};

  const scrumsWon = Number(stats.scrumsWon || 0);
  const scrumsLost = Number(stats.scrumsLost || 0);

  const lineoutsWon = Number(stats.lineoutsWon || 0);
  const lineoutsLost = Number(stats.lineoutsLost || 0);

  const ruckFor = Number(stats.ruckTurnoversFor || 0);
  const ruckAgainst = Number(stats.ruckTurnoversAgainst || 0);

  const tacklesMade = Number(stats.tacklesMade || 0);
  const tacklesMissed = Number(stats.tacklesMissed || 0);

  if (scrumSuccessRate) scrumSuccessRate.textContent = getPercentage(scrumsWon, scrumsLost);
  if (scrumsWonDisplay) scrumsWonDisplay.textContent = scrumsWon;
  if (scrumsLostDisplay) scrumsLostDisplay.textContent = scrumsLost;

  if (lineoutSuccessRate) lineoutSuccessRate.textContent = getPercentage(lineoutsWon, lineoutsLost);
  if (lineoutsWonDisplay) lineoutsWonDisplay.textContent = lineoutsWon;
  if (lineoutsLostDisplay) lineoutsLostDisplay.textContent = lineoutsLost;

  if (ruckTurnoverBalance) ruckTurnoverBalance.textContent = ruckFor - ruckAgainst;
  if (ruckTurnoversForDisplay) ruckTurnoversForDisplay.textContent = ruckFor;
  if (ruckTurnoversAgainstDisplay) ruckTurnoversAgainstDisplay.textContent = ruckAgainst;

  if (tackleCompletionRate) tackleCompletionRate.textContent = getPercentage(tacklesMade, tacklesMissed);
  if (tacklesMadeDisplay) tacklesMadeDisplay.textContent = tacklesMade;
  if (tacklesMissedDisplay) tacklesMissedDisplay.textContent = tacklesMissed;
}

function renderMatchCentre() {
  renderPlayerDropdown();
  renderScore();
  renderMatchStatsSummary();
  setTeamStatsForm(currentMatch?.teamStats || {});
  renderTeamStatsSummary();
  renderTimeline();
  updateMatchMinuteDisplay();
  startMatchClock();
}

eventType?.addEventListener("change", updateConversionFieldVisibility);

teamMatchStatsForm?.addEventListener("submit", async function (event) {
  event.preventDefault();

  const submitStatsButton = teamMatchStatsForm.querySelector("button[type='submit']");
  const originalText = submitStatsButton?.textContent || "Save Team Stats";

  if (submitStatsButton) {
    submitStatsButton.disabled = true;
    submitStatsButton.textContent = "Saving...";
  }

  try {
    const teamStats = getTeamStatsFromForm();

    await updateDoc(doc(db, "matches", matchId), {
      teamStats,
      updatedAt: serverTimestamp()
    });

    currentMatch = {
      ...currentMatch,
      teamStats
    };

    renderTeamStatsSummary();

    showToast("Team match stats saved.", "success");
  } catch (error) {
    console.error("Error saving team match stats:", error);
    showToast("Could not save team match stats: " + error.message, "error");
  } finally {
    if (submitStatsButton) {
      submitStatsButton.disabled = false;
      submitStatsButton.textContent = originalText;
    }
  }
});

matchEventForm?.addEventListener("submit", async function (event) {
  event.preventDefault();

  const autoMinute = getCurrentMatchMinute();

  if (eventMinute) {
    eventMinute.value = autoMinute;
  }

  const selectedPlayer = playersCache.find((player) => player.id === eventPlayer?.value);

  const eventData = {
    matchId,
    team: eventTeam?.value || "home",
    type: eventType?.value || "try",
    conversionResult: eventType?.value === "conversion" ? conversionResult?.value || "successful" : "",
    minute: Number(eventMinute?.value || autoMinute || 0),
    playerId: eventPlayer?.value || "",
    playerName: selectedPlayer ? getPlayerName(selectedPlayer) : getSelectedPlayerName(),
    notes: eventNotes?.value.trim() || "",
    organisationId: activeProfile.organisationId,
    updatedAt: serverTimestamp()
  };

  setButtonLoading(true, editingEventId ? "Updating..." : "Saving...");

  try {
    if (editingEventId) {
      await updateDoc(doc(db, "matchEvents", editingEventId), eventData);

      eventsCache = eventsCache.map((item) =>
        item.id === editingEventId
          ? {
              ...item,
              ...eventData,
              updatedAt: new Date()
            }
          : item
      );

      showToast("Match event updated.", "success");
    } else {
      const eventRef = await addDoc(collection(db, "matchEvents"), {
        ...eventData,
        createdBy: activeProfile.uid,
        createdAt: serverTimestamp()
      });

      eventsCache.push({
        id: eventRef.id,
        ...eventData,
        createdBy: activeProfile.uid,
        createdAt: new Date()
      });

      showToast("Match event saved.", "success");
    }

    sortEvents();
    resetEventForm();
    renderScore();
    renderMatchStatsSummary();
    renderTimeline();

    await saveCurrentScoreToMatch();
  } catch (error) {
    console.error("Error saving match event:", error);
    showToast("Could not save match event: " + error.message, "error");
  } finally {
    setButtonLoading(false);
  }
});

matchTimeline?.addEventListener("click", async function (event) {
  const editBtn = event.target.closest(".edit-event-btn");
  const deleteBtn = event.target.closest(".delete-event-btn");

  if (editBtn) {
    const eventId = editBtn.dataset.id;
    const matchEvent = eventsCache.find((item) => item.id === eventId);

    if (!matchEvent) return;

    editingEventId = matchEvent.id;

    eventMinute.value = matchEvent.minute || "";
    eventTeam.value = matchEvent.team || "home";
    eventType.value = matchEvent.type || "try";
    conversionResult.value = matchEvent.conversionResult || "successful";

    updateConversionFieldVisibility();

    eventPlayer.value = matchEvent.playerId || "";
    eventNotes.value = matchEvent.notes || "";

    if (submitButton) {
      submitButton.textContent = "Update Event";
    }

    window.scrollTo({ top: 0, behavior: "smooth" });
  }

  if (deleteBtn) {
    const eventId = deleteBtn.dataset.id;

    const confirmed = confirm("Are you sure you want to delete this match event?");
    if (!confirmed) return;

    deleteBtn.disabled = true;
    deleteBtn.textContent = "Deleting...";

    try {
      await deleteDoc(doc(db, "matchEvents", eventId));

      eventsCache = eventsCache.filter((item) => item.id !== eventId);

      renderScore();
      renderMatchStatsSummary();
      renderTimeline();

      await saveCurrentScoreToMatch();

      showToast("Match event deleted.", "success");
    } catch (error) {
      console.error("Error deleting match event:", error);
      showToast("Could not delete match event: " + error.message, "error");
    } finally {
      deleteBtn.disabled = false;
      deleteBtn.textContent = "Delete";
    }
  }
});

function formatAnnouncementType(type) {
  const cleanType = String(type || "").toLowerCase();

  if (cleanType === "preparation") return "Match Preparation";
  if (cleanType === "arrival") return "Arrival Instructions";
  if (cleanType === "travel") return "Travel Instructions";

  return "Team Message";
}

async function createCoachAnnouncementNotification(announcementId, announcementData) {
  const notificationRef = doc(
    db,
    "notifications",
    `coach-announcement-${announcementId}`
  );

  await setDoc(notificationRef, {
    sourceId: announcementId,
    sourceCollection: "coachAnnouncements",
    type: "announcement",
    severity: "info",
    title: announcementData.title || formatAnnouncementType(announcementData.announcementType),
    message: announcementData.message || "",
    link: `player-match-detail.html?id=${matchId}`,
    teamId: currentMatch.teamId || "",
    teamName: currentTeam?.name || "",
    playerId: "",
    playerName: "",
    organisationId: activeProfile.organisationId,
    readBy: {},
    createdAt: serverTimestamp(),
    updatedAt: serverTimestamp()
  });
}

async function createMatchStatusNotification(status) {
  const notificationRef = doc(
    db,
    "notifications",
    `match-status-${matchId}`
  );

  await setDoc(notificationRef, {
    sourceId: matchId,
    sourceCollection: "matches",
    type: "match",
    severity: status === "Live" ? "monitor" : "info",
    title: `Match Status: ${status}`,
    message: `${currentTeam?.name || "Team"} vs ${currentMatch?.opponent || "Opponent"} is now ${status}.`,
    link: `player-match-detail.html?id=${matchId}`,
    teamId: currentMatch.teamId || "",
    teamName: currentTeam?.name || "",
    playerId: "",
    playerName: "",
    organisationId: activeProfile.organisationId,
    readBy: {},
    createdAt: serverTimestamp(),
    updatedAt: serverTimestamp()
  });
}

coachAnnouncementForm?.addEventListener("submit", async function (event) {
  event.preventDefault();

  const announcementType = coachAnnouncementType?.value || "team_message";
  const title = coachAnnouncementTitle?.value.trim() || "";
  const message = coachAnnouncementMessage?.value.trim() || "";

  if (!title || !message) {
    showToast("Please enter an announcement title and message.", "warning");
    return;
  }

  try {
    const announcementRef = await addDoc(collection(db, "coachAnnouncements"), {
      matchId,
      teamId: currentMatch.teamId || "",
      teamName: currentTeam?.name || "",
      opponent: currentMatch.opponent || "",
      matchDate: currentMatch.date || "",
      announcementType,
      announcementTypeLabel: formatAnnouncementType(announcementType),
      title,
      message,
      organisationId: activeProfile.organisationId,
      createdBy: activeProfile.uid,
      createdAt: serverTimestamp(),
      updatedAt: serverTimestamp()
    });

    await createCoachAnnouncementNotification(announcementRef.id, {
      announcementType,
      title,
      message
    });

    coachAnnouncementForm.reset();

    showToast("Coach announcement sent to players.", "success");
  } catch (error) {
    console.error("Coach announcement error:", error);
    showToast("Could not send announcement: " + error.message, "error");
  }
});

matchStatusButtons.forEach((button) => {
  button.addEventListener("click", async function () {
    const newStatus = button.dataset.status;

    button.disabled = true;

    try {
      const statusUpdate = {
        status: newStatus,
        updatedAt: serverTimestamp()
      };

      if (newStatus === "Not Started") {
        statusUpdate.half = "1st";
        statusUpdate.result = "pending";
        statusUpdate.homeScore = 0;
        statusUpdate.awayScore = 0;
        statusUpdate.firstHalfStartedAt = deleteField();
        statusUpdate.secondHalfStartedAt = deleteField();
      }

      if (newStatus === "Live") {
        if (currentMatch.status === "Half Time" || currentMatch.half === "2nd") {
          statusUpdate.half = "2nd";

          if (!currentMatch.secondHalfStartedAt) {
            statusUpdate.secondHalfStartedAt = new Date().toISOString();
          }
        } else {
          statusUpdate.half = "1st";

          if (!currentMatch.firstHalfStartedAt) {
            statusUpdate.firstHalfStartedAt = new Date().toISOString();
          }
        }
      }

      if (newStatus === "Half Time") {
        statusUpdate.half = "1st";
      }

      if (newStatus === "Full Time") {
        statusUpdate.half = "2nd";
      }

      await updateDoc(doc(db, "matches", matchId), statusUpdate);

      currentMatch = {
        ...currentMatch,
        ...statusUpdate
      };
    
      if (newStatus === "Not Started") {
        delete currentMatch.firstHalfStartedAt;
        delete currentMatch.secondHalfStartedAt;
      }

      updateStatusVisual(newStatus);

      if (matchHalf) {
        matchHalf.textContent = currentMatch.half || "1st";
      }

      if (matchHalfSelect) {
        matchHalfSelect.value = currentMatch.half || "1st";
      }

      updateMatchMinuteDisplay();
      startMatchClock();

      await saveCurrentScoreToMatch();
      await createMatchStatusNotification(newStatus);

      showToast(`Match status updated to ${newStatus}.`, "success");
    } catch (error) {
      console.error("Error updating match status:", error);
      showToast("Could not update match status: " + error.message, "error");
    } finally {
      button.disabled = false;
    }
  });
});

matchHalfSelect?.addEventListener("change", async function () {
  try {
    if (currentMatch.status === "Live") {
      showToast("Half changes are automated while the match is live.", "warning");

      matchHalfSelect.value = currentMatch.half || "1st";
      return;
    }

    const halfUpdate = {
      half: matchHalfSelect.value,
      updatedAt: serverTimestamp()
    };

    await updateDoc(doc(db, "matches", matchId), halfUpdate);

    currentMatch = {
      ...currentMatch,
      ...halfUpdate
    };

    matchHalf.textContent = matchHalfSelect.value;
    updateMatchMinuteDisplay();
    startMatchClock();
  } catch (error) {
    console.error("Error updating half:", error);
    showToast("Could not update match half: " + error.message, "error");
  }
});

function exportTimelineCSV() {
  let csvContent = "Minute,Team,Event Type,Conversion Result,Points,Player,Notes\n";

  eventsCache.forEach((event) => {
    const row = [
      `"${event.minute || ""}"`,
      `"${event.team === "home" ? currentTeam?.name || "Team" : currentMatch.opponent || "Opponent"}"`,
      `"${event.type || ""}"`,
      `"${event.conversionResult || ""}"`,
      `"${getEventPoints(event)}"`,
      `"${event.playerName || ""}"`,
      `"${String(event.notes || "").replace(/"/g, '""')}"`
    ];

    csvContent += row.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-timeline-${currentMatch?.date || "report"}.csv`);
  link.style.visibility = "hidden";

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

  URL.revokeObjectURL(url);
}

exportTimelineCsvBtn?.addEventListener("click", exportTimelineCSV);

saveFinalScoreBtn?.addEventListener("click", async function () {
  saveFinalScoreBtn.disabled = true;
  saveFinalScoreBtn.textContent = "Saving...";

  try {
    await saveCurrentScoreToMatch();
    showToast("Final score saved successfully.", "success");
  } catch (error) {
    console.error("Error saving final score:", error);
    showToast("Could not save final score: " + error.message, "error");
  } finally {
    saveFinalScoreBtn.disabled = false;
    saveFinalScoreBtn.textContent = "Save Final Score";
  }
});

window.addEventListener("beforeunload", function () {
  if (matchClockTimer) {
    clearInterval(matchClockTimer);
  }
});

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

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

  if (matchTimeline) {
    matchTimeline.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 centre...");

  try {
    const loaded = await loadMatch();

    if (!loaded || !currentMatch) return;

    await loadMatchData();
    renderMatchCentre();
  } catch (error) {
    console.error("Match centre error:", error);

    matchCentreTitle.textContent = "Could not load match centre";

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

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