// screens-detail.jsx — Listing detail + AI evaluation full screen

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

// ─── LISTING DETAIL ────────────────────────────────────────────────────
function ListingDetailScreen({ ctx, id, publicMode = false }) {
  const {
    listings = [], evaluations = {}, navigate = () => {}, back = () => { window.location.href = '/'; },
    favs = new Set(), toggleFav = () => {}, contactAd = async () => {}, toggleSharing = () => {},
    evaluateAd = () => {}, scrapeAdDetails = () => {}, inquiryPreview = null, busy = false,
  } = ctx;
  const idKey = String(id ?? '');
  const investorItems = [
    ...(ctx.investor?.evaluations || []),
    ...(ctx.investor?.compare?.items || []),
    ...(ctx.portfolioAnalytics?.items || []),
  ];
  const investorItem = investorItems.find(item => {
    const li = item?.listing || {};
    return String(item?.adId ?? '') === idKey
      || String(item?.id ?? '') === idKey
      || String(li.id ?? '') === idKey
      || String(li.adId ?? '') === idKey;
  });
  const l = listings.find(x => String(x.id) === idKey || String(x.adId) === idKey) || investorItem?.listing;
  const eval_ = evaluations[idKey] || evaluations[id] || window.AI_EVALS?.[idKey] || window.AI_EVALS?.[id] || investorItem?.evaluation;
  const [shared, setShared] = React.useState(!!l?.sharingEnabled);
  const [shareUrl, setShareUrl] = React.useState(l?.shareUrl || null);
  const [shareOpen, setShareOpen] = React.useState(false);
  const [contactOpen, setContactOpen] = React.useState(false);
  const isKauf = l?.type === 'kauf';
  const personalizedInquiryEnabled = !isKauf && mobileRentalPersonalizationEnabled(ctx.user);
  const messageKey = `immobot.mobile.contactMessage.${isKauf ? 'purchase' : 'rental'}`;
  const cachedInquiryMessage = (!isKauf && personalizedInquiryEnabled) ? (l?.rentalInquiryMessage || '') : '';
  const standardMessage = isKauf
    ? 'Sehr geehrte Damen und Herren,\n\nich habe Interesse an dieser Immobilie und möchte gerne einen Besichtigungstermin vereinbaren.'
    : (ctx.user?.default_reply_message || 'Sehr geehrte Damen und Herren,\n\nich habe Interesse an dieser Mietwohnung und möchte gerne einen Besichtigungstermin vereinbaren.');
  const defaultMessage = cachedInquiryMessage || standardMessage;
  const [message, setMessage] = React.useState(() => cachedInquiryMessage || (isKauf ? localStorage.getItem(messageKey) : null) || standardMessage);
  const [previewLoading, setPreviewLoading] = React.useState(false);
  const pricePerArea = l?.pricePerSqm ? `${Number(l.pricePerSqm).toLocaleString('de-DE')} €/m²` : (l?.area ? `${Math.round(l.price / l.area).toLocaleString('de-DE')} €/m²` : '€/m² nicht verfügbar');
  React.useEffect(() => {
    if (!l) return;
    if (!isKauf && personalizedInquiryEnabled) return;
    localStorage.setItem(messageKey, message);
  }, [l, isKauf, personalizedInquiryEnabled, messageKey, message]);
  React.useEffect(() => {
    if (!contactOpen || isKauf || personalizedInquiryEnabled) return;
    setPreviewLoading(false);
    setMessage(localStorage.getItem(messageKey) || defaultMessage);
  }, [contactOpen, isKauf, personalizedInquiryEnabled, messageKey, defaultMessage]);
  React.useEffect(() => {
    setShared(!!l?.sharingEnabled);
    setShareUrl(l?.shareUrl || null);
  }, [l?.id, l?.sharingEnabled, l?.shareUrl]);
  React.useEffect(() => {
    if (!contactOpen || !l || isKauf || !personalizedInquiryEnabled || !inquiryPreview) return undefined;
    if (cachedInquiryMessage) {
      setMessage(cachedInquiryMessage);
      setPreviewLoading(false);
      return undefined;
    }
    let active = true;
    setMessage('');
    setPreviewLoading(true);
    inquiryPreview(l.task_id, l.adId || l.id)
      .then(result => {
        if (active && result?.message) setMessage(result.message);
      })
      .catch(() => {
        if (active) setMessage(defaultMessage);
      })
      .finally(() => {
        if (active) setPreviewLoading(false);
      });
    return () => {
      active = false;
    };
  }, [contactOpen, l?.task_id, l?.adId, l?.id, isKauf, personalizedInquiryEnabled, inquiryPreview, defaultMessage, cachedInquiryMessage]);

  if (!l) return <div style={{ padding: 60 }}>Nicht gefunden</div>;

  const isFav = !publicMode && favs.has(l.id);
  const shareDataFor = (url) => ({
    title: l.title || 'ImmoBot Anzeige',
    text: `Schau dir diese Immobilie an: ${l.title || 'ImmoBot Anzeige'}`,
    url,
  });
  const copyShareLink = async (url) => {
    if (!url) return;
    try {
      await navigator.clipboard?.writeText(url);
      alert('Share-Link wurde kopiert.');
    } catch (error) {
      const input = document.createElement('textarea');
      input.value = url;
      input.style.position = 'fixed';
      input.style.left = '-9999px';
      document.body.appendChild(input);
      input.focus();
      input.select();
      document.execCommand('copy');
      document.body.removeChild(input);
      alert('Share-Link wurde kopiert.');
    }
  };
  const openInquirySettings = () => {
    sessionStorage.setItem('immobotScrollInquiryProfile', '1');
    setContactOpen(false);
    navigate('profile');
  };
  const openContactSheet = () => {
    if (!isKauf && personalizedInquiryEnabled && cachedInquiryMessage) {
      setMessage(cachedInquiryMessage);
      setPreviewLoading(false);
    } else if (!isKauf && personalizedInquiryEnabled && inquiryPreview) {
      setMessage('');
      setPreviewLoading(true);
    } else {
      setPreviewLoading(false);
    }
    setContactOpen(true);
  };
  const nativeShare = async (url) => {
    if (!url || !navigator.share) return false;
    await navigator.share(shareDataFor(url));
    return true;
  };
  const ensureShareUrl = async () => {
    if (shareUrl || l.shareUrl) return shareUrl || l.shareUrl;
    const result = await toggleSharing(l.task_id, l.adId || l.id);
    const url = result.share_url || l.shareUrl || shareUrl;
    setShared(!!result.sharing_enabled);
    setShareUrl(url);
    return url;
  };
  const shareListing = async () => {
    try {
      const alreadyShareable = !!(shareUrl || l.shareUrl);
      const url = await ensureShareUrl();
      if (!url) return;

      if (alreadyShareable) {
        try {
          if (await nativeShare(url)) return;
        } catch (error) {
          if (error?.name === 'AbortError') return;
        }
      }

      setShareOpen(true);
    } catch (error) {
      const url = shareUrl || l.shareUrl;
      if (url) setShareOpen(true);
    }
  };
  const generatingText = previewLoading && personalizedInquiryEnabled && !isKauf;

  return (
    <div style={{ height: '100%', minHeight: 0, position: 'relative', overflow: 'hidden', display: 'flex', flexDirection: 'column', background: 'var(--bg)' }}>
      <div className="phone-scroll" style={{ flex: 1, minHeight: 0, paddingBottom: 0 }}>
        {/* Photo gallery with overlay back */}
        <div style={{ position: 'relative' }}>
          <PhotoSlider key={`detail-${l.id}`} photos={l.photos} height={320} />
          {/* Back / fav buttons */}
          <div style={{ position: 'absolute', top: 56, left: 16, right: 16, zIndex: 10, display: 'flex', justifyContent: 'space-between' }}>
            <button onClick={back} style={{
              width: 40, height: 40, borderRadius: 999, border: 0,
              background: 'rgba(255,255,255,.95)', backdropFilter: 'blur(10px)',
              display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
              color: 'var(--ink)',
            }}><I.chevL /></button>
            {!publicMode && <div style={{ display: 'flex', gap: 8 }}>
              <button onClick={() => toggleFav(l.id)} style={{
                width: 40, height: 40, borderRadius: 999, border: 0,
                background: 'rgba(255,255,255,.95)', backdropFilter: 'blur(10px)',
                display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
                color: isFav ? '#C8331C' : 'var(--ink)',
              }}>{isFav ? <I.heartFill /> : <I.heart />}</button>
              <button onClick={shareListing} style={{
                width: 40, height: 40, borderRadius: 999, border: 0,
                background: 'rgba(255,255,255,.95)', backdropFilter: 'blur(10px)',
                display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
                color: shared ? 'var(--primary)' : 'var(--ink)',
              }}><I.share /></button>
            </div>}
          </div>
        </div>

        {/* Body */}
        <div style={{ padding: '20px 20px 0' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
            <PlatformBadge platform={l.platform} size="lg" />
            {l.provisionsfrei && <span className="chip chip-success" style={{ fontSize: 11 }}>Provisionsfrei</span>}
            <span style={{ fontSize: 11, color: 'var(--ink-faint)', marginLeft: 'auto' }}>{fmtRelative(l.posted)}</span>
          </div>

          <h1 style={{ margin: 0, fontFamily: 'var(--font-display)', fontWeight: 400, fontSize: 30, lineHeight: 1.1, letterSpacing: -0.02, color: 'var(--ink)' }}>
            {l.title}
          </h1>

          <div style={{ fontSize: 14, color: 'var(--ink-muted)', marginTop: 6, display: 'flex', alignItems: 'center', gap: 5 }}>
            <I.pin style={{ width: 14, height: 14 }} />
            {l.address}, {l.plz} {l.city} · {l.district}
          </div>

          {/* Price block */}
          <div style={{
            marginTop: 22, padding: '18px 20px', borderRadius: 16,
            background: 'var(--ink)', color: '#fff',
            display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end',
          }}>
            <div>
              <div style={{ fontSize: 11, color: 'rgba(255,255,255,.6)', textTransform: 'uppercase', letterSpacing: 0.05, fontWeight: 600 }}>
                {isKauf ? 'Kaufpreis' : 'Warmmiete / Monat'}
              </div>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 38, lineHeight: 1, fontWeight: 400, letterSpacing: -0.02, marginTop: 6 }}>
                {fmtPrice(l.price)}
              </div>
              <div style={{ fontSize: 12, color: 'rgba(255,255,255,.6)', marginTop: 6 }}>
                {isKauf
                  ? pricePerArea
                  : `inkl. ${l.nebenkosten} € NK · kalt ${l.kaltmiete} €`
                }
              </div>
            </div>
            {l.aiScore !== null && l.aiScore !== undefined && <ScoreRing score={l.aiScore} size={76} stroke={6} showGrade={false} />}
          </div>

          {/* Specs grid */}
          <div style={{ marginTop: 16, display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 10 }}>
            <Spec icon={<I.ruler />} label="Wohnfläche" value={fmtArea(l.area)} />
            <Spec icon={<I.bed />} label="Zimmer" value={`${l.rooms} Zi.`} />
            <Spec icon={<I.calendar />} label="Baujahr" value={l.baujahr} />
            <Spec icon={<I.zap />} label="Energie" value={`Klasse ${l.energieklasse}`} />
            {isKauf && l.nebenkosten && <Spec icon={<I.euro />} label="Hausgeld" value={`${l.nebenkosten} €/Mt.`} />}
            {!isKauf && <Spec icon={<I.euro />} label="Kaltmiete" value={`${l.kaltmiete} €`} />}
            <Spec icon={<I.home />} label="Etage" value={l.floor} />
          </div>

          {/* AI evaluation card (if available) */}
          {eval_ && (
            <div
              onClick={() => !publicMode && navigate('aiEval', { id: l.id })}
              style={{
                marginTop: 20, padding: 16, borderRadius: 16, cursor: publicMode ? 'default' : 'pointer',
                background: 'linear-gradient(135deg, var(--primary-soft) 0%, #FCEEDE 100%)',
                border: '1px solid var(--primary-soft)',
                display: 'flex', alignItems: 'center', gap: 14,
              }}
            >
              <ScoreRing score={eval_.score} size={64} stroke={6} showGrade={false} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--primary-ink)', textTransform: 'uppercase', letterSpacing: 0.05, marginBottom: 2 }}>
                  KI-Bewertung
                </div>
                <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--ink)', marginBottom: 2 }}>
                  {eval_.recommendation} · Note {eval_.grade}
                </div>
                <div style={{ fontSize: 12, color: 'var(--ink-muted)', lineHeight: 1.4, overflow: 'hidden', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical' }}>
                  {eval_.summary}
                </div>
              </div>
              {!publicMode && <I.chevR style={{ color: 'var(--primary)', flexShrink: 0 }} />}
            </div>
          )}
          {isKauf && !eval_ && !publicMode && (
            <div style={{
              marginTop: 20, padding: 16, borderRadius: 16,
              background: 'var(--surface-2)', border: '1px dashed var(--border-strong)',
              display: 'flex', alignItems: 'center', gap: 12,
            }}>
              <div style={{
                width: 40, height: 40, borderRadius: 12, background: 'var(--surface)',
                color: 'var(--primary)', display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}><I.spark /></div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 600 }}>Noch nicht bewertet</div>
                <div style={{ fontSize: 12, color: 'var(--ink-muted)' }}>KI-Analyse jetzt starten</div>
              </div>
              <button onClick={() => evaluateAd(l.task_id, l.adId || l.id)} className="btn btn-accent" style={{ padding: '8px 14px', fontSize: 12 }}>
                Starten
              </button>
            </div>
          )}

          {/* Description */}
          <div style={{ marginTop: 24 }}>
            <div className="section-title" style={{ marginBottom: 10 }}>Beschreibung</div>
            <p style={{ margin: 0, fontSize: 14, color: 'var(--ink-2)', lineHeight: 1.6, textWrap: 'pretty' }}>
              {l.description}
            </p>
          </div>

          {/* Features */}
          <div style={{ marginTop: 24 }}>
            <div className="section-title" style={{ marginBottom: 10 }}>Ausstattung</div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {l.features.map(f => (
                <span key={f} className="chip" style={{ background: 'var(--surface)', border: '1px solid var(--border)' }}>{f}</span>
              ))}
            </div>
          </div>

          {/* Source */}
          <div style={{ marginTop: 24 }}>
            <div className="section-title" style={{ marginBottom: 10 }}>Quelle</div>
            <a
              href={l.sourceUrl} target="_blank" rel="noopener"
              className="card" style={{ padding: 14, display: 'flex', alignItems: 'center', gap: 10, textDecoration: 'none' }}
            >
              <I.link style={{ color: 'var(--info)' }} />
              <span style={{ flex: 1, fontSize: 13, color: 'var(--ink)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                {l.sourceUrl}
              </span>
              <I.chevR style={{ color: 'var(--ink-faint)' }} />
            </a>
          </div>


          <div style={{ height: 24 }} />
        </div>
      </div>

      {/* Footer CTA */}
      {!publicMode && <div style={{
        position: 'relative', flexShrink: 0, zIndex: 30,
        padding: '12px 16px calc(14px + var(--safe-bottom))',
        background: 'rgba(250,247,242,.95)',
        backdropFilter: 'blur(16px)',
        borderTop: '0.5px solid var(--border)',
        display: 'flex', gap: 8,
      }}>
        <button onClick={openContactSheet} className="btn btn-accent" style={{ flex: 1, padding: '14px', fontSize: 15 }}>
          <I.message style={{ width: 18, height: 18 }} /> {l.contacted ? 'Kontaktiert' : 'Anbieter kontaktieren'}
        </button>
        {eval_ && (
          <button onClick={() => navigate('aiEval', { id: l.id })} className="btn btn-outline" style={{ padding: '14px 16px', fontSize: 15 }}>
            <I.spark style={{ width: 18, height: 18 }} />
          </button>
        )}
      </div>}


      {!publicMode && <Sheet open={shareOpen} onClose={() => setShareOpen(false)} title="Anzeige teilen" height="46%">
        <div style={{ padding: '4px 20px 24px', display: 'grid', gap: 10 }}>
          <p style={{ margin: '0 0 6px', fontSize: 13, color: 'var(--ink-muted)', lineHeight: 1.5 }}>
            Diese Anzeige ist jetzt öffentlich teilbar. Sende den Link direkt an Freunde oder kopiere ihn.
          </p>
          {navigator.share && <button onClick={async () => {
            try { await nativeShare(shareUrl || l.shareUrl); setShareOpen(false); } catch (error) { if (error?.name !== 'AbortError') copyShareLink(shareUrl || l.shareUrl); }
          }} className="btn btn-accent" style={{ width: '100%', justifyContent: 'center', padding: 14 }}>
            <I.share style={{ width: 18, height: 18 }} /> Teilen…
          </button>}
          <a href={`https://wa.me/?text=${encodeURIComponent(`${l.title || 'ImmoBot Anzeige'} ${shareUrl || l.shareUrl || ''}`)}`} target="_blank" rel="noopener" className="btn btn-outline" style={{ justifyContent: 'center', padding: 14, textDecoration: 'none' }}>
            Per WhatsApp teilen
          </a>
          <a href={`https://t.me/share/url?url=${encodeURIComponent(shareUrl || l.shareUrl || '')}&text=${encodeURIComponent(l.title || 'ImmoBot Anzeige')}`} target="_blank" rel="noopener" className="btn btn-outline" style={{ justifyContent: 'center', padding: 14, textDecoration: 'none' }}>
            Per Telegram teilen
          </a>
          <button onClick={() => copyShareLink(shareUrl || l.shareUrl)} className="btn btn-outline" style={{ width: '100%', justifyContent: 'center', padding: 14 }}>
            Link kopieren
          </button>
        </div>
      </Sheet>}

      {!publicMode && <Sheet open={contactOpen} onClose={() => setContactOpen(false)} title="Anbieter kontaktieren" height="58%">
        <div style={{ padding: '4px 20px 24px' }}>
          <div style={{ fontSize: 13, color: 'var(--ink-muted)', marginBottom: 16 }}>
            Die Nachricht wird kopiert. Der Versand erfolgt bewusst auf der Quellplattform.
          </div>
          <Label>Betreff</Label>
          <Input value={`Anfrage: ${l.title}`} onChange={() => {}} />
          <Label style={{ marginTop: 16 }}>Nachricht</Label>
          <textarea value={generatingText ? 'Text wird generiert' : (message || defaultMessage)}
            onChange={e => setMessage(e.target.value)}
            disabled={generatingText}
            style={{
              width: '100%', minHeight: 140, padding: '13px 14px', fontSize: 14, borderRadius: 12,
              background: 'var(--surface)', border: '1px solid var(--border)', resize: 'vertical',
              fontFamily: 'var(--font-sans)', color: 'var(--ink)', outline: 'none', lineHeight: 1.5,
              boxSizing: 'border-box', opacity: generatingText ? .72 : 1,
            }}
          />
          <button
            onClick={async () => {
              try {
                await navigator.clipboard?.writeText(message || defaultMessage);
              } catch (error) {
                const ta = document.createElement('textarea');
                ta.value = message || defaultMessage;
                ta.style.position = 'fixed';
                ta.style.left = '-9999px';
                document.body.appendChild(ta);
                ta.select();
                document.execCommand('copy');
                document.body.removeChild(ta);
              }
              await contactAd(l.task_id, l.adId || l.id);
              if (l.sourceUrl) window.open(l.sourceUrl, '_blank', 'noopener');
              setContactOpen(false);
            }}
            disabled={generatingText}
            className="btn btn-primary" style={{ width: '100%', marginTop: 16, padding: 14, opacity: generatingText ? .55 : 1, cursor: generatingText ? 'not-allowed' : 'pointer' }}
          >
            Text kopieren & öffnen
          </button>
          {!isKauf && (
            <button type="button" onClick={openInquirySettings} disabled={generatingText} className="btn btn-outline" style={{ width: '100%', marginTop: 10, padding: 12, opacity: generatingText ? .55 : 1, cursor: generatingText ? 'not-allowed' : 'pointer' }}>
              Anfrageprofil bearbeiten
            </button>
          )}
          {l.platform === 'immoscout24' && (
            <button onClick={() => scrapeAdDetails(l.task_id, l.adId || l.id)} disabled={generatingText} className="btn btn-outline" style={{ width: '100%', marginTop: 10, padding: 12, opacity: generatingText ? .55 : 1, cursor: generatingText ? 'not-allowed' : 'pointer' }}>
              ImmoScout-Details nachladen
            </button>
          )}
        </div>
      </Sheet>}
    </div>
  );
}

function SharedListingScreen() {
  const listing = window.REVAMP_SHARED_LISTING;
  const evaluation = window.REVAMP_SHARED_EVALUATION;
  if (!listing) return <div style={{ padding: 60 }}>Inserat nicht gefunden</div>;

  const ctx = {
    listings: [listing],
    evaluations: evaluation ? { [listing.id]: evaluation } : {},
    favs: new Set(),
    user: null,
    back: () => { window.location.href = '/'; },
  };

  return <ListingDetailScreen ctx={ctx} id={listing.id} publicMode />;
}

function Spec({ icon, label, value }) {
  return (
    <div className="card" style={{ padding: '12px 14px' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, color: 'var(--ink-muted)', fontSize: 11, fontWeight: 500 }}>
        {icon}{label}
      </div>
      <div style={{ fontSize: 16, fontWeight: 700, color: 'var(--ink)', marginTop: 4, letterSpacing: -0.01 }}>
        {value}
      </div>
    </div>
  );
}

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

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

function EvalSimpleList({ items, tone = 'neutral' }) {
  const palette = tone === 'danger'
    ? { bg: 'var(--danger-soft)', fg: 'var(--danger)', icon: <I.warn style={{ width: 13, height: 13 }} /> }
    : tone === 'success'
      ? { bg: 'var(--success-soft)', fg: 'var(--success)', icon: <I.check style={{ width: 14, height: 14 }} /> }
      : { bg: 'var(--surface-2)', fg: 'var(--ink-muted)', icon: <I.spark style={{ width: 13, height: 13 }} /> };

  return (
    <div className="card" style={{ padding: '8px 0' }}>
      {items.map((item, i) => (
        <div key={i} style={{
          display: 'flex', alignItems: 'flex-start', gap: 10, padding: '10px 16px',
          borderBottom: i < items.length - 1 ? '0.5px solid var(--border)' : 'none',
        }}>
          <div style={{
            width: 22, height: 22, borderRadius: 999, background: palette.bg, color: palette.fg,
            display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, marginTop: 1,
          }}>{palette.icon}</div>
          <div style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.5 }}>{item}</div>
        </div>
      ))}
    </div>
  );
}

// ─── AI EVALUATION FULL SCREEN ─────────────────────────────────────────
function AIEvalScreen({ ctx, id }) {
  const { listings, navigate, back } = ctx;
  const l = listings.find(x => x.id === id);
  const eval_ = ctx.evaluations[id] || window.AI_EVALS?.[id];
  if (!eval_) return <div style={{ padding: 60 }}>Keine Bewertung verfügbar</div>;

  const scoreColor = eval_.score >= 80 ? '#2F8F5A' : eval_.score >= 60 ? '#C28428' : '#C8331C';
  const kpis = evalArray(eval_.kpis);
  const scorecard = evalArray(eval_.scorecard);
  const strengths = evalArray(eval_.strengths, eval_.key_strengths);
  const risks = evalArray(eval_.risks, eval_.key_risks);
  const assumptions = evalArray(eval_.assumptions);
  const imageObservations = evalArray(eval_.image_observations, eval_.imageObservations);
  const modelLabel = [eval_.provider === 'codex' ? 'Codex' : eval_.provider, eval_.model].filter(Boolean).join(' · ') || 'KI-Modell';

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--bg)' }}>
      <TopBar
        title="KI-Analyse" onBack={back}
        trailing={<IconBtn onClick={() => alert('Geteilt: immobot.de/eval/' + l.sharedToken)}><I.share /></IconBtn>}
      />
      <div className="phone-scroll" style={{ flex: 1, padding: '0 0 40px' }}>
        {/* Hero score */}
        <div style={{ padding: '4px 20px 24px' }}>
          <div style={{
            position: 'relative', padding: '28px 24px', borderRadius: 24,
            background: `linear-gradient(135deg, ${scoreColor}12, ${scoreColor}05)`,
            border: `1px solid ${scoreColor}30`,
            display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center',
          }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: scoreColor, textTransform: 'uppercase', letterSpacing: 0.1 }}>
              {eval_.recommendation}
            </div>
            <div style={{ marginTop: 12 }}>
              <ScoreRing score={eval_.score} size={148} stroke={11} />
            </div>
            <div style={{ marginTop: 14, fontSize: 13, color: 'var(--ink-muted)', maxWidth: 280, lineHeight: 1.5, textWrap: 'pretty' }}>
              {eval_.summary}
            </div>
            <div style={{ fontSize: 11, color: 'var(--ink-faint)', marginTop: 10 }}>
              Bewertet am {fmtDateTime(eval_.evaluatedAt)} · {modelLabel}
            </div>
          </div>
        </div>

        {/* Listing summary card */}
        <div style={{ padding: '0 20px 20px' }}>
          <div className="card" onClick={() => navigate('listing', { id: l.id })} style={{ display: 'flex', gap: 12, padding: 10, cursor: 'pointer', alignItems: 'center' }}>
            <div className="photo" style={{ width: 64, height: 64, borderRadius: 10, backgroundImage: `url(${l.photos[0]})`, flexShrink: 0 }} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{l.title}</div>
              <div style={{ fontSize: 12, color: 'var(--ink-muted)', marginTop: 2 }}>
                {fmtPrice(l.price)} · {l.district}, {l.city}
              </div>
            </div>
            <I.chevR style={{ color: 'var(--ink-faint)' }} />
          </div>
        </div>

        {/* KPIs */}
        <div style={{ padding: '0 20px' }}>
          <h3 className="section-title" style={{ marginBottom: 12 }}>Kennzahlen</h3>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            {kpis.map((k, i) => (
              <div key={i} className="card" style={{ padding: '12px 14px' }}>
                <div style={{ fontSize: 11, color: 'var(--ink-muted)', fontWeight: 500 }}>{k.label}</div>
                <div style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 400, marginTop: 4, color: 'var(--ink)', letterSpacing: -0.01, lineHeight: 1 }}>
                  {k.value}
                </div>
                {k.delta && (
                  <div style={{ fontSize: 11, marginTop: 6, color: k.positive ? 'var(--success)' : 'var(--ink-muted)', fontWeight: 500 }}>
                    {k.delta}
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>

        {/* Scorecard */}
        <div style={{ padding: '28px 20px 0' }}>
          <h3 className="section-title" style={{ marginBottom: 12 }}>Scorecard</h3>
          <div className="card" style={{ padding: '16px 16px', display: 'flex', flexDirection: 'column', gap: 14 }}>
            {scorecard.map((s, i) => (
              <ScoreBar key={i} {...s} />
            ))}
          </div>
        </div>

        {strengths.length > 0 && (
          <div style={{ padding: '28px 20px 0' }}>
            <h3 className="section-title" style={{ marginBottom: 12, color: 'var(--success)' }}>Stärken</h3>
            <EvalSimpleList items={strengths} tone="success" />
          </div>
        )}

        {risks.length > 0 && (
          <div style={{ padding: '24px 20px 0' }}>
            <h3 className="section-title" style={{ marginBottom: 12, color: 'var(--danger)' }}>Risiken</h3>
            <EvalSimpleList items={risks} tone="danger" />
          </div>
        )}

        {eval_.analysis && (
          <div style={{ padding: '24px 20px 0' }}>
            <h3 className="section-title" style={{ marginBottom: 12 }}>Vollständige Analyse</h3>
            <div className="card" style={{ padding: '16px 16px', fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.62, whiteSpace: 'pre-line' }}>
              {evalText(eval_.analysis)}
            </div>
          </div>
        )}

        {imageObservations.length > 0 && (
          <div style={{ padding: '24px 20px 0' }}>
            <h3 className="section-title" style={{ marginBottom: 12 }}>Bildanalyse</h3>
            <EvalSimpleList items={imageObservations} />
          </div>
        )}

        {assumptions.length > 0 && (
          <div style={{ padding: '24px 20px 0' }}>
            <h3 className="section-title" style={{ marginBottom: 12 }}>Annahmen</h3>
            <EvalSimpleList items={assumptions} />
          </div>
        )}

        {/* Comparables */}
        {eval_.comparables && (
          <div style={{ padding: '24px 20px 0' }}>
            <h3 className="section-title" style={{ marginBottom: 12 }}>Vergleichsobjekte</h3>
            <div className="card" style={{ padding: '8px 0' }}>
              {eval_.comparables.map((c, i) => (
                <div key={i} style={{
                  display: 'flex', alignItems: 'center', gap: 10, padding: '12px 16px',
                  borderBottom: i < eval_.comparables.length - 1 ? '0.5px solid var(--border)' : 'none',
                }}>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13, fontWeight: 600 }}>{c.addr}</div>
                    <div style={{ fontSize: 11, color: 'var(--ink-muted)' }}>
                      {c.area} m² · {Math.round(c.price/c.area).toLocaleString('de-DE')} €/m² · {c.dist} entfernt
                    </div>
                  </div>
                  <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--ink)' }}>{fmtPriceShort(c.price)}</div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Disclaimer */}
        <div style={{ padding: '24px 20px 0' }}>
          <div style={{ fontSize: 11, color: 'var(--ink-faint)', lineHeight: 1.5, padding: '12px 14px', borderRadius: 10, background: 'var(--surface-2)' }}>
            <strong>Hinweis:</strong> Die KI-Analyse basiert auf öffentlich verfügbaren Daten und stellt keine Anlageberatung dar. Vor einem Kauf sollten weitere Prüfungen erfolgen.
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ListingDetailScreen, SharedListingScreen, AIEvalScreen, Spec });
