﻿// SupportChatPage - 用户端客服小强聊天页
const { useState, useEffect, useRef } = React;

var h = React.createElement;

var NK_BLUE = "#1677ff";
var NK_BLUE_LIGHT = "#e6f4ff";
var BG_GRAY = "#F8FAFC";


function isGarbledText(txt) {
  if (!txt) return false;
  var s = String(txt);
  return s.indexOf("\uFFFD") >= 0;
}

function formatTime(dateStr) {
  if (!dateStr) return "";
  try {
    var d = new Date(dateStr);
    if (isNaN(d.getTime())) return dateStr;
    var now = new Date();
    var diffDays = Math.floor((now - d) / 86400000);
    var hh = ("0" + d.getHours()).slice(-2);
    var mm = ("0" + d.getMinutes()).slice(-2);
    if (diffDays === 0) return hh + ":" + mm;
    if (diffDays === 1) return "昨天 " + hh + ":" + mm;
    var month = d.getMonth() + 1;
    var day = d.getDate();
    return month + "月" + day + "日" + hh + ":" + mm;
  } catch(e) { return dateStr; }
}

function SupportChatPage() {
  var _conv = useState(null); var conv = _conv[0], setConv = _conv[1];
  var _msgs = useState([]); var msgs = _msgs[0], setMsgs = _msgs[1];
  var _input = useState(""); var input = _input[0], setInput = _input[1];
  var _sending = useState(false); var sending = _sending[0], setSending = _sending[1];
  var _loading = useState(true); var loading = _loading[0], setLoading = _loading[1];
  var _error = useState(""); var error = _error[0], setError = _error[1];
  var _initFail = useState(false); var initFail = _initFail[0], setInitFail = _initFail[1];
  var _sourceInfo = useState(null); var sourceInfo = _sourceInfo[0], setSourceInfo = _sourceInfo[1];
  var _previewImageUrl = useState(null); var previewImageUrl = _previewImageUrl[0], setPreviewImageUrl = _previewImageUrl[1];
  var msgEndRef = useRef(null);
  var pollTimerRef = useRef(null);
  var isLeavingRef = useRef(false);
  var socketCleanupRef = useRef(null);
  var socketConvIdRef = useRef(0);
  var supportOrderCardSentRef = useRef(false);
    function renderCardMessage(msg) {
    var cd = null;
    try { cd = typeof msg.card_data === "string" ? JSON.parse(msg.card_data) : (msg.card_data || {}); } catch(e) { cd = {}; }
    // card_data is empty or invalid
    if (!cd || Object.keys(cd).length === 0) {
      return h("div", { className: "im-card-msg", style: { maxWidth: "75%", padding: "12px 16px" } },
        h("div", { style: { fontSize: 13, color: "#94a3b8", textAlign: "center" } }, "卡片数据异常")
      );
    }
    if (msg.msg_type === "account_card") {
      return h("div", { className: "im-card-msg", style: { maxWidth: "75%" } },
        h("div", { className: "im-card-badge im-card-badge-account" }, "账号咨询"),
        h("div", { className: "im-card-body" },
          cd.cover ? h("img", { className: "im-card-cover", src: cd.cover, onError: function(e) { e.target.style.display = "none"; } }) : null,
          h("div", { className: "im-card-info" },
            h("div", { className: "im-card-title" }, cd.title || "-"),
            h("div", { className: "im-card-price" }, "¥" + (cd.price || 0)),
            h("div", { className: "im-card-meta" },
              cd.server ? h("span", { className: "im-card-meta-item" }, "服务器: " + cd.server) : null,
              cd.seller_nickname ? h("span", { className: "im-card-meta-item" }, (cd.server ? h("span", { className: "im-card-meta-divider" }, "|") : null), "卖家: " + cd.seller_nickname) : null
            )
          )
        ),
        cd.product_id ? h("div", { className: "im-card-action" },
          h("button", { className: "im-card-btn", onClick: function() { NK.Store.navigate("detail",{id:cd.product_id}); } }, "查看账号详情")
        ) : null
      );
    }
    if (msg.msg_type === "order_card") {
      var isAccountOrder = cd.card_type === "account_order";
      var isEscortOrder = cd.card_type === "escort_order";
      return h("div", { className: "im-card-msg", style: { maxWidth: "75%" } },
        h("div", { className: "im-card-badge im-card-badge-order" },
          h("span", null, "订单咨询"),
          h("span", { className: "im-card-subtype" }, isAccountOrder ? "账号订单" : isEscortOrder ? "护航订单" : "服务订单")
        ),
        h("div", { className: "im-card-body" },
          cd.cover ? h("img", { className: "im-card-cover", src: cd.cover, onError: function(e) { e.target.style.display = "none"; } }) : null,
          h("div", { className: "im-card-info" },
            h("div", { className: "im-card-title" }, cd.title || "-"),
            h("div", { className: "im-card-price" }, "¥" + (cd.price || 0)),
            cd.server ? h("div", { className: "im-card-meta" }, "服务器: " + cd.server) : null,
            cd.consultation_type ? h("div", { className: "im-card-meta", style:{ color:"#D92D20", fontWeight:600 } }, "咨询类型：" + cd.consultation_type) : null,
            h("div", { className: "im-card-meta" }, (((cd.order_status_text || cd.status_text) && !isGarbledText(cd.order_status_text || cd.status_text)) ? (isEscortOrder ? "状态: " : "") + (cd.order_status_text || cd.status_text) : "")),
            cd.order_no ? h("div", { className: "im-card-order-no" }, "订单号: " + cd.order_no) : null
          )
        ),
        cd.order_id || cd.id ? h("div", { className: "im-card-action" },
          h("button", { className: "im-card-btn", onClick: function() {
            var orderId = cd.order_id || cd.id;
            if (isAccountOrder) {
              NK.Store.navigate("tradeRoom", { orderId: orderId, source: "supportChat" });
            } else {
              var detailRole = pageParams.role === "booster" ? "booster" : "buyer";
              if (NK.Store.openEscortOrderDetailNative && NK.Store.openEscortOrderDetailNative(orderId, detailRole, { source: "supportChat" })) return;
              NK.Store.navigate("escortOrderDetail", { orderId: orderId, role: detailRole, source: "supportChat" });
            }
          } }, "查看订单详情")
        ) : null
      );
    }
    if (msg.msg_type === "escort_service_card") {
      return h("div", { className: "im-card-msg", style: { maxWidth: "75%" } },
        h("div", { className: "im-card-badge im-card-badge-escort" }, "护航服务咨询"),
        h("div", { className: "im-card-body" },
          cd.cover ? h("img", { className: "im-card-cover", src: cd.cover, onError: function(e) { e.target.style.display = "none"; } }) : null,
          h("div", { className: "im-card-info" },
            h("div", { className: "im-card-title" }, cd.title || "-"),
            h("div", { className: "im-card-price" }, "¥" + (cd.price || 0)),
            cd.summary ? h("div", { className: "im-card-meta" }, cd.summary) : null,
            cd.assignment_label ? h("div", { className: "im-card-meta" }, "派单方式: " + cd.assignment_label) : null,
            cd.booster_nickname ? h("div", { className: "im-card-meta" }, "服务打手: " + cd.booster_nickname) : null,
            cd.server ? h("div", { className: "im-card-meta" }, "适用区服: " + cd.server) : null,
            cd.service_type ? h("div", { className: "im-card-meta" }, "服务类型: " + cd.service_type) : null
          )
        ),
        cd.service_id ? h("div", { className: "im-card-action" },
          h("button", { className: "im-card-btn", onClick: function() { NK.Store.navigate("escortDetail",{id:cd.service_id}); } }, "查看服务详情")
        ) : null
      );
    }
    return null;
  }

var pageParams = NK.Store.get("pageParams") || {};
  var presetConversationId = pageParams.conversationId;
  function loadConversationMessages(convId) {
    setLoading(true);
    NK.Api.Im.messages(convId, { after_id: 0, limit: 50 }).then(function(msgRes) {
      if (msgRes.code === 0) {
        setMsgs(normalizeUniqueMessages(msgRes.data));
        var msgsArr = msgRes.data || [];
        if (msgsArr.length > 0) {
          var lastId = msgsArr[msgsArr.length - 1].id;
          NK.Api.Im.markRead(convId, { last_read_message_id: lastId });
        } else { NK.Api.Im.markRead(convId, {}); }
      }
      setLoading(false);
    }).catch(function() { setLoading(false); setError("消息加载失败"); });
  }

  function normalizeUniqueMessages(list) {
    var seen = {};
    return (Array.isArray(list) ? list : [])
      .filter(function(item) {
        if (!item || item.id == null) return false;
        var key = String(item.id);
        if (seen[key]) return false;
        seen[key] = true;
        return true;
      })
      .sort(function(a, b) {
        return Number(a.id) - Number(b.id);
      });
  }

  function appendUniqueMessages(incoming) {
    var incomingList = Array.isArray(incoming) ? incoming : [incoming];
    setMsgs(function(prev) {
      var seen = {};
      prev.forEach(function(item) {
        if (item && item.id != null) {
          seen[String(item.id)] = true;
        }
      });
      var additions = [];
      incomingList.forEach(function(item) {
        if (!item || item.id == null) return;
        var key = String(item.id);
        if (seen[key]) return;
        seen[key] = true;
        additions.push(item);
      });
      if (!additions.length) return prev;
      var next = prev.concat(additions);
      next.sort(function(a, b) {
        return Number(a.id) - Number(b.id);
      });
      return next;
    });
  }

  function connectSocket(convId) {
    if (!convId) return;
    var token = (NK.Api && NK.Api.getToken) ? NK.Api.getToken() : "";
    if (!token) return;
    if (typeof NK.UserImSocket === "undefined") return;

    var prevConvId = socketConvIdRef.current;
    if (prevConvId > 0 && prevConvId !== convId) {
      NK.UserImSocket.leaveConversation(prevConvId);
    }
    socketConvIdRef.current = convId;

    NK.UserImSocket.connect(token);

    if (socketCleanupRef.current) {
      socketCleanupRef.current();
      socketCleanupRef.current = null;
    }

    var offNewMsg = NK.UserImSocket.on("im:new_message", function(data) {
      if (!data || !data.message || !data.message.id) return;
      if (data.conversation_id !== convId) return;
      appendUniqueMessages(data.message);
    });

    var offConnect = NK.UserImSocket.on("connect", function() {
      NK.UserImSocket.joinConversation(convId);
    });

    socketCleanupRef.current = function() {
      offNewMsg();
      offConnect();
    };

    if (NK.UserImSocket.isConnected()) {
      NK.UserImSocket.joinConversation(convId);
    }
  }

  function initConversation() {
    setLoading(true); setError(""); setInitFail(false);
    var escortAftersaleOrderId = Number(pageParams.orderId || 0);
    var shouldSendEscortOrderCard = pageParams.source === "escort_order" && pageParams.serviceType === "aftersale" && escortAftersaleOrderId > 0;
    if (shouldSendEscortOrderCard && !supportOrderCardSentRef.current) {
      supportOrderCardSentRef.current = true;
      NK.Api.Im.sendEscortOrderCard({
        order_id: escortAftersaleOrderId,
        action: pageParams.consultationType === "escort_cancel" ? "cancel_consultation" : "contact_support",
        source: "escort_order_detail"
      }).then(function(res) {
        if (!res || res.code !== 0 || !res.data) throw new Error((res && res.message) || "订单卡片发送失败");
        var responseData = res.data;
        var conversationData = responseData.conversation || {};
        var convId = Number(responseData.conversation_id || conversationData.id || conversationData.conversation_id || 0);
        if (!convId) throw new Error("售后会话初始化失败");
        setConv(Object.assign({}, conversationData, { id: convId, type: "aftersale_service", title: "客服小强" }));
        loadConversationMessages(convId);
        startPolling(convId);
        connectSocket(convId);
      }).catch(function(err) {
        supportOrderCardSentRef.current = false;
        setLoading(false);
        setInitFail(true);
        setError((err && err.message) || "售后会话初始化失败");
      });
      return;
    }
    if (presetConversationId) {
      var convId = presetConversationId;
      var convData = pageParams.conversationData || {};
      if (convData.conversation_id || convData.id) {
        setConv({ id: convData.conversation_id || convData.id, type: convData.type || "presale_service", title: convData.display_title || "客服小强", avatar: convData.avatar || "", last_message: convData.last_message || "", last_message_type: convData.last_message_type || "", last_message_at: convData.last_message_at || null, status: 1, unread_count: 0 });
      } else { setConv({ id: convId, type: "presale_service", title: "客服小强" }); }
      if (convData.source_label === "护航售前咨询" || convData.type === "escort_consult" || convData.source_label === "售前客服" || convData.type === "presale_service") {
        setSourceInfo({ source_label: convData.source_label || "护航售前咨询", product_title: convData.service_title || "", product_cover: convData.service_cover || "", product_server: convData.service_summary || "", product_price: convData.service_price || "", seller_nickname: "", seller_phone: "" });
      }
      loadConversationMessages(convId);
      startPolling(convId);
      connectSocket(convId);
      return;
    }
    NK.Api.Im.getOrCreatePresale().then(function(res) {
      if (res.code === 0) { setConv(res.data); return res.data.id; }
      else { setInitFail(true); setLoading(false); return null; }
    }).then(function(convId) { if (convId) { loadConversationMessages(convId); startPolling(convId); connectSocket(convId); } });
  }

  function startPolling(convId) {
    if (pollTimerRef.current) clearInterval(pollTimerRef.current);
    var lastMsgId = 0;
    pollTimerRef.current = setInterval(function() {
      NK.Api.Im.messages(convId, { after_id: lastMsgId }).then(function(res) {
        if (res.code === 0 && Array.isArray(res.data) && res.data.length > 0) {
          // Mark new messages as read
          var lastNew = res.data[res.data.length - 1];
          if (lastNew && lastNew.id) {
            NK.Api.Im.markRead(convId, { last_read_message_id: lastNew.id }).catch(function() {});
          }
          appendUniqueMessages(res.data);
            if (res.data.length > 0) lastMsgId = res.data[res.data.length - 1].id;
        }
      }).catch(function() {});
    }, 3000);
  }

  function sendMessage() {
    var text = input.trim();
    if (!text) { alert("请输入消息内容"); return; }
    if (!conv) return;
    var convId = conv.id || conv.conversation_id;
    if (!convId) return;
    setSending(true);
    NK.Api.Im.sendMessage(convId, { msg_type: "text", content: text }).then(function(res) {
      if (res.code === 0 && res.data) { try { appendUniqueMessages(res.data); } catch(e) {} setInput(""); }
      else { alert("发送失败，请重试"); }
    }).catch(function() { alert("发送失败，请重试"); }).finally(function() { setSending(false); });
  }

  function handleSelectImage() {
    var inputEl = document.createElement("input");
    inputEl.type = "file"; inputEl.accept = "image/*";
    inputEl.onchange = function(e) {
      var file = e.target.files[0];
      if (!file) return;
      var formData = new FormData();
      formData.append("image", file);
      var convId = conv && (conv.id || conv.conversation_id);
      if (!convId) return;
      NK.Api.Im.uploadImage(formData).then(function(res) {
        if (res.code === 0 && res.data && res.data.url) {
          NK.Api.Im.sendMessage(convId, { msg_type: "image", image_url: res.data.url }).then(function(msgRes) {
            if (msgRes.code === 0 && msgRes.data) { appendUniqueMessages(msgRes.data); }
            else { alert("发送失败，请重试"); }
          }).catch(function() { alert("发送失败，请重试"); });
        } else { alert("上传失败"); }
      }).catch(function() { alert("上传失败"); });
    };
    inputEl.click();
  }

  function goBack() {
    isLeavingRef.current = true;
    if (pollTimerRef.current) { clearInterval(pollTimerRef.current); pollTimerRef.current = null; }
    if (socketCleanupRef.current) { socketCleanupRef.current(); socketCleanupRef.current = null; }
    if (typeof NK.UserImSocket !== "undefined") { NK.UserImSocket.disconnect(); }
    socketConvIdRef.current = 0;
    NK.Store.back();
  }
  useEffect(function() {
    initConversation();
    return function() {
      isLeavingRef.current = true;
      if (pollTimerRef.current) { clearInterval(pollTimerRef.current); pollTimerRef.current = null; }
      if (socketCleanupRef.current) { socketCleanupRef.current(); socketCleanupRef.current = null; }
      if (typeof NK.UserImSocket !== "undefined") { NK.UserImSocket.disconnect(); }
      socketConvIdRef.current = 0;
    };
  }, []);

  useEffect(function() {
    if (msgEndRef.current) msgEndRef.current.scrollIntoView({ behavior: "smooth" });
  }, [msgs]);

  if (initFail) {
    return h("div", { style: { textAlign: "center", padding: 40, color: "#94A3B8", fontSize: 14 } }, "初始化失败，请稍后重试");
  }
  return h("div", { style: { height: "100vh", display: "flex", flexDirection: "column", background: BG_GRAY } },
    h("div", { style: { padding: "16px", background: "#fff", borderBottom: "1px solid #f0f0f0", display: "flex", alignItems: "center" } },
      h("span", { style: { fontSize: 18, cursor: "pointer", marginRight: 12, color: "#333", padding: "4px 8px" }, onClick: goBack }, "←"),
      h("span", { style: { fontSize: 17, fontWeight: 600, color: "#1E293B" } }, (conv && conv.title) || "客服小强")
    ),
    error ? h("div", { style: { padding: "8px 16px", background: "#fff2f0", color: "#ff4d4f", fontSize: 13, textAlign: "center", borderBottom: "1px solid #ffccc7" } }, error) : null,
    sourceInfo ? h("div", { style: { margin: "8px 12px", padding: "10px 12px", background: "#f0f9ff", borderRadius: 12, border: "1px solid #bae6fd", display: "flex", gap: 10, alignItems: "center" } },
      sourceInfo.product_cover ? h("img", { src: sourceInfo.product_cover, style: { width: 44, height: 44, borderRadius: 8, objectFit: "cover", flexShrink: 0 }, onError: function(e) { e.target.style.display = "none"; } }) : h("span", { style: { fontSize: 18 } }, "💎"),
      h("div", { style: { flex: 1, minWidth: 0 } },
        sourceInfo.product_title ? h("div", { style: { fontSize: 13, fontWeight: 600, color: "#1E293B", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", marginBottom: 2 } }, sourceInfo.product_title) : null,
        h("div", { style: { fontSize: 11, color: "#64748B" } }, (sourceInfo.source_label || "账号售前咨询") + (sourceInfo.product_server ? " · " + sourceInfo.product_server : ""))
      )
    ) : null,
    loading ? h("div", { style: { flex: 1, display: "flex", alignItems: "center", justifyContent: "center", color: "#94A3B8", fontSize: 14 } }, "加载中...") :
    h("div", { style: { flex: 1, overflowY: "auto", padding: "16px", paddingBottom: 8 } },
      msgs.map(function(msg, idx) {
        var isMine = msg.sender_role === "buyer";
        var isSystem = msg.sender_role === "system";
        if (isSystem) {
          return h("div", { key: msg.id || idx, style: { textAlign: "center", margin: "12px 0" } }, h("span", { style: { fontSize: 12, color: "#94A3B8", background: "#f0f0f0", padding: "4px 12px", borderRadius: 10, display: "inline-block" } }, msg.content || ""));
        }
        return h("div", { key: msg.id || idx, style: { display: "flex", flexDirection: "column", alignItems: isMine ? "flex-end" : "flex-start", marginBottom: 12 } },
          msg.msg_type === "text"
            ? h("div", { style: { maxWidth: "75%", padding: "10px 14px", borderRadius: 12, fontSize: 15, lineHeight: 1.5, background: isMine ? NK_BLUE : "#fff", color: isMine ? "#fff" : "#1E293B", boxShadow: "0 1px 3px rgba(0,0,0,0.06)" } }, msg.content || "")
            : (msg.msg_type === "image" && msg.image_url
              ? h("img", { src: msg.image_url, style: { maxWidth: "70%", maxHeight: 200, borderRadius: 10, border: "1px solid #e8e8e8", objectFit: "contain", cursor: "pointer" }, onClick: function() { setPreviewImageUrl(msg.image_url); }, onLoad: function() { scrollToBottom(); } })
              : (msg.msg_type === "account_card" || msg.msg_type === "escort_service_card" || msg.msg_type === "order_card")
              ? renderCardMessage(msg)
              : null),
          h("span", { style: { fontSize: 10, color: "#94A3B8", marginTop: 4 } }, formatTime(msg.created_at))
        );
      }),
      h("div", { ref: msgEndRef })
    ),
    !loading ? h("div", { style: { borderTop: "1px solid #e8e8e8", background: "#fff", padding: "8px 12px", paddingBottom: "calc(8px + env(safe-area-inset-bottom, 0px))", display: "flex", alignItems: "center", gap: 8 } },
      h("span", { onClick: handleSelectImage, style: { fontSize: 22, cursor: "pointer", color: "#94A3B8", padding: "4px", flexShrink: 0 } }, "📷"),
      h("input", { type: "text", value: input, placeholder: "请输入消息", onChange: function(e) { setInput(e.target.value); }, onKeyDown: function(e) { if (e.key === "Enter") sendMessage(); }, disabled: sending, style: { flex: 1, border: "1px solid #d9d9d9", borderRadius: 20, padding: "8px 14px", fontSize: 14, outline: "none", background: "#f5f5f5" } }),
      h("button", { onClick: sendMessage, disabled: sending || !input.trim(), style: { padding: "8px 16px", background: input.trim() ? NK_BLUE : "#d9d9d9", color: "#fff", border: "none", borderRadius: 20, fontSize: 13, fontWeight: 600, cursor: (sending || !input.trim()) ? "not-allowed" : "pointer", flexShrink: 0 } }, "发送")
    ) : null,
    previewImageUrl ? h("div", { key: "image-preview", onClick: function() { setPreviewImageUrl(null); }, style: { position: "fixed", inset: 0, background: "rgba(0,0,0,0.85)", display: "flex", justifyContent: "center", alignItems: "center", zIndex: 2000, cursor: "pointer" } }, h("img", { src: previewImageUrl, style: { maxWidth: "90%", maxHeight: "90%", objectFit: "contain", borderRadius: 4 } })) : null
  );
}

window.NK = window.NK || {};
NK.SupportChatPage = SupportChatPage;
