// Pantalla Home — resultados rankeados
function HomeScreen({ criteria, onOpenProperty, onOpenCriteria, onOpenMap, onOpenImport, query, onQuery }) {
  const T = useTheme();
  const ranked = React.useMemo(
    () => window.SCORING.rankProperties(window.PROPERTIES, criteria),
    [criteria]
  );
  const [filter, setFilter] = React.useState('all');
  const visible = ranked.filter(({ p }) => {
    if (filter === 'top')      return ranked.indexOf(ranked.find(r => r.p.id === p.id)) < 5;
    if (filter === 'discount') return p.transaction === 'compra' && (window.SCORING.marketDelta(p).pct <= -3);
    if (filter === 'new')      return p.publishedDays <= 5;
    if (filter === 'eco')      return p.amenities.includes('ev') || p.amenities.includes('solar');
    if (query) return (p.title + p.sector + p.address).toLowerCase().includes(query.toLowerCase());
    return true;
  });

  return (
    <div style={{ background: T.bg, minHeight: '100%', paddingBottom: 100 }}>
      {/* Header */}
      <div style={{
        padding: '60px 20px 14px', display: 'flex', justifyContent: 'space-between',
        alignItems: 'flex-end',
      }}>
        <div>
          <div style={{ fontFamily: T.sans, fontSize: 11, color: T.ink2, letterSpacing: 1.4,
            textTransform: 'uppercase', marginBottom: 6 }}>
            Búsqueda activa · {criteria.transaction}
          </div>
          <div style={{ fontFamily: T.serif, fontSize: 36, color: T.ink, lineHeight: 1, fontWeight: 400 }}>
            {ranked.length} <span style={{ fontStyle: 'italic' }}>matches</span>
          </div>
          <div style={{ fontFamily: T.sans, fontSize: 13, color: T.ink2, marginTop: 6 }}>
            en {criteria.city} · {criteria.sectors.length} sectores
          </div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6, alignItems: 'flex-end' }}>
          {onOpenImport && (
            <button onClick={onOpenImport} style={{
              appearance: 'none', cursor: 'pointer', border: 'none',
              background: T.ink, color: T.bg, padding: '9px 12px', borderRadius: 999,
              fontFamily: T.sans, fontSize: 12, fontWeight: 500, display: 'flex',
              alignItems: 'center', gap: 6,
            }}>
              <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
                <path d="M6 2v8M2 6h8" stroke={T.bg} strokeWidth="1.6" strokeLinecap="round"/>
              </svg>
              Importar URL
            </button>
          )}
          <button onClick={onOpenCriteria} style={{
            appearance: 'none', cursor: 'pointer', border: `0.5px solid ${T.line}`,
            background: T.surf, padding: '9px 12px', borderRadius: 999,
            fontFamily: T.sans, fontSize: 12, color: T.ink, display: 'flex',
            alignItems: 'center', gap: 6,
          }}>
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
              <path d="M2 4h10M4 7h6M5.5 10h3" stroke={T.ink} strokeWidth="1.4" strokeLinecap="round"/>
            </svg>
            Criterios
          </button>
        </div>
      </div>

      {/* Search bar */}
      <div style={{ padding: '8px 20px 12px' }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 8,
          padding: '11px 14px', borderRadius: 12,
          background: T.surf, border: `0.5px solid ${T.line}`,
        }}>
          <svg width="14" height="14" viewBox="0 0 14 14">
            <circle cx="6" cy="6" r="4.5" stroke={T.ink2} strokeWidth="1.4" fill="none"/>
            <path d="M9.3 9.3L13 13" stroke={T.ink2} strokeWidth="1.4" strokeLinecap="round"/>
          </svg>
          <input value={query} onChange={(e) => onQuery(e.target.value)}
            placeholder="Buscar por sector, dirección…"
            style={{
              flex: 1, border: 'none', background: 'transparent', outline: 'none',
              fontFamily: T.sans, fontSize: 14, color: T.ink,
            }}/>
          <button onClick={onOpenMap} style={{
            appearance: 'none', border: 'none', background: T.ink2 + '15',
            padding: '5px 9px', borderRadius: 6, cursor: 'pointer',
            fontFamily: T.sans, fontSize: 11, color: T.ink, fontWeight: 500,
          }}>Mapa</button>
        </div>
      </div>

      {/* Filtros pildoras */}
      <div style={{
        display: 'flex', gap: 8, padding: '4px 20px 16px',
        overflowX: 'auto', WebkitOverflowScrolling: 'touch',
      }}>
        {[
          { id: 'all',      label: 'Todos' },
          { id: 'top',      label: 'Top 5' },
          { id: 'discount', label: '↓ Descuento' },
          { id: 'new',      label: 'Recientes' },
          { id: 'eco',      label: 'Eco' },
        ].map(f => (
          <button key={f.id} onClick={() => setFilter(f.id)} style={{
            appearance: 'none', cursor: 'pointer',
            padding: '7px 14px', borderRadius: 999,
            border: `0.5px solid ${filter === f.id ? T.ink : T.line}`,
            background: filter === f.id ? T.ink : 'transparent',
            color:      filter === f.id ? T.bg  : T.ink2,
            fontFamily: T.sans, fontSize: 12, fontWeight: 500, whiteSpace: 'nowrap',
          }}>{f.label}</button>
        ))}
      </div>

      {/* Cards */}
      <div style={{ padding: '0 20px', display: 'flex', flexDirection: 'column', gap: 16 }}>
        {visible.map((entry, i) => (
          <PropertyCard key={entry.p.id} entry={entry} rank={i + 1}
            criteria={criteria} onClick={() => onOpenProperty(entry.p.id)} />
        ))}
        {visible.length === 0 && window.PROPERTIES.length === 0 && (
          <div style={{
            padding: '40px 24px', textAlign: 'center', borderRadius: 18,
            background: T.surf, border: `0.5px solid ${T.line}`,
          }}>
            <div style={{ fontFamily: T.serif, fontSize: 26, color: T.ink,
              lineHeight: 1.15, fontWeight: 400, marginBottom: 8 }}>
              Aún sin <span style={{ fontStyle: 'italic' }}>inmuebles</span>
            </div>
            <div style={{ fontFamily: T.sans, fontSize: 13, color: T.ink2,
              lineHeight: 1.5, marginBottom: 18 }}>
              Importa tu primer listing desde Metrocuadrado, Finca Raíz, Ciencuadras o MercadoLibre.
              La IA extrae los datos y los puntúa contra tus criterios.
            </div>
            {onOpenImport && (
              <Pill primary onClick={onOpenImport}>＋ Importar primer inmueble</Pill>
            )}
          </div>
        )}
        {visible.length === 0 && window.PROPERTIES.length > 0 && (
          <div style={{
            padding: 40, textAlign: 'center', borderRadius: 16,
            background: T.surf, border: `0.5px solid ${T.line}`,
            fontFamily: T.sans, color: T.ink2, fontSize: 13,
          }}>Sin resultados con esos filtros.</div>
        )}
      </div>
    </div>
  );
}

function PropertyCard({ entry, rank, criteria, onClick }) {
  const T = useTheme();
  const { p, score } = entry;
  const portal = window.lookupPortal ? window.lookupPortal(p) : window.PORTALS.find(x => x.id === p.portal);
  const showScoreBreakdown = window.__bi_theme && window.__bi_theme.detail !== false;
  const market = score.market;
  const openPortal = (e) => {
    e.stopPropagation();
    window.open(window.portalUrl(p), '_blank', 'noopener,noreferrer');
  };

  return (
    <div onClick={onClick} style={{
      borderRadius: T.radius, background: T.surf,
      border: `0.5px solid ${T.line}`, overflow: 'hidden',
      cursor: 'pointer',
      boxShadow: '0 1px 0 rgba(26,23,20,0.04), 0 8px 24px rgba(26,23,20,0.04)',
    }}>
      {/* Imagen */}
      <div style={{ padding: T.dense ? 10 : 14, paddingBottom: 0 }}>
        <PropertyImage p={p} height={T.dense ? 120 : 160} />
      </div>

      {/* Header con rank + score */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 12,
        padding: T.dense ? '10px 14px 6px' : '14px 18px 6px',
      }}>
        <div style={{
          fontFamily: T.mono, fontSize: 10, color: T.ink2,
          padding: '3px 6px', borderRadius: 4, background: T.surf2,
          letterSpacing: 0.5,
        }}>#{String(rank).padStart(2, '0')}</div>
        <button onClick={openPortal} style={{
          appearance: 'none', border: 'none', background: 'transparent',
          padding: 0, margin: 0, cursor: 'pointer', flex: 1, textAlign: 'left',
          fontFamily: T.sans, fontSize: 11, color: T.ink2,
          display: 'inline-flex', alignItems: 'center', gap: 4,
        }}>
          <span style={{ width: 6, height: 6, borderRadius: 999, background: portal.color, display: 'inline-block' }} />
          {portal.label} · hace {p.publishedDays}d
          <svg width="9" height="9" viewBox="0 0 16 16" style={{ marginLeft: 1 }}>
            <path d="M6 3h7v7M13 3L5.5 10.5" stroke={T.ink2} strokeWidth="1.6" fill="none" strokeLinecap="round"/>
          </svg>
        </button>
        <ScoreRing score={score.total} size={42} stroke={3.5} />
      </div>

      {/* Título + dirección */}
      <div style={{ padding: T.dense ? '0 14px 10px' : '0 18px 14px' }}>
        <div style={{
          fontFamily: T.serif, fontSize: T.dense ? 19 : 22, color: T.ink,
          fontWeight: 400, lineHeight: 1.15, marginBottom: 4,
        }}>{p.title}</div>
        <div style={{ fontFamily: T.sans, fontSize: 12, color: T.ink2 }}>
          {p.address} · Estrato {p.estrato}
        </div>
      </div>

      {/* Precio + market */}
      <div style={{
        padding: T.dense ? '6px 14px 12px' : '6px 18px 14px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <div>
          <div style={{ fontFamily: T.serif, fontSize: T.dense ? 22 : 26, color: T.ink, fontWeight: 400 }}>
            {fmt.copFull(p.price)}
            {p.transaction === 'arriendo' && (
              <span style={{ fontFamily: T.sans, fontSize: 13, color: T.ink2, fontWeight: 400 }}>
                {' '}/mes
              </span>
            )}
          </div>
          <div style={{ fontFamily: T.mono, fontSize: 11, color: T.ink2, marginTop: 2 }}>
            {fmt.cop(p.price / p.areaM2)}/m² · {fmt.m2(p.areaM2)} · {p.rooms}h · {p.baths}b
          </div>
        </div>
        {market && <MarketBadge market={market} compact />}
      </div>

      {/* Breakdown chips */}
      {showScoreBreakdown && (
        <div style={{
          padding: T.dense ? '0 14px 14px' : '0 18px 16px',
          display: 'flex', gap: 6, flexWrap: 'wrap',
        }}>
          <ScoreChip label="Precio"    val={score.breakdown.price} />
          <ScoreChip label="Transp."   val={score.breakdown.transit} />
          <ScoreChip label="Sostenib." val={score.breakdown.sustain} />
          <ScoreChip label="Sector"    val={score.breakdown.sector} />
          {p.amenities.includes('ev') && <Chip tone="accent" icon="⚡">Carga EV</Chip>}
        </div>
      )}
    </div>
  );
}

function ScoreChip({ label, val }) {
  const T = useTheme();
  const tone = val >= 85 ? 'good' : val >= 65 ? 'neutral' : val >= 50 ? 'warn' : 'bad';
  const cmap = {
    good:    { fg: T.good,  bg: 'rgba(63,122,78,0.08)' },
    neutral: { fg: T.ink2,  bg: T.surf2 },
    warn:    { fg: T.warn,  bg: 'rgba(199,110,74,0.10)' },
    bad:     { fg: T.bad,   bg: 'rgba(181,72,46,0.10)' },
  };
  const s = cmap[tone];
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'baseline', gap: 4,
      padding: '4px 8px', borderRadius: 6,
      background: s.bg, color: s.fg,
      fontFamily: T.sans, fontSize: 11, fontWeight: 500,
    }}>
      {label}
      <span style={{ fontFamily: T.mono, fontWeight: 600 }}>{val}</span>
    </span>
  );
}

Object.assign(window, { HomeScreen });
