/* global React */
/* 7151 Johnston Road — sections B: Guest, Equestrian, EstateMap, Moments,
   Action (contact form), Footer. */
const EEb = window.EstablishedEstateDesignSystem_03388c;
const { Eyebrow: EyebrowB, Rule: RuleB, Button: ButtonB, EstateIcon: EstateIconB } = EEb;
const dspB = window.EEdsp, bdyB = window.EEbdy;
const EE_DISPLAY_B = window.EE_DISPLAY, EE_DISPLAY_3B = window.EE_DISPLAY_3;
const { Reveal: RevealB, PhotoSlot: PhotoSlotB, MediaSlot: MediaSlotB, Section: SectionB, SectionHead: SectionHeadB, Monogram: MonogramB } = window;
const WEB_B = window.EE_WEB;

/* ---------------------------------------------------------------- GUEST --- */
function Guest() {
  return (
    <SectionB id="guest" tone="page">
      <Reveal>
        <SectionHeadB eyebrow="Guest Flexibility" title="Room for guests to stay separately." body="Beyond the main residence, a guesthouse with its own kitchen and an upper-barn lounge / bunkhouse expand how the property can live — for visitors, extended stays, caretaking, or a quiet retreat apart from the home." measure="640px" />
      </Reveal>
      <div className="ee-split" style={{ marginTop: 'var(--space-8)', alignItems: 'stretch' }}>
        <Reveal>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)', height: '100%' }}>
            <PhotoSlotB id="guesthouse" src={`${WEB_B}placeholder/guesthouse.jpg`} alt="The guesthouse living room" tone="oat" ratio="16 / 10" icon="guesthouse" caption="Guesthouse · private entry" />
            <p style={bdyB({ fontSize: 'var(--type-body-sm)' })}>A separate guesthouse with a full kitchen — private entry, its own systems, comfortable for longer stays.</p>
          </div>
        </Reveal>
        <Reveal delay={80}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)', height: '100%' }}>
            <PhotoSlotB id="bunkhouse" src={`${WEB_B}placeholder/bunkhouse.jpg`} alt="The upper-barn lounge and bunkhouse at twilight" tone="ridge" ratio="16 / 10" icon="home" caption="Upper-barn lounge / bunkhouse" />
            <p style={bdyB({ fontSize: 'var(--type-body-sm)' })}>An attached lounge and bunkhouse above the upper barn — flexible space for guests, a studio, or quiet time apart.</p>
          </div>
        </Reveal>
      </div>
    </SectionB>
  );
}

/* ----------------------------------------------------------- EQUESTRIAN --- */
const FACILITIES = [
  { icon: 'barn', label: 'Lower Barn · 5-Stall', detail: 'Paddocks, tack room, and crosstie area' },
  { icon: 'barn', label: 'Upper Barn · 4-Stall', detail: 'Large runs, views, tack room, attached lounge / bunkhouse' },
  { icon: 'arena', label: 'Outdoor Arena', detail: "225' × 100' all-season riding and training" },
  { icon: 'arena', label: 'Covered Arena', detail: 'Ride through weather, year round' },
  { icon: 'roundpen', label: 'Covered Round Pen', detail: 'Groundwork and conditioning, under cover' },
  { icon: 'hay', label: 'Hay Barn', detail: 'Covered hay and equipment storage on property' },
  { icon: 'pasture', label: 'Pastures & Runs', detail: 'Rolling fenced turnout across the parcel' },
  { icon: 'view', label: 'Panoramic Views', detail: 'Rolling-hill and pasture views throughout' },
];
function FacTile({ f, delay }) {
  const [hover, setHover] = React.useState(false);
  return (
    <Reveal delay={delay} style={{ height: '100%' }}>
      <div
        onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
        style={{ background: 'rgba(255,253,248,0.04)', border: '1px solid var(--rule-on-deep)', borderRadius: 'var(--radius-md)', padding: 'var(--space-6)', display: 'flex', flexDirection: 'column', gap: 'var(--space-4)', height: '100%', boxShadow: hover ? '0 6px 20px rgba(0,0,0,0.18)' : 'none', transition: 'box-shadow var(--dur-base) var(--ease-estate)' }}
      >
        <span style={{ color: 'var(--color-hay)' }}><EstateIconB name={f.icon} size={28} /></span>
        <div style={{ fontFamily: 'var(--font-body)', fontSize: 'var(--type-label)', fontWeight: 600, letterSpacing: 'var(--tracking-label)', textTransform: 'uppercase', color: 'var(--color-white)' }}>{f.label}</div>
        <div style={{ fontFamily: 'var(--font-body)', fontSize: 'var(--type-body-sm)', color: 'var(--text-on-deep-muted)', lineHeight: 'var(--leading-snug)' }}>{f.detail}</div>
      </div>
    </Reveal>
  );
}
function Equestrian() {
  return (
    <SectionB id="equestrian" tone="deep">
      <Reveal>
        <SectionHeadB tone="deep" eyebrow="Equestrian Infrastructure" title="The horse-ready infrastructure is already here." body="Two barns, arenas, a covered round pen, hay storage, pastures, and runs — established and working together as one system, not a future project." measure="680px" />
      </Reveal>
      {/* two large calm images, then a calm facility grid */}
      <div className="ee-split" style={{ marginTop: 'var(--space-8)' }}>
        <Reveal><PhotoSlotB id="eq-barn" src={`${WEB_B}placeholder/eq-barn.jpg`} alt="Horses at the lower barn paddocks" tone="leather" ratio="16 / 10" icon="barn" caption="Lower barn · paddocks & runs" scrim /></Reveal>
        <Reveal delay={80}><PhotoSlotB id="eq-arena" src={`${WEB_B}placeholder/eq-arena.jpg`} alt="The outdoor riding arena" tone="gold" ratio="16 / 10" icon="arena" caption="Outdoor arena · golden hour" scrim /></Reveal>
      </div>
      <div className="ee-grid ee-grid--4" style={{ marginTop: 'var(--space-7)' }}>
        {FACILITIES.map((f, i) => <FacTile key={f.label} f={f} delay={(i % 4) * 60} />)}
      </div>
    </SectionB>
  );
}

/* ----------------------------------------------------------- ESTATE MAP ---
   The interactive Estate System Map now lives in its own config-driven module,
   src/estate-map.jsx (window.EstateMap). It loads before app.jsx. */

/* -------------------------------------------------------------- MOMENTS ---
   The Lived-Moments gallery — the curated exterior sequence. Uniform grid of
   thumbnails (matches the Interiors gallery); one shared caption in the lightbox. */
const MOMENTS = Array.from({ length: 8 }, (_, k) => {
  const n = String(k + 1).padStart(2, '0');
  return { src: `${WEB_B}moments/${n}.jpg`, caption: 'A day on the estate', alt: `7151 Johnston Road — a day on the estate, image ${k + 1}` };
});
function Moments({ onOpen }) {
  return (
    <SectionB id="moments" tone="page">
      <Reveal>
        <SectionHeadB eyebrow="Lived Moments" title="A day on the estate." body="The walk, in sequence — arrival, land, the barns and arenas, and the long golden close of the day." measure="620px" />
      </Reveal>
      <Reveal>
        <div className="ee-igrid" style={{ marginTop: 'var(--space-8)' }}>
          {MOMENTS.map((m, i) => (
            <button
              key={i}
              type="button"
              className="ee-igrid__cell"
              onClick={(e) => onOpen(MOMENTS, i, e.currentTarget)}
              aria-label={`Open exterior photo ${i + 1} of ${MOMENTS.length}`}
            >
              <img src={m.src} alt={m.alt} loading="lazy" />
            </button>
          ))}
        </div>
      </Reveal>
    </SectionB>
  );
}

/* ------------------------------------------------------------- INTERIORS ---
   A dedicated gallery so the interior photography reads as its own set.
   Uniform grid of thumbnails; click any to open the shared lightbox. */
const INTERIORS = Array.from({ length: 15 }, (_, k) => {
  const n = String(k + 1).padStart(2, '0');
  return { src: `${WEB_B}interior/${n}.jpg`, caption: 'Inside the Residence', alt: `Interior of 7151 Johnston Road — image ${k + 1}` };
});
function Interiors({ onOpen }) {
  return (
    <SectionB id="interiors" tone="alt">
      <Reveal>
        <SectionHeadB eyebrow="The Interiors" title="Inside the residence." body="Single-level living, an updated kitchen, arched doorways, and large view-facing windows — the home, room by room." measure="620px" />
      </Reveal>
      <Reveal>
        <div className="ee-igrid" style={{ marginTop: 'var(--space-8)' }}>
          {INTERIORS.map((m, i) => (
            <button
              key={i}
              type="button"
              className="ee-igrid__cell"
              onClick={(e) => onOpen(INTERIORS, i, e.currentTarget)}
              aria-label={`Open interior photo ${i + 1} of ${INTERIORS.length}`}
            >
              <img src={m.src} alt={m.alt} loading="lazy" />
            </button>
          ))}
        </div>
      </Reveal>
    </SectionB>
  );
}

/* --------------------------------------------------------------- ACTION --- */
function Field({ label, name, type = 'text', value, onChange, error, placeholder, textarea }) {
  const props = {
    id: name, name, value, placeholder,
    className: `${textarea ? 'ee-textarea' : 'ee-input'}${error ? ' is-error' : ''}`,
    onChange: (e) => onChange(name, e.target.value),
    'aria-invalid': !!error,
  };
  return (
    <div className="ee-field">
      <label htmlFor={name}>{label}</label>
      {textarea ? <textarea {...props} rows={4} /> : <input type={type} {...props} />}
      {error ? <span className="ee-field__error">{error}</span> : null}
    </div>
  );
}
/* ---- Private-showing form delivery (Web3Forms — free, no backend) ----------
   SETUP (one step): create a free Access Key at https://web3forms.com using
   mike@cre8r.agency as the email, then paste the key below. Submissions are
   emailed to that address and CC'd to the two agents in SHOWING_CC.
   Until a real key is pasted, the form falls back to opening the visitor's
   mail client (mailto) addressed to all three recipients.                     */
const WEB3FORMS_ACCESS_KEY = '0a2177ff-2507-4f6e-b650-4e85868a7597';
const SHOWING_PRIMARY = 'mike@cre8r.agency';
const SHOWING_CC = ['melanie@pburgessteam.com', 'm.bartoletti@compass.com'];
const SHOWING_RECIPIENTS = [SHOWING_PRIMARY, ...SHOWING_CC];
const KEY_READY = WEB3FORMS_ACCESS_KEY && WEB3FORMS_ACCESS_KEY.indexOf('PASTE-') === -1;

function Action() {
  const [form, setForm] = React.useState({ name: '', email: '', phone: '', message: '' });
  const [errors, setErrors] = React.useState({});
  const [status, setStatus] = React.useState('idle'); // idle | sending | sent | error
  const set = (k, v) => { setForm((f) => ({ ...f, [k]: v })); setErrors((e) => ({ ...e, [k]: undefined })); };
  const subjectLine = `Private Showing Request — 7151 Johnston Road (${form.name})`;
  const mailtoFallback = () => {
    const body = [
      `Name: ${form.name}`, `Email: ${form.email}`, `Phone: ${form.phone}`, '',
      'Preferred showing times / message:', form.message || '(none provided)', '',
      '— Sent from the 7151 Johnston Road listing site',
    ].join('\n');
    window.location.href = `mailto:${SHOWING_RECIPIENTS.join(',')}?subject=${encodeURIComponent(subjectLine)}&body=${encodeURIComponent(body)}`;
    setStatus('sent');
  };
  const submit = async (e) => {
    e.preventDefault();
    const er = {};
    if (!form.name.trim()) er.name = 'Please share your name.';
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) er.email = 'A valid email helps us reach you.';
    if (!form.phone.trim()) er.phone = 'A phone number, for scheduling.';
    setErrors(er);
    if (Object.keys(er).length) return;
    if (e.target.botcheck && e.target.botcheck.checked) return; // honeypot tripped
    if (!KEY_READY) { mailtoFallback(); return; }
    setStatus('sending');
    try {
      const res = await fetch('https://api.web3forms.com/submit', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify({
          access_key: WEB3FORMS_ACCESS_KEY,
          subject: subjectLine,
          from_name: '7151 Johnston Road — Listing Site',
          cc: SHOWING_CC.join(','),
          replyto: form.email,
          name: form.name,
          email: form.email,
          phone: form.phone,
          message: form.message || '(none provided)',
        }),
      });
      const data = await res.json();
      if (data && data.success) setStatus('sent');
      else setStatus('error');
    } catch (_) { setStatus('error'); }
  };
  const sent = status === 'sent';
  const secondaries = [
    ['Request the Property Book', '#offer'],
    ['Explore the Equestrian Facilities', '#equestrian'],
    ['View the Estate Map', '#map'],
  ];
  return (
    <SectionB id="action" tone="deep">
      <div className="ee-split ee-split--text-lead" style={{ alignItems: 'start', gap: 'clamp(2.5rem, 5vw, var(--space-9))' }}>
        <Reveal>
          <div>
            <RuleB tone="hay" length="48px" style={{ marginBottom: 'var(--space-5)' }} />
            <EyebrowB color="var(--color-hay)" style={{ marginBottom: 'var(--space-4)' }}>Private Showing</EyebrowB>
            <h2 style={dspB(EE_DISPLAY_B, { color: 'var(--color-white)' })}>See the estate for yourself.</h2>
            <p style={bdyB({ color: 'var(--text-on-deep-muted)', marginTop: 'var(--space-5)', maxWidth: '44ch' })}>By appointment for qualified equestrian and acreage buyers. Share a few details and a preferred time, and the listing team will arrange a private walk of the land, residence, and facilities.</p>
            <ul style={{ listStyle: 'none', margin: 'var(--space-7) 0 0', padding: 0, display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
              {secondaries.map(([t, href]) => (
                <li key={t}>
                  <a href={href} style={{ display: 'flex', alignItems: 'flex-start', gap: 'var(--space-3)', textDecoration: 'none', fontFamily: 'var(--font-body)', fontSize: 'var(--type-body-sm)', color: 'var(--color-white)', maxWidth: '100%' }}>
                    <span style={{ color: 'var(--color-hay)', flex: '0 0 auto' }} aria-hidden="true">&rarr;</span>{t}
                  </a>
                </li>
              ))}
            </ul>
          </div>
        </Reveal>
        <Reveal delay={80}>
          <div style={{ background: 'rgba(255,253,248,0.035)', border: '1px solid var(--rule-on-deep)', borderRadius: 'var(--radius-lg)', padding: 'clamp(1.5rem, 3.5vw, var(--space-8))' }}>
            {sent ? (
              <div style={{ textAlign: 'center', padding: 'var(--space-6) var(--space-4)' }}>
                <span style={{ display: 'inline-flex', width: 60, height: 60, borderRadius: 999, alignItems: 'center', justifyContent: 'center', background: 'rgba(198,161,91,0.16)', color: 'var(--color-hay)' }}>
                  <EstateIconB name="showing" size={30} />
                </span>
                <h3 style={dspB('var(--type-display-3)', { color: 'var(--color-white)', marginTop: 'var(--space-5)' })}>Request received.</h3>
                <p style={bdyB({ color: 'var(--text-on-deep-muted)', marginTop: 'var(--space-4)', maxWidth: '34ch', marginInline: 'auto' })}>Thank you, {form.name.split(' ')[0] || 'and welcome'}. The listing team will be in touch shortly to arrange your private showing.</p>
                <div style={{ marginTop: 'var(--space-6)' }}>
                  <ButtonB variant="ghost" onDeep size="sm" onClick={() => { setStatus('idle'); setForm({ name: '', email: '', phone: '', message: '' }); }}>Send another request</ButtonB>
                </div>
              </div>
            ) : (
              <form onSubmit={submit} noValidate style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
                <Field label="Name" name="name" value={form.name} onChange={set} error={errors.name} placeholder="Your name" />
                <div className="ee-split" style={{ gap: 'var(--space-5)', alignItems: 'start' }}>
                  <Field label="Email" name="email" type="email" value={form.email} onChange={set} error={errors.email} placeholder="you@email.com" />
                  <Field label="Phone" name="phone" type="tel" value={form.phone} onChange={set} error={errors.phone} placeholder="(000) 000-0000" />
                </div>
                <Field label="Preferred showing times / message" name="message" textarea value={form.message} onChange={set} placeholder="Weekday mornings work well — we ride, so we'd love to see the barns and arena." />
                {/* honeypot — hidden from real users, catches bots */}
                <input type="checkbox" name="botcheck" tabIndex={-1} autoComplete="off" style={{ position: 'absolute', left: '-9999px' }} aria-hidden="true" />
                <ButtonB variant="primary" size="lg" as="button" type="submit" disabled={status === 'sending'} style={{ width: '100%', whiteSpace: 'normal', opacity: status === 'sending' ? 0.7 : 1 }}>{status === 'sending' ? 'Sending…' : 'Request a Private Showing'}</ButtonB>
                {status === 'error' ? (
                  <p className="ee-note ee-note--deep" style={{ textAlign: 'center', color: '#e0a37f' }}>Something went wrong sending your request. Please email <a href={`mailto:${SHOWING_RECIPIENTS.join(',')}`} style={{ color: 'var(--color-hay)' }}>the listing team</a> directly.</p>
                ) : (
                  <p className="ee-note ee-note--deep" style={{ textAlign: 'center' }}>Submitting sends your request to the listing team. No obligation.</p>
                )}
              </form>
            )}
          </div>
        </Reveal>
      </div>
    </SectionB>
  );
}

/* --------------------------------------------------------------- FOOTER --- */
function Footer() {
  return (
    <footer style={{ background: 'var(--surface-deep)', color: 'var(--color-white)', borderTop: '1px solid var(--rule-on-deep)', paddingBlock: 'var(--space-8) var(--space-7)' }}>
      <div className="ee-container ee-container--wide">
        <div style={{ display: 'grid', gap: 'var(--space-7)', gridTemplateColumns: '1fr', alignItems: 'start', paddingBottom: 'var(--space-7)', borderBottom: '1px solid var(--rule-on-deep)' }} className="ee-footer-grid">
          <div>
            <p style={dspB('var(--type-display-4)', { color: 'var(--color-white)', maxWidth: '16ch' })}>7151 Johnston Road</p>
            <p style={bdyB({ color: 'var(--text-on-deep-muted)', fontSize: 'var(--type-body-sm)', marginTop: 'var(--space-3)' })}>Tassajara Valley · Pleasanton, CA · Private Equestrian Estate</p>
          </div>
          <div>
            <EyebrowB color="var(--color-hay)" style={{ marginBottom: 'var(--space-4)' }}>Listing Team</EyebrowB>
            <p style={bdyB({ color: 'var(--color-white)', fontSize: 'var(--type-body-sm)', fontWeight: 600, marginBottom: 'var(--space-2)' })}>Melanie Bartoletti</p>
            <p style={bdyB({ color: 'var(--text-on-deep-muted)', fontSize: 'var(--type-body-sm)', marginBottom: 'var(--space-2)' })}>REALTOR® | DRE# 02141343</p>
            <p style={{ margin: '0 0 var(--space-2)' }}>
              <a href="mailto:melanie@pburgessteam.com" style={{ color: 'var(--text-on-deep-muted)', fontFamily: 'var(--font-body)', fontSize: 'var(--type-body-sm)', textDecoration: 'none' }}>melanie@pburgessteam.com</a>
            </p>
            <p style={{ margin: 0 }}>
              <a href="tel:+15103016317" style={{ color: 'var(--text-on-deep-muted)', fontFamily: 'var(--font-body)', fontSize: 'var(--type-body-sm)', textDecoration: 'none' }}>M: 510-301-6317</a>
            </p>
            <img src={`${WEB_B}logo/burgess-team-white.png`} alt="The Burgess Team" loading="lazy" style={{ width: 'clamp(160px, 48vw, 200px)', height: 'auto', marginTop: 'var(--space-6)', opacity: 0.9 }} />
          </div>
          <div>
            <EyebrowB color="var(--color-hay)" style={{ marginBottom: 'var(--space-4)' }}>Private Showing</EyebrowB>
            <p style={bdyB({ color: 'var(--text-on-deep-muted)', fontSize: 'var(--type-body-sm)', marginBottom: 'var(--space-5)' })}>By appointment for qualified equestrian and acreage buyers.</p>
            <ButtonB variant="secondary" onDeep size="sm" href="#action">Schedule a Private Showing</ButtonB>
          </div>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingTop: 'var(--space-5)', flexWrap: 'wrap', gap: 'var(--space-4)' }}>
          <span style={{ fontFamily: 'var(--font-body)', fontSize: '11px', fontWeight: 600, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--text-on-deep-muted)' }}>In place · Established · Complete</span>
          <span style={{ fontFamily: 'var(--font-body)', fontSize: '11px', color: 'var(--text-on-deep-muted)', maxWidth: '62ch' }}>All figures, dimensions, and permitted status shown are placeholders pending verification. Information deemed reliable but not guaranteed; buyer to verify. Equal Housing Opportunity.</span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Guest, Equestrian, Moments, Interiors, INTERIORS, Action, Footer, MOMENTS });
