// pages.jsx — Home, Portfolio, About, Investment, Contact

const { useState: useStateP, useEffect: useEffectP, useRef: useRefP, useMemo: useMemoP } = React;

// ───────────────────────────────────────────────────────────────────────
// Home
// ───────────────────────────────────────────────────────────────────────
function Home({ heroVariant }) {
  const heroImage = HOME_HERO_IMAGE;

  return (
    <main className="page-anim">
      <Hero variant={heroVariant} image={heroImage} images={HERO_IMAGES} />

      {/* Story */}
      <section className="section section-cream" data-screen-label="Home / Story">
        <div className="page-inner story">
          <div className="section-eyebrow">
            <span className="flourish-line"></span>
            <span>The Studio</span>
            <span className="flourish-line"></span>
          </div>
          <p className="story-quote">
            Devoted to a single craft<br/>
            <em>making family portraits worthy of the wall.</em>
          </p>
        </div>
      </section>

      {/* Featured categories */}
      <section className="section section-parchment" data-screen-label="Home / Categories">
        <div className="page-inner">
          <div style={{ textAlign: 'center' }}>
            <div className="section-eyebrow">
              <span className="flourish-line"></span>
              <span>Commissions</span>
              <span className="flourish-line"></span>
            </div>
            <h2 className="section-title">Three commissions,<br/><em>one studio.</em></h2>
          </div>

          <div className="feature-grid">
            {[
              { name: 'Families',  cat: 'families',  img: PHOTOS.families[0].src,  alt: 'Family portrait session at Pinnacle Hills studio, Rogers AR',            blurb: 'A portrait of your family, made to live on the wall.' },
              { name: 'Maternity', cat: 'maternity', img: PHOTOS.maternity[0].src, alt: 'Fine art maternity portrait, Northwest Arkansas photographer',             blurb: 'A quiet record of a season worth keeping.' },
              { name: 'Branding',  cat: 'headshots', img: PHOTOS.headshots[0].src, alt: 'Personal branding and headshot photography, Bentonville Northwest Arkansas', blurb: 'Portraits for founders, partners, and small businesses.' },
            ].map((c) => (
              <a key={c.cat} className="feature-tile" href={`#/portfolio?cat=${c.cat}`} onClick={(e)=>navTo(`#/portfolio?cat=${c.cat}`, e)}>
                <div className="feature-tile-img-wrap">
                  <img src={c.img} alt={c.alt} />
                </div>
                <div className="feature-tile-caption">
                  <span className="feature-tile-name">{c.name}</span>
                  <span className="feature-tile-link">
                    <span>View</span>
                    <span className="arrow">→</span>
                  </span>
                </div>
                <p style={{ marginTop: '0.75rem', fontFamily: 'var(--serif)', fontStyle: 'italic', fontSize: 16, color: 'var(--forest)', opacity: 0.85, lineHeight: 1.55 }}>
                  {c.blurb}
                </p>
              </a>
            ))}
          </div>
        </div>
      </section>

      {/* Process */}
      <section className="section section-cream" data-screen-label="Home / Process">
        <div className="page-inner">
          <div style={{ textAlign: 'center' }}>
            <div className="section-eyebrow">
              <span className="flourish-line"></span>
              <span>The Experience</span>
              <span className="flourish-line"></span>
            </div>
            <h2 className="section-title">Four stations.<br/><em>One considered commission.</em></h2>
          </div>

          <div className="process">
            {[
              { n: 'i',   t: 'The Inquiry',        b: 'A short note begins the conversation. We respond within two business days and set up a planning call so we can get to know you.' },
              { n: 'ii',  t: 'The Planning',       b: 'We talk through the wall, the wardrobe, and the day. Location, light, and pacing are decided together — nothing left to the morning of.' },
              { n: 'iii', t: 'The Sitting',        b: 'Ninety unhurried minutes, in studio or on location. The frame is composed and lit. Children are children. Adults are at ease.' },
              { n: 'iv',  t: 'The Reveal',         b: 'Two weeks later, we present the work in person. Framed prints and albums are ordered through the studio and delivered to your door.' },
            ].map((s) => (
              <div key={s.n} className="process-step">
                <div className="process-num">{s.n}.</div>
                <h3 className="process-title">{s.t}</h3>
                <p className="process-body">{s.b}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* CTA strip */}
      <section className="cta-strip" data-screen-label="Home / CTA">
        <h2><em>Every family in this region</em><br/>deserves work of this kind.</h2>
        <p>We're here to make it. If you're considering a portrait, we'd love to hear from you — tell us a little about your family and the wall you have in mind.</p>
        <button className="btn-line" onClick={() => navTo('#/contact')}>
          <span>Begin an Inquiry</span>
          <span className="arrow">→</span>
        </button>
      </section>

      {/* Instagram strip */}
      <section className="ig-strip" data-screen-label="Home / Instagram">
        <div className="ig-strip-header">
          <div>
            <div style={{ fontFamily: 'var(--sans)', fontSize: 10, letterSpacing: '0.5em', textTransform: 'uppercase', opacity: 0.7, marginBottom: '0.5rem' }}>Recent work</div>
            <div className="ig-strip-h"><em>From the studio</em></div>
          </div>
          <a className="ig-strip-handle" href="https://www.instagram.com/allisonwinklephotography/" target="_blank" rel="noreferrer">
            @pinnaclehillsportraits ↗
          </a>
        </div>
        <div className="ig-grid">
          {[
            ...PHOTOS.families.slice(0, 3),
            ...PHOTOS.maternity.slice(0, 2),
            PHOTOS.headshots[0],
            ...PHOTOS.headshots.slice(1, 3),
            ...PHOTOS.families.slice(3, 7),
          ].slice(0, 12).map((p) => (
            <div key={p.id}><img src={p.src} alt={p.cap} loading="lazy" /></div>
          ))}
        </div>
      </section>
    </main>
  );
}

// ───────────────────────────────────────────────────────────────────────
// Portfolio
// ───────────────────────────────────────────────────────────────────────
const PORTFOLIO_TABS = [
  { id: 'all',       label: 'All Work',  catalogue: () => [
    ...PHOTOS.families, ...PHOTOS.maternity, ...PHOTOS.headshots,
  ]},
  { id: 'families',  label: 'Families',  catalogue: () => PHOTOS.families },
  { id: 'maternity', label: 'Maternity', catalogue: () => PHOTOS.maternity },
  { id: 'headshots', label: 'Branding',  catalogue: () => PHOTOS.headshots },
];

// Editorial layout pattern (cycles): 5-7, 4-4-4, 12, 6-6, 3-3-3-3
const SPAN_PATTERN = [
  [5, 7],
  [4, 4, 4],
  [12],
  [6, 6],
  [3, 3, 3, 3],
  [7, 5],
];

function Portfolio() {
  // Read category from hash
  const [activeTab, setActiveTab] = useStateP(() => {
    const m = window.location.hash.match(/cat=(\w+)/);
    return m ? m[1] : 'all';
  });

  useEffectP(() => {
    const onHash = () => {
      const m = window.location.hash.match(/cat=(\w+)/);
      setActiveTab(m ? m[1] : 'all');
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  const tab = PORTFOLIO_TABS.find(t => t.id === activeTab) || PORTFOLIO_TABS[0];
  const photos = tab.catalogue();

  // Build span layout
  const items = useMemoP(() => {
    const out = [];
    let i = 0, p = 0;
    while (i < photos.length) {
      const row = SPAN_PATTERN[p % SPAN_PATTERN.length];
      for (const span of row) {
        if (i >= photos.length) break;
        out.push({ ...photos[i], span });
        i++;
      }
      p++;
    }
    return out;
  }, [photos]);

  const [lightIdx, setLightIdx] = useStateP(null);

  return (
    <main className="page-anim" data-screen-label="Portfolio">
      <section className="portfolio-hero">
        <div className="section-eyebrow">
          <span className="flourish-line"></span>
          <span>The Portfolio</span>
          <span className="flourish-line"></span>
        </div>
        <h1 className="section-title">Selected commissions,<br/><em>made to be kept.</em></h1>
        <p className="section-sub">
          A rotating selection of recent work, presented as it is delivered — framed, printed, lived with.
        </p>

        <div className="portfolio-tabs">
          {PORTFOLIO_TABS.map(t => (
            <button
              key={t.id}
              className={`portfolio-tab ${activeTab === t.id ? 'is-active' : ''}`}
              onClick={() => {
                setActiveTab(t.id);
                history.replaceState(null, '', t.id === 'all' ? '#/portfolio' : `#/portfolio?cat=${t.id}`);
              }}
            >
              {t.label}
            </button>
          ))}
        </div>
      </section>

      <div className="portfolio-grid">
        {items.map((p, idx) => (
          <div
            key={p.id + idx}
            className={`portfolio-item span-${p.span}`}
            onClick={() => setLightIdx(idx)}
          >
            <img src={p.src} alt={p.cap} loading="lazy" />
            <div className="portfolio-item-cap">{p.cap}</div>
          </div>
        ))}
      </div>

      <Lightbox
        photos={items}
        index={lightIdx}
        onClose={() => setLightIdx(null)}
        onPrev={() => setLightIdx((i) => (i - 1 + items.length) % items.length)}
        onNext={() => setLightIdx((i) => (i + 1) % items.length)}
      />
    </main>
  );
}

// ───────────────────────────────────────────────────────────────────────
// About
// ───────────────────────────────────────────────────────────────────────
function About() {
  return (
    <main className="page-anim" data-screen-label="About">
      <section className="about-hero">
        <div className="about-hero-inner">
          <div className="about-hero-img">
            <img src="assets/allison-ryan.jpeg" alt="Allison and her partner at The Studio at Pinnacle Hills" />
          </div>
          <div>
            <div className="section-eyebrow" style={{ justifyContent: 'flex-start', marginBottom: '1.5rem' }}>
              <span className="flourish-line"></span>
              <span>The Studio</span>
            </div>
            <h1 className="about-hero-head">
              Portraits worthy of<br/><em>the wall.</em>
            </h1>
            <div className="about-hero-body">
              <p>
                Pinnacle Hills Portraits is a Northwest Arkansas studio devoted to a single craft — making family portraits worthy of the wall. We approach each portrait the way a furniture maker approaches a commissioned piece, or a painter approaches a canvas: the light is shaped, the composition is built, and the finished image is printed and framed for your home.
              </p>
              <p>
                The studio serves families across Rogers, Bentonville, Fayetteville, Springdale, and the greater Northwest Arkansas area. Sittings take place in our Pinnacle Hills studio.
              </p>
              <p>
                Every family in this region deserves work of this kind. We're here to make it.
              </p>
            </div>
          </div>
        </div>
      </section>

      {/* Partners */}
      <section className="section partners">
        <div className="page-inner">
          <div style={{ textAlign: 'center' }}>
            <div className="section-eyebrow">
              <span className="flourish-line"></span>
              <span>The Partners</span>
              <span className="flourish-line"></span>
            </div>
            <h2 className="section-title">Two hands. <em>One studio.</em></h2>
          </div>

          <div className="partners-grid">
            <div className="partner">
              <div className="partner-img">
                <img src="assets/allison.jpeg" alt="Allison, photographer and co-founder of Pinnacle Hills Portraits" />
              </div>
              <div>
                <div className="partner-name">Allison</div>
                <div className="partner-role">Photographer · Co-Founder</div>
                <p className="partner-bio">
                  Allison's eye for light, posing, and the quiet details that make a portrait feel alive shapes every sitting from start to finish. Her attention to each small moment — how a hand rests, where the light falls, how a family actually feels in front of a camera — is what turns a session into something worth keeping on the wall.
                </p>
              </div>
            </div>
            <div className="partner">
              <div className="partner-img">
                <img src="assets/ryan.jpeg" alt="Ryan, photographer and co-founder of Pinnacle Hills Portraits" />
              </div>
              <div>
                <div className="partner-name">Ryan</div>
                <div className="partner-role">Photographer · Co-Founder</div>
                <p className="partner-bio">
                  With over fifteen years behind the camera, Ryan brings a deep technical command to every commission — from how the light is built in studio to how the final image is refined in post. He understands both the craft of making a photograph and the precision required to bring it to print exactly as it was seen.
                </p>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Values */}
      <section className="section section-cream">
        <div className="page-inner">
          <div style={{ textAlign: 'center' }}>
            <div className="section-eyebrow">
              <span className="flourish-line"></span>
              <span>What We Stand For</span>
              <span className="flourish-line"></span>
            </div>
            <h2 className="section-title"><em>Crafted. Considered. Kept.</em></h2>
          </div>

          <div className="values">
            {[
              { mark: 'i.',   body: 'Every choice serves the wall. The portrait is the product — not the file, not the gallery, not the count.' },
              { mark: 'ii.',  body: 'A commission is a conversation. We listen carefully, plan together, and treat your family the way we\u2019d want ours treated.' },
              { mark: 'iii.', body: 'What we deliver is finished — retouched, mounted, framed, and ready to hang.' },
            ].map((v, i) => (
              <div key={i} className="value">
                <div className="value-mark">{v.mark}</div>
                <p className="value-body">{v.body}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* CTA */}
      <section className="cta-strip">
        <h2><em>Ready to plan</em><br/>a portrait?</h2>
        <button className="btn-line" onClick={() => navTo('#/contact')}>
          <span>Begin an Inquiry</span>
          <span className="arrow">→</span>
        </button>
      </section>
    </main>
  );
}

// ───────────────────────────────────────────────────────────────────────
// Investment
// ───────────────────────────────────────────────────────────────────────
function Investment() {
  const [openFaq, setOpenFaq] = useStateP(0);

  const TIERS = [
    {
      tag: 'i.',
      name: 'Signature',
      price: 'From $1,500',
      meta: 'Session fee · prints sold separately',
      list: [
        'A planning consultation',
        '10 finished images, retouched to print',
        'Print ordering session at the studio',
        'À la carte prints &amp; framing',
      ],
    },
    {
      tag: 'ii.',
      name: 'Heirloom',
      price: 'From $2,700',
      meta: 'Heirloom collection · most chosen',
      featured: true,
      list: [
        'A planning consultation',
        'Wardrobe direction included',
        '15 finished images, retouched to print',
        'Framed wall portrait (one piece, up to 24×30)',
        'Heirloom folio of ten matted prints',
      ],
    },
    {
      tag: 'iii.',
      name: 'Legacy',
      price: 'From $3,500',
      meta: 'Wall installation · by reservation',
      list: [
        'A planning consultation',
        'in-home wall planning session',
        '30 finished images, retouched',
        'Three framed wall portraits',
        'Linen-bound family album (8x8)',
        'White-glove framing &amp; delivery',
      ],
    },
  ];

  const FAQ = [
    { q: 'How far in advance should we book?',
      a: 'Most families inquire eight to twelve weeks ahead of their sitting date. Autumn dates tend to fill earliest, so a little lead time helps — but if you have something sooner in mind, send a note and we\u2019ll do our best.' },
    { q: 'What is included in the session fee?',
      a: 'The session fee covers planning, the sitting itself, and the editing of the finished work. Framed prints, albums, and digital files are ordered separately or as part of a commission tier.' },
    { q: 'Where do sittings take place?',
      a: 'Your session takes place in the Grand Hall of our studio' },
    { q: 'Do you deliver digital files?',
      a: 'We do, but the work is designed to be printed. Every commission includes high-resolution files of the chosen pieces; the print products are the primary deliverable.' },
    { q: 'What should we wear?',
      a: 'Wardrobe is part of the planning conversation. We guide families toward muted, considered palettes — cream, oat, forest, charcoal — and away from logos and busy pattern.' },
  ];

  return (
    <main className="page-anim" data-screen-label="Investment">
      <section className="invest-hero">
        <div className="section-eyebrow">
          <span className="flourish-line"></span>
          <span>Investment</span>
          <span className="flourish-line"></span>
        </div>
        <h1 className="section-title">A considered commission,<br/><em>at three scales.</em></h1>
        <p className="invest-intro">
          We offer three levels of commission so families can find the right fit for their wall and their budget. Every level begins with a planning consultation and ends with finished, framed work — what changes is how much of the wall is filled.
        </p>
      </section>

      <section style={{ padding: '0 var(--page-pad) var(--density-y)', background: 'var(--cream)' }}>
        <div className="tiers">
          {TIERS.map((t, i) => (
            <div key={i} className={`tier ${t.featured ? 'is-featured' : ''}`}>
              <div className="tier-eyebrow">{t.tag}</div>
              {t.featured && <span className="tier-tag">Most chosen</span>}
              <div className="tier-name">{t.name}</div>
              <div className="tier-price">
                {t.price}
                <small>{t.meta}</small>
              </div>
              <hr className="tier-divider" />
              <ul className="tier-list">
                {t.list.map((l, k) => <li key={k} dangerouslySetInnerHTML={{ __html: l }} />)}
              </ul>
              <div className="tier-cta">
                <button className="hero-split-cta" onClick={() => navTo('#/contact')}>
                  <span>Inquire</span>
                  <span className="arrow">→</span>
                </button>
              </div>
            </div>
          ))}
        </div>
      </section>

      {/* Add-ons */}
      <section className="section section-parchment">
        <div className="page-inner">
          <div style={{ textAlign: 'center' }}>
            <div className="section-eyebrow">
              <span className="flourish-line"></span>
              <span>Print &amp; Framing</span>
              <span className="flourish-line"></span>
            </div>
            <h2 className="section-title">A la carte.</h2>
            <p className="section-sub">
              Pieces ordered separately, or in addition to a commission. Every print is mounted, finished, and delivered installation-ready.
            </p>
          </div>

          <div className="addons" style={{ marginTop: '4rem' }}>
            {[
              { name: 'Framed wall portrait', meta: 'Up to 16×20 · museum mat · white oak or black ash frame', price: 'from $480' },
              { name: 'Statement wall piece', meta: '24×30 or 30×40 · museum mat · gallery framing', price: 'from $960' },
              { name: 'Heirloom folio',       meta: 'Ten 8×10 prints, linen-bound presentation case', price: '$640' },
              { name: 'Family album',         meta: '10×12 · linen-bound · twenty spreads', price: 'from $1,200' },
              { name: 'Digital file (single)', meta: 'High-resolution master, print release included', price: '$95' },
            ].map((a, i) => (
              <div key={i} className="addon-row">
                <div className="addon-name">
                  {a.name}
                  <small>{a.meta}</small>
                </div>
                <div className="addon-price">{a.price}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* FAQ */}
      <section className="section section-cream">
        <div className="page-inner">
          <div style={{ textAlign: 'center' }}>
            <div className="section-eyebrow">
              <span className="flourish-line"></span>
              <span>Questions</span>
              <span className="flourish-line"></span>
            </div>
            <h2 className="section-title">A few <em>commonly asked.</em></h2>
          </div>

          <div className="invest-faq" style={{ marginTop: '4rem' }}>
            {FAQ.map((f, i) => (
              <div key={i} className={`faq-row ${openFaq === i ? 'is-open' : ''}`}>
                <button className="faq-q" onClick={() => setOpenFaq(openFaq === i ? -1 : i)}>
                  <span>{f.q}</span>
                  <span className="faq-q-mark">+</span>
                </button>
                <div className="faq-a">{f.a}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      <section className="cta-strip">
        <h2><em>Every family in this region</em><br/>deserves work of this kind.</h2>
        <p>We're here to make it. Send us a note when you're ready and we'll set up a planning call.</p>
        <button className="btn-line" onClick={() => navTo('#/contact')}>
          <span>Begin an Inquiry</span>
          <span className="arrow">→</span>
        </button>
      </section>
    </main>
  );
}

// ───────────────────────────────────────────────────────────────────────
// Contact
// ───────────────────────────────────────────────────────────────────────
function Contact() {
  const [form, setForm] = useStateP({
    name: '', 
    email: '', 
    phone: '',
    commission: '',
    message: '',
  });
  const [errors, setErrors] = useStateP({});
  const [submitted, setSubmitted] = useStateP(false);
  const [sending, setSending] = useStateP(false);
  const [sendError, setSendError] = useStateP(null);

  const commissions = ['Families', 'Maternity', 'Branding', 'Not yet sure'];

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const submit = async (e) => {
    e.preventDefault();
    const errs = {};
    if (!form.name.trim()) errs.name = 'Please share your name.';
    if (!form.email.trim() || !/^\S+@\S+\.\S+$/.test(form.email)) errs.email = 'A working email, please.';
    if (!form.commission) errs.commission = 'Please choose one.';
    if (!form.message.trim() || form.message.trim().length < 12) errs.message = 'A sentence or two helps us prepare.';
    setErrors(errs);
    if (Object.keys(errs).length > 0) return;

    setSending(true);
    setSendError(null);
    try {
      const res = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      });
      if (!res.ok) throw new Error('send failed');
      setSubmitted(true);
      window.scrollTo({ top: 0, behavior: 'smooth' });
    } catch {
      setSendError('Something went wrong — please email us directly at studio@pinnaclehillsportraits.com.');
    } finally {
      setSending(false);
    }
  };

  if (submitted) {
    return (
      <main className="page-anim contact-hero" data-screen-label="Contact / Success">
        <div className="contact-grid" style={{ display: 'block', maxWidth: 720, textAlign: 'center' }}>
          <div className="section-eyebrow" style={{ justifyContent: 'center' }}>
            <span className="flourish-line"></span>
            <span>Thank you</span>
            <span className="flourish-line"></span>
          </div>
          <h1 className="about-hero-head" style={{ textAlign: 'center', marginBottom: '2rem' }}>
            Your note <em>has arrived.</em>
          </h1>
          <p style={{ fontFamily: 'var(--serif)', fontSize: 20, lineHeight: 1.7, color: 'var(--forest)', maxWidth: '52ch', margin: '0 auto' }}>
            We'll be in touch within two business days. In the meantime, a reply with a planning questionnaire is on its way to <em>{form.email}</em>.
          </p>
          <button className="btn-line" style={{ color: 'var(--forest)', borderBottomColor: 'var(--forest)', marginTop: '3rem' }}
            onClick={() => navTo('#/portfolio')}>
            <span>Return to the work</span>
            <span className="arrow">→</span>
          </button>
        </div>
        <Footer />
      </main>
    );
  }

  return (
    <main className="page-anim" data-screen-label="Contact">
      <section className="contact-hero">
        <div className="contact-grid">
          <div className="contact-intro">
            <div className="section-eyebrow" style={{ justifyContent: 'flex-start', marginBottom: '1.5rem' }}>
              <span className="flourish-line"></span>
              <span>Begin an Inquiry</span>
            </div>
            <h1>A short note<br/><em>begins it.</em></h1>
            <p>
              Tell us a little about your family and the portraits you have in mind. We respond within two business days, and we'd love to hear from you.
            </p>

            <div className="contact-meta">
              <div className="contact-meta-row">
                <div className="contact-meta-label">The Studio</div>
                <div className="contact-meta-value">141 White St<br/>Farmington, AR 72730</div>
              </div>
              <div className="contact-meta-row">
                <div className="contact-meta-label">Hours</div>
                <div className="contact-meta-value">By appointment only</div>
              </div>
              <div className="contact-meta-row">
                <div className="contact-meta-label">Direct</div>
                <div className="contact-meta-value">studio@pinnaclehillsportraits.com</div>
              </div>
            </div>
          </div>

          <form className="form" onSubmit={submit} noValidate>
            <div className="form-grid">
              <div className={`field ${errors.name ? 'is-error' : ''}`}>
                <label>Your name</label>
                <input type="text" placeholder="First and last" value={form.name} onChange={(e) => set('name', e.target.value)} />
                <span className="field-error">{errors.name}</span>
              </div>
              <div className={`field ${errors.email ? 'is-error' : ''}`}>
                <label>Email</label>
                <input type="email" placeholder="you@example.com" value={form.email} onChange={(e) => set('email', e.target.value)} />
                <span className="field-error">{errors.email}</span>
              </div>

              <div className="field">
                <label>Phone (optional)</label>
                <input type="tel" placeholder="479 · 555 · 0000" value={form.phone} onChange={(e) => set('phone', e.target.value)} />
              </div>
              <div className="field">
                <label>Town</label>
                <input type="text" placeholder="Rogers, Bentonville…" value={form.location} onChange={(e) => set('location', e.target.value)} />
              </div>

              <div className={`field field-full ${errors.commission ? 'is-error' : ''}`}>
                <label>Type of commission</label>
                <div className="radio-group">
                  {commissions.map(c => (
                    <button type="button" key={c}
                      className={`radio-pill ${form.commission === c ? 'is-selected' : ''}`}
                      onClick={() => set('commission', c)}>
                      {c}
                    </button>
                  ))}
                </div>
                <span className="field-error">{errors.commission}</span>
              </div>

              <div className={`field field-full ${errors.message ? 'is-error' : ''}`}>
                <label>Tell us about your vision</label>
                <textarea placeholder="A few sentences about your family, the season, or the wall this is for." value={form.message} onChange={(e) => set('message', e.target.value)} />
                <span className="field-error">{errors.message}</span>
              </div>

              <div className="form-submit">
                <p className="form-fine">
                  By inquiring, you agree to receive a single reply from the studio. We do not share addresses.
                </p>
                {sendError && (
                  <p style={{ color: 'var(--rust, #b94a2c)', fontFamily: 'var(--serif)', fontSize: 15, marginBottom: '1rem' }}>
                    {sendError}
                  </p>
                )}
                <button type="submit" className="btn-submit" disabled={sending}>
                  <span>{sending ? 'Sending…' : 'Send Inquiry'}</span>
                  {!sending && <span className="arrow">→</span>}
                </button>
              </div>
            </div>
          </form>
        </div>
      </section>
    </main>
  );
}

// ─── Questionnaire ───────────────────────────────────────────────────────────
function Questionnaire() {
  const params = new URLSearchParams((window.location.hash.split('?')[1]) || '');
  const token = params.get('token');
  const email = params.get('email') || '';
  const name  = params.get('name')  || '';
  const firstName = name.split(' ')[0] || 'there';

  const artworkOptions  = ['Wall Art', 'Canvas', 'Prints', 'Heirloom Album'];
  const referralOptions = ['Friend or Family', 'Social Media', 'Google', 'Community Event', 'Other'];

  const [form, setForm] = useStateP({ q1:'', q2:'', q3:'', q4:'', q5:[], q6:'', q7:'' });
  const [errors,    setErrors]    = useStateP({});
  const [submitted, setSubmitted] = useStateP(false);
  const [sending,   setSending]   = useStateP(false);
  const [sendError, setSendError] = useStateP(null);

  const set      = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const toggleQ5 = (val) => setForm(f => ({
    ...f,
    q5: f.q5.includes(val) ? f.q5.filter(x => x !== val) : [...f.q5, val],
  }));

  if (!token || !email) {
    return (
      <main className="page-anim" style={{ minHeight: '70vh', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <div style={{ textAlign: 'center', maxWidth: 480, padding: '0 2rem' }}>
          <div className="section-eyebrow" style={{ justifyContent: 'center', marginBottom: '1.5rem' }}>
            <span className="flourish-line"></span>
            <span>Pinnacle Hills Portraits</span>
            <span className="flourish-line"></span>
          </div>
          <h1 style={{ fontFamily: 'var(--serif)', fontSize: 'clamp(1.6rem,4vw,2.2rem)', fontWeight: 400, fontStyle: 'italic', color: 'var(--forest)', marginBottom: '1.25rem', lineHeight: 1.3 }}>
            This page is only accessible<br /><em>from your planning email.</em>
          </h1>
          <p style={{ fontFamily: 'var(--sans)', fontSize: 14, color: 'var(--forest)', opacity: 0.65, lineHeight: 1.8, marginBottom: '2.5rem' }}>
            Your personal questionnaire link was sent to your email after you submitted an inquiry. Please check your inbox for a message from Pinnacle Hills Portraits.
          </p>
          <button className="btn-line" style={{ color: 'var(--forest)', borderBottomColor: 'var(--forest)' }} onClick={() => navTo('#/contact')}>
            <span>Submit an Inquiry</span>
            <span className="arrow">→</span>
          </button>
        </div>
      </main>
    );
  }

  const submit = async (e) => {
    e.preventDefault();
    const errs = {};
    if (!form.q1.trim())       errs.q1 = 'Please share your thoughts.';
    if (!form.q2.trim())       errs.q2 = 'Please share your thoughts.';
    if (!form.q3.trim())       errs.q3 = 'Please share your thoughts.';
    if (!form.q4.trim())       errs.q4 = 'Please share your thoughts.';
    if (form.q5.length === 0)  errs.q5 = 'Please select at least one.';
    if (!form.q6.trim())       errs.q6 = 'Please share your thoughts.';
    if (!form.q7)              errs.q7 = 'Please select one.';
    setErrors(errs);
    if (Object.keys(errs).length > 0) {
      const first = document.querySelector('.is-error');
      if (first) first.scrollIntoView({ behavior: 'smooth', block: 'center' });
      return;
    }
    setSending(true);
    setSendError(null);
    try {
      const res = await fetch('/api/questionnaire', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ token, email, name, ...form }),
      });
      if (!res.ok) throw new Error('send failed');
      setSubmitted(true);
      window.scrollTo({ top: 0, behavior: 'smooth' });
    } catch {
      setSendError('Something went wrong — please email us directly at studio@pinnaclehillsportraits.com.');
    } finally {
      setSending(false);
    }
  };

  if (submitted) {
    return (
      <main className="page-anim contact-hero" data-screen-label="Questionnaire / Complete">
        <div className="contact-grid" style={{ display: 'block', maxWidth: 720, textAlign: 'center' }}>
          <div className="section-eyebrow" style={{ justifyContent: 'center' }}>
            <span className="flourish-line"></span>
            <span>Thank you</span>
            <span className="flourish-line"></span>
          </div>
          <h1 className="about-hero-head" style={{ textAlign: 'center', marginBottom: '2rem' }}>
            Your answers <em>have arrived.</em>
          </h1>
          <p style={{ fontFamily: 'var(--serif)', fontSize: 20, lineHeight: 1.7, color: 'var(--forest)', maxWidth: '52ch', margin: '0 auto' }}>
            We've received your planning questionnaire and we're so looking forward to creating something truly meaningful for your family. We'll be in touch soon.
          </p>
          <button className="btn-line" style={{ color: 'var(--forest)', borderBottomColor: 'var(--forest)', marginTop: '3rem' }}
            onClick={() => navTo('#/portfolio')}>
            <span>Explore the work</span>
            <span className="arrow">→</span>
          </button>
        </div>
      </main>
    );
  }

  const qa = (key, num, question, prompt, input) => (
    <div key={key} className={errors[key] ? 'is-error' : ''} style={{ padding: '2.5rem 0' }}>
      <p style={{ margin: '0 0 0.4rem', fontFamily: 'var(--sans)', fontSize: 11, letterSpacing: '0.2em', textTransform: 'uppercase', color: '#9aaa94' }}>{num}</p>
      <p style={{ margin: '0 0 0.5rem', fontFamily: 'var(--serif)', fontSize: 'clamp(1.1rem,2.5vw,1.3rem)', fontStyle: 'italic', color: 'var(--forest)', lineHeight: 1.5 }}>{question}</p>
      <p style={{ margin: '0 0 1.25rem', fontFamily: 'var(--sans)', fontSize: 13, color: '#7a8a74', lineHeight: 1.75 }}>{prompt}</p>
      {input}
      {errors[key] && <span className="field-error" style={{ display: 'block', marginTop: '0.5rem' }}>{errors[key]}</span>}
    </div>
  );

  const placeholders = {
    q1: 'Share whatever feels true — a milestone, a season of life, a feeling you want to hold onto…',
    q2: 'The laughter, the closeness, the way your children looked at this age…',
    q3: 'Tell us who will be there and what they mean to you…',
    q4: 'The way your daughter lights up a room, the quiet bond between siblings…',
    q6: 'Above the fireplace, along the staircase, in the entryway…',
  };

  const ta = (key) => (
    <div className="field" style={{ border: 'none', padding: 0 }}>
      <textarea value={form[key]}
        onChange={e => {
          set(key, e.target.value);
          e.target.style.height = 'auto';
          e.target.style.height = e.target.scrollHeight + 'px';
        }}
        placeholder={placeholders[key] || ''}
        style={{ width: '100%', minHeight: 48, boxSizing: 'border-box', overflow: 'hidden', resize: 'none' }} />
    </div>
  );

  return (
    <main className="page-anim" data-screen-label="Questionnaire">
      <section style={{ maxWidth: 720, margin: '0 auto', padding: 'clamp(5rem,10vw,8rem) 2rem 6rem' }}>

        <div style={{ textAlign: 'center', marginBottom: '3.5rem' }}>
          <div className="section-eyebrow" style={{ justifyContent: 'center', marginBottom: '1.25rem' }}>
            <span className="flourish-line"></span>
            <span>Portrait Planning</span>
            <span className="flourish-line"></span>
          </div>
          <h1 style={{ fontFamily: 'var(--serif)', fontSize: 'clamp(2rem,5vw,3rem)', fontWeight: 400, color: 'var(--forest)', marginBottom: '1.5rem', lineHeight: 1.25 }}>
            A few questions,<br /><em>for a portrait worth keeping.</em>
          </h1>
          <p style={{ fontFamily: 'var(--serif)', fontSize: 'clamp(1rem,2vw,1.15rem)', color: 'var(--forest)', lineHeight: 1.85, maxWidth: '50ch', margin: '0 auto', opacity: 0.85 }}>
            Dear {firstName}, your answers help us create an experience that is entirely yours. There are no right or wrong answers — only your story.
          </p>
        </div>

        <hr style={{ border: 'none', borderTop: '1px solid var(--rule)', margin: '0 0 0' }} />

        <form onSubmit={submit} noValidate>

          {qa('q1', '01',
            'What inspired you to commission portraits at this time in your family\'s story?',
            'We would love to learn what makes this season of life meaningful and worth preserving.',
            ta('q1')
          )}

          {qa('q2', '02',
            'Imagine looking back at these portraits twenty years from now. What do you hope they will remind you of?',
            'Tell us about the memories, emotions, and moments you hope these images will preserve for future generations.',
            ta('q2')
          )}

          {qa('q3', '03',
            'Who are the most important people you would like these portraits to celebrate?',
            'Please tell us about the individuals who will be photographed and the relationships that matter most to you.',
            ta('q3')
          )}

          {qa('q4', '04',
            'What qualities, personalities, or connections would you love for us to capture?',
            'The most treasured portraits often reveal more than appearances — they reflect the people we love and who they are.',
            ta('q4')
          )}

          {qa('q5', '05',
            'When you imagine your finished portraits, what feels most meaningful to you?',
            'Select all that resonate with you.',
            <div className="radio-group">
              {artworkOptions.map(opt => (
                <button type="button" key={opt}
                  className={`radio-pill ${form.q5.includes(opt) ? 'is-selected' : ''}`}
                  onClick={() => toggleQ5(opt)}>
                  {opt}
                </button>
              ))}
            </div>
          )}

          {qa('q6', '06',
            'Where do you envision displaying your finished artwork?',
            'If you already have a room, wall, or special place in mind, please tell us about it.',
            ta('q6')
          )}

          {qa('q7', '07',
            'How did you first hear about Pinnacle Hills Portraits?',
            'We\'d love to know what connected us.',
            <div className="radio-group">
              {referralOptions.map(opt => (
                <button type="button" key={opt}
                  className={`radio-pill ${form.q7 === opt ? 'is-selected' : ''}`}
                  onClick={() => set('q7', opt)}>
                  {opt}
                </button>
              ))}
            </div>
          )}

          <div style={{ paddingTop: '3rem' }}>
            {sendError && (
              <p style={{ fontFamily: 'var(--sans)', fontSize: 13, color: '#a04040', marginBottom: '1rem', lineHeight: 1.6 }}>{sendError}</p>
            )}
            <button type="submit" className="btn-submit" disabled={sending}>
              <span>{sending ? 'Sending…' : 'Submit Your Questionnaire'}</span>
              {!sending && <span className="arrow">→</span>}
            </button>
          </div>

        </form>
      </section>
    </main>
  );
}

Object.assign(window, { Home, Portfolio, About, Investment, Contact, Questionnaire });
