// =============================================================
// ContactWidget — 联系作者 / 反馈
//  · 右下角浮动小图标（桌面）+ 设置里入口（移动端也能用）
//  · 优先用 FormSubmit 把留言直接发到作者邮箱；失败兜底用 mailto
//  · 作者邮箱可在 config.js 用 CONTACT_EMAIL 覆盖，默认见下
// =============================================================
const XM_CONTACT_EMAIL = (window.XM_CONFIG && window.XM_CONFIG.CONTACT_EMAIL) || "boyangwei2002@163.com";

const ContactModal = ({ open, onClose }) => {
  const [msg, setMsg] = useState("");
  const [contact, setContact] = useState("");
  const [status, setStatus] = useState("idle"); // idle | sending | sent | error
  useEffect(() => { if (!open) { setMsg(""); setContact(""); setStatus("idle"); } }, [open]);

  const brandName = (window.XM_BRAND && window.XM_BRAND.name) || "小抹";
  const mailtoHref = `mailto:${XM_CONTACT_EMAIL}?subject=${encodeURIComponent(brandName + " 反馈")}`
    + `&body=${encodeURIComponent(msg + (contact ? `\n\n我的联系方式：${contact}` : ""))}`;

  // 主路径：直接写进作者的 Supabase（couple_id 由 RLS 默认值自动填）。
  const send = async () => {
    if (!msg.trim() || status === "sending") return;
    setStatus("sending");
    try {
      const { error } = await window.xm.sb.from("feedback").insert({
        message: msg.trim(),
        contact: contact.trim() || null,
        brand: brandName,
      });
      setStatus(error ? "error" : "sent");
    } catch (e) {
      setStatus("error");
    }
  };

  return (
    <Modal open={open} onClose={onClose} title="说点什么给作者 ♡">
      {status === "sent" ? (
        <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 12, padding: "10px 0 4px" }}>
          <div style={{ fontSize: 40 }}>💌</div>
          <div style={{ font: "600 16px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#4A2A1A" }}>收到啦，谢谢你 ♡</div>
          <div style={{ font: "400 13px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#8B6B43", textAlign: "center", lineHeight: 1.7 }}>
            你的每一条留言我都会认真看。
          </div>
          <div style={{ marginTop: 4 }}><Button onClick={onClose}>好的 ♡</Button></div>
        </div>
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <div style={{ font: "400 13px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#8B6B43", lineHeight: 1.7 }}>
            有想改进的地方、或者想要的新功能？写给我吧，我会积极看每一封 ♡
          </div>
          <Field label="想说的话" multiline value={msg} onChange={(e) => setMsg(e.target.value)} placeholder="比如：希望能加一个一起听歌的小角落…"/>
          <Field label="你的联系方式（选填，方便我回复你）" value={contact} onChange={(e) => setContact(e.target.value)} placeholder="微信 / 邮箱，留不留都行"/>

          {status === "error" && (
            <div style={{ font: "400 12px 'Jiangcheng Yuan', 'PingFang SC', sans-serif", color: "#C44A2E", lineHeight: 1.6 }}>
              直接发送没成功（可能是网络）——点「用邮件发送」一样能送到我这儿。
            </div>
          )}

          <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", alignItems: "center", flexWrap: "wrap" }}>
            <Button variant="ghost" onClick={onClose}>取消</Button>
            <a href={mailtoHref} style={{ textDecoration: "none" }}>
              <Button variant="secondary">用邮件发送</Button>
            </a>
            <Button onClick={send} disabled={!msg.trim() || status === "sending"}>
              {status === "sending" ? "发送中…" : "发送 ♡"}
            </Button>
          </div>
          <div style={{ font: "400 11px 'Quicksand', 'Jiangcheng Yuan', sans-serif", color: "#B5946D", textAlign: "right", letterSpacing: "0.04em" }}>
            作者邮箱：{XM_CONTACT_EMAIL}
          </div>
        </div>
      )}
    </Modal>
  );
};

const ContactButton = ({ onClick }) => (
  <button onClick={onClick} aria-label="联系作者" title="联系作者 / 反馈" style={{
    position: "fixed", right: 22, bottom: 22, zIndex: 300,
    width: 48, height: 48, borderRadius: 999, border: "none", cursor: "pointer",
    background: "linear-gradient(135deg,#FFF1D4 0%,#FBE3B0 100%)",
    boxShadow: "0 6px 18px rgba(184,133,46,0.30), inset 0 0 0 1px rgba(255,255,255,0.7)",
    display: "inline-flex", alignItems: "center", justifyContent: "center",
    transition: "transform 140ms ease",
  }}
  onMouseDown={(e) => { e.currentTarget.style.transform = "scale(0.94)"; }}
  onMouseUp={(e) => { e.currentTarget.style.transform = "scale(1)"; }}
  onMouseLeave={(e) => { e.currentTarget.style.transform = "scale(1)"; }}>
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#8B4F32" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="5" width="18" height="14" rx="2.4"/>
      <path d="m3.5 6.5 8.5 6 8.5-6"/>
    </svg>
  </button>
);

Object.assign(window, { ContactModal, ContactButton, XM_CONTACT_EMAIL });
