// Forms — Scope (Draft 3 add-on): Commission Research Request Form.
// Fields and copy per RDB spec. A second form (New Vendor Setup) is pending.
// Inputs are native/uncontrolled so they stay directly editable in the wireframe.

const COMMISSION_FIELDS = [
  { id: "sion",      label: "SION Booking number",        type: "text",     ph: "e.g. SN-4821093" },
  { id: "agentName", label: "Agent name",                 type: "text",     ph: "First and last name" },
  { id: "agentEmail",label: "Agent email address",        type: "email",    ph: "you@rdbvip.com" },
  { id: "resName",   label: "Reservation name",           type: "text",     ph: "Name on the reservation" },
  { id: "dates",     label: "Arrival – Departure dates",  type: "text",     ph: "MM/DD/YYYY – MM/DD/YYYY" },
  { id: "vendor",    label: "Vendor name",                type: "text",     ph: "Supplier / property" },
  { id: "vendorConf",label: "Vendor's confirmation number", type: "text",   ph: "Confirmation #" },
  { id: "method",    label: "Vendor's method of payment", type: "select",   options: ["Select method", "TACS", "NPC", "Onyx", "Check", "Other"] },
  { id: "payRef",    label: "Vendor's payment reference or check number", type: "text", ph: "Reference / check #" },
  { id: "payDate",   label: "Vendor's payment date",      type: "date" },
  { id: "checkAmt",  label: "Vendor's check amount",      type: "money",    ph: "0.00" },
  { id: "commAmt",   label: "Your commission amount",     type: "money",    ph: "0.00", hint: "Approximate is fine" },
];

// ── Shared form-submission helpers (used by Commission + Vendor forms) ────────
// Read a File as base64 (without the data-URL prefix) for JSON transport.
function fileToBase64(file) {
  return new Promise((resolve, reject) => {
    const r = new FileReader();
    r.onload = () => { const s = String(r.result || ""); resolve(s.slice(s.indexOf(",") + 1)); };
    r.onerror = () => reject(new Error("Could not read the attached file."));
    r.readAsDataURL(file);
  });
}

// POST a form to the server relay (/api/submit-form), which injects the Web3Forms
// key server-side and emails keyholders@rdbvip.com. Throws on failure.
async function rdbSubmitForm({ formType, from_name, subject, replyto, fields, file }) {
  const payload = { formType, from_name, subject, replyto: replyto || "", fields: fields || {} };
  if (file && file.size) {
    payload.file = { name: file.name, type: file.type || "application/octet-stream", base64: await fileToBase64(file) };
  }
  const res = await fetch("/api/submit-form", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(payload),
  });
  let data = {};
  try { data = await res.json(); } catch (e) {}
  if (!res.ok || !data.success) {
    throw new Error((data && data.message) || "Submission failed. Please try again.");
  }
  return data;
}

// Inline error callout shown when a submission fails (shared by both forms).
function FormError({ message, compact }) {
  return (
    <div role="alert" style={{ position: "relative", background: "rgba(192,57,43,0.08)", border: "1px solid rgba(192,57,43,0.45)", padding: compact ? "13px 15px 13px 19px" : "14px 18px 14px 22px", margin: "24px 0 0", overflow: "hidden" }}>
      <span style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: 3, background: "#C0392B" }} />
      <div style={{ display: "flex", gap: 12, alignItems: "flex-start" }}>
        <Icon name="alert-triangle" size={17} color="#C0392B" style={{ flexShrink: 0, marginTop: 1 }} />
        <div style={{ fontFamily: "var(--font-body)", fontSize: 13, lineHeight: 1.6, color: "var(--fg-1)" }}>{message}</div>
      </div>
    </div>
  );
}

function FormField({ f }) {
  const [focus, setFocus] = React.useState(false);
  const required = f.id !== "notes";
  const baseInput = {
    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,
    padding: "11px 13px", outline: "none", borderRadius: 2,
    transition: "border-color 140ms",
  };
  return (
    <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)" }}>
        {f.label}{required && <span style={{ color: "var(--rdb-gold)", marginLeft: 4 }}>*</span>}
        {f.hint && <span style={{ fontFamily: "var(--font-mono)", fontWeight: 400, fontSize: 10, color: "var(--ink-6)", marginLeft: 8, textTransform: "none", letterSpacing: 0 }}>{f.hint}</span>}
      </label>
      {f.type === "select" ? (
        <select name={f.id} onFocus={() => setFocus(true)} onBlur={() => setFocus(false)} style={{ ...baseInput, cursor: "pointer" }}>
          {f.options.map(o => <option key={o}>{o}</option>)}
        </select>
      ) : f.type === "money" ? (
        <div style={{ position: "relative", display: "flex", alignItems: "center" }}>
          <span style={{ position: "absolute", left: 13, fontFamily: "var(--font-mono)", fontSize: 14, color: "var(--ink-6)" }}>$</span>
          <input name={f.id} type="text" inputMode="decimal" placeholder={f.ph} onFocus={() => setFocus(true)} onBlur={() => setFocus(false)} style={{ ...baseInput, paddingLeft: 26 }} />
        </div>
      ) : (
        <input name={f.id} type={f.type} placeholder={f.ph} onFocus={() => setFocus(true)} onBlur={() => setFocus(false)} style={baseInput} />
      )}
    </div>
  );
}

// Defaults reproduce the Commission "Payment documentation" upload exactly; the
// Vendor form passes its own label/hint/accept/placeholder. `inputName` lets the
// chosen file be captured by the form's FormData on submit.
function UploadField({
  inputName = "payment",
  label = "Payment documentation",
  hint = "Image or PDF of the payment",
  placeholder = "Attach payment documentation",
  formats = "PNG, JPG, or PDF · up to 10 MB",
  accept = "image/*,.pdf",
}) {
  const [name, setName] = React.useState("");
  const [hover, setHover] = React.useState(false);
  return (
    <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)" }}>
        {label}<span style={{ color: "var(--rdb-gold)", marginLeft: 4 }}>*</span>
        <span style={{ fontFamily: "var(--font-mono)", fontWeight: 400, fontSize: 10, color: "var(--ink-6)", marginLeft: 8, textTransform: "none", letterSpacing: 0 }}>{hint}</span>
      </label>
      <label
        onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
        style={{
          display: "flex", alignItems: "center", gap: 14, cursor: "pointer",
          border: "1px dashed " + (hover || name ? "var(--rdb-gold)" : "var(--ink-4)"),
          background: name ? "var(--rdb-gold-faint)" : "var(--ink-0)",
          padding: "18px 20px", borderRadius: 2, transition: "border-color 140ms, background 140ms",
        }}>
        <div style={{ width: 40, height: 40, border: "1px solid " + (name ? "var(--rdb-gold)" : "var(--ink-4)"), display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
          <Icon name={name ? "file-check" : "upload"} size={18} color={name ? "var(--rdb-gold)" : "var(--ink-6)"} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 13, color: "var(--fg-1)" }}>
            {name || placeholder}
          </div>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--ink-6)", marginTop: 3 }}>
            {name ? "Tap to replace" : formats}
          </div>
        </div>
        <span style={{ fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase", color: hover ? "var(--rdb-gold)" : "var(--fg-2)" }}>Browse</span>
        <input name={inputName} type="file" accept={accept} onChange={e => setName(e.target.files[0] ? e.target.files[0].name : "")} style={{ display: "none" }} />
      </label>
    </div>
  );
}

function CommissionForm({ 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;
      }
      // Forward fields under their human labels so the email reads cleanly.
      const fields = {};
      COMMISSION_FIELDS.forEach(f => { fields[f.label] = raw[f.id] || ""; });
      fields["Additional notes"] = raw.notes || "";
      await rdbSubmitForm({
        formType: "commission",
        from_name: "RDB Backstage — Commission Research",
        subject: "Commission Research Request — RDB Backstage",
        replyto: raw.agentEmail || "",
        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 }}>
          Commission Research Request
        </h1>
      </div>

      {/* 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 submit a commission research request for commissions that cannot be found in SION's Unreconciled Commissions. Please complete all required fields to help us process your request.
        </p>
      </div>

      {/* Required-docs 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)" }}>
            Payment documentation from the vendor is required — we can't research a request without proof of payment, and requests submitted without it will be returned.
            <div style={{ marginTop: 8 }}>
              <span style={{ fontWeight: 700, color: "var(--rdb-gold)" }}>Important:</span> a matching booking must already be entered into SION before we can research and post the commission to your account.
            </div>
          </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 Finance will 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 }}>
            {COMMISSION_FIELDS.map(f => <FormField key={f.id} f={f} />)}
          </div>

          {/* Notes — 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)" }}>Additional notes</label>
            <textarea name="notes" rows={compact ? 4 : 3} placeholder="Anything else that will help us locate the commission" 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>

          {/* Upload — full width */}
          <div style={{ marginTop: compact ? 16 : 20 }}>
            <UploadField />
          </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>
  );
}

function FormsPage() { return <CommissionForm />; }
function MobileForms() { return <CommissionForm compact />; }

Object.assign(window, { FormsPage, MobileForms, CommissionForm, FormField, UploadField, FormError, rdbSubmitForm, fileToBase64 });
