/* Pilgrim Wright — Contact page (form validation) */

var { useState, useMemo } = React;

function ContactPage({ navigate }) {
  return (
    <div className="page">
      <PageHero
        num="№ 05 / 05"
        kicker="Begin the journey"
        title={<>The first step is<br /><em style={{ fontStyle: "italic", color: "var(--accent-deep)" }}>a conversation.</em></>}
        lede="Thirty minutes, no slides, no obligation. Tell us a little about your organization and what's on your mind. We answer every inquiry within two business days, from a human, in Plymouth."
      />

      <section className="section">
        <div className="container">
          <div style={{
            display: "grid",
            gridTemplateColumns: "minmax(0, 1fr) minmax(0, 1.6fr)",
            gap: 80,
            alignItems: "start",
          }}>
            {/* Left column — context */}
            <ContactSidebar />

            {/* Right column — form */}
            <ContactForm />
          </div>
        </div>
      </section>

      <ContactCalendar />
      <ContactDirections navigate={navigate} />
    </div>
  );
}

/* ---------- Sidebar with details ---------- */
function ContactSidebar() {
  return (
    <Reveal>
      <aside style={{ position: "sticky", top: 96 }}>
        <div className="kicker" style={{ marginBottom: 18 }}>§ 12 — Where to find us</div>

        <div style={{ display: "flex", flexDirection: "column", gap: 32 }}>
          <div>
            <div className="kicker kicker--muted" style={{ marginBottom: 10 }}>Office</div>
            <div className="serif" style={{ fontSize: 20, color: "var(--ink)", lineHeight: 1.5 }}>
              14 Leyden Street, Suite 3<br />
              Plymouth, Massachusetts 02360
            </div>
          </div>
          <div>
            <div className="kicker kicker--muted" style={{ marginBottom: 10 }}>Email</div>
            <a href="mailto:hello@pilgrimwright.ai" className="serif" style={{ fontSize: 20, color: "var(--ink)" }}>
              hello@pilgrimwright.ai
            </a>
          </div>
          <div>
            <div className="kicker kicker--muted" style={{ marginBottom: 10 }}>Phone</div>
            <a href="tel:+15085550140" className="serif" style={{ fontSize: 20, color: "var(--ink)" }}>
              (508) 555-0140
            </a>
          </div>
          <div>
            <div className="kicker kicker--muted" style={{ marginBottom: 10 }}>Office hours</div>
            <div style={{ fontSize: 14.5, color: "var(--text-muted)", lineHeight: 1.6 }}>
              Mon–Thu · 9 to 5 ET<br />
              Friday by appointment<br />
              We don't take meetings on Sundays.
            </div>
          </div>

          <div style={{
            marginTop: 12, padding: 24,
            border: "1px solid var(--line)", background: "rgba(255,255,255,0.32)",
            display: "flex", justifyContent: "space-between", alignItems: "center",
          }}>
            <div>
              <div className="kicker kicker--accent" style={{ marginBottom: 8 }}>Bearing</div>
              <div className="serif" style={{ fontSize: 22, color: "var(--ink)" }}>
                N 41° 57′ 24″<br />W 70° 40′ 04″
              </div>
            </div>
            <CompassRose size={84} accent />
          </div>

          <div style={{ paddingTop: 24, borderTop: "1px dashed var(--line)", fontSize: 13.5, color: "var(--text-muted)", lineHeight: 1.55 }}>
            Prefer paper? We still answer letters.
            Send one to the address above and we'll write back in kind.
          </div>
        </div>
      </aside>
    </Reveal>
  );
}

/* ---------- Form with realistic validation ---------- */
function ContactForm() {
  const [form, setForm] = useState({
    name: "",
    email: "",
    org: "",
    sector: "",
    size: "",
    stage: "",
    interest: "",
    message: "",
    timeline: "",
    consent: false,
  });
  const [errors, setErrors] = useState({});
  const [submitted, setSubmitted] = useState(false);
  const [submitting, setSubmitting] = useState(false);

  const update = (k, v) => {
    setForm((f) => ({ ...f, [k]: v }));
    setErrors((e) => ({ ...e, [k]: undefined }));
  };

  const validate = () => {
    const next = {};
    if (!form.name.trim()) next.name = "Please tell us your name.";
    if (!form.email.trim()) next.email = "We'll need an email to reply.";
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) next.email = "That doesn't look like a valid email.";
    if (!form.org.trim()) next.org = "Organization name, please.";
    if (!form.sector) next.sector = "Pick the closest fit.";
    if (!form.message.trim() || form.message.trim().length < 20) {
      next.message = "A sentence or two of context helps us prepare.";
    }
    if (!form.consent) next.consent = "Please confirm we may contact you.";
    setErrors(next);
    return Object.keys(next).length === 0;
  };

  const onSubmit = (e) => {
    e.preventDefault();
    if (!validate()) return;
    setSubmitting(true);
    setTimeout(() => {
      setSubmitting(false);
      setSubmitted(true);
      window.scrollTo({ top: window.scrollY - 80, behavior: "smooth" });
    }, 900);
  };

  if (submitted) {
    return (
      <Reveal>
        <div style={{
          border: "1px solid var(--ink)",
          background: "var(--ink)",
          color: "var(--paper)",
          padding: "56px 48px",
          position: "relative",
          overflow: "hidden",
        }}>
          <div style={{ position: "absolute", inset: 0, opacity: 0.08, color: "var(--paper)" }}>
            <TopoLines count={6} opacity={1} />
          </div>
          <div style={{ position: "relative" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 28 }}>
              <span style={{ color: "var(--accent-soft)" }}><CompassMark /></span>
              <span className="kicker" style={{ color: "var(--accent-soft)" }}>Received · {new Date().toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" })}</span>
            </div>
            <h3 className="display" style={{
              color: "var(--paper)", fontSize: "clamp(36px, 4.5vw, 56px)",
              fontVariationSettings: '"opsz" 48',
              marginBottom: 24,
            }}>
              Thank you, {form.name.split(" ")[0]}.
            </h3>
            <p className="lede" style={{ color: "rgba(244,237,224,0.85)", maxWidth: 560 }}>
              We have your note. A human at Pilgrim Wright — likely Aaron — will
              read it carefully and reply within two business days. If you'd like
              to put time on the calendar in the meantime, you can do that just below.
            </p>
            <div style={{ marginTop: 36, display: "flex", gap: 14, flexWrap: "wrap" }}>
              <Btn variant="accent" arrow href="#calendar">Book a 30-minute call</Btn>
              <Btn variant="secondary" onClick={() => { setSubmitted(false); setForm({
                name: "", email: "", org: "", sector: "", size: "", stage: "",
                interest: "", message: "", timeline: "", consent: false,
              }); }}>
                <span style={{ color: "var(--paper)" }}>Send another message</span>
              </Btn>
            </div>
          </div>
        </div>
      </Reveal>
    );
  }

  return (
    <Reveal>
      <form onSubmit={onSubmit} noValidate style={{
        display: "flex", flexDirection: "column", gap: 36,
      }}>
        <div>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
            <div className="kicker">Inquiry · № {Math.floor(Math.random() * 900 + 100)}</div>
            <div className="kicker kicker--muted">All fields with · are required</div>
          </div>
          <h2 className="display" style={{ fontSize: "clamp(28px, 3vw, 36px)", marginBottom: 8 }}>
            Tell us where you are.
          </h2>
          <p className="muted" style={{ maxWidth: 480 }}>
            We read every inquiry by hand. The more context you can share,
            the more useful our first reply will be.
          </p>
        </div>

        {/* Row: name + email */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 28 }}>
          <FormField
            label="Your name ·" value={form.name} error={errors.name}
            onChange={(v) => update("name", v)}
            placeholder="Jane Holloway"
          />
          <FormField
            label="Email ·" value={form.email} error={errors.email}
            onChange={(v) => update("email", v)}
            placeholder="jane@example.org"
            type="email"
          />
        </div>

        {/* Row: org + sector */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 28 }}>
          <FormField
            label="Organization ·" value={form.org} error={errors.org}
            onChange={(v) => update("org", v)}
            placeholder="Cape Ann Family Services"
          />
          <FormSelect
            label="Sector ·" value={form.sector} error={errors.sector}
            onChange={(v) => update("sector", v)}
            options={[
              "Non-profit",
              "Church or faith organization",
              "Small or medium business",
              "Other",
            ]}
          />
        </div>

        {/* Row: size + stage */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 28 }}>
          <FormSelect
            label="Team size"
            value={form.size}
            onChange={(v) => update("size", v)}
            options={["Just me", "2–10", "11–50", "51–150", "150+"]}
          />
          <FormSelect
            label="Where you are with AI"
            value={form.stage}
            onChange={(v) => update("stage", v)}
            options={[
              "Just curious",
              "Some experiments, no strategy",
              "Started; want a sanity check",
              "In motion; want stewardship",
            ]}
          />
        </div>

        {/* Service interest — segmented */}
        <div>
          <label className="kicker kicker--muted" style={{ display: "block", marginBottom: 14 }}>
            Which service are you most curious about?
          </label>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))", gap: 0, border: "1px solid var(--line)" }}>
            {[
              "Readiness Assessment",
              "Implementation",
              "Ongoing Advisory",
              "Not sure yet",
            ].map((opt, i) => (
              <button key={i} type="button"
                onClick={() => update("interest", opt)}
                style={{
                  padding: "16px 14px",
                  textAlign: "left",
                  borderRight: i < 3 ? "1px solid var(--line)" : "none",
                  background: form.interest === opt ? "var(--ink)" : "transparent",
                  color: form.interest === opt ? "var(--paper)" : "var(--ink)",
                  transition: "all 0.2s",
                  fontFamily: "var(--font-serif)",
                  fontSize: 16,
                  letterSpacing: "-0.005em",
                  position: "relative",
                }}
              >
                <div className="kicker" style={{
                  color: form.interest === opt ? "var(--accent-soft)" : "var(--text-muted)",
                  marginBottom: 6, fontSize: 10,
                }}>
                  0{i + 1}
                </div>
                {opt}
              </button>
            ))}
          </div>
        </div>

        {/* Message */}
        <div className={`field ${errors.message ? "field--error" : ""}`}>
          <label>What's on your mind? ·</label>
          <textarea
            rows={6}
            placeholder="A few sentences about what you're trying to do, who you serve, and what's prompting the question now."
            value={form.message}
            onChange={(e) => update("message", e.target.value)}
            style={{ resize: "vertical", minHeight: 140 }}
          />
          {errors.message && <div className="field__error">↳ {errors.message}</div>}
        </div>

        {/* Timeline */}
        <FormSelect
          label="Timeline"
          value={form.timeline}
          onChange={(v) => update("timeline", v)}
          options={[
            "This quarter",
            "Within six months",
            "Sometime this year",
            "Just exploring",
          ]}
        />

        {/* Consent */}
        <div>
          <label style={{ display: "flex", alignItems: "flex-start", gap: 14, cursor: "pointer" }}>
            <span style={{
              flex: "none", width: 18, height: 18, marginTop: 3,
              border: `1px solid ${errors.consent ? "var(--accent)" : "var(--ink)"}`,
              background: form.consent ? "var(--ink)" : "transparent",
              position: "relative",
              transition: "all 0.2s",
            }}>
              {form.consent && (
                <svg viewBox="0 0 18 18" style={{ position: "absolute", inset: 0 }}>
                  <path d="M4 9 L8 13 L14 5" fill="none" stroke="var(--paper)" strokeWidth="1.8" />
                </svg>
              )}
              <input type="checkbox" checked={form.consent} onChange={(e) => update("consent", e.target.checked)}
                style={{ position: "absolute", opacity: 0, inset: 0, cursor: "pointer" }} />
            </span>
            <span style={{ fontSize: 14, lineHeight: 1.55, color: "var(--text-muted)" }}>
              Please contact me regarding this inquiry. I understand Pilgrim Wright
              will not share my details with anyone and will not add me to a marketing list.
            </span>
          </label>
          {errors.consent && <div className="field__error" style={{ marginTop: 8, paddingLeft: 32 }}>↳ {errors.consent}</div>}
        </div>

        {/* Submit */}
        <div style={{
          paddingTop: 28, borderTop: "1px solid var(--line)",
          display: "flex", justifyContent: "space-between", alignItems: "center", gap: 24, flexWrap: "wrap",
        }}>
          <div className="kicker kicker--muted" style={{ maxWidth: 340 }}>
            ⌁ We reply within two business days, from a human.
          </div>
          <Btn variant="primary" arrow type="submit" onClick={submitting ? null : undefined}>
            {submitting ? "Sending…" : "Send inquiry"}
          </Btn>
        </div>
      </form>
    </Reveal>
  );
}

function FormField({ label, value, onChange, error, placeholder, type = "text" }) {
  return (
    <div className={`field ${error ? "field--error" : ""}`}>
      <label>{label}</label>
      <input
        type={type}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder}
      />
      {error && <div className="field__error">↳ {error}</div>}
    </div>
  );
}

function FormSelect({ label, value, onChange, options, error }) {
  return (
    <div className={`field ${error ? "field--error" : ""}`}>
      <label>{label}</label>
      <div style={{ position: "relative" }}>
        <select
          value={value}
          onChange={(e) => onChange(e.target.value)}
          style={{
            width: "100%",
            appearance: "none",
            background: "transparent",
            border: 0,
            borderBottom: "1px solid var(--line)",
            padding: "10px 24px 10px 0",
            fontFamily: "var(--font-sans)",
            fontSize: 16,
            color: value ? "var(--ink)" : "var(--text-faint)",
            cursor: "pointer",
          }}
        >
          <option value="" disabled>Pick one…</option>
          {options.map((o) => <option key={o} value={o}>{o}</option>)}
        </select>
        <span style={{
          position: "absolute", right: 4, top: "50%", transform: "translateY(-25%) rotate(45deg)",
          width: 6, height: 6, borderRight: "1px solid var(--ink)", borderBottom: "1px solid var(--ink)",
          pointerEvents: "none",
        }} />
      </div>
      {error && <div className="field__error">↳ {error}</div>}
    </div>
  );
}

/* ---------- Calendar placeholder ---------- */
function ContactCalendar() {
  const [selected, setSelected] = useState(null);
  // Build a fake week
  const days = useMemo(() => {
    const base = new Date();
    base.setDate(base.getDate() + 1);
    const arr = [];
    let added = 0;
    let d = 0;
    while (added < 10) {
      const cur = new Date(base);
      cur.setDate(base.getDate() + d);
      const dow = cur.getDay();
      if (dow !== 0 && dow !== 6) {
        arr.push({
          date: cur,
          slots: [
            { time: "9:00 am", taken: false },
            { time: "10:30 am", taken: Math.random() < 0.4 },
            { time: "1:00 pm", taken: Math.random() < 0.35 },
            { time: "3:30 pm", taken: Math.random() < 0.4 },
          ],
        });
        added++;
      }
      d++;
    }
    return arr;
  }, []);

  return (
    <section className="section" id="calendar" style={{ background: "var(--paper-deep)", borderTop: "1px solid var(--line)", borderBottom: "1px solid var(--line)" }}>
      <div className="container">
        <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1fr) minmax(0, 2fr)", gap: 64, marginBottom: 48 }}>
          <div>
            <div className="kicker" style={{ marginBottom: 14 }}>§ 13 — Or book directly</div>
            <h2 className="display" style={{ fontSize: "clamp(36px, 4.5vw, 56px)" }}>
              Thirty minutes,<br />on the calendar.
            </h2>
          </div>
          <p className="lede" style={{ alignSelf: "end", maxWidth: 520 }}>
            Skip the form. Pick a time below and you'll get a confirmation
            and a one-question pre-call note from us.
          </p>
        </div>

        <div style={{ border: "1px solid var(--line)", background: "rgba(255, 252, 245, 0.55)" }}>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", borderBottom: "1px solid var(--line)" }}>
            {days.slice(0, 5).map((day, i) => {
              const dow = day.date.toLocaleDateString("en-US", { weekday: "short" });
              const dnum = day.date.getDate();
              const month = day.date.toLocaleDateString("en-US", { month: "short" });
              return (
                <div key={i} style={{
                  padding: "20px 16px",
                  borderRight: i < 4 ? "1px solid var(--line)" : "none",
                  textAlign: "center",
                }}>
                  <div className="kicker kicker--muted" style={{ marginBottom: 8 }}>{dow}</div>
                  <div className="display" style={{ fontSize: 36, color: "var(--ink)" }}>{dnum}</div>
                  <div className="kicker kicker--muted" style={{ marginTop: 6 }}>{month}</div>
                </div>
              );
            })}
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)" }}>
            {days.slice(0, 5).map((day, i) => (
              <div key={i} style={{
                borderRight: i < 4 ? "1px solid var(--line)" : "none",
                padding: "16px 12px",
                display: "flex", flexDirection: "column", gap: 6,
              }}>
                {day.slots.map((slot, j) => {
                  const key = `${i}-${j}`;
                  const isSelected = selected === key;
                  return (
                    <button key={j}
                      disabled={slot.taken}
                      onClick={() => setSelected(key)}
                      style={{
                        padding: "10px 12px",
                        fontFamily: "var(--font-mono)",
                        fontSize: 12,
                        letterSpacing: "0.04em",
                        textAlign: "left",
                        border: `1px solid ${isSelected ? "var(--ink)" : "var(--line-soft)"}`,
                        background: isSelected ? "var(--ink)" : (slot.taken ? "transparent" : "rgba(255,255,255,0.5)"),
                        color: isSelected ? "var(--paper)" : (slot.taken ? "var(--text-faint)" : "var(--ink)"),
                        cursor: slot.taken ? "not-allowed" : "pointer",
                        textDecoration: slot.taken ? "line-through" : "none",
                        transition: "all 0.18s",
                      }}
                    >
                      {slot.time}
                    </button>
                  );
                })}
              </div>
            ))}
          </div>
        </div>

        {selected && (
          <div style={{
            marginTop: 24, padding: 24,
            border: "1px solid var(--ink)", background: "var(--ink)", color: "var(--paper)",
            display: "flex", justifyContent: "space-between", alignItems: "center", gap: 16, flexWrap: "wrap",
          }}>
            <div>
              <div className="kicker" style={{ color: "var(--accent-soft)", marginBottom: 6 }}>You picked</div>
              <div className="serif" style={{ fontSize: 22, color: "var(--paper)" }}>
                {(() => {
                  const [dayIdx, slotIdx] = selected.split("-").map(Number);
                  const d = days[dayIdx];
                  return `${d.date.toLocaleDateString("en-US", { weekday: "long", month: "long", day: "numeric" })} · ${d.slots[slotIdx].time}`;
                })()}
              </div>
            </div>
            <Btn variant="accent" arrow onClick={() => alert("In production this would confirm your booking. Demo only.")}>
              Confirm booking
            </Btn>
          </div>
        )}
      </div>
    </section>
  );
}

/* ---------- Directions / map placeholder ---------- */
function ContactDirections({ navigate }) {
  return (
    <section className="section">
      <div className="container">
        <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.4fr) minmax(0, 1fr)", gap: 56, alignItems: "stretch" }}>
          <Reveal>
            <div style={{
              border: "1px solid var(--line)",
              padding: 0,
              background: "var(--paper-deep)",
              height: "100%",
              minHeight: 320,
              display: "flex", alignItems: "center", justifyContent: "center",
              position: "relative", overflow: "hidden",
              color: "var(--ink-quiet)",
            }}>
              {/* Stylized map / topo */}
              <div style={{ position: "absolute", inset: 0, opacity: 0.45 }}>
                <TopoLines count={14} opacity={1} />
              </div>
              <div style={{ position: "relative", textAlign: "center" }}>
                <CompassRose size={140} accent />
                <div className="kicker kicker--accent" style={{ marginTop: 18 }}>14 Leyden St · Plymouth</div>
              </div>
              {/* corner ticks */}
              {[
                { top: 12, left: 12 }, { top: 12, right: 12 },
                { bottom: 12, left: 12 }, { bottom: 12, right: 12 },
              ].map((s, i) => (
                <div key={i} style={{
                  position: "absolute", ...s, fontFamily: "var(--font-mono)",
                  fontSize: 10, letterSpacing: "0.12em", color: "var(--text-muted)",
                }}>
                  {i === 0 && "N 41°57′28″"}
                  {i === 1 && "W 70°40′00″"}
                  {i === 2 && "N 41°57′20″"}
                  {i === 3 && "W 70°40′08″"}
                </div>
              ))}
            </div>
          </Reveal>

          <Reveal delay={120}>
            <div>
              <div className="kicker" style={{ marginBottom: 14 }}>§ 14 — Getting here</div>
              <h3 className="display" style={{ fontSize: "clamp(28px, 3.4vw, 40px)", marginBottom: 24 }}>
                We have a kettle on.
              </h3>
              <p style={{ fontSize: 16.5, lineHeight: 1.6, color: "var(--text-muted)", marginBottom: 28 }}>
                Our office is one block from Plymouth harbor, two doors down
                from the bookshop, above the small letterpress. If you're
                driving from Boston, plan on an hour. From the Cape, twenty-five
                minutes.
              </p>
              <div style={{ display: "flex", flexDirection: "column", gap: 12, paddingTop: 18, borderTop: "1px solid var(--line)" }}>
                {[
                  ["By car", "I-93 → MA-3 South, exit 6. Metered parking on Leyden."],
                  ["By train", "Plymouth Line from South Station. We'll meet you at Cordage Park."],
                  ["By boat", "There's a guest mooring most of the year. Call ahead."],
                ].map(([k, v], i) => (
                  <div key={i} style={{ display: "grid", gridTemplateColumns: "100px 1fr", gap: 16, padding: "12px 0", borderTop: i > 0 ? "1px dashed var(--line)" : "none", fontSize: 14.5, color: "var(--text-muted)" }}>
                    <div className="kicker kicker--muted">{k}</div>
                    <div>{v}</div>
                  </div>
                ))}
              </div>
            </div>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

window.ContactPage = ContactPage;
