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

// ─── LISTING DETAIL ────────────────────────────────────────────────────
function ListingDetailScreen({ ctx, id }) {
  const { listings, navigate, back, favs, toggleFav } = ctx;
  const l = listings.find(x => x.id === id);
  const eval_ = window.AI_EVALS[id];
  const [shared, setShared] = React.useState(true);
  const [contactOpen, setContactOpen] = React.useState(false);

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

  const isFav = favs.has(l.id);
  const isKauf = l.type === 'kauf';

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--bg)' }}>
      <div className="phone-scroll" style={{ flex: 1, paddingBottom: 0 }}>
        {/* Photo gallery with overlay back */}
        <div style={{ position: 'relative' }}>
          <PhotoSlider 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>
            <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 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.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
                  ? Math.round(l.price / l.area).toLocaleString('de-DE') + ' €/m²'
                  : `inkl. ${l.nebenkosten} € NK · kalt ${l.kaltmiete} €`
                }
              </div>
            </div>
            {l.aiScore && <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={() => navigate('aiEval', { id: l.id })}
              style={{
                marginTop: 20, padding: 16, borderRadius: 16, cursor: '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>
              <I.chevR style={{ color: 'var(--primary)', flexShrink: 0 }} />
            </div>
          )}
          {isKauf && !eval_ && (
            <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 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" onClick={e => e.preventDefault()}
              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>

          {/* Share toggle */}
          <div style={{ marginTop: 16 }}>
            <div
              onClick={() => setShared(!shared)} className="card"
              style={{ padding: 14, display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer' }}
            >
              <I.share style={{ color: 'var(--ink-muted)' }} />
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 600 }}>Öffentlich teilen</div>
                <div style={{ fontSize: 11, color: 'var(--ink-muted)', fontFamily: 'var(--font-mono)', marginTop: 2 }}>
                  immobot.de/s/{l.sharedToken}
                </div>
              </div>
              <Toggle on={shared} />
            </div>
          </div>

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

      {/* Footer CTA */}
      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0, zIndex: 30,
        padding: '12px 16px 28px',
        background: 'rgba(250,247,242,.95)',
        backdropFilter: 'blur(16px)',
        borderTop: '0.5px solid var(--border)',
        display: 'flex', gap: 8,
      }}>
        <button onClick={() => setContactOpen(true)} className="btn btn-accent" style={{ flex: 1, padding: '14px', fontSize: 15 }}>
          <I.message style={{ width: 18, height: 18 }} /> 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>

      <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 }}>
            Ihre Nachricht wird über ImmoBot an den Anbieter weitergeleitet.
          </div>
          <Label>Betreff</Label>
          <Input value={`Anfrage: ${l.title}`} onChange={() => {}} />
          <Label style={{ marginTop: 16 }}>Nachricht</Label>
          <textarea defaultValue={`Sehr geehrte Damen und Herren,\n\nich habe Interesse an der oben genannten Immobilie und möchte gerne einen Besichtigungstermin vereinbaren.\n\nMit freundlichen Grüßen\nMaxim Berger`}
            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',
            }}
          />
          <button onClick={() => setContactOpen(false)} className="btn btn-primary" style={{ width: '100%', marginTop: 16, padding: 14 }}>
            Nachricht senden
          </button>
        </div>
      </Sheet>
    </div>
  );
}

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>
  );
}

// ─── AI EVALUATION FULL SCREEN ─────────────────────────────────────────
function AIEvalScreen({ ctx, id }) {
  const { listings, navigate, back } = ctx;
  const l = listings.find(x => x.id === id);
  const eval_ = 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';

  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)} · gpt-4o
            </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 }}>
            {eval_.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 }}>
            {eval_.scorecard.map((s, i) => (
              <ScoreBar key={i} {...s} />
            ))}
          </div>
        </div>

        {/* Strengths */}
        <div style={{ padding: '28px 20px 0' }}>
          <h3 className="section-title" style={{ marginBottom: 12, color: 'var(--success)' }}>Stärken</h3>
          <div className="card" style={{ padding: '8px 0' }}>
            {eval_.strengths.map((s, i) => (
              <div key={i} style={{
                display: 'flex', alignItems: 'flex-start', gap: 10, padding: '10px 16px',
                borderBottom: i < eval_.strengths.length - 1 ? '0.5px solid var(--border)' : 'none',
              }}>
                <div style={{
                  width: 22, height: 22, borderRadius: 999, background: 'var(--success-soft)', color: 'var(--success)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, marginTop: 1,
                }}><I.check style={{ width: 14, height: 14 }} /></div>
                <div style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.5 }}>{s}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Risks */}
        <div style={{ padding: '24px 20px 0' }}>
          <h3 className="section-title" style={{ marginBottom: 12, color: 'var(--danger)' }}>Risiken</h3>
          <div className="card" style={{ padding: '8px 0' }}>
            {eval_.risks.map((r, i) => (
              <div key={i} style={{
                display: 'flex', alignItems: 'flex-start', gap: 10, padding: '10px 16px',
                borderBottom: i < eval_.risks.length - 1 ? '0.5px solid var(--border)' : 'none',
              }}>
                <div style={{
                  width: 22, height: 22, borderRadius: 999, background: 'var(--danger-soft)', color: 'var(--danger)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, marginTop: 1,
                }}><I.warn style={{ width: 13, height: 13 }} /></div>
                <div style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.5 }}>{r}</div>
              </div>
            ))}
          </div>
        </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, AIEvalScreen, Spec });
