/**
 * Export Dialog & Progress Monitor
 */
class ExportDialog {
  constructor(state) {
    this.state = state;
    this.modal = document.getElementById("export-modal");
    this.statusTimer = null;
    this.currentTaskId = null;
    this.currentOutputPath = null;
    this.currentOutputUrl = null;
    
    this.initUI();
  }

  initUI() {
    const exportBtn = document.getElementById("btn-export-ktv");
    const closeBtn = document.getElementById("btn-close-export-modal");
    const startBtn = document.getElementById("btn-start-export");
    const openFolderBtn = document.getElementById("btn-open-export-folder");
    const openFileBtn = document.getElementById("btn-open-export-file");

    if (exportBtn) exportBtn.addEventListener("click", () => this.open());
    if (closeBtn) closeBtn.addEventListener("click", () => this.close());
    if (startBtn) startBtn.addEventListener("click", () => this.startExport());
    if (openFolderBtn) openFolderBtn.addEventListener("click", () => this.openFolder());
    if (openFileBtn) openFileBtn.addEventListener("click", () => this.openFile());
  }

  open() {
    if (!this.state.videoUrl) {
      alert("請先載入 MP4 影片！");
      return;
    }
    if (!this.state.sentences || this.state.sentences.length === 0) {
      alert("請先匯入歌詞並設定時間軸！");
      return;
    }

    // Default filename
    const filenameInput = document.getElementById("export-filename");
    if (filenameInput) {
      filenameInput.value = `${this.state.projectTitle || 'KTV_Song'}_伴唱.mp4`;
    }

    // Reset progress UI
    document.getElementById("export-settings-form").style.display = "block";
    document.getElementById("export-progress-area").style.display = "none";
    document.getElementById("export-success-actions").style.display = "none";
    document.getElementById("btn-start-export").style.display = "inline-flex";

    this.modal.classList.add("open");
  }

  close() {
    if (this.statusTimer) {
      clearInterval(this.statusTimer);
      this.statusTimer = null;
    }
    this.modal.classList.remove("open");
  }

  async startExport() {
    const filename = document.getElementById("export-filename").value.trim() || "KTV_Output.mp4";
    const resolution = document.getElementById("export-resolution").value;

    document.getElementById("export-settings-form").style.display = "none";
    document.getElementById("export-progress-area").style.display = "block";
    document.getElementById("btn-start-export").style.display = "none";

    const progressBar = document.getElementById("export-progress-fill");
    const progressText = document.getElementById("export-progress-text");
    progressBar.style.width = "0%";
    progressText.innerText = "正在準備 ASS 卡拉OK字幕與影音串流...";

    try {
      const res = await fetch("/api/export", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          videoPath: this.state.videoLocalPath || this.state.videoUrl,
          sentences: this.state.sentences,
          style: this.state.style,
          resolution: resolution,
          outputFilename: filename
        })
      });

      const data = await res.json();
      if (!res.ok) {
        throw new Error(data.detail || "無法啟動合成任務");
      }

      this.currentTaskId = data.taskId;
      this.currentOutputPath = data.outputPath;
      this.currentOutputUrl = data.outputUrl;

      // Start polling status
      this.pollStatus();
    } catch (e) {
      alert(`合成失敗: ${e.message}`);
      this.close();
    }
  }

  pollStatus() {
    if (this.statusTimer) clearInterval(this.statusTimer);

    this.statusTimer = setInterval(async () => {
      try {
        const res = await fetch(`/api/export-status/${this.currentTaskId}`);
        const status = await res.json();

        const progressBar = document.getElementById("export-progress-fill");
        const progressText = document.getElementById("export-progress-text");

        const pct = status.progress || 0;
        progressBar.style.width = `${pct}%`;
        progressText.innerText = `正在合成 KTV 影片... ${pct}%`;

        if (status.status === "done" || status.completed) {
          clearInterval(this.statusTimer);
          progressBar.style.width = "100%";
          progressText.innerText = "🎉 KTV 伴唱影片合成完成！";

          // Set download link
          const downloadBtn = document.getElementById("btn-download-export-file");
          if (downloadBtn) {
            downloadBtn.href = status.outputUrl || this.currentOutputUrl;
            const filename = document.getElementById("export-filename").value.trim() || "KTV_伴唱影片.mp4";
            downloadBtn.download = filename;
          }

          document.getElementById("export-success-actions").style.display = "flex";
        } else if (status.status === "error") {
          clearInterval(this.statusTimer);
          progressText.innerText = `❌ 合成發生錯誤: ${status.error || '未知錯誤'}`;
        }
      } catch (e) {
        console.log("Status check error:", e);
      }
    }, 600);
  }

  async openFolder() {
    if (!this.currentOutputPath) {
      alert("尚未取得輸出路徑！");
      return;
    }
    try {
      const res = await fetch("/api/open-folder", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ filePath: this.currentOutputPath })
      });
      const data = await res.json();
      if (!data.success) {
        alert("無法開啟資料夾: " + (data.message || "路徑不存在"));
      }
    } catch (e) {
      console.log(e);
      alert("開啟資料夾失敗: " + e.message);
    }
  }

  async openFile() {
    if (!this.currentOutputPath) {
      alert("尚未取得輸出檔案路徑！");
      return;
    }
    try {
      const res = await fetch("/api/open-file", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ filePath: this.currentOutputPath })
      });
      const data = await res.json();
      if (!data.success) {
        alert("無法播放影片: " + (data.message || "檔案不存在"));
      }
    } catch (e) {
      console.log(e);
      alert("播放影片失敗: " + e.message);
    }
  }
}

window.ExportDialog = ExportDialog;
