// pages-objekte.jsx — Objektliste + Objektdetail mit AfA & Cashflow

function ObjektCard({ o, onOpen }) {
  return (
    <button onClick={onOpen} style={{
      background: '#fff', border: '1px solid var(--border-default)', borderRadius: 14,
      overflow: 'hidden', cursor: 'pointer', textAlign: 'left', padding: 0,
      display: 'flex', flexDirection: 'column', boxShadow: 'var(--shadow-xs)',
    }}>
      <div style={{ height: 160, backgroundImage: `url(${o.cover})`, backgroundSize: 'cover', backgroundPosition: 'center', position: 'relative' }}>
        <div style={{ position: 'absolute', top: 10, left: 10, display: 'flex', gap: 6 }}>
          <Pill tone={o.statusTone} size="sm">{o.status}</Pill>
          {o.badge && <Pill tone="amber" size="sm">{o.badge}</Pill>}
        </div>
        <div style={{ position: 'absolute', bottom: 8, right: 8, background: 'rgba(0,0,0,0.55)', color: '#fff', padding: '3px 7px', borderRadius: 6, fontSize: 11, fontWeight: 600 }}>{o.id}</div>
      </div>
      <div style={{ padding: 14, display: 'flex', flexDirection: 'column', gap: 6 }}>
        <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--fg-1)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{o.titel}</div>
        <div style={{ fontSize: 12, color: 'var(--fg-4)', display: 'flex', alignItems: 'center', gap: 4 }}><Icon.mapPin size={12} /> {o.adresse}</div>
        <div style={{ display: 'flex', gap: 12, fontSize: 11.5, color: 'var(--fg-3)', marginTop: 4 }}>
          <span style={{ display: 'inline-flex', gap: 4, alignItems: 'center' }}><Icon.bedDouble size={13} />{o.zimmer} Zi.</span>
          <span style={{ display: 'inline-flex', gap: 4, alignItems: 'center' }}><Icon.ruler size={13} />{o.wfl} m²</span>
          <span style={{ display: 'inline-flex', gap: 4, alignItems: 'center' }}><Icon.flame size={13} />{o.energie}</span>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 8 }}>
          <span style={{ fontSize: 17, fontWeight: 700, color: 'var(--fg-1)' }}>{fmtEUR(o.kaufpreis)}</span>
          <span style={{ fontSize: 11.5, color: 'var(--fg-4)' }}>{fmtEUR(o.qmPreis)}/m²</span>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 6, paddingTop: 10, borderTop: '1px solid var(--border-subtle)' }}>
          <span style={{ fontSize: 11.5, color: 'var(--fg-3)' }}>{o.interessenten} Interessenten</span>
          <span style={{ fontSize: 11.5, color: 'var(--success-500)', fontWeight: 600 }}>Brutto {fmtPct((o.miete*12)/o.kaufpreis, 2)}</span>
        </div>
      </div>
    </button>
  );
}

function ObjekteListe({ openObjekt }) {
  const [view, setView] = React.useState('grid');
  const [q, setQ] = React.useState('');
  const list = SAMPLE_OBJEKTE.filter(o => q === '' || o.titel.toLowerCase().includes(q.toLowerCase()) || o.ort.toLowerCase().includes(q.toLowerCase()));
  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0 }}>
      <TopBar
        title="Objekte"
        subtitle={`${SAMPLE_OBJEKTE.length} Objekte · ${SAMPLE_OBJEKTE.filter(o=>o.status==='aktiv').length} aktiv im Vertrieb`}
        actions={<>
          <Button variant="secondary" size="sm" leadingIcon={<Icon.upload size={14} />}>Import</Button>
          <Button variant="primary" size="sm" leadingIcon={<Icon.plus size={14} />}>Neues Objekt</Button>
        </>}
      />
      <div style={{ padding: '18px 28px', display: 'flex', gap: 10, alignItems: 'center', borderBottom: '1px solid var(--border-default)' }}>
        <div style={{ flex: 1, position: 'relative' }}>
          <span style={{ position: 'absolute', left: 12, top: 11, color: 'var(--fg-4)' }}><Icon.search size={16} /></span>
          <Input placeholder="Suche Titel, Stadt, Objekt-ID…" value={q} onChange={e=>setQ(e.target.value)} style={{ paddingLeft: 36 }} />
        </div>
        <Button variant="secondary" size="sm" leadingIcon={<Icon.filter size={14} />}>Filter</Button>
        <div style={{ display: 'flex', border: '1px solid var(--border-default)', borderRadius: 10, overflow: 'hidden' }}>
          <button onClick={()=>setView('grid')} style={{ padding: '8px 10px', background: view==='grid'?'var(--surface-sunken)':'#fff', border: 0, cursor:'pointer', color: 'var(--fg-2)' }}><Icon.grid size={14} /></button>
          <button onClick={()=>setView('list')} style={{ padding: '8px 10px', background: view==='list'?'var(--surface-sunken)':'#fff', border: 0, cursor:'pointer', color: 'var(--fg-2)' }}><Icon.list size={14} /></button>
        </div>
      </div>
      <div style={{ flex: 1, overflowY: 'auto', padding: '20px 28px 28px' }}>
        {view === 'grid' ? (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 16 }}>
            {list.map(o => <ObjektCard key={o.id} o={o} onOpen={()=>openObjekt(o.id)} />)}
          </div>
        ) : (
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr style={{ fontSize: 11, color: 'var(--fg-4)', textTransform: 'uppercase', letterSpacing: '0.05em', textAlign: 'left' }}>
                {['Objekt','Typ','Stadt','Wfl.','Kaufpreis','€/m²','Status',''].map(h => <th key={h} style={{ padding: '12px 8px', borderBottom: '1px solid var(--border-default)', fontWeight: 600 }}>{h}</th>)}
              </tr>
            </thead>
            <tbody>
              {list.map(o => (
                <tr key={o.id} onClick={()=>openObjekt(o.id)} style={{ cursor: 'pointer', borderBottom: '1px solid var(--border-subtle)' }}>
                  <td style={{ padding: '12px 8px' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                      <div style={{ width: 44, height: 32, borderRadius: 6, backgroundImage: `url(${o.cover})`, backgroundSize: 'cover' }}></div>
                      <div>
                        <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--fg-1)' }}>{o.titel}</div>
                        <div style={{ fontSize: 11, color: 'var(--fg-4)' }}>{o.id}</div>
                      </div>
                    </div>
                  </td>
                  <td style={{ padding: '12px 8px', fontSize: 12.5, color: 'var(--fg-2)' }}>{o.typ}</td>
                  <td style={{ padding: '12px 8px', fontSize: 12.5, color: 'var(--fg-2)' }}>{o.ort}</td>
                  <td style={{ padding: '12px 8px', fontSize: 12.5, color: 'var(--fg-2)' }}>{o.wfl} m²</td>
                  <td style={{ padding: '12px 8px', fontSize: 13, fontWeight: 600 }}>{fmtEUR(o.kaufpreis)}</td>
                  <td style={{ padding: '12px 8px', fontSize: 12.5, color: 'var(--fg-3)' }}>{fmtEUR(o.qmPreis)}</td>
                  <td style={{ padding: '12px 8px' }}><Pill tone={o.statusTone} size="sm">{o.status}</Pill></td>
                  <td style={{ padding: '12px 8px', textAlign: 'right' }}><Icon.chevronRight size={14} /></td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}

function ObjektDetail({ objektId, openObjekt, openExpose, openSelbstauskunft, go, back }) {
  const o = SAMPLE_OBJEKTE.find(x => x.id === objektId) || SAMPLE_OBJEKTE[0];
  const [tab, setTab] = React.useState('overview');
  const [imgIdx, setImgIdx] = React.useState(0);

  // Sample financing assumptions for this object's calculator card
  const [params, setParams] = React.useState({
    ek: Math.round(o.kaufpreis * 0.25),
    zinsPct: 3.8,
    tilgungPct: 2.0,
    steuersatz: 0.42,
    bundesland: o.ort === 'München' ? 'BY' : o.ort === 'Berlin' ? 'BE' : o.ort === 'Hamburg' ? 'HH' : o.ort === 'Frankfurt' ? 'HE' : 'NW',
  });

  const cf = cashflow({
    kaufpreis: o.kaufpreis,
    gebaeudewertPct: 0.8,
    sanierungskosten: o.afaTyp === 'denkmal-7i' ? Math.round(o.kaufpreis * 0.5) : 0,
    afaTyp: o.afaTyp,
    miete: o.miete,
    bewirtschaftung: o.bewirtschaftung,
    ek: params.ek,
    zinsPct: params.zinsPct,
    tilgungPct: params.tilgungPct,
    steuersatz: params.steuersatz,
    bundesland: params.bundesland,
  });

  const interessenten = SAMPLE_KUNDEN.filter(k => k.objektId === o.id);

  const TabBtn = ({ k, label }) => (
    <button onClick={()=>setTab(k)} style={{
      padding: '10px 14px', background: 'transparent', border: 0,
      borderBottom: `2px solid ${tab===k ? 'var(--accent)' : 'transparent'}`,
      color: tab===k ? 'var(--fg-1)' : 'var(--fg-3)',
      fontWeight: tab===k ? 600 : 500, fontSize: 13, cursor: 'pointer', fontFamily: 'inherit',
    }}>{label}</button>
  );

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0 }}>
      <TopBar
        breadcrumb={['Objekte', o.id]}
        title={o.titel}
        subtitle={<span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}><Icon.mapPin size={12} /> {o.adresse} · <Pill tone={o.statusTone} size="sm">{o.status}</Pill></span>}
        actions={<>
          <Button variant="secondary" size="sm" leadingIcon={<Icon.chevronLeft size={14} />} onClick={back}>Zurück</Button>
          <Button variant="secondary" size="sm" leadingIcon={<Icon.fileCheck size={14} />} onClick={()=>openSelbstauskunft(o.id)}>Selbstauskunft senden</Button>
          <Button variant="primary" size="sm" leadingIcon={<Icon.fileText size={14} />} onClick={()=>openExpose(o.id)}>Exposé erstellen</Button>
        </>}
      />
      <div style={{ display: 'flex', gap: 0, padding: '0 28px', borderBottom: '1px solid var(--border-default)' }}>
        <TabBtn k="overview" label="Übersicht" />
        <TabBtn k="afa" label="AfA & Cashflow" />
        <TabBtn k="interessenten" label={`Interessenten (${interessenten.length})`} />
        <TabBtn k="dokumente" label="Dokumente" />
      </div>

      <div style={{ flex: 1, overflowY: 'auto' }}>
        {tab === 'overview' && (
          <div style={{ padding: '20px 28px 28px', display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 18 }}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
              {/* Gallery */}
              <div style={{ borderRadius: 14, overflow: 'hidden', border: '1px solid var(--border-default)', background: '#fff' }}>
                <div style={{ height: 360, backgroundImage: `url(${o.galerie[imgIdx] || o.cover})`, backgroundSize: 'cover', backgroundPosition: 'center', position: 'relative' }}>
                  {o.badge && <div style={{ position: 'absolute', top: 14, left: 14 }}><Pill tone="amber">{o.badge}</Pill></div>}
                </div>
                <div style={{ padding: 10, display: 'flex', gap: 8, overflowX: 'auto' }}>
                  {o.galerie.map((g, i) => (
                    <button key={i} onClick={()=>setImgIdx(i)} style={{
                      width: 88, height: 60, borderRadius: 6, padding: 0, border: i===imgIdx ? '2px solid var(--accent)' : '1px solid var(--border-default)',
                      backgroundImage: `url(${g})`, backgroundSize: 'cover', cursor: 'pointer', flexShrink: 0,
                    }}/>
                  ))}
                </div>
              </div>

              {/* Stammdaten */}
              <Card padding={20}>
                <div style={{ fontSize: 16, fontWeight: 600, color: 'var(--fg-1)', marginBottom: 14 }}>Objektdaten</div>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '14px 20px' }}>
                  {[
                    ['Typ', o.typ], ['Baujahr', o.bauJahr], ['Sanierung', o.sanierung || '—'],
                    ['Wohnfläche', `${o.wfl} m²`], ['Nutzfläche', o.nfl ? `${o.nfl} m²` : '—'], ['Zimmer', o.zimmer],
                    ['Einheiten', o.einheiten], ['Energieklasse', o.energie], ['Heizung', o.heizung],
                    ['Eigentümer', o.eigentuemer], ['Provision', `${o.provisionPct} %`], ['Objekt-ID', o.id],
                  ].map(([k,v]) => (
                    <div key={k}>
                      <div style={{ fontSize: 11, color: 'var(--fg-4)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600 }}>{k}</div>
                      <div style={{ fontSize: 14, color: 'var(--fg-1)', marginTop: 3 }}>{v}</div>
                    </div>
                  ))}
                </div>
              </Card>

              {/* Beschreibung */}
              <Card padding={20}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
                  <div style={{ fontSize: 16, fontWeight: 600, color: 'var(--fg-1)' }}>Lage & Beschreibung</div>
                  <Button variant="ghost" size="sm" leadingIcon={<Icon.sparkle size={13} />}>Mit KI verbessern</Button>
                </div>
                <div style={{ fontSize: 14, lineHeight: 1.65, color: 'var(--fg-2)' }}>
                  Ruhige, stark nachgefragte Lage in {o.ort}. Anbindung an ÖPNV in &lt; 5 Gehminuten, Einkaufsmöglichkeiten und Ärzte fußläufig erreichbar. Das Objekt befindet sich in einem energetisch {o.bauJahr >= 2020 ? 'modernen Neubaustandard' : 'gepflegten Zustand'} und eignet sich für Kapitalanleger mit Fokus auf {o.afaTyp === 'denkmal-7i' ? 'maximaler Steuerersparnis durch Denkmal-AfA' : o.afaTyp === 'sonder-7b' ? 'beschleunigte Abschreibung nach §7b EStG' : 'langfristige Wertstabilität'}.
                </div>
              </Card>
            </div>

            {/* Right column: snapshot */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <Card padding={20}>
                <div style={{ fontSize: 11, color: 'var(--fg-4)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>Kaufpreis</div>
                <div style={{ fontSize: 28, fontWeight: 700, color: 'var(--fg-1)', letterSpacing: '-0.01em', marginTop: 4 }}>{fmtEUR(o.kaufpreis)}</div>
                <div style={{ fontSize: 12, color: 'var(--fg-4)', marginTop: 2 }}>{fmtEUR(o.qmPreis)} / m²</div>

                <div style={{ borderTop: '1px solid var(--border-subtle)', margin: '14px 0', paddingTop: 14, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                  <div><div style={{ fontSize: 11, color: 'var(--fg-4)', fontWeight: 600 }}>MIETE / MONAT</div><div style={{ fontSize: 16, fontWeight: 700, color: 'var(--fg-1)' }}>{fmtEUR(o.miete)}</div></div>
                  <div><div style={{ fontSize: 11, color: 'var(--fg-4)', fontWeight: 600 }}>BRUTTO-RENDITE</div><div style={{ fontSize: 16, fontWeight: 700, color: 'var(--success-500)' }}>{fmtPct(cf.bruttoMietrendite, 2)}</div></div>
                  <div><div style={{ fontSize: 11, color: 'var(--fg-4)', fontWeight: 600 }}>CASHFLOW / MONAT n.St.</div><div style={{ fontSize: 16, fontWeight: 700, color: cf.cfMonatNach >= 0 ? 'var(--success-500)' : 'var(--danger-500)' }}>{fmtEUR(cf.cfMonatNach)}</div></div>
                  <div><div style={{ fontSize: 11, color: 'var(--fg-4)', fontWeight: 600 }}>STEUER-ERSPARNIS J1</div><div style={{ fontSize: 16, fontWeight: 700, color: 'var(--wholix-amber-700)' }}>{fmtEUR(Math.max(0, cf.ersparnis))}</div></div>
                </div>

                <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 6 }}>
                  <Button variant="primary" block leadingIcon={<Icon.fileText size={14} />} onClick={()=>openExpose(o.id)}>Online-Exposé generieren</Button>
                  <Button variant="secondary" block leadingIcon={<Icon.calculator size={14} />} onClick={()=>setTab('afa')}>AfA-Rechner öffnen</Button>
                </div>
              </Card>

              <Card padding={20}>
                <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--fg-1)', marginBottom: 10 }}>KI-Match: passende Kunden</div>
                {SAMPLE_KUNDEN.filter(k => k.budget >= o.kaufpreis * 0.85 && k.budget <= o.kaufpreis * 1.3).slice(0,3).map(k => (
                  <div key={k.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0', borderBottom: '1px solid var(--border-subtle)' }}>
                    <Avatar name={k.name} size={30} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 13, fontWeight: 600 }}>{k.name}</div>
                      <div style={{ fontSize: 11, color: 'var(--fg-4)' }}>Budget {fmtEUR(k.budget)} · Score {k.score}</div>
                    </div>
                    <Pill tone="green" size="sm">Match</Pill>
                  </div>
                ))}
                <Button variant="ghost" size="sm" trailingIcon={<Icon.arrowRight size={13} />} style={{ marginTop: 8, padding: 0 }} onClick={()=>go('kunden')}>Alle anzeigen</Button>
              </Card>
            </div>
          </div>
        )}

        {tab === 'afa' && <AfACashflowTab o={o} params={params} setParams={setParams} cf={cf} />}

        {tab === 'interessenten' && (
          <div style={{ padding: '20px 28px' }}>
            <Card padding={0}>
              {interessenten.length === 0 ? (
                <EmptyState icon={<Icon.users size={20} />} title="Noch keine Interessenten" hint="Sobald jemand das Exposé öffnet oder die Selbstauskunft anfordert, erscheint er hier." />
              ) : (
                <div>
                  {interessenten.map((k,i) => (
                    <div key={k.id} style={{ padding: '14px 18px', borderBottom: i < interessenten.length-1 ? '1px solid var(--border-subtle)' : 0, display: 'flex', alignItems: 'center', gap: 14 }}>
                      <Avatar name={k.name} size={36} />
                      <div style={{ flex: 1 }}>
                        <div style={{ fontSize: 14, fontWeight: 600 }}>{k.name}</div>
                        <div style={{ fontSize: 12, color: 'var(--fg-4)' }}>{k.email} · {k.tel}</div>
                      </div>
                      <Pill tone={PIPELINE_STAGES.find(s=>s.key===k.stage).tone} size="sm">{PIPELINE_STAGES.find(s=>s.key===k.stage).label}</Pill>
                      <span style={{ fontSize: 12, color: 'var(--fg-3)' }}>EK {fmtEUR(k.ek)}</span>
                      <Button variant="ghost" size="sm" trailingIcon={<Icon.arrowRight size={13} />}>Profil</Button>
                    </div>
                  ))}
                </div>
              )}
            </Card>
          </div>
        )}

        {tab === 'dokumente' && (
          <div style={{ padding: '20px 28px' }}>
            <DokumenteListe scope={`Objekt ${o.id}`} />
          </div>
        )}
      </div>
    </div>
  );
}

function AfACashflowTab({ o, params, setParams, cf }) {
  const [afaTyp, setAfaTyp] = React.useState(o.afaTyp);
  const sched = afaSchedule({
    profil: afaTyp,
    gebaeudewert: o.kaufpreis * 0.8,
    sanierungskosten: afaTyp === 'denkmal-7i' ? Math.round(o.kaufpreis * 0.5) : 0,
    jahre: 12,
  });
  const tilg = tilgungsplan({ darlehen: cf.darlehen, zinsPct: params.zinsPct, tilgungPct: params.tilgungPct, jahre: 10 });

  const update = (k,v) => setParams(p => ({ ...p, [k]: v }));

  return (
    <div style={{ padding: '20px 28px 28px', display: 'grid', gridTemplateColumns: '1fr 1.4fr', gap: 18 }}>
      {/* Inputs */}
      <Card padding={20}>
        <div style={{ fontSize: 16, fontWeight: 600, marginBottom: 14 }}>Annahmen</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <Field label="AfA-Profil">
            <Select value={afaTyp} onChange={e=>setAfaTyp(e.target.value)}>
              {Object.entries(AFA_PROFILE).map(([k,v]) => <option key={k} value={k}>{v.label}</option>)}
            </Select>
            <div style={{ fontSize: 11.5, color: 'var(--fg-4)', marginTop: 4 }}>{AFA_PROFILE[afaTyp].beschreibung}</div>
          </Field>
          <Field label="Bundesland (Grunderwerbsteuer)">
            <Select value={params.bundesland} onChange={e=>update('bundesland', e.target.value)}>
              {Object.entries(BL_LABEL).map(([k,v]) => <option key={k} value={k}>{v} ({GRESt_BL[k]} %)</option>)}
            </Select>
          </Field>
          <Field label={`Eigenkapital — ${fmtEUR(params.ek)}`}>
            <input type="range" min={0} max={Math.round(o.kaufpreis*1.2)} step={5000} value={params.ek} onChange={e=>update('ek', +e.target.value)} style={{ width: '100%', accentColor: 'var(--accent)' }}/>
          </Field>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            <Field label={`Zins ${params.zinsPct.toFixed(2)} %`}>
              <input type="range" min={1} max={7} step={0.05} value={params.zinsPct} onChange={e=>update('zinsPct', +e.target.value)} style={{ width: '100%', accentColor: 'var(--accent)' }}/>
            </Field>
            <Field label={`Tilgung ${params.tilgungPct.toFixed(2)} %`}>
              <input type="range" min={1} max={5} step={0.05} value={params.tilgungPct} onChange={e=>update('tilgungPct', +e.target.value)} style={{ width: '100%', accentColor: 'var(--accent)' }}/>
            </Field>
          </div>
          <Field label={`Grenzsteuersatz ${(params.steuersatz*100).toFixed(0)} %`}>
            <input type="range" min={0.14} max={0.45} step={0.01} value={params.steuersatz} onChange={e=>update('steuersatz', +e.target.value)} style={{ width: '100%', accentColor: 'var(--accent)' }}/>
          </Field>
        </div>
      </Card>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
        {/* KPI strip */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 12 }}>
          <Stat label="Cashflow / Monat n.St." value={fmtEUR(cf.cfMonatNach)} delta={cf.cfMonatNach >= 0 ? 'positiv' : 'negativ'} deltaTone={cf.cfMonatNach >= 0 ? 'green' : 'red'} />
          <Stat label="AfA Jahr 1" value={fmtEUR(sched[0].betrag)} sub={AFA_PROFILE[afaTyp].label.split('(')[0].trim()} />
          <Stat label="Steuerersparnis J1" value={fmtEUR(Math.max(0, cf.ersparnis))} delta={fmtPct(params.steuersatz, 0)+ ' Grenzsteuer'} deltaTone="amber" />
          <Stat label="EK-Rendite n.St." value={fmtPct(cf.ekRendite, 2)} sub={`auf ${fmtEUR(params.ek)} EK`} />
        </div>

        {/* Cashflow breakdown */}
        <Card padding={20}>
          <div style={{ fontSize: 16, fontWeight: 600, marginBottom: 14 }}>Cashflow Jahr 1 (vereinfacht)</div>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
            <tbody>
              {[
                ['Mieteinnahmen (kalt)', cf.mieteJ, '+'],
                ['./. Bewirtschaftung n.umlf.', cf.bewirtJ, '−'],
                ['./. Schuldzinsen', cf.zinsJ, '−'],
                ['= Cashflow vor Tilgung', cf.mieteJ - cf.bewirtJ - cf.zinsJ, '='],
                ['./. Tilgung', cf.tilgungJ, '−'],
                ['= Cashflow vor Steuer', cf.cfVor, '=', true],
                ['./. AfA (steuerlich)', cf.afa1, '−'],
                ['= Steuerliches Ergebnis', cf.steuerErgebnis, '='],
                ['Steuerwirkung @ ' + fmtPct(params.steuersatz, 0), cf.steuerWirkung, cf.steuerWirkung >= 0 ? '−' : '+'],
                ['Cashflow nach Steuer', cf.cfNach, '=', true],
              ].map(([label, val, sign, bold], i) => (
                <tr key={i} style={{ borderTop: bold ? '1px solid var(--border-default)' : '1px solid var(--border-subtle)' }}>
                  <td style={{ padding: '8px 0', color: bold ? 'var(--fg-1)' : 'var(--fg-2)', fontWeight: bold ? 700 : 400 }}>{label}</td>
                  <td style={{ padding: '8px 0', textAlign: 'right', color: 'var(--fg-3)', width: 30 }}>{sign}</td>
                  <td style={{ padding: '8px 0', textAlign: 'right', fontVariantNumeric: 'tabular-nums', fontWeight: bold ? 700 : 500, color: bold ? 'var(--fg-1)' : 'var(--fg-2)' }}>{fmtEUR(Math.abs(val))}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>

        {/* AfA chart */}
        <Card padding={20}>
          <div style={{ fontSize: 16, fontWeight: 600, marginBottom: 14 }}>AfA-Verlauf — erste 12 Jahre</div>
          <BarChart data={sched.map(s => ({ label: 'J'+s.jahr, value: s.betrag }))} />
        </Card>

        {/* Tilgung */}
        <Card padding={20}>
          <div style={{ fontSize: 16, fontWeight: 600, marginBottom: 4 }}>Tilgungsplan ({fmtEUR(cf.darlehen)} Darlehen)</div>
          <div style={{ fontSize: 12, color: 'var(--fg-4)', marginBottom: 12 }}>Annuität {fmtEUR(cf.annuitaet.monat)}/Monat · {fmtPct(params.zinsPct/100, 2)} Zins · {fmtPct(params.tilgungPct/100, 2)} Anfangstilgung</div>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12.5 }}>
            <thead>
              <tr style={{ color: 'var(--fg-4)', fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.05em' }}>
                <th style={{ textAlign:'left', padding: '8px 0' }}>Jahr</th>
                <th style={{ textAlign:'right', padding: '8px 0' }}>Zinsen</th>
                <th style={{ textAlign:'right', padding: '8px 0' }}>Tilgung</th>
                <th style={{ textAlign:'right', padding: '8px 0' }}>Annuität</th>
                <th style={{ textAlign:'right', padding: '8px 0' }}>Restschuld</th>
              </tr>
            </thead>
            <tbody>
              {tilg.map(r => (
                <tr key={r.jahr} style={{ borderTop: '1px solid var(--border-subtle)' }}>
                  <td style={{ padding: '7px 0', fontWeight: 600 }}>{r.jahr}</td>
                  <td style={{ padding: '7px 0', textAlign:'right', fontVariantNumeric: 'tabular-nums' }}>{fmtEUR(r.zinsen)}</td>
                  <td style={{ padding: '7px 0', textAlign:'right', fontVariantNumeric: 'tabular-nums', color: 'var(--success-500)' }}>{fmtEUR(r.tilgung)}</td>
                  <td style={{ padding: '7px 0', textAlign:'right', fontVariantNumeric: 'tabular-nums' }}>{fmtEUR(r.annu)}</td>
                  <td style={{ padding: '7px 0', textAlign:'right', fontVariantNumeric: 'tabular-nums', color: 'var(--fg-3)' }}>{fmtEUR(r.restschuld)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>

        {/* Nebenkosten */}
        <Card padding={20}>
          <div style={{ fontSize: 16, fontWeight: 600, marginBottom: 14 }}>Kaufnebenkosten</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
            {[
              ['GrESt ' + cf.nebenkosten.grEStPct + ' %', cf.nebenkosten.grESt],
              ['Notar & Grundbuch', cf.nebenkosten.notar],
              ['Maklerprovision', cf.nebenkosten.makler],
              ['Summe Nebenkosten', cf.nebenkosten.summe, true],
            ].map(([label, val, bold], i) => (
              <div key={i} style={{ background: bold ? 'var(--accent-soft)' : 'var(--surface-app)', padding: 12, borderRadius: 10 }}>
                <div style={{ fontSize: 11, color: 'var(--fg-4)', fontWeight: 600 }}>{label}</div>
                <div style={{ fontSize: 16, fontWeight: 700, color: bold ? 'var(--wholix-amber-800)' : 'var(--fg-1)', marginTop: 3 }}>{fmtEUR(val)}</div>
              </div>
            ))}
          </div>
        </Card>
      </div>
    </div>
  );
}

function BarChart({ data }) {
  const max = Math.max(...data.map(d => d.value));
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', gap: 6, height: 160, padding: '0 0 24px' }}>
      {data.map((d,i) => (
        <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
          <div style={{ flex: 1, width: '100%', display: 'flex', alignItems: 'flex-end' }}>
            <div title={fmtEUR(d.value)} style={{
              width: '100%', height: `${(d.value/max)*100}%`,
              background: 'linear-gradient(180deg, var(--wholix-amber-400), var(--wholix-amber-600))',
              borderRadius: '6px 6px 2px 2px', minHeight: 4, transition: 'height 220ms',
            }}/>
          </div>
          <div style={{ fontSize: 10.5, color: 'var(--fg-4)', fontWeight: 500 }}>{d.label}</div>
        </div>
      ))}
    </div>
  );
}

window.ObjekteListe = ObjekteListe;
window.ObjektDetail = ObjektDetail;
