// Direction 1 — "Heimish Editorial"
// Warm cream/terracotta. Serif display (Cormorant Garamond) + sans body
// (Geist). Generous whitespace, editorial magazine-style rhythm.
// Self-contained: home → search → listing → booking → upsells → dashboard → admin
// Uses window.Placeholder, window.Ico, window.DYRA.

function D1Prototype({ tweaks, live }) {
  const [screen, setScreen] = React.useState('home');
  const [propertyId, setPropertyId] = React.useState('eph-4br-2ba');
  const [bookingStep, setBookingStep] = React.useState(0);
  const [goData, setGoData] = React.useState(null); // payload passed between screens (e.g. confirmation details)
  const [heb, setHeb] = React.useState(tweaks?.hebDensity ?? 'medium');
  React.useEffect(() => setHeb(tweaks?.hebDensity ?? 'medium'), [tweaks?.hebDensity]);

  // Hash-based deep-linking. External pages (e.g. /presidential) can link to
  //   /#listing:<slug>      → opens that listing's detail page
  //   /#booking:<slug>      → jumps into the booking flow for that listing
  //   /#search              → opens the search/results screen
  // Mirrors the hash convention used by the mobile site at /m.
  //
  // Magic-link email sends guests to "/?screen=dashboard&token=…" so we also
  // honour ?screen=… on the initial query string. We process it once on mount
  // (the dashboard gate handles token reads + sessionStorage persistence).
  React.useEffect(() => {
    if (!live) return;
    // Handle ?screen=… on initial mount (magic-link arrival).
    try {
      const sp = new URLSearchParams(window.location.search || '');
      const target = sp.get('screen');
      const ALLOWED = ['home','search','listing','booking','upsells','dashboard','payBalance','confirmation','paymentFailed','admin','listYourHome'];
      if (target && ALLOWED.indexOf(target) !== -1) {
        setScreen(target);
      }
    } catch (_) { /* ignore */ }

    const applyHash = () => {
      let h = (window.location.hash || '').replace(/^#/, '');
      const qi = h.indexOf('?');
      if (qi >= 0) h = h.slice(0, qi);
      if (!h) return;
      const [route, id] = h.split(':');
      if (route === 'listing' && id) {
        setPropertyId(id);
        setScreen('listing');
        requestAnimationFrame(() => window.scrollTo({ top: 0, behavior: 'auto' }));
      } else if (route === 'booking' && id) {
        setPropertyId(id);
        setBookingStep(0);
        setScreen('booking');
      } else if (route === 'search' || route === 'home') {
        setScreen(route);
      }
    };
    applyHash();
    window.addEventListener('hashchange', applyHash);
    return () => window.removeEventListener('hashchange', applyHash);
  }, [live]);

  // ── LIVE STORE: subscribe so admin edits flow into the guest site immediately ──
  // Subscribes to DyraStore (same tab → admin saves; cross-tab → storage events).
  // Falls back to the static seed if the store script isn't loaded yet.
  const [, forceUpdate] = React.useReducer(x => x + 1, 0);
  React.useEffect(() => {
    if (!window.DyraStore || !window.DyraStore.subscribe) return;
    return window.DyraStore.subscribe(() => forceUpdate());
  }, []);
  const properties = (window.DyraStore && window.DyraStore.state && window.DyraStore.state.properties)
    || (window.DYRA && window.DYRA.PROPERTIES) || [];
  // Match by id OR slug so deep-links like /#listing:presidential resolve
  // (the /presidential landing CTA passes the slug, not the UUID).
  const findProp = (id) => properties.find(x => x.id === id || x.slug === id);

  const tone = tweaks?.palette ?? 'terracotta';
  const palettes = {
    terracotta: { bg: '#f5efe3', ink: '#2a241c', muted: '#6b5e47', accent: '#b8532a', accent2: '#8a6a3d', line: '#d9cfba', card: '#fbf6ea' },
    olive:      { bg: '#f1eee0', ink: '#252820', muted: '#5e624e', accent: '#6b7a3e', accent2: '#8f7a3a', line: '#d3d2bd', card: '#f9f7e9' },
    plum:       { bg: '#f2ede5', ink: '#26202a', muted: '#5e4f63', accent: '#6b3a58', accent2: '#8a6a3d', line: '#d7cfc9', card: '#faf4ec' },
  };
  const p = palettes[tone] || palettes.terracotta;

  const serif = tweaks?.serif ?? 'Cormorant Garamond';
  const sans = tweaks?.sans ?? 'Geist';
  const hebFont = tweaks?.hebFont ?? 'Frank Ruhl Libre';

  const scrollRef = React.useRef(null);
  const go = (s, id, data) => {
    if (id) setPropertyId(id);
    setGoData(data ?? null);
    setScreen(s);
    if (s === 'booking') setBookingStep(0);
    // Track listing views against the active search session
    if (s === 'listing' && id && window.DyraStore && DyraStore.appendSearchView) {
      const searchId = window.DYRA && window.DYRA._search && window.DYRA._search.searchId;
      if (searchId) DyraStore.appendSearchView(searchId, id);
    }
    // In canvas mode, scroll the inner div; in live mode, scroll the window.
    requestAnimationFrame(() => {
      if (live) {
        window.scrollTo({ top: 0, behavior: 'auto' });
      } else if (scrollRef.current) {
        scrollRef.current.scrollTop = 0;
      }
    });
  };

  const HebSpan = ({ children, en }) => {
    if (heb === 'none') return <>{en}</>;
    if (heb === 'subtle') return <>{en}</>;
    if (heb === 'strong') return <span style={{ fontFamily: hebFont, direction: 'rtl', unicodeBidi: 'embed' }}>{children}</span>;
    return <><span style={{ fontFamily: hebFont, direction: 'rtl', unicodeBidi: 'embed', opacity: 0.8, marginInlineStart: 6, fontSize: '0.85em' }}>{children}</span></>;
  };

  const screens = {
    home:      <D1Home p={p} serif={serif} sans={sans} hebFont={hebFont} heb={heb} go={go} tweaks={tweaks} properties={properties}/>,
    search:    <D1Search p={p} serif={serif} sans={sans} go={go} properties={properties}/>,
    listing:   <D1Listing p={p} serif={serif} sans={sans} hebFont={hebFont} heb={heb} property={findProp(propertyId)} go={go}/>,
    booking:   <D1Booking p={p} serif={serif} sans={sans} hebFont={hebFont} property={findProp(propertyId)} step={bookingStep} setStep={setBookingStep} goData={goData} go={go}/>,
    upsells:   <D1Upsells p={p} serif={serif} sans={sans} go={go}/>,
    dashboard: <D1DashboardGate p={p} serif={serif} sans={sans} hebFont={hebFont} go={go}/>,
    payBalance: <D1PayBalance p={p} serif={serif} sans={sans} go={go}/>,
    confirmation: <D1Confirmation p={p} serif={serif} sans={sans} hebFont={hebFont} property={findProp(propertyId)} data={goData} go={go}/>,
    paymentFailed: <D1PaymentFailed p={p} serif={serif} sans={sans} property={findProp(propertyId)} data={goData} go={go}/>,
    admin:     <D1Admin p={p} serif={serif} sans={sans} go={go}/>,
    listYourHome: <D1ListYourHome p={p} serif={serif} sans={sans} go={go}/>,
  };

  return (
    <div style={{
      // `live` mode = standalone-website rendering: drop the fixed-canvas
      // overflow lock so the page can grow with content + scroll naturally.
      // Canvas mode (default) keeps the original 1280×820 letterbox behavior.
      width: '100%',
      height: live ? 'auto' : '100%',
      minHeight: live ? '100vh' : undefined,
      background: p.bg, color: p.ink, fontFamily: `${sans}, -apple-system, sans-serif`,
      display: 'flex', flexDirection: 'column',
      overflow: live ? 'visible' : 'hidden',
    }}>
      <D1Nav p={p} serif={serif} current={screen} go={go}/>
      {/* In canvas/letterbox mode, this is the inner scrollable region.
          In live/standalone mode, we let the page itself scroll instead, so
          fixed-position UI (sticky headers, the Tweaks panel handle, etc.)
          anchors to the browser viewport rather than to a clipped div. */}
      <div ref={scrollRef} style={{
        flex: live ? 'none' : 1,
        overflow: live ? 'visible' : 'auto',
        width: '100%',
      }}>
        {screens[screen]}
      </div>
    </div>
  );
}

function D1Nav({ p, serif, current, go }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: '22px 48px', borderBottom: `1px solid ${p.line}`, background: p.bg, zIndex: 5,
    }}>
      <div onClick={() => go('home')} style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 12 }}>
        <img src={(typeof window !== 'undefined' && window.DYRA_LOGO) || "assets/dyra-logo-original.jpg"} alt="Dyra" style={{ width: 44, height: 44, borderRadius: 6, objectFit: 'cover', display: 'block' }}/>
        <div style={{ fontSize: 10, letterSpacing: '0.22em', textTransform: 'uppercase', color: p.muted }}>Crown Heights</div>
      </div>
      <div style={{ display: 'flex', gap: 32, fontSize: 13, color: p.muted }}>
      </div>
      <div style={{ display: 'flex', gap: 16, alignItems: 'center' }}>
        <span style={{ fontSize: 12, color: p.muted }}>EN · עב</span>
        <button onClick={() => go('dashboard')} style={{
          background: p.accent, color: p.bg, border: 'none', padding: '9px 18px', borderRadius: 999,
          fontSize: 12, letterSpacing: '0.06em', textTransform: 'uppercase', cursor: 'pointer',
        }}>My stay</button>
        <button onClick={() => go('listYourHome')} style={{
          background: p.accent, color: p.bg, border: 'none', padding: '9px 18px', borderRadius: 999,
          fontSize: 12, letterSpacing: '0.06em', textTransform: 'uppercase', cursor: 'pointer',
        }}>List your home</button>
        <button onClick={() => {
          // Deployed build: navigate to the standalone admin portal at /admin/.
          // Prototype: open the standalone Dyra Admin.html (real login screen + analytics).
          if (typeof window !== 'undefined' && window.DYRA_DEPLOY) {
            window.location.href = '/admin';
          } else {
            window.location.href = '/admin';
          }
        }} style={{
          background: p.accent, color: p.bg, border: 'none', padding: '9px 18px', borderRadius: 999,
          fontSize: 12, letterSpacing: '0.06em', textTransform: 'uppercase', cursor: 'pointer',
        }}>Login</button>
      </div>
    </div>
  );
}

function D1ScreenBar({ current, setScreen, p }) {
  const items = [
    ['home', 'Home'], ['search', 'Search'], ['listing', 'Listing'],
    ['booking', 'Booking'], ['upsells', 'Upsells'], ['dashboard', 'Guest'], ['admin', 'Admin'],
  ];
  return (
    <div style={{
      display: 'flex', gap: 4, padding: '8px 10px', borderTop: `1px solid ${p.line}`, background: p.card,
      fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase',
    }}>
      {items.map(([k, label]) => (
        <button key={k} onClick={() => setScreen(k)} style={{
          background: current === k ? p.ink : 'transparent',
          color: current === k ? p.bg : p.muted,
          border: 'none', padding: '5px 10px', borderRadius: 3, cursor: 'pointer',
          fontFamily: 'inherit', fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase',
        }}>{label}</button>
      ))}
    </div>
  );
}

// ─────── HOME ───────
function D1Home({ p, serif, sans, hebFont, heb, go, tweaks, properties }) {
  const heroVariant = tweaks?.heroVariant ?? 'centered';
  const cardStyle = tweaks?.cardStyle ?? 'editorial';
  const photoStyle = tweaks?.photoStyle ?? 'warm';
  // Live from store (admin Content edits hero copy + featured property IDs).
  // Falls back to seed if store hasn't loaded yet. The seed contains demo IDs
  // that don't exist in the live database, so we always backfill from `all`
  // until we have 3 listings to show — matching the mobile portfolio strip.
  const all = properties || (window.DYRA && window.DYRA.PROPERTIES) || [];
  const content = (window.DyraStore && window.DyraStore.state && window.DyraStore.state.content) || null;
  const featuredIds = content?.featuredIds;
  const lookedUp = (featuredIds || [])
    .map(id => all.find(x => x.id === id))
    .filter(Boolean);
  let featured = lookedUp;
  if (featured.length < 3) {
    const seen = new Set(featured.map(x => x.id));
    featured = [...featured, ...all.filter(x => !seen.has(x.id))].slice(0, 3);
  } else {
    featured = featured.slice(0, 3);
  }
  const nextParsha = (content?.parsha && content.parsha[0]) || (window.DYRA && window.DYRA.PARSHA && window.DYRA.PARSHA[0]) || null;
  const heroContent = content?.hero;

  return (
    <div style={{ position: 'relative' }}>
      {/* SHABBOS CLOCK — small bottom-right overlay on hero */}
      <div style={{
        position: 'absolute', top: 24, right: 32, zIndex: 6,
        background: p.card,
        color: p.ink,
        border: `1px solid ${p.line}`,
        borderRadius: 8,
        padding: '12px 16px', minWidth: 200,
        boxShadow: '0 4px 14px rgba(42,36,28,0.08)',
        backdropFilter: 'blur(6px)',
      }}>
        <div style={{ fontSize: 9, letterSpacing: '0.2em', textTransform: 'uppercase', color: p.muted, marginBottom: 6 }}>This Shabbos</div>
        <div style={{ fontFamily: serif, fontSize: 19, fontWeight: 400, lineHeight: 1.1 }}>
          Parshas <em style={{ color: p.accent }}>{nextParsha.parsha}</em>
        </div>
        {heb !== 'none' && nextParsha.parshaHeb && (
          <div style={{ fontFamily: hebFont, fontSize: 12, color: p.muted, direction: 'rtl', marginTop: 3 }}>{nextParsha.parshaHeb}</div>
        )}
        <div style={{ display: 'flex', gap: 14, marginTop: 10, paddingTop: 10, borderTop: `1px solid ${p.line}`, fontSize: 11 }}>
          <div>
            <div style={{ fontSize: 8, letterSpacing: '0.16em', color: p.muted, textTransform: 'uppercase' }}>Candle</div>
            <div style={{ fontFamily: serif, fontSize: 14, marginTop: 2 }}>{nextParsha.candleLight}</div>
          </div>
          <div>
            <div style={{ fontSize: 8, letterSpacing: '0.16em', color: p.muted, textTransform: 'uppercase' }}>Havdalah</div>
            <div style={{ fontFamily: serif, fontSize: 14, marginTop: 2 }}>{nextParsha.havdalah}</div>
          </div>
        </div>
      </div>

      {/* HERO */}
      {heroVariant === 'split' ? (
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', minHeight: 540 }}>
          <div style={{ padding: '80px 48px 64px', display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
            <div style={{ fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', color: p.accent, marginBottom: 28 }}>
              {heroContent?.eyebrow || 'Kosher homes · Crown Heights'}
            </div>
            <h1 style={{ fontFamily: serif, fontSize: 76, fontWeight: 400, lineHeight: 0.98, letterSpacing: '-0.02em', margin: '0 0 28px' }}>
              {heroContent?.headline ? (
                heroContent.headline
              ) : (
                <>
                  The <em style={{ color: p.accent }}>gold&nbsp;standard</em><br/>
                  of kosher stays — in the<br/>
                  heart of Crown&nbsp;Heights.
                </>
              )}
            </h1>
            {heb !== 'none' && (
              <div style={{ fontFamily: hebFont, fontSize: 20, color: p.muted, marginBottom: 28, direction: 'rtl' }}>
                בית כשר · ברוכים הבאים לקראון הייטס
              </div>
            )}
            <p style={{ fontSize: 16, lineHeight: 1.6, color: p.muted, maxWidth: 440, margin: '0 0 40px' }}>
              Six private homes within walking distance of 770 — including four-, three-, two- and one-bedroom residences directly across from the Rebbe. Every kitchen kashered, every Shabbos set up before you arrive.
            </p>
            <div style={{ display: 'flex', gap: 14 }}>
              <button onClick={() => go('search')} style={{
                background: p.ink, color: p.bg, border: 'none', padding: '14px 24px', borderRadius: 999,
                fontSize: 13, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 8,
              }}>Find your stay <Ico name="arrow" size={14}/></button>
              <button style={{
                background: 'transparent', color: p.ink, border: `1px solid ${p.line}`, padding: '14px 24px', borderRadius: 999,
                fontSize: 13, cursor: 'pointer',
              }}>Host with Dyra</button>
            </div>
          </div>
          <Placeholder label="Hero · brownstone facade at golden hour" tone={photoStyle === 'warm' ? 'clay' : photoStyle === 'muted' ? 'stone' : 'cream'} density="loose" style={{ minHeight: 540 }}/>
        </div>
      ) : heroVariant === 'centered' ? (
        <div style={{ position: 'relative', minHeight: 620 }}>
          {/* Striped backdrop, full-bleed and behind everything — accent-tinted, no label */}
          <Placeholder tone="accent" density="loose" style={{ position: 'absolute', inset: 0 }}/>
          {/* Soft wash so type stays legible against the stripes */}
          <div style={{ position: 'absolute', inset: 0, background: `linear-gradient(180deg, ${p.bg}d9 0%, ${p.bg}b3 45%, ${p.bg}d9 100%)` }}/>
          {/* Centered slogan column with the search pill anchored to the bottom of the hero box */}
          <div style={{
            position: 'relative', minHeight: 620,
            display: 'flex', flexDirection: 'column', alignItems: 'center',
            padding: '96px 48px 40px', textAlign: 'center',
          }}>
            {/* Top group: eyebrow + slogan, vertically centered in the available space */}
            <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', width: '100%' }}>
              <div style={{ fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', color: p.accent, marginBottom: 28 }}>
                {heroContent?.eyebrow || 'Dyra Kosher Rentals'}
              </div>
              <h1 style={{ fontFamily: serif, fontSize: 88, fontWeight: 400, lineHeight: 0.98, letterSpacing: '-0.02em', margin: 0, maxWidth: 1100 }}>
                {heroContent?.headline ? (
                  heroContent.headline
                ) : (
                  <>
                    The <em style={{ color: p.accent }}>gold&nbsp;standard</em> of kosher stays<br/>
                    in the heart of Crown&nbsp;Heights.
                  </>
                )}
              </h1>
            </div>
            {/* Quick-search pill — pinned to the bottom of the hero box */}
            <div style={{ width: '100%', maxWidth: 1080 }}>
              <D1SearchPill p={p} serif={serif} hebFont={hebFont} heb={heb} go={go} embedded/>
            </div>
          </div>
        </div>
      ) : (
        <div style={{ position: 'relative', minHeight: 560 }}>
          <Placeholder label="Hero · Crown Heights morning" tone="clay" density="loose" style={{ position: 'absolute', inset: 0 }}/>
          <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(42,36,28,0.15), rgba(42,36,28,0.55))' }}/>
          <div style={{ position: 'relative', padding: '120px 48px 80px', color: '#fbf6ea', maxWidth: 780 }}>
            <div style={{ fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', marginBottom: 28, opacity: 0.9 }}>
              Kosher homes · Crown Heights
            </div>
            <h1 style={{ fontFamily: serif, fontSize: 92, fontWeight: 400, lineHeight: 0.95, letterSpacing: '-0.02em', margin: '0 0 28px' }}>
              The <em style={{
                background: 'linear-gradient(180deg, #d4a541 0%, #b8862a 55%, #8a5e15 100%)',
                WebkitBackgroundClip: 'text',
                backgroundClip: 'text',
                WebkitTextFillColor: 'transparent',
                color: '#b8862a', /* fallback for non-webkit */
                fontStyle: 'italic',
              }}>gold standard</em> of kosher stays in the heart of Crown&nbsp;Heights.
            </h1>
          </div>
        </div>
      )}

      {/* QUICK-SEARCH PILL — embedded in the centered hero, so this duplicate is removed */}

      {/* FEATURED HOMES */}
      <div style={{ padding: '72px 48px 24px', display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
        <h2 style={{ fontFamily: serif, fontSize: 44, fontWeight: 400, letterSpacing: '-0.02em', margin: 0 }}>
          The <em style={{ color: p.accent }}>portfolio.</em>
        </h2>
        <span onClick={() => go('search')} style={{ cursor: 'pointer', fontSize: 13, color: p.muted, display: 'flex', alignItems: 'center', gap: 6 }}>
          See all <Ico name="arrow" size={14}/>
        </span>
      </div>

      <div style={{ padding: '0 48px 72px', display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 32 }}>
        {featured.map((prop) => (
          <D1FeaturedCard key={prop.id} prop={prop} p={p} serif={serif} cardStyle={cardStyle} photoStyle={photoStyle} onClick={() => go('listing', prop.id)}/>
        ))}
      </div>

      {/* KOSHER PROMISE STRIP */}
      <div style={{ padding: '64px 48px 72px' }}>
        <div style={{ fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', color: p.accent, marginBottom: 16 }}>
          The Dyra Promise
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '48px 48px', marginTop: 8 }}>
          {[
            { ico: 'pin', t: 'Unmatched location', s: 'Every home is walking distance to 770, close to mikvah, shuls, and Kingston.' },
            { ico: 'flame', t: 'Kosher kitchen', s: 'Every home is strictly kosher. Separate meat and dairy — sinks, counters, dishes, silverware.' },
            { ico: 'candle', t: 'Shabbos-ready', s: 'Every home comes with an urn, a blech / hot plate, and Shabbos lamps ready to go.' },
            { ico: 'home', t: 'Elevated comfort', s: 'Freshly-washed linens, plush towels, full-sized appliances, and thoughtful details. Designed to feel like home, only better.' },
            { ico: 'sparkle', t: 'Fast, responsive support', s: 'A real person on WhatsApp. Most messages answered in under ten minutes — before, during, and after your stay.' },
            { ico: 'shield', t: 'Reliable every time', s: 'Same standard, every home. Every turnover. No surprises on arrival, no improvisation — just a place that\u2019s ready for you.' },
          ].map((x, i) => (
            <div key={i}>
              <div style={{ color: p.accent, marginBottom: 14 }}><Ico name={x.ico} size={22} stroke={1.2}/></div>
              <h3 style={{ fontFamily: serif, fontSize: 22, fontWeight: 500, margin: '0 0 8px', letterSpacing: '-0.01em' }}>{x.t}</h3>
              <p style={{ fontSize: 13, lineHeight: 1.6, color: p.muted, margin: 0 }}>{x.s}</p>
            </div>
          ))}
        </div>
      </div>

      {/* CONTACT FORM — guests can send a message; populates admin inquiries */}
      <D1ContactBlock p={p} serif={serif}/>

      {/* FOOTER — WhatsApp + Email contact */}
      <div style={{ padding: '56px 48px 64px', borderTop: `1px solid ${p.line}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 32, flexWrap: 'wrap' }}>
        <div style={{ fontFamily: serif, fontSize: 28, fontWeight: 500 }}>Dyra</div>
        <div style={{ display: 'flex', gap: 14, alignItems: 'center', flexWrap: 'wrap' }}>
          <a
            href="https://wa.me/18625207797"
            target="_blank"
            rel="noopener noreferrer"
            style={{
              display: 'inline-flex', alignItems: 'center', gap: 12,
              textDecoration: 'none', color: p.ink,
              background: p.card, border: `1px solid ${p.line}`, borderRadius: 999,
              padding: '12px 20px 12px 14px',
            }}
          >
            <span style={{
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              width: 34, height: 34, borderRadius: 999, background: '#25D366', color: '#fff',
            }}>
              <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor" aria-hidden="true">
                <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.297-.497.1-.198.05-.371-.025-.52-.075-.148-.669-1.611-.916-2.206-.242-.579-.487-.5-.669-.51l-.57-.01c-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.095 3.2 5.076 4.487.709.306 1.263.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.247-.694.247-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413"/>
              </svg>
            </span>
            <div style={{ display: 'flex', flexDirection: 'column', lineHeight: 1.15 }}>
              <span style={{ fontSize: 10, letterSpacing: '0.2em', textTransform: 'uppercase', color: p.muted }}>WhatsApp</span>
              <span style={{ fontFamily: serif, fontSize: 20, fontWeight: 500 }}>862-520-7797</span>
            </div>
          </a>

          <a
            href="mailto:dyrakosherrentals@gmail.com"
            style={{
              display: 'inline-flex', alignItems: 'center', gap: 12,
              textDecoration: 'none', color: p.ink,
              background: p.card, border: `1px solid ${p.line}`, borderRadius: 999,
              padding: '12px 20px 12px 14px',
            }}
          >
            <span style={{
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              width: 34, height: 34, borderRadius: 999, background: '#EA4335', color: '#fff',
            }}>
              <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor" aria-hidden="true">
                <path d="M24 5.457v13.909c0 .904-.732 1.636-1.636 1.636h-3.819V11.73L12 16.64l-6.545-4.91v9.273H1.636A1.636 1.636 0 0 1 0 19.366V5.457c0-2.023 2.309-3.178 3.927-1.964L5.455 4.64 12 9.548l6.545-4.91 1.528-1.145C21.69 2.28 24 3.434 24 5.457z"/>
              </svg>
            </span>
            <div style={{ display: 'flex', flexDirection: 'column', lineHeight: 1.15 }}>
              <span style={{ fontSize: 10, letterSpacing: '0.2em', textTransform: 'uppercase', color: p.muted }}>Email</span>
              <span style={{ fontFamily: serif, fontSize: 20, fontWeight: 500 }}>dyrakosherrentals@gmail.com</span>
            </div>
          </a>
        </div>
      </div>
    </div>
  );
}

function D1SearchPill({ p, serif, hebFont, heb, go, embedded }) {
  const [open, setOpen] = React.useState(null); // null | 'checkin' | 'checkout' | 'guests'
  const [checkIn, setCheckIn] = React.useState({ y: 2026, m: 4, d: 14 }); // May 14
  const [checkOut, setCheckOut] = React.useState({ y: 2026, m: 4, d: 17 }); // May 17
  const [guests, setGuests] = React.useState({ adults: 2, kids: 3, infants: 1 });

  // Close popover on outside click
  const wrapRef = React.useRef(null);
  React.useEffect(() => {
    const h = (e) => { if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(null); };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, []);

  const fmtDate = (d) => {
    const dt = new Date(d.y, d.m, d.d);
    const day = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'][dt.getDay()];
    const mon = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'][d.m];
    return `${day}, ${mon} ${d.d}`;
  };
  // Hebrew date for any Gregorian {y, m, d}. Anchored at 2026-05-14 = 26 Iyar
  // 5786; we walk forward/backward through the month-length table to roll
  // over month boundaries, so every month in the picker has Hebrew dates,
  // not just the current one.
  const HEB_MONTHS = [
    { name: 'Tishrei',  len: 30 }, { name: 'Cheshvan', len: 29 }, { name: 'Kislev',  len: 30 },
    { name: 'Tevet',    len: 29 }, { name: 'Shvat',    len: 30 }, { name: 'Adar',    len: 29 },
    { name: 'Nisan',    len: 30 }, { name: 'Iyar',     len: 29 }, { name: 'Sivan',   len: 30 },
    { name: 'Tammuz',   len: 29 }, { name: 'Av',       len: 30 }, { name: 'Elul',    len: 29 },
  ];
  const hebDate = (d) => {
    if (!d || d.y == null || d.m == null || d.d == null) return '';
    const anchor = new Date('2026-05-14T00:00:00');
    const target = new Date(d.y, d.m, d.d);
    let dayOffset = Math.round((target - anchor) / 86400000);
    let monthIdx = 7;            // Iyar
    let dayInMonth = 26 + dayOffset;
    while (dayInMonth > HEB_MONTHS[monthIdx].len) {
      dayInMonth -= HEB_MONTHS[monthIdx].len;
      monthIdx = (monthIdx + 1) % 12;
    }
    while (dayInMonth < 1) {
      monthIdx = (monthIdx - 1 + 12) % 12;
      dayInMonth += HEB_MONTHS[monthIdx].len;
    }
    return `${dayInMonth} ${HEB_MONTHS[monthIdx].name}`;
  };

  const guestSummary = () => {
    const parts = [];
    if (guests.adults) parts.push(`${guests.adults} adult${guests.adults !== 1 ? 's' : ''}`);
    if (guests.kids) parts.push(`${guests.kids} kid${guests.kids !== 1 ? 's' : ''}`);
    return parts.join(' · ') || 'Add guests';
  };
  const guestSub = () => guests.infants ? `${guests.infants} infant${guests.infants !== 1 ? 's' : ''}` : 'No infants';

  return (
    <div style={{ padding: embedded ? 0 : '40px 48px 0', position: 'relative' }}>
      <div ref={wrapRef} style={{
        background: p.card, border: `1px solid ${p.line}`, borderRadius: 999, padding: '10px 10px 10px 24px',
        display: 'grid', gridTemplateColumns: '1fr 1fr 1fr auto', alignItems: 'center', gap: 0,
        boxShadow: '0 2px 0 rgba(0,0,0,0.03)',
        position: 'relative',
      }}>
        <SearchField
          label="Check in" value={fmtDate(checkIn)} sub={hebDate(checkIn)} p={p}
          active={open === 'checkin'}
          onClick={() => setOpen(open === 'checkin' ? null : 'checkin')}
        />
        <SearchField
          label="Check out" value={fmtDate(checkOut)} sub={hebDate(checkOut)} p={p} divider
          active={open === 'checkout'}
          onClick={() => setOpen(open === 'checkout' ? null : 'checkout')}
        />
        <SearchField
          label="Guests" value={guestSummary()} sub={guestSub()} p={p} divider
          active={open === 'guests'}
          onClick={() => setOpen(open === 'guests' ? null : 'guests')}
        />
        <button onClick={() => {
          const ci = `${checkIn.y}-${String(checkIn.m+1).padStart(2,'0')}-${String(checkIn.d).padStart(2,'0')}`;
          const co = `${checkOut.y}-${String(checkOut.m+1).padStart(2,'0')}-${String(checkOut.d).padStart(2,'0')}`;
          window.DYRA._search = { guests: { ...guests }, checkIn: ci, checkOut: co };
          if (window.DyraStore && DyraStore.logSearch) {
            const sid = DyraStore.logSearch({
              checkIn: ci, checkOut: co,
              adults: guests.adults || 0,
              children: (guests.kids || 0) + (guests.infants || 0),
            });
            window.DYRA._search.searchId = sid;
          }
          go('search');
        }} style={{
          background: p.accent, color: p.bg, border: 'none', padding: '16px 22px', borderRadius: 999,
          cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 8, fontSize: 13,
        }}><Ico name="search" size={15}/> Search</button>

        {(open === 'checkin' || open === 'checkout') && (
          <DatePopover
            p={p} serif={serif} hebFont={hebFont} heb={heb}
            mode={open}
            minNights={2}
            checkIn={checkIn} checkOut={checkOut}
            hebDate={hebDate}
            onPick={(d) => {
              if (open === 'checkin') {
                setCheckIn(d);
                // Enforce min 2 nights: if new checkin is within 2 days of checkout, bump checkout
                const inT = new Date(d.y, d.m, d.d).getTime();
                const outT = new Date(checkOut.y, checkOut.m, checkOut.d).getTime();
                const minOutT = new Date(d.y, d.m, d.d + 2).getTime();
                if (outT < minOutT) {
                  const nx = new Date(d.y, d.m, d.d + 3); // default to 3-night stay
                  setCheckOut({ y: nx.getFullYear(), m: nx.getMonth(), d: nx.getDate() });
                }
                setOpen('checkout');
              } else {
                setCheckOut(d);
                setOpen(null);
              }
            }}
            onClose={() => setOpen(null)}
          />
        )}
        {open === 'guests' && (
          <GuestsPopover p={p} serif={serif} guests={guests} setGuests={setGuests} onClose={() => setOpen(null)}/>
        )}
      </div>
    </div>
  );
}

function DatePopover({ p, serif, hebFont, heb, mode, checkIn, checkOut, hebDate, onPick, onClose, minNights = 2 }) {
  const [cursor, setCursor] = React.useState({ y: 2026, m: 4 }); // May 2026
  const monthName = (m, y) => `${['January','February','March','April','May','June','July','August','September','October','November','December'][m]} ${y}`;

  const buildMonth = (y, m) => {
    const first = new Date(y, m, 1).getDay();
    const daysIn = new Date(y, m + 1, 0).getDate();
    const cells = [];
    for (let i = 0; i < first; i++) cells.push(null);
    for (let d = 1; d <= daysIn; d++) cells.push(d);
    return cells;
  };

  const sameDay = (a, b) => a && b && a.y === b.y && a.m === b.m && a.d === b.d;
  const inRange = (y, m, d) => {
    const t = new Date(y, m, d).getTime();
    const a = new Date(checkIn.y, checkIn.m, checkIn.d).getTime();
    const b = new Date(checkOut.y, checkOut.m, checkOut.d).getTime();
    return t > a && t < b;
  };
  // Earliest valid checkout = checkIn + minNights
  const minCheckoutDate = new Date(checkIn.y, checkIn.m, checkIn.d + minNights);

  const renderMonth = (y, m, monthIdx) => {
    const cells = buildMonth(y, m);
    return (
      <div key={`${y}-${m}`} style={{ flex: 1 }}>
        <div style={{ textAlign: 'center', fontFamily: serif, fontSize: 19, fontWeight: 500, marginBottom: 14 }}>
          {monthName(m, y)}
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 2, fontSize: 10, color: p.muted, textAlign: 'center', marginBottom: 6, letterSpacing: '0.1em' }}>
          {['S','M','T','W','T','F','S'].map((d, i) => <div key={i} style={{ padding: '4px 0', fontWeight: 500 }}>{d}</div>)}
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 2 }}>
          {cells.map((d, i) => {
            if (!d) return <div key={i}/>;
            const isCheckIn = sameDay({ y, m, d }, checkIn);
            const isCheckOut = sameDay({ y, m, d }, checkOut);
            const between = inRange(y, m, d);
            const isEdge = isCheckIn || isCheckOut;
            const heb = hebDate({ y, m, d });
            // Fridays & Saturdays get a subtle accent dot
            const wk = new Date(y, m, d).getDay();
            const isShabbos = wk === 5 || wk === 6;
            // Disable too-early checkout dates (enforces min-nights rule)
            const cellDate = new Date(y, m, d);
            const tooEarlyCheckout = mode === 'checkout' && cellDate < minCheckoutDate;
            const disabled = tooEarlyCheckout;
            return (
              <button
                key={i}
                onClick={() => !disabled && onPick({ y, m, d })}
                disabled={disabled}
                title={disabled ? `Minimum ${minNights} night${minNights === 1 ? '' : 's'}` : undefined}
                style={{
                  padding: '8px 0 6px',
                  background: isEdge ? p.ink : between ? 'rgba(184,83,42,0.08)' : 'transparent',
                  color: disabled ? p.muted : (isEdge ? p.bg : p.ink),
                  opacity: disabled ? 0.35 : 1,
                  border: 'none', cursor: disabled ? 'not-allowed' : 'pointer', borderRadius: 6,
                  fontFamily: 'inherit', fontSize: 13, lineHeight: 1.1,
                  position: 'relative',
                  textDecoration: disabled ? 'line-through' : 'none',
                }}
              >
                <div style={{ fontFamily: serif, fontSize: 15, fontWeight: isEdge ? 500 : 400 }}>{d}</div>
                <div style={{ fontSize: 8.5, opacity: isEdge ? 0.85 : 0.55, letterSpacing: '0.02em', marginTop: 1 }}>
                  {heb ? heb.split(' ').slice(0, 2).join(' ') : ''}
                </div>
                {isShabbos && !isEdge && (
                  <div style={{ position: 'absolute', bottom: 3, left: '50%', transform: 'translateX(-50%)', width: 3, height: 3, borderRadius: 99, background: p.accent, opacity: 0.7 }}/>
                )}
              </button>
            );
          })}
        </div>
      </div>
    );
  };

  const next = { y: cursor.m === 11 ? cursor.y + 1 : cursor.y, m: (cursor.m + 1) % 12 };

  return (
    <div style={{
      position: 'absolute',
      top: 'calc(100% + 12px)',
      left: mode === 'checkin' ? '32%' : '48%',
      background: p.card,
      border: `1px solid ${p.line}`,
      borderRadius: 16,
      padding: 24,
      boxShadow: '0 12px 40px rgba(42,36,28,0.14)',
      width: 680,
      zIndex: 20,
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
        <div style={{ fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: p.muted }}>
          {mode === 'checkin' ? 'Select check-in' : 'Select check-out'}
        </div>
        <div style={{ display: 'flex', gap: 6 }}>
          <button onClick={() => setCursor(c => ({ y: c.m === 0 ? c.y - 1 : c.y, m: (c.m + 11) % 12 }))} style={{ background: 'transparent', border: `1px solid ${p.line}`, borderRadius: 99, width: 28, height: 28, cursor: 'pointer', color: p.ink, fontSize: 13 }}>‹</button>
          <button onClick={() => setCursor(c => ({ y: c.m === 11 ? c.y + 1 : c.y, m: (c.m + 1) % 12 }))} style={{ background: 'transparent', border: `1px solid ${p.line}`, borderRadius: 99, width: 28, height: 28, cursor: 'pointer', color: p.ink, fontSize: 13 }}>›</button>
        </div>
      </div>

      <div style={{ display: 'flex', gap: 32, marginTop: 8 }}>
        {renderMonth(cursor.y, cursor.m, 0)}
        {renderMonth(next.y, next.m, 1)}
      </div>

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 20, paddingTop: 16, borderTop: `1px solid ${p.line}` }}>
        <div style={{ fontSize: 11, color: p.muted, display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
            <span style={{ width: 6, height: 6, borderRadius: 99, background: p.accent, opacity: 0.7 }}/> Shabbos
          </span>
          <span style={{ color: p.muted, opacity: 0.5 }}>·</span>
          <span>Min {minNights} night{minNights === 1 ? '' : 's'}</span>
          <span style={{ color: p.muted, opacity: 0.5 }}>·</span>
          <span>Hebrew date below each day</span>
        </div>
        <button onClick={onClose} style={{
          background: 'transparent', color: p.ink, border: `1px solid ${p.line}`,
          padding: '8px 16px', borderRadius: 999, cursor: 'pointer', fontSize: 12,
        }}>Close</button>
      </div>
    </div>
  );
}

function GuestsPopover({ p, serif, guests, setGuests, onClose }) {
  const Row = ({ label, sub, k, min = 0, max = 12 }) => (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '14px 0', borderBottom: `1px solid ${p.line}` }}>
      <div>
        <div style={{ fontFamily: serif, fontSize: 17 }}>{label}</div>
        <div style={{ fontSize: 11, color: p.muted, marginTop: 2 }}>{sub}</div>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <button
          onClick={() => setGuests(g => ({ ...g, [k]: Math.max(min, g[k] - 1) }))}
          style={{ width: 30, height: 30, borderRadius: 99, border: `1px solid ${p.line}`, background: 'transparent', cursor: 'pointer', color: p.ink, fontSize: 14 }}
        >–</button>
        <div style={{ minWidth: 20, textAlign: 'center', fontFamily: serif, fontSize: 17 }}>{guests[k]}</div>
        <button
          onClick={() => setGuests(g => ({ ...g, [k]: Math.min(max, g[k] + 1) }))}
          style={{ width: 30, height: 30, borderRadius: 99, border: `1px solid ${p.line}`, background: 'transparent', cursor: 'pointer', color: p.ink, fontSize: 14 }}
        >+</button>
      </div>
    </div>
  );
  return (
    <div style={{
      position: 'absolute',
      top: 'calc(100% + 12px)',
      right: 24,
      background: p.card,
      border: `1px solid ${p.line}`,
      borderRadius: 16,
      padding: '8px 24px 20px',
      boxShadow: '0 12px 40px rgba(42,36,28,0.14)',
      width: 340,
      zIndex: 20,
    }}>
      <Row label="Adults" sub="Age 13+" k="adults" min={1}/>
      <Row label="Children" sub="Ages 2–12" k="kids"/>
      <Row label="Infants" sub="Under 2" k="infants"/>
      <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 12 }}>
        <button onClick={onClose} style={{
          background: p.ink, color: p.bg, border: 'none',
          padding: '10px 18px', borderRadius: 999, cursor: 'pointer', fontSize: 12,
        }}>Done</button>
      </div>
    </div>
  );
}

function SearchField({ label, value, sub, p, divider, active, onClick }) {
  return (
    <div onClick={onClick} style={{
      padding: '6px 18px',
      borderLeft: divider ? `1px solid ${p.line}` : 'none',
      cursor: 'pointer',
      borderRadius: 999,
      background: active ? 'rgba(42,36,28,0.04)' : 'transparent',
      transition: 'background 120ms ease',
    }}>
      <div style={{ fontSize: 10, letterSpacing: '0.15em', textTransform: 'uppercase', color: p.muted, marginBottom: 3 }}>{label}</div>
      <div style={{ fontSize: 14, color: p.ink }}>{value}</div>
      <div style={{ fontSize: 11, color: p.muted }}>{sub}</div>
    </div>
  );
}

function D1FeaturedCard({ prop, p, serif, cardStyle, photoStyle, onClick }) {
  const tones = { luxury: 'clay', premium: 'cream', standard: 'warm', value: 'ivory' };
  const heroSrc = prop.photos && prop.photos[0] ? prop.photos[0].src : null;
  const heroPos = prop.photos && prop.photos[0] ? prop.photos[0].pos : 'center';
  if (cardStyle === 'minimal') {
    return (
      <div onClick={onClick} style={{ cursor: 'pointer' }}>
        <Placeholder src={heroSrc} objectPosition={heroPos} label={prop.hero} tone={tones[prop.tier]} density="med" style={{ aspectRatio: '4/5', marginBottom: 18 }}/>
        {prop.cardEyebrow && (
          <div style={{ fontSize: 10, letterSpacing: '0.2em', textTransform: 'uppercase', color: p.accent, marginBottom: 6 }}>{prop.cardEyebrow}</div>
        )}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
          <h3 style={{ fontFamily: serif, fontSize: 24, fontWeight: 500, margin: 0, letterSpacing: '-0.01em' }}>{prop.name}</h3>
          <div style={{ fontSize: 14 }}>${prop.priceFrom}<span style={{ color: p.muted, fontSize: 11 }}>/nt</span></div>
        </div>
        <div style={{ fontSize: 13, color: p.muted, marginTop: 4 }}>{prop.tagline} · {prop.walkMinTo770} min walk to 770</div>
      </div>
    );
  }
  if (cardStyle === 'bordered') {
    return (
      <div onClick={onClick} style={{ cursor: 'pointer', border: `1px solid ${p.line}`, background: p.card, borderRadius: 6, overflow: 'hidden' }}>
        <Placeholder src={heroSrc} objectPosition={heroPos} label={prop.hero} tone={tones[prop.tier]} density="med" style={{ aspectRatio: '4/3' }}/>
        <div style={{ padding: '20px 20px 22px' }}>
          <div style={{ fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: p.accent, marginBottom: 8 }}>{prop.cardEyebrow || prop.tier}</div>
          <h3 style={{ fontFamily: serif, fontSize: 24, fontWeight: 500, margin: '0 0 6px', letterSpacing: '-0.01em' }}>{prop.name}</h3>
          <div style={{ fontSize: 13, color: p.muted, marginBottom: 14 }}>{prop.tagline}</div>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, color: p.muted, paddingTop: 14, borderTop: `1px solid ${p.line}` }}>
            <span>Sleeps {prop.sleeps}</span>
            {prop.rating && prop.reviews > 0 ? <span>★ {prop.rating}</span> : <span/>}
            <span style={{ color: p.ink }}>${prop.priceFrom}/nt</span>
          </div>
        </div>
      </div>
    );
  }
  // editorial (default)
  return (
    <div onClick={onClick} style={{ cursor: 'pointer' }}>
      <Placeholder src={heroSrc} objectPosition={heroPos} label={prop.hero} tone={tones[prop.tier]} density="med" style={{ aspectRatio: '4/5', marginBottom: 20 }}/>
      <div style={{ fontSize: 10, letterSpacing: '0.2em', textTransform: 'uppercase', color: p.accent, marginBottom: 6 }}>
        {prop.cardEyebrow || `${prop.tier} · ${prop.walkMinTo770} min walk to 770`}
      </div>
      <h3 style={{ fontFamily: serif, fontSize: 28, fontWeight: 500, margin: '0 0 6px', letterSpacing: '-0.02em' }}>{prop.name}</h3>
      <div style={{ fontSize: 14, color: p.muted, marginBottom: 14 }}>{prop.tagline}</div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', fontSize: 13 }}>
        <span style={{ color: p.muted }}>Sleeps {prop.sleeps}</span>
        <span>From <strong>${prop.priceFrom}</strong> <span style={{ color: p.muted, fontSize: 11 }}>/nt</span></span>
      </div>
    </div>
  );
}

window.D1Prototype = D1Prototype;

// ─────── LIST YOUR HOME ─ inquiry form ───────
// Stable helpers for D1ListYourHome (defined outside the component so inputs don't lose focus on re-render).
function LYHField({ label, p, children }) {
  return (
    <label style={{ display: 'block', marginBottom: 20 }}>
      <div style={{ fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase', color: p.muted, marginBottom: 8 }}>{label}</div>
      {children}
    </label>
  );
}
function LYHChip({ active, onClick, p, children }) {
  return (
    <button type="button" onClick={onClick} style={{
      background: active ? p.ink : 'transparent', color: active ? p.bg : p.ink,
      border: `1px solid ${active ? p.ink : p.line}`, padding: '8px 14px', borderRadius: 999,
      fontSize: 12, cursor: 'pointer', fontFamily: 'inherit',
    }}>{children}</button>
  );
}

function D1ListYourHome({ p, serif, sans, go }) {
  const [submitted, setSubmitted] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [f, setF] = React.useState({
    crossStreets: '', bedrooms: '', bathrooms: '', basement: '', fullKitchen: '',
    separateMeatDairy: '', sleeps: '', targetRate: '', arrangement: '',
    name: '', email: '', phone: '', notes: '',
  });
  const set = (k, v) => setF(s => ({ ...s, [k]: v }));
  const inputStyle = { width: '100%', padding: '12px 14px', border: `1px solid ${p.line}`, borderRadius: 8, fontSize: 14, fontFamily: 'inherit', background: p.card, color: p.ink, boxSizing: 'border-box' };

  if (submitted) {
    return (
      <div style={{ maxWidth: 620, margin: '0 auto', padding: '80px 48px', textAlign: 'center' }}>
        <div style={{ fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', color: p.accent, marginBottom: 18 }}>Inquiry received</div>
        <h1 style={{ fontFamily: serif, fontSize: 48, fontWeight: 400, margin: '0 0 16px', letterSpacing: '-0.02em', lineHeight: 1.1 }}>Thank you.</h1>
        <p style={{ fontSize: 16, color: p.muted, lineHeight: 1.7, margin: '0 0 32px' }}>
          I'll review your details and reach out personally within 24 hours to walk through next steps — management, arbitrage, or a simple listing.
        </p>
        <button onClick={() => go('home')} style={{
          background: p.ink, color: p.bg, border: 'none', padding: '12px 22px', borderRadius: 999, fontSize: 13, cursor: 'pointer',
        }}>Back to home</button>
      </div>
    );
  }

  return (
    <div style={{ maxWidth: 720, margin: '0 auto', padding: '48px 48px 80px' }}>
      <div style={{ fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', color: p.accent, marginBottom: 14 }}>List your home</div>
      <h1 style={{ fontFamily: serif, fontSize: 52, fontWeight: 400, margin: '0 0 14px', letterSpacing: '-0.02em', lineHeight: 1.05 }}>Have a home in Crown Heights?</h1>
      <p style={{ fontSize: 16, color: p.muted, lineHeight: 1.7, margin: '0 0 40px', maxWidth: 580 }}>
        Tell us about your place. We'll review and follow up personally to discuss how we can work together.
      </p>

      <div style={{ background: p.card, border: `1px solid ${p.line}`, borderRadius: 10, padding: 32 }}>
        <div style={{ fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', color: p.accent, marginBottom: 20 }}>The property</div>
        <LYHField p={p} label="Cross streets">
          <input value={f.crossStreets} onChange={e => set('crossStreets', e.target.value)} placeholder="e.g. President & Kingston" style={inputStyle}/>
        </LYHField>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 16 }}>
          <LYHField p={p} label="Bedrooms"><input type="number" min="0" value={f.bedrooms} onChange={e => set('bedrooms', e.target.value)} style={inputStyle}/></LYHField>
          <LYHField p={p} label="Bathrooms"><input type="number" step="0.5" min="0" value={f.bathrooms} onChange={e => set('bathrooms', e.target.value)} style={inputStyle}/></LYHField>
          <LYHField p={p} label="Sleeps"><input type="number" min="0" value={f.sleeps} onChange={e => set('sleeps', e.target.value)} style={inputStyle}/></LYHField>
        </div>
        <LYHField p={p} label="Is this a basement apartment?">
          <div style={{ display: 'flex', gap: 8 }}>
            {['Yes', 'No', 'Partial / garden-level'].map(o => <LYHChip p={p} key={o} active={f.basement === o} onClick={() => set('basement', o)}>{o}</LYHChip>)}
          </div>
        </LYHField>
        <LYHField p={p} label="Full kitchen?">
          <div style={{ display: 'flex', gap: 8 }}>
            {['Yes', 'Kitchenette only', 'No'].map(o => <LYHChip p={p} key={o} active={f.fullKitchen === o} onClick={() => set('fullKitchen', o)}>{o}</LYHChip>)}
          </div>
        </LYHField>
        <LYHField p={p} label="Separate meat & dairy setups?">
          <div style={{ display: 'flex', gap: 8 }}>
            {['Yes', 'No', 'Can be set up'].map(o => <LYHChip p={p} key={o} active={f.separateMeatDairy === o} onClick={() => set('separateMeatDairy', o)}>{o}</LYHChip>)}
          </div>
        </LYHField>

        <div style={{ fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', color: p.accent, margin: '32px 0 20px' }}>The arrangement</div>
        <LYHField p={p} label="Target nightly rate">
          <input value={f.targetRate} onChange={e => set('targetRate', e.target.value)} placeholder="e.g. $350 / night" style={inputStyle}/>
        </LYHField>
        <LYHField p={p} label="What are you looking for?">
          <div style={{ display: 'grid', gap: 8 }}>
            {[
              ['manage',   'Full management', 'We handle listing, bookings, guests, cleaning, everything.'],
              ['arbitrage','Rental arbitrage', 'We lease from you at a fixed monthly rate and sublet.'],
              ['listOnly', 'List only', 'You keep management; we just list and send bookings.'],
              ['unsure',   'Not sure yet', 'Happy to walk through options on a call.'],
            ].map(([id, title, sub]) => (
              <button key={id} type="button" onClick={() => set('arrangement', id)} style={{
                textAlign: 'left', padding: '14px 16px', borderRadius: 8, cursor: 'pointer', fontFamily: 'inherit',
                background: f.arrangement === id ? p.bg : 'transparent',
                border: `1px solid ${f.arrangement === id ? p.accent : p.line}`,
                color: p.ink,
              }}>
                <div style={{ fontSize: 14, fontWeight: 500 }}>{title}</div>
                <div style={{ fontSize: 12, color: p.muted, marginTop: 3 }}>{sub}</div>
              </button>
            ))}
          </div>
        </LYHField>

        <div style={{ fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', color: p.accent, margin: '32px 0 20px' }}>Your contact</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
          <LYHField p={p} label="Name"><input value={f.name} onChange={e => set('name', e.target.value)} style={inputStyle}/></LYHField>
          <LYHField p={p} label="Phone"><input type="tel" value={f.phone} onChange={e => set('phone', e.target.value)} style={inputStyle}/></LYHField>
        </div>
        <LYHField p={p} label="Email"><input type="email" value={f.email} onChange={e => set('email', e.target.value)} style={inputStyle}/></LYHField>
        <LYHField p={p} label="Anything else?">
          <textarea value={f.notes} onChange={e => set('notes', e.target.value)} rows={4} placeholder="Photos available, unique features, timing, questions…" style={{ ...inputStyle, resize: 'vertical', lineHeight: 1.5 }}/>
        </LYHField>

        <button disabled={sending} onClick={async () => {
          const arrangementLabels = {
            manage: 'Full management',
            arbitrage: 'Rental arbitrage',
            listOnly: 'List only',
            unsure: 'Not sure yet',
          };
          const payload = {
            _subject: 'Dyra List My Home',
            name: f.name,
            email: f.email,
            phone: f.phone,
            cross_streets: f.crossStreets,
            bedrooms: f.bedrooms,
            bathrooms: f.bathrooms,
            sleeps: f.sleeps,
            basement: f.basement,
            full_kitchen: f.fullKitchen,
            separate_meat_dairy: f.separateMeatDairy,
            target_rate: f.targetRate,
            looking_for: arrangementLabels[f.arrangement] || '',
            notes: f.notes,
          };
          setSending(true); setError(null);
          // Mirror to admin store regardless of formspree result
          if (window.DyraStore && DyraStore.update) {
            try {
              DyraStore.update(s => {
                const id = DyraStore.uid('inq');
                s.inquiries.unshift({
                  id, kind: 'listYourHome', status: 'new',
                  source: 'list-your-home',
                  receivedAt: new Date().toISOString().slice(0, 10),
                  name: f.name, email: f.email, phone: f.phone,
                  bedrooms: Number(f.bedrooms) || null,
                  address: f.crossStreets,
                  kosher: f.separateMeatDairy === 'Yes',
                  notes: [
                    f.notes,
                    f.targetRate && `Target rate: ${f.targetRate}`,
                    f.bathrooms && `${f.bathrooms} bathrooms`,
                    f.sleeps && `Sleeps ${f.sleeps}`,
                    f.basement && `Basement: ${f.basement}`,
                    f.fullKitchen && `Kitchen: ${f.fullKitchen}`,
                    payload.looking_for && `Looking for: ${payload.looking_for}`,
                  ].filter(Boolean).join(' · '),
                });
                s.notifications.unshift({
                  id: DyraStore.uid('ntf'), at: new Date().toISOString(),
                  kind: 'inquiry', read: false,
                  title: `New inquiry · ${f.name || 'unnamed'}`,
                  body: `${f.bedrooms || '?'}BR · ${f.crossStreets || 'address pending'}`,
                  link: { screen: 'inquiries' },
                });
              });
            } catch (e) { /* fine */ }
          }
          try {
            const res = await fetch('https://formspree.io/f/xjgjlowo', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
              body: JSON.stringify(payload),
            });
            if (!res.ok) throw new Error('Network response was not ok');
            setSubmitted(true);
          } catch (err) {
            setError('Something went wrong. Please try again, or WhatsApp / email directly.');
          } finally {
            setSending(false);
          }
        }} style={{
          width: '100%', background: p.accent, color: p.bg, border: 'none', padding: '15px', borderRadius: 8,
          fontSize: 14, cursor: sending ? 'wait' : 'pointer', marginTop: 8, opacity: sending ? 0.7 : 1,
        }}>{sending ? 'Sending…' : 'Send inquiry'}</button>
        {error && (
          <div style={{ fontSize: 12, color: '#c0392b', marginTop: 10, textAlign: 'center' }}>{error}</div>
        )}
        <div style={{ fontSize: 11, color: p.muted, marginTop: 12, textAlign: 'center' }}>
          Or WhatsApp me directly at <a href="https://wa.me/18625207797" target="_blank" rel="noopener noreferrer" style={{ color: p.accent, textDecoration: 'none' }}>862-520-7797</a>
        </div>
      </div>
    </div>
  );
}
window.D1ListYourHome = D1ListYourHome;

// ─────── CONTACT FORM (homepage footer block) ─────────
function D1ContactBlock({ p, serif }) {
  const [name, setName] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [phone, setPhone] = React.useState('');
  const [message, setMessage] = React.useState('');
  const [sent, setSent] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState(null);

  const fieldStyle = {
    width: '100%', boxSizing: 'border-box',
    padding: '11px 14px', border: `1px solid ${p.line}`,
    borderRadius: 8, background: p.bg, color: p.ink,
    fontSize: 14, fontFamily: 'inherit', outline: 'none',
  };
  const submit = async () => {
    if (!name || !email || !message || sending) return;
    setSending(true);
    setError(null);
    try {
      const res = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          guest_name: name,
          guest_email: email,
          guest_phone: phone || null,
          body: message,
        }),
      });
      if (!res.ok) {
        let detail = '';
        try { const j = await res.json(); detail = j && j.error ? ` (${j.error})` : ''; } catch (e) {}
        throw new Error('send-failed' + detail);
      }
      // Best-effort: also reflect to admin in-memory store so it shows up in the demo inbox.
      if (window.DyraStore && DyraStore.update) {
        try {
          DyraStore.update(s => {
            const id = DyraStore.uid('inq');
            s.inquiries.unshift({
              id, kind: 'contact', status: 'new',
              source: 'contact-form',
              receivedAt: new Date().toISOString().slice(0, 10),
              name, email, phone, notes: message,
            });
            s.notifications.unshift({
              id: DyraStore.uid('ntf'), at: new Date().toISOString(),
              kind: 'inquiry', read: false,
              title: `New contact · ${name}`,
              body: message.slice(0, 80),
              link: { screen: 'inquiries' },
            });
          });
        } catch (e) { /* ok */ }
      }
      setSent(true);
    } catch (err) {
      setError("Sorry — that didn't go through. Please try again, or WhatsApp 862-520-7797.");
    } finally {
      setSending(false);
    }
  };

  return (
    <div style={{ padding: '64px 48px', borderTop: `1px solid ${p.line}`, background: p.card }}>
      <div style={{ maxWidth: 760, margin: '0 auto', textAlign: 'center' }}>
        <div style={{ fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', color: p.accent, marginBottom: 12 }}>Send a message</div>
        <div style={{ fontFamily: serif, fontSize: 36, lineHeight: 1.15, marginBottom: 14 }}>Have a question? We'll get back to you.</div>
        <div style={{ fontSize: 14, color: p.muted, marginBottom: 28, lineHeight: 1.6 }}>
          Questions about kashrus standards, pricing, accessibility, or anything else — leave a note and we'll reply within a few hours.
        </div>

        {sent ? (
          <div style={{
            background: p.bg, border: `1px solid ${p.line}`, borderRadius: 12,
            padding: '32px 24px', maxWidth: 480, margin: '0 auto',
          }}>
            <div style={{ fontFamily: serif, fontSize: 22, marginBottom: 8 }}>Thank you — message received.</div>
            <div style={{ fontSize: 13, color: p.muted, lineHeight: 1.6 }}>
              We'll reply to <b style={{ color: p.ink }}>{email}</b> within a few hours. For anything urgent, WhatsApp <a href="https://wa.me/18625207797" target="_blank" rel="noopener noreferrer" style={{ color: p.accent, textDecoration: 'none' }}>862-520-7797</a>.
            </div>
          </div>
        ) : (
          <div style={{ maxWidth: 560, margin: '0 auto', textAlign: 'left' }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 12 }}>
              <input placeholder="Your name" value={name} onChange={e => setName(e.target.value)} style={fieldStyle}/>
              <input placeholder="Email" type="email" value={email} onChange={e => setEmail(e.target.value)} style={fieldStyle}/>
            </div>
            <input placeholder="Phone (optional)" value={phone} onChange={e => setPhone(e.target.value)} style={{ ...fieldStyle, marginBottom: 12 }}/>
            <textarea placeholder="How can we help?" value={message} onChange={e => setMessage(e.target.value)} rows={4} style={{ ...fieldStyle, resize: 'vertical', marginBottom: 14 }}/>
            <div style={{ textAlign: 'center' }}>
              <button onClick={submit} disabled={!name || !email || !message || sending} style={{
                background: p.accent, color: p.bg, border: 'none',
                padding: '13px 32px', borderRadius: 999, fontSize: 13,
                letterSpacing: '0.06em', textTransform: 'uppercase',
                cursor: (!name || !email || !message) ? 'not-allowed' : (sending ? 'wait' : 'pointer'),
                opacity: (!name || !email || !message) ? 0.5 : (sending ? 0.7 : 1),
                fontFamily: 'inherit',
              }}>{sending ? 'Sending…' : 'Send message'}</button>
            </div>
            {error && (
              <div style={{ fontSize: 12, color: '#c0392b', marginTop: 12, textAlign: 'center' }}>{error}</div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}
window.D1ContactBlock = D1ContactBlock;
