/* global React, Photo, Eyebrow, Rule */
const { useState: useStateC } = React;

function ContactHeader() {
  return (
    <header className="page-header page-header--wide" style={{ paddingBottom: 24 }}>
      <div className="page-header__inner">
        <Eyebrow center>Inquire</Eyebrow>
        <h1 className="kit-headline kit-headline--xl headline-oneline" style={{ margin: '32px 0 24px' }}>
          tell me about <em>your day.</em>
        </h1>
        <Rule center />
        <p className="kit-lede page-lede page-lede--center">
          The more you'd like to share, the better. I read every note
          personally &amp; write back within two business days — usually
          much sooner.
        </p>
      </div>
    </header>
  );
}

/* Session-type-specific questions. Each field: state key, label, optional
   input type / placeholder / grid span (default 1 of 2 columns). */
const TYPE_FIELDS = {
  'Wedding': [
    { k: 'date',     label: 'Wedding Date',        type: 'date' },
    { k: 'location', label: 'Venue / Location',    ph: 'Athens, GA · or destination' },
    { k: 'planner',  label: 'Planner',             ph: 'Their name — or not yet' },
  ],
  'Engagement': [
    { k: 'date',     label: 'Preferred Date',      type: 'date' },
    { k: 'location', label: 'Location in Mind',    ph: 'Downtown Athens · a family farm · not sure yet', span: 2 },
  ],
  'Lifestyle / Family': [
    { k: 'date',     label: 'Preferred Date',      type: 'date' },
    { k: 'family',   label: 'Who All Will Be There', ph: 'The four of us, plus grandma', span: 2 },
  ],
  'Editorial / Brand': [
    { k: 'date',     label: 'Preferred Date',      type: 'date' },
    { k: 'brand',    label: 'Brand / Business',    ph: 'Your shop, studio, or team' },
    { k: 'location', label: 'Where Will We Shoot?', ph: 'Studio · storefront · on location' },
  ],
};

/* The story prompt is the field people actually pause on, so it asks about the
   session they picked rather than a wedding by default. Falls back to STORY_FALLBACK
   if a new session type is added here without a matching prompt. */
const STORY_FALLBACK = "Tell me anything you'd like me to know — what you're picturing, what matters most to you, and what you'd love to remember.";
const STORY_PLACEHOLDER = {
  'Wedding': "What does the morning feel like? Where will you be getting ready, what kind of dinner is it, what is most important to you about the photographs…",
  'Engagement': "How did the two of you meet? What do you love doing together, and what kind of afternoon are you picturing…",
  'Lifestyle / Family': "Who will be in the photographs, and what are they like right now? What do you most want to remember about this season…",
  'Editorial / Brand': "What are you building, who is it for, and where will these images live — a website, socials, print…",
};

const REFERRALS = [
  'Instagram',
  'From a friend',
  'Vendor referral',
  'Google Search',
  'Other',
];

function InquireForm() {
  const [submitted, setSubmitted] = useStateC(false);
  const [sending, setSending] = useStateC(false);
  const [error, setError] = useStateC(null);
  const [form, setForm] = useStateC({
    first: '', last: '', email: '', phone: '', type: 'Wedding',
    date: '', location: '', planner: '', family: '', brand: '',
    referral: '', story: '',
    company: '',   // honeypot — see the hidden field near the submit button
  });
  const set = (k) => (e) => setForm({ ...form, [k]: e.target.value });

  const showReply = () => {
    setSubmitted(true);
    // Below 900px the photo stacks above the form, so submitting from the foot
    // of the page leaves both the swapped photo and the thank-you off screen.
    // Desktop keeps its place, where they are already in view.
    if (window.matchMedia('(max-width: 900px)').matches) {
      const top = document.querySelector('.inquire');
      if (top) top.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
  };

  /* Posts to the Pages Function in functions/api/inquiry.js.
     Promise chaining rather than async/await: these files are transpiled by
     Babel standalone in the browser, with no regenerator runtime loaded. */
  const submit = (e) => {
    e.preventDefault();
    if (sending) return;
    setSending(true);
    setError(null);

    fetch('/api/inquiry', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(form),
    })
      .then((res) => res.json()
        .catch(() => ({}))          // a non-JSON body (404 page, proxy error)
        .then((body) => ({ res, body })))
      .then(({ res, body }) => {
        if (!res.ok) throw new Error(body.error || '');
        setSending(false);
        showReply();
      })
      .catch((err) => {
        setSending(false);
        setError(err.message
          || "That didn't send. Please try again, or email abbyharperphoto@gmail.com.");
      });
  };

  // Swapped in place of the form (same column) after submitting — no scroll,
  // no navigation, so the reader stays exactly where they were on the page.
  const thankYou = (
    <div>
      <img src={asset("assets/ahp-logo/Symbol-clay.png")} alt="" style={{ height: 72, marginBottom: 28 }} />
      <h2 className="kit-headline kit-headline--lg" style={{ marginBottom: 24 }}>
        <em>Thank you</em><br />— so much.
      </h2>
      <hr className="kit-rule" />
      <p className="kit-lede" style={{ margin: 0 }}>
        Your note just landed in my inbox. I'll be in touch within
        48 hours with a hello, a few follow-up questions, &amp; the
        full pricing guide.
      </p>
      <p className="inquire__sig">— Abby</p>
      <button className="kit-btn kit-btn--ghost" style={{ marginTop: 36 }} onClick={() => setSubmitted(false)}>
        Send Another
      </button>
    </div>
  );

  const typeFields = TYPE_FIELDS[form.type] || [];
  const storyPlaceholder = STORY_PLACEHOLDER[form.type] || STORY_FALLBACK;

  return (
    <section className="inquire">
      <div className="inquire__inner">
        <div className="inquire__aside">
          <Photo
            src={submitted ? "assets/ahp-photos/contact-after.jpg" : "assets/ahp-photos/contact-before.jpg"}
            aspect="4/5"
          />
          <div style={{ marginTop: 40 }}>
            <Eyebrow>The Studio</Eyebrow>
            <p className="inquire__email">
              <a href="mailto:abbyharperphoto@gmail.com">abbyharperphoto@gmail.com</a>
            </p>
            <p className="inquire__where">Athens, Georgia</p>
            <hr className="kit-rule" />
            <div className="inquire__note">
              I respond personally to every note. Most weeks that's
              within a business day; busier weeks within two. If you're
              on a tight deadline, please mention that in your story
              — I'll prioritize.
            </div>
          </div>
        </div>

        {submitted ? thankYou : (
        <form className="inquire__form" onSubmit={submit}>
          <div>
            <label className="form-label">First Name</label>
            <input className="form-input" value={form.first} onChange={set('first')} required />
          </div>
          <div>
            <label className="form-label">Last Name</label>
            <input className="form-input" value={form.last} onChange={set('last')} required />
          </div>
          <div>
            <label className="form-label">Email</label>
            <input type="email" className="form-input" value={form.email} onChange={set('email')} required />
          </div>
          <div>
            <label className="form-label">Phone</label>
            <input type="tel" className="form-input" value={form.phone} onChange={set('phone')} />
          </div>
          <div>
            <label className="form-label">Session Type</label>
            <select className="form-input" value={form.type} onChange={set('type')}>
              <option>Wedding</option>
              <option>Engagement</option>
              <option>Lifestyle / Family</option>
              <option>Editorial / Brand</option>
            </select>
          </div>
          {typeFields.map((f) => (
            <div key={f.k} className={f.span === 2 ? 'form-field--wide' : null}>
              <label className="form-label">{f.label}</label>
              <input
                type={f.type || 'text'}
                className="form-input"
                value={form[f.k]}
                onChange={set(f.k)}
                placeholder={f.ph}
              />
            </div>
          ))}
          <div className="form-field--wide">
            <label className="form-label">Where Did You Hear About Me? *</label>
            <select className="form-input" value={form.referral} onChange={set('referral')} required>
              {/* Empty and disabled, so `required` makes this an actual choice
                  rather than silently defaulting to the first option. */}
              <option value="" disabled>Select one…</option>
              {REFERRALS.map(r => <option key={r}>{r}</option>)}
            </select>
          </div>
          <div className="form-field--wide">
            <label className="form-label">Tell Me Your Story</label>
            <textarea
              className="form-input"
              rows={5}
              value={form.story}
              onChange={set('story')}
              placeholder={storyPlaceholder}
            />
          </div>
          {/* Off-screen and never announced; only a bot fills this in. */}
          <div className="form-hp" aria-hidden="true">
            <label>
              Company
              <input tabIndex={-1} autoComplete="off" value={form.company} onChange={set('company')} />
            </label>
          </div>

          <div className="form-field--wide" style={{ marginTop: 8 }}>
            <button type="submit" className="kit-btn kit-btn--primary kit-btn--lg" disabled={sending}>
              {sending ? 'Sending…' : 'Send the Note'}
            </button>
            {error && <p className="form-error" role="alert">{error}</p>}
            <p className="form-fine">Replies within two business days · No mailing list, ever</p>
          </div>
        </form>
        )}
      </div>
    </section>
  );
}

/* Unused for now — removed from the page per request (2026-07). Kept here in
   case the studio strip is ever wanted again; delete when sure. */
function ContactStrip() {
  return (
    <section className="contact-strip">
      <div className="contact-strip__inner">
        <div className="contact-strip__col">
          <h6>Studio</h6>
          <p>Prince Avenue<br />Athens, GA</p>
          <span>By Appointment Only</span>
        </div>
        <div className="contact-strip__col">
          <h6>Booking Window</h6>
          <p>Now booking 2026 &amp; 2027</p>
          <span>Six Weddings, Per Season</span>
        </div>
        <div className="contact-strip__col">
          <h6>Elsewhere</h6>
          <p>@abbyharperphoto</p>
          <span>Instagram · Pinterest</span>
        </div>
      </div>
    </section>
  );
}

function ContactPage({ onNav }) {
  return (
    <React.Fragment>
      <ContactHeader />
      <InquireForm />
    </React.Fragment>
  );
}

window.ContactPage = ContactPage;
