// =========================================================
// FILE: player-match-detail.js | TYPE: Player Match Centre
// =========================================================

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
} 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 matchSubtext = document.getElementById("matchSubtext");

const heroOpponent = document.getElementById("heroOpponent");
const heroMatchDate = document.getElementById("heroMatchDate");
const heroKickoffTime = document.getElementById("heroKickoffTime");
const heroVenue = document.getElementById("heroVenue");

const matchOpponent = document.getElementById("matchOpponent");
const matchDate = document.getElementById("matchDate");
const matchKickoffTime = document.getElementById("matchKickoffTime");
const matchVenue = document.getElementById("matchVenue");
const matchType = document.getElementById("matchType");

const matchCountdown = document.getElementById("matchCountdown");
const matchDetails = document.getElementById("matchDetails");
const matchNotes = document.getElementById("matchNotes");

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

function calculateCountdown(dateValue) {
  if (!dateValue) return "-";

  const today = new Date();
  today.setHours(0, 0, 0, 0);

  const matchDate = new Date(dateValue);
  matchDate.setHours(0, 0, 0, 0);

  const diffTime = matchDate - today;
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

  if (diffDays < 0) return "Played";
  if (diffDays === 0) return "Today";
  if (diffDays === 1) return "Tomorrow";

  return `${diffDays} Days`;
}

function renderMatch(match) {
  const title = `${match.teamName || "My Team"} vs ${match.opponent || "Opponent"}`;

  setText(matchTitle, title);

  setText(
    matchSubtext,
    `${match.date || "No date"}${match.venue ? " • " + match.venue : ""}`
  );

  const kickoffTime = match.time || match.kickoffTime || "No kickoff time";

  setText(heroOpponent, match.opponent || "Opponent");
  setText(heroMatchDate, match.date || "No date");
  setText(heroKickoffTime, match.time || match.kickoffTime || "No kickoff time");
  setText(heroVenue, match.venue || "No venue");

  setText(matchOpponent, match.opponent || "Opponent");
  setText(matchDate, match.date || "No date");
  setText(matchKickoffTime, match.time || match.kickoffTime || "No kickoff time");
  setText(matchVenue, match.venue || "No venue");
  setText(matchType, match.type || "Fixture");

  setText(matchCountdown, calculateCountdown(match.date));

  if (matchDetails) {
    matchDetails.innerHTML = `
      <div class="match-detail-item">
        <strong>Team</strong>
        <p>${match.teamName || "No team listed"}</p>
      </div>

      <div class="match-detail-item">
        <strong>Opponent</strong>
        <p>${match.opponent || "No opponent listed"}</p>
      </div>

      <div class="match-detail-item">
        <strong>Date</strong>
        <p>${match.date || "No date listed"}</p>
      </div>

      <div class="match-detail-item">
        <strong>Kickoff Time</strong>
        <p>${match.time || match.kickoffTime || "No kickoff time listed"}</p>
      </div>

      <div class="match-detail-item">
        <strong>Venue</strong>
        <p>${match.venue || "No venue listed"}</p>
      </div>

      <div class="match-detail-item">
        <strong>Match Type</strong>
        <p>${match.type || "No match type listed"}</p>
      </div>
    `;
  }

  if (matchNotes) {
    matchNotes.innerHTML = `
      <div class="list-item">
        <strong>Coach Notes</strong>
        <p>${match.notes || match.coachNotes || "No coach notes added yet."}</p>
      </div>
    `;
  }
}

async function loadMatch() {
  if (!matchId) {
    throw new Error("No match ID found in the page URL.");
  }

  const matchRef = doc(db, "matches", matchId);
  const matchSnap = await getDoc(matchRef);

  if (!matchSnap.exists()) {
    throw new Error("Match fixture not found.");
  }

  return {
    id: matchSnap.id,
    ...matchSnap.data()
  };
}

requireAuth(async function () {
  setupLogoutButton();

  showLoader("Loading fixture...");

  try {
    const match = await loadMatch();
    renderMatch(match);
  } catch (error) {
    console.error("Player match detail error:", error);
    showToast("Could not load fixture: " + error.message, "error");

    setText(matchTitle, "Fixture Not Found");

    if (matchDetails) {
      matchDetails.innerHTML = `
        <div class="match-detail-item">
          <strong>Error loading fixture.</strong>
          <p>${error.message}</p>
        </div>
      `;
    }
  } finally {
    hideLoader();
  }
});