/**
 * TDV_CORE.js - Game Logic Layer (Exam Mode)
 * Nhiệm vụ: Quản lý State, Sanitize Data (G110), Timer, Logic Loop
 */

var TDV_Core = {
  // Data Storage
  list: [],
  currentQuestion: null,
  questionTemplate: [],
  missingChars: [],
  blankIndexes: [],
  solutionKey: [], // Lưu đáp án gốc để chấm điểm

  // Game State
  level: 0,
  userResults: [],
  gameStartTime: null,
  submitTimeout: null,
  score: 0,

  // Timer Variables
  timeLimit: 180, // Mặc định 180s
  timeRemaining: 180,
  timerInterval: null,

  // Tracking người chơi
  placedChars: [],
  canSubmit: 0,

  // ==================== 1. DATA LOADING & SETUP ====================

  loadCleanData: function (payload) {
    if (!payload || !payload.items) return;
    this.setupGame(payload.items);
  },

  loadRawData: function (rawItems) {
    if (!rawItems) return;
    const cleanItems = this.sanitizeData(rawItems);
    this.setupGame(cleanItems);
  },

  setupGame: function (items) {
    this.list = items;
    this.level = 0;
    this.userResults = [];
    this.score = 0;
    this.gameStartTime = new Date();

    // 1. Setup Timer (Lấy từ config câu đầu tiên hoặc mặc định 180s)
    // Đây là Timer tổng cho cả bài thi
    if (items.length > 0 && items[0].time_limit) {
      this.timeLimit = items[0].time_limit;
    } else {
      this.timeLimit = 180;
    }
    this.startTimer(); // <--- BẮT ĐẦU ĐẾM NGAY

    console.log(
      `🧠 [CORE] Game Setup. Loaded ${this.list.length} questions. Timer: ${this.timeLimit}s`,
    );

    this.loadCurrentLevel();

    // 2. Báo hiệu cho C2
    window.TDV_READY = 1;
    console.log("🚩 [CORE] Ready Flag set to 1");

    if (typeof c2_callFunction !== "undefined") {
      c2_callFunction("CMD_LoadGame");
    }
  },

  loadCurrentLevel: function () {
    this.currentQuestion = this.list[this.level];
    if (!this.currentQuestion) return;

    this.questionTemplate = [...(this.currentQuestion.question || [])];
    this.missingChars = [...(this.currentQuestion.options || [])];
    this.solutionKey = this.currentQuestion.solution || [];

    // Tính toán ô trống
    this.blankIndexes = [];
    for (let i = 0; i < this.questionTemplate.length; i++) {
      if (this.questionTemplate[i] === "") this.blankIndexes.push(i);
    }

    // Reset tracking
    this.placedChars = new Array(this.questionTemplate.length).fill("");
    this.canSubmit = 0;

    // Gọi View tính lại layout
    if (window.TDV_View) {
      TDV_View.calculateLayout(this.questionTemplate.length);
    }
  },

  // ==================== 2. TIMER LOGIC (SIMPLE) ====================

  startTimer: function () {
    this.stopTimer(); // Reset nếu đang chạy
    this.timeRemaining = this.timeLimit;

    console.log(`⏱️ Timer Started: ${this.timeRemaining}`);

    this.timerInterval = setInterval(() => {
      if (this.timeRemaining > 0) {
        this.timeRemaining--;
      } else {
        // HẾT GIỜ
        this.stopTimer();
        console.log("⏰ Time Out!");
        if (typeof c2_callFunction !== "undefined") {
          c2_callFunction("CMD_TimeOut");
        }
      }
    }, 1000);
  },

  stopTimer: function () {
    if (this.timerInterval) {
      clearInterval(this.timerInterval);
      this.timerInterval = null;
    }
  },

  getTimeRaw: function () {
    return this.timeRemaining; // Trả về số nguyên (VD: 179)
  },

  // ==================== 3. SANITIZE LOGIC ====================
  sanitizeData: function (rawItems) {
    return rawItems.map((item) => {
      if (item.question && Array.isArray(item.question)) return item;

      // Xóa dấu cách
      let cleanWord = item.word || "";
      cleanWord = cleanWord.replace(/\s+/g, "");

      const parts = item.parts || cleanWord.split("");
      const missingCount = item.missing_letter_count || 1;

      // Random đục lỗ
      let indices = Array.from({ length: parts.length }, (_, i) => i);
      for (let i = indices.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [indices[i], indices[j]] = [indices[j], indices[i]];
      }
      const blanks = indices.slice(0, missingCount);

      const questionArr = [...parts];
      const optionsArr = [];

      blanks.forEach((idx) => {
        optionsArr.push(parts[idx]);
        questionArr[idx] = "";
      });

      // Shuffle options
      for (let i = optionsArr.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [optionsArr[i], optionsArr[j]] = [optionsArr[j], optionsArr[i]];
      }

      return {
        id: item.id,
        question: questionArr,
        options: optionsArr,
        solution: parts, // Lưu đáp án gốc để chấm điểm
        audio_url: item.audio_url,
        time_limit: item.time_limit, // Giữ lại config time nếu có
      };
    });
  },

  // ==================== 4. GAMEPLAY ACTIONS ====================

  play: function () {
    if (!this.canSubmit) return;
    if (!this.currentQuestion) return;

    const finalAnswer = this.getPlacedArray();

    // DEV MODE: Giả lập chấm điểm
    if (TDV_Net.mode !== "live") {
      this.simulateLocalCheck(finalAnswer);
    }

    // Gửi kết quả
    const timeSpent = new Date() - this.gameStartTime;
    TDV_Net.sendAnswer(this.currentQuestion.id, finalAnswer, timeSpent);
  },

  onServerResult: function (data) {
    // Lưu kết quả
    this.userResults.push({
      id: data.question_id,
      result: data.correct ? 1 : 0,
    });

    if (data.correct) {
      this.score += 10;
    }

    // Gọi về C2
    if (typeof c2_callFunction !== "undefined") {
      c2_callFunction("CMD_ShowResult", [data.correct ? 1 : 0]);
    }
  },

  nextQuestion: function () {
    if (this.level < this.list.length - 1) {
      this.level++;
      this.loadCurrentLevel();
      return 1; // Còn câu hỏi
    }

    // HẾT GAME -> DỪNG ĐỒNG HỒ
    this.stopTimer();
    console.log("🏁 End Game.");
    return 0;
  },

  // ==================== 5. HELPER LOGIC ====================

  setCharAtSlot: function (char, slotIndex) {
    if (slotIndex < 0 || slotIndex >= this.placedChars.length) return 0;

    // Kiểm tra ghế có người ngồi chưa (Quan trọng để không đè chữ)
    if (this.placedChars[slotIndex] !== "") {
      console.log(`⛔ Slot ${slotIndex} occupied.`);
      return 0;
    }

    this.placedChars[slotIndex] = char;
    this.updateSubmitState();
    return 1;
  },

  clearCharAtSlot: function (slotIndex) {
    if (slotIndex >= 0 && slotIndex < this.placedChars.length) {
      this.placedChars[slotIndex] = "";
      this.updateSubmitState();
    }
  },

  updateSubmitState: function () {
    var required = this.blankIndexes.length;
    var current = this.placedChars.filter((c) => c !== "").length;
    this.canSubmit = current === required ? 1 : 0;
  },

  getPlacedArray: function () {
    var result = [];
    for (var i = 0; i < this.questionTemplate.length; i++) {
      if (this.isBlankIndex(i)) {
        result.push(this.placedChars[i] || "");
      } else {
        result.push(this.questionTemplate[i]);
      }
    }
    return result;
  },

  // Chấm điểm giả lập (So sánh với Solution Key)
  simulateLocalCheck: function (ansArr) {
    console.log("📝 Check vs Key:", this.solutionKey);
    let isCorrect = true;
    for (let i = 0; i < this.solutionKey.length; i++) {
      if (ansArr[i] !== this.solutionKey[i]) {
        isCorrect = false;
        break;
      }
    }
    setTimeout(() => {
      this.onServerResult({
        question_id: this.currentQuestion.id,
        correct: isCorrect,
      });
    }, 500);
  },

  // Getters
  isBlankIndex: function (i) {
    return this.blankIndexes.indexOf(i) !== -1 ? 1 : 0;
  },
  getCharByIndex: function (i) {
    return this.missingChars[i] || "";
  },
  getCharsCount: function () {
    return this.questionTemplate.length;
  },
  getMissingCharsCount: function () {
    return this.missingChars.length;
  },
  canSubmitAnswer: function () {
    return this.canSubmit;
  },
};

// ============================================================
// BRIDGE CHO C2 (MAPPING) - ĐÃ DỌN DẸP GỌN GÀNG
// ============================================================
window.tdv_sdk = {
  // 1. Gameplay Interaction
  setWordAtSlot: function (char, idx) {
    return TDV_Core.setCharAtSlot(char, idx);
  },
  clearLetterAtSlot: function (idx) {
    TDV_Core.clearCharAtSlot(idx);
  },
  canSubmitAnswer: function () {
    return TDV_Core.canSubmitAnswer();
  },
  submitAnswer: function () {
    TDV_Core.play();
    return 1;
  },
  nextQuestion: function () {
    return TDV_Core.nextQuestion();
  },

  // 2. Data & UI Getters
  getScore: function () {
    return TDV_Core.score;
  },
  getTime: function () {
    return TDV_Core.getTimeRaw();
  }, // Trả về số nguyên đơn giản

  getCharsCount: function () {
    return TDV_Core.getCharsCount();
  },
  getMissingCharsCount: function () {
    return TDV_Core.getMissingCharsCount();
  },

  isPresetSlot: function (i) {
    return !TDV_Core.isBlankIndex(i) ? 1 : 0;
  },
  getDisplayText: function (i) {
    return TDV_View.getDisplayText(i);
  },
  getAnswerText: function (i) {
    return TDV_View.getAnswerText(i);
  },

  // 3. View Getters
  getSlotX: function (i) {
    return TDV_View.getSlotX(i);
  },
  getSlotY: function (i) {
    return TDV_View.getSlotY(i);
  },
  getAnswerX: function (i) {
    return TDV_View.getAnswerX(i);
  },
  getAnswerY: function (i) {
    return TDV_View.getAnswerY(i);
  },
  getAnswerAngle: function (i) {
    return TDV_View.getAnswerAngle(i);
  },
  getScale: function () {
    return TDV_View.getScale();
  },
  getFontSize: function () {
    return TDV_View.getFontSize();
  },
  getAnswerFontSize: function () {
    return TDV_View.getAnswerFontSize();
  },
};

// Public Core ra window
window.TDV_Core = TDV_Core;
console.log("✅ TDV_CORE V2 (Fixed Timer & Cleaned) Loaded!");
