/* global React */
/* 7151 Johnston Road — sections A: Hero, Setting, Film, Offer, Residence. */
const EEa = window.EstablishedEstateDesignSystem_03388c;
const { Eyebrow: EyebrowA, Rule: RuleA, Button: ButtonA, StatBlock: StatBlockA, EstateIcon: EstateIconA } = EEa;
const dspA = window.EEdsp, bdyA = window.EEbdy;
const EE_DISPLAY_A = window.EE_DISPLAY, EE_DISPLAY_3A = window.EE_DISPLAY_3;
const { Reveal: RevealA, PhotoSlot: PhotoSlotA, MediaSlot: MediaSlotA, Section: SectionA, SectionHead: SectionHeadA } = window;
const WEB_A = window.EE_WEB;

/* ----------------------------------------------------------------- HERO --- */
function Hero() {
  return (
    <section id="top" style={{ position: 'relative', minHeight: '92vh', display: 'flex', alignItems: 'flex-end', overflow: 'hidden', background: 'linear-gradient(150deg, #e8d9c2 0%, #b69a73 52%, #6f5a3e 100%)' }}>
      {/* Hero — curated twilight exterior */}
      <img src={`${WEB_A}placeholder/hero.jpg`} alt="7151 Johnston Road at twilight — the main residence and grounds" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />
      {/* bottom-up walnut scrim for reversed text */}
      <span aria-hidden="true" style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to top, rgba(33,26,20,0.64) 0%, rgba(33,26,20,0.20) 48%, rgba(33,26,20,0.05) 100%)' }} />
      {/* faint topographic contour motif */}
      <svg viewBox="0 0 1440 400" preserveAspectRatio="none" aria-hidden="true" style={{ position: 'absolute', bottom: 0, left: 0, width: '100%', height: '42%', opacity: 0.16 }} fill="none" stroke="#FFFDF8" strokeWidth="1">
        <path d="M-20 300 Q360 240 720 280 T1460 250" />
        <path d="M-20 340 Q360 280 720 320 T1460 295" />
        <path d="M-20 380 Q360 320 720 360 T1460 335" />
      </svg>
      <div className="ee-container" style={{ position: 'relative', width: '100%', paddingBottom: 'clamp(3rem, 7vw, 7rem)', paddingTop: '6rem' }}>
        <EyebrowA color="rgba(255,253,248,0.88)" style={{ marginBottom: 'var(--space-5)' }}>Tassajara Valley · Private Equestrian Estate</EyebrowA>
        <h1 style={dspA('clamp(2.5rem, 6.2vw, 4.75rem)', { color: 'var(--color-white)', maxWidth: '15ch', lineHeight: 1.04 })}>The equestrian estate lifestyle, already in place.</h1>
        <p style={bdyA({ color: 'rgba(255,253,248,0.9)', fontSize: 'var(--type-lead)', lineHeight: 1.45, maxWidth: '52ch', marginTop: 'var(--space-5)' })}>A private acreage retreat where the land, barns, arenas, pastures, guest flexibility, and single-level residence come together as one complete horse-ready estate.</p>
        <div style={{ display: 'flex', gap: 'var(--space-4)', marginTop: 'var(--space-7)', flexWrap: 'wrap' }}>
          <ButtonA variant="primary" size="lg" href="#action" style={{ whiteSpace: 'normal', maxWidth: '100%' }}>Schedule a Private Showing</ButtonA>
          <ButtonA variant="secondary" size="lg" onDeep href="#equestrian" iconRight={<span aria-hidden="true">&rarr;</span>} style={{ whiteSpace: 'normal', maxWidth: '100%' }}>Explore the Equestrian Facilities</ButtonA>
        </div>
      </div>
    </section>
  );
}

/* -------------------------------------------------------------- SETTING --- */
function Setting() {
  return (
    <SectionA id="setting" tone="page">
      <div className="ee-split ee-split--text-lead ee-split--flip-mobile">
        <Reveal>
          <SectionHeadA eyebrow="The Setting" title="Tucked into the hills of Tassajara Valley." />
          <p style={bdyA({ marginTop: 'var(--space-5)', maxWidth: '48ch' })}>Set back from the road behind mature oaks, the estate opens onto rolling pasture and long valley views. Privacy comes from the land itself — acreage, distance, and the quiet of the valley.</p>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 'var(--space-7) var(--space-8)', marginTop: 'var(--space-7)' }}>
            <StatBlockA value="10+" label="Private Acres" caption="Tassajara Valley" />
            <StatBlockA value="Single-Level" label="Main Residence" />
            <StatBlockA value="Established" label="Infrastructure" />
          </div>
        </Reveal>
        <Reveal delay={80}>
          <PhotoSlotA id="setting-hero" src={`${WEB_A}placeholder/setting.jpg`} alt="Valley views over the estate at golden hour" tone="dawn" ratio="4 / 3.4" icon="view" caption="Valley views · golden hour" />
        </Reveal>
      </div>
    </SectionA>
  );
}

/* ------------------------------------------------------------- THE FILM --- */
/* Branded facade player. The YouTube iframe only loads after the user clicks
   play — the video id (MEDIA.film.youtubeId in app) is the single swap point. */
function Film({ film }) {
  const [playing, setPlaying] = React.useState(false);
  const [posterFailed, setPosterFailed] = React.useState(false);
  const id = film && film.youtubeId;
  const poster = film && film.poster;
  const hasPoster = poster && !posterFailed;
  return (
    <SectionA id="film" tone="alt">
      <div style={{ maxWidth: '720px', marginInline: 'auto', textAlign: 'center', marginBottom: 'var(--space-8)' }}>
        <RuleA tone="leather" length="48px" style={{ margin: '0 auto var(--space-5)' }} />
        <EyebrowA align="center" style={{ marginBottom: 'var(--space-4)' }}>The Estate Film</EyebrowA>
        <h2 style={dspA(EE_DISPLAY_A)}>Walk the estate in three minutes.</h2>
        <p style={bdyA({ marginTop: 'var(--space-5)', maxWidth: '52ch', marginInline: 'auto' })}>A cinematic pass over the land, the residence, and the equestrian facilities — shot in golden-hour light, the way the property actually lives.</p>
      </div>
      <Reveal>
        <div className="ee-frame" style={{ aspectRatio: '16 / 9', borderRadius: 'var(--radius-lg)', background: playing ? '#000' : 'linear-gradient(150deg, #d8b878 0%, #8a6a3c 48%, #3a2f20 100%)' }}>
          {playing && id ? (
            <iframe
              title="The Estate Film"
              src={`https://www.youtube-nocookie.com/embed/${id}?autoplay=1&rel=0&modestbranding=1`}
              allow="accelerated-disk; autoplay; encrypted-media; picture-in-picture"
              allowFullScreen
              style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', border: 0 }}
            />
          ) : (
            <button
              type="button"
              onClick={() => setPlaying(true)}
              aria-label="Play the estate film"
              style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', border: 0, cursor: 'pointer', background: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center' }}
            >
              {hasPoster ? (
                <img src={poster} alt="" loading="lazy" onError={() => setPosterFailed(true)} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />
              ) : null}
              <span aria-hidden="true" style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to top, rgba(33,26,20,0.5), rgba(33,26,20,0.12) 60%, transparent)' }} />
              {!hasPoster ? (
                <span aria-hidden="true" style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'rgba(255,253,248,0.16)' }}>
                  <EstateIconA name="arena" size={120} strokeWidth={0.8} />
                </span>
              ) : null}
              <span style={{ position: 'relative', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 'var(--space-4)' }}>
                <span style={{ width: 78, height: 78, borderRadius: 999, background: 'var(--color-leather)', display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 6px 24px rgba(33,26,20,0.4)' }}>
                  <svg width="26" height="30" viewBox="0 0 26 30" fill="var(--color-white)" aria-hidden="true"><path d="M2 2.5 23 15 2 27.5Z" /></svg>
                </span>
                <span style={{ fontFamily: 'var(--font-body)', fontSize: 11, fontWeight: 600, letterSpacing: '0.2em', textTransform: 'uppercase', color: 'var(--color-white)' }}>Play the film · 4K</span>
              </span>
              <span className="ee-slot-chip">{id ? 'The Estate Film' : 'Placeholder · Estate Film'}</span>
            </button>
          )}
        </div>
      </Reveal>
      {!id ? <p className="ee-note" style={{ marginTop: 'var(--space-4)', textAlign: 'center' }}>Branded poster + play button shown. The film is in edit; the YouTube link is the single swap point.</p> : null}
    </SectionA>
  );
}

/* ---------------------------------------------------------------- OFFER --- */
function ProofTile({ index, title, meta, children, delay }) {
  return (
    <Reveal delay={delay} style={{ height: '100%' }}>
      <div style={{ background: 'rgba(255,253,248,0.04)', border: '1px solid var(--rule-on-deep)', borderRadius: 'var(--radius-md)', padding: 'var(--space-7)', display: 'flex', flexDirection: 'column', gap: 'var(--space-4)', height: '100%' }}>
        <div style={{ fontFamily: 'var(--font-body)', fontSize: 'var(--type-label-sm)', fontWeight: 700, letterSpacing: 'var(--tracking-label-sm)', color: 'var(--color-hay)' }}>{String(index).padStart(2, '0')}</div>
        <h3 style={dspA('var(--type-display-4)', { color: 'var(--color-white)', lineHeight: 1.18 })}>{title}</h3>
        <p style={bdyA({ color: 'var(--text-on-deep-muted)' })}>{children}</p>
        <div style={{ marginTop: 'auto', paddingTop: 'var(--space-4)', borderTop: '1px solid var(--rule-on-deep)', fontFamily: 'var(--font-body)', fontSize: 'var(--type-label)', fontWeight: 600, letterSpacing: 'var(--tracking-label)', textTransform: 'uppercase', color: 'var(--text-on-deep-muted)' }}>{meta}</div>
      </div>
    </Reveal>
  );
}
function Offer() {
  const specs = [
    '10+ private acres', 'Single-level main residence', 'Separate guesthouse',
    'Two barns · 5-stall + 4-stall', "225' × 100' outdoor arena", 'Covered arena',
    'Covered round pen', 'Hay barn', 'Rolling pastures with runs',
  ];
  return (
    <SectionA id="offer" tone="deep">
      <Reveal>
        <div style={{ maxWidth: '760px' }}>
          <RuleA tone="hay" length="48px" style={{ marginBottom: 'var(--space-5)' }} />
          <EyebrowA color="var(--color-hay)" style={{ marginBottom: 'var(--space-5)' }}>The Offer</EyebrowA>
          <p style={dspA(EE_DISPLAY_3A, { color: 'var(--color-white)', lineHeight: 1.16 })}>Most acreage buyers have to assemble the lifestyle piece by piece. Here, the major pieces are already working together.</p>
        </div>
      </Reveal>
      {/* specification stat band — figures marked as placeholders */}
      <Reveal delay={60}>
        <ul style={{ listStyle: 'none', margin: 'var(--space-8) 0 0', padding: 'var(--space-7) 0 0', borderTop: '1px solid var(--rule-on-deep)', display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: 'var(--space-5) var(--space-6)' }}>
          {specs.map((s, i) => (
            <li key={s} style={{ display: 'flex', gap: 'var(--space-3)', alignItems: 'baseline' }}>
              <span style={{ fontFamily: 'var(--font-body)', fontSize: 'var(--type-label-sm)', fontWeight: 700, color: 'var(--color-hay)', minWidth: '1.8em' }}>{String(i + 1).padStart(2, '0')}</span>
              <span style={{ fontFamily: 'var(--font-display)', fontSize: '1.4rem', color: 'var(--color-white)', lineHeight: 1.15 }}>{s}</span>
            </li>
          ))}
        </ul>
      </Reveal>
      <div className="ee-grid ee-grid--3" style={{ marginTop: 'var(--space-8)' }}>
        <ProofTile index={1} title="The land is private" meta="10+ acres" delay={0}>Mature oaks and rolling pasture wrap the residence, with equestrian facilities set back across the parcel.</ProofTile>
        <ProofTile index={2} title="Horses have a place" meta="Barns · arenas · round pen" delay={80}>Stalls, turnout, and riding infrastructure are in place and working together — not a future project.</ProofTile>
        <ProofTile index={3} title="Guests stay separately" meta="Guesthouse · lounge" delay={160}>Flexible guest spaces let the property host without crowding the main residence.</ProofTile>
      </div>
    </SectionA>
  );
}

/* ------------------------------------------------------------ RESIDENCE --- */
/* Floor plans, in display order. Shared with the gallery lightbox. */
const FLOORPLANS = [
  { src: `${WEB_A}floorplan/01-main-residence.jpg`, label: 'Main Residence', caption: 'Floor Plan · Main Residence', alt: 'Floor plan of the main residence at 7151 Johnston Road' },
  { src: `${WEB_A}floorplan/02-guest-house.jpg`,    label: 'Guest House',    caption: 'Floor Plan · Guest House',    alt: 'Floor plan of the guest house' },
  { src: `${WEB_A}floorplan/03-bunk-house.jpg`,     label: 'Bunk House',     caption: 'Floor Plan · Bunk House',     alt: 'Floor plan of the upper-barn bunkhouse' },
];

/* Sliding floor-plan gallery — arrows step through the plans; clicking a plan
   opens it in the shared lightbox for a closer read. Lives in the deep panel. */
function FloorPlanGallery({ items, onOpen }) {
  const [i, setI] = React.useState(0);
  const n = items.length;
  const go = (d) => setI((p) => (p + d + n) % n);
  return (
    <div className="ee-fpg">
      <div className="ee-fpg__viewport">
        <div className="ee-fpg__track" style={{ transform: `translateX(-${i * 100}%)` }}>
          {items.map((f, idx) => (
            <button
              key={f.src}
              type="button"
              className="ee-fpg__slide"
              onClick={(e) => onOpen(items, idx, e.currentTarget)}
              aria-label={`Open ${f.label} floor plan in full screen`}
              tabIndex={idx === i ? 0 : -1}
            >
              <img src={f.src} alt={f.alt} loading="lazy" />
              <span className="ee-fpg__zoom" aria-hidden="true">
                <svg width="16" height="16" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="1.7" fill="none" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="7" /><path d="M21 21l-4.3-4.3M11 8v6M8 11h6" /></svg>
              </span>
            </button>
          ))}
        </div>
        <button type="button" className="ee-fpg__arrow ee-fpg__arrow--prev" onClick={() => go(-1)} aria-label="Previous floor plan">
          <svg width="20" height="20" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="1.7" fill="none" strokeLinecap="round" strokeLinejoin="round"><path d="M15 5l-7 7 7 7" /></svg>
        </button>
        <button type="button" className="ee-fpg__arrow ee-fpg__arrow--next" onClick={() => go(1)} aria-label="Next floor plan">
          <svg width="20" height="20" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="1.7" fill="none" strokeLinecap="round" strokeLinejoin="round"><path d="M9 5l7 7-7 7" /></svg>
        </button>
      </div>
      <div className="ee-fpg__foot">
        <span className="ee-fpg__label">{items[i].label}</span>
        <span className="ee-fpg__dots" role="tablist" aria-label="Floor plans">
          {items.map((f, idx) => (
            <button
              key={f.src}
              type="button"
              role="tab"
              aria-selected={idx === i}
              aria-label={f.label}
              className={`ee-fpg__dot${idx === i ? ' is-active' : ''}`}
              onClick={() => setI(idx)}
            />
          ))}
        </span>
      </div>
    </div>
  );
}

function Residence({ onOpenTour, onOpenLightbox }) {
  const feats = [['home', 'Single-level living'], ['view', 'Large view-facing windows'], ['oak', 'Updated kitchen'], ['guesthouse', 'Arched doorways']];
  return (
    <SectionA id="residence" tone="alt">
      <div className="ee-split ee-split--media-lead" style={{ marginBottom: 'var(--space-9)' }}>
        <Reveal>
          <PhotoSlotA id="residence-exterior" src={`${WEB_A}placeholder/residence-exterior.jpg`} alt="The single-level main residence at 7151 Johnston Road" tone="oak" ratio="4 / 3.2" icon="home" caption="Main residence · single-level" />
        </Reveal>
        <Reveal delay={80}>
          <SectionHeadA eyebrow="The Main Residence" title="A single-level home that anchors the estate." />
          <p style={bdyA({ marginTop: 'var(--space-5)', maxWidth: '46ch' })}>The residence sits at the calm center of the property, oriented to the land. Living on one level — with an updated kitchen, arched doorways, and large view-facing windows framing pasture and ridge — keeps daily life connected to the estate around it.</p>
          <ul style={{ listStyle: 'none', margin: 'var(--space-6) 0 0', padding: 0, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-4)' }}>
            {feats.map(([ic, t]) => (
              <li key={t} style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-3)' }}>
                <span style={{ color: 'var(--color-leather)', flex: '0 0 auto' }}><EstateIconA name={ic} size={22} /></span>
                <span style={{ fontFamily: 'var(--font-body)', fontSize: 'var(--type-body-sm)', color: 'var(--text-primary)' }}>{t}</span>
              </li>
            ))}
          </ul>
        </Reveal>
      </div>

      {/* Floor-plan deep panel — dramatic depth translated into the estate palette */}
      <Reveal>
        <div style={{ background: 'var(--surface-deep)', borderRadius: 'var(--radius-lg)', padding: 'clamp(1.5rem, 4vw, var(--space-8))', boxShadow: 'var(--shadow-md)' }}>
          <div className="ee-split ee-split--text-lead" style={{ alignItems: 'center' }}>
            <div>
              <RuleA tone="hay" length="40px" style={{ marginBottom: 'var(--space-4)' }} />
              <EyebrowA color="var(--color-hay)" style={{ marginBottom: 'var(--space-4)' }}>The Floor Plan</EyebrowA>
              <h3 style={dspA(EE_DISPLAY_3A, { color: 'var(--color-white)' })}>Every level, read at a glance.</h3>
              <p style={bdyA({ color: 'var(--text-on-deep-muted)', marginTop: 'var(--space-5)', maxWidth: '40ch' })}>Floor plans for the main residence, guest house, and bunk house — slide through all three, and click any plan to open it full screen for a closer read.</p>
              <div style={{ marginTop: 'var(--space-6)' }}>
                <ButtonA variant="secondary" onDeep size="md" onClick={onOpenTour} iconRight={<span aria-hidden="true">&rarr;</span>} style={{ whiteSpace: 'normal', maxWidth: '100%' }}>Explore the interactive tour</ButtonA>
              </div>
            </div>
            <FloorPlanGallery items={FLOORPLANS} onOpen={(items, i, el) => onOpenLightbox(items, i, el, { frame: true })} />
          </div>
        </div>
      </Reveal>
    </SectionA>
  );
}

Object.assign(window, { Hero, Setting, Film, Offer, Residence });
