/**
 * ============================================================================
 * myclaw-iteration.js — 我卡住了，帮我继续改
 * ============================================================================
 *
 * 功能：
 *   - 在聊天工具栏注入「🤔」按钮
 *   - 弹出两级选择面板（问题 → 行动），动态联动
 *   - 根据选择生成针对性提示词发给 AI
 *
 * 依赖：
 *   - window.VoiceInput（讯飞 SDK，可选，用于语音补充输入）
 *   - window.myclawIteration.init({ trySend }) 在 myclaw-inject.js 初始化时注入
 * ============================================================================
 */
(function () {
  "use strict";

  // ══════════ 配置 ══════════

  var ITERATION_CONFIG = {
    problems: ["样子不对", "逻辑不对", "不够好玩", "缺少创意玩法", "救命我卡住了"],
    actionsByProblem: {
      "样子不对":     ["更好看", "更像我想的", "更清楚", "我还没想好"],
      "逻辑不对":     ["让它有反应", "让它运行正确", "先只改一个功能", "我还没想好"],
      "不够好玩":     ["加一个东西", "加一点互动", "加一个角色", "我还没想好"],
      "缺少创意玩法": ["加一个新机制", "加一个有趣挑战", "加一个惊喜元素", "我还没想好"],
      "救命我卡住了": ["先鼓励我一下", "帮我找卡点", "帮我缩成一步", "直接给我最简单版本"],
    },
  };

  // ══════════ 提示词生成 ══════════

  function buildIterationPrompt(problem, action, extraNote) {
    var note = extraNote && extraNote.trim()
      ? "\n补充说明：" + extraNote.trim()
      : "";

    if (!problem || !action) return "";

    // 第二列选了"我还没想好"：发散模式
    if (action === "我还没想好") {
      return "你是一个帮助学生继续推进项目的助手。\n"
           + "我现在这个作品的问题是【" + problem + "】，\n"
           + "但我还没想好具体要怎么改。\n\n"
           + "请结合我当前正在做的内容，给我 3 个具体、容易执行的改进方向。\n"
           + "要求：\n"
           + "- 每条都要很短\n"
           + "- 每条都要能马上动手\n"
           + "- 不要太复杂\n"
           + "- 最后帮我选 1 个最容易成功的方向\n\n"
           + "输出格式：\n"
           + "方向1：...\n"
           + "方向2：...\n"
           + "方向3：...\n"
           + "建议我先做：..." + note;
    }

    // 逻辑类
    if (problem === "逻辑不对") {
      return "你是一个帮助学生继续推进项目的助手。\n"
           + "我现在这个作品的问题是【" + problem + "】。\n"
           + "我下一步想先【" + action + "】。\n\n"
           + "请根据我当前正在做的内容，只帮我解决一个最小的问题。\n"
           + "要求：\n"
           + "- 只改一个点\n"
           + "- 优先选择最容易成功的做法\n"
           + "- 不要重构，不要大改\n"
           + "- 如果你认为现在应该先缩小范围，也请直接告诉我最小版本应该怎么做\n\n"
           + "输出格式：\n"
           + "先改什么：...\n"
           + "为什么先改这个：...\n"
           + "我可以直接照着做的一句话：..." + note;
    }

    // 样子类
    if (problem === "样子不对") {
      return "你是一个帮助学生继续推进项目的助手。\n"
           + "我现在这个作品的问题是【" + problem + "】。\n"
           + "我下一步想先【" + action + "】。\n\n"
           + "请根据我当前正在做的内容，只帮我做一个最小的视觉改进。\n"
           + "要求：\n"
           + "- 优先改样式、布局、文案、配色、画面感觉\n"
           + "- 不要顺便改很多功能\n"
           + "- 只给我一个最容易成功的下一步\n\n"
           + "输出格式：\n"
           + "先改什么：...\n"
           + "为什么先改这个：...\n"
           + "我可以直接发给 AI 的一句话：..." + note;
    }

    // 好玩类
    if (problem === "不够好玩") {
      return "你是一个帮助学生继续推进项目的助手。\n"
           + "我现在这个作品的问题是【" + problem + "】。\n"
           + "我下一步想先【" + action + "】。\n\n"
           + "请根据我当前正在做的内容，只帮我增加一个最小的有趣点。\n"
           + "要求：\n"
           + "- 只加一个\n"
           + "- 要容易实现\n"
           + "- 不要把项目复杂度一下拉高\n"
           + "- 优先选择能马上看到效果的改动\n\n"
           + "输出格式：\n"
           + "先加什么：...\n"
           + "为什么先加这个：...\n"
           + "我可以直接照着做的一句话：..." + note;
    }

    // 创意类
    if (problem === "缺少创意玩法") {
      return "你是一个帮助学生继续推进项目的助手。\n"
           + "我现在这个作品的问题是【" + problem + "】。\n"
           + "我下一步想先【" + action + "】。\n\n"
           + "请根据我当前正在做的内容，帮我加一个最有创意、又最容易实现的新点子。\n"
           + "要求：\n"
           + "- 只加一个\n"
           + "- 要让人眼前一亮\n"
           + "- 不要做太复杂\n"
           + "- 优先选择不需要大改就能看到效果的\n\n"
           + "输出格式：\n"
           + "先加什么：...\n"
           + "为什么先加这个：...\n"
           + "我可以直接照着做的一句话：..." + note;
    }

    // 卡住类
    if (problem === "救命我卡住了") {
      return "你是一个帮助学生继续推进项目的助手。\n"
           + "学生现在卡住了，下一步想【" + action + "】。\n\n"
           + "请根据当前项目内容，用最温和、最清楚的方式帮他继续推进。\n"
           + "要求：\n"
           + "- 不要给太多任务\n"
           + "- 不要让他大改\n"
           + "- 只给一个最小、最容易成功的下一步\n"
           + "- 用孩子也能看懂的话说\n\n"
           + "输出格式：\n"
           + "我现在最该先做：...\n"
           + "为什么：...\n"
           + "我现在就可以开始做的一句话：..." + note;
    }

    // 兜底
    return "你是一个帮助学生继续推进项目的助手。\n"
         + "我现在这个作品的问题是【" + problem + "】。\n"
         + "我下一步想先【" + action + "】。\n\n"
         + "请根据我当前正在做的内容，帮我只改一个点，\n"
         + "给我一个最简单、最容易成功的下一步方案。\n\n"
         + "要求：\n"
         + "- 只给一个方向\n"
         + "- 不要太复杂\n"
         + "- 不要大改\n"
         + "- 要让我马上能动手\n\n"
         + "输出格式：\n"
         + "先改什么：...\n"
         + "为什么先改这个：...\n"
         + "我可以直接照着做的一句话：..." + note;
  }

  // ══════════ 状态 ══════════

  var promptOpen = false;
  var modalVoiceDestroy = null;
  var _trySend = null;  // 由 myclaw-inject.js 注入

  // ══════════ 工具组件 ══════════

  function makeLabel(text) {
    var el = document.createElement("div");
    el.textContent = text;
    el.style.cssText = "font-size:13px;font-weight:bold;color:#cdd6f4;margin-bottom:8px;font-family:-apple-system,sans-serif;";
    return el;
  }

  function makeChipGroup(items, activeColor, onChange) {
    var wrap = document.createElement("div");
    wrap.style.cssText = "display:flex;flex-wrap:wrap;gap:7px;";
    var chips = [];
    items.forEach(function (label) {
      var chip = document.createElement("button");
      chip.textContent = label;
      chip.dataset.selected = "0";
      chip.style.cssText = [
        "padding:6px 13px",
        "border-radius:20px",
        "border:1.5px solid #3d3d5c",
        "background:#252536",
        "color:#888",
        "font-size:13px",
        "font-family:-apple-system,sans-serif",
        "cursor:pointer",
        "transition:all 0.15s",
        "white-space:nowrap",
      ].join(";");

      function applyStyle(sel) {
        if (sel) {
          chip.style.background  = activeColor;
          chip.style.borderColor = activeColor;
          chip.style.color       = "#fff";
          chip.style.fontWeight  = "bold";
        } else {
          chip.style.background  = "#252536";
          chip.style.borderColor = "#3d3d5c";
          chip.style.color       = "#888";
          chip.style.fontWeight  = "normal";
        }
      }

      chip.onmouseenter = function () {
        if (chip.dataset.selected !== "1") chip.style.borderColor = activeColor;
      };
      chip.onmouseleave = function () {
        if (chip.dataset.selected !== "1") chip.style.borderColor = "#3d3d5c";
      };
      chip.onclick = function () {
        var nowOn = chip.dataset.selected !== "1";
        chips.forEach(function (c) {
          if (c !== chip) {
            c.style.background  = "#252536";
            c.style.borderColor = "#3d3d5c";
            c.style.color       = "#888";
            c.style.fontWeight  = "normal";
            c.dataset.selected  = "0";
          }
        });
        chip.dataset.selected = nowOn ? "1" : "0";
        applyStyle(nowOn);
        onChange(nowOn ? label : "");
      };

      chips.push(chip);
      wrap.appendChild(chip);
    });
    return wrap;
  }

  function makeVoiceInputField(placeholder, maxLength, onChange) {
    var lVoice     = null;
    var lRecording = false;
    var lStopping  = false;

    var wrap = document.createElement("div");
    wrap.style.cssText = "display:flex;gap:8px;align-items:center;width:100%;box-sizing:border-box;";

    var input = document.createElement("input");
    input.type = "text";
    input.maxLength = maxLength || 60;
    input.placeholder = placeholder || "";
    input.style.cssText = [
      "flex:1", "min-width:0", "padding:9px 12px",
      "background:#252536",
      "border:1.5px solid #3d3d5c",
      "border-radius:8px",
      "color:#cdd6f4",
      "font-size:13px",
      "font-family:-apple-system,sans-serif",
      "outline:none",
      "transition:border-color 0.15s, border-left-width 0.1s",
    ].join(";");
    input.onfocus = function () { if (!lRecording) input.style.borderColor = "#6366f1"; };
    input.onblur  = function () { if (!lRecording) input.style.borderColor = "#3d3d5c"; };
    input.oninput = function () { if (onChange) onChange(input.value); };

    var micBtn = document.createElement("button");
    micBtn.type = "button";
    micBtn.title = "语音输入";
    micBtn.style.cssText = [
      "width:34px", "height:34px", "flex-shrink:0",
      "border-radius:50%",
      "border:1.5px solid #3d3d5c",
      "background:#252536",
      "color:#888",
      "cursor:pointer",
      "display:flex", "align-items:center", "justify-content:center",
      "transition:all 0.15s",
      "position:relative",
    ].join(";");
    micBtn.innerHTML = [
      '<svg width="14" height="14" viewBox="0 0 24 24" fill="none"',
      ' stroke="currentColor" stroke-width="2"',
      ' stroke-linecap="round" stroke-linejoin="round">',
      '  <path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"/>',
      '  <path d="M19 10v2a7 7 0 0 1-14 0v-2"/>',
      '  <line x1="12" x2="12" y1="19" y2="22"/>',
      '</svg>',
    ].join("");

    function setUI(recording) {
      if (recording) {
        micBtn.style.background      = "#ff4444";
        micBtn.style.borderColor     = "#ff4444";
        micBtn.style.color           = "#fff";
        micBtn.title                 = "停止录音";
        input.style.borderColor      = "#ff4444";
        input.style.borderLeftWidth  = "3px";
      } else {
        micBtn.style.background      = "#252536";
        micBtn.style.borderColor     = "#3d3d5c";
        micBtn.style.color           = "#888";
        micBtn.title                 = "语音输入";
        input.style.borderColor      = "#3d3d5c";
        input.style.borderLeftWidth  = "1.5px";
      }
    }

    function initLVoice() {
      if (typeof window.VoiceInput === "undefined") return false;
      lVoice = new window.VoiceInput({
        onResult: function (text) {
          if (!lRecording && !lStopping) return;
          input.value = text;
          if (onChange) onChange(text);
        },
        onStatusChange: function (oldS, newS) {
          if (newS === "idle" && lRecording && !lStopping) {
            setTimeout(function () {
              if (lRecording && lVoice) lVoice.start();
            }, 300);
          }
        },
        onError: function (err) {
          console.error("[myclaw-iteration] voice error:", err);
          lRecording = false; lStopping = false;
          setUI(false);
        },
      });
      return true;
    }

    function startLocal() {
      if (!lVoice && !initLVoice()) {
        console.warn("[myclaw-iteration] VoiceInput SDK 未加载");
        return;
      }
      lRecording = true;
      setUI(true);
      lVoice.start();
    }

    function stopLocal() {
      if (!lRecording) return;
      lStopping  = true;
      lRecording = false;
      setUI(false);
      setTimeout(function () {
        lStopping = false;
        if (lVoice) lVoice.stop();
      }, 1500);
    }

    micBtn.onclick = function () {
      if (lRecording) { stopLocal(); } else { startLocal(); }
    };

    wrap.appendChild(input);
    wrap.appendChild(micBtn);

    return {
      el:       wrap,
      getValue: function ()  { return input.value; },
      setValue: function (v) { input.value = v; if (onChange) onChange(v); },
      destroy:  function ()  { if (lRecording) stopLocal(); },
    };
  }

  function insertPromptText(text) {
    var ta = document.querySelector(".agent-chat__input textarea");
    if (!ta) return;

    var start = ta.selectionStart || 0;
    var end   = ta.selectionEnd   || 0;
    var current  = ta.value;
    var newValue = current.substring(0, start) + text + current.substring(end);

    var setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value").set;
    setter.call(ta, newValue);
    ta.dispatchEvent(new Event("input", { bubbles: true }));

    var newCursor = start + text.length;
    try { ta.setSelectionRange(newCursor, newCursor); } catch (e) {}
    ta.focus();
  }

  // ══════════ Modal ══════════

  function openPromptModal() {
    if (document.querySelector("#myclaw-prompt-modal")) return;
    promptOpen = true;

    var iconBtn = document.querySelector("#myclaw-prompt-btn");
    if (iconBtn) iconBtn.style.color = "#6366f1";

    var state = { problem: "", action: "", note: "" };

    function buildText() {
      return buildIterationPrompt(state.problem, state.action, state.note);
    }

    function buildPayload() {
      return {
        type:           "iteration_helper",
        problem:        state.problem,
        next_action:    state.action,
        extra_note:     state.note,
        generated_text: buildText(),
      };
    }

    var previewEl, actionSendBtn, actionInsertBtn;
    function refresh() {
      var text  = buildText();
      var ready = !!(state.problem && state.action);
      if (previewEl) {
        previewEl.textContent = text || "先选上面两项，这里会自动生成要发给 AI 的内容 ✨";
        previewEl.style.color = ready ? "#cdd6f4" : "#555";
      }
      if (actionSendBtn) {
        actionSendBtn.disabled     = !ready;
        actionSendBtn.style.opacity = ready ? "1" : "0.4";
        actionSendBtn.style.cursor  = ready ? "pointer" : "not-allowed";
      }
      if (actionInsertBtn) {
        actionInsertBtn.disabled     = !ready;
        actionInsertBtn.style.opacity = ready ? "1" : "0.4";
        actionInsertBtn.style.cursor  = ready ? "pointer" : "not-allowed";
      }
    }

    // ── 遮罩 ──
    var overlay = document.createElement("div");
    overlay.id = "myclaw-prompt-modal";
    overlay.style.cssText = [
      "position:fixed", "top:0", "left:0",
      "width:100vw", "height:100vh",
      "background:rgba(0,0,0,0.45)",
      "z-index:99998",
      "display:flex", "align-items:center", "justify-content:center",
      "animation:myclaw-fade-in 0.15s ease",
    ].join(";");

    // ── 弹框 ──
    var box = document.createElement("div");
    box.style.cssText = [
      "width:560px", "max-width:96vw", "max-height:92vh",
      "background:#1e1e2e",
      "border-radius:12px",
      "overflow:hidden",
      "display:flex", "flex-direction:column",
      "box-shadow:0 12px 48px rgba(0,0,0,0.6)",
    ].join(";");

    // ── 标题栏 ──
    var header = document.createElement("div");
    header.style.cssText = [
      "display:flex", "align-items:center", "justify-content:space-between",
      "padding:13px 18px",
      "background:linear-gradient(135deg,#6366f1,#8b5cf6)",
      "color:#fff",
      "font-size:15px", "font-weight:bold",
      "font-family:-apple-system,sans-serif",
      "user-select:none", "flex-shrink:0",
    ].join(";");
    header.innerHTML = "<span>🤔 我卡住了，帮我继续改</span>";
    var closeX = document.createElement("span");
    closeX.textContent = "✕";
    closeX.style.cssText = "cursor:pointer;padding:2px 8px;border-radius:4px;font-size:15px;transition:background 0.15s;";
    closeX.onmouseenter = function () { closeX.style.background = "rgba(255,255,255,0.2)"; };
    closeX.onmouseleave = function () { closeX.style.background = "none"; };
    closeX.onclick = function () { closePromptModal(); };
    header.appendChild(closeX);

    // ── 内容区 ──
    var scroll = document.createElement("div");
    scroll.style.cssText = "flex:1;overflow-y:auto;padding:20px 20px 8px;display:flex;flex-direction:column;gap:20px;";

    // 第1区：问题
    var sec1 = document.createElement("div");
    sec1.appendChild(makeLabel("只改一点选什么？"));
    sec1.appendChild(makeChipGroup(ITERATION_CONFIG.problems, "#f59e0b", function (val) {
      state.problem = val;
      state.action  = "";
      renderActionChips();
      refresh();
    }));
    scroll.appendChild(sec1);

    // 第2区：行动（动态联动）
    var sec2 = document.createElement("div");
    sec2.appendChild(makeLabel("你想怎么改？"));
    var actionChipsWrap = document.createElement("div");
    sec2.appendChild(actionChipsWrap);
    sec2.style.display = "none";
    scroll.appendChild(sec2);

    function renderActionChips() {
      actionChipsWrap.innerHTML = "";
      var actions = ITERATION_CONFIG.actionsByProblem[state.problem];
      if (!actions) { sec2.style.display = "none"; return; }
      sec2.style.display = "";
      actionChipsWrap.appendChild(makeChipGroup(actions, "#6366f1", function (val) {
        state.action = val; refresh();
      }));
    }

    // 第3区：补充
    var sec3 = document.createElement("div");
    sec3.appendChild(makeLabel("你的补充很关键！"));
    var placeholders = ["比如：我想做成飞行射击", "比如：我想更像小猫主题", "比如：按钮点了以后想有变化"];
    var noteField = makeVoiceInputField(
      placeholders[Math.floor(Math.random() * placeholders.length)],
      60,
      function (val) { state.note = val; refresh(); }
    );
    modalVoiceDestroy = noteField.destroy;
    sec3.appendChild(noteField.el);
    scroll.appendChild(sec3);

    // 预览区
    var previewWrap = document.createElement("div");
    previewWrap.style.cssText = [
      "padding:12px 14px",
      "background:#252536",
      "border-radius:8px",
      "border-left:3px solid #6366f1",
    ].join(";");
    var previewLabel = document.createElement("div");
    previewLabel.textContent = "将要发给 AI 的内容：";
    previewLabel.style.cssText = "font-size:11px;color:#6366f1;font-weight:bold;margin-bottom:6px;font-family:monospace;letter-spacing:0.3px;";
    previewEl = document.createElement("div");
    previewEl.style.cssText = "font-size:13px;line-height:1.7;white-space:pre-wrap;font-family:-apple-system,sans-serif;word-break:break-all;";
    previewWrap.appendChild(previewLabel);
    previewWrap.appendChild(previewEl);
    scroll.appendChild(previewWrap);

    // ── 底部按钮 ──
    var footer = document.createElement("div");
    footer.style.cssText = [
      "display:flex", "gap:10px",
      "padding:14px 20px",
      "border-top:1px solid #2d2d3f",
      "flex-shrink:0",
      "background:#1e1e2e",
    ].join(";");

    actionSendBtn = document.createElement("button");
    actionSendBtn.textContent = "➤ 直接发给 AI";
    actionSendBtn.disabled = true;
    actionSendBtn.style.cssText = [
      "flex:1", "padding:11px 0",
      "background:#10b981", "color:#fff",
      "border:none", "border-radius:8px",
      "font-size:14px", "font-weight:bold",
      "font-family:-apple-system,sans-serif",
      "cursor:not-allowed", "transition:all 0.15s", "opacity:0.4",
    ].join(";");
    actionSendBtn.onmouseenter = function () { if (!actionSendBtn.disabled) actionSendBtn.style.background = "#059669"; };
    actionSendBtn.onmouseleave = function () { if (!actionSendBtn.disabled) actionSendBtn.style.background = "#10b981"; };
    actionSendBtn.onclick = function () {
      if (actionSendBtn.disabled) return;
      var payload = buildPayload();
      console.log("[myclaw-iteration] onSendDirect", payload);
      insertPromptText(payload.generated_text);
      closePromptModal();
      setTimeout(function () { if (_trySend) _trySend(); }, 50);
    };

    actionInsertBtn = document.createElement("button");
    actionInsertBtn.textContent = "⬇ 先放到聊天框";
    actionInsertBtn.disabled = true;
    actionInsertBtn.style.cssText = [
      "flex:1", "padding:11px 0",
      "background:#6366f1", "color:#fff",
      "border:none", "border-radius:8px",
      "font-size:14px", "font-weight:bold",
      "font-family:-apple-system,sans-serif",
      "cursor:not-allowed", "transition:all 0.15s", "opacity:0.4",
    ].join(";");
    actionInsertBtn.onmouseenter = function () { if (!actionInsertBtn.disabled) actionInsertBtn.style.background = "#4f46e5"; };
    actionInsertBtn.onmouseleave = function () { if (!actionInsertBtn.disabled) actionInsertBtn.style.background = "#6366f1"; };
    actionInsertBtn.onclick = function () {
      if (actionInsertBtn.disabled) return;
      var payload = buildPayload();
      console.log("[myclaw-iteration] onInsertToInput", payload);
      insertPromptText(payload.generated_text);
      closePromptModal();
    };

    footer.appendChild(actionSendBtn);
    footer.appendChild(actionInsertBtn);

    box.appendChild(header);
    box.appendChild(scroll);
    box.appendChild(footer);
    overlay.appendChild(box);
    overlay.onclick = function (e) { if (e.target === overlay) closePromptModal(); };
    document.body.appendChild(overlay);

    refresh();
  }

  function closePromptModal() {
    if (modalVoiceDestroy) { modalVoiceDestroy(); modalVoiceDestroy = null; }
    var modal = document.querySelector("#myclaw-prompt-modal");
    if (modal) modal.remove();
    promptOpen = false;

    var btn = document.querySelector("#myclaw-prompt-btn");
    if (btn) btn.style.color = "";
  }

  // ══════════ 触发按钮 ══════════

  function createPromptButton() {
    var btn = document.createElement("button");
    btn.id = "myclaw-prompt-btn";
    btn.className = "agent-chat__input-btn";
    btn.title = "我卡住了，帮我继续改";
    btn.setAttribute("aria-label", "我卡住了，帮我继续改");
    btn.innerHTML = [
      '<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18"',
      '  viewBox="0 0 24 24" fill="none" stroke="currentColor"',
      '  stroke-width="2" stroke-linecap="round" stroke-linejoin="round">',
      '  <circle cx="12" cy="12" r="10"/>',
      '  <path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/>',
      '  <line x1="12" y1="17" x2="12.01" y2="17"/>',
      '</svg>',
    ].join("");

    btn.addEventListener("click", function (e) {
      e.stopPropagation();
      if (promptOpen) {
        closePromptModal();
      } else {
        openPromptModal();
      }
    });

    return btn;
  }

  // ══════════ 对外接口 ══════════

  window.myclawIteration = {
    init: function (deps) {
      if (deps && deps.trySend) _trySend = deps.trySend;
    },
    createButton: createPromptButton,
    open:  openPromptModal,
    close: closePromptModal,
    isOpen: function () { return promptOpen; },
  };
})();
