// PropertyDetailScreen — gallery, key facts, description, consultant contact panel.
function PropertyDetailScreen({ propertyId, onBack }) {
  const { Button, Badge, IconButton, Avatar } = window.SBLImVeisDesignSystem_08a506;
  const { isMobile } = window.useResponsive();
  const { t, field } = window.useLang();
  const p = window.SBL_DATA.properties.find((x) => x.id === propertyId) || window.SBL_DATA.properties[0];
  const [active, setActive] = React.useState(0);
  const kindLabel = { sale: 'Venda', rent: 'Aluguel', season: 'Temporada' }[p.kind];

  // ── Favorites ──────────────────────────────────────────────────────────────
  function loadFavs() { try { return JSON.parse(localStorage.getItem('sbl_favorites') || '[]'); } catch { return []; } }
  const [fav, setFav] = React.useState(() => loadFavs().includes(p.id));
  const [favToast, setFavToast] = React.useState(null);
  const favTimerRef = React.useRef(null);

  function toggleFav() {
    const favs = loadFavs();
    const isNowFav = !favs.includes(p.id);
    const next = isNowFav ? [...favs, p.id] : favs.filter(id => id !== p.id);
    localStorage.setItem('sbl_favorites', JSON.stringify(next));
    setFav(isNowFav);
    window.dispatchEvent(new CustomEvent('sbl:favorites-changed'));
    clearTimeout(favTimerRef.current);
    setFavToast(isNowFav ? 'added' : 'removed');
    favTimerRef.current = setTimeout(() => setFavToast(null), 3000);
  }

  React.useEffect(() => () => clearTimeout(favTimerRef.current), []);

  function handleShare() {
    const siteUrl = window.location.origin + (window.location.pathname.replace(/\/[^/]*$/, '/') || '/');
    const text = t('Veja esse imóvel incrível que encontrei no site da SBL:') + ' ' + p.title + ' — ' + siteUrl;
    window.open('https://wa.me/?text=' + encodeURIComponent(text), '_blank', 'noopener');
  }
  const gallery = p.gallery || [];
  const thumbRef = React.useRef(null);

  function prev() { setActive(i => (i - 1 + gallery.length) % gallery.length); }
  function next() { setActive(i => (i + 1) % gallery.length); }

  // Scroll active thumbnail into view
  React.useEffect(() => {
    if (!thumbRef.current) return;
    const el = thumbRef.current.children[active];
    if (el) el.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' });
  }, [active]);

  // Keyboard navigation
  React.useEffect(() => {
    function onKey(e) {
      if (e.key === 'ArrowLeft')  prev();
      else if (e.key === 'ArrowRight') next();
    }
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [gallery.length]);

  const facts = [
    { icon: 'bed-double', v: p.beds,         l: t('Quartos') },
    { icon: 'bath',       v: p.baths,        l: t('Banheiros') },
    { icon: 'car',        v: p.parking,      l: t('Vagas') },
    { icon: 'maximize',   v: p.area + ' m²', l: t('Área útil') },
  ];

  const arrowBtn = (onClick, icon, side) => (
    <button
      onClick={onClick}
      style={{
        position: 'absolute', top: '50%', transform: 'translateY(-50%)',
        [side]: 14,
        width: 44, height: 44, borderRadius: '50%',
        background: 'rgba(255,255,255,0.88)', border: 'none',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        cursor: 'pointer', boxShadow: '0 2px 10px rgba(0,0,0,0.18)',
        zIndex: 2, color: 'var(--brown-800)',
        transition: 'background 0.15s',
      }}
      onMouseEnter={e => e.currentTarget.style.background = '#fff'}
      onMouseLeave={e => e.currentTarget.style.background = 'rgba(255,255,255,0.88)'}
    >
      <i data-lucide={icon} style={{ width: 20, height: 20 }}></i>
    </button>
  );

  return (
    <div style={{ maxWidth: 1280, margin: '0 auto', padding: isMobile ? '20px 16px 60px' : '28px 40px 80px' }}>
      <button onClick={onBack} style={{ display: 'inline-flex', alignItems: 'center', gap: 8, background: 'none', border: 'none', cursor: 'pointer', color: 'var(--warmgray-600)', fontFamily: 'var(--font-body)', fontSize: 13.5, marginBottom: 22, padding: 0 }}>
        <i data-lucide="arrow-left" style={{ width: 17, height: 17 }}></i> {t('Voltar aos imóveis')}
      </button>

      {/* Gallery */}
      <div style={{ marginBottom: 14 }}>
        {/* Main photo */}
        <div style={{ position: 'relative', borderRadius: 'var(--radius-lg)', overflow: 'hidden', aspectRatio: isMobile ? '4/3' : '16/7', boxShadow: 'var(--shadow-md)', marginBottom: 10 }}>
          <img
            key={active}
            src={gallery[active]}
            alt={p.title}
            style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}
          />

          {/* Badges */}
          <div style={{ position: 'absolute', top: 16, left: 16, display: 'flex', gap: 8 }}>
            <Badge tone={p.kind} solid>{t(kindLabel)}</Badge>
            {p.featured && <Badge tone="accent" solid icon="sparkles">{t('Destaque')}</Badge>}
          </div>

          {/* Fav / share */}
          <div style={{ position: 'absolute', top: 14, right: 14, display: 'flex', gap: 8 }}>
            <IconButton icon="heart" active={fav} label={fav ? t('Remover dos favoritos') : t('Salvar nos favoritos')} onClick={toggleFav} />
            <IconButton icon="share-2" label={t('Compartilhar')} onClick={handleShare} />
          </div>

          {/* Counter */}
          {gallery.length > 1 && (
            <div style={{ position: 'absolute', bottom: 14, right: 14, background: 'rgba(30,20,12,0.55)', color: '#fff', fontFamily: 'var(--font-body)', fontSize: 12, fontWeight: 600, padding: '4px 10px', borderRadius: 99, backdropFilter: 'blur(4px)' }}>
              {active + 1} / {gallery.length}
            </div>
          )}

          {/* Arrows */}
          {gallery.length > 1 && arrowBtn(prev, 'chevron-left', 'left')}
          {gallery.length > 1 && arrowBtn(next, 'chevron-right', 'right')}
        </div>

        {/* Thumbnail strip */}
        {gallery.length > 1 && (
          <div
            ref={thumbRef}
            style={{ display: 'flex', gap: 8, overflowX: 'auto', paddingBottom: 4, WebkitOverflowScrolling: 'touch', scrollbarWidth: 'none' }}
          >
            {gallery.map((g, i) => (
              <div
                key={i}
                onClick={() => setActive(i)}
                style={{
                  flexShrink: 0,
                  width: isMobile ? 68 : 88,
                  height: isMobile ? 50 : 64,
                  borderRadius: 8,
                  overflow: 'hidden',
                  cursor: 'pointer',
                  border: active === i ? '2.5px solid var(--brown-500)' : '2.5px solid transparent',
                  opacity: active === i ? 1 : 0.6,
                  transition: 'opacity 0.15s, border-color 0.15s',
                  boxShadow: active === i ? '0 0 0 1px var(--brown-300)' : 'none',
                }}
              >
                <img src={g} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Body */}
      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1.7fr 1fr', gap: 44, marginTop: 36 }}>
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
            <i data-lucide="map-pin" style={{ width: 16, height: 16, color: 'var(--rose-600)' }}></i>
            <span style={{ fontFamily: 'var(--font-body)', fontSize: 14, color: 'var(--warmgray-600)' }}>{p.location}</span>
          </div>
          <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: isMobile ? 26 : 38, color: 'var(--text-strong)', margin: '0 0 28px', lineHeight: 1.12 }}>{field(p, 'title')}</h1>

          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 36 }}>
            {facts.map((f) => (
              <div key={f.l} style={{ background: 'var(--surface-card)', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-md)', padding: '18px 16px', textAlign: 'center' }}>
                <span style={{ color: 'var(--brown-400)', display: 'inline-flex', marginBottom: 8 }}><i data-lucide={f.icon} style={{ width: 24, height: 24 }}></i></span>
                <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 22, color: 'var(--brown-700)' }}>{f.v}</div>
                <div style={{ fontFamily: 'var(--font-logo)', fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--text-muted)', marginTop: 2 }}>{f.l}</div>
              </div>
            ))}
          </div>

          <div className="sbl-divider" style={{ marginBottom: 24 }}><span className="sbl-divider__mark">✦</span></div>
          <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 24, color: 'var(--text-strong)', margin: '0 0 14px' }}>{t('Sobre o imóvel')}</h2>
          <p style={{ fontFamily: 'var(--font-body)', fontSize: 15.5, color: 'var(--text-body)', lineHeight: 1.75, margin: '0 0 30px' }}>{field(p, 'desc')}</p>

          {p.amenities && p.amenities.length > 0 && (
            <>
              <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 24, color: 'var(--text-strong)', margin: '0 0 16px' }}>{t('Diferenciais')}</h2>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                {p.amenities.map((a) => (
                  <div key={a} style={{ display: 'flex', alignItems: 'center', gap: 10, color: 'var(--text-body)' }}>
                    <span style={{ color: 'var(--green-600)' }}><i data-lucide="check" style={{ width: 18, height: 18 }}></i></span>
                    <span style={{ fontFamily: 'var(--font-body)', fontSize: 14.5 }}>{a}</span>
                  </div>
                ))}
              </div>
            </>
          )}
        </div>

        {/* Contact panel */}
        <aside>
          <div style={{ position: isMobile ? 'static' : 'sticky', top: 104, background: 'var(--surface-card)', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-lg)', padding: 28, boxShadow: 'var(--shadow-md)' }}>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 4 }}>
              <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 32, color: 'var(--brown-700)' }}>{p.price}</span>
              <span style={{ fontFamily: 'var(--font-body)', fontSize: 14, color: 'var(--text-muted)' }}>{p.priceSuffix}</span>
            </div>
            <div style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--text-muted)', marginBottom: 22 }}>{t('Cód.')} {p.code ? p.code.toUpperCase() : 'SBL-' + p.id.toUpperCase()}</div>

            <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 0', borderTop: '1px solid var(--border-subtle)', borderBottom: '1px solid var(--border-subtle)', marginBottom: 20 }}>
              <Avatar name="Sibelle Bernardes" src="../../assets/team_rosto.jpg" size="md" ring />
              <div>
                <div style={{ fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 14, color: 'var(--text-strong)' }}>Sibelle Bernardes</div>
                <div style={{ fontFamily: 'var(--font-body)', fontSize: 12.5, color: 'var(--text-muted)' }}>{t('Consultora · CRECI 16696')}</div>
              </div>
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              <a href="https://wa.me/558399585248?text=Ol%C3%A1%2C%20vim%20pelo%20site%20da%20SBL%20e%20gostaria%20de%20mais%20informa%C3%A7%C3%B5es." target="_blank" rel="noopener noreferrer" style={{ textDecoration: 'none' }}>
                <Button variant="accent" size="lg" full iconLeft="message-circle">{t('Falar no WhatsApp')}</Button>
              </a>
              <Button variant="outline" size="lg" full iconLeft="calendar">{t('Agendar visita')}</Button>
            </div>
          </div>
        </aside>
      </div>
      {/* Favorites toast */}
      {favToast && (
        <div style={{
          position: 'fixed', bottom: 28, left: '50%', transform: 'translateX(-50%)',
          background: favToast === 'added' ? 'var(--brown-800)' : 'var(--warmgray-600)',
          color: '#fff', borderRadius: 'var(--radius-pill)',
          padding: '12px 20px', display: 'flex', alignItems: 'center', gap: 14,
          fontFamily: 'var(--font-body)', fontSize: 14, fontWeight: 500,
          boxShadow: '0 6px 28px rgba(0,0,0,0.22)', zIndex: 9000, whiteSpace: 'nowrap',
        }}>
          <span>{favToast === 'added' ? t('♥ Salvo nos favoritos') : t('♡ Removido dos favoritos')}</span>
          {favToast === 'added' && (
            <button onClick={() => { setFavToast(null); onBack(); }} style={{
              background: 'rgba(255,255,255,0.2)', border: 'none', borderRadius: 'var(--radius-pill)',
              color: '#fff', fontFamily: 'var(--font-body)', fontSize: 13, fontWeight: 600,
              padding: '5px 14px', cursor: 'pointer',
            }}>
              {t('Ver favoritos')}
            </button>
          )}
        </div>
      )}
    </div>
  );
}
window.PropertyDetailScreen = PropertyDetailScreen;
