import { createClient } from "https://esm.sh/@anam-ai/js-sdk@latest";
import { AnamEvent } from "https://esm.sh/@anam-ai/js-sdk@latest/dist/module/types";

let anamClient = null;

// DOM elements
const startButton = document.getElementById("start-button");
const stopButton = document.getElementById("stop-button");
const personaImage = document.getElementById("persona-image");
const idleVideo = document.getElementById("idle-video");
const videoElement = document.getElementById("persona-video");

function matchWebcamVideoHeight() {
    // Get Jim's video element (use the visible one)
    const jimVideo = document.querySelector('#persona-image'); // or '#idle-video'
    const webcamVideo = document.querySelector('#webcam-video');

    // Get the computed height of Jim's video
    const jimVideoHeight = jimVideo.offsetHeight;

    // Set the webcam video container to match
    webcamVideo.style.height = jimVideoHeight + 'px';
    webcamVideo.style.objectFit = 'cover';
}

// Run on page load
window.addEventListener('load', matchWebcamVideoHeight);
// Also run on window resize
window.addEventListener('resize', matchWebcamVideoHeight);


function showLoadingState() {
  personaImage.style.opacity = 0;
  idleVideo.style.display = "block";
  idleVideo.style.opacity = 1;
  videoElement.style.opacity = 0;
  videoElement.style.display = "block"; // make sure it's visible for streaming
  stopButton.style.display = "block";
  startButton.style.display = "none";
}

function hideLoadingState() {
  idleVideo.style.opacity = 0;       // fade out idle video
  videoElement.style.opacity = 1;    // fade in live video
}

// After idle video fades out, hide it to save resources
idleVideo.addEventListener("transitionend", () => {
  if (idleVideo.style.opacity == 0) {
    idleVideo.style.display = "none";
  }
});

async function startChat() {
  try {
    startButton.disabled = true;
    showLoadingState();

    // Get session token from server
    const response = await fetch("/api/session-token", { method: "POST" });
    const { sessionToken } = await response.json();

    // Create Anam client
    anamClient = createClient(sessionToken);

    // Listen for SESSION_READY event
    anamClient.addListener(AnamEvent.SESSION_READY, () => {
      console.log("Session is ready!");
      hideLoadingState();
      startButton.disabled = true;
      stopButton.disabled = false;
    });

    // Important: clear previous srcObject to ensure video plays again
    videoElement.srcObject = null;

    // Start streaming to live video
    await anamClient.streamToVideoElement("persona-video");
    console.log("Chat started successfully!");
  } catch (error) {
    console.error("Failed to start chat:", error);
    resetUI();
  }
}

function resetUI() {
  // Reset all elements to initial state
  personaImage.style.display = "block";
  personaImage.style.opacity = 1;

  idleVideo.style.display = "none";
  idleVideo.style.opacity = 0;

  videoElement.style.display = "none";
  videoElement.style.opacity = 0;
  videoElement.srcObject = null;

  stopButton.style.display = "none";
  startButton.style.display = "block";
  startButton.disabled = false;
  stopButton.disabled = true;
}

function stopChat() {
  if (anamClient) {
    anamClient.stopStreaming();
    anamClient = null;
  }
  resetUI();
}

startButton.addEventListener("click", startChat);
stopButton.addEventListener("click", stopChat);


// const profileBtn = document.getElementById("profile-avatar");
// const profileModal = document.getElementById("profile-modal");
// const closeProfileModal = document.getElementById("close-profile-modal");

// profileBtn.onclick = () => {
//     profileModal.style.display = "flex";
// };

// closeProfileModal.onclick = () => {
//     profileModal.style.display = "none";
// };

// // Close modal if click outside box
// profileModal.onclick = (e) => {
//     if (e.target === profileModal) profileModal.style.display = "none";
// };

// PROFILE MODAL
const profileBtn = document.getElementById('profile-avatar');
const profileModal = document.getElementById('profile-modal');
const closeProfileModal = document.getElementById('close-profile-modal');

profileBtn.onclick = () => {
    profileModal.style.display = "flex";
};

closeProfileModal.onclick = () => {
    profileModal.style.display = "none";
};

// Close profile modal if click outside box
profileModal.onclick = (e) => {
    if (e.target === profileModal) profileModal.style.display = "none";
};

// MEDICAL RECORDS MODAL
const medicalBtn = document.getElementById('medical-record-avatar');
const medicalModal = document.getElementById('medical-modal');
const closeMedicalModal = document.getElementById('close-medical-modal');

medicalBtn.onclick = () => {
    medicalModal.style.display = "flex";
};

closeMedicalModal.onclick = () => {
    medicalModal.style.display = "none";
};

// Close medical modal if click outside box
medicalModal.onclick = (e) => {
    if (e.target === medicalModal) medicalModal.style.display = "none";
};

const webcamVideo = document.getElementById('webcam-video');

navigator.mediaDevices.getUserMedia({ video: true, audio: false })
  .then(stream => {
    webcamVideo.srcObject = stream;
  })
  .catch(err => {
    console.error("Error accessing webcam: ", err);
    alert("Unable to access webcam. Please check permissions.");
  });
