// ListingsScreen — search results: filter rail + property grid.

const _filterSelectStyle = {
  padding: '0 32px 0 12px',
  height: 44,
  border: '1px solid var(--border-default)',
  borderRadius: 'var(--radius-md)',
  background: 'var(--surface-card)',
  fontFamily: 'var(--font-body)',
  fontSize: 13.5,
  color: 'var(--text-strong)',
  outline: 'none',
  cursor: 'pointer',
  appearance: 'none',
  WebkitAppearance: 'none',
  width: '100%',
  backgroundImage: "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%236b7280' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E\")",
  backgroundRepeat: 'no-repeat',
  backgroundPosition: 'right 10px center',
};

const _labelStyle = {
  fontFamily: 'var(--font-body)',
  fontSize: 11,
  fontWeight: 600,
  letterSpacing: '0.08em',
  textTransform: 'uppercase',
  color: 'var(--text-muted)',
  marginBottom: 6,
  display: 'block',
};

const BAIRROS = ['Cabo Branco', 'Tambaú', 'Manaíra', 'Bessa', 'Altiplano', 'Jardim Oceania'];
const TIPOS   = ['Apartamento', 'Casa', 'Cobertura', 'Flat', 'Terreno'];

function FilterSelect({ label, value, onChange, options, placeholder }) {
  const { t } = window.useLang();
  return (
    <div>
      <span style={_labelStyle}>{t(label)}</span>
      <select value={value} onChange={e => onChange(e.target.value)} style={_filterSelectStyle}>
        <option value="">{t(placeholder)}</option>
        {options.map(o => typeof o === 'string'
          ? <option key={o} value={o}>{t(o)}</option>
          : <option key={o.value} value={o.value}>{t(o.label)}</option>
        )}
      </select>
    </div>
  );
}

function _XIcon() {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24"
      fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
      <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
    </svg>
  );
}

function parseRawPrice(s) {
  if (!s) return 0;
  return parseFloat(s.replace(/[^0-9]/g, '')) || 0;
}

function ListingsScreen({ onOpenProperty, initialKind, initialNeighborhood, initialFeatured, initialPropertyType, initialLaunch, initialLuxury }) {
  const { PropertyCard, Button } = window.SBLImVeisDesignSystem_08a506;
  const { isMobile, isTablet } = window.useResponsive();
  const { t } = window.useLang();
  const all = window.SBL_DATA.properties;
  const featured = !!initialFeatured;
  const launch   = !!initialLaunch;
  const luxury   = !!initialLuxury;

  const [kind,         setKind]         = React.useState(initialKind || 'all');
  const [neighborhood, setNeighborhood] = React.useState(initialNeighborhood || '');
  const [propertyType, setPropertyType] = React.useState(initialPropertyType || '');
  const [minBeds,      setMinBeds]      = React.useState('');
  const [priceRange,   setPriceRange]   = React.useState('');
  const [sortBy,       setSortBy]       = React.useState('');
  const [showFilters,  setShowFilters]  = React.useState(false);
  const [showFavs,     setShowFavs]     = React.useState(false);
  const [favIds,       setFavIds]       = React.useState(() => {
    try { return JSON.parse(localStorage.getItem('sbl_favorites') || '[]'); } catch { return []; }
  });

  React.useEffect(() => {
    function sync() {
      try { setFavIds(JSON.parse(localStorage.getItem('sbl_favorites') || '[]')); } catch {}
    }
    window.addEventListener('sbl:favorites-changed', sync);
    return () => window.removeEventListener('sbl:favorites-changed', sync);
  }, []);

  const thirtyDaysAgo = React.useMemo(() => new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString(), []);

  const filtered = React.useMemo(() => {
    return all.filter(p => {
      if (showFavs && !favIds.includes(p.id)) return false;
      if (launch && (!p.createdAt || p.createdAt < thirtyDaysAgo)) return false;
      if (luxury && !p.featured && parseRawPrice(p.price) < 1000000) return false;
      if (kind !== 'all' && p.kind !== kind) return false;
      if (featured && !p.featured) return false;
      if (neighborhood) {
        const loc = ((p.location || '') + ' ' + (p.neighborhood || '')).toLowerCase();
        if (!loc.includes(neighborhood.toLowerCase())) return false;
      }
      if (propertyType) {
        const typeStr = ((p.type || '') + ' ' + (p.title || '')).toLowerCase();
        if (!typeStr.includes(propertyType.toLowerCase())) return false;
      }
      if (minBeds && (p.beds || 0) < parseInt(minBeds)) return false;
      if (priceRange && (p.kind === 'sale' || kind === 'sale')) {
        const num = parseRawPrice(p.price);
        if (priceRange === 'ate500k'  && num > 500000) return false;
        if (priceRange === '500k1m'   && (num <= 500000 || num > 1000000)) return false;
        if (priceRange === 'acima1m'  && num <= 1000000) return false;
      }
      return true;
    });
  }, [all, kind, featured, launch, luxury, neighborhood, propertyType, minBeds, priceRange, showFavs, favIds, thirtyDaysAgo]);

  const list = React.useMemo(() => {
    return [...filtered].sort((a, b) => {
      if (sortBy === 'price-asc')  return parseRawPrice(a.price) - parseRawPrice(b.price);
      if (sortBy === 'price-desc') return parseRawPrice(b.price) - parseRawPrice(a.price);
      return 0;
    });
  }, [filtered, sortBy]);

  const activeCount = [neighborhood, propertyType, minBeds, priceRange, showFavs ? 'fav' : ''].filter(Boolean).length;

  function clearAllFilters() {
    setNeighborhood(''); setPropertyType(''); setMinBeds(''); setPriceRange(''); setShowFavs(false);
  }

  const pageTitle = (() => {
    if (launch)        return t('Lançamentos em João Pessoa');
    if (luxury)        return t('Imóveis de Luxo em João Pessoa');
    if (neighborhood)  return t('Imóveis em {bairro}', { bairro: neighborhood });
    if (featured)      return t('Imóveis de Luxo em João Pessoa');
    if (kind === 'sale')   return t('Imóveis à Venda em João Pessoa');
    if (kind === 'season') return t('Temporada em João Pessoa');
    if (kind === 'rent')   return t('Aluguel em João Pessoa');
    return t('Imóveis em João Pessoa');
  })();

  const Chip = ({ id, label }) => {
    const active = kind === id && !neighborhood && !featured && !propertyType && !showFavs && !launch && !luxury;
    return (
      <button onClick={() => setKind(id)} style={{
        fontFamily: 'var(--font-body)', fontSize: isMobile ? 12.5 : 13.5, fontWeight: 500,
        padding: isMobile ? '8px 12px' : '9px 18px', borderRadius: 'var(--radius-pill)', cursor: 'pointer',
        border: '1px solid ' + (active ? 'var(--brown-500)' : 'var(--border-default)'),
        background: active ? 'var(--brown-500)' : 'var(--surface-card)',
        color: active ? 'var(--cream-50)' : 'var(--warmgray-600)',
        transition: 'all var(--dur-base) var(--ease-out)', flexShrink: 0,
      }}>{label}</button>
    );
  };

  const tagSty = {
    display: 'inline-flex', alignItems: 'center', gap: 6,
    padding: isMobile ? '8px 12px' : '9px 16px', borderRadius: 'var(--radius-pill)',
    background: 'var(--brown-500)', color: 'var(--cream-50)',
    fontFamily: 'var(--font-body)', fontSize: isMobile ? 12.5 : 13.5, fontWeight: 600,
    border: 'none', cursor: 'pointer', flexShrink: 0,
  };

  const priceLabel = { ate500k: 'Até R$ 500k', '500k1m': 'R$ 500k–1mi', acima1m: 'Acima R$ 1mi' };

  return (
    <div style={{ background: 'var(--color-bg)' }}>
      {/* Page head */}
      <div style={{ background: 'var(--surface-card)', borderBottom: '1px solid var(--border-subtle)' }}>
        <div style={{ maxWidth: 1280, margin: '0 auto', padding: isMobile ? '30px 20px 24px' : '40px 40px 30px' }}>
          <div className="sbl-eyebrow" style={{ marginBottom: 12 }}>{t('Portfólio')}</div>
          <h1 style={{
            fontFamily: 'var(--font-display)', fontWeight: 700,
            fontSize: isMobile ? 28 : 38, color: 'var(--text-strong)', margin: '0 0 24px',
          }}>{pageTitle}</h1>

          {/* Desktop filters */}
          {!isMobile && (
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr 1fr auto', gap: 12, alignItems: 'end' }}>
              <FilterSelect label="Bairro" placeholder="Todos os bairros"
                value={neighborhood} onChange={setNeighborhood} options={BAIRROS} />
              <FilterSelect label="Tipo de imóvel" placeholder="Todos os tipos"
                value={propertyType} onChange={setPropertyType} options={TIPOS} />
              <FilterSelect label="Quartos" placeholder="Qualquer"
                value={minBeds} onChange={setMinBeds}
                options={[{value:'1',label:'1+ quarto'},{value:'2',label:'2+ quartos'},{value:'3',label:'3+ quartos'},{value:'4',label:'4+ quartos'}]} />
              <FilterSelect label="Faixa de preço" placeholder="Qualquer"
                value={priceRange} onChange={setPriceRange}
                options={[{value:'ate500k',label:'Até R$ 500 mil'},{value:'500k1m',label:'R$ 500 mil – 1 mi'},{value:'acima1m',label:'Acima de R$ 1 mi'}]} />
              <FilterSelect label="Ordenar por" placeholder="Mais recentes"
                value={sortBy} onChange={setSortBy}
                options={[{value:'price-asc',label:'Menor preço'},{value:'price-desc',label:'Maior preço'}]} />
              {activeCount > 0 ? (
                <button onClick={clearAllFilters} style={{
                  height: 44, padding: '0 16px', border: '1px solid var(--border-default)',
                  borderRadius: 'var(--radius-md)', background: 'transparent',
                  fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--text-muted)',
                  cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6, whiteSpace: 'nowrap',
                }}>
                  <_XIcon /> {t('Limpar')} ({activeCount})
                </button>
              ) : <div style={{ height: 44 }} />}
            </div>
          )}
        </div>
      </div>

      {/* Toolbar */}
      <div style={{ maxWidth: 1280, margin: '0 auto', padding: isMobile ? '16px 20px 0' : '28px 40px 0' }}>
        <div style={{
          display: 'flex', flexDirection: isMobile ? 'column' : 'row',
          alignItems: isMobile ? 'flex-start' : 'center',
          justifyContent: 'space-between', gap: 12,
        }}>
          {/* Active filter tags + kind chips */}
          <div style={{
            display: 'flex', gap: isMobile ? 8 : 10, overflowX: 'auto',
            paddingBottom: isMobile ? 4 : 0, alignItems: 'center', width: isMobile ? '100%' : 'auto',
          }}>
            {favIds.length > 0 && (
              <button onClick={() => setShowFavs(f => !f)} style={{
                fontFamily: 'var(--font-body)', fontSize: isMobile ? 12.5 : 13.5, fontWeight: 600,
                padding: isMobile ? '8px 12px' : '9px 18px', borderRadius: 'var(--radius-pill)', cursor: 'pointer',
                border: '1px solid ' + (showFavs ? '#c0415a' : 'var(--border-default)'),
                background: showFavs ? '#c0415a' : 'var(--surface-card)',
                color: showFavs ? '#fff' : 'var(--warmgray-600)',
                display: 'flex', alignItems: 'center', gap: 6, flexShrink: 0,
                transition: 'all var(--dur-base) var(--ease-out)',
              }}>
                ♥ {t('Meus favoritos')} ({favIds.length})
              </button>
            )}
            {launch        && <span style={{ ...tagSty, cursor: 'default' }}>🆕 {t('Lançamentos — últimos 30 dias')}</span>}
            {luxury        && <span style={{ ...tagSty, cursor: 'default' }}>✦ {t('Imóveis de luxo')}</span>}
            {neighborhood  && <button onClick={() => setNeighborhood('')}  style={tagSty}>📍 {neighborhood} <_XIcon /></button>}
            {propertyType  && <button onClick={() => setPropertyType('')}  style={tagSty}>🏠 {t(propertyType)} <_XIcon /></button>}
            {minBeds       && <button onClick={() => setMinBeds('')}        style={tagSty}>🛏 {minBeds}+ {t('quartos')} <_XIcon /></button>}
            {priceRange    && <button onClick={() => setPriceRange('')}     style={tagSty}>💰 {t(priceLabel[priceRange])} <_XIcon /></button>}
            {featured      && <span style={{ ...tagSty, cursor: 'default' }}>✨ {t('Imóveis de luxo')}</span>}
            {!neighborhood && !featured && !propertyType && !showFavs && !launch && !luxury && (
              <>
                <Chip id="all"    label={t('Todos')} />
                <Chip id="sale"   label={t('Venda')} />
                <Chip id="season" label={t('Temporada')} />
                <Chip id="rent"   label={t('Aluguel')} />
              </>
            )}
          </div>

          {/* Count + sort / mobile filter button */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, width: isMobile ? '100%' : 'auto' }}>
            <span style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--text-muted)', whiteSpace: 'nowrap' }}>
              {list.length === 1 ? t('1 encontrado') : t('{n} encontrados', { n: list.length })}
            </span>
            {isMobile && (
              <button onClick={() => setShowFilters(true)} style={{
                flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                padding: '10px 16px', borderRadius: 'var(--radius-md)',
                border: '1px solid ' + (activeCount > 0 ? 'var(--brown-500)' : 'var(--border-default)'),
                background: activeCount > 0 ? 'var(--brown-500)' : 'var(--surface-card)',
                color: activeCount > 0 ? 'var(--cream-50)' : 'var(--text-body)',
                fontFamily: 'var(--font-body)', fontSize: 13.5, fontWeight: 500, cursor: 'pointer',
              }}>
                <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24"
                  fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"/>
                </svg>
                {t('Filtros')}{activeCount > 0 ? ` (${activeCount})` : ''}
              </button>
            )}
            {!isMobile && (
              <div style={{ width: 180 }}>
                <select value={sortBy} onChange={e => setSortBy(e.target.value)}
                  style={{ ..._filterSelectStyle, height: 38, fontSize: 13 }}>
                  <option value="">{t('Mais recentes')}</option>
                  <option value="price-asc">{t('Menor preço')}</option>
                  <option value="price-desc">{t('Maior preço')}</option>
                </select>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Grid */}
      <div style={{ maxWidth: 1280, margin: '0 auto', padding: isMobile ? '20px 20px 60px' : '26px 40px 80px' }}>
        {list.length === 0 ? (
          <div key="listings-empty" style={{ textAlign: 'center', padding: '80px 0', fontFamily: 'var(--font-body)', color: 'var(--text-muted)' }}>
            <div style={{ fontSize: 48, marginBottom: 16 }}>🏠</div>
            <div style={{ fontSize: 18, fontWeight: 600, color: 'var(--text-body)', marginBottom: 8 }}>
              {t('Nenhum imóvel encontrado')}
            </div>
            <div style={{ fontSize: 14, marginBottom: 24 }}>
              {neighborhood
                ? t('Não há imóveis em {bairro} com os filtros selecionados.', { bairro: neighborhood })
                : t('Não há imóveis disponíveis para os filtros selecionados.')}
            </div>
            {activeCount > 0 && (
              <button onClick={clearAllFilters} style={{
                padding: '10px 24px', borderRadius: 'var(--radius-pill)',
                border: '1px solid var(--border-default)',
                background: 'var(--surface-card)', color: 'var(--text-body)',
                fontFamily: 'var(--font-body)', fontSize: 14, cursor: 'pointer',
              }}>{t('Limpar filtros')}</button>
            )}
          </div>
        ) : (
          <div key="listings-table">
            <div style={{
              display: 'grid',
              gridTemplateColumns: isMobile ? '1fr' : isTablet ? 'repeat(2, 1fr)' : 'repeat(3, 1fr)',
              gap: 26,
            }}>
              {list.map(p => <PropertyCard key={p.id} {...p} onClick={() => onOpenProperty(p.id)} />)}
            </div>
            <div style={{ display: 'flex', justifyContent: 'center', marginTop: 50 }}>
              <Button variant="outline" iconRight="chevron-down">{t('Carregar mais imóveis')}</Button>
            </div>
          </div>
        )}
      </div>

      {/* Mobile filter bottom sheet */}
      {showFilters && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 1000 }}>
          <div onClick={() => setShowFilters(false)}
            style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.5)' }} />
          <div style={{
            position: 'absolute', bottom: 0, left: 0, right: 0,
            background: 'var(--surface-card)', borderRadius: '20px 20px 0 0',
            padding: '24px 20px 40px', maxHeight: '80vh', overflowY: 'auto',
          }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
              <span style={{ fontFamily: 'var(--font-display)', fontSize: 20, fontWeight: 700, color: 'var(--text-strong)' }}>
                {t('Filtros')}
              </span>
              {activeCount > 0 && (
                <button onClick={clearAllFilters} style={{
                  fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--rose-700)',
                  background: 'none', border: 'none', cursor: 'pointer', padding: 0,
                }}>{t('Limpar tudo')}</button>
              )}
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
              <FilterSelect label="Bairro" placeholder="Todos os bairros"
                value={neighborhood} onChange={setNeighborhood} options={BAIRROS} />
              <FilterSelect label="Tipo de imóvel" placeholder="Todos os tipos"
                value={propertyType} onChange={setPropertyType} options={TIPOS} />
              <FilterSelect label="Quartos (mínimo)" placeholder="Qualquer"
                value={minBeds} onChange={setMinBeds}
                options={[{value:'1',label:'1+ quarto'},{value:'2',label:'2+ quartos'},{value:'3',label:'3+ quartos'},{value:'4',label:'4+ quartos'}]} />
              <FilterSelect label="Faixa de preço" placeholder="Qualquer"
                value={priceRange} onChange={setPriceRange}
                options={[{value:'ate500k',label:'Até R$ 500 mil'},{value:'500k1m',label:'R$ 500 mil – 1 mi'},{value:'acima1m',label:'Acima de R$ 1 mi'}]} />
              <FilterSelect label="Ordenar por" placeholder="Mais recentes"
                value={sortBy} onChange={setSortBy}
                options={[{value:'price-asc',label:'Menor preço'},{value:'price-desc',label:'Maior preço'}]} />
            </div>
            <button onClick={() => setShowFilters(false)} style={{
              width: '100%', marginTop: 28, padding: 14, borderRadius: 'var(--radius-md)',
              background: 'var(--brown-700)', color: 'var(--cream-50)',
              fontFamily: 'var(--font-body)', fontSize: 15, fontWeight: 600,
              border: 'none', cursor: 'pointer',
            }}>
              {list.length === 1 ? t('Ver 1 imóvel') : t('Ver {n} imóveis', { n: list.length })}
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
window.ListingsScreen = ListingsScreen;
