// Feedback (anonymous) + New Vendor Request (placeholder).
//
// ANONYMITY CONTRACT — by design this form captures ZERO identifying information:
// no name, email, member ID, IP, timestamp-as-identity, or hidden fields. The only
// data submitted is the comment text and an optional category, posted to a dedicated
// Google Sheet. The page is MemberSpace-gated for access, but nothing about the
// member is attached to the submission. (Gating is wired as the final step.)

const FEEDBACK_CATEGORIES = ["No category", "Suppliers & partners", "Air & travel", "Payments & commissions", "Website / portal", "Events", "Something else"];

function FeedbackPage({ compact }) {
  const [comment, setComment] = React.useState("");
  const [category, setCategory] = React.useState(FEEDBACK_CATEGORIES[0]);
  const [sent, setSent] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState("");
  const [focus, setFocus] = React.useState(false);
  const pad = compact ? "22px 18px 60px" : "48px 64px 96px";
  const max = compact ? "100%" : 760;

  async function submit(e) {
    e.preventDefault();
    if (sending) return;
    const text = comment.trim();
    if (!text) return;
    setError("");
    setSending(true);
    try {
      // Send ONLY the comment — no identity, no member info, no category. The
      // server adds an anonymous timestamp; nothing identifying ever leaves here.
      const res = await fetch("/api/feedback", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ feedback: text }),
      });
      let data = {};
      try { data = await res.json(); } catch (e2) {}
      if (!res.ok || !data.success) {
        throw new Error((data && data.message) || "Submission failed. Please try again.");
      }
      setSent(true);
      setComment("");
      setCategory(FEEDBACK_CATEGORIES[0]);
      window.scrollTo(0, 0);
    } catch (err) {
      setError((err && err.message) || "We couldn't submit your feedback. Please try again.");
    } finally {
      setSending(false);
    }
  }

  return (
    <div style={{ padding: pad, maxWidth: max, margin: "0 auto" }}>
      <div style={{ marginBottom: 12 }}>
        <div className="rdb-eyebrow" style={{ marginBottom: 14 }}>Backstage · Your voice</div>
        <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: compact ? 30 : 48, letterSpacing: "-0.02em", color: "var(--fg-1)", margin: 0, lineHeight: 1.02 }}>Anonymous Feedback</h1>
      </div>

      {/* Anonymity assurance */}
      <div style={{ position: "relative", background: "var(--rdb-gold-faint)", border: "1px solid rgba(201,168,76,0.40)", padding: compact ? "16px 16px 16px 20px" : "18px 22px 18px 26px", margin: "22px 0 8px", overflow: "hidden" }}>
        <span style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: 3, background: "var(--rdb-gold)" }} />
        <div style={{ display: "flex", gap: 14 }}>
          <Icon name="shield-check" size={20} color="var(--rdb-gold)" style={{ flexShrink: 0, marginTop: 1 }} />
          <div style={{ fontFamily: "var(--font-body)", fontSize: 13.5, lineHeight: 1.6, color: "var(--fg-2)" }}>
            This is genuinely anonymous. We collect <span style={{ color: "var(--fg-1)", fontWeight: 600 }}>only your comment</span> — no name, email, member ID, or hidden tracking is attached to your submission. Share candidly; we can't tell who sent it, and we read every note.
          </div>
        </div>
      </div>

      <div style={{ height: 1, background: "var(--rdb-gold-soft)", margin: compact ? "22px 0" : "28px 0 30px" }} />

      {sent ? (
        <div style={{ border: "1px solid rgba(201,168,76,0.4)", background: "var(--rdb-gold-faint)", padding: "32px 28px", display: "flex", alignItems: "center", gap: 16 }}>
          <Icon name="check-circle" size={26} color="var(--success)" />
          <div>
            <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 18, color: "var(--fg-1)" }}>Thank you — your anonymous feedback has been submitted.</div>
            <div style={{ fontFamily: "var(--font-body)", fontSize: 13, color: "var(--fg-2)", marginTop: 4 }}>Nothing identifying was sent with it. <a onClick={() => setSent(false)} style={{ color: "var(--rdb-gold)", cursor: "pointer" }}>Leave another note</a>.</div>
          </div>
        </div>
      ) : (
        <form onSubmit={submit}>
          <div style={{ display: "flex", flexDirection: "column", gap: 7, marginBottom: 20 }}>
            <label style={{ fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 11, letterSpacing: "0.06em", color: "var(--fg-2)" }}>Category <span style={{ fontFamily: "var(--font-mono)", fontWeight: 400, fontSize: 10, color: "var(--ink-6)", letterSpacing: 0, marginLeft: 6 }}>optional</span></label>
            <select value={category} onChange={e => setCategory(e.target.value)} style={{
              width: "100%", maxWidth: compact ? "100%" : 320, boxSizing: "border-box", background: "var(--ink-0)", border: "1px solid var(--ink-3)",
              color: "var(--fg-1)", fontFamily: "var(--font-body)", fontSize: 14, padding: "11px 13px", outline: "none", borderRadius: 2, cursor: "pointer",
            }}>
              {FEEDBACK_CATEGORIES.map(c => <option key={c}>{c}</option>)}
            </select>
          </div>

          <div style={{ display: "flex", flexDirection: "column", gap: 7 }}>
            <label style={{ fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 11, letterSpacing: "0.06em", color: "var(--fg-2)" }}>Your comment <span style={{ color: "var(--rdb-gold)", marginLeft: 4 }}>*</span></label>
            <textarea
              value={comment} onChange={e => setComment(e.target.value)}
              onFocus={() => setFocus(true)} onBlur={() => setFocus(false)}
              rows={compact ? 7 : 6} placeholder="What's working, what isn't, what would help you do your job better…"
              style={{ width: "100%", boxSizing: "border-box", background: "var(--ink-0)",
                border: "1px solid " + (focus ? "var(--rdb-gold)" : "var(--ink-3)"),
                color: "var(--fg-1)", fontFamily: "var(--font-body)", fontSize: 14, lineHeight: 1.6,
                padding: "13px 15px", outline: "none", borderRadius: 2, resize: "vertical", transition: "border-color 140ms" }} />
          </div>

          {error && <FormError message={error} compact={compact} />}

          <div style={{ display: "flex", alignItems: "center", gap: 16, marginTop: 24, flexWrap: "wrap" }}>
            <Button variant="primary" size="lg" type="submit" icon={<Icon name="send" size={15} />} disabled={sending || !comment.trim()}>{sending ? "Submitting…" : "Submit anonymously"}</Button>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 7, fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--ink-6)" }}>
              <Icon name="lock" size={12} color="var(--ink-6)" />No identity attached
            </span>
          </div>
        </form>
      )}
    </div>
  );
}

// ---- New Vendor Request — submits to keyholders@rdbvip.com via Web3Forms ----
// Field set finalized by RDB (Lizzie): vendor name, type/description, website,
// the contractor's contact name + email, and the vendor form Excel attachment.
const VENDOR_FIELDS = [
  { id: "vendorName",   label: "Vendor name",          type: "text",  ph: "Company / supplier name" },
  { id: "website",      label: "Vendor website",       type: "text",  ph: "https://" },
  { id: "contactName",  label: "Vendor contact name",  type: "text",  ph: "Who is requesting this vendor", hint: "Your name" },
  { id: "contactEmail", label: "Vendor contact email", type: "email", ph: "you@rdbvip.com", hint: "Your email" },
];

function VendorRequestPage({ compact }) {
  const [sent, setSent] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState("");
  const formRef = React.useRef(null);
  const pad = compact ? "22px 18px 60px" : "48px 64px 96px";
  const maxW = compact ? "100%" : 880;

  async function submit(e) {
    e.preventDefault();
    if (sending) return;
    setError("");
    setSending(true);
    try {
      const fd = new FormData(formRef.current);
      let file = null;
      const raw = {};
      for (const [k, v] of fd.entries()) {
        if (v instanceof File) { if (v && v.size) file = v; }
        else raw[k] = v;
      }
      const fields = {};
      VENDOR_FIELDS.forEach(f => { fields[f.label] = raw[f.id] || ""; });
      fields["Vendor type / brief description"] = raw.vendorType || "";
      await rdbSubmitForm({
        formType: "vendor",
        from_name: "RDB Backstage — New Vendor Request",
        subject: "New Vendor Request — RDB Backstage",
        replyto: raw.contactEmail || "",
        fields,
        file,
      });
      if (formRef.current) formRef.current.reset();
      setSent(true);
      window.scrollTo(0, 0);
    } catch (err) {
      setError((err && err.message) || "We couldn't submit your request. Please try again.");
    } finally {
      setSending(false);
    }
  }

  return (
    <div style={{ padding: pad, maxWidth: maxW, margin: "0 auto" }}>
      <div style={{ marginBottom: 12 }}>
        <div className="rdb-eyebrow" style={{ marginBottom: 14 }}>Backstage · Forms</div>
        <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: compact ? 28 : 44, letterSpacing: "-0.02em", color: "var(--fg-1)", margin: 0, lineHeight: 1.04 }}>New Vendor Request</h1>
      </div>

      <AdminVerifyReminder compact={compact} />

      {/* Purpose */}
      <div style={{ display: "flex", flexDirection: "column", gap: 14, margin: compact ? "18px 0 8px" : "22px 0 10px", maxWidth: 640 }}>
        <p style={{ fontFamily: "var(--font-body)", fontSize: compact ? 14 : 15, lineHeight: 1.6, color: "var(--fg-2)", margin: 0 }}>
          Use this form to request a new vendor be set up with RDB. Tell us who they are and attach the completed vendor form (Excel) — RDB will review and follow up at the contact email you provide.
        </p>
      </div>

      {/* Attachment callout (Nova gold left-border pattern) */}
      <div style={{ position: "relative", background: "var(--rdb-gold-faint)", border: "1px solid rgba(201,168,76,0.40)", padding: compact ? "14px 16px 14px 20px" : "16px 20px 16px 24px", margin: "18px 0 8px", overflow: "hidden" }}>
        <span style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: 3, background: "var(--rdb-gold)" }} />
        <div style={{ display: "flex", gap: 12 }}>
          <Icon name="alert-circle" size={17} color="var(--rdb-gold)" style={{ flexShrink: 0, marginTop: 1 }} />
          <div style={{ fontFamily: "var(--font-body)", fontSize: 13, lineHeight: 1.6, color: "var(--fg-2)" }}>
            The completed vendor form (Excel) is required — please attach it in its original format so RDB can process the setup.
          </div>
        </div>
      </div>

      <div style={{ height: 1, background: "var(--rdb-gold-soft)", margin: compact ? "22px 0" : "28px 0 32px" }} />

      {sent ? (
        <div style={{ border: "1px solid rgba(201,168,76,0.4)", background: "var(--rdb-gold-faint)", padding: "32px 28px", display: "flex", alignItems: "center", gap: 16 }}>
          <Icon name="check-circle" size={26} color="var(--success)" />
          <div>
            <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 18, color: "var(--fg-1)" }}>Request submitted</div>
            <div style={{ fontFamily: "var(--font-body)", fontSize: 13, color: "var(--fg-2)", marginTop: 4 }}>RDB will review the new vendor and follow up at the email provided.</div>
          </div>
        </div>
      ) : (
        <form ref={formRef} onSubmit={submit}>
          <div style={{ display: "grid", gridTemplateColumns: compact ? "1fr" : "1fr 1fr", gap: compact ? 16 : 20 }}>
            {VENDOR_FIELDS.map(f => <FormField key={f.id} f={f} />)}
          </div>

          {/* Vendor type / description — full width */}
          <div style={{ marginTop: compact ? 16 : 20, display: "flex", flexDirection: "column", gap: 7 }}>
            <label style={{ fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 11, letterSpacing: "0.06em", color: "var(--fg-2)" }}>
              Vendor type / brief description<span style={{ color: "var(--rdb-gold)", marginLeft: 4 }}>*</span>
            </label>
            <textarea name="vendorType" rows={compact ? 4 : 3} placeholder="What does this vendor do? A sentence or two is fine." style={{
              width: "100%", boxSizing: "border-box", background: "var(--ink-0)", border: "1px solid var(--ink-3)",
              color: "var(--fg-1)", fontFamily: "var(--font-body)", fontSize: 14, padding: "11px 13px",
              outline: "none", borderRadius: 2, resize: "vertical",
            }} />
          </div>

          {/* Excel upload — full width */}
          <div style={{ marginTop: compact ? 16 : 20 }}>
            <UploadField
              inputName="vendorForm"
              label="Vendor form"
              hint="The completed vendor form, original format"
              placeholder="Attach the vendor form"
              formats="Excel (.xls or .xlsx) · up to 10 MB"
              accept=".xls,.xlsx,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            />
          </div>

          {error && <FormError message={error} compact={compact} />}

          <div style={{ display: "flex", alignItems: "center", gap: 18, marginTop: 28, flexWrap: "wrap" }}>
            <Button variant="primary" size="lg" type="submit" disabled={sending} icon={<Icon name="send" size={15} />}>{sending ? "Submitting…" : "Submit request"}</Button>
            <span style={{ fontFamily: "var(--font-body)", fontSize: 12, color: "var(--ink-6)" }}>
              <span style={{ color: "var(--rdb-gold)" }}>*</span> Required field
            </span>
          </div>
        </form>
      )}
    </div>
  );
}

Object.assign(window, { FeedbackPage, VendorRequestPage });
