// desktop-screen-detail.jsx — Listing Detail + AI Eval desktop screens

function desktopEvalArray(primary, fallback = []) {
  return Array.isArray(primary) ? primary : (Array.isArray(fallback) ? fallback : []);
}

function desktopEvalText(value) {
  return String(value || '').replace(/\\r\\n/g, '\n').replace(/\\n/g, '\n').replace(/\\t/g, '\t');
}

function desktopRentalPersonalizationEnabled(user) {
  const value = user?.rental_profile?.personalized_inquiry_enabled;
  return !(value === false || value === 'false' || value === 0 || value === '0');
}

function DesktopEvalList({ items, tone = 'neutral' }) {
  const color = tone === 'danger' ? 'var(--danger)' : (tone === 'success' ? 'var(--success)' : 'var(--ink-muted)');
  const marker = tone === 'danger' ? '−' : (tone === 'success' ? '+' : '•');
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
      {items.map((item, i) => (
        <div key={i} style={{ display: 'flex', gap: 8, fontSize: 12.5, lineHeight: 1.5, color: 'var(--ink-2)' }}>
          <span style={{ color, flexShrink: 0 }}>{marker}</span>
          <span>{item}</span>
        </div>
      ))}
    </div>
  );
}

// ─── LISTING DETAIL ────────────────────────────────────────────────────
function DetailDesktop({
  active = 'kauf',
  onNav = () => {},
  onOpenAI = () => {},
  id = null,
  ctx = {},
  topBarProps = {},
} = {}) {
  const l = desktopFindListing(ctx, id);
  const safeListing = l || {};
  const eval_ = desktopEvaluationForListing(ctx, safeListing);
  const photos = desktopPhotos(safeListing);
  const [lightboxIndex, setLightboxIndex] = React.useState(null);
  const isRental = safeListing.type === 'miete';
  const detailActive = isRental ? 'miete' : active;
  const isFav = ctx.favs?.has(String(safeListing.id)) || ctx.favs?.has(safeListing.id);
  const adId = safeListing.adId || safeListing.id;
  const taskId = safeListing.task_id || safeListing.searchId;
  const personalizedInquiryEnabled = isRental && desktopRentalPersonalizationEnabled(ctx.user);
  const messageKey = isRental ? 'immobot.desktop.contactMessage.rental' : 'immobot.desktop.contactMessage.purchase';
  const evalModelLabel = eval_ ? [eval_.provider === 'codex' ? 'Codex' : eval_.provider, eval_.model].filter(Boolean).join(' · ') : '';
  const cachedInquiryMessage = personalizedInquiryEnabled ? (safeListing.rentalInquiryMessage || '') : '';
  const standardMessage = isRental
    ? (ctx.user?.default_reply_message || 'Sehr geehrte Damen und Herren,\n\nich habe Interesse an dieser Mietwohnung und möchte gerne einen Besichtigungstermin vereinbaren.')
    : 'Sehr geehrte Damen und Herren,\n\nich habe Interesse an dieser Immobilie und möchte gerne einen Besichtigungstermin vereinbaren.';
  const defaultMessage = cachedInquiryMessage || standardMessage;
  const [contactMessage, setContactMessage] = React.useState(() => personalizedInquiryEnabled ? cachedInquiryMessage : ((isRental ? null : localStorage.getItem(messageKey)) || standardMessage));
  const [contactLoading, setContactLoading] = React.useState(() => personalizedInquiryEnabled && !cachedInquiryMessage);
  React.useEffect(() => {
    if (isRental && personalizedInquiryEnabled) return;
    localStorage.setItem(messageKey, contactMessage);
  }, [isRental, personalizedInquiryEnabled, messageKey, contactMessage]);
  React.useEffect(() => {
    if (!isRental || personalizedInquiryEnabled) return;
    setContactLoading(false);
    setContactMessage(localStorage.getItem(messageKey) || defaultMessage);
  }, [isRental, personalizedInquiryEnabled, messageKey, defaultMessage]);
  React.useEffect(() => {
    if (!isRental || !personalizedInquiryEnabled || !taskId || !adId || !ctx.inquiryPreview) return undefined;
    if (cachedInquiryMessage) {
      setContactMessage(cachedInquiryMessage);
      setContactLoading(false);
      return undefined;
    }
    let active = true;
    setContactMessage('');
    setContactLoading(true);
    ctx.inquiryPreview(taskId, adId)
      .then(result => {
        if (active && result?.message) setContactMessage(result.message);
      })
      .catch(() => {
        if (active) setContactMessage(defaultMessage);
      })
      .finally(() => {
        if (active) setContactLoading(false);
      });
    return () => {
      active = false;
    };
  }, [isRental, personalizedInquiryEnabled, taskId, adId, ctx.inquiryPreview, defaultMessage, cachedInquiryMessage]);
  React.useEffect(() => {
    if (lightboxIndex == null) return undefined;
    const onKey = (event) => {
      if (event.key === 'Escape') setLightboxIndex(null);
      if (event.key === 'ArrowRight') setLightboxIndex(i => (i + 1) % photos.length);
      if (event.key === 'ArrowLeft') setLightboxIndex(i => (i + photos.length - 1) % photos.length);
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [lightboxIndex, photos.length]);
  const copyAndOpenSource = async () => {
    if (contactLoading) return;
    const text = contactMessage || defaultMessage;
    try {
      await navigator.clipboard?.writeText(text);
    } catch (error) {
      const ta = document.createElement('textarea');
      ta.value = text;
      ta.style.position = 'fixed';
      ta.style.left = '-9999px';
      document.body.appendChild(ta);
      ta.select();
      document.execCommand('copy');
      document.body.removeChild(ta);
    }
    await ctx.contactAd?.(taskId, adId);
    if (safeListing.sourceUrl) window.open(safeListing.sourceUrl, '_blank', 'noopener');
  };
  const openInquirySettings = () => {
    sessionStorage.setItem('immobotScrollInquiryProfile', '1');
    onNav('profile');
  };
  const generatingText = personalizedInquiryEnabled && (contactLoading || contactMessage === '');

  if (!l) return <DesktopEmpty active={active} onNav={onNav} ctx={ctx} title="Inserat nicht gefunden" icon={<I.home />} />;

  return (
    <DesktopFrame url={`app.immobot.de/inserat/${l.id}`}>
      <Sidebar active={detailActive} notifBadge={ctx.notifBadge || 0} onNav={onNav} user={ctx.user} taskLimit={ctx.taskLimit} />
      <main style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0, background: 'var(--bg)' }}>
        <DTopBar
	          crumb={[isRental ? 'Mieten' : 'Kaufen', l.city || 'Objekte', 'Inserat']}
          title={l.title}
          subtitle={<span>
            <I.pin style={{ width: 12, height: 12, display: 'inline', verticalAlign: -1 }} /> {l.address}, {l.plz} {l.city} · {l.district} · inseriert {fmtRelative(l.posted)}
          </span>}
		          actions={<>
		            <DButton kind="icon" icon={isFav ? <I.heartFill /> : <I.heart />} onClick={() => ctx.toggleFav?.(l.id)} title={isFav ? 'Gemerkt' : 'Merken'} />
		            <DButton kind="icon" icon={<I.share />} onClick={() => ctx.toggleSharing?.(taskId, adId)} title="Teilen" />
			            <DButton kind="primary" size="sm" icon={<I.message />} onClick={copyAndOpenSource} disabled={generatingText}>Text kopieren & öffnen</DButton>
		          </>}
		          {...topBarProps}
		          showSearch={false}
		          compactActions
		        />

        <div className="desktop-scroll" style={{ flex: 1, overflowY: 'auto' }}>
          <div style={{ padding: '24px 32px 40px', display: 'grid', gridTemplateColumns: '1.65fr 1fr', gap: 22 }}>
            {/* LEFT — gallery + body */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
              {/* Gallery */}
              <div>
                <div style={{
                  display: 'grid', gridTemplateColumns: '2fr 1fr 1fr', gridTemplateRows: '180px 180px',
                  gap: 6, borderRadius: 14, overflow: 'hidden',
                }}>
	                  <button type="button" className="photo" onClick={() => setLightboxIndex(0)} style={{ gridRow: '1 / 3', backgroundImage: `url(${photos[0]})`, position: 'relative', border: 0, cursor: 'zoom-in', textAlign: 'left' }}>
	                    <div style={{ position: 'absolute', top: 12, left: 12, display: 'flex', gap: 6 }}>
	                      <PlatformBadge platform={l.platform} size="lg" />
	                      {l.provisionsfrei && <DChip tone="success">✓ Provisionsfrei</DChip>}
	                      {!isRental && <DChip tone="ghost">Denkmal</DChip>}
	                    </div>
	                  </button>
	                  <button type="button" className="photo" onClick={() => setLightboxIndex(1)} style={{ backgroundImage: `url(${photos[1]})`, border: 0, cursor: 'zoom-in' }} />
	                  <button type="button" className="photo" onClick={() => setLightboxIndex(2)} style={{ backgroundImage: `url(${photos[2]})`, border: 0, cursor: 'zoom-in' }} />
	                  <button type="button" className="photo" onClick={() => setLightboxIndex(1)} style={{ backgroundImage: `url(${photos[1]})`, border: 0, cursor: 'zoom-in' }} />
	                  <button type="button" className="photo" onClick={() => setLightboxIndex(3)} style={{ backgroundImage: `url(${photos[3]})`, position: 'relative', border: 0, cursor: 'zoom-in' }}>
	                    <div style={{
	                      position: 'absolute', inset: 0, background: 'rgba(0,0,0,.45)',
	                      display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column',
	                      color: '#fff',
	                    }}>
	                      <I.grid style={{ width: 22, height: 22, color: '#fff' }} />
	                      <span style={{ fontSize: 13, fontWeight: 600, marginTop: 4 }}>Fotos ansehen</span>
	                    </div>
	                  </button>
	                </div>
	              </div>

              {/* Key specs strip */}
              <div>
                <div style={{ display: 'flex', gap: 16, alignItems: 'center', fontSize: 13, color: 'var(--ink-2)' }}>
                  <SpecInline icon={<I.ruler />} label={fmtArea(l.area)} />
                  <SpecInline icon={<I.bed />} label={`${l.rooms} Zimmer`} />
                  <SpecInline icon={<I.calendar />} label={`Baujahr ${l.baujahr}`} />
                  <SpecInline icon={<I.home />} label={l.floor} />
                  <SpecInline icon={<I.zap />} label={`Energie ${l.energieklasse}`} />
                </div>
              </div>

	              {/* Specs grid */}
	              <DCard padding={0}>
	                <div style={{ padding: '16px 22px 12px' }}>
	                  <h3 style={{ margin: 0, fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 20, letterSpacing: -0.01 }}>Kennzahlen</h3>
	                </div>
                <div style={{
                  display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)',
                  borderTop: '1px solid var(--border)',
                }}>
		                  <SpecCell label={isRental ? 'Miete pro m²' : 'Preis pro m²'} value={l.area ? `${Math.round(l.price/l.area).toLocaleString('de-DE')} €` : '—'} />
	                  <SpecCell label={isRental ? 'Nebenkosten' : 'Hausgeld'} value={l.nebenkosten ? `${l.nebenkosten} €/Mt.` : '—'} sep />
	                  <SpecCell label="Verfügbar" value="sofort" sep />
	                  <SpecCell label="Heizung" value="Zentralheizung" sep />
	                  <SpecCell label={isRental ? 'Kaution' : 'Stellplatz'} value={isRental ? 'nach Vereinbarung' : 'Tiefgarage'} top />
	                  <SpecCell label="Aufzug" value={(l.features || []).join(' ').toLowerCase().includes('aufzug') ? 'vorhanden' : 'prüfen'} top sep />
	                  <SpecCell label="Geschoss" value={`${l.floor} (von 4)`} top sep />
	                  <SpecCell label="Objekt-ID" value={String(l.id).toUpperCase()} mono top sep />
	                </div>
	              </DCard>

	              {/* Description */}
	              <DCard padding={22}>
	                <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 12 }}>
	                  <h3 style={{ margin: 0, fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 20, letterSpacing: -0.01 }}>Beschreibung</h3>
	                  <span style={{ fontSize: 11, color: 'var(--ink-muted)' }}>Quelle: {l.platform === 'immoscout24' ? 'ImmoScout24' : 'Kleinanzeigen'}</span>
	                </div>
	                <p style={{ margin: 0, fontSize: 14, lineHeight: 1.7, color: 'var(--ink-2)', textWrap: 'pretty', maxWidth: 720 }}>
	                  {l.description}
	                </p>

	                <div className="hairline" style={{ margin: '22px 0' }} />

	                <h4 style={{ margin: '0 0 10px', fontSize: 13, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.06, color: 'var(--ink-muted)' }}>Ausstattung</h4>
	                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
	                  {(l.features || []).map(f => (
	                    <span key={f} style={{
	                      padding: '6px 12px', borderRadius: 999, fontSize: 12, fontWeight: 500,
	                      background: 'var(--surface-2)', color: 'var(--ink-2)',
	                    }}>{f}</span>
	                  ))}
	                </div>
	              </DCard>

              {/* Source link card */}
              <DCard padding={16} style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
                <div style={{
                  width: 40, height: 40, borderRadius: 10, background: 'var(--info-soft)', color: 'var(--info)',
                  display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                }}><I.link /></div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 600 }}>Original-Inserat</div>
                  <div style={{ fontSize: 11.5, color: 'var(--ink-muted)', fontFamily: 'var(--font-mono)' }}>{l.sourceUrl}</div>
                </div>
                <DButton kind="outline" size="sm" onClick={() => l.sourceUrl && window.open(l.sourceUrl, '_blank', 'noopener')}>
                  Auf {l.platform === 'immoscout24' ? 'Scout24' : 'Kleinanzeigen'} öffnen ↗
                </DButton>
              </DCard>
            </div>

            {/* RIGHT — sticky rail */}
            <aside style={{ display: 'flex', flexDirection: 'column', gap: 18, position: 'sticky', top: 20, alignSelf: 'flex-start' }}>
              {/* Price block */}
              <div style={{
                background: 'var(--ink)', color: '#fff',
                borderRadius: 16, padding: '22px 22px 20px',
              }}>
	                <div style={{ fontSize: 11, fontWeight: 700, color: 'rgba(255,255,255,.6)', letterSpacing: 0.08, textTransform: 'uppercase' }}>
	                  {isRental ? 'Mietpreis' : 'Kaufpreis'}
	                </div>
	                <div style={{
	                  fontFamily: 'var(--font-display)', fontSize: 44, fontWeight: 500, marginTop: 8, letterSpacing: -0.02,
	                }}>{fmtPrice(l.price)}{isRental ? <span style={{ fontSize: 18, marginLeft: 6, color: 'rgba(255,255,255,.7)', fontFamily: 'var(--font-sans)' }}>/Mt.</span> : null}</div>
	                <div style={{ fontSize: 12.5, color: 'rgba(255,255,255,.7)', marginTop: 6 }}>
	                  {l.pricePerSqm ? Number(l.pricePerSqm).toLocaleString('de-DE') : (l.area ? Math.round(l.price / l.area).toLocaleString('de-DE') : '—')} €/m² · {isRental ? 'Mietangebot' : (l.provisionsfrei ? 'provisionsfrei' : 'Provision prüfen')}
	                </div>

	                <div style={{ marginTop: 16, paddingTop: 16, borderTop: '1px solid rgba(255,255,255,.12)', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
	                  {isRental ? (
	                    <>
	                      <MiniMetric label="Kaution" value={fmtPriceShort(l.price * 3)} />
	                      <MiniMetric label="Warmmiete" value={l.nebenkosten ? fmtPriceShort(l.price + l.nebenkosten) : fmtPriceShort(l.price)} />
	                      <MiniMetric label="Nebenkosten" value={l.nebenkosten ? `${l.nebenkosten} €/Mt.` : 'prüfen'} />
	                      <MiniMetric label="Kontakt" value="Quelle öffnen" good />
	                    </>
	                  ) : (
	                    <>
	                      <MiniMetric label="Anzahlung 20%" value={fmtPriceShort(l.price * 0.2)} />
	                      <MiniMetric label="Rate (bei 3,8%)" value="≈ 1.984 €/Mt." />
	                      <MiniMetric label="Nebenkosten" value={fmtPriceShort(l.price * 0.09)} sub="≈ 9% Kauf" />
	                      <MiniMetric label="Brutto-Rendite" value="3,8% p.a." good />
	                    </>
	                  )}
	                </div>
	              </div>

              {/* AI eval card */}
              {eval_ ? (
                <div style={{
                  background: 'linear-gradient(140deg, var(--primary-soft) 0%, #FBF6E6 100%)',
                  border: '1px solid #EFE0BA', borderRadius: 16, padding: 18,
                }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
                    <DRing score={eval_.score} size={68} stroke={6} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--primary-ink)', letterSpacing: 0.08, textTransform: 'uppercase' }}>
                        KI-Bewertung
                      </div>
                      <div style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 500, color: 'var(--ink)', letterSpacing: -0.01, marginTop: 2 }}>
                        {eval_.recommendation}
                      </div>
                      <div style={{ fontSize: 11.5, color: 'var(--primary-ink)', opacity: .8, marginTop: 2 }}>
                        Note {eval_.grade} · {eval_.score}/100{evalModelLabel ? ` · ${evalModelLabel}` : ''}
                      </div>
                    </div>
                  </div>
                  <p style={{
                    margin: '14px 0 0', fontSize: 12.5, color: 'var(--ink-2)',
                    lineHeight: 1.55, textWrap: 'pretty',
                  }}>{eval_.summary}</p>
                  <button type="button" onClick={() => onOpenAI(l.id)} style={{
                    marginTop: 14, width: '100%', padding: '11px 12px', borderRadius: 10,
                    background: 'var(--ink)', color: '#fff', border: 0, cursor: 'pointer',
                    fontFamily: 'var(--font-sans)', fontSize: 13, fontWeight: 600,
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
                  }}>Vollständige Analyse <I.chevR style={{ width: 14, height: 14 }} /></button>
                </div>
              ) : (
                <DCard padding={18}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                    <span style={{ width: 40, height: 40, borderRadius: 10, background: 'var(--primary-soft)', color: 'var(--primary)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
                      <I.spark />
                    </span>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 13.5, fontWeight: 800 }}>Noch nicht bewertet</div>
                      <div style={{ fontSize: 11.5, color: 'var(--ink-muted)', marginTop: 2 }}>Starten Sie eine KI-Analyse für dieses Objekt.</div>
                    </div>
                  </div>
                  <button type="button" onClick={() => ctx.evaluateAd?.(taskId, adId)} style={{
                    marginTop: 14, width: '100%', padding: '11px 12px', borderRadius: 10,
                    background: 'var(--primary)', color: '#fff', border: 0, cursor: 'pointer',
                    fontFamily: 'var(--font-sans)', fontSize: 13, fontWeight: 600,
                  }}>KI-Analyse starten</button>
                </DCard>
              )}

              {/* Contact block */}
              <DCard padding={18}>
                <h3 style={{ margin: '0 0 12px', fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 18, letterSpacing: -0.01 }}>
                  Anbieter
                </h3>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14 }}>
                  <div style={{
                    width: 44, height: 44, borderRadius: 999,
                    background: 'linear-gradient(135deg, #C9B481, #8D704A)',
                    color: '#fff', fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 500,
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                  }}>A</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13.5, fontWeight: 700 }}>Anbieter</div>
                    <div style={{ fontSize: 11.5, color: 'var(--ink-muted)' }}>{l.platform === 'immoscout24' ? 'ImmoScout24' : 'Kleinanzeigen'} · Original-Inserat</div>
                  </div>
                </div>
                <textarea
	                  value={generatingText ? 'Text wird generiert' : (contactMessage || defaultMessage)}
	                  onChange={event => setContactMessage(event.target.value)}
                    disabled={generatingText}
                  style={{
                    width: '100%', minHeight: 92, padding: '10px 12px', fontSize: 12.5, borderRadius: 10,
                    background: 'var(--surface-2)', border: '1px solid var(--border)', resize: 'none',
                    fontFamily: 'var(--font-sans)', color: 'var(--ink)', outline: 'none', lineHeight: 1.5,
                    boxSizing: 'border-box', opacity: generatingText ? .72 : 1,
                  }}
                />
	                <button type="button" onClick={copyAndOpenSource} disabled={generatingText} style={{
	                  marginTop: 10, width: '100%', padding: '11px 12px', borderRadius: 10,
	                  background: 'var(--primary)', color: '#fff', border: 0, cursor: generatingText ? 'not-allowed' : 'pointer',
	                  fontFamily: 'var(--font-sans)', fontSize: 13, fontWeight: 600,
                    opacity: generatingText ? .55 : 1,
	                }}>Text kopieren & Inserat öffnen</button>
                {isRental && (
                  <button type="button" onClick={openInquirySettings} disabled={generatingText} style={{
                    marginTop: 8, width: '100%', padding: '10px 12px', borderRadius: 10,
                    background: 'var(--surface)', color: 'var(--ink)', border: '1px solid var(--border)', cursor: generatingText ? 'not-allowed' : 'pointer',
                    fontFamily: 'var(--font-sans)', fontSize: 12.5, fontWeight: 700,
                    opacity: generatingText ? .55 : 1,
                  }}>Anfrageprofil bearbeiten</button>
                )}
	                <div style={{ marginTop: 10, fontSize: 11, color: 'var(--ink-muted)', textAlign: 'center' }}>
	                  Die Nachricht wird kopiert. Der Versand erfolgt bewusst auf der Quellplattform.
	                </div>
              </DCard>
            </aside>
          </div>
        </div>
	      </main>
	      {lightboxIndex != null && (
	        <div
	          onClick={() => setLightboxIndex(null)}
	          style={{
	            position: 'fixed', inset: 0, zIndex: 1000,
	            background: 'rgba(17,14,10,.88)',
	            display: 'grid', gridTemplateColumns: '72px 1fr 72px',
	            alignItems: 'center', gap: 12, padding: 28,
	          }}
	        >
	          <button type="button" onClick={event => { event.stopPropagation(); setLightboxIndex(i => (i + photos.length - 1) % photos.length); }} style={lightboxBtnStyle('left')} aria-label="Vorheriges Foto">
	            <I.chevR style={{ width: 24, height: 24, transform: 'rotate(180deg)' }} />
	          </button>
	          <div onClick={event => event.stopPropagation()} style={{ height: '100%', minHeight: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 14 }}>
	            <img src={photos[lightboxIndex]} alt={l.title} style={{ maxWidth: '100%', maxHeight: 'calc(100vh - 130px)', objectFit: 'contain', borderRadius: 12, boxShadow: '0 30px 80px rgba(0,0,0,.38)' }} />
	            <div style={{ display: 'flex', alignItems: 'center', gap: 12, color: '#fff' }}>
	              <span style={{ fontSize: 13, fontWeight: 800 }}>{lightboxIndex + 1} / {photos.length}</span>
	              <button type="button" onClick={() => setLightboxIndex(null)} style={{ border: '1px solid rgba(255,255,255,.35)', background: 'rgba(255,255,255,.12)', color: '#fff', borderRadius: 9, padding: '8px 12px', cursor: 'pointer', fontWeight: 800 }}>
	                Schließen
	              </button>
	            </div>
	          </div>
	          <button type="button" onClick={event => { event.stopPropagation(); setLightboxIndex(i => (i + 1) % photos.length); }} style={lightboxBtnStyle('right')} aria-label="Nächstes Foto">
	            <I.chevR style={{ width: 24, height: 24 }} />
	          </button>
	        </div>
	      )}
	    </DesktopFrame>
	  );
	}

function lightboxBtnStyle(side) {
  return {
    width: 52,
    height: 52,
    borderRadius: 999,
    border: '1px solid rgba(255,255,255,.26)',
    background: 'rgba(255,255,255,.13)',
    color: '#fff',
    cursor: 'pointer',
    display: 'inline-flex',
    alignItems: 'center',
    justifyContent: 'center',
    justifySelf: side === 'left' ? 'end' : 'start',
  };
}

function SpecInline({ icon, label }) {
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
      {React.cloneElement(icon, { width: 15, height: 15, style: { opacity: .7 } })}
      <span style={{ fontWeight: 500 }}>{label}</span>
    </span>
  );
}

function SpecCell({ label, value, mono, top, sep }) {
  return (
    <div style={{
      padding: '14px 20px',
      borderTop: top ? '1px solid var(--border)' : 'none',
      borderLeft: sep ? '1px solid var(--border)' : 'none',
    }}>
      <div style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--ink-muted)', letterSpacing: 0.06, textTransform: 'uppercase' }}>{label}</div>
      <div style={{
        marginTop: 5, fontSize: 14.5, fontWeight: 700, color: 'var(--ink)',
        fontFamily: mono ? 'var(--font-mono)' : 'var(--font-sans)',
      }}>{value}</div>
    </div>
  );
}

function MiniMetric({ label, value, sub, good }) {
  return (
    <div>
      <div style={{ fontSize: 10.5, color: 'rgba(255,255,255,.55)', letterSpacing: 0.05, textTransform: 'uppercase', fontWeight: 600 }}>{label}</div>
      <div style={{
        marginTop: 4, fontSize: 15, fontWeight: 700, color: good ? '#9CE0B5' : '#fff',
        fontVariantNumeric: 'tabular-nums',
      }}>{value}</div>
      {sub && <div style={{ fontSize: 10, color: 'rgba(255,255,255,.5)' }}>{sub}</div>}
    </div>
  );
}

// ─── Desktop Score Ring (compact) ──────────────────────────────────────
function DRing({ score, size = 72, stroke = 6 }) {
  const r = (size - stroke) / 2;
  const c = 2 * Math.PI * r;
  const pct = score / 100;
  const color = score >= 80 ? '#2F8F5A' : score >= 60 ? '#C28428' : '#C8331C';
  return (
    <div style={{ position: 'relative', width: size, height: size, flexShrink: 0 }}>
      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ transform: 'rotate(-90deg)' }}>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="rgba(0,0,0,.08)" strokeWidth={stroke} />
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke={color} strokeWidth={stroke}
          strokeDasharray={c} strokeDashoffset={c * (1 - pct)} strokeLinecap="round" />
      </svg>
      <div style={{
        position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontFamily: 'var(--font-display)', fontSize: size * 0.36, fontWeight: 500, letterSpacing: -0.02, color: 'var(--ink)',
      }}>{score}</div>
    </div>
  );
}

// ─── AI EVAL DESKTOP ───────────────────────────────────────────────────
function AIEvalDesktop({ active = 'kauf', onNav = () => {}, id = null, ctx = {}, onOpenDetail = () => {}, topBarProps = {} } = {}) {
  const l = desktopFindListing(ctx, id) || (!id ? desktopListings(ctx).find(x => desktopEvaluationForListing(ctx, x)) : null);
  if (!l) return <DesktopEmpty active={active} onNav={onNav} ctx={ctx} title="Keine Analyse verfügbar" icon={<I.spark />} />;
  const e = desktopEvaluationForListing(ctx, l);
  if (!e) return <DesktopEmpty active={active} onNav={onNav} ctx={ctx} title="Keine KI-Analyse verfügbar" subtitle="Für dieses Objekt wurde noch keine Bewertung gespeichert." icon={<I.spark />} />;
  const photos = desktopPhotos(l);
  const scoreColor = e.score >= 80 ? '#2F8F5A' : e.score >= 60 ? '#C28428' : '#C8331C';
  const adId = l.adId || l.id;
  const taskId = l.task_id || l.searchId;
  const detailActive = l.type === 'miete' ? 'miete' : active;
  const kpis = desktopEvalArray(e.kpis);
  const scorecard = desktopEvalArray(e.scorecard);
  const strengths = desktopEvalArray(e.strengths, e.key_strengths);
  const risks = desktopEvalArray(e.risks, e.key_risks);
  const assumptions = desktopEvalArray(e.assumptions);
  const imageObservations = desktopEvalArray(e.image_observations, e.imageObservations);
  const modelLabel = [e.provider === 'codex' ? 'Codex' : e.provider, e.model].filter(Boolean).join(' · ') || 'KI-Investitionsanalyse';

  return (
    <DesktopFrame url={`app.immobot.de/inserat/${l.id}/ki-analyse`}>
	      <Sidebar active={detailActive} notifBadge={ctx.notifBadge || 0} onNav={onNav} user={ctx.user} taskLimit={ctx.taskLimit} />
      <main style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0, background: 'var(--bg)' }}>
        <DTopBar
	          crumb={[l.type === 'miete' ? 'Mieten' : 'Kaufen', 'Inserat', 'KI-Analyse']}
          title="KI-Investitionsanalyse"
          subtitle={<span>
            {l.title} · bewertet am {fmtDateTime(e.evaluatedAt)} · {modelLabel}
          </span>}
	          actions={<>
	            <DButton kind="ghost" icon={<I.refresh />} onClick={() => ctx.evaluateAd?.(taskId, adId)}>Neu bewerten</DButton>
	            <DButton kind="ghost" icon={<I.share />} onClick={() => ctx.toggleSharing?.(taskId, adId)}>Teilen</DButton>
	            <DButton kind="primary" icon={<I.download />} onClick={() => window.print()}>PDF</DButton>
	          </>}
	          {...topBarProps}
	        />

        <div className="desktop-scroll" style={{ flex: 1, overflowY: 'auto' }}>
          <div style={{ padding: '24px 32px 40px', display: 'flex', flexDirection: 'column', gap: 22 }}>

            {/* Hero score banner */}
            <div style={{
              background: `linear-gradient(135deg, ${scoreColor}12 0%, ${scoreColor}04 100%)`,
              border: `1px solid ${scoreColor}30`, borderRadius: 18, padding: '26px 28px',
              display: 'grid', gridTemplateColumns: '160px 1fr auto', gap: 28, alignItems: 'center',
            }}>
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                <DRing score={e.score} size={140} stroke={9} />
                <div style={{
                  marginTop: 10, padding: '4px 12px', borderRadius: 999,
                  background: scoreColor, color: '#fff', fontSize: 11, fontWeight: 800, letterSpacing: 0.06,
                }}>NOTE {e.grade}</div>
              </div>
              <div>
                <div style={{ fontSize: 11, fontWeight: 700, color: scoreColor, letterSpacing: 0.08, textTransform: 'uppercase' }}>
                  Empfehlung
                </div>
                <h2 style={{
                  margin: '6px 0 12px', fontFamily: 'var(--font-display)', fontWeight: 500,
                  fontSize: 38, lineHeight: 1.1, letterSpacing: -0.02,
                }}>{e.recommendation}</h2>
                <p style={{
                  margin: 0, fontSize: 14.5, color: 'var(--ink-2)', lineHeight: 1.6,
                  maxWidth: 640, textWrap: 'pretty',
                }}>{e.summary}</p>
              </div>
              <div style={{
                background: 'var(--surface)', border: '1px solid var(--border)',
                borderRadius: 12, padding: 14, width: 200, display: 'flex', gap: 12, alignItems: 'center',
              }}>
                <div className="photo" style={{
                  width: 50, height: 50, borderRadius: 8, flexShrink: 0,
                  backgroundImage: `url(${photos[0]})`,
                }} />
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 11, color: 'var(--ink-muted)' }}>Objekt</div>
	                  <button type="button" onClick={() => onOpenDetail(l.id)} style={{ display: 'block', padding: 0, border: 0, background: 'transparent', fontSize: 12.5, fontWeight: 700, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', cursor: 'pointer', color: 'var(--ink)', textAlign: 'left', width: '100%' }}>{l.title}</button>
                  <div style={{ fontSize: 11, color: 'var(--ink-muted)', marginTop: 2 }}>{fmtPriceShort(l.price)} · {l.district}</div>
                </div>
              </div>
            </div>

            {/* KPIs */}
            <div>
              <DSectionHead title="Kennzahlen" subtitle="Modell-Schätzungen, basierend auf öffentlichen Daten" />
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 12 }}>
                {kpis.map((k, i) => (
                  <DCard key={i} padding={16} style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                    <div style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--ink-muted)', letterSpacing: 0.05, textTransform: 'uppercase' }}>
                      {k.label}
                    </div>
                    <div style={{
                      fontFamily: 'var(--font-display)', fontSize: 24, fontWeight: 500,
                      marginTop: 6, letterSpacing: -0.01, fontVariantNumeric: 'tabular-nums',
                    }}>{k.value}</div>
                    {k.delta && (
                      <div style={{
                        fontSize: 11, marginTop: 2,
                        color: k.positive ? 'var(--success)' : 'var(--ink-muted)', fontWeight: 500,
                      }}>{k.positive && '▲ '}{k.delta}</div>
                    )}
                  </DCard>
                ))}
              </div>
            </div>

            {/* Scorecard + Comparables / Strengths + Risks */}
            <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 18 }}>
              <DCard padding={22}>
                <h3 style={{ margin: '0 0 6px', fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 20, letterSpacing: -0.01 }}>Scorecard</h3>
                <div style={{ fontSize: 12, color: 'var(--ink-muted)', marginBottom: 18 }}>
                  Gewichteter Mittelwert: <strong style={{ color: 'var(--ink)' }}>{e.score}/100</strong>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                  {scorecard.map((s, i) => (
                    <ScoreBar key={i} {...s} />
                  ))}
                </div>
              </DCard>

              <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
                {strengths.length > 0 && <DCard padding={20}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
                    <span style={{
                      width: 24, height: 24, borderRadius: 7, background: 'var(--success-soft)', color: 'var(--success)',
                      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                    }}><I.check style={{ width: 14, height: 14 }} /></span>
                    <h3 style={{ margin: 0, fontSize: 14, fontWeight: 700, color: 'var(--success)', letterSpacing: 0.04, textTransform: 'uppercase' }}>Stärken</h3>
                  </div>
                  <DesktopEvalList items={strengths} tone="success" />
                </DCard>}

                {risks.length > 0 && <DCard padding={20}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
                    <span style={{
                      width: 24, height: 24, borderRadius: 7, background: 'var(--danger-soft)', color: 'var(--danger)',
                      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                    }}><I.warn style={{ width: 13, height: 13 }} /></span>
                    <h3 style={{ margin: 0, fontSize: 14, fontWeight: 700, color: 'var(--danger)', letterSpacing: 0.04, textTransform: 'uppercase' }}>Risiken</h3>
                  </div>
                  <DesktopEvalList items={risks} tone="danger" />
                </DCard>}
              </div>
            </div>

            {e.analysis && (
              <DCard padding={22}>
                <h3 style={{ margin: '0 0 12px', fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 20, letterSpacing: -0.01 }}>Vollständige Analyse</h3>
                <div style={{ fontSize: 13.5, color: 'var(--ink-2)', lineHeight: 1.65, whiteSpace: 'pre-line', maxWidth: 920 }}>
                  {desktopEvalText(e.analysis)}
                </div>
              </DCard>
            )}

            {(imageObservations.length > 0 || assumptions.length > 0) && (
              <div style={{ display: 'grid', gridTemplateColumns: imageObservations.length > 0 && assumptions.length > 0 ? '1fr 1fr' : '1fr', gap: 18 }}>
                {imageObservations.length > 0 && (
                  <DCard padding={20}>
                    <h3 style={{ margin: '0 0 12px', fontSize: 14, fontWeight: 800, color: 'var(--ink)', letterSpacing: 0.04, textTransform: 'uppercase' }}>Bildanalyse</h3>
                    <DesktopEvalList items={imageObservations} />
                  </DCard>
                )}
                {assumptions.length > 0 && (
                  <DCard padding={20}>
                    <h3 style={{ margin: '0 0 12px', fontSize: 14, fontWeight: 800, color: 'var(--ink)', letterSpacing: 0.04, textTransform: 'uppercase' }}>Annahmen</h3>
                    <DesktopEvalList items={assumptions} />
                  </DCard>
                )}
              </div>
            )}

            {/* Comparables */}
            {e.comparables && e.comparables.length > 0 && <DCard padding={0}>
              <div style={{ padding: '18px 22px 14px' }}>
                <h3 style={{ margin: 0, fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 20, letterSpacing: -0.01 }}>Vergleichsobjekte in {l.district}</h3>
                <div style={{ fontSize: 12, color: 'var(--ink-muted)', marginTop: 2 }}>
                  Verkäufe der letzten 90 Tage im 500m-Radius
                </div>
              </div>
              <div style={{
                display: 'grid', gridTemplateColumns: '2.2fr 1fr 1fr 1fr 1fr 1fr',
                fontSize: 10.5, fontWeight: 700, letterSpacing: 0.05, textTransform: 'uppercase',
                color: 'var(--ink-muted)', padding: '8px 22px', background: 'var(--surface-2)',
                borderTop: '1px solid var(--border)', borderBottom: '1px solid var(--border)',
              }}>
                <span>Adresse</span>
                <span style={{ textAlign: 'right' }}>Preis</span>
                <span style={{ textAlign: 'right' }}>Fläche</span>
                <span style={{ textAlign: 'right' }}>€/m²</span>
                <span style={{ textAlign: 'right' }}>vs. dieses</span>
                <span style={{ textAlign: 'right' }}>Entfernung</span>
              </div>
              {e.comparables && e.comparables.map((c, i) => {
                const ppm = Math.round(c.price / c.area);
                const thisPpm = Math.round(l.price / l.area);
                const delta = ((ppm - thisPpm) / thisPpm * 100).toFixed(1);
                return (
                  <div key={i} style={{
                    display: 'grid', gridTemplateColumns: '2.2fr 1fr 1fr 1fr 1fr 1fr',
                    padding: '12px 22px', fontSize: 13, alignItems: 'center',
                    borderBottom: i < e.comparables.length - 1 ? '1px solid var(--border)' : 'none',
                  }}>
                    <span style={{ fontWeight: 600 }}>{c.addr}</span>
                    <span style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>{fmtPriceShort(c.price)}</span>
                    <span style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums', color: 'var(--ink-muted)' }}>{c.area} m²</span>
                    <span style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums', fontWeight: 700 }}>{ppm.toLocaleString('de-DE')} €</span>
                    <span style={{ textAlign: 'right', color: +delta > 0 ? 'var(--success)' : 'var(--danger)', fontWeight: 600, fontVariantNumeric: 'tabular-nums' }}>
                      {+delta > 0 ? '+' : ''}{delta}%
                    </span>
                    <span style={{ textAlign: 'right', color: 'var(--ink-muted)', fontVariantNumeric: 'tabular-nums' }}>{c.dist}</span>
                  </div>
                );
              })}
            </DCard>}

            {/* Disclaimer */}
            <div style={{
              padding: 14, borderRadius: 10, background: 'var(--surface-2)',
              fontSize: 11.5, color: 'var(--ink-muted)', lineHeight: 1.55,
            }}>
              <strong>Hinweis:</strong> Die KI-Analyse basiert auf öffentlich verfügbaren Daten und stellt keine Anlageberatung dar. Werte sind Schätzungen, keine Garantien. Vor einem Kauf empfehlen wir Beratung durch eine:n Sachverständige:n.
            </div>
          </div>
        </div>
      </main>
    </DesktopFrame>
  );
}

Object.assign(window, { DetailDesktop, AIEvalDesktop, DRing });
