

var periodNumber;
var AllperiodData = [];
var selectedGlobalLang = "en";

/* =========================
   TRANSLATE + TTS HELPERS
========================= */
function extractTextFromHTML(html) {
  const div = document.createElement("div");
  div.innerHTML = html;
  return div.innerText.trim();
}

/* ===== LOADER HELPERS ===== */
function showLangLoader() {
  const loader = document.getElementById('loader');
  if (loader) loader.style.display = 'block';
}

function hideLangLoader() {
  const loader = document.getElementById('loader');
  if (loader) loader.style.display = 'none';
}

/* ===== ENABLE/DISABLE TRANSLATE BUTTONS ===== */
function disableTranslateButtons() {
  document.querySelectorAll('.translateBtn').forEach(btn => {
    try {
      btn.style.pointerEvents = 'none';
      btn.classList.add('disabled');
      btn.setAttribute('aria-disabled', 'true');
    } catch (e) {}
  });
}

function enableTranslateButtons() {
  document.querySelectorAll('.translateBtn').forEach(btn => {
    try {
      btn.style.pointerEvents = '';
      btn.classList.remove('disabled');
      btn.removeAttribute('aria-disabled');
    } catch (e) {}
  });
}

/* ===== GLOBAL AUDIO CONTROL ===== */
let activeAudio = null;
let activeButton = null;   // 🔥 track which button owns audio
let isPlaying = false;
 
let currentChunks = [];
let currentChunkIndex = 0;
let currentLang = "";
let currentText = "";
let resumeTime = 0;
let pausedChunkIndex = 0;

function stopSpeak() {
  isMuted = true;

  if (activeAudio) {
    resumeTime = activeAudio.currentTime; // ✅ SAVE POSITION
    activeAudio.pause();
  }
}

// function resetSpeakState() {
//   stopSpeak();
//   activeAudio = null;
//   currentChunks = [];
//   currentChunkIndex = 0;
//   resumeTime = 0;
//   currentLang = "";
//   currentText = "";
// }

function hardStopAudio() {
  if (activeAudio) {
    activeAudio.pause();
    activeAudio = null;
  }
 
  if (activeButton) {
    activeButton.querySelector("img").src = "images/mute.png";
    activeButton.querySelector("span").textContent = "Mute";
    activeButton.classList.add("muted");
  }
 
  isPlaying = false;
  currentChunks = [];
  currentChunkIndex = 0;
  resumeTime = 0;
  pausedChunkIndex = 0;
}
function pauseAudio() {
  if (activeAudio) {
    resumeTime = activeAudio.currentTime || 0;
    pausedChunkIndex = currentChunkIndex;
    activeAudio.pause();
    activeAudio = null;
  }

  if (activeButton) {
    activeButton.querySelector("img").src = "images/mute.png";
    activeButton.querySelector("span").textContent = "Mute";
    activeButton.classList.add("muted");
  }

  isPlaying = false;
}
function resetSpeakState() {
  if (activeAudio) {
    console.log("11111");
    
    activeAudio.pause();
    activeAudio = null;
    // isMuted = true;
  }
// isMuted = true;
  currentChunks = [];
  currentChunkIndex = 0;
  resumeTime = 0;
  currentLang = "";
  currentText = "";
}

async function translateAndSpeak(text, targetLang) {
  if (!text) return "";

  // ensure loader shown and buttons disabled (caller may also do this)
  showLangLoader();
  disableTranslateButtons();

  // 🔹 New text or language → reset
  if (text !== currentText || targetLang !== currentLang) {
    resetSpeakState();
    currentText = text;
    currentLang = targetLang;
  }

  let textToSpeak = text;

  if (targetLang !== "en") {
    try {
      const response = await fetch(
        `${getUrl}/translate?lang=${targetLang}&text=${encodeURIComponent(text)}`
      );
      // alert(response.status);
      console.log(`${getUrl}/translate?lang=${targetLang}&text=${encodeURIComponent(text)}`);
      
      const data = await response.json();
      textToSpeak = data.text;
    } catch (err) {
      console.error("Translation failed", err);
      hideLangLoader();
      enableTranslateButtons();
      return text;
    }
  }

  // leave loader visible until audio starts playing (see speakText onplaying)
  speakText(textToSpeak, targetLang);
  return textToSpeak;
}


// function speakText(text, lang) {
//   if (isMuted) return;

//   stopSpeak(); // stop any previous audio
//   isMuted = false;

//   const chunks = text.match(/.{1,150}(?=\s|$)|\S+/g) || [text];
//   let index = 0;

//   function playNext() {
//     if (index >= chunks.length || isMuted) return;

//     const audio = new Audio(
//       `${getUrl}/tts?lang=${lang}&text=${encodeURIComponent(chunks[index])}`
//     );

//     activeAudio = audio;

//     audio.onended = () => {
//       index++;
//       playNext();
//     };

//     audio.onerror = () => {
//       index++;
//       playNext();
//     };

//     audio.play();
//   }

//   playNext();
// }


// function speakText(text, lang) {
//   // if (isMuted) return;
//   console.log("sadf asd fasdf asdf ");
  
//   // 🔹 First time: create chunks
//   if (!currentChunks.length) {
//     currentChunks = text.match(/.{1,150}(?=\s|$)|\S+/g) || [text];
//     currentChunkIndex = 0;
//     resumeTime = 0;
//   }

//   function playNext() {
//     if (isMuted || currentChunkIndex >= currentChunks.length) return;

//     const audio = new Audio(
//       `${getUrl}/tts?lang=${lang}&text=${encodeURIComponent(
//         currentChunks[currentChunkIndex]
//       )}`
//     );

//     activeAudio = audio;

//     // 🔹 Resume from paused time
//     audio.currentTime = resumeTime || 0;

//     audio.onended = () => {
//       resumeTime = 0;
//       currentChunkIndex++;
//       playNext();
//     };

//     audio.onerror = () => {
//       resumeTime = 0;
//       currentChunkIndex++;
//       playNext();
//     };

//     audio.play();
//   }

//   playNext();
// }

function speakText(text, lang) {
  // Initialize chunks only if not already present (so resume is possible)
  if (!currentChunks.length) {
    currentChunks = text.match(/.{1,150}(?=\s|$)|\S+/g) || [text];
    currentChunkIndex = 0;
    // fresh start
    resumeTime = 0;
    pausedChunkIndex = 0;
  }
 
  function playNext() {
    if (!isPlaying || currentChunkIndex >= currentChunks.length) {
      hardStopAudio();
      return;
    }
 
    const audio = new Audio(
      `${getUrl}/tts?lang=${lang}&text=${encodeURIComponent(
        currentChunks[currentChunkIndex]
      )}`
    );
 
    activeAudio = audio;

    // when audio playback actually begins, hide loader and re-enable buttons
    audio.onplaying = () => {
      hideLangLoader();
      enableTranslateButtons();
    };

    // If we paused mid-chunk, resume from saved time for that chunk
    if (resumeTime > 0 && currentChunkIndex === pausedChunkIndex) {
      try {
        // setting currentTime may fail before metadata is loaded; set after loadedmetadata
        if (audio.readyState >= 1) {
          audio.currentTime = resumeTime;
        } else {
          audio.addEventListener("loadedmetadata", function onMeta() {
            audio.removeEventListener("loadedmetadata", onMeta);
            try {
              if (audio.duration && resumeTime < audio.duration) audio.currentTime = resumeTime;
            } catch (e) {
              // ignore
            }
          });
        }
      } catch (e) {
        // some browsers may throw if setting currentTime before metadata; ignore
      }
    }

    audio.onended = () => {
      // once a chunk finishes, don't resume into it
      resumeTime = 0;
      pausedChunkIndex = 0;
      currentChunkIndex++;
      // re-enable buttons after playback finishes
      if (currentChunkIndex >= currentChunks.length) {
        enableTranslateButtons();
        hideLangLoader();
      }
      playNext();
    };
 
    audio.onerror = () => {
      // on error, ensure loader hidden and buttons re-enabled
      hideLangLoader();
      enableTranslateButtons();

      resumeTime = 0;
      pausedChunkIndex = 0;
      currentChunkIndex++;
      playNext();
    };
 
    audio.play();
  }
 
  playNext();
}

/* =========================
   MAIN FUNCTION
========================= */
function getactivitylist(name, lessonId, BookId) {
  let loader = document.getElementById("loader");
  loader.style.display = "block";

  periodNumber = name;
  document.querySelector(".main").style.display = "none";

  const url = bmsURL + "getPeriodActivityDetails";
  const payload = {
    app_type: "TDA",
    mobile: userPhoneNumber || phoneNumber,
    period_id: name + 1,
    lesson_id: lessonId,
    series_id: BookId,
    is_live: 1,
    user_id: bmsuserid,
    academic_session: academicYear,
    class: getclass,
    section: section?.toUpperCase(),
  };

  async function getActivitylist() {
    const resp = await axios.post(url, payload, {
      headers: {
        Authorization: `Bearer d90b3ac333de82aab2846bf0f9cb5bc31bdb2309`,
      },
    });

    AllperiodData = resp.data.data;
    afterData();
  }

  getActivitylist();

  function afterData() {
    loader.style.display = "none";
    document.querySelector(".ActivityMain").style.display = "block";

    const activityListElement = document.getElementById("activity-list");
    activityListElement.innerHTML = "";

    const speakTranslateDiv =
      document.getElementsByClassName("speaktranslate")[0];

    /* ===== GLOBAL LANGUAGE SELECT ===== */
    const globalTranslateBox = document.createElement("div");
    // globalTranslateBox.style.position = "absolute";
    // globalTranslateBox.style.top = "50px";
    globalTranslateBox.style.right = "220px";
    globalTranslateBox.innerHTML = `
      <label>Translate:</label>
      <select id="globalLang">
        <option value="en">English</option>
        <option value="hi">Hindi</option>
        <option value="te">Telugu</option>
        <option value="kn">Kannada</option>
        <option value="ml">Malayalam</option>
        <option value="ta">Tamil</option>
      </select>
    `;
    // speakTranslateDiv.appendChild(globalTranslateBox);
const headerRow = speakTranslateDiv.querySelector(".row");
headerRow.appendChild(globalTranslateBox);
    // document.getElementById("globalLang").addEventListener("change", (e) => {
    //   selectedGlobalLang = e.target.value;
    // });
// document.getElementById("globalLang").addEventListener("change", e => {
//   selectedGlobalLang = e.target.value;
// console.log( selectedGlobalLang, "-------------------   -1111111111111111");
//   resetSpeakState();

//   // Reset UI
//   document.querySelectorAll(".translateBtn").forEach(btn => {
//     const icon = btn.querySelector("img");
//     const text = btn.querySelector("span");
//     if (icon) icon.src = "images/mute.png";
//     if (text) text.textContent = "Mute";
//     btn.classList.add("muted");
//   });
// });
document.getElementById("globalLang").addEventListener("change", e => {
  selectedGlobalLang = e.target.value;
 
  // 🔥 stop audio immediately
  hardStopAudio();
 
  console.log("Language changed:", selectedGlobalLang);
});
    /* ===== ACTIVITY CARDS ===== */
    AllperiodData.forEach((activity) => {
      const card = document.createElement("div");
      card.className = "card act-list";

      const cardContent = document.createElement("div");
      cardContent.className = "card-body";

      const titleRow = document.createElement("div");
      titleRow.className = "activity-title";

      const activityTitle = document.createElement("span");
      activityTitle.className = "card-title";
      activityTitle.innerHTML = activity.activity_title || "";
      titleRow.appendChild(activityTitle);

      /* ===== SPEAK / MUTE BUTTON ===== */
      const translateBox = document.createElement("div");
      translateBox.style.marginTop = "10px";
      translateBox.innerHTML = `
        <span type="button" class="translateBtn muted">
          <img src="images/mute.png" alt="Mute" width="20">
          <span>Mute</span>
        </span>
      `;
      titleRow.appendChild(translateBox);

      /* ===== CHECKBOX ===== */
      const checkboxLabel = document.createElement("label");
      const checkbox = document.createElement("input");
      checkbox.type = "checkbox";
      checkbox.className = "filled-in form-check-input f-chk";
      checkbox.dataset.id = activity.activity_id;
      checkbox.checked = activity.is_completed;
      checkbox.disabled = activity.is_completed;

      const span = document.createElement("span");
      span.className = "checkbox-right";

      checkbox.addEventListener("change", function () {
        if (this.checked) {
          document.getElementById("submit-btn").disabled = false;
        }
      });

      checkboxLabel.appendChild(checkbox);
      checkboxLabel.appendChild(span);
      titleRow.appendChild(checkboxLabel);

      cardContent.appendChild(titleRow);

      let descriptionText = activity.activity_title || "";

      if (activity.activity_description) {
        const activityDescription = document.createElement("div");
        activityDescription.className = "card-text";
        activityDescription.innerHTML = activity.activity_description;
        console.log(activityDescription.innerHTML, "activityDescription");
        // After activityDescription.innerHTML is set
        const imgs = activityDescription.querySelectorAll("img");

        imgs.forEach(img => {
          img.classList.add("img-fluid");
        });

        cardContent.appendChild(activityDescription);

        descriptionText = extractTextFromHTML(activity.activity_description);
      }

      /* ===== BUTTON TOGGLE EVENT ===== */
      const btn = translateBox.querySelector(".translateBtn");
      const icon = btn.querySelector("img");
      const text = btn.querySelector("span");

//     btn.addEventListener("click", async () => {
//       console.log("click first time");
      
//   if (!isMuted) {
//     stopSpeak(); // pause
//     icon.src = "images/mute.png";
//     text.textContent = "Mute";
//     btn.classList.add("muted");
//     return;
//   }

//   // ▶️ first click OR resume
//   isMuted = false;
//   icon.src = "images/speak.png";
//   text.textContent = "Speak";
//   btn.classList.remove("muted");

//   await translateAndSpeak(descriptionText, selectedGlobalLang);
// });
btn.addEventListener("click", async () => {
  // 🔁 If another audio is playing → stop it and start new
  if (isPlaying && activeButton !== btn) {
    hardStopAudio();
  }

  // ⏸ If same button is playing → pause (keep resume info)
  if (isPlaying && activeButton === btn) {
    pauseAudio();
    return;
  }

  // ▶️ If not playing and same button was active and we have chunks → resume
  if (!isPlaying && activeButton === btn && currentChunks.length) {
    isPlaying = true;
    btn.querySelector("img").src = "images/speak.png";
    btn.querySelector("span").textContent = "Speak";
    btn.classList.remove("muted");
    await speakText(currentText, currentLang);
    return;
  }

  // ▶️ START FRESH PLAYBACK
  hardStopAudio(); // clean start (important)

  isPlaying = true;
  activeButton = btn;

  btn.querySelector("img").src = "images/speak.png";
  btn.querySelector("span").textContent = "Speak";
  btn.classList.remove("muted");

  currentText = descriptionText;
  currentLang = selectedGlobalLang;

  await translateAndSpeak(descriptionText, selectedGlobalLang);
});

      card.appendChild(cardContent);
      activityListElement.appendChild(card);
    });
  }
}

/* =========================
   SUBMIT (UNCHANGED)
========================= */
async function submitActivities() {
  const completedActivities = [];

  AllperiodData.forEach((activity) => {
    const checkbox = document.querySelector(
      `input[type="checkbox"][data-id="${activity.activity_id}"]`
    );
    if (checkbox && checkbox.checked) {
      completedActivities.push({
        activity_id: activity.activity_id,
        is_completed: "1",
      });
    }
  });

  const url = bmsURL + "postActivityCompletion";

  const res = await axios.post(
    url,
    {
      user_id: bmsuserid,
      subject_id: getSubjectId[0],
      grade: grade,
      period_id: periodNumber + 1,
      activity_data: JSON.stringify(completedActivities),
      lesson_id: lessonId,
      series_id: BookId,
      academic_session: academicYear,
      class: getclass,
      section: section?.toUpperCase(),
    },
    {
      headers: {
        Authorization: `Bearer d90b3ac333de82aab2846bf0f9cb5bc31bdb2309`,
      },
    }
  );

  if (res.data.error === false) {
    alert("success");
  }
}
