// =========================================================
// FILE: legal-acceptance.js | TYPE: Legal Acceptance Logic
// =========================================================

import { auth, db } from "./firebase-config.js";
import { showLoader, hideLoader } from "./loader.js";
import { showToast } from "./toast.js";

import {
  onAuthStateChanged
} from "https://www.gstatic.com/firebasejs/10.12.2/firebase-auth.js";

import {
  doc,
  getDoc,
  updateDoc,
  serverTimestamp
} from "https://www.gstatic.com/firebasejs/10.12.2/firebase-firestore.js";

const legalAcceptanceForm = document.getElementById("legalAcceptanceForm");
const ndaAcceptedInput = document.getElementById("ndaAccepted");
const popiaAcceptedInput = document.getElementById("popiaAccepted");

const LEGAL_VERSION = "TryTrack-v1.0";

const ROLE_HOME = {
  director: "dashboard.html",
  coach: "dashboard.html",
  player: "player-dashboard.html",
  biokineticist: "bio-dashboard.html"
};

let activeUser = null;
let activeProfile = null;

function getRoleHome(role) {
  return ROLE_HOME[role] || "dashboard.html";
}

function hasAcceptedCurrentLegalVersion(profile) {
  const legal = profile?.legalAcceptance;

  return (
    legal?.requiredAccepted === true &&
    legal?.acceptedVersion === LEGAL_VERSION &&
    legal?.ndaVersion === LEGAL_VERSION &&
    legal?.popiaVersion === LEGAL_VERSION
  );
}

onAuthStateChanged(auth, async function (user) {
  if (!user) {
    window.location.href = "login.html";
    return;
  }

  activeUser = user;

  showLoader("Checking access...");

  try {
    const userRef = doc(db, "users", user.uid);
    const userSnap = await getDoc(userRef);

    if (!userSnap.exists()) {
      showToast("User profile not found.", "error");
      window.location.href = "login.html";
      return;
    }

    activeProfile = {
      uid: user.uid,
      email: user.email,
      ...userSnap.data()
    };

    if (hasAcceptedCurrentLegalVersion(activeProfile)) {
      window.location.href = getRoleHome(activeProfile.role);
      return;
    }
  } catch (error) {
    console.error("Legal acceptance load error:", error);
    showToast("Could not load acceptance page: " + error.message, "error");
  } finally {
    hideLoader();
  }
});

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

  if (!activeUser || !activeProfile) {
    showToast("User profile not loaded yet.", "warning");
    return;
  }

  if (!ndaAcceptedInput.checked || !popiaAcceptedInput.checked) {
    showToast("Please accept both required acknowledgements.", "warning");
    return;
  }

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

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

  showLoader("Saving acceptance...");

  try {
    const userRef = doc(db, "users", activeUser.uid);

    await updateDoc(userRef, {
      legalAcceptance: {
        requiredAccepted: true,
    
        ndaAccepted: true,
        ndaAcceptedAt: serverTimestamp(),
        ndaVersion: LEGAL_VERSION,
    
        popiaAccepted: true,
        popiaAcceptedAt: serverTimestamp(),
        popiaVersion: LEGAL_VERSION,
    
        acceptedAt: serverTimestamp(),
        acceptedVersion: LEGAL_VERSION,
    
        email: activeUser.email || activeProfile.email || "",
        fullName: activeProfile.fullName || activeProfile.name || "",
        uid: activeUser.uid,
    
        clubId: activeProfile.clubId || "",
        organisationId: activeProfile.organisationId || "",
    
        role: activeProfile.role || "",
    
        userAgent: navigator.userAgent || "",
        browserLanguage: navigator.language || "",
        platform: navigator.platform || "",
    
        acceptedIpAddress: ""
      },

      legalAccepted: true,
      legalAcceptedVersion: LEGAL_VERSION,
      legalAcceptedAt: serverTimestamp(),
    
      updatedAt: serverTimestamp()
    });

    showToast("Acceptance saved successfully.", "success");

    window.location.href = getRoleHome(activeProfile.role);
  } catch (error) {
    console.error("Legal acceptance save error:", error);
    showToast("Could not save acceptance: " + error.message, "error");
  } finally {
    if (submitButton) {
      submitButton.disabled = false;
      submitButton.textContent = "Accept and Continue";
    }

    hideLoader();
  }
});