/* ============================================================
   New Liberty Homes — Shared components
   ============================================================ */
const { useState } = React;
const Icon = window.Icon;

// ── Logo Mark ────────────────────────────────────────────────
function BrandMark({ size = 52 }) {
  return (
    <div className="brand-mark" style={{width:size,height:size}}>
      <svg viewBox="0 0 32 32" fill="none">
        {/* Stylized house with star */}
        <path d="M5 14l11-8 11 8v13a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V14z" stroke="#fff" strokeWidth="1.6" strokeLinejoin="round"/>
        <path d="M13 28v-7h6v7" stroke="#fff" strokeWidth="1.6" strokeLinejoin="round"/>
        <path d="M16 8.5l.9 2 2 .3-1.5 1.4.4 2-1.8-1-1.8 1 .4-2-1.5-1.4 2-.3z" fill="#B3141E" stroke="#B3141E" strokeWidth="0.4" strokeLinejoin="round"/>
      </svg>
    </div>
  );
}

// ── Status Badge ─────────────────────────────────────────────
function StatusBadge({ status }) {
  const cls = status.toLowerCase();
  return <span className={`status-badge ${cls}`}>{status}</span>;
}

// ── 3D Tour Modal (embedded iframe — stays on same tab) ──────
function Tour3DModal({ url, title, onClose }) {
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = prev;
    };
  }, [onClose]);
  return (
    <div className="tour3d-backdrop" onClick={onClose}>
      <div className="tour3d-frame" onClick={e => e.stopPropagation()}>
        <div className="tour3d-bar">
          <span className="tour3d-title">▶ 3D Tour{title ? ` — ${title}` : ''}</span>
          <button className="tour3d-close" onClick={onClose} aria-label="Close 3D tour">✕</button>
        </div>
        <iframe
          src={url}
          title={title ? `3D Tour — ${title}` : '3D Tour'}
          allow="xr-spatial-tracking; fullscreen; vr"
          allowFullScreen
          frameBorder="0"
        />
      </div>
    </div>
  );
}

// ── Home Card ────────────────────────────────────────────────
function HomeCard({ home, onView, onNotify }) {
  const isComingSoon = home.status === 'Coming Soon';
  const [tourOpen, setTourOpen] = useState(false);
  return (
    <article className="home-card">
      <div className="home-img">
        <StatusBadge status={home.status} />
        <button className="home-fav" aria-label="Save home"><Icon.Heart /></button>
        {Array.isArray(home.gallery) && home.gallery[0] ? (
          <img
            src={home.gallery[0].src}
            alt={`${home.name} — ${home.gallery[0].caption || 'home photo'}`}
            className="home-img-photo"
            loading="lazy"
          />
        ) : (
          <div className="home-img-ph">
            <Icon.Camera />
            <small>{home.photosComingSoon ? 'Photos coming soon' : 'Home photo'}</small>
          </div>
        )}
        {home.tour3d && (
          <button
            type="button"
            className="home-img-3d"
            onClick={e => { e.stopPropagation(); setTourOpen(true); }}
          >
            <span>▶</span> 3D Tour
          </button>
        )}
        {tourOpen && (
          <Tour3DModal url={home.tour3d} title={home.name} onClose={() => setTourOpen(false)} />
        )}
      </div>
      <div className="home-body">
        <div className="home-location"><Icon.MapPin />{home.location}</div>
        <h3 className="home-name">{home.name}</h3>
        <div className="home-specs">
          {home.beds && (
            <div className="home-spec">
              <span className="home-spec-val">{home.beds}</span>
              <span className="home-spec-lbl">Beds</span>
            </div>
          )}
          {home.baths && (
            <div className="home-spec">
              <span className="home-spec-val">{home.baths}</span>
              <span className="home-spec-lbl">Baths</span>
            </div>
          )}
          {home.sqft && (
            <div className="home-spec">
              <span className="home-spec-val">{home.sqft}</span>
              <span className="home-spec-lbl">Sq Ft</span>
            </div>
          )}
          {home.lotAcres && (
            <div className="home-spec">
              <span className="home-spec-val">{home.lotAcres}</span>
              <span className="home-spec-lbl">Lot Acres</span>
            </div>
          )}
          {!home.beds && !home.baths && !home.sqft && !home.lotAcres && (
            <div className="home-specs-tbd">Details coming soon</div>
          )}
        </div>
        <div className="home-foot">
          <div className="home-price-block">
            <span className="home-price-lbl">Starting at</span>
            <span className="home-price">${home.price}</span>
          </div>
          <div className="home-cta-row">
            <button type="button" className="home-cta" onClick={() => onView && onView(home)}>
              View <Icon.Arrow />
            </button>
            {isComingSoon && (
              <button type="button" className="home-cta home-cta--notify" onClick={() => onNotify && onNotify(home)}>
                🔔 Notify Me
              </button>
            )}
          </div>
        </div>
      </div>
    </article>
  );
}

// ── Get Notified Modal ──────────────────────────────────────
function GetNotifiedModal({ home, onClose }) {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [phone, setPhone] = useState('');
  const [submitted, setSubmitted] = useState(false);

  if (!home) return null;

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal-card modal-card--sm" onClick={e => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose} aria-label="Close">✕</button>
        {submitted ? (
          <div className="modal-success">
            <div className="modal-success-icon">🔔</div>
            <h3>You're on the alert list!</h3>
            <p>Thanks, {name.split(' ')[0] || 'there'} — we'll let you know the moment <strong>{home.name}</strong> in {home.location} is available. Usually 7–14 days before it's public.</p>
          </div>
        ) : (
          <>
            <div className="modal-eyebrow">Coming Soon · {home.location}</div>
            <h2 className="modal-title">{home.name}</h2>
            <p className="modal-sub">This home isn't here yet, but it's on the way. Drop your info and we'll text and email you the second it's ready to tour.</p>
            <form onSubmit={e => { e.preventDefault(); setSubmitted(true); }}>
              <div className="field">
                <label>Full Name <span className="req">*</span></label>
                <input className="input" type="text" value={name} onChange={e => setName(e.target.value)} placeholder="First & last name" required />
              </div>
              <div className="field">
                <label>Email <span className="req">*</span></label>
                <input className="input" type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="you@email.com" required />
              </div>
              <div className="field" style={{ marginBottom: 0 }}>
                <label>Phone <span className="req">*</span></label>
                <input className="input" type="tel" value={phone} onChange={e => setPhone(e.target.value)} placeholder="(555) 000-0000" required />
              </div>
              <button type="submit" className="btn btn-primary btn-block btn-lg" style={{ marginTop: 18 }}>🔔 Notify Me When Ready</button>
              <div style={{ fontSize: 12, color: 'var(--muted)', textAlign: 'center', marginTop: 12 }}>No spam, no hassles. Unsubscribe any time.</div>
            </form>
          </>
        )}
      </div>
    </div>
  );
}

// ── Home Details Modal ──────────────────────────────────────
function HomeDetailsModal({ home, onClose }) {
  const [tab, setTab] = useState('Photos');
  const [preApprovalOpen, setPreApprovalOpen] = useState(false);
  const [tour3dOpen, setTour3dOpen] = useState(false);
  const [lightboxIdx, setLightboxIdx] = useState(null);
  const galleryLen = Array.isArray(home.gallery) ? home.gallery.length : 0;
  const openLightbox = (i) => setLightboxIdx(i);
  const closeLightbox = () => setLightboxIdx(null);
  const lbNext = () => setLightboxIdx(i => (i + 1) % galleryLen);
  const lbPrev = () => setLightboxIdx(i => (i - 1 + galleryLen) % galleryLen);

  React.useEffect(() => {
    if (lightboxIdx === null) return;
    const onKey = (e) => {
      if (e.key === 'Escape') closeLightbox();
      else if (e.key === 'ArrowRight') lbNext();
      else if (e.key === 'ArrowLeft') lbPrev();
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [lightboxIdx, galleryLen]);
  if (!home) return null;

  const tabs = ['Photos', 'Floor Plans', 'Specs', 'Site Package'];
  const defaultFeatures = ['Garage Ready', 'Walk-in Pantry', 'Endwall Entry', 'Kitchen Island', 'Freestanding Bath Tub', 'Utility Room', 'Walk-in Shower', 'Energy Star Appliances'];
  const features = home.features || defaultFeatures;
  const description = home.description || `This manufactured home is built to the federal (HUD) building code for manufactured housing. Quality construction, modern finishes, and an open floor plan designed for real Texas families.`;
  const hasSitePackage = Array.isArray(home.sitePackage) && home.sitePackage.length > 0;

  // ── Spec rows (auto-populated from data) ──
  const specRows = [
    home.address && { label: 'Address', value: home.address },
    home.brand && { label: 'Brand', value: home.brand },
    home.model && { label: 'Model', value: home.model },
    home.modelYear && { label: 'Model Year', value: home.modelYear },
    home.sectionType && { label: 'Section', value: home.sectionType },
    home.beds && { label: 'Bedrooms', value: home.beds },
    home.baths && { label: 'Bathrooms', value: home.baths },
    home.sqft && { label: 'Square Feet', value: home.sqft },
    home.lotAcres && { label: 'Lot Acres', value: home.lotAcres },
    home.constructionType && { label: 'Construction', value: `${home.constructionType} — Federal Manufactured Housing Code` },
    home.homePrice && { label: 'Home Price', value: `$${home.homePrice}` },
    home.sitePrice && { label: 'Site Package', value: `$${home.sitePrice}` },
  ].filter(Boolean);

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal-card modal-card--lg" onClick={e => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose} aria-label="Close">✕</button>

        {/* Gallery */}
        <div className="modal-gallery">
          <div className="modal-gallery-main">
            {Array.isArray(home.gallery) && home.gallery[0] ? (
              <img
                className="modal-gallery-hero"
                src={home.gallery[0].src}
                alt={`${home.name} — ${home.gallery[0].caption || 'hero shot'}`}
                onClick={() => openLightbox(0)}
                style={{ cursor: 'zoom-in' }}
              />
            ) : (
              <div className="modal-gallery-ph">
                <Icon.Camera />
                <small>Hero shot · {home.name}</small>
              </div>
            )}
            {home.tour3d ? (
              <button
                type="button"
                className="modal-gallery-cta"
                onClick={() => setTour3dOpen(true)}
              >
                ▶ Explore 3D Space
              </button>
            ) : (
              <div className="modal-gallery-cta">▶ Explore 3D Space</div>
            )}
          </div>
          <div className="modal-gallery-grid">
            {Array.isArray(home.gallery) && home.gallery.length > 1 ? (
              home.gallery.slice(1, 5).map((g, i, arr) => {
                const isLast = i === arr.length - 1;
                const remaining = home.gallery.length - 5;
                return (
                  <div className="modal-gallery-small" key={i} onClick={() => openLightbox(i + 1)} style={{ cursor: 'zoom-in' }}>
                    <img src={g.src} alt={g.caption || `${home.name} photo ${i + 2}`} />
                    {isLast && remaining > 0 && (
                      <div className="modal-gallery-overlay">+{remaining} photos</div>
                    )}
                  </div>
                );
              })
            ) : (
              <>
                <div className="modal-gallery-small"><Icon.Camera /><small>Exterior</small></div>
                <div className="modal-gallery-small"><Icon.Camera /><small>Elevation</small></div>
                <div className="modal-gallery-small"><span style={{fontSize:24}}>▶</span><small>Walkthrough</small></div>
                <div className="modal-gallery-small">
                  <Icon.Camera />
                  <small>+28 photos</small>
                </div>
              </>
            )}
          </div>
        </div>

        {home.photosNotice && (
          <div className="modal-photos-notice" role="note">
            <strong>Note:</strong> {home.photosNotice}
          </div>
        )}

        {/* Tabs */}
        <div className="modal-tabs">
          {tabs.map(t => (
            <button key={t} className={`modal-tab${tab === t ? ' active' : ''}`} onClick={() => setTab(t)}>{t}</button>
          ))}
        </div>

        {/* Body */}
        <div className="modal-body">
          <div className="modal-location"><Icon.MapPin /> {home.location} · {home.status}</div>
          <h2 className="modal-h">{home.name}</h2>
          {(home.sqft || home.lotAcres) && (
            <div className="modal-specs-line">{home.sqft ? `${home.sqft} Square Feet` : ''}{home.sqft && home.lotAcres ? ' · ' : ''}{home.lotAcres ? `${home.lotAcres} Acre Lot` : ''}</div>
          )}
          {(home.beds || home.baths || home.sectionType) ? (
            <div className="modal-specs-row">
              {home.beds && <span>{home.beds} beds</span>}
              {home.beds && home.baths && <span className="modal-dot">·</span>}
              {home.baths && <span>{home.baths} baths</span>}
              {home.sectionType && <>
                <span className="modal-dot">·</span>
                <span>{home.sectionType}</span>
              </>}
            </div>
          ) : (
            <div className="modal-specs-row"><span style={{ color: 'var(--red)', fontWeight: 700 }}>Details coming soon</span></div>
          )}
          <p className="modal-desc">{description}</p>

          {tab === 'Floor Plans' && (
            <div className="modal-floorplan">
              {Array.isArray(home.floorPlans) && home.floorPlans.length > 0 ? (
                <div className="floorplan-imgs">
                  {home.floorPlans.map((fp, i) => (
                    <figure className="floorplan-img" key={i}>
                      <img src={fp.src} alt={fp.caption || `Floor plan ${i+1}`} />
                      {fp.caption && <figcaption>{fp.caption}</figcaption>}
                    </figure>
                  ))}
                </div>
              ) : (
                <FloorPlanSVG home={home} />
              )}
            </div>
          )}

          {tab === 'Specs' && (
            <div className="modal-spectable">
              {specRows.map(r => (
                <div className="modal-specrow" key={r.label}>
                  <span className="modal-specrow-lbl">{r.label}</span>
                  <span className="modal-specrow-val">{r.value}</span>
                </div>
              ))}
            </div>
          )}

          {tab === 'Site Package' && (
            hasSitePackage ? (
              <div className="modal-sitepkg">
                <div className="modal-sitepkg-intro">Turn-key setup included — everything to get the home delivered, sited, and ready to live in.</div>
                <div className="modal-features-grid">
                  {home.sitePackage.map(s => (
                    <div className="modal-feature" key={s}>
                      <div className="modal-feature-icon"><Icon.Check /></div>
                      <span>{s}</span>
                    </div>
                  ))}
                </div>
                {home.sitePrice && <div className="modal-sitepkg-total">Site package total: <strong>${home.sitePrice}</strong></div>}
              </div>
            ) : (
              <div className="modal-empty">Site package details available on request.</div>
            )
          )}

          {tab === 'Photos' && (
            <>
              <h3 className="modal-section-title">Home Features</h3>
              <div className="modal-features-grid">
                {features.map(f => (
                  <div className="modal-feature" key={f}>
                    <div className="modal-feature-icon">
                      <Icon.Check />
                    </div>
                    <span>{f}</span>
                  </div>
                ))}
              </div>
            </>
          )}

          <div className="modal-price-block">
            <div>
              <div className="modal-price-lbl">Starting at</div>
              <div className="modal-price">${home.price}</div>
              {home.homePrice && home.sitePrice && (
                <div className="modal-price-breakdown">Home ${home.homePrice} + site package ${home.sitePrice}</div>
              )}
            </div>
            <div style={{display:'flex',gap:10,flexWrap:'wrap'}}>
              <button type="button" onClick={() => setPreApprovalOpen(true)} className="btn btn-primary btn-sm">Apply / Inquire</button>
            </div>
          </div>
        </div>
      </div>
      {preApprovalOpen && <PreApprovalModal home={home} onClose={() => setPreApprovalOpen(false)} />}
      {tour3dOpen && home.tour3d && (
        <Tour3DModal url={home.tour3d} title={home.name} onClose={() => setTour3dOpen(false)} />
      )}
      {lightboxIdx !== null && Array.isArray(home.gallery) && home.gallery[lightboxIdx] && (
        <div className="lightbox" onClick={closeLightbox}>
          <button className="lightbox-close" onClick={(e) => { e.stopPropagation(); closeLightbox(); }} aria-label="Close">✕</button>
          <button className="lightbox-nav lightbox-prev" onClick={(e) => { e.stopPropagation(); lbPrev(); }} aria-label="Previous">‹</button>
          <button className="lightbox-nav lightbox-next" onClick={(e) => { e.stopPropagation(); lbNext(); }} aria-label="Next">›</button>
          <div className="lightbox-stage" onClick={(e) => e.stopPropagation()}>
            <img src={home.gallery[lightboxIdx].src} alt={home.gallery[lightboxIdx].caption || `Photo ${lightboxIdx + 1}`} />
            <div className="lightbox-caption">
              <span>{home.gallery[lightboxIdx].caption || `Photo ${lightboxIdx + 1}`}</span>
              <span className="lightbox-count">{lightboxIdx + 1} / {galleryLen}</span>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ── Apply / Inquire Modal ───────────────────────────────────
function PreApprovalModal({ home, onClose }) {
  // Auto-fill home/package field from the page/home the user is viewing
  const defaultInterest = home
    ? `${home.name}${home.location ? ` — ${home.location}` : ''}`
    : '';

  const [submitted, setSubmitted] = useState(false);
  const [data, setData] = useState({
    fullName: '',
    email: '',
    phone: '',
    interest: defaultInterest,
    timeline: '',
    notes: '',
  });
  const update = (k, v) => setData(prev => ({ ...prev, [k]: v }));

  const canSubmit = data.fullName && data.email && data.phone;

  const submit = (e) => {
    if (e) e.preventDefault();
    if (!canSubmit) return;
    setSubmitted(true);
  };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal-card modal-card--md preapp-card" onClick={e => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose} aria-label="Close">✕</button>

        {submitted ? (
          <div className="modal-success" style={{ padding: '40px 28px' }}>
            <div className="modal-success-icon">✓</div>
            <h3>Thanks, {data.fullName.split(' ')[0] || 'there'}!</h3>
            <p>Your inquiry{data.interest ? <> for <strong>{data.interest}</strong></> : ''} is in. A New Liberty Homes specialist will reach out within one business day.</p>
            <p style={{marginTop:14, fontSize:13, color:'var(--muted)'}}>Prefer to talk now? Call us at <a href="tel:+18324134038" style={{color:'var(--navy)',fontWeight:600}}>(832) 413-4038</a>.</p>
          </div>
        ) : (
          <>
            <div className="preapp-head">
              {home && (home.name || home.location) && (
                <div className="modal-eyebrow">
                  Apply / Inquire{home.name ? ` · ${home.name}` : ''}{home.location ? ` · ${home.location}` : ''}
                </div>
              )}
              <h2 className="modal-title" style={{marginBottom:6}}>Apply / Inquire</h2>
              <p className="modal-sub" style={{marginBottom:0}}>Tell us a little about you and we'll be in touch within one business day. No credit check.</p>
            </div>

            <form className="preapp-body" onSubmit={submit}>
              <div className="field">
                <label>Full Name <span className="req">*</span></label>
                <input
                  className="input"
                  value={data.fullName}
                  onChange={e=>update('fullName',e.target.value)}
                  placeholder="Jane Doe"
                  required
                />
              </div>

              <div className="field-row">
                <div className="field">
                  <label>Email Address <span className="req">*</span></label>
                  <input
                    className="input"
                    type="email"
                    value={data.email}
                    onChange={e=>update('email',e.target.value)}
                    placeholder="you@email.com"
                    required
                  />
                </div>
                <div className="field">
                  <label>Phone Number <span className="req">*</span></label>
                  <input
                    className="input"
                    type="tel"
                    value={data.phone}
                    onChange={e=>update('phone',e.target.value)}
                    placeholder="(555) 000-0000"
                    required
                  />
                </div>
              </div>

              <div className="field">
                <label>Which home / package are you interested in?</label>
                <input
                  className="input"
                  value={data.interest}
                  onChange={e=>update('interest',e.target.value)}
                  placeholder="e.g. Pine Creek 3/2 — Erath County, TX"
                />
              </div>

              <div className="field">
                <label>How soon are you looking to buy?</label>
                <select
                  className="input"
                  value={data.timeline}
                  onChange={e=>update('timeline',e.target.value)}
                >
                  <option value="">Select a timeline…</option>
                  <option>ASAP (0–30 days)</option>
                  <option>1–3 months</option>
                  <option>3–6 months</option>
                  <option>6–12 months</option>
                  <option>Just exploring</option>
                </select>
              </div>

              <div className="field" style={{marginBottom:0}}>
                <label>Comments or questions?</label>
                <textarea
                  className="input"
                  rows={4}
                  value={data.notes}
                  onChange={e=>update('notes',e.target.value)}
                  placeholder="Anything specific about your situation, financing, trade-ins, land, etc."
                />
              </div>
            </form>

            <div className="preapp-foot">
              <span style={{fontSize:12, color:'var(--muted)'}}>We'll never share your info.</span>
              <button
                type="button"
                className="btn btn-primary btn-sm"
                onClick={submit}
                disabled={!canSubmit}
                style={!canSubmit ? {opacity:.5, cursor:'not-allowed'} : {}}
              >
                Submit Inquiry →
              </button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

// ── Floor Plan SVG (procedural from bed/bath count) ─────────
function FloorPlanSVG({ home }) {
  // Singlewide 16×76 default; scale lightly off sqft
  const isSingle = (home.sectionType || '').toLowerCase().includes('single');
  const W = isSingle ? 720 : 720;
  const H = isSingle ? 170 : 280;
  const stroke = '#13294B';
  const wall = 3;
  const fill = '#F5F4F1';
  return (
    <svg viewBox={`0 0 ${W} ${H}`} className="floorplan-svg" role="img" aria-label="Floor plan">
      {/* Outer shell */}
      <rect x={wall} y={wall} width={W - wall*2} height={H - wall*2} fill={fill} stroke={stroke} strokeWidth={wall*2} />

      {/* Living / Dining / Kitchen (left half) */}
      <line x1={W*0.38} y1={wall} x2={W*0.38} y2={H-wall} stroke={stroke} strokeWidth={wall} />
      {/* Open archway gap */}
      <line x1={W*0.38} y1={H*0.45} x2={W*0.38} y2={H*0.75} stroke={fill} strokeWidth={wall+1} />

      {/* Kitchen island */}
      <rect x={W*0.10} y={H*0.55} width={W*0.18} height={H*0.10} fill="#E8E5DE" stroke={stroke} strokeWidth={1.5} />
      <text x={W*0.19} y={H*0.62} fontSize="9" textAnchor="middle" fill="#5B6573" fontFamily="ui-monospace, monospace">ISLAND</text>

      {/* Range + counter top wall */}
      <rect x={wall} y={H*0.18} width={W*0.36} height={H*0.08} fill="#E8E5DE" stroke={stroke} strokeWidth={1} />
      <text x={W*0.18} y={H*0.235} fontSize="9" textAnchor="middle" fill="#5B6573" fontFamily="ui-monospace, monospace">KITCHEN</text>

      <text x={W*0.19} y={H*0.45} fontSize="12" textAnchor="middle" fill={stroke} fontFamily="ui-monospace, monospace" fontWeight="700">LIVING / DINING</text>

      {/* Bathroom 2 (middle) */}
      <rect x={W*0.38} y={wall} width={W*0.16} height={H*0.42} fill="none" stroke={stroke} strokeWidth={wall} />
      <text x={W*0.46} y={H*0.20} fontSize="10" textAnchor="middle" fill={stroke} fontFamily="ui-monospace, monospace" fontWeight="700">BATH 2</text>
      <rect x={W*0.40} y={H*0.05} width={W*0.05} height={H*0.10} fill="#E8E5DE" stroke={stroke} strokeWidth={1}/>
      <text x={W*0.425} y={H*0.115} fontSize="7" textAnchor="middle" fill="#5B6573" fontFamily="ui-monospace, monospace">TUB</text>

      {/* Bedroom 2 + 3 (middle bottom) */}
      <line x1={W*0.54} y1={H*0.42} x2={W*0.54} y2={H-wall} stroke={stroke} strokeWidth={wall} />
      <rect x={W*0.38} y={H*0.42} width={W*0.16} height={H*0.58 - wall} fill="none" stroke={stroke} strokeWidth={wall} />
      <text x={W*0.46} y={H*0.72} fontSize="11" textAnchor="middle" fill={stroke} fontFamily="ui-monospace, monospace" fontWeight="700">BED 2</text>

      <rect x={W*0.54} y={H*0.42} width={W*0.18} height={H*0.58 - wall} fill="none" stroke={stroke} strokeWidth={wall} />
      <text x={W*0.63} y={H*0.72} fontSize="11" textAnchor="middle" fill={stroke} fontFamily="ui-monospace, monospace" fontWeight="700">BED 3</text>

      {/* Utility / Hall */}
      <rect x={W*0.54} y={wall} width={W*0.18} height={H*0.42} fill="none" stroke={stroke} strokeWidth={wall} />
      <text x={W*0.63} y={H*0.25} fontSize="10" textAnchor="middle" fill="#5B6573" fontFamily="ui-monospace, monospace">UTILITY · W/D</text>

      {/* Master suite (right) */}
      <line x1={W*0.72} y1={wall} x2={W*0.72} y2={H-wall} stroke={stroke} strokeWidth={wall} />
      <text x={W*0.83} y={H*0.30} fontSize="13" textAnchor="middle" fill={stroke} fontFamily="ui-monospace, monospace" fontWeight="700">PRIMARY</text>
      <text x={W*0.83} y={H*0.46} fontSize="11" textAnchor="middle" fill={stroke} fontFamily="ui-monospace, monospace">BEDROOM</text>

      {/* Master bath */}
      <line x1={W*0.72} y1={H*0.55} x2={W-wall} y2={H*0.55} stroke={stroke} strokeWidth={wall} />
      <text x={W*0.83} y={H*0.72} fontSize="10" textAnchor="middle" fill={stroke} fontFamily="ui-monospace, monospace" fontWeight="700">PRIMARY BATH</text>
      <rect x={W*0.74} y={H*0.78} width={W*0.07} height={H*0.12} fill="#E8E5DE" stroke={stroke} strokeWidth={1}/>
      <text x={W*0.775} y={H*0.86} fontSize="7" textAnchor="middle" fill="#5B6573" fontFamily="ui-monospace, monospace">SHWR</text>
      <rect x={W*0.86} y={H*0.78} width={W*0.10} height={H*0.12} fill="#E8E5DE" stroke={stroke} strokeWidth={1}/>
      <text x={W*0.91} y={H*0.86} fontSize="7" textAnchor="middle" fill="#5B6573" fontFamily="ui-monospace, monospace">CLOSET</text>

      {/* Front door (bottom left) */}
      <rect x={W*0.05} y={H-wall} width={W*0.07} height={6} fill={stroke} />
      <text x={W*0.085} y={H-8} fontSize="8" textAnchor="middle" fill="#fff" fontFamily="ui-monospace, monospace">FRONT</text>
      {/* Rear door */}
      <rect x={W*0.30} y={wall-3} width={W*0.06} height={6} fill={stroke} />

      {/* Dimensions */}
      <text x={W/2} y={H-4} fontSize="9" textAnchor="middle" fill="#5B6573" fontFamily="ui-monospace, monospace">76' 0"</text>
      <text x={W-6} y={H/2} fontSize="9" textAnchor="middle" fill="#5B6573" fontFamily="ui-monospace, monospace" transform={`rotate(90 ${W-6} ${H/2})`}>15' 2"</text>
    </svg>
  );
}

// ── Homes Grid (with modal state) ───────────────────────────
function HomesGrid({ homes }) {
  const [viewing, setViewing] = useState(null);
  const [notifying, setNotifying] = useState(null);

  React.useEffect(() => {
    document.body.style.overflow = (viewing || notifying) ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [viewing, notifying]);

  return (
    <>
      <div className="home-grid">
        {homes.map(h => (
          <HomeCard key={h.name} home={h} onView={setViewing} onNotify={setNotifying} />
        ))}
      </div>
      {viewing && <HomeDetailsModal home={viewing} onClose={() => setViewing(null)} />}
      {notifying && <GetNotifiedModal home={notifying} onClose={() => setNotifying(null)} />}
    </>
  );
}

// ── VIP Form ─────────────────────────────────────────────────
function VipForm() {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [phone, setPhone] = useState('');
  const [interest, setInterest] = useState('');
  const [submitted, setSubmitted] = useState(false);

  function handleSubmit(e) {
    e.preventDefault();
    setSubmitted(true);
  }

  if (submitted) {
    return (
      <div style={{textAlign:'center',padding:'20px 0'}}>
        <div style={{width:60,height:60,borderRadius:'50%',background:'var(--green)',color:'#fff',display:'flex',alignItems:'center',justifyContent:'center',margin:'0 auto 16px',fontSize:30}}>✓</div>
        <div className="vip-form-title">You're on the VIP list!</div>
        <p style={{fontSize:14,color:'var(--mid)',lineHeight:1.6,marginTop:6}}>We'll notify you the moment new homes match your interests. Watch your inbox.</p>
      </div>
    );
  }

  return (
    <form onSubmit={handleSubmit}>
      <div className="vip-form-title">Get Early Access</div>
      <div className="vip-form-sub">Quick — under 30 seconds.</div>

      <div className="field">
        <label>Full Name <span className="req">*</span></label>
        <input className="input" type="text" value={name} onChange={e=>setName(e.target.value)} placeholder="Jane Doe" required />
      </div>
      <div className="field-row" style={{marginBottom:14}}>
        <div className="field" style={{marginBottom:0}}>
          <label>Email <span className="req">*</span></label>
          <input className="input" type="email" value={email} onChange={e=>setEmail(e.target.value)} placeholder="you@email.com" required />
        </div>
        <div className="field" style={{marginBottom:0}}>
          <label>Phone</label>
          <input className="input" type="tel" value={phone} onChange={e=>setPhone(e.target.value)} placeholder="(555) 000-0000" />
        </div>
      </div>
      <div className="field">
        <label>I'm Interested In <span className="req">*</span></label>
        <select className="select" value={interest} onChange={e=>setInterest(e.target.value)} required>
          <option value="">Select…</option>
          <option>Home + Land Packages</option>
          <option>Building on My Land</option>
          <option>Home Only (delivery)</option>
          <option>Pre-Owned Homes</option>
          <option>Owner Financing</option>
          <option>Just Exploring</option>
        </select>
      </div>
      <input type="text" name="website_url" className="honeypot" tabIndex="-1" autoComplete="off" />
      <button type="submit" className="btn btn-primary btn-block btn-lg" style={{marginTop:6}}>
        Join the VIP List <Icon.Arrow />
      </button>
      <div style={{fontSize:12,color:'var(--muted)',textAlign:'center',marginTop:12}}>No spam. Unsubscribe any time.</div>
    </form>
  );
}

// ── Multi-step Questionnaire ─────────────────────────────────
const QUIZ_STEPS = [
  { num: '01', title: 'Contact Info' },
  { num: '02', title: 'Buying Situation' },
  { num: '03', title: 'Property' },
  { num: '04', title: 'Home Preferences' },
  { num: '05', title: 'Financing' },
  { num: '06', title: 'Timeline' },
  { num: '07', title: 'How Did You Find Us?' },
];

function Questionnaire() {
  const [step, setStep] = useState(0);
  const [data, setData] = useState({
    fullName: '', phone: '', email: '', contactMethod: 'Phone',
    situation: '',
    ownsLand: '', propertyLocation: '', utilities: [],
    homeType: '', beds: '', baths: '', sqft: '', budget: '',
    needsFinancing: '', ownerFinance: '', tradeIn: '',
    timeline: '',
    leadSource: '',
  });
  const [submitted, setSubmitted] = useState(false);

  function update(k, v) { setData(prev => ({...prev, [k]: v})); }
  function toggle(k, v) {
    setData(prev => ({...prev, [k]: prev[k].includes(v) ? prev[k].filter(x=>x!==v) : [...prev[k], v]}));
  }

  function nextStep() {
    if (step < QUIZ_STEPS.length - 1) setStep(step + 1);
    else setSubmitted(true);
  }
  function prevStep() { if (step > 0) setStep(step - 1); }

  function canAdvance() {
    if (step === 0) return data.fullName && data.phone && data.email;
    if (step === 1) return data.situation;
    if (step === 5) return data.timeline;
    return true;
  }

  if (submitted) {
    return (
      <div className="quiz-wrap">
        <div className="quiz-success">
          <div className="quiz-success-icon">✓</div>
          <h3>Thank you, {data.fullName.split(' ')[0] || 'there'}!</h3>
          <p>We received your inquiry. A member of the New Liberty Homes team will reach out within one business day.</p>
          <a href="#homes" className="btn btn-navy btn-lg">Browse Available Homes <Icon.Arrow /></a>
        </div>
      </div>
    );
  }

  const current = QUIZ_STEPS[step];

  return (
    <div className="quiz-wrap">
      <div className="quiz-header">
        <div className="quiz-step-num">Step {current.num} of {String(QUIZ_STEPS.length).padStart(2,'0')}</div>
        <div className="quiz-step-title">{current.title}</div>
        <div className="quiz-progress">
          {QUIZ_STEPS.map((_, i) => (
            <div key={i} className={`progress-seg ${i < step ? 'done' : i === step ? 'current' : ''}`}></div>
          ))}
        </div>
      </div>

      <div className="quiz-body">
        {step === 0 && (
          <div>
            <div className="quiz-section-label">Contact Info</div>
            <h3 className="quiz-h">Let's start with the basics</h3>
            <p className="quiz-sub">So we know how to reach you. We respect your privacy and never share your info.</p>
            <div className="field">
              <label>Full Name <span className="req">*</span></label>
              <input className="input" value={data.fullName} onChange={e=>update('fullName',e.target.value)} placeholder="Jane Doe" />
            </div>
            <div className="field-row" style={{marginBottom:0}}>
              <div className="field" style={{marginBottom:0}}>
                <label>Phone <span className="req">*</span></label>
                <input className="input" type="tel" value={data.phone} onChange={e=>update('phone',e.target.value)} placeholder="(555) 000-0000" />
              </div>
              <div className="field" style={{marginBottom:0}}>
                <label>Email <span className="req">*</span></label>
                <input className="input" type="email" value={data.email} onChange={e=>update('email',e.target.value)} placeholder="you@email.com" />
              </div>
            </div>
          </div>
        )}

        {step === 1 && (
          <div>
            <div className="quiz-section-label">Buying Situation</div>
            <h3 className="quiz-h">What best describes you?</h3>
            <p className="quiz-sub">Pick whichever feels closest — we'll dial in the details together.</p>
            <div className="radio-grid cols-2">
              {[
                {v:'Home + Land', d:'Move into a complete package'},
                {v:'I Own Land', d:'Place a home on my property'},
                {v:'Home Only', d:'Just need the home itself'},
                {v:'Pre-Owned Home', d:'Affordable used options'},
                {v:'Financing Options', d:'Need to figure out the money side'},
                {v:'Just Exploring', d:'Still researching'},
              ].map(opt => (
                <label key={opt.v} className={`radio-card ${data.situation===opt.v?'active':''}`} style={{padding:'18px 16px',alignItems:'flex-start'}}>
                  <input type="radio" name="situation" checked={data.situation===opt.v} onChange={()=>update('situation',opt.v)} />
                  <span className="rdot" style={{marginTop:2}}></span>
                  <div>
                    <div className="rlabel" style={{marginBottom:2}}>{opt.v}</div>
                    <div style={{fontSize:12.5,color:'var(--mid)',fontWeight:500}}>{opt.d}</div>
                  </div>
                </label>
              ))}
            </div>
          </div>
        )}

        {step === 2 && (
          <div>
            <div className="quiz-section-label">Property</div>
            <h3 className="quiz-h">Tell us about the land</h3>
            <p className="quiz-sub">If you don't own land yet, no problem — we can help you find one too.</p>
            <div className="field">
              <label>Do you own land?</label>
              <div className="radio-grid cols-3">
                {['Yes','No','Looking'].map(o => (
                  <label key={o} className={`radio-card ${data.ownsLand===o?'active':''}`}>
                    <input type="radio" checked={data.ownsLand===o} onChange={()=>update('ownsLand',o)} />
                    <span className="rdot"></span>
                    <span className="rlabel">{o}</span>
                  </label>
                ))}
              </div>
            </div>
            <div className="field">
              <label>Property Location (city / county)</label>
              <input className="input" value={data.propertyLocation} onChange={e=>update('propertyLocation',e.target.value)} placeholder="e.g. Stephenville, TX" />
            </div>
            <div className="field" style={{marginBottom:0}}>
              <label>Utilities Available <span style={{color:'var(--muted)',fontWeight:500,textTransform:'none',letterSpacing:0}}>(check all that apply)</span></label>
              <div className="check-grid">
                {['Water','Electric','Septic / Sewer','Natural Gas','None Yet','Not Sure'].map(u => (
                  <label key={u} className={`check-card ${data.utilities.includes(u)?'active':''}`}>
                    <input type="checkbox" checked={data.utilities.includes(u)} onChange={()=>toggle('utilities',u)} />
                    <span className="cbox"></span>
                    {u}
                  </label>
                ))}
              </div>
            </div>
          </div>
        )}

        {step === 3 && (
          <div>
            <div className="quiz-section-label">Home Preferences</div>
            <h3 className="quiz-h">Your dream home, in detail</h3>
            <p className="quiz-sub">These are starting points — we can adjust as we find the right fit.</p>
            <div className="field">
              <label>Home Type</label>
              <div className="radio-grid cols-2">
                {['Single Wide','Double Wide'].map(o => (
                  <label key={o} className={`radio-card ${data.homeType===o?'active':''}`}>
                    <input type="radio" checked={data.homeType===o} onChange={()=>update('homeType',o)} />
                    <span className="rdot"></span>
                    <span className="rlabel">{o}</span>
                  </label>
                ))}
              </div>
            </div>
            <div className="field-row" style={{marginBottom:14}}>
              <div className="field" style={{marginBottom:0}}>
                <label>Bedrooms</label>
                <select className="select" value={data.beds} onChange={e=>update('beds',e.target.value)}>
                  <option value="">Select…</option>
                  <option>1</option><option>2</option><option>3</option><option>4</option><option>5+</option>
                </select>
              </div>
              <div className="field" style={{marginBottom:0}}>
                <label>Bathrooms</label>
                <select className="select" value={data.baths} onChange={e=>update('baths',e.target.value)}>
                  <option value="">Select…</option>
                  <option>1</option><option>1.5</option><option>2</option><option>2.5</option><option>3+</option>
                </select>
              </div>
            </div>
            <div className="field-row" style={{marginBottom:0}}>
              <div className="field" style={{marginBottom:0}}>
                <label>Square Footage</label>
                <select className="select" value={data.sqft} onChange={e=>update('sqft',e.target.value)}>
                  <option value="">Select…</option>
                  <option>Under 900</option><option>900 – 1,200</option><option>1,200 – 1,600</option><option>1,600 – 2,000</option><option>2,000+</option>
                </select>
              </div>
              <div className="field" style={{marginBottom:0}}>
                <label>Budget Range</label>
                <select className="select" value={data.budget} onChange={e=>update('budget',e.target.value)}>
                  <option value="">Select…</option>
                  <option>Under $75k</option><option>$75k – $125k</option><option>$125k – $175k</option><option>$175k – $250k</option><option>$250k+</option>
                </select>
              </div>
            </div>
          </div>
        )}

        {step === 4 && (
          <div>
            <div className="quiz-section-label">Financing</div>
            <h3 className="quiz-h">How would you like to pay?</h3>
            <p className="quiz-sub">We work with multiple lenders and offer flexible owner-financing on select homes.</p>
            <div className="field">
              <label>Will you need financing?</label>
              <div className="radio-grid cols-3">
                {['Yes','Cash','Not Sure'].map(o => (
                  <label key={o} className={`radio-card ${data.needsFinancing===o?'active':''}`}>
                    <input type="radio" checked={data.needsFinancing===o} onChange={()=>update('needsFinancing',o)} />
                    <span className="rdot"></span>
                    <span className="rlabel">{o}</span>
                  </label>
                ))}
              </div>
            </div>
            <div className="field">
              <label>Interested in Owner Financing?</label>
              <div className="radio-grid cols-3">
                {['Yes','No','Tell Me More'].map(o => (
                  <label key={o} className={`radio-card ${data.ownerFinance===o?'active':''}`}>
                    <input type="radio" checked={data.ownerFinance===o} onChange={()=>update('ownerFinance',o)} />
                    <span className="rdot"></span>
                    <span className="rlabel">{o}</span>
                  </label>
                ))}
              </div>
            </div>
            <div className="field" style={{marginBottom:0}}>
              <label>Do you have a home to trade in?</label>
              <div className="radio-grid cols-2">
                {['Yes','No'].map(o => (
                  <label key={o} className={`radio-card ${data.tradeIn===o?'active':''}`}>
                    <input type="radio" checked={data.tradeIn===o} onChange={()=>update('tradeIn',o)} />
                    <span className="rdot"></span>
                    <span className="rlabel">{o}</span>
                  </label>
                ))}
              </div>
            </div>
          </div>
        )}

        {step === 5 && (
          <div>
            <div className="quiz-section-label">Timeline</div>
            <h3 className="quiz-h">When are you ready to move?</h3>
            <p className="quiz-sub">Knowing your timing helps us prioritize the right homes and financing options.</p>
            <div className="radio-grid cols-2">
              {[
                {v:'ASAP', d:'Within a few weeks'},
                {v:'30 Days', d:'About a month out'},
                {v:'1–3 Months', d:'Plenty of runway'},
                {v:'3–6 Months', d:'Planning ahead'},
                {v:'Just Exploring', d:'No specific timeline yet'},
              ].map(opt => (
                <label key={opt.v} className={`radio-card ${data.timeline===opt.v?'active':''}`} style={{padding:'18px 16px',alignItems:'flex-start'}}>
                  <input type="radio" checked={data.timeline===opt.v} onChange={()=>update('timeline',opt.v)} />
                  <span className="rdot" style={{marginTop:2}}></span>
                  <div>
                    <div className="rlabel" style={{marginBottom:2}}>{opt.v}</div>
                    <div style={{fontSize:12.5,color:'var(--mid)',fontWeight:500}}>{opt.d}</div>
                  </div>
                </label>
              ))}
            </div>
          </div>
        )}

        {step === 6 && (
          <div>
            <div className="quiz-section-label">One Last Thing</div>
            <h3 className="quiz-h">How did you find us?</h3>
            <p className="quiz-sub">Helps us serve you better — and know what's working.</p>
            <div className="radio-grid cols-2">
              {['Facebook','Google','QR Code','Referral','Drive-by Sign','Event','Other'].map(o => (
                <label key={o} className={`radio-card ${data.leadSource===o?'active':''}`}>
                  <input type="radio" checked={data.leadSource===o} onChange={()=>update('leadSource',o)} />
                  <span className="rdot"></span>
                  <span className="rlabel">{o}</span>
                </label>
              ))}
            </div>
          </div>
        )}
      </div>

      <div className="quiz-foot">
        <div className="quiz-foot-info">
          {step > 0 ? <span><strong>Step {step+1}</strong> of {QUIZ_STEPS.length} · {Math.round(((step)/QUIZ_STEPS.length)*100)}% complete</span> : <span>Takes about 2 minutes</span>}
        </div>
        <div style={{display:'flex',gap:10}}>
          {step > 0 && (
            <button type="button" className="btn btn-ghost btn-sm" onClick={prevStep}>← Back</button>
          )}
          <button type="button" className="btn btn-primary btn-sm" onClick={nextStep} disabled={!canAdvance()} style={{opacity: canAdvance() ? 1 : 0.5}}>
            {step === QUIZ_STEPS.length - 1 ? 'Submit Inquiry' : 'Continue'} <Icon.Arrow />
          </button>
        </div>
      </div>
    </div>
  );
}

// ── BUYER INQUIRY FORM ──────────────────────────────────────
// 4-step lead capture, used in the hero
const TX_LOCATIONS = [
  'Stephenville','Dublin','Comanche','Kerrville','Granbury','Glen Rose','Hico','Hamilton',
  'De Leon','Gorman','Mineral Wells','Weatherford','Brownwood','Early','Goldthwaite',
  'Lampasas','Llano','Fredericksburg','Boerne','Bandera','Junction','Mason','San Saba',
  'Erath County','Comanche County','Hood County','Somervell County','Hamilton County',
  'Eastland County','Palo Pinto County','Parker County','Brown County','Mills County',
  'Lampasas County','Llano County','Gillespie County','Kendall County','Kerr County',
  'Bandera County','Kimble County','San Saba County','Mason County','Bosque County',
  'Johnson County','Burnet County','Real County','Edwards County','Coryell County',
];

function BuyerInquiryForm() {
  const [step, setStep] = useState(1); // 1..4
  const [data, setData] = useState({
    fullName: '', phone: '', email: '',
    looking: [],
    locations: [],
    homeType: '', beds: '', baths: '', sqft: '', budget: '', timeline: '',
  });
  const [submitted, setSubmitted] = useState(false);
  const [locQuery, setLocQuery] = useState('');
  const [locOpen, setLocOpen] = useState(false);

  const update = (k, v) => setData(prev => ({ ...prev, [k]: v }));
  const toggle = (k, v) => setData(prev => ({ ...prev, [k]: prev[k].includes(v) ? prev[k].filter(x => x !== v) : [...prev[k], v] }));

  const canContinue1 = data.fullName && data.phone && data.email;
  const canContinue2 = data.looking.length > 0;
  const canContinue3 = data.locations.length > 0;

  const locSuggestions = locQuery.trim()
    ? TX_LOCATIONS.filter(l => l.toLowerCase().includes(locQuery.toLowerCase()) && !data.locations.includes(l)).slice(0, 8)
    : TX_LOCATIONS.filter(l => !data.locations.includes(l)).slice(0, 8);

  if (submitted) {
    return (
      <div className="inquiry-card inquiry-success">
        <div className="inquiry-success-icon">✓</div>
        <h3>You're on the list, {data.fullName.split(' ')[0] || 'friend'}!</h3>
        <p>You'll be among the <strong>first to know</strong> when a home matching your preferences becomes available.</p>
        <p className="inquiry-success-sub">Save our number so we don't end up in spam: <strong>(832) 413-4038</strong></p>
      </div>
    );
  }

  const Header = ({ title, sub }) => (
    <div className="inquiry-hd">
      <div className="inquiry-step-line">
        <div className="inquiry-step-title">{title}</div>
      </div>
      {sub && <p style={{fontSize:13.5, color:'rgba(255,255,255,0.78)', marginTop:10, lineHeight:1.5}}>{sub}</p>}
      <div className="inquiry-progress">
        {[1,2,3,4].map(n => (
          <div key={n} className={`inquiry-seg ${n < step ? 'done' : n === step ? 'current' : ''}`}></div>
        ))}
      </div>
    </div>
  );

  // ── STEP 1: Contact ──
  if (step === 1) {
    return (
      <div className="inquiry-card">
        <Header title="Be the First to Know When a Home Becomes Available" />
        <div className="inquiry-body">
          <div className="field" style={{marginBottom:12}}>
            <label>Full Name <span className="req">*</span></label>
            <input className="input" value={data.fullName} onChange={e => update('fullName', e.target.value)} placeholder="Jane Doe" />
          </div>
          <div className="field" style={{marginBottom:12}}>
            <label>Phone <span className="req">*</span></label>
            <input className="input" type="tel" value={data.phone} onChange={e => update('phone', e.target.value)} placeholder="(555) 000-0000" />
          </div>
          <div className="field" style={{marginBottom:0}}>
            <label>Email <span className="req">*</span></label>
            <input className="input" type="email" value={data.email} onChange={e => update('email', e.target.value)} placeholder="you@email.com" />
          </div>
        </div>
        <div className="inquiry-foot">
          <div className="inquiry-foot-info"><span>Your information is kept confidential and will not be shared.</span></div>
          <button type="button" className="btn btn-primary btn-sm" onClick={() => setStep(2)} disabled={!canContinue1} style={!canContinue1 ? {opacity:0.5, cursor:'not-allowed'} : {}}>Get Early Access →</button>
        </div>
      </div>
    );
  }

  // ── STEP 2: What are you looking for? ──
  if (step === 2) {
    const options = ['Home & Land Package','Home Only','Pre-Owned Home','Owner Financing','Other'];
    return (
      <div className="inquiry-card">
        <Header
          title="What are you looking for?"
          sub="Select all that apply — this helps us match you with the right inventory."
        />
        <div className="inquiry-body">
          <div className="check-grid" style={{display:'grid', gridTemplateColumns:'1fr', gap:8}}>
            {options.map(o => (
              <label key={o} className={`check-card ${data.looking.includes(o)?'active':''}`}>
                <input type="checkbox" checked={data.looking.includes(o)} onChange={()=>toggle('looking',o)} />
                <span className="cbox"></span>
                {o}
              </label>
            ))}
          </div>
        </div>
        <div className="inquiry-foot">
          <button type="button" className="inquiry-edit-link" onClick={()=>setStep(1)}>← Back</button>
          <button type="button" className="btn btn-primary btn-sm" onClick={()=>setStep(3)} disabled={!canContinue2} style={!canContinue2 ? {opacity:0.5, cursor:'not-allowed'} : {}}>Next →</button>
        </div>
      </div>
    );
  }

  // ── STEP 3: Location preferences ──
  if (step === 3) {
    return (
      <div className="inquiry-card">
        <Header
          title="What area are you interested in?"
          sub="Search Texas counties and cities — pick as many as you'd like."
        />
        <div className="inquiry-body">
          <div className="field" style={{marginBottom:12, position:'relative'}}>
            <label>Search counties &amp; cities <span className="muted-label">(start typing)</span></label>
            <input
              className="input"
              value={locQuery}
              onChange={e => { setLocQuery(e.target.value); setLocOpen(true); }}
              onFocus={() => setLocOpen(true)}
              onBlur={() => setTimeout(() => setLocOpen(false), 180)}
              placeholder="e.g. Stephenville, Erath County…"
            />
            {locOpen && locSuggestions.length > 0 && (
              <div className="loc-suggest">
                {locSuggestions.map(s => (
                  <button
                    type="button"
                    key={s}
                    className="loc-suggest-item"
                    onMouseDown={(e) => { e.preventDefault(); toggle('locations', s); setLocQuery(''); }}
                  >
                    <span>{s}</span>
                    <span className="loc-suggest-add">+ Add</span>
                  </button>
                ))}
              </div>
            )}
          </div>
          {data.locations.length > 0 && (
            <div className="field" style={{marginBottom:0}}>
              <label>Selected <span className="muted-label">({data.locations.length})</span></label>
              <div className="loc-chips">
                {data.locations.map(l => (
                  <span key={l} className="loc-chip">
                    {l}
                    <button type="button" onClick={() => toggle('locations', l)} aria-label={`Remove ${l}`}>×</button>
                  </span>
                ))}
              </div>
            </div>
          )}
        </div>
        <div className="inquiry-foot">
          <button type="button" className="inquiry-edit-link" onClick={()=>setStep(2)}>← Back</button>
          <button type="button" className="btn btn-primary btn-sm" onClick={()=>setStep(4)} disabled={!canContinue3} style={!canContinue3 ? {opacity:0.5, cursor:'not-allowed'} : {}}>Next →</button>
        </div>
      </div>
    );
  }

  // ── STEP 4: Tell us about your ideal home ──
  const Section = ({ title, children }) => (
    <div className="inquiry-section">
      <h4 className="inquiry-section-title">{title}</h4>
      {children}
    </div>
  );

  return (
    <div className="inquiry-card">
      <Header title="Tell us about your ideal home" sub="One last step — these help us send you the right matches first." />
      <div className="inquiry-body inquiry-body--scroll" style={{maxHeight:480}}>
        <Section title="Home Type">
          <div className="radio-grid cols-3">
            {['Single Wide','Double Wide','Not Sure'].map(o => (
              <label key={o} className={`radio-card ${data.homeType===o?'active':''}`}>
                <input type="radio" checked={data.homeType===o} onChange={()=>update('homeType',o)} />
                <span className="rdot"></span>
                <span className="rlabel">{o}</span>
              </label>
            ))}
          </div>
        </Section>

        <Section title="Bedrooms">
          <div className="radio-grid" style={{gridTemplateColumns:'repeat(4, 1fr)'}}>
            {['1','2','3','4+'].map(o => (
              <label key={o} className={`radio-card ${data.beds===o?'active':''}`} style={{justifyContent:'center', textAlign:'center'}}>
                <input type="radio" checked={data.beds===o} onChange={()=>update('beds',o)} />
                <span className="rdot"></span>
                <span className="rlabel">{o}</span>
              </label>
            ))}
          </div>
        </Section>

        <Section title="Bathrooms">
          <div className="radio-grid cols-3">
            {['2','3','4+'].map(o => (
              <label key={o} className={`radio-card ${data.baths===o?'active':''}`} style={{justifyContent:'center', textAlign:'center'}}>
                <input type="radio" checked={data.baths===o} onChange={()=>update('baths',o)} />
                <span className="rdot"></span>
                <span className="rlabel">{o}</span>
              </label>
            ))}
          </div>
        </Section>

        <Section title="Square Footage">
          <div className="radio-grid cols-3">
            {['Under 1,500','1,501–2,000','2,001+'].map(o => (
              <label key={o} className={`radio-card ${data.sqft===o?'active':''}`}>
                <input type="radio" checked={data.sqft===o} onChange={()=>update('sqft',o)} />
                <span className="rdot"></span>
                <span className="rlabel">{o}</span>
              </label>
            ))}
          </div>
        </Section>

        <Section title="Budget">
          <div className="radio-grid cols-2">
            {['Under $100k','$100k–$150k','$150k–$200k','$200k–$250k','$250k+'].map(o => (
              <label key={o} className={`radio-card ${data.budget===o?'active':''}`}>
                <input type="radio" checked={data.budget===o} onChange={()=>update('budget',o)} />
                <span className="rdot"></span>
                <span className="rlabel">{o}</span>
              </label>
            ))}
          </div>
        </Section>

        <Section title="Timeline">
          <div className="radio-grid cols-2">
            {['Within 30 Days','1–3 Months','3–6 Months','Just Exploring'].map(o => (
              <label key={o} className={`radio-card ${data.timeline===o?'active':''}`}>
                <input type="radio" checked={data.timeline===o} onChange={()=>update('timeline',o)} />
                <span className="rdot"></span>
                <span className="rlabel">{o}</span>
              </label>
            ))}
          </div>
        </Section>

        <input type="text" name="website_url" style={{display:'none'}} tabIndex="-1" autoComplete="off" />
      </div>

      <div className="inquiry-foot">
        <button type="button" className="inquiry-edit-link" onClick={()=>setStep(3)}>← Back</button>
        <button type="button" className="btn btn-primary btn-sm" onClick={() => setSubmitted(true)}>Submit</button>
      </div>
    </div>
  );
}

Object.assign(window, { BrandMark, StatusBadge, HomeCard, HomesGrid, GetNotifiedModal, HomeDetailsModal, PreApprovalModal, VipForm, Questionnaire, BuyerInquiryForm });
