// inquiry.jsx — reusable inquiry/contact section, mirrors the home "Begin Your Reservation"
const { useState: useInqState } = React;

function InqField({ label, children }) {
  return <label className="field"><span className="field-label">{label}</span>{children}</label>;
}

function InquiryForm({
  id, eyebrow, title, intro,
  interestLabel = "Interest", interestOptions = [], interestPlaceholder = "Select…",
  divisions = null, divisionLabel = "Sea or Air",
  extraFields = null,
  docUploads = null, docUploadsLabel = "Verification Documents",
  showDates = true,
  datesLabel = "Preferred Dates", datesPlaceholder = "e.g. Jun 14 – 16", dateMode = "range",
  submitText = "Submit Request", sentTitle = "Request Received",
  messagePlaceholder = "Anything we should know…",
  contactPhone = null, contactHours = null,
}) {
  const [form, setForm] = useInqState({ name: "", phone: "", email: "", phone2: "", division: "", interest: "", dates: "", message: "" });
  const [err, setErr] = useInqState({});
  const { sending, sent, sinkName, begin, onSinkLoad, reset } = useEmailForm();
  const blankInq = { name: "", phone: "", email: "", phone2: "", division: "", interest: "", dates: "", message: "" };
  const set = (k) => (e) => setForm(f => ({ ...f, [k]: e.target.value }));
  const setFile = (k) => (file) => setForm(f => ({ ...f, [k]: file }));
  const subject = `New ${title || eyebrow || "Inquiry"} — ${form.name || "Website"}`;
  const onSubmit = (e) => {
    const er = {};
    if (!form.name.trim()) er.name = 1;
    if (!form.phone.trim() && !form.email.trim()) { er.phone = 1; er.email = 1; }
    setErr(er);
    if (Object.keys(er).length !== 0) { e.preventDefault(); return; }
    begin(); // allow the native form to POST into the hidden iframe
  };
  return (
    <section className="section reserve" id={id}>
      <div className="container">
        <div className="reserve-grid">
          <Reveal className="reserve-intro">
            <Eyebrow>{eyebrow}</Eyebrow>
            <h2 className="section-title">{title}</h2>
            <p className="section-intro">{intro}</p>
            <ul className="contact-list">
              <li><span className="cl-k">Phone</span><a href={`tel:${(contactPhone || CONTACT.phone).replace(/[^0-9]/g,"")}`}>{contactPhone || CONTACT.phone}</a></li>
              <li><span className="cl-k"></span><a href={`tel:${CONTACT.phone2.replace(/[^0-9]/g,"")}`}>{CONTACT.phone2}</a></li>
              <li><span className="cl-k">Email</span><a href={`mailto:${CONTACT.email}`}>{CONTACT.email}</a></li>
              <li><span className="cl-k">Hours</span><span>{contactHours || CONTACT.hours}</span></li>
              <li><span className="cl-k">Area</span><span>{CONTACT.area}</span></li>
            </ul>
          </Reveal>

          <Reveal delay={100} className="reserve-form">
            {sent ? (
              <div className="form-sent">
                <span className="sent-tick">
                  <svg viewBox="0 0 48 48" width="40" height="40" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">
                    <circle cx="24" cy="24" r="20" /><path d="M15 24.5l6 6 12-13" />
                  </svg>
                </span>
                <h3>{sentTitle}</h3>
                <p>Thank you, {form.name.split(" ")[0] || "and welcome"}. A member of the team will be in touch shortly to confirm the details.</p>
                <button className="text-link" onClick={() => { reset(); setForm(blankInq); }}>Submit another request</button>
              </div>
            ) : (
              <form className="form-body" action={FORM_ENDPOINT} method="POST" encType="multipart/form-data" target={sinkName} onSubmit={onSubmit}>
                <FormSubmitMeta subject={subject} />
                <input type="hidden" name="Form" value={title || eyebrow || "Inquiry"} />
                {divisions && (
                  <InqField label={divisionLabel}>
                    <div className="seg" role="group">
                      {divisions.map(d => (
                        <button type="button" key={d}
                          className={`seg-btn ${form.division === d ? "is-on" : ""}`}
                          onClick={() => setForm(f => ({ ...f, division: d }))}>{d}</button>
                      ))}
                    </div>
                    <input type="hidden" name={divisionLabel} value={form.division} />
                  </InqField>
                )}
                <div className="form-row">
                  <InqField label="Name"><input className={`inp ${err.name ? "inp-err" : ""}`} name="Name" value={form.name} onChange={set("name")} placeholder="Full name" /></InqField>
                  <InqField label="Phone"><input className={`inp ${err.phone ? "inp-err" : ""}`} name="Phone" value={form.phone} onChange={set("phone")} placeholder="(   )   -" /></InqField>
                </div>
                <div className="form-row">
                  <InqField label="Email"><input className={`inp ${err.email ? "inp-err" : ""}`} name="email" value={form.email} onChange={set("email")} placeholder="you@example.com" /></InqField>
                  {showDates
                    ? <InqField label={datesLabel}><DatePicker value={form.dates} onChange={(v) => setForm(f => ({ ...f, dates: v }))} mode={dateMode} placeholder={datesPlaceholder} /><input type="hidden" name={datesLabel} value={form.dates} /></InqField>
                    : <InqField label="Phone (alt.)"><input className="inp" name="Phone (alt.)" value={form.phone2 || ""} onChange={set("phone2")} placeholder="Optional" /></InqField>}
                </div>
                <InqField label={interestLabel}>
                  <div className="select-wrap">
                    <select className="inp" name={interestLabel} value={form.interest} onChange={set("interest")}>
                      <option value="">{interestPlaceholder}</option>
                      {interestOptions.map(o => <option key={o} value={o}>{o}</option>)}
                    </select>
                    <i className="select-caret" />
                  </div>
                </InqField>
                {extraFields && (
                  <div className="form-row">
                    {extraFields.map(f => (
                      <InqField key={f.key} label={f.label}>
                        <input className="inp" name={f.label} value={form[f.key] || ""} onChange={set(f.key)} placeholder={f.placeholder} />
                      </InqField>
                    ))}
                  </div>
                )}
                {docUploads && (
                  <div className="form-docs">
                    <span className="field-label">{docUploadsLabel} <em>— optional, or bring at delivery</em></span>
                    <div className="doc-grid">
                      {docUploads.map(d => (
                        <DocUpload key={d.key} name={d.label} label={d.label} hint={d.hint || "PDF, JPG or PNG"} icon={d.icon || "doc"} file={form[d.key]} onFile={setFile(d.key)} />
                      ))}
                    </div>
                    <p className="doc-secure">
                      <svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><rect x="5" y="11" width="14" height="9" rx="2" /><path d="M8 11V8a4 4 0 0 1 8 0v3" /></svg>
                      Shared securely and used only to verify your reservation. Up to 10 MB total.
                    </p>
                  </div>
                )}
                <InqField label="Message"><textarea className="inp inp-area" rows={3} name="Message" value={form.message} onChange={set("message")} placeholder={messagePlaceholder} /></InqField>
                {(err.name || err.phone) && <div className="form-hint">Please share your name and a way to reach you.</div>}
                <GoldButton full size="lg" disabled={sending}>{sending ? "Sending…" : submitText}</GoldButton>
                <iframe name={sinkName} title="form-target" onLoad={onSinkLoad} style={{ display: "none" }} />
              </form>
            )}
          </Reveal>
        </div>
      </div>
    </section>
  );
}

function scrollToInquiry(id) {
  const el = document.getElementById(id);
  if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 72, behavior: "smooth" });
}

Object.assign(window, { InquiryForm, scrollToInquiry });
