// pages-partner.jsx — Vertriebspartner & Provisionen, Selbstauskunft, Expose, Dokumente, Kunden-Detail, Kampagnen, Rechner

// ===================== KUNDEN-DETAIL =====================
function KundeDetail({ kundeId, openObjekt, openSelbstauskunft, openExpose, back }) {
  const k = SAMPLE_KUNDEN.find(x => x.id === kundeId) || SAMPLE_KUNDEN[0];
  const obj = SAMPLE_OBJEKTE.find(o => o.id === k.objektId);
  const stage = PIPELINE_STAGES.find(s => s.key === k.stage);

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0 }}>
      <TopBar
        breadcrumb={['Kunden', k.id]}
        title={k.name}
        subtitle={<span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>{k.email} · {k.tel} · <Pill tone={stage.tone} size="sm">{stage.label}</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.envelope size={14} />}>E-Mail</Button>
          <Button variant="primary" size="sm" leadingIcon={<Icon.fileCheck size={14} />} onClick={()=>openSelbstauskunft(k.objektId || 'OBJ-2041')}>Selbstauskunft anfordern</Button>
        </>}
      />
      <div style={{ flex: 1, overflowY: 'auto', padding: '20px 28px 28px', display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 18 }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <Card padding={20}>
            <div style={{ fontSize: 16, fontWeight: 600, marginBottom: 14 }}>Pipeline-Verlauf</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 0 }}>
              {PIPELINE_STAGES.map((s, i) => {
                const active = PIPELINE_STAGES.findIndex(x=>x.key===k.stage) >= i;
                return (
                  <React.Fragment key={s.key}>
                    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, flex: 1 }}>
                      <div style={{
                        width: 28, height: 28, borderRadius: 999,
                        background: active ? 'var(--accent)' : 'var(--surface-sunken)',
                        color: active ? 'var(--fg-on-amber)' : 'var(--fg-4)',
                        display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontWeight: 700,
                      }}>{i+1}</div>
                      <div style={{ fontSize: 11, fontWeight: 600, color: active ? 'var(--fg-1)' : 'var(--fg-4)', textAlign: 'center' }}>{s.label}</div>
                    </div>
                    {i < PIPELINE_STAGES.length-1 && <div style={{ flex: 1, height: 2, background: PIPELINE_STAGES.findIndex(x=>x.key===k.stage) > i ? 'var(--accent)' : 'var(--border-default)', alignSelf: 'flex-start', marginTop: 13 }}></div>}
                  </React.Fragment>
                );
              })}
            </div>
          </Card>

          <Card padding={20}>
            <div style={{ fontSize: 16, fontWeight: 600, marginBottom: 14 }}>Finanzielles Profil</div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }}>
              {[['Budget', fmtEUR(k.budget)],['Eigenkapital', fmtEUR(k.ek)],['Haushalts-Netto / Monat', fmtEUR(k.einkommen)],
                ['Score (KI)', k.score+' / 100'],['Selbstauskunft', k.selbstauskunft],['Stadt', k.stadt]].map(([a,b]) => (
                <div key={a}><div style={{ fontSize: 11, color: 'var(--fg-4)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.05em' }}>{a}</div><div style={{ fontSize: 14, color: 'var(--fg-1)', marginTop: 3 }}>{b}</div></div>
              ))}
            </div>
          </Card>

          <Card padding={20}>
            <div style={{ fontSize: 16, fontWeight: 600, marginBottom: 12, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              Aktivitätsverlauf
              <Button variant="ghost" size="sm" leadingIcon={<Icon.plus size={13} />}>Notiz</Button>
            </div>
            {[
              { i: 'send', t: 'Exposé "Stadtvilla Königsallee" versendet', m: 'sandra@office-vertrieb.de · vor 2 Std' },
              { i: 'eye', t: 'Exposé 4× geöffnet — letzte Ansicht 18 Min', m: 'tracking@wholix' },
              { i: 'fileCheck', t: 'Selbstauskunft eingereicht', m: 'Mit allen Pflichtfeldern · vor 12 Min' },
              { i: 'phone', t: 'Telefonat — 14 Min', m: 'Sandra Kersten · gestern' },
            ].map((a,i) => {
              const Ic = Icon[a.i];
              return (
                <div key={i} style={{ display: 'flex', gap: 12, padding: '10px 0', borderTop: i>0 ? '1px solid var(--border-subtle)' : 0 }}>
                  <div style={{ width: 28, height: 28, borderRadius: 999, background: 'var(--surface-sunken)', color: 'var(--fg-3)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Ic size={14} /></div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13, color: 'var(--fg-1)' }}>{a.t}</div>
                    <div style={{ fontSize: 11, color: 'var(--fg-4)', marginTop: 2 }}>{a.m}</div>
                  </div>
                </div>
              );
            })}
          </Card>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          {obj && (
            <Card padding={0}>
              <div style={{ height: 150, backgroundImage: `url(${obj.cover})`, backgroundSize: 'cover', backgroundPosition: 'center', borderRadius: '14px 14px 0 0' }}></div>
              <div style={{ padding: 16 }}>
                <div style={{ fontSize: 11, color: 'var(--fg-4)', fontWeight: 600, textTransform: 'uppercase' }}>Aktuelles Objekt</div>
                <div style={{ fontSize: 15, fontWeight: 600, marginTop: 4 }}>{obj.titel}</div>
                <div style={{ fontSize: 12, color: 'var(--fg-4)', marginTop: 2 }}>{obj.adresse}</div>
                <div style={{ fontSize: 18, fontWeight: 700, marginTop: 8 }}>{fmtEUR(obj.kaufpreis)}</div>
                <div style={{ display: 'flex', gap: 8, marginTop: 10 }}>
                  <Button variant="primary" size="sm" block onClick={()=>openObjekt(obj.id)}>Objekt öffnen</Button>
                </div>
              </div>
            </Card>
          )}
          <Card padding={20}>
            <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 10, display: 'flex', alignItems: 'center', gap: 6 }}><Icon.sparkle size={14} /> KI-Zusammenfassung</div>
            <div style={{ fontSize: 13, lineHeight: 1.55, color: 'var(--fg-2)' }}>
              {k.name} bringt {fmtEUR(k.ek)} Eigenkapital ({Math.round(k.ek/k.budget*100)} % vom Budget) und ein Haushalts-Netto von {fmtEUR(k.einkommen)} mit. Bonität-Score {k.score}/100 — {k.score >= 85 ? 'sehr stark' : k.score >= 70 ? 'solide' : 'unterdurchschnittlich'}. Empfehlung: {k.score >= 85 ? 'Reservierungs-Gespräch zeitnah anstoßen.' : 'Vor Reservierung Bonitätsprüfung & Finanzierungsbestätigung einholen.'}
            </div>
          </Card>
          <Card padding={20}>
            <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 10 }}>Berater</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <Avatar name={k.berater} size={40} />
              <div><div style={{ fontSize: 13, fontWeight: 600 }}>{k.berater}</div><div style={{ fontSize: 11, color: 'var(--fg-4)' }}>Senior Vertriebspartner</div></div>
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
}

// ===================== VERTRIEBSPARTNER =====================
function PartnerListe() {
  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0 }}>
      <TopBar title="Vertriebspartner" subtitle={`${SAMPLE_PARTNER.length} Partner · ${fmtEUR(SAMPLE_PARTNER.reduce((s,p)=>s+p.provisionYTD,0))} Provisionen YTD`} actions={<><Button variant="secondary" size="sm" leadingIcon={<Icon.download size={14}/>}>Export</Button><Button variant="primary" size="sm" leadingIcon={<Icon.plus size={14}/>}>Partner einladen</Button></>}/>
      <div style={{ flex: 1, overflowY: 'auto', padding: '20px 28px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginBottom: 18 }}>
          <Stat label="Aktive Partner" value={SAMPLE_PARTNER.filter(p=>p.status==='aktiv').length} icon={<Icon.handshake size={18}/>}/>
          <Stat label="Pipeline-Volumen" value={fmtEUR(SAMPLE_PARTNER.reduce((s,p)=>s+p.pipeline,0))} icon={<Icon.pipeline size={18}/>}/>
          <Stat label="Abschlüsse YTD" value={SAMPLE_PARTNER.reduce((s,p)=>s+p.abschluesse,0)} icon={<Icon.checkCircle size={18}/>}/>
          <Stat label="Provisionen YTD" value={fmtEUR(SAMPLE_PARTNER.reduce((s,p)=>s+p.provisionYTD,0))} icon={<Icon.receipt size={18}/>}/>
        </div>
        <Card padding={0}>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr style={{ fontSize: 11, color: 'var(--fg-4)', textTransform: 'uppercase', letterSpacing: '0.05em', textAlign: 'left' }}>
                {['Partner','Region','Kunden','Pipeline','Abschlüsse','Provision %','Provision YTD','Score',''].map(h => <th key={h} style={{ padding: '14px 14px', borderBottom: '1px solid var(--border-default)', fontWeight: 600 }}>{h}</th>)}
              </tr>
            </thead>
            <tbody>
              {SAMPLE_PARTNER.map((p,i) => (
                <tr key={p.id} style={{ borderBottom: i < SAMPLE_PARTNER.length-1 ? '1px solid var(--border-subtle)' : 0 }}>
                  <td style={{ padding: '14px' }}><div style={{ display:'flex', alignItems:'center', gap:10 }}><Avatar name={p.name} size={36}/><div><div style={{ fontSize:13.5, fontWeight:600 }}>{p.name}</div><div style={{ fontSize:11.5, color:'var(--fg-4)' }}>{p.rolle}</div></div></div></td>
                  <td style={{ padding: '14px', fontSize:12.5 }}>{p.region}</td>
                  <td style={{ padding: '14px', fontSize:13, fontWeight:600 }}>{p.kunden}</td>
                  <td style={{ padding: '14px', fontSize:13, fontWeight:600 }}>{fmtEUR(p.pipeline)}</td>
                  <td style={{ padding: '14px', fontSize:13 }}>{p.abschluesse}</td>
                  <td style={{ padding: '14px', fontSize:13 }}>{p.provisionPct} %</td>
                  <td style={{ padding: '14px', fontSize:13, fontWeight:700, color:'var(--success-500)' }}>{fmtEUR(p.provisionYTD)}</td>
                  <td style={{ padding: '14px' }}><span style={{ display:'inline-block', padding:'3px 8px', borderRadius:6, fontSize:12, fontWeight:700, background: p.score>=85?'var(--success-soft)':p.score>=70?'var(--accent-soft)':'var(--surface-sunken)', color: p.score>=85?'#166534':p.score>=70?'var(--wholix-amber-800)':'var(--fg-3)' }}>{p.score}</span></td>
                  <td style={{ padding: '14px', textAlign:'right' }}><Icon.chevronRight size={14}/></td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      </div>
    </div>
  );
}

// ===================== PROVISIONEN =====================
function Provisionen() {
  const offen = [
    { id: 'PROV-2451', objekt: 'OBJ-2042 — WE 04', kunde: 'Familie Vogt', partner: 'Tim Rauch', pct: 1.4, betrag: 11_830, datum: '15.04.2026', status: 'fällig' },
    { id: 'PROV-2452', objekt: 'OBJ-2037 — Reihenhaus', kunde: 'F. Lehnert', partner: 'Sandra Kersten', pct: 1.5, betrag: 10_800, datum: '02.05.2026', status: 'ausgezahlt' },
    { id: 'PROV-2453', objekt: 'OBJ-2041 — Stadtvilla', kunde: 'M. Albrecht', partner: 'Sandra Kersten', pct: 1.5, betrag: 19_350, datum: 'in Reservierung', status: 'pending' },
    { id: 'PROV-2454', objekt: 'OBJ-2039 — Speicherstadt', kunde: 'P. Wenzel', partner: 'Tim Rauch', pct: 1.4, betrag: 16_520, datum: 'in Reservierung', status: 'pending' },
  ];
  const tones = { 'fällig': 'amber', 'ausgezahlt': 'green', 'pending': 'grey' };
  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0 }}>
      <TopBar title="Provisionen & Abrechnung" subtitle="Provisionen je Vertriebspartner und Objekt." actions={<Button variant="primary" size="sm" leadingIcon={<Icon.download size={14}/>}>Abrechnungslauf starten</Button>}/>
      <div style={{ flex:1, overflowY:'auto', padding:'20px 28px' }}>
        <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:12, marginBottom:18 }}>
          <Stat label="Fällig" value={fmtEUR(offen.filter(o=>o.status==='fällig').reduce((s,o)=>s+o.betrag,0))} deltaTone="amber" icon={<Icon.clock size={18}/>}/>
          <Stat label="In Reservierung" value={fmtEUR(offen.filter(o=>o.status==='pending').reduce((s,o)=>s+o.betrag,0))} icon={<Icon.bookmark size={18}/>}/>
          <Stat label="Ausgezahlt MTD" value={fmtEUR(offen.filter(o=>o.status==='ausgezahlt').reduce((s,o)=>s+o.betrag,0))} icon={<Icon.checkCircle size={18}/>}/>
          <Stat label="Provisionen YTD" value={fmtEUR(408_400)} icon={<Icon.receipt size={18}/>} delta="+18 %" deltaTone="green"/>
        </div>
        <Card padding={0}>
          <table style={{ width:'100%', borderCollapse:'collapse' }}>
            <thead><tr style={{ fontSize:11, color:'var(--fg-4)', textTransform:'uppercase', letterSpacing:'0.05em', textAlign:'left' }}>
              {['ID','Objekt','Kunde','Partner','%','Betrag','Datum','Status',''].map(h => <th key={h} style={{ padding:'14px', borderBottom:'1px solid var(--border-default)', fontWeight:600 }}>{h}</th>)}
            </tr></thead>
            <tbody>
              {offen.map((r,i) => (
                <tr key={r.id} style={{ borderBottom: i<offen.length-1?'1px solid var(--border-subtle)':0 }}>
                  <td style={{ padding:'14px', fontSize:12, fontFamily:'var(--font-mono)' }}>{r.id}</td>
                  <td style={{ padding:'14px', fontSize:13 }}>{r.objekt}</td>
                  <td style={{ padding:'14px', fontSize:13 }}>{r.kunde}</td>
                  <td style={{ padding:'14px', fontSize:13 }}>{r.partner}</td>
                  <td style={{ padding:'14px', fontSize:13 }}>{r.pct} %</td>
                  <td style={{ padding:'14px', fontSize:13, fontWeight:700 }}>{fmtEUR(r.betrag)}</td>
                  <td style={{ padding:'14px', fontSize:12, color:'var(--fg-3)' }}>{r.datum}</td>
                  <td style={{ padding:'14px' }}><Pill tone={tones[r.status]} size="sm">{r.status}</Pill></td>
                  <td style={{ padding:'14px', textAlign:'right' }}><Button variant="ghost" size="sm">Details</Button></td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      </div>
    </div>
  );
}

// ===================== EXPOSÉS-ÜBERSICHT =====================
function ExposeListe({ openExpose, openExposePublic }) {
  const items = SAMPLE_OBJEKTE.filter(o => o.status !== 'verkauft').map(o => ({
    o, aufrufe: Math.floor(Math.random()*40+5), versendet: Math.floor(Math.random()*15+3),
  }));
  return (
    <div style={{ flex:1, display:'flex', flexDirection:'column', minHeight:0 }}>
      <TopBar title="Online-Exposés" subtitle="Pro Objekt ein Online-Exposé. Per Link teilbar — öffentlich oder personalisiert."
        actions={<Button variant="primary" size="sm" leadingIcon={<Icon.plus size={14}/>}>Neues Exposé</Button>}/>
      <div style={{ flex:1, overflowY:'auto', padding:'20px 28px' }}>
        <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(320px, 1fr))', gap:16 }}>
          {items.map(({o, aufrufe, versendet}) => (
            <Card key={o.id} padding={0}>
              <div style={{ height:140, backgroundImage:`url(${o.cover})`, backgroundSize:'cover', backgroundPosition:'center', borderRadius:'14px 14px 0 0', position:'relative' }}>
                <div style={{ position:'absolute', top:10, left:10 }}><Pill tone="green" size="sm">veröffentlicht</Pill></div>
              </div>
              <div style={{ padding:16, display:'flex', flexDirection:'column', gap:8 }}>
                <div style={{ fontSize:14, fontWeight:600 }}>{o.titel}</div>
                <div style={{ fontSize:12, color:'var(--fg-4)' }}>{o.adresse}</div>
                <div style={{ display:'flex', gap:14, fontSize:12, color:'var(--fg-3)', marginTop:4 }}>
                  <span style={{ display:'inline-flex', gap:4, alignItems:'center' }}><Icon.eye size={13}/> {aufrufe} Aufrufe</span>
                  <span style={{ display:'inline-flex', gap:4, alignItems:'center' }}><Icon.send size={13}/> {versendet} Versand</span>
                </div>
                <div style={{ display:'flex', gap:8, marginTop:8 }}>
                  <Button variant="secondary" size="sm" leadingIcon={<Icon.eye size={13}/>} onClick={()=>openExposePublic(o.id)} style={{ flex:1 }}>Vorschau</Button>
                  <Button variant="primary" size="sm" leadingIcon={<Icon.shareLink size={13}/>} onClick={()=>openExpose(o.id)} style={{ flex:1 }}>Versenden</Button>
                </div>
              </div>
            </Card>
          ))}
        </div>
      </div>
    </div>
  );
}

// ===================== EXPOSE-EDITOR =====================
function ExposeEditor({ objektId, openExposePublic, back }) {
  const o = SAMPLE_OBJEKTE.find(x => x.id === objektId) || SAMPLE_OBJEKTE[0];
  const [mode, setMode] = React.useState('public');
  const [pwd, setPwd] = React.useState('');
  const [recipient, setRecipient] = React.useState('');
  const [generating, setGenerating] = React.useState(false);
  const [text, setText] = React.useState(`Exklusive Anlagemöglichkeit in ${o.ort}: ${o.titel}. ${o.bauJahr >= 2020 ? 'Energieeffizienter Neubau' : 'Gepflegter Bestand'} mit ${o.wfl} m² Wohnfläche, ${o.zimmer} Zimmern und attraktiver Mietsituation. ${o.afaTyp === 'denkmal-7i' ? 'Maximale Steuerersparnis durch Denkmal-AfA nach §7i EStG.' : o.afaTyp === 'sonder-7b' ? 'Beschleunigte Sonder-AfA §7b für Mietwohnungsneubau.' : 'Solide Brutto-Mietrendite und langfristige Wertstabilität.'}\n\nDie Lage überzeugt durch hervorragende Anbindung, Infrastruktur und ein nachhaltig steigendes Mietniveau im Quartier.`);
  const link = `https://app.wholix.de/x/${o.id.toLowerCase()}-${mode === 'public' ? 'pub' : 'a8f2'}`;

  const generate = () => {
    setGenerating(true);
    setTimeout(() => {
      setText(`✦ ${o.titel}\n\n${o.ort} bleibt einer der gefragtesten Standorte Deutschlands. Mit ${o.wfl} m² auf ${o.zimmer} Zimmer bietet diese Immobilie alles, was Kapitalanleger 2026 suchen: stabile Mieteinnahmen (${fmtEUR(o.miete)} kalt/Monat), eine ${(o.miete*12/o.kaufpreis*100).toFixed(2)} % Brutto-Mietrendite und ${o.afaTyp === 'denkmal-7i' ? '12 Jahre erhöhte Denkmal-AfA bis zu 9 % p.a.' : o.afaTyp === 'sonder-7b' ? 'Sonder-AfA §7b von 5 % zusätzlich in den ersten 4 Jahren' : 'planbare lineare AfA über die volle Nutzungsdauer'}.\n\nKurz: Eine Immobilie, die rechnet.`);
      setGenerating(false);
    }, 1100);
  };

  return (
    <div style={{ flex:1, display:'flex', flexDirection:'column', minHeight:0 }}>
      <TopBar breadcrumb={['Exposés', o.id]} title={`Exposé — ${o.titel}`} subtitle="Editor mit KI-gestützter Texterzeugung und Vorschau."
        actions={<><Button variant="secondary" size="sm" onClick={back} leadingIcon={<Icon.chevronLeft size={14}/>}>Zurück</Button><Button variant="primary" size="sm" leadingIcon={<Icon.eye size={14}/>} onClick={()=>openExposePublic(o.id)}>Live-Vorschau</Button></>}/>
      <div style={{ flex:1, overflowY:'auto', padding:'20px 28px', display:'grid', gridTemplateColumns:'1fr 1fr', gap:18 }}>
        <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
          <Card padding={20}>
            <div style={{ fontSize:16, fontWeight:600, marginBottom:14 }}>Inhalt</div>
            <Field label="Headline"><Input defaultValue={`${o.titel} — Anlagemöglichkeit in ${o.ort}`}/></Field>
            <div style={{ height:14 }}/>
            <Field label="Beschreibung" hint="Du kannst diesen Text manuell anpassen oder von der KI neu schreiben lassen.">
              <Textarea rows={9} value={generating ? 'KI generiert eine neue Beschreibung aus den Objektdaten…' : text} onChange={e=>setText(e.target.value)}/>
            </Field>
            <div style={{ display:'flex', gap:8, marginTop:12 }}>
              <Button variant="primary" leadingIcon={<Icon.sparkle size={14}/>} onClick={generate}>{generating ? 'Schreibe…' : 'KI: Text neu generieren'}</Button>
              <Button variant="secondary" leadingIcon={<Icon.edit size={14}/>}>Kürzen</Button>
            </div>
          </Card>
          <Card padding={20}>
            <div style={{ fontSize:16, fontWeight:600, marginBottom:14 }}>Anhänge</div>
            <Dropzone hint="Grundriss, Energieausweis, Teilungserklärung als PDF"/>
          </Card>
        </div>
        <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
          <Card padding={20}>
            <div style={{ fontSize:16, fontWeight:600, marginBottom:14 }}>Versand-Modus</div>
            <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:8, marginBottom:14 }}>
              {[['public','Öffentlich','Jeder mit Link'],['personal','Personalisiert','Pro Interessent + Tracking'],['protected','Passwort','Mit Passwort']].map(([k,l,h]) => (
                <button key={k} onClick={()=>setMode(k)} style={{ padding:'10px 12px', borderRadius:10, border: mode===k?'2px solid var(--accent)':'1px solid var(--border-default)', background: mode===k?'var(--accent-soft)':'#fff', cursor:'pointer', textAlign:'left' }}>
                  <div style={{ fontSize:13, fontWeight:600, color: mode===k?'var(--wholix-amber-800)':'var(--fg-1)' }}>{l}</div>
                  <div style={{ fontSize:11, color:'var(--fg-4)', marginTop:2 }}>{h}</div>
                </button>
              ))}
            </div>
            {mode === 'personal' && <Field label="Empfänger E-Mail"><Input placeholder="kunde@example.de" value={recipient} onChange={e=>setRecipient(e.target.value)}/></Field>}
            {mode === 'protected' && <Field label="Passwort setzen"><Input placeholder="z.B. K42-haus" value={pwd} onChange={e=>setPwd(e.target.value)}/></Field>}
            <div style={{ marginTop:14, padding:'10px 12px', background:'var(--surface-sunken)', borderRadius:10, display:'flex', alignItems:'center', gap:8 }}>
              <Icon.link size={14} />
              <input value={link} readOnly style={{ flex:1, border:0, background:'transparent', fontSize:12.5, fontFamily:'var(--font-mono)', color:'var(--fg-2)', outline:'none' }}/>
              <Button variant="secondary" size="sm" leadingIcon={<Icon.copyLink size={13}/>}>Kopieren</Button>
            </div>
            <Button variant="primary" block style={{ marginTop:14 }} leadingIcon={<Icon.send size={14}/>}>{mode==='personal' ? 'An Empfänger senden' : 'Link generieren & teilen'}</Button>
          </Card>
          <Card padding={20}>
            <div style={{ fontSize:14, fontWeight:600, marginBottom:10 }}>Mitversenden</div>
            {[['Selbstauskunft-Link', true], ['AfA & Cashflow-Rechner', true], ['Energieausweis (PDF)', true], ['Teilungserklärung (PDF)', false]].map(([l,v]) => (
              <label key={l} style={{ display:'flex', alignItems:'center', gap:10, padding:'8px 0', borderTop:'1px solid var(--border-subtle)' }}>
                <input type="checkbox" defaultChecked={v} style={{ accentColor:'var(--accent)', width:16, height:16 }}/>
                <span style={{ fontSize:13 }}>{l}</span>
              </label>
            ))}
          </Card>
        </div>
      </div>
    </div>
  );
}

// ===================== ÖFFENTLICHES EXPOSÉ (Kundensicht) =====================
function ExposePublic({ objektId, openSelbstauskunftPublic, back }) {
  const o = SAMPLE_OBJEKTE.find(x => x.id === objektId) || SAMPLE_OBJEKTE[0];
  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: Math.round(o.kaufpreis*0.25), zinsPct:3.8, tilgungPct:2, steuersatz:0.42, bundesland:'NW' });
  return (
    <div style={{ minHeight:'100vh', background:'#fff' }}>
      {/* Public-mode preview chrome */}
      <div style={{ position:'sticky', top:0, zIndex:10, background:'#0A0A0A', color:'#fff', padding:'10px 18px', display:'flex', alignItems:'center', justifyContent:'space-between', fontSize:12 }}>
        <span style={{ display:'inline-flex', alignItems:'center', gap:8, opacity:0.85 }}><Icon.eye size={14}/> Vorschau · Online-Exposé · {o.id}</span>
        <button onClick={back} style={{ background:'transparent', color:'#fff', border:'1px solid rgba(255,255,255,0.3)', borderRadius:8, padding:'5px 10px', fontSize:12, cursor:'pointer' }}>Zur Editor-Ansicht</button>
      </div>
      <div style={{ maxWidth:1100, margin:'0 auto', padding:'30px 24px 80px' }}>
        <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:24 }}>
          <img src="assets/logo-wholix-light.svg" alt="Wholix" style={{ width:96 }}/>
          <span style={{ fontSize:11, color:'var(--fg-4)', letterSpacing:'0.08em', textTransform:'uppercase' }}>Office Vertrieb · Sandra Kersten</span>
        </div>
        <div style={{ display:'grid', gridTemplateColumns:'2fr 1fr', gap:6, height:480, marginBottom:32, borderRadius:18, overflow:'hidden' }}>
          <div style={{ backgroundImage:`url(${o.galerie[0]||o.cover})`, backgroundSize:'cover', backgroundPosition:'center' }}/>
          <div style={{ display:'grid', gridTemplateRows:'1fr 1fr', gap:6 }}>
            {(o.galerie.slice(1,3).length === 2 ? o.galerie.slice(1,3) : [o.cover, o.cover]).map((g,i) => <div key={i} style={{ backgroundImage:`url(${g})`, backgroundSize:'cover', backgroundPosition:'center' }}/>)}
          </div>
        </div>
        <div style={{ display:'grid', gridTemplateColumns:'1.5fr 1fr', gap:40 }}>
          <div>
            {o.badge && <div style={{ marginBottom:14 }}><Pill tone="amber">{o.badge}</Pill></div>}
            <h1 style={{ fontSize:42, fontWeight:700, letterSpacing:'-0.02em', lineHeight:1.1, margin:'0 0 10px' }}>{o.titel}</h1>
            <div style={{ fontSize:15, color:'var(--fg-3)', display:'inline-flex', alignItems:'center', gap:6, marginBottom:24 }}><Icon.mapPin size={14}/> {o.adresse}</div>
            <p style={{ fontSize:16, lineHeight:1.7, color:'var(--fg-2)' }}>Exklusive Kapitalanlage-Immobilie in {o.ort}. {o.bauJahr >= 2020 ? 'Energieeffizienter Neubau' : 'Gepflegter Bestand'} mit ${o.wfl} m² Wohnfläche und stabiler Mietsituation. {o.afaTyp === 'denkmal-7i' ? 'Maximale Steuerersparnis durch Denkmal-AfA nach §7i EStG — bis zu 9 % p.a. der Sanierungskosten in den ersten 8 Jahren absetzbar.' : o.afaTyp === 'sonder-7b' ? 'Beschleunigte Sonder-AfA §7b: 5 % zusätzlich in den ersten 4 Jahren plus lineare Abschreibung.' : 'Planbare lineare AfA und langfristige Wertstabilität in nachgefragter Lage.'}</p>
            <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:18, marginTop:30, paddingTop:24, borderTop:'1px solid var(--border-default)' }}>
              {[['Wohnfläche', `${o.wfl} m²`],['Zimmer', o.zimmer],['Baujahr', o.bauJahr],['Energieklasse', o.energie],['Heizung', o.heizung],['Einheiten', o.einheiten]].map(([k,v]) => (
                <div key={k}><div style={{ fontSize:12, color:'var(--fg-4)', textTransform:'uppercase', letterSpacing:'0.05em', fontWeight:600 }}>{k}</div><div style={{ fontSize:18, fontWeight:600, marginTop:3 }}>{v}</div></div>
              ))}
            </div>

            <div style={{ marginTop:40 }}>
              <h2 style={{ fontSize:22, fontWeight:700, marginBottom:14 }}>Wirtschaftlichkeit auf einen Blick</h2>
              <div style={{ display:'grid', gridTemplateColumns:'repeat(2, 1fr)', gap:12 }}>
                {[
                  ['Kaufpreis', fmtEUR(o.kaufpreis)],
                  ['Brutto-Mietrendite', fmtPct(cf.bruttoMietrendite, 2)],
                  ['Cashflow / Monat n.St.', fmtEUR(cf.cfMonatNach)],
                  ['Steuerersparnis Jahr 1', fmtEUR(Math.max(0, cf.ersparnis))],
                ].map(([k,v]) => (
                  <div key={k} style={{ background:'var(--surface-app)', border:'1px solid var(--border-default)', borderRadius:12, padding:16 }}>
                    <div style={{ fontSize:11, color:'var(--fg-4)', fontWeight:600, textTransform:'uppercase', letterSpacing:'0.05em' }}>{k}</div>
                    <div style={{ fontSize:22, fontWeight:700, marginTop:4 }}>{v}</div>
                  </div>
                ))}
              </div>
              <div style={{ fontSize:11, color:'var(--fg-4)', marginTop:10 }}>Annahmen: 25 % EK, 3,8 % Zins, 2 % Anfangstilgung, 42 % Grenzsteuersatz. Beispielrechnung — keine Anlageempfehlung.</div>
            </div>
          </div>

          <div>
            <div style={{ position:'sticky', top:80, background:'#fff', border:'1px solid var(--border-default)', borderRadius:14, padding:24, boxShadow:'var(--shadow-md)' }}>
              <div style={{ fontSize:11, color:'var(--fg-4)', fontWeight:600, textTransform:'uppercase', letterSpacing:'0.05em' }}>Kaufpreis</div>
              <div style={{ fontSize:36, fontWeight:700, letterSpacing:'-0.02em', margin:'4px 0 6px' }}>{fmtEUR(o.kaufpreis)}</div>
              <div style={{ fontSize:13, color:'var(--fg-3)' }}>{fmtEUR(o.qmPreis)} / m² · zzgl. NK</div>
              <div style={{ borderTop:'1px solid var(--border-default)', margin:'16px 0', paddingTop:16, display:'flex', flexDirection:'column', gap:8, fontSize:13 }}>
                <div style={{ display:'flex', justifyContent:'space-between' }}><span style={{ color:'var(--fg-3)' }}>Miete kalt</span><b>{fmtEUR(o.miete)}/Monat</b></div>
                <div style={{ display:'flex', justifyContent:'space-between' }}><span style={{ color:'var(--fg-3)' }}>Brutto-Rendite</span><b>{fmtPct(cf.bruttoMietrendite, 2)}</b></div>
                <div style={{ display:'flex', justifyContent:'space-between' }}><span style={{ color:'var(--fg-3)' }}>AfA Jahr 1</span><b>{fmtEUR(cf.afa1)}</b></div>
              </div>
              <Button variant="primary" block size="lg" leadingIcon={<Icon.fileCheck size={16}/>} onClick={()=>openSelbstauskunftPublic(o.id)}>Selbstauskunft starten</Button>
              <Button variant="secondary" block style={{ marginTop:8 }} leadingIcon={<Icon.download size={14}/>}>PDF herunterladen</Button>
              <div style={{ borderTop:'1px solid var(--border-subtle)', marginTop:16, paddingTop:14, display:'flex', alignItems:'center', gap:10 }}>
                <Avatar name="Sandra Kersten" size={36}/>
                <div style={{ flex:1 }}><div style={{ fontSize:13, fontWeight:600 }}>Sandra Kersten</div><div style={{ fontSize:11, color:'var(--fg-4)' }}>+49 211 99 88 700</div></div>
                <IconButton icon={<Icon.phone size={14}/>} size={32}/>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ===================== SELBSTAUSKUNFT (Kundensicht, öffentlich) =====================
function SelbstauskunftPublic({ objektId, back, onSubmit }) {
  const o = SAMPLE_OBJEKTE.find(x => x.id === objektId);
  const [step, setStep] = React.useState(1);
  const [form, setForm] = React.useState({
    couple: false, anrede: 'Herr', vorname: '', nachname: '', geburt: '', staat: 'Deutschland', familie: 'verheiratet', kinder: 0,
    arbeitgeber: '', position: '', seit: '', brutto: 5000, befristet: false,
    eigenkapital: 100000, depot: 0, weitere: '',
    kredit: 0, leasing: 0,
    kaufpreis: o?.kaufpreis || 800000, ek: 200000, fremdmittel: 600000, tilgungPct: 2,
    docs: [], schufa: false, signed: '',
  });
  const STEPS = ['Persönlich', 'Beruf & Einkommen', 'Vermögen & Verbindlichkeiten', 'Finanzierung', 'Dokumente', 'SCHUFA & Unterschrift'];
  const upd = (k,v) => setForm(f => ({...f, [k]: v}));

  return (
    <div style={{ minHeight:'100vh', background:'var(--surface-app)' }}>
      <div style={{ position:'sticky', top:0, zIndex:10, background:'#0A0A0A', color:'#fff', padding:'10px 18px', display:'flex', alignItems:'center', justifyContent:'space-between', fontSize:12 }}>
        <span style={{ display:'inline-flex', alignItems:'center', gap:8, opacity:0.85 }}><Icon.eye size={14}/> Vorschau · Selbstauskunft (Kundensicht)</span>
        <button onClick={back} style={{ background:'transparent', color:'#fff', border:'1px solid rgba(255,255,255,0.3)', borderRadius:8, padding:'5px 10px', fontSize:12, cursor:'pointer' }}>Zurück zur App</button>
      </div>
      <div style={{ maxWidth:840, margin:'0 auto', padding:'30px 24px 80px' }}>
        <div style={{ display:'flex', alignItems:'center', gap:12, marginBottom:18 }}>
          <img src="assets/logo-wholix-light.svg" alt="Wholix" style={{ width:88 }}/>
          <span style={{ fontSize:11, color:'var(--wholix-amber-800)', background:'var(--accent-soft)', padding:'3px 6px', borderRadius:4, letterSpacing:'0.1em', fontWeight:700 }}>SELBSTAUSKUNFT</span>
        </div>
        <h1 style={{ fontSize:32, fontWeight:700, letterSpacing:'-0.02em', margin:'0 0 8px' }}>Deine Selbstauskunft</h1>
        <p style={{ fontSize:15, color:'var(--fg-3)', maxWidth:600, lineHeight:1.6 }}>Damit dein Berater die Finanzierung optimal vorbereiten kann, brauchen wir ein paar Angaben zu dir. Dauer: ca. 6 Min. Alle Daten werden verschlüsselt übertragen.</p>
        {o && <div style={{ marginTop:18, background:'#fff', border:'1px solid var(--border-default)', borderRadius:12, padding:14, display:'flex', alignItems:'center', gap:14 }}>
          <div style={{ width:64, height:48, borderRadius:8, backgroundImage:`url(${o.cover})`, backgroundSize:'cover' }}/>
          <div style={{ flex:1 }}><div style={{ fontSize:13, fontWeight:600 }}>{o.titel}</div><div style={{ fontSize:11.5, color:'var(--fg-4)' }}>{o.adresse}</div></div>
          <div style={{ fontSize:15, fontWeight:700 }}>{fmtEUR(o.kaufpreis)}</div>
        </div>}

        {/* Stepper */}
        <div style={{ display:'flex', alignItems:'center', gap:0, margin:'30px 0 20px', overflowX:'auto' }}>
          {STEPS.map((s,i) => (
            <React.Fragment key={i}>
              <div style={{ display:'flex', flexDirection:'column', alignItems:'center', gap:4, flex:'0 0 auto', minWidth:90 }}>
                <div style={{ width:26, height:26, borderRadius:999, background: step>i ? 'var(--success-500)' : step===i+1 ? 'var(--accent)' : 'var(--surface-sunken)', color: step>=i+1 ? '#fff' : 'var(--fg-4)', display:'flex', alignItems:'center', justifyContent:'center', fontSize:11, fontWeight:700 }}>
                  {step>i ? <Icon.check size={13}/> : i+1}
                </div>
                <div style={{ fontSize:10.5, fontWeight:500, color: step===i+1 ? 'var(--fg-1)' : 'var(--fg-4)', textAlign:'center' }}>{s}</div>
              </div>
              {i<STEPS.length-1 && <div style={{ flex:1, height:2, background: step>i+1 ? 'var(--success-500)' : 'var(--border-default)', alignSelf:'flex-start', marginTop:13 }}/>}
            </React.Fragment>
          ))}
        </div>

        <Card padding={26}>
          {step === 1 && <SaStep1 form={form} upd={upd}/>}
          {step === 2 && <SaStep2 form={form} upd={upd}/>}
          {step === 3 && <SaStep3 form={form} upd={upd}/>}
          {step === 4 && <SaStep4 form={form} upd={upd} obj={o}/>}
          {step === 5 && <SaStep5 form={form} upd={upd}/>}
          {step === 6 && <SaStep6 form={form} upd={upd} onSubmit={onSubmit}/>}
        </Card>

        <div style={{ display:'flex', justifyContent:'space-between', marginTop:18 }}>
          <Button variant="secondary" onClick={()=>setStep(s=>Math.max(1,s-1))} disabled={step===1} leadingIcon={<Icon.chevronLeft size={14}/>}>Zurück</Button>
          {step < STEPS.length ? <Button variant="primary" onClick={()=>setStep(s=>Math.min(STEPS.length, s+1))} trailingIcon={<Icon.arrowRight size={14}/>}>Weiter</Button> :
            <Button variant="success" onClick={onSubmit} leadingIcon={<Icon.check size={14}/>}>Abschicken</Button>}
        </div>
      </div>
    </div>
  );
}

function SaStep1({ form, upd }) {
  return (
    <>
      <div style={{ fontSize:18, fontWeight:600, marginBottom:14 }}>Persönliche Angaben</div>
      <label style={{ display:'flex', alignItems:'center', gap:10, marginBottom:18, padding:'10px 14px', background:'var(--accent-soft)', borderRadius:10, cursor:'pointer' }}>
        <input type="checkbox" checked={form.couple} onChange={e=>upd('couple', e.target.checked)} style={{ accentColor:'var(--accent)' }}/>
        <span style={{ fontSize:13 }}>Wir kaufen zu zweit (Ehe-/Lebenspartner)</span>
      </label>
      <div style={{ display:'grid', gridTemplateColumns:'1fr 2fr 2fr', gap:14, marginBottom:14 }}>
        <Field label="Anrede"><Select value={form.anrede} onChange={e=>upd('anrede', e.target.value)}><option>Herr</option><option>Frau</option><option>Divers</option></Select></Field>
        <Field label="Vorname" required><Input value={form.vorname} onChange={e=>upd('vorname', e.target.value)} placeholder="Max"/></Field>
        <Field label="Nachname" required><Input value={form.nachname} onChange={e=>upd('nachname', e.target.value)} placeholder="Mustermann"/></Field>
      </div>
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14, marginBottom:14 }}>
        <Field label="Geburtsdatum" required><Input type="date" value={form.geburt} onChange={e=>upd('geburt', e.target.value)}/></Field>
        <Field label="Staatsangehörigkeit"><Input value={form.staat} onChange={e=>upd('staat', e.target.value)}/></Field>
      </div>
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 }}>
        <Field label="Familienstand"><Select value={form.familie} onChange={e=>upd('familie', e.target.value)}><option>ledig</option><option>verheiratet</option><option>geschieden</option><option>verwitwet</option><option>Lebenspartnerschaft</option></Select></Field>
        <Field label="Kinder im Haushalt"><Input type="number" min={0} value={form.kinder} onChange={e=>upd('kinder', +e.target.value)}/></Field>
      </div>
    </>
  );
}
function SaStep2({ form, upd }) {
  return (
    <>
      <div style={{ fontSize:18, fontWeight:600, marginBottom:14 }}>Beruf & Einkommen</div>
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14, marginBottom:14 }}>
        <Field label="Arbeitgeber" required><Input value={form.arbeitgeber} onChange={e=>upd('arbeitgeber', e.target.value)}/></Field>
        <Field label="Position"><Input value={form.position} onChange={e=>upd('position', e.target.value)}/></Field>
      </div>
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:14, marginBottom:14 }}>
        <Field label="Beschäftigt seit"><Input type="month" value={form.seit} onChange={e=>upd('seit', e.target.value)}/></Field>
        <Field label="Brutto / Monat (€)" required><Input type="number" value={form.brutto} onChange={e=>upd('brutto', +e.target.value)}/></Field>
        <Field label="Beschäftigungsart">
          <Select value={form.befristet?'befristet':'unbefristet'} onChange={e=>upd('befristet', e.target.value==='befristet')}>
            <option value="unbefristet">unbefristet</option><option value="befristet">befristet</option>
          </Select>
        </Field>
      </div>
      <Field label="Weitere Einkommen (z.B. Mieteinnahmen, selbständige Tätigkeit)"><Textarea rows={3} placeholder="Optional"/></Field>
    </>
  );
}
function SaStep3({ form, upd }) {
  return (
    <>
      <div style={{ fontSize:18, fontWeight:600, marginBottom:14 }}>Vermögen & Verbindlichkeiten</div>
      <div style={{ fontSize:14, fontWeight:600, color:'var(--fg-2)', margin:'8px 0' }}>Vermögen</div>
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14, marginBottom:14 }}>
        <Field label="Eigenkapital / Bankguthaben (€)" required><Input type="number" value={form.eigenkapital} onChange={e=>upd('eigenkapital', +e.target.value)}/></Field>
        <Field label="Wertpapiere / Depot (€)"><Input type="number" value={form.depot} onChange={e=>upd('depot', +e.target.value)}/></Field>
      </div>
      <Field label="Weitere Vermögenswerte (Immobilien, Lebensversicherung, …)"><Textarea rows={2} value={form.weitere} onChange={e=>upd('weitere', e.target.value)}/></Field>
      <div style={{ fontSize:14, fontWeight:600, color:'var(--fg-2)', margin:'18px 0 8px' }}>Verbindlichkeiten</div>
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 }}>
        <Field label="Laufende Kreditrate / Monat (€)"><Input type="number" value={form.kredit} onChange={e=>upd('kredit', +e.target.value)}/></Field>
        <Field label="Leasingraten / Monat (€)"><Input type="number" value={form.leasing} onChange={e=>upd('leasing', +e.target.value)}/></Field>
      </div>
    </>
  );
}
function SaStep4({ form, upd, obj }) {
  const fremd = Math.max(0, form.kaufpreis - form.ek);
  return (
    <>
      <div style={{ fontSize:18, fontWeight:600, marginBottom:14 }}>Finanzierungsvorhaben</div>
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14, marginBottom:14 }}>
        <Field label="Kaufpreis Objekt (€)"><Input type="number" value={form.kaufpreis} onChange={e=>upd('kaufpreis', +e.target.value)}/></Field>
        <Field label="Eingesetztes Eigenkapital (€)"><Input type="number" value={form.ek} onChange={e=>upd('ek', +e.target.value)}/></Field>
      </div>
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 }}>
        <Field label="Benötigte Fremdmittel (€)"><Input type="number" value={fremd} readOnly/></Field>
        <Field label="Anfangstilgung (%)"><Input type="number" step={0.1} value={form.tilgungPct} onChange={e=>upd('tilgungPct', +e.target.value)}/></Field>
      </div>
      <div style={{ marginTop:14, padding:'12px 16px', background:'var(--accent-soft)', border:'1px solid var(--accent-soft-border)', borderRadius:10, fontSize:13, color:'var(--fg-2)' }}>
        Beleihung: <b>{Math.round(fremd/form.kaufpreis*100)}%</b> · EK-Quote: <b>{Math.round(form.ek/form.kaufpreis*100)}%</b>
      </div>
    </>
  );
}
function SaStep5({ form, upd }) {
  const docs = [
    { k: 'gehalt', l: 'Gehaltsnachweise (3 Monate)', req: true },
    { k: 'konto', l: 'Kontoauszüge (3 Monate)', req: true },
    { k: 'ausweis', l: 'Personalausweis / Reisepass', req: true },
    { k: 'schufa', l: 'SCHUFA-Auskunft (optional)', req: false },
    { k: 'ek', l: 'EK-Nachweis (Depot, Sparbuch)', req: true },
  ];
  return (
    <>
      <div style={{ fontSize:18, fontWeight:600, marginBottom:14 }}>Dokumente hochladen</div>
      <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
        {docs.map(d => (
          <div key={d.k} style={{ display:'flex', alignItems:'center', gap:14, padding:'12px 14px', border:'1px solid var(--border-default)', borderRadius:10, background:'#fff' }}>
            <div style={{ width:36, height:36, borderRadius:8, background:'var(--surface-sunken)', display:'flex', alignItems:'center', justifyContent:'center', color:'var(--fg-3)' }}><Icon.fileText size={16}/></div>
            <div style={{ flex:1 }}>
              <div style={{ fontSize:13, fontWeight:600 }}>{d.l}{d.req && <span style={{ color:'var(--danger-500)', marginLeft:4 }}>*</span>}</div>
              <div style={{ fontSize:11, color:'var(--fg-4)' }}>PDF, JPG · max 10 MB</div>
            </div>
            <Button variant="secondary" size="sm" leadingIcon={<Icon.upload size={13}/>}>Hochladen</Button>
          </div>
        ))}
      </div>
      <Dropzone hint="oder ziehe Dateien direkt hier rein"/>
    </>
  );
}
function SaStep6({ form, upd, onSubmit }) {
  return (
    <>
      <div style={{ fontSize:18, fontWeight:600, marginBottom:14 }}>SCHUFA & Unterschrift</div>
      <div style={{ padding:'14px 16px', background:'var(--surface-app)', border:'1px solid var(--border-default)', borderRadius:10, fontSize:12.5, lineHeight:1.6, color:'var(--fg-2)', maxHeight:160, overflowY:'auto' }}>
        Mit meiner Unterschrift erkläre ich, dass die gemachten Angaben wahrheitsgemäß sind und stimme zu, dass die Office Vertrieb GmbH sowie deren Finanzierungspartner zur Vorbereitung der Finanzierung Auskünfte über mich bei der SCHUFA Holding AG einholen und an diese Daten übermitteln dürfen. Die Datenverarbeitung erfolgt gemäß DSGVO Art. 6 Abs. 1 lit. b und f. Diese Einwilligung kann jederzeit für die Zukunft widerrufen werden.
      </div>
      <label style={{ display:'flex', alignItems:'flex-start', gap:10, marginTop:14, cursor:'pointer' }}>
        <input type="checkbox" checked={form.schufa} onChange={e=>upd('schufa', e.target.checked)} style={{ accentColor:'var(--accent)', marginTop:3 }}/>
        <span style={{ fontSize:13, lineHeight:1.5 }}>Ich willige in die SCHUFA-Anfrage und Datenverarbeitung ein.</span>
      </label>
      <div style={{ marginTop:18 }}>
        <Field label="Unterschrift (Name in Druckbuchstaben)" required>
          <Input value={form.signed} onChange={e=>upd('signed', e.target.value)} placeholder="Vor- und Nachname" style={{ fontFamily: 'Brush Script MT, cursive', fontSize:22, height:60 }}/>
        </Field>
      </div>
    </>
  );
}

// ===================== SELBSTAUSKUNFT (intern: Versand + Eingänge) =====================
function SelbstauskunftHub({ openSelbstauskunftPublic }) {
  const items = SAMPLE_KUNDEN.filter(k => k.selbstauskunft !== '—');
  const tones = { 'unterschrieben': 'green', 'eingegangen': 'blue', 'angefragt': 'amber' };
  return (
    <div style={{ flex:1, display:'flex', flexDirection:'column', minHeight:0 }}>
      <TopBar title="Selbstauskunft" subtitle="Versand, Eingänge und Status pro Interessent." actions={<Button variant="primary" size="sm" leadingIcon={<Icon.send size={14}/>}>Neue Anfrage senden</Button>}/>
      <div style={{ flex:1, overflowY:'auto', padding:'20px 28px' }}>
        <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:12, marginBottom:18 }}>
          <Stat label="Angefragt" value={items.filter(k=>k.selbstauskunft==='angefragt').length} icon={<Icon.send size={18}/>}/>
          <Stat label="Eingegangen" value={items.filter(k=>k.selbstauskunft==='eingegangen').length} icon={<Icon.fileCheck size={18}/>}/>
          <Stat label="Unterschrieben" value={items.filter(k=>k.selbstauskunft==='unterschrieben').length} icon={<Icon.signature size={18}/>}/>
          <Stat label="Conversion" value="68 %" icon={<Icon.trending size={18}/>} delta="+12 pp" deltaTone="green"/>
        </div>
        <Card padding={0}>
          <table style={{ width:'100%', borderCollapse:'collapse' }}>
            <thead><tr style={{ fontSize:11, color:'var(--fg-4)', textTransform:'uppercase', letterSpacing:'0.05em', textAlign:'left' }}>
              {['Kunde','Objekt','Status','Versendet','Berater',''].map(h=><th key={h} style={{ padding:'14px', borderBottom:'1px solid var(--border-default)', fontWeight:600 }}>{h}</th>)}
            </tr></thead>
            <tbody>
              {items.map((k,i) => {
                const obj = SAMPLE_OBJEKTE.find(o=>o.id===k.objektId);
                return (
                  <tr key={k.id} style={{ borderBottom: i<items.length-1?'1px solid var(--border-subtle)':0 }}>
                    <td style={{ padding:'14px' }}><div style={{ display:'flex', alignItems:'center', gap:10 }}><Avatar name={k.name} size={32}/><div><div style={{ fontSize:13, fontWeight:600 }}>{k.name}</div><div style={{ fontSize:11, color:'var(--fg-4)' }}>{k.email}</div></div></div></td>
                    <td style={{ padding:'14px', fontSize:12.5 }}>{obj?.titel || '—'}</td>
                    <td style={{ padding:'14px' }}><Pill tone={tones[k.selbstauskunft] || 'grey'} size="sm">{k.selbstauskunft}</Pill></td>
                    <td style={{ padding:'14px', fontSize:12, color:'var(--fg-3)' }}>{k.lastTouch}</td>
                    <td style={{ padding:'14px', fontSize:12.5 }}>{k.berater}</td>
                    <td style={{ padding:'14px', textAlign:'right' }}>
                      <Button variant="ghost" size="sm" trailingIcon={<Icon.arrowRight size={13}/>} onClick={()=>openSelbstauskunftPublic(k.objektId || 'OBJ-2041')}>Vorschau</Button>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </Card>
      </div>
    </div>
  );
}

// ===================== DOKUMENTE =====================
function Dropzone({ hint }) {
  const [hover, setHover] = React.useState(false);
  return (
    <div onDragOver={e=>{e.preventDefault();setHover(true);}} onDragLeave={()=>setHover(false)} onDrop={e=>{e.preventDefault();setHover(false);}}
      style={{ border:`1.5px dashed ${hover?'var(--accent)':'var(--border-strong)'}`, background: hover?'var(--accent-soft)':'var(--surface-sunken)', borderRadius:12, padding:'20px 16px', display:'flex', flexDirection:'column', alignItems:'center', gap:10, color:'var(--fg-3)', fontSize:13, transition:'all 160ms', marginTop:14 }}>
      <span style={{ color:'var(--wholix-amber-600)' }}><Icon.cloudUp size={28}/></span>
      <div style={{ textAlign:'center' }}>{hint || 'Dateien hier ablegen oder'}</div>
      <Button variant="secondary" size="sm" leadingIcon={<Icon.upload size={13}/>}>Datei wählen</Button>
    </div>
  );
}
function DokumenteListe({ scope }) {
  const docs = [
    { name: 'Energieausweis_Stadtvilla.pdf', objekt:'OBJ-2041', kategorie:'Energieausweis', size:'1,2 MB', von:'Sandra K.', datum:'02.05.2026' },
    { name: 'Teilungserklaerung_Maximilianhoefe.pdf', objekt:'OBJ-2042', kategorie:'WEG', size:'4,8 MB', von:'Tim R.', datum:'28.04.2026' },
    { name: 'Grundriss_Loft12.pdf', objekt:'OBJ-2039', kategorie:'Grundriss', size:'820 KB', von:'Mira H.', datum:'22.04.2026' },
    { name: 'Selbstauskunft_Albrecht.pdf', objekt:'OBJ-2041', kategorie:'Selbstauskunft', size:'340 KB', von:'M. Albrecht', datum:'02.05.2026' },
    { name: 'Gehaltsnachweise_Vogt.zip', objekt:'OBJ-2042', kategorie:'Einkommen', size:'2,1 MB', von:'F. Vogt', datum:'30.04.2026' },
    { name: 'Notarvertrag_Entwurf_Vogt.pdf', objekt:'OBJ-2042', kategorie:'Vertrag', size:'1,8 MB', von:'Notar Müller', datum:'29.04.2026' },
  ];
  return (
    <Card padding={0}>
      <div style={{ padding:'14px 18px', borderBottom:'1px solid var(--border-default)', display:'flex', alignItems:'center', justifyContent:'space-between' }}>
        <div><div style={{ fontSize:15, fontWeight:600 }}>Dokumente {scope ? `· ${scope}` : ''}</div><div style={{ fontSize:11.5, color:'var(--fg-4)', marginTop:2 }}>{docs.length} Dateien · {fmtNum(docs.length*1200)} KB gesamt</div></div>
        <Button variant="primary" size="sm" leadingIcon={<Icon.upload size={13}/>}>Hochladen</Button>
      </div>
      <table style={{ width:'100%', borderCollapse:'collapse' }}>
        <thead><tr style={{ fontSize:11, color:'var(--fg-4)', textTransform:'uppercase', letterSpacing:'0.05em', textAlign:'left' }}>
          {['Datei','Kategorie','Objekt','Hochgeladen von','Größe','Datum',''].map(h=><th key={h} style={{ padding:'12px 18px', borderBottom:'1px solid var(--border-default)', fontWeight:600 }}>{h}</th>)}
        </tr></thead>
        <tbody>
          {docs.map((d,i) => (
            <tr key={i} style={{ borderBottom: i<docs.length-1?'1px solid var(--border-subtle)':0 }}>
              <td style={{ padding:'14px 18px' }}><div style={{ display:'flex', alignItems:'center', gap:10 }}><span style={{ color:'var(--danger-500)' }}><Icon.pdf size={20}/></span><span style={{ fontSize:13, fontWeight:500 }}>{d.name}</span></div></td>
              <td style={{ padding:'14px 18px' }}><Tag>{d.kategorie}</Tag></td>
              <td style={{ padding:'14px 18px', fontSize:12, fontFamily:'var(--font-mono)' }}>{d.objekt}</td>
              <td style={{ padding:'14px 18px', fontSize:12.5 }}>{d.von}</td>
              <td style={{ padding:'14px 18px', fontSize:12, color:'var(--fg-3)' }}>{d.size}</td>
              <td style={{ padding:'14px 18px', fontSize:12, color:'var(--fg-3)' }}>{d.datum}</td>
              <td style={{ padding:'14px 18px', textAlign:'right' }}><IconButton icon={<Icon.download size={14}/>} size={28}/></td>
            </tr>
          ))}
        </tbody>
      </table>
    </Card>
  );
}
function DokumenteHub() {
  return (
    <div style={{ flex:1, display:'flex', flexDirection:'column', minHeight:0 }}>
      <TopBar title="Dokumente" subtitle="Zentrales Dokumenten-Center für alle Objekte und Kunden." actions={<Button variant="primary" size="sm" leadingIcon={<Icon.upload size={14}/>}>Datei hochladen</Button>}/>
      <div style={{ flex:1, overflowY:'auto', padding:'20px 28px' }}><DokumenteListe/></div>
    </div>
  );
}

// ===================== RECHNER-SUITE =====================
function RechnerHub() {
  const [tab, setTab] = React.useState('afa');
  const [params, setParams] = React.useState({ kaufpreis:850000, ek:200000, miete:1900, bewirtschaftung:160, zinsPct:3.8, tilgungPct:2, steuersatz:0.42, bundesland:'BY', afaTyp:'sonder-7b' });
  const cf = cashflow({ ...params, gebaeudewertPct:0.8 });
  const upd = (k,v) => setParams(p=>({...p, [k]:v}));
  const TabBtn = ({ k, label, ic }) => {
    const Ic = Icon[ic];
    return (
      <button onClick={()=>setTab(k)} style={{ display:'flex', alignItems:'center', gap:8, padding:'10px 14px', background: tab===k?'var(--accent-soft)':'transparent', border:0, borderRadius:8, cursor:'pointer', fontFamily:'inherit', color: tab===k?'var(--wholix-amber-800)':'var(--fg-2)', fontWeight: tab===k?600:500, fontSize:13 }}>
        <Ic size={14}/> {label}
      </button>
    );
  };
  return (
    <div style={{ flex:1, display:'flex', flexDirection:'column', minHeight:0 }}>
      <TopBar title="Rechner" subtitle="AfA, Cashflow, Tilgung, Nebenkosten — alles, was Anlageimmobilien brauchen."/>
      <div style={{ display:'flex', gap:6, padding:'12px 28px', borderBottom:'1px solid var(--border-default)', overflowX:'auto' }}>
        <TabBtn k="afa" label="AfA" ic="trending"/>
        <TabBtn k="cashflow" label="Cashflow" ic="euro"/>
        <TabBtn k="tilgung" label="Tilgungsplan" ic="trendingDown"/>
        <TabBtn k="nebenkosten" label="Kaufnebenkosten" ic="receipt"/>
        <TabBtn k="rendite" label="Renditen" ic="star"/>
      </div>
      <div style={{ flex:1, overflowY:'auto', padding:'20px 28px', display:'grid', gridTemplateColumns:'320px 1fr', gap:18 }}>
        <Card padding={20}>
          <div style={{ fontSize:15, fontWeight:600, marginBottom:14 }}>Annahmen</div>
          <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
            <Field label={`Kaufpreis ${fmtEUR(params.kaufpreis)}`}><input type="range" min={150000} max={3000000} step={5000} value={params.kaufpreis} onChange={e=>upd('kaufpreis', +e.target.value)} style={{ width:'100%', accentColor:'var(--accent)' }}/></Field>
            <Field label={`Eigenkapital ${fmtEUR(params.ek)}`}><input type="range" min={0} max={params.kaufpreis} step={5000} value={params.ek} onChange={e=>upd('ek', +e.target.value)} style={{ width:'100%', accentColor:'var(--accent)' }}/></Field>
            <Field label={`Miete kalt / Monat ${fmtEUR(params.miete)}`}><input type="range" min={300} max={10000} step={50} value={params.miete} onChange={e=>upd('miete', +e.target.value)} style={{ width:'100%', accentColor:'var(--accent)' }}/></Field>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:8 }}>
              <Field label={`Zins ${params.zinsPct.toFixed(2)}%`}><input type="range" min={1} max={7} step={0.05} value={params.zinsPct} onChange={e=>upd('zinsPct', +e.target.value)} style={{ 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=>upd('tilgungPct', +e.target.value)} style={{ 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=>upd('steuersatz', +e.target.value)} style={{ width:'100%', accentColor:'var(--accent)' }}/></Field>
            <Field label="Bundesland"><Select value={params.bundesland} onChange={e=>upd('bundesland', e.target.value)}>{Object.entries(BL_LABEL).map(([k,v])=><option key={k} value={k}>{v}</option>)}</Select></Field>
            <Field label="AfA-Profil"><Select value={params.afaTyp} onChange={e=>upd('afaTyp', e.target.value)}>{Object.entries(AFA_PROFILE).map(([k,v])=><option key={k} value={k}>{v.label}</option>)}</Select></Field>
          </div>
        </Card>
        <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
          {tab === 'afa' && <Card padding={20}>
            <div style={{ fontSize:16, fontWeight:600, marginBottom:14 }}>AfA-Verlauf — {AFA_PROFILE[params.afaTyp].label}</div>
            <BarChart data={afaSchedule({ profil: params.afaTyp, gebaeudewert: params.kaufpreis*0.8, sanierungskosten: params.afaTyp==='denkmal-7i'?params.kaufpreis*0.5:0, jahre:12 }).map(s=>({ label:'J'+s.jahr, value:s.betrag }))}/>
          </Card>}
          {tab === 'cashflow' && <>
            <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:12 }}>
              <Stat label="Cashflow / Monat n.St." value={fmtEUR(cf.cfMonatNach)} deltaTone={cf.cfMonatNach>=0?'green':'red'}/>
              <Stat label="Steuerersparnis J1" value={fmtEUR(Math.max(0, cf.ersparnis))}/>
              <Stat label="EK-Rendite n.St." value={fmtPct(cf.ekRendite, 2)}/>
              <Stat label="Brutto-Mietrendite" value={fmtPct(cf.bruttoMietrendite, 2)}/>
            </div>
          </>}
          {tab === 'tilgung' && <Card padding={20}>
            <div style={{ fontSize:16, fontWeight:600, marginBottom:4 }}>Tilgungsplan</div>
            <div style={{ fontSize:12, color:'var(--fg-4)', marginBottom:12 }}>Annuität {fmtEUR(cf.annuitaet.monat)}/Monat über 10 Jahre — danach Anschlussfinanzierung.</div>
            <table style={{ width:'100%', borderCollapse:'collapse', fontSize:12.5 }}>
              <thead><tr style={{ color:'var(--fg-4)', fontSize:11, textTransform:'uppercase' }}>
                <th style={{ textAlign:'left', padding:'8px 0' }}>Jahr</th><th style={{ textAlign:'right' }}>Zinsen</th><th style={{ textAlign:'right' }}>Tilgung</th><th style={{ textAlign:'right' }}>Annuität</th><th style={{ textAlign:'right' }}>Restschuld</th>
              </tr></thead>
              <tbody>{tilgungsplan({ darlehen: cf.darlehen, zinsPct: params.zinsPct, tilgungPct: params.tilgungPct, jahre:10 }).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>}
          {tab === 'nebenkosten' && <Card padding={20}>
            <div style={{ fontSize:16, fontWeight:600, marginBottom:14 }}>Kaufnebenkosten — {BL_LABEL[params.bundesland]}</div>
            <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:12 }}>
              {[['GrESt '+cf.nebenkosten.grEStPct+' %', cf.nebenkosten.grESt],['Notar & GB 1,5 %', cf.nebenkosten.notar],['Makler '+cf.nebenkosten.maklerPct+' %', cf.nebenkosten.makler],['Summe NK', cf.nebenkosten.summe, true]].map(([l,v,b],i) => (
                <div key={i} style={{ background: b?'var(--accent-soft)':'var(--surface-app)', padding:14, borderRadius:10 }}>
                  <div style={{ fontSize:11, color:'var(--fg-4)', fontWeight:600 }}>{l}</div>
                  <div style={{ fontSize:18, fontWeight:700, marginTop:4, color: b?'var(--wholix-amber-800)':'var(--fg-1)' }}>{fmtEUR(v)}</div>
                </div>
              ))}
            </div>
          </Card>}
          {tab === 'rendite' && <Card padding={20}>
            <div style={{ fontSize:16, fontWeight:600, marginBottom:14 }}>Renditekennzahlen</div>
            {[['Brutto-Mietrendite', cf.bruttoMietrendite, 'Jahresmiete / Kaufpreis'], ['Netto-Mietrendite', cf.nettoMietrendite, '(Miete – Bewirtschaftung) / (Kaufpreis + NK)'], ['EK-Rendite n.St.', cf.ekRendite, 'Cashflow n.St. / Eigenkapital']].map(([l,v,h]) => (
              <div key={l} style={{ display:'flex', justifyContent:'space-between', alignItems:'center', padding:'14px 0', borderBottom:'1px solid var(--border-subtle)' }}>
                <div><div style={{ fontSize:14, fontWeight:600 }}>{l}</div><div style={{ fontSize:11.5, color:'var(--fg-4)', marginTop:2 }}>{h}</div></div>
                <div style={{ fontSize:22, fontWeight:700, color: v>=0?'var(--success-500)':'var(--danger-500)' }}>{fmtPct(v, 2)}</div>
              </div>
            ))}
          </Card>}
        </div>
      </div>
    </div>
  );
}

// ===================== EMAIL-KAMPAGNEN (vereinfacht) =====================
function Kampagnen() {
  return (
    <div style={{ flex:1, display:'flex', flexDirection:'column', minHeight:0 }}>
      <TopBar title="E-Mail-Kampagnen" subtitle="KI-gestützte Outreach-Kampagnen für Interessenten." actions={<Button variant="primary" size="sm" leadingIcon={<Icon.plus size={14}/>}>Neue Kampagne</Button>}/>
      <div style={{ flex:1, overflowY:'auto', padding:'20px 28px' }}>
        <InfoBanner>Diese E-Mail wird automatisch aus deinen Objektdaten und dem Wholix-Lead-Profil generiert.</InfoBanner>
        <div style={{ display:'grid', gridTemplateColumns:'1.5fr 1fr', gap:18, marginTop:18 }}>
          <Card padding={20}>
            <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:14 }}>
              <div style={{ width:24, height:24, borderRadius:999, background:'var(--accent)', color:'var(--fg-on-amber)', fontSize:12, fontWeight:700, display:'flex', alignItems:'center', justifyContent:'center' }}>1</div>
              <b style={{ fontSize:15 }}>Anlage-Highlights Mai 2026</b>
              <Pill tone="green" size="sm">aktiv</Pill>
            </div>
            <Card padding={18} style={{ background:'var(--surface-app)' }}>
              <div style={{ fontSize:14, lineHeight:1.7, color:'var(--fg-2)', whiteSpace:'pre-wrap' }}>
{`Betreff: Neue Anlage-Highlights — bis zu 9 % AfA möglich

Hallo [Vorname],

basierend auf deinem Suchprofil ([Stadt], Anlage bis [Budget]) habe ich
3 neue Objekte mit besonders attraktiver Steuerwirkung für dich zusammengestellt:

→ Speicherstadt Loft 12 (Hamburg) — Denkmal-AfA bis 9 % p.a.
→ Maximilianhöfe WE 04 (München) — Sonder-AfA §7b
→ Quartier Friedrichspark (Berlin) — Degressive AfA 5 %

Die kompletten Online-Exposés inkl. AfA-Rechner findest du unter:
https://app.wholix.de/x/highlights-mai

Beste Grüße
[Berater]`}
              </div>
            </Card>
            <div style={{ display:'flex', justifyContent:'center', marginTop:14 }}>
              <Button variant="primary" leadingIcon={<Icon.sparkle size={14}/>}>E-Mail neu generieren</Button>
            </div>
          </Card>
          <Card padding={20}>
            <div style={{ fontSize:15, fontWeight:600, marginBottom:14 }}>Performance</div>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10 }}>
              <Stat label="Empfänger" value="186"/>
              <Stat label="Öffnungsrate" value="32 %" deltaTone="green" delta="+8 pp"/>
              <Stat label="Klickrate" value="14 %"/>
              <Stat label="Selbstauskünfte" value="9"/>
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
}

// ===================== AI CHAT =====================
function AiChat() {
  const [msgs, setMsgs] = React.useState([{ role:'ai', text:'Hallo Sandra, wie kann ich dir heute helfen?' }]);
  const [q, setQ] = React.useState('');
  const send = async () => {
    if (!q.trim()) return;
    const m = q;
    setMsgs(p => [...p, { role:'user', text:m }, { role:'ai', text:'…' }]);
    setQ('');
    try {
      const r = await window.claude.complete(`Du bist Wholix-Assistent für deutsche Immobilienvertriebe. Antworte kurz, im Du-Format. Frage: ${m}`);
      setMsgs(p => [...p.slice(0,-1), { role:'ai', text:r }]);
    } catch(e) {
      setMsgs(p => [...p.slice(0,-1), { role:'ai', text: 'Tipp: Schau dir das passende AfA-Profil im Rechner an — Sonder-AfA §7b kann bei Neubauten den Cashflow erheblich verbessern.' }]);
    }
  };
  return (
    <div style={{ flex:1, display:'flex', flexDirection:'column', minHeight:0 }}>
      <TopBar title="AI-Assistent" subtitle="Frag mich nach Objekten, Cashflow-Szenarien oder Kunden."/>
      <div style={{ flex:1, overflowY:'auto', padding:'20px 28px', display:'flex', flexDirection:'column', gap:12, maxWidth:780, width:'100%', alignSelf:'center', boxSizing:'border-box' }}>
        {msgs.map((m,i) => (
          <div key={i} style={{ display:'flex', gap:10, alignSelf: m.role==='user'?'flex-end':'flex-start', maxWidth:'85%' }}>
            {m.role==='ai' && <div style={{ width:30, height:30, borderRadius:999, background:'var(--accent-soft)', color:'var(--wholix-amber-700)', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}><Icon.bot size={14}/></div>}
            <div style={{ background: m.role==='user'?'var(--accent)':'#fff', color: m.role==='user'?'var(--fg-on-amber)':'var(--fg-1)', border: m.role==='user'?0:'1px solid var(--border-default)', padding:'10px 14px', borderRadius:12, fontSize:13.5, lineHeight:1.5 }}>{m.text}</div>
          </div>
        ))}
      </div>
      <div style={{ padding:'14px 28px', borderTop:'1px solid var(--border-default)', background:'#fff', display:'flex', gap:8, maxWidth:780, width:'100%', alignSelf:'center', boxSizing:'border-box' }}>
        <Input placeholder="Frage stellen…" value={q} onChange={e=>setQ(e.target.value)} onKeyDown={e=>{ if(e.key==='Enter')send(); }}/>
        <Button variant="primary" leadingIcon={<Icon.send size={14}/>} onClick={send}>Senden</Button>
      </div>
    </div>
  );
}

window.KundeDetail = KundeDetail;
window.PartnerListe = PartnerListe;
window.Provisionen = Provisionen;
window.ExposeListe = ExposeListe;
window.ExposeEditor = ExposeEditor;
window.ExposePublic = ExposePublic;
window.SelbstauskunftPublic = SelbstauskunftPublic;
window.SelbstauskunftHub = SelbstauskunftHub;
window.DokumenteHub = DokumenteHub;
window.DokumenteListe = DokumenteListe;
window.RechnerHub = RechnerHub;
window.Kampagnen = Kampagnen;
window.AiChat = AiChat;
window.Dropzone = Dropzone;
