/* global React, Icon, BeginCTA */
const { useState: useStateContact } = React;

// Web3Forms access key — replace with the one Gene generates at https://web3forms.com
// (free; sends form submissions to gene.groves@ioucounselingservices.com)
const WEB3FORMS_ACCESS_KEY = "76e7f339-4ff5-4cac-bcb6-54561e28eb0b";

const INTAKE_DEFAULTS = {
  fullName: "",
  email: "",
  phone: "",
  serviceType: "",
  presenting: "",
  experiences: [],
  safety: "",
  availability: "",
  payment: "",
  insurance: "",
  reflection: "",
  telehealthAck: false,
  consent: false,
};

const EXPERIENCE_OPTIONS = [
  "Anxiety / Overthinking",
  "Depression / Low mood",
  "Relationship challenges",
  "Stress / Burnout",
  "Emotional overwhelm",
  "Life transitions",
  "Boundary issues",
];

function ContactPage({ navigate }) {
  const [form, setForm] = useStateContact(INTAKE_DEFAULTS);
  const [status, setStatus] = useStateContact("idle"); // idle | sending | sent | error
  const [errorMsg, setErrorMsg] = useStateContact("");

  // Waitlist email-capture (separate from full intake form)
  const [waitlistOpen, setWaitlistOpen] = useStateContact(false);
  const [waitlist, setWaitlist] = useStateContact({ name: "", email: "" });
  const [waitlistStatus, setWaitlistStatus] = useStateContact("idle");
  const [waitlistErr, setWaitlistErr] = useStateContact("");

  const set = (k) => (e) => setForm({ ...form, [k]: e.target.value });
  const setBool = (k) => (e) => setForm({ ...form, [k]: e.target.checked });
  const setWl = (k) => (e) => setWaitlist({ ...waitlist, [k]: e.target.value });

  const onWaitlistSubmit = async (e) => {
    e.preventDefault();
    if (!waitlist.email) return;
    setWaitlistStatus("sending");
    setWaitlistErr("");
    try {
      const res = await fetch("https://api.web3forms.com/submit", {
        method: "POST",
        headers: { "Content-Type": "application/json", Accept: "application/json" },
        body: JSON.stringify({
          access_key: WEB3FORMS_ACCESS_KEY,
          subject: "New Waitlist Signup — Washington, D.C.",
          from_name: waitlist.name || "D.C. Waitlist Signup",
          replyto: waitlist.email,
          "Name": waitlist.name,
          "Email": waitlist.email,
          "Interest": "Washington, D.C. waitlist (services anticipated September 2026)",
        }),
      });
      const data = await res.json().catch(() => ({}));
      if (res.ok && data.success !== false) {
        setWaitlistStatus("sent");
        setWaitlist({ name: "", email: "" });
      } else {
        setWaitlistStatus("error");
        setWaitlistErr(data.message || "Something went wrong. Please email gene.groves@ioucounselingservices.com directly.");
      }
    } catch (err) {
      setWaitlistStatus("error");
      setWaitlistErr("Network error. Please email gene.groves@ioucounselingservices.com directly.");
    }
  };
  const toggleExperience = (label) => () => {
    setForm((f) => {
      const has = f.experiences.includes(label);
      return { ...f, experiences: has ? f.experiences.filter((x) => x !== label) : [...f.experiences, label] };
    });
  };

  const onSubmit = async (e) => {
    e.preventDefault();
    if (!form.telehealthAck) {
      setStatus("error");
      setErrorMsg("Please acknowledge the telehealth and location requirement before submitting.");
      return;
    }
    if (!form.consent) {
      setStatus("error");
      setErrorMsg("Please agree to be contacted before submitting.");
      return;
    }
    setStatus("sending");
    setErrorMsg("");

    const payload = {
      access_key: WEB3FORMS_ACCESS_KEY,
      subject: "New Intake Request — I.O.U. Counseling Services",
      from_name: form.fullName || "Website Intake",
      replyto: form.email,
      "Full Name": form.fullName,
      "Email": form.email,
      "Phone": form.phone,
      "Service Type": form.serviceType,
      "Presenting Concern": form.presenting,
      "Current Experiences": form.experiences.join(", "),
      "Safety — Thoughts of harming self or others": form.safety,
      "Availability": form.availability,
      "Payment Method": form.payment,
      "Insurance Provider": form.insurance,
      "IOU Reflection": form.reflection,
      "Telehealth & Location Acknowledgment": form.telehealthAck ? "Acknowledged" : "Not acknowledged",
      "Consent": form.consent ? "Yes" : "No",
    };

    try {
      const res = await fetch("https://api.web3forms.com/submit", {
        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 !== false) {
        setStatus("sent");
        setForm(INTAKE_DEFAULTS);
        setTimeout(() => setStatus("idle"), 8000);
      } else {
        setStatus("error");
        setErrorMsg(data.message || "Something went wrong. Please email gene.groves@ioucounselingservices.com directly.");
      }
    } catch (err) {
      setStatus("error");
      setErrorMsg("Network error. Please email gene.groves@ioucounselingservices.com directly.");
    }
  };

  const faqs = [
    { q: "Do you offer in-person or telehealth sessions?", a: "I.O.U. Counseling Services offers telehealth sessions only for clients in licensed states. In-person sessions are currently unavailable." },
    { q: "What can I expect from the first session?", a: "Mostly listening. We talk about what's bringing you in and decide together whether this feels like the right fit." },
    { q: "What issues do you commonly work with?", a: "Anxiety, relational patterns, men's work, identity, polyamory and ENM, and recovery from narcissistic abuse." },
    { q: "Do you accept insurance?", a: "I am out-of-network. I can provide a superbill for partial reimbursement through your plan." },
    { q: "How often should I come to therapy?", a: "Most clients begin weekly and taper. We design the cadence together based on what the work needs." },
    { q: "Is everything I share kept private?", a: "Yes, sessions are confidential within standard legal limits relating to safety." },
  ];
  const [open, setOpen] = useStateContact(0);

  return (
    <div className="page">
      <section style={{ padding: "140px 0 48px", position: "relative", overflow: "hidden" }}>
        <div className="container">
          <div className="reveal" style={{ display: "flex", flexDirection: "column", gap: 20 }}>
            <span className="eyebrow" style={{ color: "var(--sage-600)" }}>Get In Touch</span>
            <h1 className="contact-hero__title">
              Take the <em className="serif-italic">First Step</em>
            </h1>
            <p className="section__lede" style={{ maxWidth: "60ch", margin: 0 }}>
              Reach out for a free 15-minute consultation. We'll talk through what brings you in and decide together whether this feels like the right fit.
            </p>
          </div>
          <div style={{ position: "absolute", right: -120, top: 80, opacity: .35, color: "var(--sage-500)", width: 600, height: 360, pointerEvents: "none" }}>
            <Icon.Squiggle />
          </div>
        </div>
      </section>

      {/* Location & Availability + Important Information */}
      <section className="section" style={{ paddingTop: 24, paddingBottom: 24 }}>
        <div className="container">
          <div className="loc-grid reveal">
            <div className="loc-card">
              <div className="eyebrow mb-16" style={{ color: "var(--sage-600)" }}>Location &amp; Availability</div>
              <h2 className="loc-card__title">All services are provided via secure telehealth.</h2>
              <p className="loc-card__copy mt-16">
                I currently provide services to clients located in <strong>Maryland</strong>.
              </p>
              <p className="loc-card__copy mt-16">
                Services in <strong>Washington, D.C.</strong> are expected to be available beginning <strong>September 2026</strong>, pending licensure approval.
              </p>
              <div className="loc-card__cta mt-32">
                <a
                  className="btn btn-primary"
                  href="#intake-form"
                  onClick={(e) => {
                    e.preventDefault();
                    const el = document.getElementById("intake-form");
                    if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 60, behavior: "smooth" });
                  }}
                >
                  Book a Consultation
                </a>
              </div>
            </div>

            <div className="loc-card loc-card--alt">
              <div className="eyebrow mb-16" style={{ color: "var(--sage-600)" }}>Important Information</div>
              <ul className="loc-list">
                <li>Services are provided via telehealth only</li>
                <li>You must be physically located in Maryland at the time of your session</li>
                <li>Availability in Washington, D.C. will begin once licensure is approved</li>
              </ul>
              <div className="loc-card__divider" />
              <div className="eyebrow mb-16" style={{ color: "var(--sage-600)" }}>Waitlist (Recommended)</div>
              <p className="loc-card__copy">
                Located in Washington, D.C.? Drop your email and we'll let you know the moment services become available.
              </p>

              {!waitlistOpen && waitlistStatus !== "sent" && (
                <div className="loc-card__cta mt-24">
                  <button
                    type="button"
                    className="btn btn-ghost"
                    aria-expanded="false"
                    aria-controls="waitlist-form"
                    onClick={() => setWaitlistOpen(true)}
                  >
                    Join the Waitlist
                  </button>
                </div>
              )}

              {waitlistOpen && waitlistStatus !== "sent" && (
                <form id="waitlist-form" className="waitlist-form mt-20" onSubmit={onWaitlistSubmit} noValidate>
                  <div className="field">
                    <label htmlFor="wl-name">Name <span className="muted">(optional)</span></label>
                    <input id="wl-name" value={waitlist.name} onChange={setWl("name")} autoComplete="name" />
                  </div>
                  <div className="field">
                    <label htmlFor="wl-email">Email *</label>
                    <input id="wl-email" type="email" required value={waitlist.email} onChange={setWl("email")} autoComplete="email" autoFocus />
                  </div>
                  <p className="waitlist-form__note">
                    We'll only use your email to notify you when D.C. services become available. No newsletters, no sharing.
                  </p>
                  {waitlistStatus === "error" && (
                    <div className="intake-status intake-status--error" role="alert">{waitlistErr}</div>
                  )}
                  <div className="waitlist-form__actions">
                    <button type="submit" className="btn btn-primary" disabled={waitlistStatus === "sending"}>
                      {waitlistStatus === "sending" ? "Adding…" : "Notify Me"}
                    </button>
                    <button type="button" className="waitlist-form__cancel" onClick={() => { setWaitlistOpen(false); setWaitlistStatus("idle"); setWaitlistErr(""); }}>
                      Cancel
                    </button>
                  </div>
                </form>
              )}

              {waitlistStatus === "sent" && (
                <div className="waitlist-success mt-20" role="status">
                  <span className="waitlist-success__check" aria-hidden="true">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12" /></svg>
                  </span>
                  <div>
                    <strong>You're on the list.</strong>
                    <p>We'll email you the moment D.C. services become available.</p>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </section>

      <section id="intake-form" className="section section--cream" style={{ paddingTop: 80 }}>
        <div className="container">
          <h2 style={{ fontSize: "clamp(32px, 4vw, 56px)", marginBottom: 12 }}>Request for Services</h2>
          <p className="section__lede" style={{ maxWidth: "60ch", margin: "0 0 40px" }}>
            Initial intake. Share a bit about yourself and what brings you in. Gene reviews every submission personally and replies within 1–2 business days.
          </p>
          <div className="two-col" style={{ alignItems: "stretch", gap: 48 }}>
            <aside className="reveal contact-info" style={{ alignSelf: "start", display: "flex", flexDirection: "column", gap: 28, padding: "32px", background: "#fff", borderRadius: 12, boxShadow: "0 30px 80px -40px rgba(46,50,49,.45), 0 4px 12px -4px rgba(46,50,49,.15)" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                <span style={{ color: "var(--sage-600)" }}><Icon.Logo size={48} /></span>
                <div>
                  <div className="muted" style={{ fontSize: 12, letterSpacing: ".12em", textTransform: "uppercase" }}>Gene Groves, LCPC, NCC</div>
                  <div style={{ marginTop: 6, fontFamily: "var(--serif)", fontSize: 22, lineHeight: 1.2 }}>Consultation Session</div>
                </div>
              </div>

              <p style={{ margin: 0, color: "var(--slate-700)", fontSize: 15, lineHeight: 1.6 }}>
                Consultations are scheduled directly with Gene. Reach out by phone or email and we'll set up a time that works for you.
              </p>

              <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
                <a href="tel:+12022868811" style={{ display: "flex", alignItems: "center", gap: 12, color: "var(--slate-900)", textDecoration: "none", fontFamily: "var(--sans)", fontSize: 16 }}>
                  <span style={{ width: 36, height: 36, borderRadius: 999, background: "var(--sage-50, rgba(132,181,159,.15))", color: "var(--sage-600)", display: "inline-flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                    <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                      <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92z" />
                    </svg>
                  </span>
                  <span>
                    <span style={{ display: "block", fontSize: 11, letterSpacing: ".12em", textTransform: "uppercase", color: "var(--slate-500)" }}>Call</span>
                    <strong style={{ fontWeight: 600 }}>(202) 286-8811</strong>
                  </span>
                </a>
                <a href="mailto:gene.groves@ioucounselingservices.com" style={{ display: "flex", alignItems: "center", gap: 12, color: "var(--slate-900)", textDecoration: "none", fontFamily: "var(--sans)", fontSize: 16 }}>
                  <span style={{ width: 36, height: 36, borderRadius: 999, background: "var(--sage-50, rgba(132,181,159,.15))", color: "var(--sage-600)", display: "inline-flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                    <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                      <rect x="3" y="5" width="18" height="14" rx="2" />
                      <path d="m3 7 9 6 9-6" />
                    </svg>
                  </span>
                  <span>
                    <span style={{ display: "block", fontSize: 11, letterSpacing: ".12em", textTransform: "uppercase", color: "var(--slate-500)" }}>Email</span>
                    <strong style={{ fontWeight: 600 }}>gene.groves@ioucounselingservices.com</strong>
                  </span>
                </a>
              </div>

              <div style={{ marginTop: "auto", paddingTop: 16, borderTop: "1px solid rgba(46,50,49,.12)", fontSize: 13, color: "var(--slate-700)", lineHeight: 1.55 }}>
                <strong style={{ fontFamily: "var(--sans)", letterSpacing: ".08em", fontSize: 11, textTransform: "uppercase", color: "var(--slate-500)", display: "block", marginBottom: 6 }}>Telehealth</strong>
                Sessions held via secure video in licensed states. In-person sessions are currently unavailable.
              </div>
            </aside>

            <form className="reveal delay-2 intake-form" onSubmit={onSubmit} noValidate>
              <h3 className="intake-form__title">Initial Intake</h3>

              <div className="field">
                <label htmlFor="fullName">Full Name *</label>
                <input id="fullName" required value={form.fullName} onChange={set("fullName")} autoComplete="name" />
              </div>

              <div className="field">
                <label htmlFor="email">Email *</label>
                <input id="email" required type="email" value={form.email} onChange={set("email")} autoComplete="email" />
              </div>

              <div className="field">
                <label htmlFor="phone">Phone *</label>
                <input id="phone" required type="tel" value={form.phone} onChange={set("phone")} autoComplete="tel" />
              </div>

              <div className="field">
                <label htmlFor="serviceType">Service Type *</label>
                <select id="serviceType" required value={form.serviceType} onChange={set("serviceType")}>
                  <option value="" disabled>Select an option</option>
                  <option>Individual Therapy</option>
                  <option>Couples Counseling</option>
                  <option>Family Therapy</option>
                  <option>Men's Work</option>
                  <option>Not sure</option>
                </select>
              </div>

              <div className="field">
                <label htmlFor="presenting">What brings you to counseling at this time? *</label>
                <textarea id="presenting" required value={form.presenting} onChange={set("presenting")} rows={4} />
              </div>

              <fieldset className="field intake-checks">
                <legend>What are you currently experiencing? <span className="muted">(check all that apply)</span></legend>
                <div className="intake-checks__grid">
                  {EXPERIENCE_OPTIONS.map((label) => (
                    <label key={label} className="intake-check">
                      <input
                        type="checkbox"
                        checked={form.experiences.includes(label)}
                        onChange={toggleExperience(label)}
                      />
                      <span>{label}</span>
                    </label>
                  ))}
                </div>
              </fieldset>

              <div className="field">
                <label htmlFor="safety">Are you currently experiencing thoughts of harming yourself or others? *</label>
                <select id="safety" required value={form.safety} onChange={set("safety")}>
                  <option value="" disabled>Select an option</option>
                  <option>No</option>
                  <option>Unsure</option>
                  <option>Yes</option>
                </select>
              </div>

              <div className="field">
                <label htmlFor="availability">What times generally work best for you?</label>
                <input id="availability" value={form.availability} onChange={set("availability")} placeholder="e.g. weekday evenings, Saturday mornings" />
              </div>

              <div className="field">
                <label htmlFor="payment">How would you like to handle payment? *</label>
                <select id="payment" required value={form.payment} onChange={set("payment")}>
                  <option value="" disabled>Select an option</option>
                  <option>Insurance</option>
                  <option>Private Pay</option>
                  <option>Not sure</option>
                </select>
              </div>

              <div className="field">
                <label htmlFor="insurance">Insurance Provider <span className="muted">(optional)</span></label>
                <input id="insurance" value={form.insurance} onChange={set("insurance")} />
              </div>

              <div className="field">
                <label htmlFor="reflection">What are you hoping to gain from counseling?</label>
                <textarea id="reflection" value={form.reflection} onChange={set("reflection")} rows={3} />
              </div>

              <div className="intake-disclosure" role="group" aria-labelledby="telehealth-heading">
                <h4 id="telehealth-heading" className="intake-disclosure__title">Telehealth &amp; Location Requirement</h4>
                <p className="intake-disclosure__copy">
                  I.O.U. Counseling Services provides therapy exclusively via secure telehealth.
                </p>
                <p className="intake-disclosure__copy">
                  You agree to be physically located in the state of <strong>Maryland</strong> at the time of each session, as services are only provided in jurisdictions where the clinician is licensed.
                </p>
                <p className="intake-disclosure__copy">
                  Services for clients located in Washington, D.C. are not currently available and are anticipated to begin in <strong>September 2026</strong>, pending licensure approval.
                </p>
                <p className="intake-disclosure__sub">By submitting this form, you acknowledge and agree that:</p>
                <ul className="intake-disclosure__list">
                  <li>You will be physically located in Maryland during all sessions</li>
                  <li>You understand that services cannot be provided outside of licensed jurisdictions</li>
                  <li>You have been informed of current and future service availability</li>
                </ul>
              </div>

              <label className="intake-consent">
                <input type="checkbox" checked={form.telehealthAck} onChange={setBool("telehealthAck")} required />
                <span>I acknowledge and agree to the telehealth and location requirement above.</span>
              </label>

              <label className="intake-consent">
                <input type="checkbox" checked={form.consent} onChange={setBool("consent")} required />
                <span>I agree to be contacted regarding my inquiry.</span>
              </label>

              {status === "error" && (
                <div className="intake-status intake-status--error" role="alert">{errorMsg}</div>
              )}
              {status === "sent" && (
                <div className="intake-status intake-status--ok" role="status">
                  Thank you. Your intake has been received. Gene will reach out within 1–2 business days.
                </div>
              )}

              <button
                type="submit"
                className="btn btn-primary"
                disabled={status === "sending"}
                style={{ alignSelf: "flex-start", marginTop: 8 }}
              >
                {status === "sending" ? "Sending…" : "Request Consultation"}
              </button>
              <p className="intake-safety-note" role="note">
                If you are in immediate danger, call <strong>911</strong> or <strong>988</strong>. This form is not monitored 24/7.
              </p>
            </form>
          </div>
        </div>
      </section>

      {/* FAQ */}
      <section className="section">
        <div className="container">
          <div className="text-center reveal">
            <h2 style={{ marginTop: 8 }}>Your questions. Answered.</h2>
            <p className="muted" style={{ margin: "16px auto 0", maxWidth: "60ch" }}>
              Not sure what to expect? These answers might help you feel more confident as you begin.
            </p>
          </div>
          <div style={{ maxWidth: 780, margin: "48px auto 0" }} className="faq__list">
            {faqs.map((f, i) => (
              <div key={i} className={`faq__item ${open === i ? "is-open" : ""}`}>
                <button className="faq__head" onClick={() => setOpen(open === i ? -1 : i)}>
                  <span>{f.q}</span>
                  <span className="faq__plus" />
                </button>
                <div className="faq__body" style={{ maxHeight: open === i ? 320 : 0 }}>
                  <div className="faq__body-inner">{f.a}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Emergency banner */}
      <section style={{ padding: "32px 0 80px" }}>
        <div className="container">
          <div className="emergency-banner reveal" role="note">
            <div className="emergency-banner__icon" aria-hidden="true">
              <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M12 9v4" /><path d="M12 17h.01" />
                <path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
              </svg>
            </div>
            <div className="emergency-banner__body">
              <strong>Emergency Disclaimer · </strong>
              I.O.U. Counseling Services does not provide emergency or crisis services through this website. If you are experiencing a mental health emergency, call <strong>911</strong>, go to the nearest emergency room, or call/text <strong>988</strong> for the Suicide &amp; Crisis Lifeline.
              {" "}<a href="#/disclaimer" onClick={(e) => {e.preventDefault();navigate("/disclaimer");}}>Read full disclaimers →</a>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}

window.ContactPage = ContactPage;
