const DSe = window.PolishedAmpPinnedDesignSystem_6a1c01;

const BANDS = {
  a: "Under $800",
  b: "$800 – $1,400",
  c: "$1,400 – $2,200",
  d: "Still working it out"
};

function Enquire({ go }) {
  const { SectionHead, Field, Input, Select, ChoiceGroup, Button, Eyebrow } = DSe;
  const [sent, setSent] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState("");
  const [band, setBand] = React.useState("");
  const [form, setForm] = React.useState({ name: "", email: "", date: "", location: "", party: "", notes: "" });
  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));
  const doneRef = React.useRef(null);
  React.useEffect(() => { if (sent && doneRef.current) doneRef.current.focus(); }, [sent]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setSubmitting(true);
    setError("");

    const payload = {
      _subject: `Wedding hair enquiry — ${form.name} (${form.date})`,
      _replyto: form.email,
      _template: "table",
      "Bride's Name": form.name,
      "Email Address": form.email,
      "Wedding Date": form.date,
      "Party Size": form.party || "Not specified",
      "Getting-Ready Location": form.location || "Not specified",
      "Budget Band": BANDS[band] || "Not selected",
      "Notes": form.notes || "None"
    };

    // Also notify local server if running
    try {
      fetch("/api/enquire", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload)
      }).catch(() => {});
    } catch (_) {}

    try {
      const res = await fetch("https://formsubmit.co/ajax/81a6af7b61e71d7fc907604109ce4ab0", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Accept": "application/json"
        },
        body: JSON.stringify(payload)
      });
      const data = await res.json().catch(() => ({}));
      if (res.ok || data.success === "true" || data.success === true || (data.message && data.message.includes("Activation"))) {
        setSent(true);
      } else {
        setError(data.message || "There was a problem sending your enquiry. Please write directly to stefano.taffuri@gmail.com.");
      }
    } catch (err) {
      setError("Unable to reach the mail server. You can write directly to stefano.taffuri@gmail.com.");
    } finally {
      setSubmitting(false);
    }
  };

  if (sent) {
    return (
      <window.Page current="enquire" go={go}>
        <window.Section rule={false} style={{ paddingTop: "var(--space-10)", paddingBottom: "var(--space-10)" }}>
          <div role="status" aria-live="polite">
          <Eyebrow style={{ marginBottom: "var(--space-5)" }}>Enquiry received</Eyebrow>
          <h1 className="pp-headline" ref={doneRef} tabIndex={-1} style={{ maxWidth: "16ch", outlineOffset: "4px" }}>Thank you. We&rsquo;ll reply within one working day.</h1>
          <p style={{ marginTop: "var(--space-6)", maxWidth: "52ch" }}>
            We&rsquo;ll check {form.date ? form.date : "your date"} against the calendar and send a tailored quote.
          </p>
          </div>
          <div style={{ marginTop: "var(--space-7)", display: "flex", gap: "var(--space-3)" }}>
            <Button variant="secondary" onClick={() => go("work")}>See recent work</Button>
            <Button variant="quiet" onClick={() => { setSent(false); }}>Send another</Button>
          </div>
        </window.Section>
      </window.Page>
    );
  }

  return (
    <window.Page current="enquire" go={go}>
      <window.Section>
        <div className="pp-stack" style={{ display: "grid", gridTemplateColumns: "1fr 1.25fr", gap: "var(--space-9)", alignItems: "start" }}>
          <div>
            <SectionHead headline="Enquire about your date" size="34px" />
            <p style={{ marginTop: "var(--space-6)" }}>Share your date, location, and party size. We&rsquo;ll confirm availability and send a tailored quote.</p>
            <p style={{ marginTop: "var(--space-4)" }}>Every wedding has a different schedule, party size, and travel time, so pricing is confirmed for your plans.</p>
          </div>

          <form
            onSubmit={handleSubmit}
            style={{ display: "flex", flexDirection: "column", gap: "var(--space-6)" }}
          >
            {error && (
              <div role="alert" style={{ border: "1px solid var(--line-hairline)", background: "var(--surface-block)", padding: "var(--space-4) var(--space-5)", color: "var(--text-secondary)", fontSize: "var(--size-body-sm)" }}>
                {error}
              </div>
            )}
            <div className="pp-stack" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "var(--space-6)" }}>
              <Field label="Your name" htmlFor="f-name" required><Input id="f-name" name="name" autoComplete="name" value={form.name} onChange={set("name")} required /></Field>
              <Field label="Email" htmlFor="f-email" required><Input id="f-email" name="email" type="email" inputMode="email" autoComplete="email" spellCheck={false} placeholder="you@example.com" value={form.email} onChange={set("email")} required /></Field>
              <Field label="Wedding date" htmlFor="f-date" required><Input id="f-date" name="wedding-date" type="date" autoComplete="off" value={form.date} onChange={set("date")} required /></Field>
              <Field label="Party size" htmlFor="f-party">
                <Select id="f-party" name="party-size" placeholder="How many heads?" value={form.party} onChange={set("party")} options={["Just me", "Two to four", "Five to eight", "More than eight"]} />
              </Field>
            </div>
            <Field label="Getting-ready location" htmlFor="f-loc" hint="A suite, a house, or the venue. An address or a neighbourhood is fine.">
              <Input id="f-loc" name="location" autoComplete="street-address" value={form.location} onChange={set("location")} />
            </Field>
            <Field label="Budget band" hint="A range, not a commitment. It helps us prepare an accurate quote.">
              <ChoiceGroup name="budget" columns={4} value={band} onChange={setBand} options={[
                { value: "a", label: "Under $800" },
                { value: "b", label: "$800 – $1,400" },
                { value: "c", label: "$1,400 – $2,200" },
                { value: "d", label: "Still working it out", note: "Perfectly fine" }
              ]} />
            </Field>
            <Field label="Anything else" htmlFor="f-notes" hint="Fine hair, an early start, a venue we should know about, a mother of the bride who&rsquo;d like her hair done too.">
              <Input id="f-notes" name="notes" multiline rows={4} value={form.notes} onChange={set("notes")} />
            </Field>
            <div style={{ display: "flex", alignItems: "center", gap: "var(--space-6)" }}>
              <Button type="submit" disabled={submitting}>{submitting ? "Sending..." : "Send the enquiry"}</Button>
              <span className="pp-caption">We reply within one working day.</span>
            </div>
          </form>
        </div>
      </window.Section>
    </window.Page>
  );
}

Object.assign(window, { Enquire });
