import { db, auth, collection, addDoc, getDocs, query, where, orderBy, limit, doc, getDoc, setDoc, increment, arrayUnion, signInWithEmailAndPassword, createUserWithEmailAndPassword, onAuthStateChanged, signOut } from './firebase-config.js';

// Retry function for handling API rate limits
const retryWithBackoff = async (fn, retries = 3, delay = 1000) => {
  for (let i = 0; i < retries; i++) {
    try {
      return await fn();
    } catch (error) {
      if (error.message.includes("429") && i < retries - 1) {
        await new Promise(resolve => setTimeout(resolve, delay * Math.pow(2, i)));
        continue;
      }
      throw error;
    }
  }
};

// 🔐 Login
window.login = function () {
  const email = document.getElementById("email")?.value?.trim();
  const password = document.getElementById("password")?.value?.trim();
  if (!email || !password) {
    alert("Please enter both email and password.");
    return;
  }
  signInWithEmailAndPassword(auth, email, password)
    .then(userCredential => {
      console.log("Logged in:", userCredential.user);
    })
    .catch(error => {
      console.error("Login error:", error.message);
      alert("Login failed: " + error.message);
    });
};

// 🆕 Register
function register() {
  const email = document.getElementById("email").value.trim();
  const password = document.getElementById("password").value.trim();
  const username = document.getElementById("username")?.value.trim();
  const isHuman = document.getElementById("human-check")?.checked;

  if (!email || !password || !username || password.length < 6) {
    alert("Please fill all fields. Password must be at least 6 characters.");
    return;
  }

  if (!isHuman) {
    alert("Please confirm you're not a robot.");
    return;
  }

  // Check for referral code in URL
  const params = new URLSearchParams(window.location.search);
  const referredBy = params.get("ref") || null;

  createUserWithEmailAndPassword(auth, email, password)
    .then(async (userCredential) => {
      const user = userCredential.user;
      const userData = {
        email,
        username,
        referredBy,
        createdAt: new Date().toISOString()
      };

      // Save to Firestore under "users" collection
      await setDoc(doc(db, "users", user.uid), userData);

      alert("Registration successful! You can now log in.");
    })
    .catch((error) => {
      console.error("Registration error:", error.message);
      alert("Registration failed: " + error.message);
    });
}


// 🚪 Logout
window.logout = function () {
  signOut(auth)
    .then(() => {
      console.log("User signed out.");
    })
    .catch(error => {
      console.error("Logout error:", error.message);
      alert("Logout failed: " + error.message);
    });
};

// CBT Thought Record (cbt-exercises.html)
window.saveThoughtRecord = async function() {
  if (!auth.currentUser) return alert("Please log in to save a thought record.");
  const situation = document.getElementById("situation")?.value?.trim();
  const emotion = document.getElementById("emotion")?.value?.trim();
  const thought = document.getElementById("thought")?.value?.trim();
  const evidenceFor = document.getElementById("evidence-for")?.value?.trim();
  const evidenceAgainst = document.getElementById("evidence-against")?.value?.trim();
  const reframe = document.getElementById("reframe")?.value?.trim();
  if (!situation || !emotion || !thought) {
    alert("Please fill in at least the situation, emotion, and thought fields.");
    return;
  }
  try {
    await addDoc(collection(db, "cbt"), {
      userId: auth.currentUser.uid,
      situation: situation,
      emotion: emotion,
      thought: thought,
      evidenceFor: evidenceFor,
      evidenceAgainst: evidenceAgainst,
      reframe: reframe,
      timestamp: new Date()
    });
    document.getElementById("save-status").textContent = "Thought record saved!";
    document.getElementById("situation").value = "";
    document.getElementById("emotion").value = "";
    document.getElementById("thought").value = "";
    document.getElementById("evidence-for").value = "";
    document.getElementById("evidence-against").value = "";
    document.getElementById("reframe").value = "";
    window.loadRecentThoughts();
  } catch (error) {
    console.error("Error saving thought record:", error.message);
    alert("Error saving thought record: " + error.message);
  }
};

window.loadRecentThoughts = async function() {
  if (!auth.currentUser) return;
  const q = query(
    collection(db, "cbt"),
    where("userId", "==", auth.currentUser.uid),
    orderBy("timestamp", "desc"),
    limit(5)
  );
  const querySnapshot = await getDocs(q);
  const recentThoughtsList = document.getElementById("recent-thoughts");
  if (recentThoughtsList) {
    recentThoughtsList.innerHTML = "";
    querySnapshot.forEach(doc => {
      const data = doc.data();
      const date = data.timestamp?.toDate ? data.timestamp.toDate().toLocaleString() : "N/A";
      const li = document.createElement("li");
      li.innerHTML = `<span class="prompt">Situation on ${date}:</span><br>${data.situation.substring(0, 100)}${data.situation.length > 100 ? "..." : ""}<br><strong>Emotion:</strong> ${data.emotion}`;
      recentThoughtsList.appendChild(li);
    });
  }
};

window.suggestReframe = async function () {
  if (!auth.currentUser) return alert("Please log in to use this feature.");
  const thought = document.getElementById("thought")?.value?.trim();
  const reframeInput = document.getElementById("reframe");
  const saveStatus = document.getElementById("save-status");
  const loading = document.getElementById("api-loading") || document.createElement("p");
  loading.id = "api-loading";
  loading.className = "loading";
  loading.textContent = "Generating reframe...";
  document.getElementById("thought")?.after(loading);

  if (!thought) {
    alert("Please enter your automatic thought first.");
    loading.remove();
    return;
  }

  const apiKey = "bb260ba35amsh481340f9e9b7d3cp172d93jsn463ac4a81999"; // Your RapidAPI key
  const url = 'https://twinword-text-analysis-bundle.p.rapidapi.com/association/';

  try {
    const response = await retryWithBackoff(() =>
      fetch(url, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-RapidAPI-Key": apiKey,
          "X-RapidAPI-Host": "twinword-text-analysis-bundle.p.rapidapi.com"
        },
        body: JSON.stringify({ text: thought })
      })
    );

    if (!response.ok) {
      throw new Error(`API request failed with status ${response.status}`);
    }

    const data = await response.json();
    if (data.result_code !== "200") {
      throw new Error(data.result_msg || "Invalid API response");
    }

    const positiveWords = data.associations?.filter(word => word.score > 0).slice(0, 3).map(w => w.word) || [];
    const suggestion = positiveWords.length
      ? `Consider this perspective: "I can focus on ${positiveWords.join(", ")} to find a more positive outlook."`
      : "Try viewing this situation from a more balanced perspective.";

    reframeInput.value = suggestion;
    saveStatus.textContent = "Reframe suggested!";
  } catch (error) {
    console.error("Reframe error:", error.message);
    reframeInput.value = error.message.includes("429")
      ? "API rate limit reached. Please try again later."
      : "Unable to generate reframe. Please try again.";
    saveStatus.textContent = "Error generating reframe.";
  } finally {
    loading.remove();
  }
};

// Mood Tracker (mood-tracker.html)
window.logMood = function(moodValue) {
  if (!auth.currentUser) return alert("Please log in to log your mood.");
  let message = "";
  switch (moodValue) {
    case 5: message = "Awesome to hear you're feeling great!"; break;
    case 4: message = "Glad you're doing good!"; break;
    case 3: message = "Okay is a good start. Try a mindfulness exercise?"; break;
    case 2: message = "Sorry you're feeling sad. How about a journal entry?"; break;
    case 1: message = "We're here for you. Consider checking our crisis support."; break;
  }
  const moodMessageElement = document.getElementById("mood-message");
  if (moodMessageElement) {
    moodMessageElement.textContent = message; // Line 195
  } else {
    console.warn("mood-message element not found");
  }
  addDoc(collection(db, "moods"), {
    userId: auth.currentUser.uid,
    mood: moodValue,
    timestamp: new Date()
  })
  .then(() => {
    console.log(`Mood ${moodValue} saved!`);
    if (moodMessageElement) {
      moodMessageElement.textContent += " Mood saved!";
    }
    window.loadRecentMoods();
  })
  .catch(error => {
    console.error("Error saving mood:", error.message);
    alert("Error saving mood: " + error.message);
  });
};

window.loadRecentMoods = async function() {
  if (!auth.currentUser) return;
  const q = query(
    collection(db, "moods"),
    where("userId", "==", auth.currentUser.uid),
    orderBy("timestamp", "desc"),
    limit(5)
  );
  const querySnapshot = await getDocs(q);
  const recentMoodsList = document.getElementById("recent-moods");
  if (recentMoodsList) {
    recentMoodsList.innerHTML = "";
    querySnapshot.forEach(doc => {
      const data = doc.data();
      const moodText = {
        5: "😊 Great",
        4: "🙂 Good",
        3: "😐 Okay",
        2: "😔 Sad",
        1: "😢 Bad"
      }[data.mood];
      const date = data.timestamp?.toDate ? data.timestamp.toDate().toLocaleString() : "N/A";
      const li = document.createElement("li");
      li.textContent = `${moodText} - ${date}`;
      recentMoodsList.appendChild(li);
    });
  }
};

// Journal (journal.html)
window.saveJournalEntry = async function() {
  if (!auth.currentUser) return alert("Please log in to save a journal entry.");
  const entry = document.getElementById("journal-entry")?.value?.trim();
  if (!entry) return alert("Please write something in the journal.");

  const sentiment = await window.analyzeSentiment(entry);
  let message = "Journal entry saved!";
  if (sentiment === "negative") {
    message += " It seems you're feeling down. Please consider checking our crisis support resources.";
  }

  try {
    await addDoc(collection(db, "journal"), {
      userId: auth.currentUser.uid,
      entry: entry,
      sentiment: sentiment,
      timestamp: new Date()
    });
    document.getElementById("save-status")?.textContent = message;
    document.getElementById("journal-entry").value = "";
    window.loadRecentEntries();
  } catch (error) {
    console.error("Error saving journal entry:", error.message);
    alert("Error saving journal entry: " + error.message);
  }
};

window.analyzeSentiment = async function(text) {
  const distressKeywords = ["hopeless", "suicidal", "desperate", "worthless"];
  const saveStatus = document.getElementById("save-status");
  const loading = document.getElementById("api-loading") || document.createElement("p");
  loading.id = "api-loading";
  loading.className = "loading";
  loading.textContent = "Analyzing sentiment...";
  document.getElementById("journal-entry")?.after(loading);

  if (distressKeywords.some(keyword => text.toLowerCase().includes(keyword))) {
    saveStatus.textContent = "Warning: Your entry contains concerning language. Please consider checking our crisis support resources.";
    loading.remove();
    return "negative";
  }

  const apiKey = "bb260ba35amsh481340f9e9b7d3cp172d93jsn463ac4a81999"; // Your RapidAPI key
  const url = 'https://twinword-text-analysis-bundle.p.rapidapi.com/sentiment/';

  try {
    const response = await retryWithBackoff(() =>
      fetch(url, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-RapidAPI-Key": apiKey,
          "X-RapidAPI-Host": "twinword-text-analysis-bundle.p.rapidapi.com"
        },
        body: JSON.stringify({ text: text })
      })
    );

    if (!response.ok) {
      throw new Error(`API request failed with status ${response.status}`);
    }

    const data = await response.json();
    if (data.result_code !== "200" || !data.type) {
      throw new Error(data.result_msg || "Invalid API response");
    }

    saveStatus.textContent = "Sentiment analyzed successfully!";
    loading.remove();
    return data.type;
  } catch (error) {
    console.error("Sentiment analysis error:", error.message);
    saveStatus.textContent = error.message.includes("429")
      ? "API rate limit reached. Please try again later."
      : "Unable to analyze sentiment. Defaulting to neutral.";
    loading.remove();
    return "neutral";
  }
};

window.loadRecentEntries = async function() {
  if (!auth.currentUser) return;
  const q = query(
    collection(db, "journal"),
    where("userId", "==", auth.currentUser.uid),
    orderBy("timestamp", "desc"),
    limit(5)
  );
  const querySnapshot = await getDocs(q);
  const recentEntriesList = document.getElementById("recent-entries");
  if (recentEntriesList) {
    recentEntriesList.innerHTML = "";
    querySnapshot.forEach(doc => {
      const data = doc.data();
      const date = data.timestamp?.toDate ? data.timestamp.toDate().toLocaleString() : "N/A";
      const li = document.createElement("li");
      li.innerHTML = `<span class="prompt">Entry on ${date} (${data.sentiment}):</span><br>${data.entry.substring(0, 100)}${data.entry.length > 100 ? "..." : ""}`;
      recentEntriesList.appendChild(li);
    });
  }
};

window.suggestReflection = async function () {
  if (!auth.currentUser) return alert("Please log in to use this feature.");
  const entry = document.getElementById("journal-entry")?.value?.trim();
  const suggestionElement = document.getElementById("ai-suggestion");
  const loading = document.getElementById("api-loading") || document.createElement("p");
  loading.id = "api-loading";
  loading.className = "loading";
  loading.textContent = "Generating reflection...";
  document.getElementById("journal-entry")?.after(loading);

  if (!entry) {
    alert("Please write your journal entry first.");
    loading.remove();
    return;
  }

  const apiKey = "bb260ba35amsh481340f9e9b7d3cp172d93jsn463ac4a81999"; // Your RapidAPI key
  const url = 'https://twinword-text-analysis-bundle.p.rapidapi.com/association/';

  try {
    const response = await retryWithBackoff(() =>
      fetch(url, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-RapidAPI-Key": apiKey,
          "X-RapidAPI-Host": "twinword-text-analysis-bundle.p.rapidapi.com"
        },
        body: JSON.stringify({ text: entry })
      })
    );

    if (!response.ok) {
      throw new Error(`API request failed with status ${response.status}`);
    }

    const data = await response.json();
    if (data.result_code !== "200") {
      throw new Error(data.result_msg || "Invalid API response");
    }

    const positiveWords = data.associations?.filter(word => word.score > 0).slice(0, 3).map(w => w.word) || [];
    const suggestion = positiveWords.length
      ? `Reflect on ${positiveWords.join(", ")} to find calm and clarity today.`
      : "Take a moment to breathe and reflect on a positive aspect of your day.";

    suggestionElement.textContent = suggestion;
  } catch (error) {
    console.error("Reflection error:", error.message);
    suggestionElement.textContent = error.message.includes("429")
      ? "API rate limit reached. Please try again later."
      : "Unable to generate reflection. Please try again.";
  } finally {
    loading.remove();
  }
};

// Crisis Support (crisis.html)
window.getLocalResources = function() {
  const resourcesList = document.getElementById("crisis-resources");
  if (resourcesList) {
    resourcesList.innerHTML = "<li>Loading...</li>";
    if ("geolocation" in navigator) {
      navigator.geolocation.getCurrentPosition(
        async (position) => {
          const { latitude, longitude } = position.coords;
          try {
            const response = await fetch(`https://nominatim.openstreetmap.org/reverse?lat=${latitude}&lon=${longitude}&format=json`);
            const data = await response.json();
            const countryCode = data.address?.country_code?.toUpperCase() || "default";
            const hotlines = {
              "US": [
                { name: "National Suicide Prevention Lifeline", number: "1-800-273-8255" },
                { name: "Crisis Text Line", number: "Text HOME to 741741" }
              ],
              "UK": [
                { name: "Samaritans", number: "116 123" },
                { name: "Mind", number: "0300 123 3393" }
              ],
              "CA": [
                { name: "Canada Suicide Prevention Service", number: "1-833-456-4566" },
                { name: "Crisis Text Line", number: "Text HOME to 686868" }
              ],
              "default": [
                { name: "International Association for Suicide Prevention", number: "Find local resources at iasp.info" }
              ]
            }[countryCode] || hotlines["default"];
            resourcesList.innerHTML = "";
            hotlines.forEach(hotline => {
              const li = document.createElement("li");
              li.innerHTML = `<strong>${hotline.name}</strong>: ${hotline.number}`;
              resourcesList.appendChild(li);
            });
          } catch (error) {
            console.error("Geolocation error:", error.message);
            resourcesList.innerHTML = "<li>Error loading resources. Please try again.</li>";
          }
        },
        (error) => {
          console.error("Geolocation access denied:", error.message);
          resourcesList.innerHTML = "";
          const hotlines = [
            { name: "International Association for Suicide Prevention", number: "Find local resources at iasp.info" }
          ];
          hotlines.forEach(hotline => {
            const li = document.createElement("li");
            li.innerHTML = `<strong>${hotline.name}</strong>: ${hotline.number}`;
            resourcesList.appendChild(li);
          });
        }
      );
    } else {
      resourcesList.innerHTML = "<li>Geolocation not supported in this browser.</li>";
      const hotlines = [
        { name: "International Association for Suicide Prevention", number: "Find local resources at iasp.info" }
      ];
      hotlines.forEach(hotline => {
        const li = document.createElement("li");
        li.innerHTML = `<strong>${hotline.name}</strong>: ${hotline.number}`;
        resourcesList.appendChild(li);
      });
    }
  }
};

// Mindfulness (mindfulness.html)
window.chart = null;
window.drawChart = function(sessionDates, completions) {
  if (typeof Chart === 'undefined') {
    console.error("Chart.js not loaded for drawChart. Please check the script tag in mindfulness.html.");
    return;
  }
  const ctx = document.getElementById('completionChart')?.getContext('2d');
  if (ctx) {
    if (window.chart) window.chart.destroy();
    window.chart = new Chart(ctx, {
      type: 'line',
      data: {
        labels: sessionDates,
        datasets: [{
          label: 'Completion Rate (%)',
          data: completions.map(c => c * 100),
          borderColor: 'rgba(75, 192, 192, 1)',
          fill: false
        }]
      },
      options: {
        scales: {
          y: { beginAtZero: true, max: 100 }
        }
      }
    });
  }
};

window.populateVoiceList = function() {
  if (!('speechSynthesis' in window)) {
    console.log("Web Speech API not supported.");
    return;
  }
  const voiceSelect = document.getElementById("voice-select");
  if (voiceSelect) {
    function updateVoices() {
      const voices = speechSynthesis.getVoices();
      voiceSelect.innerHTML = '<option value="">Select a voice</option>';
      voices.forEach(voice => {
        const option = document.createElement("option");
        option.value = voice.name;
        option.textContent = `${voice.name} (${voice.lang})`;
        voiceSelect.appendChild(option);
      });
    }
    updateVoices();
    speechSynthesis.onvoiceschanged = updateVoices;
  }
};

window.updateSettings = function() {
  const pitchValue = document.getElementById("pitch-value");
  const rateValue = document.getElementById("rate-value");
  const pitch = document.getElementById("pitch");
  const rate = document.getElementById("rate");
  if (pitchValue && pitch) pitchValue.textContent = pitch.value;
  if (rateValue && rate) rateValue.textContent = rate.value;
};

window.loadStats = async function(userId) {
  if (!auth.currentUser) return;
  const snapshot = await getDoc(doc(db, "stats", userId));
  const data = snapshot.data() || { breathing: 0, bodyScan: 0, guidedMed: 0, totalTime: 0, sessionDates: [], durations: [], completions: [] };
  const sessionDates = Array.isArray(data.sessionDates) ? data.sessionDates : [];
  const durations = Array.isArray(data.durations) ? data.durations : [];
  const completions = Array.isArray(data.completions) ? data.completions : [];
  const totalSessions = data.breathing + data.bodyScan + data.guidedMed;
  const breathingCount = document.getElementById("breathing-count");
  const bodyScanCount = document.getElementById("body-scan-count");
  const guidedMedCount = document.getElementById("guided-med-count");
  const totalTime = document.getElementById("total-time");
  const lastSessionDate = document.getElementById("last-session-date");
  const avgDuration = document.getElementById("avg-duration");
  const successRate = document.getElementById("success-rate");
  if (breathingCount) breathingCount.textContent = data.breathing;
  if (bodyScanCount) bodyScanCount.textContent = data.bodyScan;
  if (guidedMedCount) guidedMedCount.textContent = data.guidedMed;
  if (totalTime) totalTime.textContent = (data.totalTime / 60).toFixed(1);
  if (lastSessionDate) lastSessionDate.textContent = sessionDates.length ? sessionDates[sessionDates.length - 1] : "N/A";
  if (avgDuration) avgDuration.textContent = totalSessions ? (durations.reduce((a, b) => a + b, 0) / durations.length).toFixed(1) : "0";
  if (successRate) successRate.textContent = totalSessions ? ((completions.reduce((a, b) => a + b, 0) / totalSessions) * 100).toFixed(1) : "0";
  window.drawChart(sessionDates, completions);
};

window.updateStats = async function(type, duration, completed = false) {
  if (!auth.currentUser) return;
  const userId = auth.currentUser.uid;
  const now = new Date().toISOString().split('T')[0];
  await setDoc(doc(db, "stats", userId), {
    breathing: type === "breathing" ? increment(1) : increment(0),
    bodyScan: type === "bodyScan" ? increment(1) : increment(0),
    guidedMed: type === "guidedMed" ? increment(1) : increment(0),
    totalTime: increment(duration),
    sessionDates: arrayUnion(now),
    durations: arrayUnion(duration),
    completions: arrayUnion(completed ? 1 : 0)
  }, { merge: true });
  window.loadStats(userId);
};

window.exportData = async function() {
  if (!auth.currentUser) return;
  const userId = auth.currentUser.uid;
  const snapshot = await getDoc(doc(db, "stats", userId));
  const data = {
    stats: snapshot.data() || { breathing: 0, bodyScan: 0, guidedMed: 0, totalTime: 0, sessionDates: [], durations: [], completions: [] },
    journal: (await getDocs(collection(db, "journal"))).docs.map(doc => ({ id: doc.id, ...doc.data() })),
    cbt: (await getDocs(collection(db, "cbt"))).docs.map(doc => ({ id: doc.id, ...doc.data() }))
  };
  const sessionDates = Array.isArray(data.stats.sessionDates) ? data.stats.sessionDates : [];
  const durations = Array.isArray(data.stats.durations) ? data.durations : [];
  const completions = Array.isArray(data.stats.completions) ? data.completions : [];

  if (document.getElementById("export-format")?.value === "json") {
    const jsonString = JSON.stringify(data, null, 2);
    const blob = new Blob([jsonString], { type: "application/json" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `selftherapy_data_${new Date().toISOString().split('T')[0]}.json`;
    a.click();
    URL.revokeObjectURL(url);
  } else {
    let csvContent = "Category,Detail,Value\n";
    csvContent += `Stats,Breathing Sessions,${data.stats.breathing}\n`;
    csvContent += `Stats,Body Scan Sessions,${data.stats.bodyScan}\n`;
    csvContent += `Stats,Guided Meditation Sessions,${data.stats.guidedMed}\n`;
    csvContent += `Stats,Total Time (minutes),${(data.stats.totalTime / 60).toFixed(1)}\n`;
    csvContent += `Stats,Last Session Date,${sessionDates.length ? sessionDates[sessionDates.length - 1] : "N/A"}\n`;
    csvContent += `Stats,Average Duration (seconds),${durations.length ? (durations.reduce((a, b) => a + b, 0) / durations.length).toFixed(1) : "0"}\n`;
    csvContent += `Stats,Success Rate (%),${completions.length ? ((completions.reduce((a, b) => a + b, 0) / completions.length) * 100).toFixed(1) : "0"}\n`;
    data.journal.forEach(entry => {
      csvContent += `Journal,${entry.id},${JSON.stringify(entry.entry).replace(/"/g, "'")}\n`;
    });
    data.cbt.forEach(entry => {
      csvContent += `CBT,${entry.id},${JSON.stringify(entry.situation).replace(/"/g, "'")}\n`;
    });
    const blob = new Blob([csvContent], { type: "text/csv" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `selftherapy_data_${new Date().toISOString().split('T')[0]}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  }
};

window.startBreathing = function() {
  if (!auth.currentUser) return alert("Please log in to use this feature.");
  const circle = document.getElementById("breathing-circle");
  const timer = document.getElementById("timer");
  const cue = document.getElementById("breathing-cue");
  const progressBar = document.getElementById("progress-bar");
  if (circle && timer && cue && progressBar) {
    circle.classList.add("active");
    let timeLeft = 60;
    timer.textContent = "1:00";
    progressBar.style.width = "0%";
    let lastSpoken = null;
    const startTime = Date.now();
    const interval = setInterval(() => {
      timeLeft--;
      const minutes = Math.floor(timeLeft / 60);
      const seconds = timeLeft % 60;
      timer.textContent = `${minutes}:${seconds < 10 ? "0" : ""}${seconds}`;
      const progress = ((60 - timeLeft) / 60) * 100;
      progressBar.style.width = `${progress}%`;
      const isInhale = timeLeft % 4 < 2;
      const currentCue = isInhale ? "Inhale" : "Exhale";
      cue.textContent = currentCue;
      if (window.isSoundOn && !speechSynthesis.speaking && lastSpoken !== currentCue) {
        window.speakCue(currentCue);
        lastSpoken = currentCue;
      }
      if (timeLeft <= 0) {
        clearInterval(interval);
        window.stopBreathing();
        const duration = (Date.now() - startTime) / 1000;
        window.updateStats("breathing", duration, true);
      }
    }, 1000);
    window.breathingInterval = interval;
  }
};

window.stopBreathing = function() {
  if (!auth.currentUser) return;
  const circle = document.getElementById("breathing-circle");
  const timer = document.getElementById("timer");
  const cue = document.getElementById("breathing-cue");
  const progressBar = document.getElementById("progress-bar");
  if (circle && timer && cue && progressBar) {
    circle.classList.remove("active");
    if (window.breathingInterval) {
      clearInterval(window.breathingInterval);
      const duration = (Date.now() - (new Date().getTime() - (60 - parseInt(timer.textContent.split(':')[1]) * 1000))) / 1000;
      window.updateStats("breathing", duration, false);
    }
    timer.textContent = "1:00";
    cue.textContent = "Prepare to begin...";
    progressBar.style.width = "0%";
    window.stopSoundCue();
  }
};

window.toggleSound = function() {
  if (!auth.currentUser) return alert("Please log in to use this feature.");
  window.isSoundOn = !window.isSoundOn;
  if (window.isSoundOn) {
    alert("Voice cues enabled. They will play with the next start.");
  } else {
    alert("Voice cues disabled.");
    window.stopSoundCue();
  }
};

window.speakCue = function(text) {
  if (!window.isSoundOn) return;
  if ('speechSynthesis' in window) {
    if (speechSynthesis.speaking) {
      speechSynthesis.cancel();
    }
    const utterance = new SpeechSynthesisUtterance(text);
    const voiceSelect = document.getElementById("voice-select");
    const voices = speechSynthesis.getVoices();
    const selectedVoice = voices.find(voice => voice.name === voiceSelect?.value) || voices[0];
    utterance.voice = selectedVoice;
    utterance.volume = 1;
    utterance.rate = parseFloat(document.getElementById("rate")?.value || 1);
    utterance.pitch = parseFloat(document.getElementById("pitch")?.value || 1);
    utterance.lang = selectedVoice.lang || 'en-US';
    speechSynthesis.speak(utterance);
  } else {
    console.log("Web Speech API not supported in this browser.");
  }
};

window.stopSoundCue = function() {
  if ('speechSynthesis' in window) {
    speechSynthesis.cancel();
  }
};

window.startBodyScan = function() {
  if (!auth.currentUser) return alert("Please log in to use this feature.");
  const instructions = document.getElementById("body-scan-instructions");
  const duration = Math.min(Math.max(parseInt(document.getElementById("body-scan-duration")?.value) || 25, 10), 60);
  if (instructions) {
    const steps = ["toes", "feet", "legs", "torso", "whole body"];
    let step = 0;
    instructions.innerHTML = `Focus on your ${steps[step]}... (Step 1 of ${steps.length})`;
    const startTime = Date.now();
    const intervalTime = duration * 1000 / steps.length;
    const scanInterval = setInterval(() => {
      step++;
      if (step < steps.length) {
        instructions.innerHTML = `Focus on your ${steps[step]}... (Step ${step + 1} of ${steps.length})`;
        if (window.isSoundOn && !speechSynthesis.speaking) {
          window.speakCue(`Focus on your ${steps[step]}`);
        }
      } else {
        instructions.innerHTML = `Relax your ${steps[steps.length - 1]}... (Step ${steps.length} of ${steps.length})`;
        if (window.isSoundOn && !speechSynthesis.speaking) {
          window.speakCue(`Relax your ${steps[steps.length - 1]}`);
        }
        clearInterval(scanInterval);
        setTimeout(() => instructions.innerHTML = "", duration * 1000 - (steps.length - 1) * intervalTime);
        const totalDuration = (Date.now() - startTime) / 1000;
        window.updateStats("bodyScan", totalDuration, true);
      }
    }, intervalTime);
    window.scanInterval = scanInterval;
  }
};

window.stopBodyScan = function() {
  if (!auth.currentUser) return;
  if (window.scanInterval) {
    clearInterval(window.scanInterval);
    const duration = Math.min(Math.max(parseInt(document.getElementById("body-scan-duration")?.value) || 25, 10), 60);
    const elapsed = (Date.now() - (new Date().getTime() - duration * 1000)) / 1000;
    window.updateStats("bodyScan", elapsed, false);
    const instructions = document.getElementById("body-scan-instructions");
    if (instructions) instructions.innerHTML = "";
  }
};

window.startGuidedMeditation = function() {
  if (!auth.currentUser) return alert("Please log in to use this feature.");
  const instructions = document.getElementById("guided-meditation-instructions");
  const duration = Math.min(Math.max(parseInt(document.getElementById("guided-med-duration")?.value) || 15, 10), 60);
  if (instructions) {
    const steps = ["breathe deeply", "imagine a calm place", "return slowly"];
    let step = 0;
    instructions.innerHTML = `${steps[step]}... (Step 1 of ${steps.length})`;
    const startTime = Date.now();
    const intervalTime = duration * 1000 / steps.length;
    const meditationInterval = setInterval(() => {
      step++;
      if (step < steps.length) {
        instructions.innerHTML = `${steps[step]}... (Step ${step + 1} of ${steps.length})`;
        if (window.isSoundOn && !speechSynthesis.speaking) {
          window.speakCue(steps[step]);
        }
      } else {
        instructions.innerHTML = `${steps[steps.length - 1]}... (Step ${steps.length} of ${steps.length})`;
        if (window.isSoundOn && !speechSynthesis.speaking) {
          window.speakCue(steps[steps.length - 1]);
        }
        clearInterval(meditationInterval);
        setTimeout(() => instructions.innerHTML = "", duration * 1000 - (steps.length - 1) * intervalTime);
        const totalDuration = (Date.now() - startTime) / 1000;
        window.updateStats("guidedMed", totalDuration, true);
      }
    }, intervalTime);
    window.meditationInterval = meditationInterval;
  }
};

window.stopGuidedMeditation = function() {
  if (!auth.currentUser) return;
  if (window.meditationInterval) {
    clearInterval(window.meditationInterval);
    const duration = Math.min(Math.max(parseInt(document.getElementById("guided-med-duration")?.value) || 15, 10), 60);
    const elapsed = (Date.now() - (new Date().getTime() - duration * 1000)) / 1000;
    window.updateStats("guidedMed", elapsed, false);
    const instructions = document.getElementById("guided-meditation-instructions");
    if (instructions) instructions.innerHTML = "";
  }
};

// Dashboard (dashboard.html)
window.loadDashboard = async function(userId) {
  if (!auth.currentUser) return;

  // Update dashboard stats
  const journalSnapshot = await getDocs(query(collection(db, "journal"), where("userId", "==", userId)));
  const cbtSnapshot = await getDocs(query(collection(db, "cbt"), where("userId", "==", userId)));
  const moodSnapshot = await getDocs(query(collection(db, "moods"), where("userId", "==", userId)));
  const statsSnapshot = await getDoc(doc(db, "stats", userId));
  const statsData = statsSnapshot.data() || { breathing: 0, bodyScan: 0, guidedMed: 0 };
  const journalCount = document.getElementById("journal-count");
  const thoughtCount = document.getElementById("thought-count");
  const moodCount = document.getElementById("mood-count");
  const mindfulnessCount = document.getElementById("mindfulness-count");
  if (journalCount) journalCount.textContent = journalSnapshot.size;
  if (thoughtCount) thoughtCount.textContent = cbtSnapshot.size;
  if (moodCount) moodCount.textContent = moodSnapshot.size;
  if (mindfulnessCount) mindfulnessCount.textContent = statsData.breathing + statsData.bodyScan + statsData.guidedMed;
};

// Auth State Listener
onAuthStateChanged(auth, (user) => {
  const authSection = document.getElementById("auth-section");
  const userInfo = document.getElementById("user-info");
  const logoutBtn = document.getElementById("logout-btn");
  if (user) {
    if (userInfo) userInfo.style.display = "block";
    if (logoutBtn) logoutBtn.style.display = "inline";
    if (authSection) authSection.style.display = "none";
    if (document.getElementById("user-email")) document.getElementById("user-email").textContent = user.email;
    if (document.getElementById("recent-thoughts")) window.loadRecentThoughts();
    if (document.getElementById("recent-moods")) window.loadRecentMoods();
    if (document.getElementById("recent-entries")) window.loadRecentEntries();
    if (document.getElementById("breathing-count")) window.loadStats(user.uid);
    if (document.getElementById("journal-count")) window.loadDashboard(user.uid);
  } else {
    if (authSection) authSection.style.display = "block";
    if (userInfo) userInfo.style.display = "none";
    if (logoutBtn) logoutBtn.style.display = "none";
    if (document.getElementById("save-status")) document.getElementById("save-status").textContent = "";
    if (document.getElementById("mood-message")) document.getElementById("mood-message").textContent = "";
    if (document.getElementById("recent-thoughts")) document.getElementById("recent-thoughts").innerHTML = "";
    if (document.getElementById("recent-moods")) document.getElementById("recent-moods").innerHTML = "";
    if (document.getElementById("recent-entries")) document.getElementById("recent-entries").innerHTML = "";
    if (document.getElementById("crisis-resources")) document.getElementById("crisis-resources").innerHTML = "";
    if (document.getElementById("breathing-count")) {
      document.getElementById("breathing-count").textContent = "0";
      document.getElementById("body-scan-count").textContent = "0";
      document.getElementById("guided-med-count").textContent = "0";
      document.getElementById("total-time").textContent = "0";
      document.getElementById("last-session-date").textContent = "N/A";
      document.getElementById("avg-duration").textContent = "0";
      document.getElementById("success-rate").textContent = "0";
      if (window.chart) window.chart.destroy();
    }
  }
});

// Initialize on Load
document.addEventListener("DOMContentLoaded", () => {
  if (document.getElementById("recent-thoughts")) window.loadRecentThoughts();
  if (document.getElementById("recent-moods")) window.loadRecentMoods();
  if (document.getElementById("recent-entries")) window.loadRecentEntries();
  ifCPs:
  if (document.getElementById("breathing-count")) {
    window.populateVoiceList();
    const pitch = document.getElementById("pitch");
    const rate = document.getElementById("rate");
    if (pitch) pitch.addEventListener("input", window.updateSettings);
    if (rate) rate.addEventListener("input", window.updateSettings);
    window.updateSettings();
    window.loadStats(auth.currentUser?.uid);
  }
  if (document.getElementById("journal-count")) window.loadDashboard(auth.currentUser?.uid);

  const loginBtn = document.getElementById("login-btn");
  const registerBtn = document.getElementById("register-btn");
  const logoutBtn = document.getElementById("logout-btn");
  const suggestReframeBtn = document.getElementById("suggest-reframe-btn");
  const saveThoughtBtn = document.getElementById("save-thought-btn");
  if (loginBtn) loginBtn.addEventListener("click", window.login);
  if (registerBtn) registerBtn.addEventListener("click", window.register);
  if (logoutBtn) logoutBtn.addEventListener("click", window.logout);
  if (suggestReframeBtn) suggestReframeBtn.addEventListener("click", window.suggestReframe);
  if (saveThoughtBtn) saveThoughtBtn.addEventListener("click", window.saveThoughtRecord);

  console.log("script.js loaded successfully");
});

// Initialize sound state
window.isSoundOn = false;