// 客服信箱 — 讀 support@duidui.app 的 Gmail 收件匣（IMAP）並直接回覆（SMTP）

const fmtMailDate = (s) => {
  if (!s) return "";
  try {
    return new Date(s).toLocaleString("zh-TW", {
      month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit",
      hour12: false, timeZone: "Asia/Taipei",
    });
  } catch { return ""; }
};

const SupportPage = () => {
  const toast = useToast();
  const [state, setState] = useState({ loading: true, notConfigured: false, address: "", messages: [], error: "" });
  const [selectedUid, setSelectedUid] = useState(null);
  const [detail, setDetail] = useState(null);
  const [loadingDetail, setLoadingDetail] = useState(false);
  const [reply, setReply] = useState("");
  const [sending, setSending] = useState(false);

  const load = async () => {
    setState(s => ({ ...s, loading: true, error: "" }));
    try {
      const res = await fetch("/api/admin/support-inbox", { credentials: "include" });
      const data = await res.json();
      if (!res.ok) { setState({ loading: false, notConfigured: false, address: "", messages: [], error: data.error || "載入失敗" }); return; }
      setState({ loading: false, notConfigured: !!data.notConfigured, address: data.address || "", messages: data.messages || [], error: "" });
    } catch {
      setState({ loading: false, notConfigured: false, address: "", messages: [], error: "連線失敗" });
    }
  };

  useEffect(() => { load(); }, []);

  const openMsg = async (uid) => {
    setSelectedUid(uid);
    setDetail(null);
    setReply("");
    setLoadingDetail(true);
    try {
      const res = await fetch(`/api/admin/support-inbox/${uid}`, { credentials: "include" });
      const data = await res.json();
      if (!res.ok) { toast({ title: "讀取失敗", message: data.error || "請稍後再試", icon: "alert" }); setLoadingDetail(false); return; }
      setDetail(data);
      // 本地標記已讀
      setState(s => ({ ...s, messages: s.messages.map(m => m.uid === uid ? { ...m, seen: true } : m) }));
    } catch {
      toast({ title: "讀取失敗", message: "連線錯誤", icon: "alert" });
    } finally {
      setLoadingDetail(false);
    }
  };

  const sendReply = async () => {
    if (!detail || !reply.trim() || sending) return;
    // 客服信的寄件人是 noreply@duidui.app（已驗證網域），真正該回覆的用戶信箱在 Reply-To；
    // 優先用 replyTo，退而求其次才用 from。
    const replyTarget = detail.replyTo?.address || detail.from?.address;
    if (!replyTarget) { toast({ title: "無法回覆", message: "這封信沒有可回覆的用戶地址", icon: "alert" }); return; }
    setSending(true);
    try {
      const res = await fetch("/api/admin/support-inbox/reply", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({
          to: replyTarget,
          subject: detail.subject,
          text: reply.trim(),
          inReplyTo: detail.messageId,
          references: detail.references,
          uid: detail.uid,
        }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) { toast({ title: "回覆失敗", message: data.error || "請稍後再試", icon: "alert" }); setSending(false); return; }
      toast({ title: "已送出回覆", message: `已寄給 ${replyTarget}`, icon: "check" });
      setReply("");
      setState(s => ({ ...s, messages: s.messages.map(m => m.uid === detail.uid ? { ...m, seen: true, answered: true } : m) }));
    } catch {
      toast({ title: "回覆失敗", message: "連線錯誤", icon: "alert" });
    } finally {
      setSending(false);
    }
  };

  return (
    <div className="fade-in">
      <PageHeader
        title={<span style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <Icon name="mail" size={22} /> 客服信箱
        </span>}
        subtitle={state.address ? `${state.address} · 收件匣最近 30 封` : "support@duidui.app 收件與回覆"}
        actions={<Button variant="secondary" icon="refresh" onClick={load} disabled={state.loading}>重新整理</Button>}
      />

      {state.notConfigured ? (
        <Card style={{ marginTop: 8 }}>
          <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 10 }}>尚未設定客服信箱連線</div>
          <div style={{ fontSize: 13.5, color: "var(--ink-3)", lineHeight: 1.9 }}>
            請在 Cloud Run 服務加上環境變數後重新部署：
            <ul style={{ margin: "10px 0 0 18px" }}>
              <li><code>SUPPORT_IMAP_USER</code> = support@duidui.app</li>
              <li><code>SUPPORT_IMAP_PASS</code> = Google「應用程式密碼」（需先開兩步驗證後於 Google 帳戶產生，不是登入密碼）</li>
            </ul>
            <div style={{ marginTop: 10 }}>預設走 Gmail 的 imap.gmail.com:993 / smtp.gmail.com:465，若非 Gmail 可另設 SUPPORT_IMAP_HOST / SUPPORT_SMTP_HOST。</div>
          </div>
        </Card>
      ) : state.error ? (
        <Card style={{ marginTop: 8 }}>
          <div style={{ fontSize: 14, color: "var(--danger)" }}>{state.error}</div>
          <div style={{ marginTop: 12 }}><Button variant="secondary" icon="refresh" onClick={load}>再試一次</Button></div>
        </Card>
      ) : (
        <div style={{ display: "flex", gap: 16, marginTop: 8, alignItems: "flex-start", flexWrap: "wrap" }}>
          {/* 列表 */}
          <div style={{ flex: "1 1 340px", minWidth: 300, maxWidth: 440 }}>
            <Card padding={0}>
              {state.loading ? (
                <div style={{ padding: 40, textAlign: "center", color: "var(--ink-4)", fontSize: 13 }}>載入中…</div>
              ) : state.messages.length === 0 ? (
                <div style={{ padding: 40, textAlign: "center", color: "var(--ink-4)", fontSize: 13 }}>收件匣沒有信件</div>
              ) : (
                <div>
                  {state.messages.map((m, i) => {
                    const active = m.uid === selectedUid;
                    return (
                      <button
                        key={m.uid}
                        onClick={() => openMsg(m.uid)}
                        style={{
                          width: "100%", textAlign: "left", padding: "12px 14px", cursor: "pointer",
                          background: active ? "var(--surface-2)" : "transparent",
                          borderTop: i === 0 ? "none" : "1px solid var(--border)",
                          display: "flex", flexDirection: "column", gap: 3,
                        }}
                      >
                        <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                          {!m.seen && <span style={{ width: 8, height: 8, borderRadius: 4, background: "var(--accent, #A7664B)", flexShrink: 0 }} />}
                          <span style={{ fontSize: 13.5, fontWeight: m.seen ? 500 : 700, color: "var(--ink)", flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{m.fromName}</span>
                          <span style={{ fontSize: 11, color: "var(--ink-4)", flexShrink: 0 }}>{fmtMailDate(m.date)}</span>
                        </div>
                        <div style={{ fontSize: 12.5, color: m.seen ? "var(--ink-3)" : "var(--ink)", fontWeight: m.seen ? 400 : 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{m.subject}</div>
                      </button>
                    );
                  })}
                </div>
              )}
            </Card>
          </div>

          {/* 內文 + 回覆 */}
          <div style={{ flex: "2 1 420px", minWidth: 320 }}>
            <Card>
              {!selectedUid ? (
                <div style={{ padding: 40, textAlign: "center", color: "var(--ink-4)", fontSize: 13 }}>← 從左側選一封信閱讀與回覆</div>
              ) : loadingDetail ? (
                <div style={{ padding: 40, textAlign: "center", color: "var(--ink-4)", fontSize: 13 }}>讀取中…</div>
              ) : detail ? (
                <div>
                  <div style={{ fontSize: 16, fontWeight: 700, color: "var(--ink)", marginBottom: 8 }}>{detail.subject}</div>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 8, paddingBottom: 12, borderBottom: "1px solid var(--border)", marginBottom: 14 }}>
                    <div style={{ fontSize: 13, color: "var(--ink-3)" }}>
                      <span style={{ fontWeight: 600, color: "var(--ink)" }}>{detail.from?.name || detail.from?.address || "(未知)"}</span>
                      {detail.from?.address && <span style={{ color: "var(--ink-4)" }}> · {detail.from.address}</span>}
                    </div>
                    <div style={{ fontSize: 12, color: "var(--ink-4)", flexShrink: 0 }}>{fmtMailDate(detail.date)}</div>
                  </div>
                  <div style={{ fontSize: 14, lineHeight: 1.8, color: "var(--ink)", whiteSpace: "pre-wrap", wordBreak: "break-word", maxHeight: 360, overflow: "auto" }}>
                    {detail.text}
                  </div>

                  <div style={{ marginTop: 18, paddingTop: 16, borderTop: "1px solid var(--border)" }}>
                    <div style={{ fontSize: 12, fontWeight: 600, color: "var(--ink-3)", marginBottom: 8 }}>
                      回覆給 {detail.replyTo?.address || detail.from?.address || "(無寄件地址)"}
                    </div>
                    <textarea
                      value={reply}
                      onChange={e => setReply(e.target.value)}
                      placeholder="輸入回覆內容…"
                      rows={6}
                      style={{
                        width: "100%", borderRadius: 10, border: "1px solid var(--border)",
                        padding: "10px 12px", fontSize: 13.5, lineHeight: 1.7, resize: "vertical",
                        outline: "none", background: "var(--surface)", color: "var(--ink)", fontFamily: "inherit",
                      }}
                    />
                    <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 10 }}>
                      <Button variant="primary" icon="mail" onClick={sendReply} disabled={sending || !reply.trim() || !(detail.replyTo?.address || detail.from?.address)}>
                        {sending ? "傳送中…" : "送出回覆"}
                      </Button>
                    </div>
                  </div>
                </div>
              ) : (
                <div style={{ padding: 40, textAlign: "center", color: "var(--ink-4)", fontSize: 13 }}>讀取失敗</div>
              )}
            </Card>
          </div>
        </div>
      )}
    </div>
  );
};

window.SupportPage = SupportPage;
