// therapist.js
// Unified chat logic: UI, Firestore persistence, Clear Chat, Speech-to-Text, TTS, and API call.

import {
  auth, db,
  collection, addDoc, getDocs, query, orderBy, onAuthStateChanged,
  doc, setDoc
} from './firebase-config.js';

// --- Config ---
const API_URL = "https://virtualtherapist-grih4wv77a-uc.a.run.app";

// Try to get deleteDoc dynamically (in case firebase-config doesn’t export it)
let deleteDocFn = null;
try {
  const mod = await import("https://www.gstatic.com/firebasejs/10.12.2/firebase-firestore.js");
  deleteDocFn = mod.deleteDoc || null;
} catch (_) { /* no-op */ }

// ------- DOM -------
const chatForm = document.getElementById("chat-form");
const userInput = document.getElementById("user-input");
const chatHistory = document.getElementById("chat-history");
const typingIndicator = document.getElementById("typing-indicator");
const clearBtn = document.getElementById("clear-chat");
const voiceBtn = document.getElementById("voice-btn");
const emojiBtn = document.getElementById("emoji-btn");
const languageSelect = document.getElementById("language-select");

// ------- Helpers -------
function formatTime(ts) {
  const d = ts instanceof Date ? ts : (ts?.toDate?.() || new Date());
  return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}

function appendMessage(sender, text, ts = new Date(), isTherapist = false, speak = false) {
  const wrapper = document.createElement("div");
  wrapper.className = `msg ${isTherapist ? "therapist" : "user"}`;

  const avatar = document.createElement("div");
  avatar.className = "avatar";
  avatar.textContent = isTherapist ? "🧠" : "🧑";

  const bubble = document.createElement("div");
  bubble.className = "bubble";

  // Add speaker icon for therapist messages (TTS)
  if (isTherapist && speak) {
    const speakBtn = document.createElement("button");
    speakBtn.type = "button";
    speakBtn.className = "speaker";
    speakBtn.title = "Listen";
    speakBtn.textContent = "🔊";
    speakBtn.addEventListener("click", () => {
      const utterance = new SpeechSynthesisUtterance(text);
      speechSynthesis.speak(utterance);
    });
    bubble.appendChild(speakBtn);
  }

  const textNode = document.createElement("span");
  textNode.textContent = text;
  bubble.appendChild(textNode);

  const timestamp = document.createElement("div");
  timestamp.className = "timestamp";
  timestamp.textContent = formatTime(ts);

  const textWrapper = document.createElement("div");
  textWrapper.className = "text-wrapper";
  textWrapper.appendChild(bubble);
  textWrapper.appendChild(timestamp);

  wrapper.appendChild(avatar);
  wrapper.appendChild(textWrapper);

  wrapper.style.opacity = "0";
  chatHistory.appendChild(wrapper);
  chatHistory.scrollTop = chatHistory.scrollHeight;
  requestAnimationFrame(() => {
    wrapper.style.transition = "opacity 180ms ease";
    wrapper.style.opacity = "1";
  });
}

async function saveMessage(userId, sender, message, ts = new Date()) {
  if (!userId) return; // not signed in; skip persistence
  const ref = collection(db, "chats", userId, "messages");
  await addDoc(ref, { sender, message, timestamp: ts });
}

async function loadChatHistory(userId) {
  chatHistory.innerHTML = "";
  if (!userId) return;
  const ref = collection(db, "chats", userId, "messages");
  const q = query(ref, orderBy("timestamp"));
  const snapshot = await getDocs(q);
  snapshot.forEach(docSnap => {
    const data = docSnap.data();
    appendMessage(
      data.sender === "therapist" ? "Therapist" : "You",
      data.message,
      data.timestamp,
      data.sender === "therapist",
      data.sender === "therapist" // speak therapist msgs on demand
    );
  });
  chatHistory.scrollTop = chatHistory.scrollHeight;
}

// ------- Emoji -------
if (emojiBtn) {
  emojiBtn.addEventListener("click", () => {
    const emoji = prompt("Enter emoji (e.g. 😀 or ❤️):");
    if (emoji) {
      userInput.value = (userInput.value || "") + emoji;
      userInput.focus();
    }
  });
}

// ------- Clear Chat -------
if (clearBtn) {
  clearBtn.addEventListener("click", async () => {
    const ok = confirm("Clear the entire conversation?");
    if (!ok) return;

    // Clear UI immediately
    chatHistory.innerHTML = "";

    // Delete from Firestore if possible
    const user = auth.currentUser;
    if (user) {
      try {
        const msgsCol = collection(db, "chats", user.uid, "messages");
        const snap = await getDocs(msgsCol);
        if (deleteDocFn) {
          const tasks = [];
          snap.forEach(d => tasks.push(deleteDocFn(doc(db, "chats", user.uid, "messages", d.id))));
          await Promise.all(tasks);
        } else {
          // Fallback: mark the thread as cleared
          await setDoc(doc(db, "chats", user.uid, "_meta"), { clearedAt: new Date() }, { merge: true });
        }
      } catch (err) {
        console.error("Failed to clear remote chat:", err);
      }
    }
  });
}

// ------- Speech-to-Text (Mic) -------
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
let recognition = null;

function mapLang(val) {
  if (!val) return "en-US";
  const v = val.toLowerCase();
  if (v === "en") return "en-US";
  if (v === "fr") return "fr-FR";
  if (v === "es") return "es-ES";
  if (v === "de") return "de-DE";
  if (v === "zh") return "zh-CN";
  return "en-US";
}

function setupRecognition() {
  if (!SpeechRecognition) return null;
  const rec = new SpeechRecognition();
  rec.continuous = false;
  rec.interimResults = false;
  rec.lang = mapLang(languageSelect?.value);
  rec.onresult = (e) => {
    const transcript = Array.from(e.results).map(r => r[0].transcript).join(" ");
    userInput.value = (userInput.value ? userInput.value + " " : "") + transcript.trim();
    userInput.focus();
  };
  rec.onstart = () => { if (voiceBtn) { voiceBtn.disabled = true; voiceBtn.textContent = "🎤…"; } };
  rec.onend   = () => { if (voiceBtn) { voiceBtn.disabled = false; voiceBtn.textContent = "🎤"; } };
  rec.onerror = () => { if (voiceBtn) { voiceBtn.disabled = false; voiceBtn.textContent = "🎤"; } };
  return rec;
}

if (voiceBtn) {
  if (!SpeechRecognition) {
    voiceBtn.title = "Speech recognition not supported in this browser";
    voiceBtn.disabled = true;
  } else {
    voiceBtn.addEventListener("click", () => {
      try { recognition?.abort?.(); } catch {}
      recognition = setupRecognition();
      recognition?.start?.();
    });
  }
}

if (languageSelect && SpeechRecognition) {
  languageSelect.addEventListener("change", () => {
    try { recognition?.abort?.(); } catch {}
    recognition = null; // recreate next time with new language
  });
}

// ------- API call to your Cloud Function -------
async function getTherapistReply(userMessage, language) {
  const res = await fetch(API_URL, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ message: userMessage, language: language || "en" })
  });

  // If your function returns { reply: "..." }
  if (!res.ok) throw new Error(`API error: ${res.status}`);
  const data = await res.json();
  return data.reply || "Sorry, I couldn't understand that.";
}

// ------- Form submit -------
chatForm.addEventListener("submit", async (e) => {
  e.preventDefault();
  const message = userInput.value.trim();
  if (!message) return;

  appendMessage("You", message, new Date(), false);
  const user = auth.currentUser;
  await saveMessage(user?.uid, "user", message, new Date());

  userInput.value = "";
  typingIndicator.style.display = "block";

  try {
    const reply = await getTherapistReply(message, languageSelect?.value || "en");
    appendMessage("Therapist", reply, new Date(), true, true);
    await saveMessage(user?.uid, "therapist", reply, new Date());
  } catch (err) {
    console.error(err);
    appendMessage("Therapist", "Error connecting to therapist.", new Date(), true);
  } finally {
    typingIndicator.style.display = "none";
  }
});

// ------- Load history when signed in -------
onAuthStateChanged(auth, (user) => {
  if (user) {
    loadChatHistory(user.uid);
  } else {
    chatHistory.innerHTML = "";
  }
});
