// Pantalla Comparador
function CompareScreen({ ids, onRemove, onAdd, onOpenProperty, criteria }) {
  const T = useTheme();
  const items = ids.map(id => {
    const p = window.PROPERTIES.find(x => x.id === id);
    return { p, score: window.SCORING.computeScore(p, criteria) };
  });

  const rows = [
    { label: 'Match',   render: (e) => <span style={{ fontFamily: T.mono, fontWeight: 600, color: T.ink }}>{e.score.total}</span> },
    { label: 'Precio',  render: (e) => <span style={{ fontFamily: T.mono, color: T.ink }}>{fmt.cop(e.p.price)}</span> },
    { label: 'Mercado', render: (e) => e.score.market ? <MarketBadge market={e.score.market} compact/> : '—' },
    { label: 'Área',    render: (e) => fmt.m2(e.p.areaM2) },
    { label: '$/m²',    render: (e) => fmt.cop(e.p.price/e.p.areaM2) },
    { label: 'Estrato', render: (e) => e.p.estrato },
    { label: 'Hab.',    render: (e) => e.p.rooms },
    { label: 'Baños',   render: (e) => e.p.baths },
    { label: 'Parq.',   render: (e) => e.p.parking },
    { label: 'Piso',    render: (e) => e.p.type === 'Casa' ? '—' : `${e.p.floor}/${e.p.totalFloors}` },
    { label: 'Año',     render: (e) => e.p.yearBuilt },
    { label: 'TM',      render: (e) => fmt.dist(e.p.transit.transmilenio_m) },
    { label: 'EV',      render: (e) => e.p.amenities.includes('ev') ? '✓' : '—' },
    { label: 'Solar',   render: (e) => e.p.amenities.includes('solar') ? '✓' : '—' },
  ];

  return (
    <div style={{ background: T.bg, minHeight: '100%', paddingBottom: 100 }}>
      <div style={{ padding: '60px 20px 14px' }}>
        <div style={{ fontFamily: T.sans, fontSize: 11, color: T.ink2,
          letterSpacing: 1.4, textTransform: 'uppercase', marginBottom: 6 }}>
          Comparar
        </div>
        <div style={{ fontFamily: T.serif, fontSize: 32, color: T.ink, lineHeight: 1, fontWeight: 400 }}>
          {items.length} <span style={{ fontStyle: 'italic' }}>opciones</span>
        </div>
      </div>

      {items.length === 0 ? (
        <EmptyState
          title="Aún no comparas nada"
          body="Abre cualquier inmueble y toca + Comparar para sumarlo a esta vista."
        />
      ) : (
        <>
          {/* Tarjetas con foto */}
          <div style={{ padding: '4px 20px 14px', display: 'flex', gap: 10, overflowX: 'auto' }}>
            {items.map(e => (
              <div key={e.p.id} style={{ width: 130, flexShrink: 0 }}>
                <div style={{ position: 'relative' }}>
                  <PropertyImage p={e.p} height={100} showBadge={false}/>
                  <button onClick={() => onRemove(e.p.id)} style={{
                    position: 'absolute', top: 6, right: 6, width: 22, height: 22,
                    borderRadius: 999, border: 'none', cursor: 'pointer',
                    background: 'rgba(0,0,0,0.55)', color: '#fff',
                    fontFamily: T.mono, fontSize: 12, lineHeight: 1,
                  }}>×</button>
                </div>
                <div style={{
                  fontFamily: T.serif, fontSize: 14, color: T.ink, marginTop: 6,
                  lineHeight: 1.15, height: 32, overflow: 'hidden',
                }}>{e.p.title}</div>
                <div style={{ fontFamily: T.sans, fontSize: 10, color: T.ink2 }}>{e.p.sector}</div>
              </div>
            ))}
            {items.length < 3 && (
              <button onClick={onAdd} style={{
                width: 130, flexShrink: 0, height: 100, marginTop: 0,
                appearance: 'none', cursor: 'pointer',
                borderRadius: 14, border: `1px dashed ${T.ink3}`,
                background: 'transparent', color: T.ink2,
                fontFamily: T.sans, fontSize: 12,
              }}>＋ Añadir</button>
            )}
          </div>

          {/* Tabla */}
          <div style={{ padding: '0 20px' }}>
            <div style={{
              borderRadius: T.radius, background: T.surf,
              border: `0.5px solid ${T.line}`, overflow: 'hidden',
            }}>
              {rows.map((row, idx) => (
                <div key={row.label} style={{
                  display: 'grid', gridTemplateColumns: `90px repeat(${items.length}, 1fr)`,
                  borderBottom: idx === rows.length - 1 ? 'none' : `0.5px solid ${T.line}`,
                }}>
                  <div style={{
                    padding: '11px 14px', fontFamily: T.sans, fontSize: 11.5,
                    color: T.ink2, background: T.surf2, fontWeight: 500,
                  }}>{row.label}</div>
                  {items.map(e => (
                    <div key={e.p.id} style={{
                      padding: '11px 10px', fontFamily: T.sans, fontSize: 12.5,
                      color: T.ink, textAlign: 'center', borderLeft: `0.5px solid ${T.line}`,
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                    }}>{row.render(e)}</div>
                  ))}
                </div>
              ))}
            </div>
          </div>

          <div style={{ padding: '16px 20px' }}>
            {items.map(e => (
              <button key={e.p.id} onClick={() => onOpenProperty(e.p.id)} style={{
                appearance: 'none', cursor: 'pointer', width: '100%',
                padding: '12px 14px', borderRadius: 12, marginBottom: 8,
                background: 'transparent', border: `0.5px solid ${T.line}`,
                fontFamily: T.sans, fontSize: 13, color: T.ink, textAlign: 'left',
                display: 'flex', justifyContent: 'space-between', alignItems: 'center',
              }}>
                <span>Ver detalle de {e.p.sector}</span>
                <span style={{ color: T.ink2 }}>→</span>
              </button>
            ))}
          </div>
        </>
      )}
    </div>
  );
}

// Pantalla Guardados / alertas
function SavedScreen({ savedIds, criteria, onOpenProperty, onRemove }) {
  const T = useTheme();
  const items = savedIds.map(id => {
    const p = window.PROPERTIES.find(x => x.id === id);
    return p ? { p, score: window.SCORING.computeScore(p, criteria) } : null;
  }).filter(Boolean);

  const alerts = [
    { id: 'a1', name: 'Compra · Norte sostenible',  active: true,  newCount: 3 },
    { id: 'a2', name: 'Arriendo · Chapinero',       active: true,  newCount: 1 },
    { id: 'a3', name: 'Casa · Suba bajo presupuesto', active: false, newCount: 0 },
  ];

  return (
    <div style={{ background: T.bg, minHeight: '100%', paddingBottom: 100 }}>
      <div style={{ padding: '60px 20px 14px' }}>
        <div style={{ fontFamily: T.sans, fontSize: 11, color: T.ink2,
          letterSpacing: 1.4, textTransform: 'uppercase', marginBottom: 6 }}>
          Guardados
        </div>
        <div style={{ fontFamily: T.serif, fontSize: 32, color: T.ink, lineHeight: 1, fontWeight: 400 }}>
          Tu <span style={{ fontStyle: 'italic' }}>biblioteca</span>
        </div>
      </div>

      <div style={{ padding: '4px 20px 14px' }}>
        <div style={{ fontFamily: T.sans, fontSize: 11, color: T.ink2,
          letterSpacing: 1.2, textTransform: 'uppercase', marginBottom: 10 }}>
          Búsquedas guardadas
        </div>
        <div style={{
          borderRadius: T.radius, background: T.surf,
          border: `0.5px solid ${T.line}`, overflow: 'hidden',
        }}>
          {alerts.map((a, i) => (
            <div key={a.id} style={{
              display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px',
              borderBottom: i === alerts.length - 1 ? 'none' : `0.5px solid ${T.line}`,
            }}>
              <div style={{
                width: 32, height: 32, borderRadius: 999,
                background: a.active ? T.accent + '22' : T.surf2,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                <svg width="14" height="14" viewBox="0 0 14 14">
                  <path d="M3 6a4 4 0 018 0v3l1 2H2l1-2V6z" stroke={a.active ? T.accent : T.ink2}
                    strokeWidth="1.4" fill="none" strokeLinejoin="round"/>
                </svg>
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: T.sans, fontSize: 13.5, color: T.ink, fontWeight: 500 }}>
                  {a.name}
                </div>
                <div style={{ fontFamily: T.sans, fontSize: 11, color: T.ink2, marginTop: 2 }}>
                  {a.active ? 'Notificándote a diario' : 'Pausada'}
                  {a.newCount > 0 && <> · <span style={{ color: T.accent, fontWeight: 600 }}>
                    {a.newCount} nuevo{a.newCount > 1 ? 's' : ''}
                  </span></>}
                </div>
              </div>
              <span style={{ color: T.ink3 }}>›</span>
            </div>
          ))}
        </div>
      </div>

      <div style={{ padding: '14px 20px' }}>
        <div style={{ fontFamily: T.sans, fontSize: 11, color: T.ink2,
          letterSpacing: 1.2, textTransform: 'uppercase', marginBottom: 10 }}>
          Inmuebles favoritos
        </div>
        {items.length === 0 ? (
          <EmptyState title="Sin favoritos" body="Toca el ícono de marcador en cualquier inmueble para guardarlo aquí."/>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {items.map(e => (
              <div key={e.p.id} onClick={() => onOpenProperty(e.p.id)} style={{
                display: 'flex', gap: 12, padding: 12, borderRadius: T.radius,
                background: T.surf, border: `0.5px solid ${T.line}`, cursor: 'pointer',
              }}>
                <div style={{ width: 70, flexShrink: 0 }}>
                  <PropertyImage p={e.p} height={70} showBadge={false}/>
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontFamily: T.serif, fontSize: 16, color: T.ink,
                    lineHeight: 1.15, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {e.p.title}
                  </div>
                  <div style={{ fontFamily: T.sans, fontSize: 11, color: T.ink2, marginTop: 2 }}>
                    {e.p.sector} · Estrato {e.p.estrato}
                  </div>
                  <div style={{ display: 'flex', gap: 6, alignItems: 'center', marginTop: 6 }}>
                    <span style={{ fontFamily: T.mono, fontSize: 12, color: T.ink, fontWeight: 600 }}>
                      {fmt.cop(e.p.price)}
                    </span>
                    <span style={{ fontFamily: T.mono, fontSize: 11, color: T.ink2 }}>
                      · match {e.score.total}
                    </span>
                  </div>
                </div>
                <button onClick={(ev) => { ev.stopPropagation(); onRemove(e.p.id); }} style={{
                  appearance: 'none', border: 'none', background: 'transparent',
                  cursor: 'pointer', color: T.ink3, fontSize: 18, padding: 6,
                }}>×</button>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

function EmptyState({ title, body }) {
  const T = useTheme();
  return (
    <div style={{
      margin: '0 20px', padding: '36px 24px', textAlign: 'center',
      borderRadius: 18, background: T.surf, border: `0.5px solid ${T.line}`,
    }}>
      <div style={{ fontFamily: T.serif, fontSize: 22, color: T.ink, fontWeight: 400, marginBottom: 6 }}>
        {title}
      </div>
      <div style={{ fontFamily: T.sans, fontSize: 13, color: T.ink2, lineHeight: 1.4 }}>
        {body}
      </div>
    </div>
  );
}

Object.assign(window, { CompareScreen, SavedScreen, EmptyState });
