// =========================================================
// FILE: profile.js | TYPE: User Profile + Qualifications 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,
  doc,
  getDoc,
  getDocs,
  query,
  where,
  updateDoc,
  serverTimestamp
} from "https://www.gstatic.com/firebasejs/10.12.2/firebase-firestore.js";

const profileName = document.getElementById("profileName");
const profileMeta = document.getElementById("profileMeta");

const profileRole = document.getElementById("profileRole");
const profileEmail = document.getElementById("profileEmail");
const profileStatus = document.getElementById("profileStatus");

const directorSection = document.getElementById("directorSection");
const directorPhone = document.getElementById("directorPhone");
const directorTitle = document.getElementById("directorTitle");
const directorOrganisation = document.getElementById("directorOrganisation");
const directorSubscription = document.getElementById("directorSubscription");
const directorTeams = document.getElementById("directorTeams");
const directorPlayers = document.getElementById("directorPlayers");
const directorLegal = document.getElementById("directorLegal");

const directorProfileForm = document.getElementById("directorProfileForm");
const directorPhoneInput = document.getElementById("directorPhoneInput");
const directorTitleInput = document.getElementById("directorTitleInput");

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

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

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

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

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

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

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

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

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

let activeUser = null;
let activeProfile = null;

let qualificationsCache = [];

function setText(element, value) {
  if (!element) return;

  element.textContent = value;
}

function formatRole(role) {
  if (role === "biokineticist") {
    return "Biokineticist";
  }

  return (
    String(role || "user")
      .charAt(0)
      .toUpperCase() +
    String(role || "user")
      .slice(1)
  );
}

async function loadDirectorOverview() {
  if (!activeProfile?.organisationId) return;

  const organisationRef = doc(db, "organisations", activeProfile.organisationId);
  const organisationSnap = await getDoc(organisationRef);

  let organisation = null;

  if (organisationSnap.exists()) {
    organisation = organisationSnap.data();
  }

  const teamsQuery = query(
    collection(db, "teams"),
    where("organisationId", "==", activeProfile.organisationId)
  );

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

  const [teamsSnapshot, playersSnapshot] = await Promise.all([
    getDocs(teamsQuery),
    getDocs(playersQuery)
  ]);

  const subscription = organisation?.subscription || {};
  const legal = activeProfile.legalAcceptance || {};

  setText(directorPhone, activeProfile.phone || "Not added");
  setText(directorTitle, activeProfile.title || "Not added");
  setText(directorOrganisation, organisation?.name || "Organisation not found");
  setText(directorSubscription, formatRole(subscription.plan || "trial"));
  setText(directorTeams, teamsSnapshot.size);
  setText(directorPlayers, playersSnapshot.size);
  setText(
    directorLegal,
    legal.requiredAccepted ? "Accepted" : "Not accepted"
  );

  if (directorPhoneInput) {
    directorPhoneInput.value = activeProfile.phone || "";
  }

  if (directorTitleInput) {
    directorTitleInput.value = activeProfile.title || "";
  }
}

function renderProfile() {
  setText(
    profileName,
    activeProfile.fullName ||
    activeProfile.email ||
    "TryTrack User"
  );

  setText(
    profileMeta,
    `${formatRole(activeProfile.role)} profile`
  );

  setText(
    profileRole,
    formatRole(activeProfile.role)
  );

  setText(
    profileEmail,
    activeProfile.email || "-"
  );

  setText(
    profileStatus,
    activeProfile.status || "active"
  );

  const canUseQualifications =
    ["coach", "biokineticist"]
      .includes(activeProfile.role);

  const isDirector =
    activeProfile.role === "director";

  if (qualificationSection) {
    qualificationSection.classList.toggle(
      "hidden",
      !canUseQualifications
    );
  }

  if (directorSection) {
    directorSection.classList.toggle(
      "hidden",
      !isDirector
    );
  }
}

function renderQualifications() {
  if (!qualificationList) return;

  qualificationList.innerHTML = "";

  if (!qualificationsCache.length) {

    qualificationList.innerHTML = `
      <div class="app-card">
        No qualifications added yet.
      </div>
    `;

    return;
  }

  qualificationsCache.forEach((qualification, index) => {

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

    item.className = "app-card";

    item.innerHTML = `
      <strong>
        ${qualification.title || "Untitled Qualification"}
      </strong>

      <small>
        ${qualification.institution || "No institution"}

        ${
          qualification.year
            ? " • " + qualification.year
            : ""
        }

        ${
          qualification.expiryDate
            ? " • Expires: " + qualification.expiryDate
            : ""
        }
      </small>

      <p>
        ${qualification.category || "other"}

        ${
          qualification.registrationNumber
            ? " • Reg/Cert: " + qualification.registrationNumber
            : ""
        }
      </p>

      <div class="record-actions">

        <button
          class="btn-danger delete-qualification-btn"
          data-index="${index}"
          type="button"
        >
          Delete
        </button>

      </div>
    `;

    qualificationList.appendChild(item);
  });
}

async function saveQualifications() {

  await updateDoc(
    doc(db, "users", activeUser.uid),
    {
      qualifications: qualificationsCache,
      updatedAt: serverTimestamp()
    }
  );
}

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

  if (!activeUser) return;

  const phone = directorPhoneInput?.value.trim() || "";
  const title = directorTitleInput?.value.trim() || "";

  try {
    await updateDoc(doc(db, "users", activeUser.uid), {
      phone,
      title,
      updatedAt: serverTimestamp()
    });

    activeProfile.phone = phone;
    activeProfile.title = title;

    renderProfile();
    await loadDirectorOverview();

    showToast("Director profile updated successfully.", "success");
  } catch (error) {
    console.error("Director profile update error:", error);
    showToast("Could not update profile: " + error.message, "error");
  }
});

qualificationForm?.addEventListener(
  "submit",
  async function (event) {

    event.preventDefault();

    const title =
      qualificationTitle.value.trim();

    const institution =
      qualificationInstitution.value.trim();

    if (!title || !institution) {

      showToast(
        "Please enter the qualification title and institution.",
        "warning"
      );

      return;
    }

    const qualification = {
      title,
      institution,

      year: qualificationYear.value
        ? Number(qualificationYear.value)
        : "",

      registrationNumber:
        qualificationRegistration.value.trim(),

      expiryDate:
        qualificationExpiry.value || "",

      category:
        qualificationCategory.value || "other",

      createdAt:
        new Date().toISOString()
    };

    try {

      qualificationsCache.push(qualification);

      await saveQualifications();

      qualificationForm.reset();

      renderQualifications();

      showToast(
        "Qualification added successfully.",
        "success"
      );

    } catch (error) {

      console.error(
        "Qualification save error:",
        error
      );

      showToast(
        "Could not save qualification: " +
        error.message,
        "error"
      );
    }
  }
);

qualificationList?.addEventListener(
  "click",
  async function (event) {

    const deleteBtn =
      event.target.closest(
        ".delete-qualification-btn"
      );

    if (!deleteBtn) return;

    const index =
      Number(deleteBtn.dataset.index);

    if (Number.isNaN(index)) return;

    const confirmed = confirm(
      "Are you sure you want to delete this qualification?"
    );

    if (!confirmed) return;

    try {

      qualificationsCache.splice(index, 1);

      await saveQualifications();

      renderQualifications();

      showToast(
        "Qualification deleted.",
        "success"
      );

    } catch (error) {

      console.error(
        "Qualification delete error:",
        error
      );

      showToast(
        "Could not delete qualification: " +
        error.message,
        "error"
      );
    }
  }
);

requireAuth(
  async function (user, profile) {

    activeUser = user;
    activeProfile = profile;

    qualificationsCache =
      Array.isArray(profile.qualifications)
        ? profile.qualifications
        : [];

    setupLogoutButton();

    showLoader("Loading profile...");

    try {

      renderProfile();

      if (activeProfile.role === "director") {
        await loadDirectorOverview();
      }

      renderQualifications();

    } catch (error) {

      console.error(
        "Profile load error:",
        error
      );

      showToast(
        "Could not load profile: " +
        error.message,
        "error"
      );

    } finally {

      hideLoader();
    }
  }
);