// ── Custom SearchBar ──────────────────────────────────────────────────────────
// Full custom dropdown (no native <select>) so the option list inherits the
// site's fonts, colours and spacing instead of the browser's default styling.

const _SB_BAIRROS = [
  { value: '', label: 'Todos os bairros' },
  { value: 'Cabo Branco',    label: 'Cabo Branco' },
  { value: 'Tambaú',         label: 'Tambaú' },
  { value: 'Manaíra',        label: 'Manaíra' },
  { value: 'Bessa',          label: 'Bessa' },
  { value: 'Altiplano',      label: 'Altiplano' },
  { value: 'Jardim Oceania', label: 'Jardim Oceania' },
];
const _SB_TIPOS = [
  { value: '', label: 'Qualquer' },
  { value: 'Apartamento', label: 'Apartamento' },
  { value: 'Casa',        label: 'Casa' },
  { value: 'Cobertura',   label: 'Cobertura' },
  { value: 'Flat',        label: 'Flat' },
  { value: 'Terreno',     label: 'Terreno' },
];

function _SBField({ label, icon, value, onChange, options, placeholder, required, hasError }) {
  const Icon = window.SBLImVeisDesignSystem_08a506.Icon;
  const { t } = window.useLang();
  const [open, setOpen] = React.useState(false);
  const wrapRef = React.useRef(null);

  const found   = options.find(o => o.value === value);
  const display = found ? found.label : placeholder;

  // Close on outside click
  React.useEffect(() => {
    if (!open) return;
    function handler(e) { if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false); }
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [open]);

  // Close on Escape
  React.useEffect(() => {
    if (!open) return;
    function handler(e) { if (e.key === 'Escape') setOpen(false); }
    document.addEventListener('keydown', handler);
    return () => document.removeEventListener('keydown', handler);
  }, [open]);

  const borderColor = hasError && !open
    ? 'var(--rose-500)'
    : open ? 'var(--rose-500)' : 'var(--border-default)';
  const boxShadow = hasError && !open
    ? '0 0 0 3px rgba(220,38,38,0.10)'
    : open ? '0 0 0 4px var(--focus-ring)' : 'var(--shadow-xs)';

  return (
    <div ref={wrapRef} style={{ display: 'flex', flexDirection: 'column', gap: 7, position: 'relative' }}>
      <span style={{ fontFamily: 'var(--font-body)', fontSize: 12.5, fontWeight: 600, letterSpacing: '0.04em', color: hasError && !open ? 'var(--rose-600)' : 'var(--text-strong)' }}>
        {t(label)}{required ? <span style={{ color: 'var(--rose-600)' }}> *</span> : null}
      </span>

      {/* Trigger button */}
      <button
        type="button"
        onClick={() => setOpen(o => !o)}
        style={{ display: 'flex', alignItems: 'center', gap: 10, background: 'var(--surface-card)', border: '1px solid ' + borderColor, borderRadius: open ? 'var(--radius-md) var(--radius-md) 0 0' : 'var(--radius-md)', padding: '0 14px 0 16px', height: 50, boxShadow, cursor: 'pointer', width: '100%', textAlign: 'left', transition: 'border-color 0.15s, box-shadow 0.15s' }}
      >
        <Icon name={icon} size={18} color="var(--warmgray-500)" />
        <span style={{ flex: 1, fontFamily: 'var(--font-body)', fontSize: 14.5, color: value ? 'var(--text-strong)' : 'var(--text-muted)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {t(display)}
        </span>
        <span style={{ display: 'flex', transition: 'transform 0.2s', transform: open ? 'rotate(180deg)' : 'none' }}>
          <Icon name="chevron-down" size={18} color="var(--brown-400)" />
        </span>
      </button>

      {/* Custom option list */}
      {open && (
        <div style={{ position: 'absolute', top: '100%', left: 0, right: 0, background: 'var(--surface-card)', border: '1px solid var(--rose-400)', borderTop: 'none', borderRadius: '0 0 var(--radius-md) var(--radius-md)', boxShadow: '0 8px 24px rgba(0,0,0,0.12)', zIndex: 500, overflow: 'hidden' }}>
          {options.map((o, i) => {
            const selected = o.value === value;
            return (
              <button key={o.value} type="button"
                onClick={() => { onChange(o.value); setOpen(false); }}
                style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%', padding: '11px 16px', textAlign: 'left', fontFamily: 'var(--font-body)', fontSize: 14, color: selected ? 'var(--brown-700)' : o.value === '' ? 'var(--text-muted)' : 'var(--text-body)', fontWeight: selected ? 600 : 400, background: selected ? 'var(--rose-50)' : 'transparent', border: 'none', borderTop: i > 0 ? '1px solid var(--border-subtle)' : 'none', cursor: 'pointer', transition: 'background 0.1s' }}
                onMouseEnter={e => { if (!selected) e.currentTarget.style.background = 'var(--cream-100)'; }}
                onMouseLeave={e => { if (!selected) e.currentTarget.style.background = 'transparent'; }}
              >
                <span>{t(o.label)}</span>
                {selected && <Icon name="check" size={15} color="var(--brown-600)" />}
              </button>
            );
          })}
        </div>
      )}

      {/* Error callout (only when closed) */}
      {hasError && !open && (
        <span style={{ position: 'absolute', top: '100%', left: 0, marginTop: 6, background: 'var(--rose-600)', color: '#fff', borderRadius: 6, padding: '4px 10px', fontFamily: 'var(--font-body)', fontSize: 12, fontWeight: 500, whiteSpace: 'nowrap', zIndex: 20, pointerEvents: 'none' }}>
          {t('Selecione a finalidade para buscar')}
        </span>
      )}
    </div>
  );
}

function SiteSearchBar({ onSearch, style }) {
  const Icon = window.SBLImVeisDesignSystem_08a506.Icon;
  const { t } = window.useLang();
  const [purpose, setPurpose] = React.useState('');
  const [city,    setCity]    = React.useState('');
  const [type,    setType]    = React.useState('');
  const [error,   setError]   = React.useState(false);

  function handleSearch() {
    if (!purpose) { setError(true); return; }
    setError(false);
    onSearch && onSearch({ purpose, city, type });
  }

  return (
    <div style={{ background: 'var(--surface-card)', borderRadius: 'var(--radius-xl)', boxShadow: 'var(--shadow-lg)', border: '1px solid var(--border-subtle)', padding: 14, display: 'grid', gridTemplateColumns: '1fr 1fr 1fr auto', gap: 12, alignItems: 'end', ...style }}>
      <_SBField label="Finalidade" icon="key" required
        value={purpose} onChange={v => { setPurpose(v); if (v) setError(false); }}
        options={[{value:'',label:'Selecione'},{value:'comprar',label:'Comprar'},{value:'temporada',label:'Temporada'},{value:'alugar',label:'Alugar'}]}
        placeholder="Selecione" hasError={error}
      />
      <_SBField label="Bairro" icon="map-pin"
        value={city} onChange={setCity}
        options={_SB_BAIRROS} placeholder="Todos os bairros"
      />
      <_SBField label="Tipo" icon="home"
        value={type} onChange={setType}
        options={_SB_TIPOS} placeholder="Qualquer"
      />
      <button type="button" onClick={handleSearch}
        style={{ height: 50, padding: '0 24px', background: 'var(--color-primary)', color: 'var(--cream-50)', border: 'none', borderRadius: 'var(--radius-md)', fontFamily: 'var(--font-logo)', fontSize: 13, fontWeight: 700, letterSpacing: '0.08em', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, whiteSpace: 'nowrap' }}>
        <Icon name="search" size={18} color="currentColor" />
        {t('Buscar')}
      </button>
    </div>
  );
}

// HomeScreen — SBL homepage: hero + search, featured listings, trust, owner CTA, testimonial.
function HomeScreen({ onNav, onOpenProperty, onAnnounce }) {
  const { Button, PropertyCard, Stat, Badge, Avatar } = window.SBLImVeisDesignSystem_08a506;
  const { isMobile, isTablet } = window.useResponsive();
  const { t } = window.useLang();
  const props = window.SBL_DATA.properties;
  const featured = props.filter((p) => p.featured || p.kind === 'season').slice(0, 3);

  return (
    <div>
      {/* HERO */}
      <section style={{ position: 'relative', minHeight: 640, display: 'flex', alignItems: 'center', overflow: 'hidden' }}>
        <img src="https://images.unsplash.com/photo-1512917774080-9991f1c4c750?w=1700&q=80" alt=""
          style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />
        <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(100deg, rgba(30,20,12,0.78) 0%, rgba(46,27,16,0.55) 45%, rgba(46,27,16,0.18) 100%)' }}></div>
        <div style={{ position: 'relative', maxWidth: 1280, margin: '0 auto', padding: isMobile ? '64px 20px' : '96px 40px', width: '100%' }}>
          <div style={{ maxWidth: 660, paddingTop: 0, paddingBottom: 30 }} className="sbl-rise">
            <div className="sbl-eyebrow" style={{ color: 'var(--rose-300)', marginBottom: 20 }}>SBL · Imóveis e Locações · João Pessoa</div>
            <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: isMobile ? 36 : 60, lineHeight: 1.04, color: 'var(--cream-50)', margin: '0 0 22px', letterSpacing: '-0.01em', textAlign: isMobile ? 'center' : 'left' }}>
              {t('O seu próximo endereço')}<br />{t('à beira-mar')}
            </h1>
            <p style={{ fontFamily: 'var(--font-editorial)', fontSize: isMobile ? 16 : 23, fontStyle: 'italic', color: 'var(--rose-100)', lineHeight: 1.45, margin: '0 0 34px', maxWidth: 540 }}>
              {t('Imóveis selecionados para morar, investir e passar temporada — com a confiança e o cuidado que você merece.')}
            </p>
          </div>
          <SiteSearchBar
            style={isMobile ? {
              width: 'calc(100% / 0.72)',
              transform: 'scale(0.72)',
              transformOrigin: 'left top',
              marginBottom: -28,
            } : { maxWidth: 920 }}
            onSearch={(state) => {
              const kindMap = { comprar: 'sale', temporada: 'season', alugar: 'rent' };
              const filters = {};
              if (state.purpose) filters.kind = kindMap[state.purpose];
              if (state.city)    filters.neighborhood = state.city;
              if (state.type)    filters.propertyType = state.type;
              onNav('listings', filters);
            }}
          />
          <div style={{ display: 'flex', flexWrap: 'nowrap', gap: isMobile ? 16 : 44, marginTop: 34, justifyContent: isMobile ? 'space-between' : 'flex-start', width: '100%' }}>
            <Stat value="+500" label={isMobile ? t("Imóveis") : t("Imóveis no portfólio")} align="left" onDark />
            <Stat value="12" label={isMobile ? t("Anos em JP") : t("Anos em João Pessoa")} align="left" onDark />
            <Stat value="98%" label={isMobile ? t("Satisfeitos") : t("Clientes satisfeitos")} align="left" onDark />
          </div>
        </div>
      </section>

      {/* FEATURED */}
      <section style={{ maxWidth: 1280, margin: '0 auto', padding: isMobile ? '64px 20px 20px' : '88px 40px 20px' }}>
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 36, flexDirection: isMobile ? 'column' : 'row', gap: isMobile ? 16 : 0 }}>
          <div style={{ textAlign: isMobile ? 'center' : 'left' }}>
            <div className="sbl-eyebrow" style={{ marginBottom: 12 }}>{t('Seleção SBL')}</div>
            <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: isMobile ? 30 : 40, color: 'var(--text-strong)', margin: 0 }}>{t('Imóveis em destaque')}</h2>
          </div>
          <Button variant="outline" iconRight="arrow-right" onClick={() => onNav('listings')}>{t('Ver todos')}</Button>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : isTablet ? 'repeat(2, 1fr)' : 'repeat(3, 1fr)', gap: 26 }}>
          {featured.map((p) => (
            <PropertyCard key={p.id} {...p} onClick={() => onOpenProperty(p.id)} />
          ))}
        </div>
      </section>

      {/* WHY SBL */}
      <section style={{ maxWidth: 1280, margin: '0 auto', padding: isMobile ? '64px 20px' : '88px 40px' }}>
        <div style={{ textAlign: 'center', maxWidth: 640, margin: '0 auto 52px' }}>
          <div className="sbl-divider" style={{ maxWidth: 240, margin: '0 auto 20px' }}><span className="sbl-divider__mark">✦</span></div>
          <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 40, color: 'var(--text-strong)', margin: '0 0 14px' }}>{t('Por que escolher a SBL')}</h2>
          <p style={{ fontFamily: 'var(--font-body)', fontSize: 16, color: 'var(--text-body)', margin: 0 }}>{t('Cuidamos de cada detalhe para que comprar, alugar ou anunciar seja simples, seguro e elegante.')}</p>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : isTablet ? 'repeat(2, 1fr)' : 'repeat(3, 1fr)', gap: 26 }}>
          {[
            { icon: 'shield-check', t: 'Segurança jurídica', d: 'Documentação verificada e contratos transparentes em cada negociação.' },
            { icon: 'gem', t: 'Curadoria exclusiva', d: 'Imóveis selecionados a dedo nos melhores bairros de João Pessoa.' },
            { icon: 'hand-heart', t: 'Atendimento próximo', d: 'Um consultor dedicado do primeiro contato à entrega das chaves.' },
          ].map((f) => (
            <div key={f.t} style={{ background: 'var(--surface-card)', borderRadius: 'var(--radius-lg)', padding: '34px 30px', border: '1px solid var(--border-subtle)', boxShadow: 'var(--shadow-sm)' }}>
              <span style={{ width: 56, height: 56, borderRadius: 'var(--radius-md)', background: 'var(--rose-100)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', color: 'var(--rose-700)', marginBottom: 20 }}>
                <i data-lucide={f.icon} style={{ width: 26, height: 26 }}></i>
              </span>
              <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 22, color: 'var(--text-strong)', margin: '0 0 10px' }}>{t(f.t)}</h3>
              <p style={{ fontFamily: 'var(--font-body)', fontSize: 14.5, color: 'var(--text-body)', lineHeight: 1.6, margin: 0 }}>{t(f.d)}</p>
            </div>
          ))}
        </div>
      </section>

      {/* OWNER CTA */}
      <section style={{ background: 'var(--brown-700)', position: 'relative', overflow: 'hidden' }}>
        <div style={{ maxWidth: 1280, margin: '0 auto', padding: isMobile ? '60px 20px' : '76px 40px', display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1.2fr 0.8fr', gap: 50, alignItems: 'center' }}>
          <div style={{ textAlign: isMobile ? 'center' : 'left' }}>
            <div className="sbl-eyebrow" style={{ color: 'var(--rose-300)', marginBottom: 16 }}>{t('Proprietários')}</div>
            <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: isMobile ? 30 : 42, color: 'var(--cream-50)', margin: '0 0 16px', lineHeight: 1.1, textAlign: isMobile ? 'justify' : 'left' }}>
              {t('Tem um imóvel para temporada? Nós cuidamos de tudo.')}
            </h2>
            <p style={{ fontFamily: 'var(--font-body)', fontSize: 16, color: 'var(--brown-100)', lineHeight: 1.65, margin: '0 0 30px', maxWidth: 520, textAlign: isMobile ? 'justify' : 'left' }}>
              {t('Anuncie com a SBL e tenha divulgação profissional, hóspedes verificados e gestão completa da sua locação por temporada em João Pessoa.')}
            </p>
            <div style={{ display: 'flex', flexDirection: isMobile ? 'column' : 'row', gap: 12 }}>
              <Button variant="accent" size={isMobile ? 'md' : 'lg'} iconLeft="plus" onClick={onAnnounce} full={isMobile}>{t('Anunciar meu imóvel')}</Button>
              <Button variant="ghost" size={isMobile ? 'md' : 'lg'} style={{ color: 'var(--rose-100)', borderColor: 'var(--brown-500)' }} onClick={() => onNav('howitworks')} full={isMobile}>{t('Como funciona')}</Button>
            </div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            {[['percent', 'Sem taxas escondidas'], ['camera', 'Fotos e tour profissionais'], ['calendar-check', 'Gestão de reservas e calendário']].map(([ic, label]) => (
              <div key={label} style={{ display: 'flex', alignItems: 'center', gap: 14, background: 'color-mix(in srgb, var(--brown-900) 40%, transparent)', borderRadius: 'var(--radius-md)', padding: '16px 20px', border: '1px solid var(--brown-600)' }}>
                <span style={{ color: 'var(--rose-300)' }}><i data-lucide={ic} style={{ width: 22, height: 22 }}></i></span>
                <span style={{ fontFamily: 'var(--font-body)', fontSize: 14.5, fontWeight: 500, color: 'var(--cream-50)' }}>{t(label)}</span>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* TESTIMONIAL */}
      <section style={{ maxWidth: 900, margin: '0 auto', padding: isMobile ? '60px 20px' : '90px 40px', textAlign: 'center' }}>
        <div style={{ color: 'var(--rose-400)', marginBottom: 18 }}><i data-lucide="quote" style={{ width: 40, height: 40 }}></i></div>
        <p style={{ fontFamily: 'var(--font-editorial)', fontSize: 30, fontStyle: 'italic', color: 'var(--brown-700)', lineHeight: 1.4, margin: '0 0 28px' }}>
          {t('“A SBL encontrou exatamente o apartamento que sonhávamos em Cabo Branco. Atendimento impecável, do início ao fim.”')}
        </p>
        <Avatar src="../../assets/team_rosto.jpg" name="Marina Albuquerque" role={t('Compradora · Cabo Branco')} showName style={{ justifyContent: 'center' }} />
      </section>
    </div>
  );
}
window.HomeScreen = HomeScreen;
