/* global React, window */
// M4 (A-4): Actionable «not useful» feedback.
// Opens a Modal with structured reasons + free text, submits, fires a Toast.
// Replaces the dead-end "Was this helpful?" thumbs widget.

const { useState } = React;

const REASONS = [
  {
    id: "off_persona",
    en: "Off-target persona — doesn't match my actual audience",
    zh: "Persona 不对 —— 跟我真实的受众对不上",
  },
  {
    id: "bad_example",
    en: "Bad example — the reference creative doesn't help",
    zh: "示例不好 —— 参考创意没什么帮助",
  },
  {
    id: "wrong_metric",
    en: "Wrong metric — this rec optimizes for the wrong thing",
    zh: "指标不对 —— 这条建议在优化错的指标",
  },
  {
    id: "already_tried",
    en: "Already tried — we tested this and it didn't work",
    zh: "已经试过 —— 我们之前测过没效果",
  },
  {
    id: "other",
    en: "Other (please describe below)",
    zh: "其他(下方描述)",
  },
];

function FeedbackModal({ open, rec, ad, onClose, onSubmit }) {
  const { Icon } = window;
  const t = window.useT();
  const isZh = window.getLang() === "zh";
  const [reason, setReason] = useState(null);
  const [text, setText] = useState("");
  const [submitting, setSubmitting] = useState(false);

  if (!open) return null;

  function reset() {
    setReason(null);
    setText("");
    setSubmitting(false);
  }
  function handleClose() {
    reset();
    onClose();
  }
  function handleSubmit() {
    if (!reason) return;
    setSubmitting(true);
    // Simulated network — real impl would POST to /feedback
    setTimeout(() => {
      onSubmit({ reasonId: reason, text, recId: rec?.id, adId: ad?.id });
      reset();
    }, 500);
  }

  const r = REASONS.find(x => x.id === reason);

  return (
    <div
      className={"modal-scrim " + (open ? "open" : "")}
      onClick={handleClose}
      style={{ position: "fixed", zIndex: 150 }}
    >
      <div
        className="modal"
        onClick={e => e.stopPropagation()}
        style={{ width: 540, padding: 0 }}
      >
        <div style={{
          padding: "18px 22px 12px",
          borderBottom: "1px solid var(--rule)",
        }}>
          <div className="label" style={{ color: "var(--accent)", marginBottom: 6 }}>
            {t("FEEDBACK · TUNES YOUR ACCOUNT", "反馈 · 会调整你的账号偏好")}
          </div>
          <div className="t-h1" style={{ fontSize: 22, marginBottom: 4 }}>
            {t(`Help us tune this for ${window.BRAND?.name || "your account"}.`, `帮我们为 ${window.BRAND?.name || "你的账号"} 调整这条建议。`)}
          </div>
          <div style={{ fontSize: 12, color: "var(--ink-3)", lineHeight: 1.55 }}>
            {t(
              "Your feedback de-prioritizes this type of recommendation for similar ads. We never share it across accounts.",
              "你的反馈会让同类型广告里这种建议降权。我们绝不会跨账号共享你的反馈。"
            )}
          </div>
        </div>

        <div style={{ padding: "16px 22px 0" }}>
          <div className="label" style={{ marginBottom: 8 }}>{t("What's wrong with this rec?", "这条建议哪里不对?")}</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
            {REASONS.map(opt => {
              const isSelected = reason === opt.id;
              return (
                <button
                  key={opt.id}
                  onClick={() => setReason(opt.id)}
                  style={{
                    textAlign: "left",
                    padding: "10px 12px",
                    border: isSelected ? "1.5px solid var(--accent)" : "1px solid var(--rule)",
                    borderRadius: 4,
                    background: isSelected ? "var(--accent-tint)" : "var(--card)",
                    cursor: "pointer",
                    display: "flex",
                    alignItems: "flex-start",
                    gap: 10,
                    fontSize: 13,
                    color: "var(--ink)",
                    transition: "background .15s, border-color .15s",
                  }}
                >
                  <span style={{
                    minWidth: 16, height: 16, borderRadius: "50%",
                    border: isSelected ? "5px solid var(--accent)" : "1.5px solid var(--rule-strong)",
                    background: "var(--card)",
                    marginTop: 2,
                    flexShrink: 0,
                  }} />
                  <span>{isZh ? opt.zh : opt.en}</span>
                </button>
              );
            })}
          </div>
          <div style={{ marginTop: 14 }}>
            <div className="label" style={{ marginBottom: 6 }}>
              {reason === "other" ? t("Tell us what's off", "告诉我们哪里不对") : t("Add detail (optional)", "补充细节(可选)")}
            </div>
            <textarea
              value={text}
              onChange={e => setText(e.target.value)}
              placeholder={reason === "other" ? t("Describe what was off…", "描述一下哪里不对…") : t("Anything else we should know?", "还有什么想让我们知道的?")}
              style={{
                width: "100%",
                minHeight: 64,
                padding: "8px 10px",
                border: "1px solid var(--rule-strong)",
                borderRadius: 4,
                fontSize: 13,
                fontFamily: "inherit",
                color: "var(--ink)",
                background: "var(--card)",
                resize: "vertical",
              }}
            />
          </div>
        </div>

        <div style={{
          padding: "14px 22px",
          borderTop: "1px solid var(--rule)",
          marginTop: 16,
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          gap: 12,
        }}>
          <span className="mono" style={{ fontSize: 10, color: "var(--ink-3)" }}>
            {t("Sends to model • not shared between accounts", "发送到模型 • 不会跨账号共享")}
          </span>
          <span style={{ display: "inline-flex", gap: 8 }}>
            <button className="btn" onClick={handleClose}>{t("Cancel", "取消")}</button>
            <button
              className="btn primary"
              onClick={handleSubmit}
              disabled={!reason || submitting}
              style={{ opacity: !reason || submitting ? 0.6 : 1 }}
            >
              {submitting ? t("Sending…", "发送中…") : t("Send feedback", "发送反馈")}
            </button>
          </span>
        </div>
      </div>
    </div>
  );
}

// Inline widget that triggers the modal — replaces the dead-end thumbs.
function FeedbackWidget({ rec, ad, onUseful, onNotUseful }) {
  const { Icon } = window;
  const t = window.useT();
  const [given, setGiven] = useState(null); // null | "useful" | "submitted"
  if (given === "useful") {
    return (
      <div
        className="mono"
        style={{
          fontSize: 11,
          color: "var(--grade-a)",
          display: "inline-flex",
          alignItems: "center",
          gap: 6,
          padding: "6px 10px",
          background: "var(--card)",
          border: "1px solid var(--rule)",
          borderRadius: 4,
        }}
      >
        <Icon name="check" size={12} /> {t("Thanks — we'll surface more like this.", "收到 —— 之后会多推这类建议。")}
      </div>
    );
  }
  if (given === "submitted") {
    return (
      <div
        className="mono"
        style={{
          fontSize: 11,
          color: "var(--ink-3)",
          padding: "6px 10px",
        }}
      >
        {t(`Got it — saved for ${window.BRAND?.name || "your account"}.`, `收到 —— 已为 ${window.BRAND?.name || "你的账号"} 保存。`)}
      </div>
    );
  }
  return (
    <div style={{
      display: "inline-flex",
      gap: 6,
      alignItems: "center",
      fontSize: 11,
    }}>
      <span className="mono" style={{ color: "var(--ink-3)", marginRight: 4 }}>
        {t("Was this useful?", "这条有用吗?")}
      </span>
      <button
        className="btn sm"
        onClick={() => { setGiven("useful"); onUseful && onUseful(); }}
        title={t("Useful — we'll surface more like this", "有用 —— 之后会多推这类建议")}
      >
        <Icon name="thumbUp" size={11} /> {t("Useful", "有用")}
      </button>
      <button
        className="btn sm"
        onClick={() => { onNotUseful && onNotUseful(() => setGiven("submitted")); }}
        title={t("Not for me — opens a structured feedback form", "不适合我 —— 打开结构化反馈表单")}
      >
        <Icon name="thumbDown" size={11} /> {t("Not for me", "不适合我")}
      </button>
    </div>
  );
}

Object.assign(window, { FeedbackModal, FeedbackWidget });
