// ════════════════════════════════════════════════════════════════
// Contact page — v2 preview React components.
// The form logic (field set, the /api/contact POST, success/error/loading
// handling, and the honeypot) is reused VERBATIM from contact/sections.jsx —
// only the markup is restyled with the v2 design system (.v2-input/.v2-label).
// Reuses the shared system: Nav, Eyebrow, Section, Footer.
// ════════════════════════════════════════════════════════════════

const CONTACT_API = window.CONTACT_API_URL || "/api/contact";

const CONTACT_TOPICS = [
  "General enquiry",
  "Sales & pricing",
  "Technical support",
  "Billing",
  "Partnership or press",
];

// ===== Contact form — reused logic, v2 styling =====
function ContactFormV2() {
  // `website` is a honeypot. Hidden visually and from keyboard/assistive tech;
  // any value submitted means a bot filled the form and the server silently
  // drops the message. Real users never touch it.
  const [form, setForm] = React.useState({ name: "", email: "", topic: CONTACT_TOPICS[0], message: "", website: "" });
  const [status, setStatus] = React.useState("idle"); // idle | sending | success | error
  const [errorMsg, setErrorMsg] = React.useState("");

  function set(field) { return e => setForm(f => ({ ...f, [field]: e.target.value })); }

  async function submit(e) {
    e.preventDefault();
    setStatus("sending");
    setErrorMsg("");
    try {
      const res = await fetch(CONTACT_API, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(form),
      });
      const data = await res.json();
      if (res.ok && data.success) {
        setStatus("success");
      } else {
        setErrorMsg(data.error || "Something went wrong. Please try again.");
        setStatus("error");
      }
    } catch (_) {
      setErrorMsg("Could not reach the server. Please try again shortly.");
      setStatus("error");
    }
  }

  if (status === "success") {
    return (
      <div className="v2-form-success">
        <div className="v2-form-success-mark">✓</div>
        <h3 style={{ fontSize: 22, fontWeight: 700, letterSpacing: "-.02em", margin: "0 0 10px" }}>Message sent!</h3>
        <p style={{ fontSize: 15, color: "var(--ink-2)", lineHeight: 1.6, maxWidth: 320, margin: "0 auto" }}>
          Thanks, <strong>{form.name}</strong>. We'll reply to <strong>{form.email}</strong> within one business day.
        </p>
        <button
          type="button"
          className="btn btn-ghost btn-md"
          style={{ marginTop: 24 }}
          onClick={() => { setForm({ name: "", email: "", topic: CONTACT_TOPICS[0], message: "", website: "" }); setStatus("idle"); }}
        >
          Send another message
        </button>
      </div>
    );
  }

  return (
    <form onSubmit={submit} className="v2-form">
      {/*
        Honeypot: off-screen text input that legitimate users won't see, can't
        tab to, and won't be read by screen readers. Bots tend to fill every
        input; the API silently drops requests where this field has content.
        Do not remove name="website" — the server matches on that.
      */}
      <input
        type="text"
        name="website"
        tabIndex={-1}
        autoComplete="off"
        aria-hidden="true"
        value={form.website}
        onChange={set("website")}
        style={{ position: "absolute", left: "-9999px", width: 1, height: 1, opacity: 0, pointerEvents: "none" }}
      />

      {/* Name + Email row */}
      <div className="v2-form-row">
        <div className="v2-field">
          <label className="v2-label" htmlFor="cf-name">Full name <span style={{ color: "var(--accent)" }}>*</span></label>
          <input className="v2-input" id="cf-name" type="text" required placeholder="Jane Smith" value={form.name} onChange={set("name")} />
        </div>
        <div className="v2-field">
          <label className="v2-label" htmlFor="cf-email">Email address <span style={{ color: "var(--accent)" }}>*</span></label>
          <input className="v2-input" id="cf-email" type="email" required placeholder="jane@company.com" value={form.email} onChange={set("email")} />
        </div>
      </div>

      {/* Topic */}
      <div className="v2-field">
        <label className="v2-label" htmlFor="cf-topic">What's this about?</label>
        <select className="v2-input" id="cf-topic" value={form.topic} onChange={set("topic")}>
          {CONTACT_TOPICS.map(t => <option key={t} value={t}>{t}</option>)}
        </select>
      </div>

      {/* Message */}
      <div className="v2-field">
        <label className="v2-label" htmlFor="cf-message">Message <span style={{ color: "var(--accent)" }}>*</span></label>
        <textarea className="v2-input v2-textarea" id="cf-message" required placeholder="Tell us how we can help…" value={form.message} onChange={set("message")} />
      </div>

      {/* Error */}
      {status === "error" && (
        <div className="v2-form-error" role="alert">{errorMsg}</div>
      )}

      {/* Submit */}
      <button type="submit" className="btn btn-primary btn-lg v2-form-submit" disabled={status === "sending"}>
        {status === "sending" ? (
          <>
            <span className="v2-spinner" />
            Sending…
          </>
        ) : (
          "Send message →"
        )}
      </button>
      <p style={{ fontSize: 12.5, color: "var(--muted)", textAlign: "center", margin: "-2px 0 0" }}>
        We typically reply within one business day.
      </p>
    </form>
  );
}

// ===== Info column — email + response-time, reusing the production copy =====
function ContactInfoV2() {
  const items = [
    { t: "General enquiries", d: "Questions about features, how the product works, or anything else — we're happy to help." },
    { t: "Sales & pricing", d: "Want a demo, a custom quote, or need help choosing the right plan for your team?" },
    { t: "Technical support", d: "Having trouble with an import, an export, or something that doesn't look right? Tell us and we'll fix it." },
    { t: "Enterprise & partnerships", d: "Need a pilot, custom SLA, or want to discuss an integration or partnership?" },
  ];
  return (
    <aside className="v2-contact-info">
      <div className="v2-contact-card">
        <div className="mono v2-contact-card-label">RESPONSE TIME</div>
        <p style={{ margin: "10px 0 0", fontSize: 15, lineHeight: 1.6, color: "var(--ink-2)" }}>
          Mon – Fri, 9 am – 5 pm (EST). We aim to reply within <strong style={{ color: "var(--ink)" }}>one business day</strong>. No bots, no ticket numbers — a real person reads your message.
        </p>
      </div>
      <ul className="v2-contact-list">
        {items.map(item => (
          <li key={item.t}>
            <div className="v2-contact-list-t">{item.t}</div>
            <div className="v2-contact-list-d">{item.d}</div>
          </li>
        ))}
      </ul>
    </aside>
  );
}

// ===== Page =====
function ContactPage() {
  return <div>
    <Nav/>
    <Section id="contact">
      <div className="v2-head" style={{ textAlign: "center", maxWidth: 720, margin: "0 auto" }}>
        <div style={{ display: "flex", justifyContent: "center", marginBottom: 18 }}>
          <Eyebrow>CONTACT</Eyebrow>
        </div>
        <h1 className="display" style={{ fontSize: "clamp(34px,5.6vw,60px)", lineHeight: 1.02 }}>
          Talk to a <span className="serif-i" style={{ color: "var(--accent)" }}>human.</span>
        </h1>
        <p style={{ fontSize: 18, lineHeight: 1.55, color: "var(--ink-2)", margin: "20px auto 0", maxWidth: 540 }}>
          Fill in the form and we'll get back to you within one business day. No bots, no ticket numbers.
        </p>
      </div>
      <div className="v2-contact-grid">
        <div className="v2-contact-formcol"><ContactFormV2/></div>
        <ContactInfoV2/>
      </div>
    </Section>
    <Footer/>
  </div>;
}

Object.assign(window, { ContactFormV2, ContactInfoV2, ContactPage });
