// Pantalla Detalle de inmueble — incluye análisis de mercado vía Claude
function DetailScreen({ propertyId, criteria, onBack, onCompare, onSave, savedIds }) {
  const T = useTheme();
  const p = window.PROPERTIES.find(x => x.id === propertyId);
  const score = window.SCORING.computeScore(p, criteria);
  const portal = window.lookupPortal ? window.lookupPortal(p) : window.PORTALS.find(x => x.id === p.portal);
  const market = score.market;
  const isSaved = savedIds.includes(propertyId);

  // Análisis Claude — se carga al abrir
  const [aiAnalysis, setAiAnalysis] = React.useState(null);
  const [loadingAi, setLoadingAi] = React.useState(true);
  const [aiError, setAiError] = React.useState(false);

  React.useEffect(() => {
    let alive = true;
    setLoadingAi(true);
    setAiError(false);
    setAiAnalysis(null);

    // Preferimos window.claude.analyze (proxy estructurado al Worker → Claude
    // Haiku 4.5 vía Anthropic API). Fallback a window.claude.complete con prompt
    // textual cuando no exista (tests viejos / mock antiguo).
    const run = (window.claude && typeof window.claude.analyze === 'function')
      ? window.claude.analyze(p, market)
      : (function () {
          const prompt = 'Analiza esta oferta y responde SOLO con JSON {"verdict","reasoning","tip"}. ' +
            p.type + ' en ' + p.sector + ', ' + p.city + '. Diferencia: ' + market.pct + '% (' + market.verdict + ').';
          return window.claude.complete(prompt).then(function (text) {
            const cleaned = String(text).replace(/```json\s*|\s*```/g, '').trim();
            return JSON.parse(cleaned);
          });
        })();

    run.then(function (json) {
      if (!alive) return;
      setAiAnalysis(json);
      setLoadingAi(false);
    }).catch(function () {
      if (!alive) return;
      setAiError(true);
      setLoadingAi(false);
    });
    return function () { alive = false; };
  }, [propertyId]);

  return (
    <div style={{ background: T.bg, minHeight: '100%', paddingBottom: 110 }}>
      {/* Hero */}
      <div style={{ position: 'relative' }}>
        <div style={{ padding: '8px 16px 0' }}>
          <PropertyImage p={p} height={300} showBadge />
        </div>
        {/* back + save */}
        <div style={{
          position: 'absolute', top: 60, left: 16, right: 16,
          display: 'flex', justifyContent: 'space-between',
        }}>
          <button onClick={onBack} style={{
            appearance: 'none', border: 'none', cursor: 'pointer',
            width: 40, height: 40, borderRadius: 999,
            background: 'rgba(255,255,255,0.92)', backdropFilter: 'blur(12px)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            boxShadow: '0 2px 10px rgba(0,0,0,0.12)',
          }}>
            <svg width="14" height="14" viewBox="0 0 14 14">
              <path d="M9 2L4 7l5 5" stroke="#1A1714" strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </button>
          <button onClick={() => onSave(propertyId)} style={{
            appearance: 'none', border: 'none', cursor: 'pointer',
            width: 40, height: 40, borderRadius: 999,
            background: 'rgba(255,255,255,0.92)', backdropFilter: 'blur(12px)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            boxShadow: '0 2px 10px rgba(0,0,0,0.12)',
          }}>
            <svg width="16" height="16" viewBox="0 0 16 16">
              <path d="M3 2h10v12l-5-3.5L3 14V2z" stroke="#1A1714" strokeWidth="1.4" strokeLinejoin="round"
                fill={isSaved ? '#1A1714' : 'none'}/>
            </svg>
          </button>
        </div>
      </div>

      {/* Header */}
      <div style={{ padding: '20px 20px 14px' }}>
        <div style={{
          display: 'flex', gap: 6, marginBottom: 8, flexWrap: 'wrap',
        }}>
          <Chip><span style={{ width: 5, height: 5, borderRadius: 999, background: portal.color, display: 'inline-block' }}/>{portal.label}</Chip>
          <Chip>Estrato {p.estrato}</Chip>
          <Chip>{p.type}</Chip>
          <Chip>Hace {p.publishedDays}d</Chip>
        </div>
        <div style={{
          fontFamily: T.serif, fontSize: 30, color: T.ink, lineHeight: 1.1,
          fontWeight: 400, letterSpacing: -0.3,
        }}>{p.title}</div>
        <div style={{ fontFamily: T.sans, fontSize: 13, color: T.ink2, marginTop: 6 }}>
          {p.address} · {p.sector}, {p.city}
        </div>
      </div>

      {/* Score + precio principal */}
      <div style={{ padding: '0 20px 18px', display: 'flex', gap: 14, alignItems: 'stretch' }}>
        <div style={{
          flex: 1, padding: 16, borderRadius: T.radius,
          background: T.surf, border: `0.5px solid ${T.line}`,
        }}>
          <div style={{ fontFamily: T.sans, fontSize: 10.5, letterSpacing: 1.2,
            color: T.ink2, textTransform: 'uppercase' }}>Precio publicado</div>
          <div style={{
            fontFamily: T.serif, fontSize: 26, color: T.ink, marginTop: 4,
            lineHeight: 1, fontWeight: 400,
          }}>
            {fmt.copFull(p.price)}
          </div>
          <div style={{ fontFamily: T.mono, fontSize: 11, color: T.ink2, marginTop: 4 }}>
            {fmt.cop(p.price/p.areaM2)}/m² {p.transaction === 'arriendo' ? '· mensual' : ''}
          </div>
        </div>
        <div style={{
          width: 96, padding: 14, borderRadius: T.radius,
          background: T.surf, border: `0.5px solid ${T.line}`,
          display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
        }}>
          <ScoreRing score={score.total} size={56} stroke={5} />
          <div style={{ fontFamily: T.sans, fontSize: 9.5, color: T.ink2, marginTop: 6,
            letterSpacing: 0.6, textTransform: 'uppercase' }}>match</div>
        </div>
      </div>

      {/* Análisis de mercado (Claude) — solo compra */}
      {p.transaction === 'compra' && (
        <div style={{ padding: '0 20px 18px' }}>
          <div style={{
            padding: 18, borderRadius: T.radius,
            background: T.ink, color: T.bg, position: 'relative', overflow: 'hidden',
          }}>
            {/* decoración esquina */}
            <div style={{
              position: 'absolute', right: -30, top: -30, width: 120, height: 120,
              borderRadius: 999, background: 'rgba(255,255,255,0.04)',
            }} />
            <div style={{
              display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12,
            }}>
              <div style={{
                width: 6, height: 6, borderRadius: 999, background: T.accent,
                boxShadow: `0 0 10px ${T.accent}`,
              }} />
              <span style={{ fontFamily: T.sans, fontSize: 10.5, letterSpacing: 1.4,
                textTransform: 'uppercase', opacity: 0.7 }}>Análisis de mercado · IA</span>
            </div>

            <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginBottom: 14 }}>
              <div style={{
                fontFamily: T.serif, fontSize: 44, fontWeight: 400, lineHeight: 1,
                color: market.pct < 0 ? '#9DD4A4' : market.pct > 5 ? '#E8A88E' : T.bg,
              }}>{fmt.pct(market.pct)}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: T.sans, fontSize: 13, fontWeight: 600, opacity: 0.9 }}>
                  {market.verdict === 'ganga' ? 'Ganga'
                  : market.verdict === 'descuento' ? 'Descuento real'
                  : market.verdict === 'justo' ? 'Precio justo'
                  : market.verdict === 'sobreprecio' ? 'Sobreprecio'
                  : 'Caro vs. mercado'}
                </div>
                <div style={{ fontFamily: T.sans, fontSize: 11, opacity: 0.55 }}>
                  vs. {fmt.cop(p.marketPriceM2)}/m² promedio en {p.sector}
                </div>
              </div>
            </div>

            {/* Comparación visual */}
            <div style={{
              height: 6, borderRadius: 999, background: 'rgba(255,255,255,0.10)',
              position: 'relative', marginBottom: 16,
            }}>
              <div style={{
                position: 'absolute', left: '50%', top: -3, bottom: -3, width: 1,
                background: 'rgba(255,255,255,0.3)',
              }} />
              <div style={{
                position: 'absolute', height: '100%', borderRadius: 999,
                background: market.pct < 0 ? '#9DD4A4' : '#E8A88E',
                ...(market.pct < 0
                  ? { right: '50%', width: `${Math.min(50, Math.abs(market.pct) * 2)}%` }
                  : { left:  '50%', width: `${Math.min(50, market.pct * 2)}%` }),
              }} />
            </div>

            {/* Veredicto Claude */}
            <div style={{
              padding: 12, borderRadius: 10,
              background: 'rgba(255,255,255,0.06)',
              minHeight: 70,
            }}>
              {loadingAi ? (
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <div className="bi-pulse" style={{
                    width: 6, height: 6, borderRadius: 999, background: T.accent,
                  }} />
                  <span style={{ fontFamily: T.sans, fontSize: 12, opacity: 0.6 }}>
                    Analizando con IA…
                  </span>
                </div>
              ) : aiError ? (
                <div style={{ fontFamily: T.sans, fontSize: 12, opacity: 0.6 }}>
                  No pudimos generar el análisis ahora. {fmt.pct(market.pct)} sobre el promedio del sector.
                </div>
              ) : (
                <div>
                  <div style={{ fontFamily: T.serif, fontSize: 17, fontStyle: 'italic',
                    lineHeight: 1.3, marginBottom: 6 }}>
                    "{aiAnalysis.verdict}"
                  </div>
                  <div style={{ fontFamily: T.sans, fontSize: 12, opacity: 0.78,
                    lineHeight: 1.45, marginBottom: aiAnalysis.tip ? 8 : 0 }}>
                    {aiAnalysis.reasoning}
                  </div>
                  {aiAnalysis.tip && (
                    <div style={{ display: 'flex', gap: 6, alignItems: 'flex-start',
                      paddingTop: 8, borderTop: '0.5px solid rgba(255,255,255,0.10)' }}>
                      <span style={{ fontFamily: T.mono, fontSize: 10, opacity: 0.5,
                        marginTop: 1 }}>TIP</span>
                      <span style={{ fontFamily: T.sans, fontSize: 12, opacity: 0.85,
                        lineHeight: 1.4 }}>{aiAnalysis.tip}</span>
                    </div>
                  )}
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {/* Especificaciones */}
      <div style={{ padding: '0 20px 18px' }}>
        <SectionTitle>Especificaciones</SectionTitle>
        <div style={{
          display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 1,
          background: T.line, border: `0.5px solid ${T.line}`,
          borderRadius: T.radius, overflow: 'hidden',
        }}>
          {[
            ['Área',    fmt.m2(p.areaM2)],
            ['Habit.',  p.rooms],
            ['Baños',   p.baths],
            ['Parq.',   p.parking],
            ['Piso',    p.type === 'Casa' ? '—' : `${p.floor}/${p.totalFloors}`],
            ['Año',     p.yearBuilt],
          ].map(([k, v]) => (
            <div key={k} style={{ background: T.surf, padding: '12px 14px' }}>
              <div style={{ fontFamily: T.sans, fontSize: 10.5, color: T.ink2,
                letterSpacing: 0.8, textTransform: 'uppercase' }}>{k}</div>
              <div style={{ fontFamily: T.mono, fontSize: 17, color: T.ink,
                fontWeight: 500, marginTop: 4 }}>{v}</div>
            </div>
          ))}
        </div>
      </div>

      {/* Score breakdown */}
      <div style={{ padding: '0 20px 18px' }}>
        <SectionTitle>Cómo calificó cada criterio</SectionTitle>
        <div style={{
          padding: 16, borderRadius: T.radius,
          background: T.surf, border: `0.5px solid ${T.line}`,
        }}>
          {[
            ['Precio',          'price',     criteria.weights.price],
            ['Área',            'area',      criteria.weights.area],
            ['Transporte',      'transit',   criteria.weights.transit],
            ['Sostenibilidad',  'sustain',   criteria.weights.sustain],
            ['Estrato',         'estrato',   criteria.weights.estrato],
            ['Piso',            'floor',     criteria.weights.floor],
            ['Cercanías',       'nearby',    criteria.weights.nearby],
            ['Amenidades',      'amenities', criteria.weights.amenities],
          ].map(([label, key, w]) => (
            <ScoreBar key={key} label={label} value={score.breakdown[key]} weight={w} />
          ))}
        </div>
      </div>

      {/* Transporte y cercanías */}
      <div style={{ padding: '0 20px 18px' }}>
        <SectionTitle>Conectividad</SectionTitle>
        <div style={{
          display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8,
        }}>
          <DistCard label="TransMilenio" value={fmt.dist(p.transit.transmilenio_m)} caminos={Math.round(p.transit.transmilenio_m / 75)} />
          <DistCard label="SITP" value={fmt.dist(p.transit.sitp_m)} caminos={Math.round(p.transit.sitp_m / 75)} />
          <DistCard label="Metro (futuro)" value={fmt.dist(p.transit.metro_m)} caminos={Math.round(p.transit.metro_m / 75)} />
          <DistCard label="Ciclorruta" value={fmt.dist(p.transit.bike_m)} caminos={Math.round(p.transit.bike_m / 75)} />
        </div>
        <div style={{ marginTop: 14 }}>
          <SectionTitle small>Cercanías</SectionTitle>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            <Chip>🎓 Colegios · {fmt.dist(p.nearby.schools_m)}</Chip>
            <Chip>🛒 Mercado · {fmt.dist(p.nearby.supermarkets_m)}</Chip>
            <Chip>🏥 Salud · {fmt.dist(p.nearby.hospitals_m)}</Chip>
            <Chip>🏬 C.C. · {fmt.dist(p.nearby.malls_m)}</Chip>
          </div>
        </div>
      </div>

      {/* Mapa */}
      <div style={{ padding: '0 20px 18px' }}>
        <SectionTitle>Ubicación</SectionTitle>
        <MiniMap properties={[{ p, score }]} current={p.id} height={220} />
      </div>

      {/* Amenidades */}
      <div style={{ padding: '0 20px 18px' }}>
        <SectionTitle>Amenidades & sostenibilidad</SectionTitle>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
          {p.amenities.map(a => {
            const am = window.AMENITY_LABELS[a];
            const isSus = ['ev','solar','water','gas'].includes(a);
            return (
              <Chip key={a} tone={isSus ? 'accent' : 'neutral'} icon={am.icon}>
                {am.label}
              </Chip>
            );
          })}
        </div>
      </div>

      {/* Descripción */}
      <div style={{ padding: '0 20px 18px' }}>
        <SectionTitle>Descripción del anuncio</SectionTitle>
        <div style={{
          padding: 16, borderRadius: T.radius,
          background: T.surf, border: `0.5px solid ${T.line}`,
          fontFamily: T.sans, fontSize: 13.5, color: T.ink, lineHeight: 1.55,
        }}>
          {p.description}
          <div style={{ marginTop: 12, paddingTop: 12, borderTop: `0.5px solid ${T.line}`,
            display: 'flex', alignItems: 'center', gap: 8 }}>
            <div style={{ width: 8, height: 8, borderRadius: 999, background: portal.color }} />
            <span style={{ fontFamily: T.sans, fontSize: 11.5, color: T.ink2 }}>
              Capturado de {portal.label} · ID {p.id}
            </span>
          </div>
        </div>
      </div>

      {/* Link al portal de origen */}
      <div style={{ padding: '0 20px 18px' }}>
        <SectionTitle>Publicación original</SectionTitle>
        <a href={window.portalUrl(p)} target="_blank" rel="noopener noreferrer" style={{
          display: 'flex', alignItems: 'center', gap: 12, padding: 14,
          borderRadius: T.radius, background: T.surf, border: `0.5px solid ${T.line}`,
          textDecoration: 'none', color: 'inherit',
        }}>
          <div style={{
            width: 38, height: 38, borderRadius: 10, flexShrink: 0,
            background: portal.color, display: 'flex',
            alignItems: 'center', justifyContent: 'center',
            fontFamily: T.serif, fontSize: 18, color: '#fff', fontStyle: 'italic',
          }}>{portal.label[0]}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontFamily: T.sans, fontSize: 13.5, color: T.ink, fontWeight: 500 }}>
              Ver en {portal.label}
            </div>
            <div style={{
              fontFamily: T.mono, fontSize: 10.5, color: T.ink2, marginTop: 2,
              overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
            }}>{window.portalUrl(p)}</div>
          </div>
          <svg width="16" height="16" viewBox="0 0 16 16" style={{ flexShrink: 0 }}>
            <path d="M6 3h7v7M13 3L5.5 10.5M3 7v6h6" stroke={T.ink2}
              strokeWidth="1.4" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </a>
      </div>

      {/* CTA bottom */}
      <div style={{
        position: 'fixed', bottom: 0, left: 0, right: 0,
        padding: '12px 20px 28px', background: T.bg + 'EE',
        backdropFilter: 'blur(16px)', borderTop: `0.5px solid ${T.line}`,
        display: 'flex', gap: 8, zIndex: 30,
      }}>
        <Pill onClick={() => onCompare(propertyId)}>＋ Comparar</Pill>
        <Pill primary full>Contactar publicador</Pill>
      </div>
    </div>
  );
}

function SectionTitle({ children, small }) {
  const T = useTheme();
  return (
    <div style={{
      fontFamily: T.sans, fontSize: small ? 10 : 11, color: T.ink2,
      letterSpacing: small ? 1.0 : 1.4, textTransform: 'uppercase', marginBottom: 10,
      fontWeight: 500,
    }}>{children}</div>
  );
}

function ScoreBar({ label, value, weight }) {
  const T = useTheme();
  const col = value >= 85 ? T.good : value >= 65 ? T.accent : value >= 50 ? T.warn : T.bad;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '7px 0' }}>
      <div style={{ width: 100, fontFamily: T.sans, fontSize: 12.5, color: T.ink }}>
        {label}
      </div>
      <div style={{ flex: 1, height: 4, background: T.line, borderRadius: 999, position: 'relative' }}>
        <div style={{
          height: '100%', borderRadius: 999, background: col,
          width: `${value}%`, transition: 'width 0.4s',
        }} />
      </div>
      <div style={{
        fontFamily: T.mono, fontSize: 12, color: T.ink, fontWeight: 500,
        width: 28, textAlign: 'right',
      }}>{value}</div>
      <div style={{
        fontFamily: T.mono, fontSize: 9.5, color: T.ink3, width: 26,
      }}>w{weight}</div>
    </div>
  );
}

function DistCard({ label, value, caminos }) {
  const T = useTheme();
  return (
    <div style={{
      padding: 12, borderRadius: 12,
      background: T.surf, border: `0.5px solid ${T.line}`,
    }}>
      <div style={{ fontFamily: T.sans, fontSize: 10.5, color: T.ink2,
        letterSpacing: 0.6, textTransform: 'uppercase' }}>{label}</div>
      <div style={{ fontFamily: T.serif, fontSize: 22, color: T.ink,
        fontWeight: 400, marginTop: 4 }}>{value}</div>
      <div style={{ fontFamily: T.mono, fontSize: 10.5, color: T.ink2, marginTop: 2 }}>
        ≈ {caminos} min caminando
      </div>
    </div>
  );
}

Object.assign(window, { DetailScreen });
