/* ═══════════════════════════════════════════════════════════════
   bezirk.live — Screens Part 2: Compose, Chat, Profile, Notifications
   ═══════════════════════════════════════════════════════════════ */

// ───────────────────────────────────────────────────────────────
// COMPOSE SHEET — completely overhauled
// Step 0: Type-Picker  →  Step 1: Form  →  Step 2: Preview
// ───────────────────────────────────────────────────────────────
function ComposeSheet({open, onClose, onPosted}){
  const [type,setType] = useState(null);
  const state = window._appState;

  if (!open) return null;

  const tier = state.me.tier;
  const isPremium = tier==='basic' || tier==='pro' || tier==='premium';

  // Grouped, visual type picker — feels less like a form, more like a choice
  const GROUPS = [
    {
      label: 'Was willst du teilen?',
      items: [
        {k:'frage',    l:'Frage stellen',       sub:'Diskussion mit der Nachbarschaft', i:'💬', c:T.green, bg:T.greenL, big:true},
      ],
    },
    {
      label: 'Hilfe & Soforthilfe',
      items: [
        {k:'sos',      l:'Hilfe suchen',         sub:'Babysitten, Einkaufen, Tragen …',    i:'🆘', c:T.care, bg:T.careL},
        {k:'sos-help', l:'Hilfe anbieten',       sub:'Ich kann jemandem unter die Arme greifen', i:'🤝', c:T.green, bg:T.greenL},
      ],
    },
    {
      label: 'Marktplatz',
      items: [
        {k:'angebot',  l:'Anbieten',             sub:'Tausch · Verleih · Verschenken',     i:'📦', c:T.amber, bg:T.amberL},
        {k:'gesuch',   l:'Suche',                sub:'Ich suche etwas Bestimmtes',         i:'🔍', c:T.purple, bg:T.purpleL},
      ],
    },
    {
      label: 'Geschäft',
      items: [
        {k:'deal',     l:'Deal posten',          sub:'Aktion für deinen Bezirk',           i:'⚡', c:T.gold, bg:T.goldL, premium:true},
      ],
    },
  ];

  return (
    <Sheet open={open} onClose={()=>{ setType(null); onClose(); }} title={null} height="92vh">
      <div style={{padding: type ? '0' : '4px 22px 32px'}}>
        {!type && (
          <div className="aIn">
            {/* Header */}
            <div style={{marginBottom:18}}>
              <div style={{fontFamily:'Fraunces, serif', fontSize:26, fontWeight:700, letterSpacing:'-.6px', lineHeight:1.1, marginBottom:5}}>
                Was möchtest<br/>du teilen?
              </div>
              <div style={{fontSize:13, color:T.sec, fontWeight:500, lineHeight:1.45}}>
                📍 Du postest in <strong style={{color:T.text}}>{state.me.bezirk || 'deinem Ort'}</strong> · sichtbar für deine Nachbar:innen
              </div>
            </div>

            {GROUPS.map((g, gi) => (
              <div key={gi} style={{marginBottom: gi<GROUPS.length-1 ? 18 : 0}}>
                {gi > 0 && <div style={{fontSize:10.5, fontWeight:800, letterSpacing:'.5px', color:T.muted, marginBottom:8, paddingLeft:2}}>{g.label.toUpperCase()}</div>}

                <div style={{display:'flex', flexDirection:'column', gap:8}}>
                  {g.items.map(t => {
                    const locked = t.premium && !isPremium;
                    return (
                      <button key={t.k} onClick={()=>!locked && setType(t.k)} disabled={locked} style={{
                        padding: t.big ? '18px 16px' : '14px 14px',
                        borderRadius:13,
                        border:`1.5px solid ${locked?T.bdr: t.c+'30'}`,
                        background: locked?T.bg : t.bg,
                        display:'flex', gap:13, alignItems:'center', cursor:locked?'not-allowed':'pointer',
                        textAlign:'left', opacity: locked?0.55:1, width:'100%',
                        fontFamily:'inherit', transition:'transform .15s, box-shadow .15s',
                      }}
                      onMouseDown={e => !locked && (e.currentTarget.style.transform='scale(.98)')}
                      onMouseUp={e => e.currentTarget.style.transform='scale(1)'}
                      onMouseLeave={e => e.currentTarget.style.transform='scale(1)'}
                      >
                        <div style={{
                          width: t.big?54:44, height: t.big?54:44, borderRadius:12,
                          background:'#fff', display:'flex', alignItems:'center', justifyContent:'center',
                          fontSize: t.big?28:22, flexShrink:0,
                          boxShadow:'0 2px 6px rgba(0,0,0,.04)',
                        }}>{t.i}</div>
                        <div style={{flex:1, minWidth:0}}>
                          <div style={{fontSize: t.big?16:14.5, fontWeight:700, color:t.c, display:'flex', alignItems:'center', gap:6, marginBottom:2}}>
                            {t.l}
                            {locked && <span style={{fontSize:9, fontWeight:800, color:T.gold, background:'#fff', padding:'2px 6px', borderRadius:4, letterSpacing:'.3px'}}>PREMIUM</span>}
                          </div>
                          <div style={{fontSize: t.big?13:12, color:T.sec, fontWeight:500, lineHeight:1.4}}>{t.sub}</div>
                        </div>
                        <div style={{color:locked?T.muted:t.c, fontSize:20, fontWeight:300}}>{locked?'🔒':'›'}</div>
                      </button>
                    );
                  })}
                </div>
              </div>
            ))}
          </div>
        )}
        {type && <ComposeForm type={type} onBack={()=>setType(null)} onPosted={(id)=>{ setType(null); onPosted(id); }}/>}
      </div>
    </Sheet>
  );
}

// ─── Bezirk-Banner: gleiches DNA über alle Compose-Typen ───────
function ComposeBezirkBanner({type, color}){
  const state = window._appState;
  const labels = {
    sos:       { kind:'HILFE-ANFRAGE',  desc:'Nachbar:innen werden priorisiert benachrichtigt. Aktiv 24h.' },
    'sos-help':{ kind:'HILFE-ANGEBOT',  desc:'Sichtbar für alle in deinem Ort — Nachbar:innen können dich direkt anschreiben.' },
    angebot:   { kind:'MARKTPLATZ',     desc:'Sichtbar in deinem Ort und im Umkreis von 20 km.' },
    gesuch:    { kind:'GESUCH',         desc:'Nachbar:innen mit passenden Sachen sehen deinen Suchaufruf.' },
    frage:     { kind:'ÖFFENTLICHE DISKUSSION', desc:'Alle Nachbar:innen sehen deine Frage und können öffentlich antworten. Eine echte Diskussion — direkt aus deiner Nachbarschaft.' },
    deal:      { kind:'DEAL',           desc:'Wird Nachbar:innen im Hero-Slot rotierend prominent angezeigt.' },
  };
  const L = labels[type] || labels.angebot;
  const bg = `linear-gradient(135deg, ${color}, ${color}DD)`;
  return (
    <div style={{padding:'14px 16px', background:bg, borderRadius:14, marginBottom:18, color:'#fff', position:'relative', overflow:'hidden'}}>
      <div style={{position:'absolute', top:-20, right:-20, width:100, height:100, borderRadius:'50%', background:'rgba(255,255,255,.08)'}}></div>
      <div style={{position:'relative', zIndex:1}}>
        <div style={{display:'flex', alignItems:'center', gap:8, marginBottom:5}}>
          <span style={{fontSize:11, fontWeight:800, letterSpacing:'.6px', color:'rgba(255,255,255,.85)'}}>{L.kind}</span>
          <span style={{width:3, height:3, borderRadius:'50%', background:'rgba(255,255,255,.4)'}}></span>
          <span style={{fontSize:11, fontWeight:700, letterSpacing:'.3px', color:'rgba(255,255,255,.85)'}}>📍 {state.me.bezirk || 'Dein Ort'}</span>
        </div>
        <div style={{fontSize:12.5, color:'rgba(255,255,255,.92)', fontWeight:500, lineHeight:1.45}}>{L.desc}</div>
      </div>
    </div>
  );
}

// ─── Photo-Upload: drag, tap or paste ───────────────────────────
function PhotoUpload({photos, onChange, max=4, accent}){
  const fileRef = useRef(null);
  const handle = (files) => {
    const fs = Array.from(files || []).filter(f => f.type.startsWith('image/'));
    const slots = max - photos.length;
    const remaining = fs.slice(0, slots);
    Promise.all(remaining.map(f => new Promise(res => {
      const r = new FileReader();
      r.onload = e => res({ id:'ph_'+Date.now()+'_'+Math.random().toString(36).slice(2,5), src: e.target.result, name: f.name });
      r.readAsDataURL(f);
    }))).then(newOnes => onChange([...photos, ...newOnes]));
  };
  return (
    <div style={{marginBottom:14}}>
      <div style={{fontSize:12, fontWeight:700, color:T.sec, marginBottom:7, letterSpacing:'.2px'}}>Fotos (optional, max. {max})</div>
      <div style={{display:'grid', gridTemplateColumns:'repeat(4, 1fr)', gap:8}}>
        {photos.map((p, i) => (
          <div key={p.id} style={{position:'relative', aspectRatio:'1/1', borderRadius:11, overflow:'hidden', background:T.bg, border:`1px solid ${T.bdr}`}}>
            <img src={p.src} alt="" style={{width:'100%', height:'100%', objectFit:'cover', display:'block'}}/>
            <button onClick={()=>onChange(photos.filter(x=>x.id!==p.id))} style={{
              position:'absolute', top:4, right:4, width:22, height:22, borderRadius:'50%',
              background:'rgba(0,0,0,.65)', color:'#fff', border:'none', cursor:'pointer',
              fontSize:13, fontWeight:600, display:'flex', alignItems:'center', justifyContent:'center',
              padding:0, lineHeight:1,
            }}>×</button>
            {i===0 && <div style={{position:'absolute', bottom:4, left:4, fontSize:9, fontWeight:800, color:'#fff', background:'rgba(0,0,0,.7)', padding:'2px 6px', borderRadius:4, letterSpacing:'.3px'}}>VORSCHAU</div>}
          </div>
        ))}
        {photos.length < max && (
          <button onClick={()=>fileRef.current?.click()} style={{
            aspectRatio:'1/1', borderRadius:11,
            background:'#fff', border:`1.5px dashed ${accent||T.green}40`,
            cursor:'pointer', display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center',
            gap:3, color: accent||T.green, fontFamily:'inherit',
          }}>
            <div style={{fontSize:22, lineHeight:1}}>📷</div>
            <div style={{fontSize:10, fontWeight:700, letterSpacing:'.3px'}}>Foto +</div>
          </button>
        )}
      </div>
      <input ref={fileRef} type="file" accept="image/*" multiple style={{display:'none'}} onChange={e=>{ handle(e.target.files); e.target.value=''; }}/>
      {photos.length === 0 && (
        <div style={{fontSize:10.5, color:T.muted, fontWeight:600, marginTop:6, lineHeight:1.4}}>💡 Posts mit Foto bekommen 3× mehr Aufmerksamkeit</div>
      )}
    </div>
  );
}

function ComposeForm({type, onBack, onPosted}){
  const state = window._appState;
  const A = window.AppStore.actions;
  const [data,setData] = useState({
    title:'', description:'', category:'',
    sosCategory:'Einkaufen', urgency:'heute', timeFrom:'10:00', timeTo:'12:00',
    payment:'free', paymentAmount:'',
    angebotKind:'tausch', price:0, priceLabel:'Tausch',
    originalPrice:'', deal_price:'', savings:'',
    photos: [],
  });
  const [preview, setPreview] = useState(false);

  const typeMeta = {
    sos:       { color:T.care,  cta:'Hilfe-Anfrage posten', label:'Hilfe suchen', emoji:'🆘' },
    'sos-help':{ color:T.green, cta:'Angebot posten',       label:'Hilfe anbieten', emoji:'🤝' },
    angebot:   { color:T.amber, cta:'Angebot posten',       label:'Anbieten', emoji:'📦' },
    gesuch:    { color:T.purple,cta:'Gesuch posten',        label:'Suche', emoji:'🔍' },
    frage:     { color:T.green, cta:'Frage öffentlich stellen', label:'Frage stellen', emoji:'💬' },
    deal:      { color:T.gold,  cta:'Deal veröffentlichen',  label:'Deal posten', emoji:'⚡' },
  }[type] || { color:T.green, cta:'Posten', label:'Posten', emoji:'📍' };

  const titleValid = data.title.trim().length >= 3;

  function buildPost(){
    const colors = {
      sos:['#FAD0D0','#C84A4A'], 'sos-help':['#C8E0C0','#5A9060'],
      angebot:['#F0D8A8','#D4A040'], gesuch:['#D8C0E0','#7A4FB8'],
      frage:['#C0DCD4','#0F4C44'], deal:['#FBE4D8','#D47828'],
    };
    const icons = {sos:'🆘','sos-help':'🤝',angebot:'📦',gesuch:'🔍',frage:'💬',deal:'⚡'};
    const post = {
      type: type==='sos-help'?'angebot':type,
      title: data.title.trim(),
      sub: data.description.split('\n')[0].slice(0,80) || (data.title.slice(0, 80)),
      description: data.description,
      icon: icons[type] || '📍',
      gradient: colors[type] || ['#E0E0DD','#A8A59E'],
      distance: 0,
      photos: data.photos,
      image: data.photos[0]?.src || null,
    };
    if (type==='sos'){
      Object.assign(post, {sosCategory:data.sosCategory, urgency:data.urgency, timeFrom:data.timeFrom, timeTo:data.timeTo, payment:data.payment, paymentAmount:data.paymentAmount});
    }
    if (type==='angebot' || type==='sos-help'){
      Object.assign(post, {angebotKind:data.angebotKind, price:parseFloat(data.price)||0, priceLabel:data.priceLabel});
    }
    if (type==='deal'){
      Object.assign(post, {price:parseFloat(data.deal_price)||0, originalPrice:parseFloat(data.originalPrice)||null, savings:parseInt(data.savings)||null, featured:true});
    }
    return post;
  }

  const [uploading, setUploading] = useState(false);

  async function submit(){
    if (!titleValid) return alert('Bitte fülle den Titel aus (mind. 3 Zeichen).');

    // ─── Fotos zu Supabase Storage hochladen ─────────────────
    let uploadedPhotos = data.photos;
    if (data.photos.length > 0 && window.BL?.user && window.BL.uploadDataURL){
      setUploading(true);
      try {
        uploadedPhotos = await Promise.all(data.photos.map(async (ph) => {
          // Bereits eine URL? Dann durchreichen.
          if (ph.src && /^https?:/.test(ph.src)) return ph;
          try {
            const url = await window.BL.uploadDataURL('posts', ph.src);
            return { ...ph, src: url };
          } catch(e){
            console.warn('[upload] Foto konnte nicht hochgeladen werden, nutze base64:', e);
            return ph;
          }
        }));
      } catch(e){
        console.error('[upload] error', e);
      } finally {
        setUploading(false);
      }
    }

    // Build post mit den hochgeladenen URLs
    const finalPost = (() => {
      const base = buildPost();
      return {
        ...base,
        photos: uploadedPhotos,
        image: uploadedPhotos[0]?.src || null,
      };
    })();

    const id = A.addPost(finalPost);
    A.notify({type:'post', title:'Post veröffentlicht!', body:`Dein Post „${data.title.trim()}" ist live.`, postId:id});
    onPosted(id);
  }

  // ─── PREVIEW MODUS ────────────────────────────────────
  if (preview){
    const previewPost = { ...buildPost(), createdAt: Date.now(), expiresAt: Date.now() + 24*3600*1000, ownerId:'me', owner:state.me.name||'Du', ownerAvatar:state.me.avatar, ownerTier:state.me.tier, ownerVerified:state.me.verified, bezirk:state.me.bezirk };
    return (
      <div className="aIn" style={{padding:'18px 22px 22px'}}>
        <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:14}}>
          <button onClick={()=>setPreview(false)} style={{background:'none',border:'none',color:T.sec,fontSize:13,fontWeight:600,cursor:'pointer', padding:0, fontFamily:'inherit'}}>‹ Bearbeiten</button>
          <div style={{fontSize:11, fontWeight:800, color:T.muted, letterSpacing:'.4px'}}>VORSCHAU</div>
        </div>
        <div style={{fontFamily:'Fraunces, serif', fontSize:22, fontWeight:700, letterSpacing:'-.5px', marginBottom:14}}>So sieht dein Post aus</div>

        {/* Mock post card */}
        <div style={{background:'#fff', border:`1px solid ${T.bdr}`, borderRadius:14, padding:14, marginBottom:16, boxShadow:'0 2px 8px rgba(0,0,0,.03)'}}>
          {previewPost.image && (
            <div style={{height:180, borderRadius:11, marginBottom:12, overflow:'hidden'}}>
              <img src={previewPost.image} alt="" style={{width:'100%', height:'100%', objectFit:'cover', display:'block'}}/>
            </div>
          )}
          {!previewPost.image && (
            <div style={{height:120, borderRadius:11, marginBottom:12, background:`linear-gradient(135deg, ${previewPost.gradient[0]}, ${previewPost.gradient[1]})`, display:'flex', alignItems:'center', justifyContent:'center', fontSize:50}}>{previewPost.icon}</div>
          )}
          <div style={{display:'flex', gap:6, marginBottom:8, flexWrap:'wrap'}}>
            <Badge type={previewPost.type}/>
            {previewPost.urgency==='heute' && <span style={{fontSize:10, fontWeight:800, color:'#fff', background:T.care, padding:'2px 6px', borderRadius:4}}>HEUTE</span>}
          </div>
          <div style={{fontFamily:'Fraunces, serif', fontSize:18, fontWeight:700, lineHeight:1.2, marginBottom:5}}>{previewPost.title}</div>
          {previewPost.description && <div style={{fontSize:13, color:T.sec, fontWeight:500, lineHeight:1.5, marginBottom:10, whiteSpace:'pre-wrap'}}>{previewPost.description.slice(0,200)}{previewPost.description.length>200?'…':''}</div>}
          <div style={{display:'flex', gap:10, alignItems:'center', fontSize:11.5, color:T.muted, fontWeight:600}}>
            <Avatar a={state.me.avatar} size={22} name={state.me.name||'Du'}/>
            <span style={{color:T.text, fontWeight:700}}>{state.me.name || 'Du'}</span>
            <span>·</span>
            <span>📍 {state.me.bezirk || 'Dein Ort'}</span>
            <span>·</span>
            <span>gerade eben</span>
          </div>
        </div>

        <Btn full kind="primary" size="lg" onClick={submit} disabled={uploading} style={{background:typeMeta.color}}>{uploading ? '⏳ Fotos werden hochgeladen…' : typeMeta.cta + ' →'}</Btn>
        <div style={{fontSize:11, color:T.muted, fontWeight:600, marginTop:10, textAlign:'center', lineHeight:1.5}}>
          Mit dem Posten stimmst du unseren <a style={{color:T.green, fontWeight:700}}>Bezirks-Regeln</a> zu.
        </div>
      </div>
    );
  }

  return (
    <div className="aIn" style={{padding:'14px 22px 28px'}}>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:14}}>
        <button onClick={onBack} style={{background:'none',border:'none',color:T.sec,fontSize:13,fontWeight:600,cursor:'pointer', padding:0, fontFamily:'inherit'}}>‹ Zurück</button>
        <div style={{fontSize:11, fontWeight:800, color:T.muted, letterSpacing:'.4px'}}>{typeMeta.emoji} {typeMeta.label.toUpperCase()}</div>
      </div>

      <ComposeBezirkBanner type={type} color={typeMeta.color}/>

      {/* ─── HILFE-ANFRAGE ─────────────────────────────────── */}
      {type==='sos' && (
        <>
          <Input label="Worum geht's?" value={data.title} onChange={v=>setData({...data,title:v})} placeholder="z.B. Babysitter heute Abend gesucht" max={80} autoFocus/>

          <div style={{marginBottom:14}}>
            <div style={{fontSize:12, fontWeight:700, color:T.sec, marginBottom:6, letterSpacing:'.2px'}}>Worum geht's?</div>
            <div style={{display:'flex', gap:6, flexWrap:'wrap'}}>
              {[
                {l:'Babysitten', i:'👶'},{l:'Einkaufen',i:'🛒'},{l:'Tragen',i:'📦'},
                {l:'Mitfahrt',i:'🚗'},{l:'Hund',i:'🐕'},{l:'Reparatur',i:'🔧'},
                {l:'Garten',i:'🌱'},{l:'Sonstiges',i:'🤲'},
              ].map(c=>(
                <button key={c.l} onClick={()=>setData({...data,sosCategory:c.l})} style={{
                  padding:'7px 10px', borderRadius:9, border:`1.5px solid ${data.sosCategory===c.l?T.care:T.bdr}`,
                  background: data.sosCategory===c.l?T.careL:'#fff', cursor:'pointer',
                  color: data.sosCategory===c.l?T.care:T.text, fontSize:12, fontWeight:700, fontFamily:'inherit',
                  display:'inline-flex', alignItems:'center', gap:5,
                }}>{c.i} {c.l}</button>
              ))}
            </div>
          </div>

          <div style={{marginBottom:14}}>
            <div style={{fontSize:12, fontWeight:700, color:T.sec, marginBottom:6}}>Wann brauchst du Hilfe?</div>
            <div style={{display:'flex', gap:6, marginBottom:10}}>
              {[{k:'heute',l:'Heute'},{k:'morgen',l:'Morgen'},{k:'flexibel',l:'Flexibel'}].map(u=>(
                <Pill key={u.k} active={data.urgency===u.k} onClick={()=>setData({...data,urgency:u.k})} color={T.care}>{u.l}</Pill>
              ))}
            </div>
            <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:8}}>
              <Input label="Von" value={data.timeFrom} onChange={v=>setData({...data,timeFrom:v})} placeholder="10:00"/>
              <Input label="Bis" value={data.timeTo} onChange={v=>setData({...data,timeTo:v})} placeholder="12:00"/>
            </div>
          </div>

          <div style={{marginBottom:14}}>
            <div style={{fontSize:12, fontWeight:700, color:T.sec, marginBottom:6}}>Bezahlung / Gegenleistung</div>
            <div style={{display:'flex', gap:6, marginBottom:8}}>
              {[{k:'free',l:'Gratis'},{k:'paid',l:'Bezahlt'},{k:'reward',l:'Gegenleistung'}].map(p=>(
                <Pill key={p.k} active={data.payment===p.k} onClick={()=>setData({...data,payment:p.k})} color={T.care}>{p.l}</Pill>
              ))}
            </div>
            {data.payment!=='free' && <Input value={data.paymentAmount} onChange={v=>setData({...data,paymentAmount:v})} placeholder={data.payment==='paid'?'z.B. 15 € pro Stunde':'z.B. Hausgemachter Kuchen'}/>}
          </div>

          <Input label="Mehr Details" value={data.description} onChange={v=>setData({...data,description:v})} placeholder="Erkläre kurz die Situation — ehrliche Beschreibungen finden schneller Hilfe." multiline rows={3} max={500}/>

          <PhotoUpload photos={data.photos} onChange={p=>setData({...data, photos:p})} max={2} accent={T.care}/>
        </>
      )}

      {/* ─── HILFE ANBIETEN ─────────────────────────────────── */}
      {type==='sos-help' && (
        <>
          <Input label="Was bietest du an?" value={data.title} onChange={v=>setData({...data,title:v})} placeholder="z.B. Ich helfe gerne beim Einkaufen" max={80} autoFocus/>
          <Input label="Mehr Details" value={data.description} onChange={v=>setData({...data,description:v})} placeholder="Was kannst du anbieten? Wann hast du Zeit?" multiline rows={4} max={500}/>
          <PhotoUpload photos={data.photos} onChange={p=>setData({...data, photos:p})} max={2} accent={T.green}/>
        </>
      )}

      {/* ─── MARKTPLATZ: ANBIETEN ───────────────────────────── */}
      {type==='angebot' && (
        <>
          <Input label="Titel" value={data.title} onChange={v=>setData({...data,title:v})} placeholder="z.B. Marillenmarmelade hausgemacht" max={80} autoFocus/>

          <div style={{marginBottom:14}}>
            <div style={{fontSize:12, fontWeight:700, color:T.sec, marginBottom:6}}>Art des Angebots</div>
            <div style={{display:'flex', gap:6}}>
              {[
                {k:'tausch',l:'Tauschen',i:'🔄'},
                {k:'verleih',l:'Verleihen',i:'🤝'},
                {k:'verschenken',l:'Verschenken',i:'🎁'},
              ].map(a=>(
                <button key={a.k} onClick={()=>setData({...data,angebotKind:a.k,priceLabel:a.l})} style={{
                  flex:1, padding:'10px 8px', borderRadius:10, border:`1.5px solid ${data.angebotKind===a.k?T.amber:T.bdr}`,
                  background: data.angebotKind===a.k?T.amberL:'#fff', cursor:'pointer',
                  color: data.angebotKind===a.k?T.amber:T.text, fontSize:12, fontWeight:700, fontFamily:'inherit',
                  display:'flex', flexDirection:'column', alignItems:'center', gap:3,
                }}>
                  <span style={{fontSize:18}}>{a.i}</span>
                  <span>{a.l}</span>
                </button>
              ))}
            </div>
          </div>

          <PhotoUpload photos={data.photos} onChange={p=>setData({...data, photos:p})} max={4} accent={T.amber}/>

          <Input label="Beschreibung" value={data.description} onChange={v=>setData({...data,description:v})} placeholder="Erkläre genauer was es ist, Zustand, Größe etc." multiline rows={4} max={500}/>
        </>
      )}

      {/* ─── MARKTPLATZ: GESUCH ─────────────────────────────── */}
      {type==='gesuch' && (
        <>
          <Input label="Was suchst du?" value={data.title} onChange={v=>setData({...data,title:v})} placeholder="z.B. Suche Kinderwagen" max={80} autoFocus/>
          <Input label="Details" value={data.description} onChange={v=>setData({...data,description:v})} multiline rows={4} max={500} placeholder="Beschreibe genauer was du suchst — Marke, Zustand, Budget …"/>
          <PhotoUpload photos={data.photos} onChange={p=>setData({...data, photos:p})} max={2} accent={T.purple}/>
        </>
      )}

      {/* ─── FRAGE (Bezirks-Diskussion) ─────────────────────── */}
      {type==='frage' && (
        <>
          <Input
            label={`Was willst du ${state.me.bezirk || 'den Bezirk'} fragen?`}
            value={data.title}
            onChange={v=>setData({...data,title:v})}
            placeholder="z.B. Welcher Kinderarzt nimmt noch Patient:innen?"
            max={120}
            autoFocus
          />
          <Input
            label="Mehr Kontext (optional)"
            value={data.description}
            onChange={v=>setData({...data,description:v})}
            multiline
            rows={5}
            max={500}
            placeholder="Je mehr Kontext, desto bessere Antworten. Erzähl was du schon weißt oder warum du fragst."
          />
          <PhotoUpload photos={data.photos} onChange={p=>setData({...data, photos:p})} max={2} accent={T.green}/>
        </>
      )}

      {/* ─── DEAL (Gewerbe) ─────────────────────────────────── */}
      {type==='deal' && (
        <>
          <Input label="Titel des Deals" value={data.title} onChange={v=>setData({...data,title:v})} placeholder="z.B. 30% auf alle Pizzen" max={80} autoFocus/>
          <div style={{display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:8, marginBottom:14}}>
            <Input label="Normal" value={data.originalPrice} onChange={v=>setData({...data,originalPrice:v})} placeholder="14.00" prefix="€"/>
            <Input label="Aktion" value={data.deal_price} onChange={v=>setData({...data,deal_price:v})} placeholder="9.80" prefix="€"/>
            <Input label="Rabatt" value={data.savings} onChange={v=>setData({...data,savings:v})} placeholder="30" suffix="%"/>
          </div>
          <PhotoUpload photos={data.photos} onChange={p=>setData({...data, photos:p})} max={4} accent={T.gold}/>
          <Input label="Beschreibung" value={data.description} onChange={v=>setData({...data,description:v})} multiline rows={4} max={500} placeholder="Beschreibe deinen Deal — Bedingungen, Gültigkeit, …"/>
        </>
      )}

      {/* ─── CTA: Preview → Submit ─────────────────────────── */}
      <div style={{marginTop:18, display:'flex', flexDirection:'column', gap:8}}>
        <Btn
          full
          kind="primary"
          size="lg"
          disabled={!titleValid}
          onClick={()=>setPreview(true)}
          style={{background: titleValid?typeMeta.color:T.bdrSoft, color: titleValid?'#fff':T.muted, borderColor:'transparent'}}
        >
          {titleValid ? 'Vorschau ansehen →' : 'Titel ausfüllen, um fortzufahren'}
        </Btn>
        <div style={{fontSize:11, color:T.muted, fontWeight:600, textAlign:'center', lineHeight:1.5}}>
          📌 Bitte halte dich an die <a style={{color:T.green, fontWeight:700}}>Bezirks-Regeln</a> · keine Werbung · sei respektvoll
        </div>
      </div>
    </div>
  );
}

// ───────────────────────────────────────────────────────────────
// CHAT
// ───────────────────────────────────────────────────────────────
function InboxScreen({onOpenChat}){
  const state = window._appState;
  const chats = Object.values(state.chats).sort((a,b)=>{
    const la = a.messages[a.messages.length-1]?.t || a.createdAt;
    const lb = b.messages[b.messages.length-1]?.t || b.createdAt;
    return lb-la;
  });
  return (
    <div className="aIn" style={{flex:1, overflowY:'auto', background:T.bg}}>
      <div style={{padding:'18px 22px 14px'}}>
        <div style={{fontFamily:'Fraunces, serif', fontSize:28, fontWeight:700, letterSpacing:'-.6px'}}>Chats</div>
        <div style={{fontSize:12, color:T.sec, fontWeight:600, marginTop:2}}>{chats.length} Unterhaltungen</div>
      </div>
      {chats.length===0 ? (
        <Empty icon="💬" title="Noch keine Chats" sub="Sobald du mit jemandem schreibst, taucht der Chat hier auf."/>
      ) : (
        <div style={{padding:'0 14px'}}>
          {chats.map(c=>{
            const last = c.messages[c.messages.length-1];
            return (
              <div key={c.id} onClick={()=>onOpenChat(c.id)} className="cp" style={{padding:'12px 12px', display:'flex', gap:12, alignItems:'center', cursor:'pointer', borderRadius:13, marginBottom:4, background: c.unread?T.greenL:'transparent'}}>
                <Avatar a={c.peer.a} size={46} name={c.peer.name}/>
                <div style={{flex:1, minWidth:0}}>
                  <div style={{display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom:2}}>
                    <div style={{fontSize:14, fontWeight:700, display:'flex', gap:5, alignItems:'center'}}>{c.peer.name}{c.peer.verified && <span style={{color:T.care, fontSize:11}}>✓</span>}</div>
                    {last && <div style={{fontSize:11, color:T.muted, fontWeight:600}}>{timeAgo(last.t)}</div>}
                  </div>
                  <div style={{fontSize:12, color:T.sec, fontWeight:500, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap'}}>{last?.text || `Zu: ${c.postTitle}`}</div>
                </div>
                {c.unread>0 && <div style={{width:20, height:20, borderRadius:'50%', background:T.green, color:'#fff', fontSize:11, fontWeight:800, display:'flex', alignItems:'center', justifyContent:'center'}}>{c.unread}</div>}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

function ChatScreen({chatId, onBack, onOpenRating}){
  const state = window._appState;
  const A = window.AppStore.actions;
  const chat = state.chats[chatId];
  const [text,setText] = useState('');
  const scrollRef = useRef(null);

  useEffect(()=>{ A.markChatRead(chatId); },[chatId]);
  useEffect(()=>{ if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight; },[chat?.messages.length]);

  // ─── Cloud: Nachrichten für diesen Chat laden + live abonnieren ───
  useEffect(()=>{
    const isCloudChat = typeof chatId === 'string' && chatId.length > 30 && chatId.includes('-');
    if (!isCloudChat || !window.BL?.client || !window.BL.user) return;
    let cleanup = null;

    // 1. Vorhandene Nachrichten laden (falls Chat erst jetzt geöffnet wird)
    window.BL.fetchMessages(chatId).then(({ data }) => {
      if (!data) return;
      const mapped = data.map(m => ({
        id: m.id,
        from: m.sender_id === window.BL.user.id ? 'me' : 'them',
        text: m.text, t: new Date(m.created_at).getTime(), kind: m.kind || 'text',
      }));
      window.AppStore.setState(s => {
        const c = s.chats[chatId]; if (!c) return s;
        return { ...s, chats: { ...s.chats, [chatId]: { ...c, messages: mapped } } };
      });
    }).catch(()=>{});

    // 2. Live abonnieren (neue Nachrichten dieses Chats)
    cleanup = window.BL.subscribeChat(chatId, (m) => {
      if (m.sender_id === window.BL.user.id) return; // eigene Echos überspringen
      window.AppStore.setState(s => {
        const c = s.chats[chatId]; if (!c) return s;
        if (c.messages.find(x => x.id === m.id)) return s; // dedupe
        return { ...s, chats: { ...s.chats, [chatId]: { ...c, messages: [...c.messages, {
          id: m.id, from: 'them', text: m.text, t: new Date(m.created_at).getTime(), kind: m.kind || 'text',
        }] } } };
      });
    });
    return () => { if (cleanup) cleanup(); };
  }, [chatId]);

  if (!chat) return null;
  const post = state.posts.find(p=>p.id===chat.postId);
  const canRate = post && (post.status==='erledigt' || post.status==='hilfe-gefunden' || post.status==='abgeholt');
  const alreadyRated = state.ratings.some(r=>r.postId===chat.postId);

  const send = ()=>{
    if (!text.trim()) return;
    // Phishing detection
    const sus = /(\d{4,}[ .-]?\d{4,})|(IBAN|AT\d{2}\s?\d)/i.test(text);
    A.sendMessage(chatId, text, sus?'flagged':'text');
    setText('');
  };

  return (
    <div style={{flex:1, display:'flex', flexDirection:'column', background:T.bg}}>
      {/* Header */}
      <div style={{padding:'12px 14px', display:'flex', alignItems:'center', gap:11, background:'#fff', borderBottom:`1px solid ${T.bdr}`}}>
        <button onClick={onBack} style={{width:34, height:34, borderRadius:10, background:'#fff', border:`1px solid ${T.bdr}`, fontSize:16, cursor:'pointer'}}>‹</button>
        <Avatar a={chat.peer.a} size={36} name={chat.peer.name}/>
        <div style={{flex:1, minWidth:0}}>
          <div style={{display:'flex', gap:5, alignItems:'center'}}><div style={{fontSize:14, fontWeight:700}}>{chat.peer.name}</div>{chat.peer.verified && <span style={{color:T.care, fontSize:11}}>✓</span>}</div>
          <div style={{fontSize:11, color:T.sec, fontWeight:500, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap'}}>Zu: {chat.postTitle}</div>
        </div>
      </div>

      {/* Messages */}
      <div ref={scrollRef} style={{flex:1, overflowY:'auto', padding:'14px 14px', display:'flex', flexDirection:'column', gap:8}}>
        {/* Safety banner */}
        {chat.messages.length<2 && (
          <div style={{padding:'10px 12px', background:T.goldL, borderRadius:11, fontSize:11, color:T.gold, fontWeight:600, lineHeight:1.45, marginBottom:8}}>
            🛡 Erste Konversation: Triff dich an einem öffentlichen Ort. Kein Geld vorab überweisen. Bei Verdacht melden.
          </div>
        )}
        {chat.messages.map(m=>(
          <div key={m.id} style={{display:'flex', justifyContent: m.from==='me'?'flex-end':'flex-start'}}>
            <div style={{
              maxWidth:'78%', padding:'9px 13px', borderRadius:14,
              background: m.from==='me'?T.text:'#fff', color: m.from==='me'?'#fff':T.text,
              border: m.from==='me'?'none':`1px solid ${T.bdr}`,
              fontSize:13.5, lineHeight:1.4, fontWeight:500,
              borderBottomRightRadius: m.from==='me'?4:14,
              borderBottomLeftRadius: m.from==='me'?14:4,
            }}>
              {m.kind==='flagged' && <div style={{fontSize:10, fontWeight:800, color:T.red, marginBottom:3}}>⚠ Möglicher Phishing-Versuch erkannt</div>}
              {m.text}
            </div>
          </div>
        ))}

        {canRate && !alreadyRated && (
          <div style={{padding:'12px 14px', background:T.greenL, borderRadius:13, margin:'10px 0'}}>
            <div style={{fontSize:11, fontWeight:800, color:T.green, letterSpacing:'.3px', marginBottom:6}}>⭐ TRANSAKTION ABGESCHLOSSEN</div>
            <div style={{fontSize:13, color:T.text, fontWeight:500, marginBottom:10}}>Bewerte {chat.peer.name} damit andere Vertrauen aufbauen können.</div>
            <Btn kind="success" size="sm" onClick={()=>onOpenRating(chat)}>Jetzt bewerten</Btn>
          </div>
        )}
      </div>

      {/* Input */}
      <div style={{padding:'10px 12px', background:'#fff', borderTop:`1px solid ${T.bdr}`, display:'flex', gap:8}}>
        <input value={text} onChange={e=>setText(e.target.value)} onKeyDown={e=>e.key==='Enter'&&send()} placeholder="Nachricht..." style={{flex:1, padding:'11px 14px', borderRadius:18, border:`1px solid ${T.bdr}`, background:T.bg, fontSize:13.5, color:T.text, outline:'none'}}/>
        <button onClick={send} style={{width:42, height:42, borderRadius:'50%', background:T.text, color:'#fff', border:'none', fontSize:16, cursor:'pointer'}}>↑</button>
      </div>
    </div>
  );
}

function RatingModal({chat, onClose}){
  const A = window.AppStore.actions;
  const [stars,setStars] = useState(0);
  const [tags,setTags] = useState([]);
  const [text,setText] = useState('');
  if (!chat) return null;
  const TAGS = ['Pünktlich','Freundlich','Zuverlässig','Genau wie beschrieben','Hilfsbereit','Empfehlenswert'];
  const submit = ()=>{
    A.addRating({toId: chat.peer.id, postId: chat.postId, stars, tags, comment:text, context: 'Soforthilfe'});
    onClose();
  };
  return (
    <Modal open={!!chat} onClose={onClose} title={`${chat.peer.name} bewerten`}>
      <div style={{display:'flex', justifyContent:'center', gap:6, margin:'12px 0 18px'}}>
        {[1,2,3,4,5].map(n=>(
          <button key={n} onClick={()=>setStars(n)} style={{background:'none',border:'none',fontSize:34,cursor:'pointer',color: n<=stars?T.gold:T.bdr,padding:0,lineHeight:1}}>{n<=stars?'★':'☆'}</button>
        ))}
      </div>
      <div style={{fontSize:12, fontWeight:700, color:T.sec, marginBottom:8}}>Was hat gepasst?</div>
      <div style={{display:'flex', flexWrap:'wrap', gap:6, marginBottom:14}}>
        {TAGS.map(t=>(
          <Pill key={t} active={tags.includes(t)} onClick={()=>setTags(tags.includes(t)?tags.filter(x=>x!==t):[...tags,t])} color={T.green}>{t}</Pill>
        ))}
      </div>
      <Input label="Kommentar (optional)" value={text} onChange={setText} multiline rows={3} max={300}/>
      <div style={{display:'flex', gap:8}}>
        <Btn kind="secondary" onClick={onClose}>Abbrechen</Btn>
        <Btn kind="success" full disabled={stars===0} onClick={submit}>Bewertung abgeben</Btn>
      </div>
    </Modal>
  );
}

// ───────────────────────────────────────────────────────────────
// PROFILE
// ───────────────────────────────────────────────────────────────
function ProfileScreen({onUpgrade, onSettings, onSelect, onBusiness}){
  const state = window._appState;
  const myPosts = state.posts.filter(p=>p.ownerId==='me');
  const [tab,setTab] = useState('overview');
  const [uploadingAvatar, setUploadingAvatar] = useState(false);
  const [ambassador, setAmbassador] = useState(null);  // {rank, total} oder null
  const avatarInputRef = useRef(null);
  const A = window.AppStore.actions;

  // ─── Botschafter:in-Status checken ──────────────────────
  useEffect(() => {
    if (!window.BL?.user || !window.BL.client || !state.me.bezirk) return;
    (async () => {
      try {
        // Wie viele User insgesamt in meinem Bezirk?
        const { count } = await window.BL.client.from('profiles')
          .select('id', { count: 'exact', head: true })
          .eq('bezirk', state.me.bezirk);
        // Welchen Rang habe ich (sortiert nach created_at)?
        const { data: earlier } = await window.BL.client.from('profiles')
          .select('id, created_at')
          .eq('bezirk', state.me.bezirk)
          .order('created_at', { ascending: true })
          .limit(50);
        const myIndex = (earlier || []).findIndex(p => p.id === window.BL.user.id);
        const rank = myIndex >= 0 ? myIndex + 1 : null;
        setAmbassador({ rank, total: count || 0, isAmbassador: rank !== null && rank <= 5 });
      } catch(e) {
        console.warn('[ambassador] check failed', e);
      }
    })();
  }, [state.me.bezirk]);

  // ─── Avatar Upload (Profile-Foto) ───────────────────────
  async function handleAvatarFile(file){
    if (!file || !file.type.startsWith('image/')) { alert('Bitte ein Bild auswählen.'); return; }
    if (file.size > 5 * 1024 * 1024) { alert('Bitte ein Bild unter 5 MB wählen.'); return; }
    setUploadingAvatar(true);
    try {
      // Read as data URL first (instant feedback)
      const reader = new FileReader();
      const dataUrl = await new Promise((res, rej) => {
        reader.onload = e => res(e.target.result);
        reader.onerror = rej;
        reader.readAsDataURL(file);
      });
      // Optimistic update
      A.updateMe({ avatarUrl: dataUrl });
      // Real upload to Supabase Storage
      if (window.BL?.user && window.BL.uploadDataURL){
        try {
          const publicUrl = await window.BL.uploadDataURL('avatars', dataUrl);
          A.updateMe({ avatarUrl: publicUrl });
          // Auch in profiles.avatar_url speichern
          if (window.BL.client){
            await window.BL.client.from('profiles').update({ avatar_url: publicUrl }).eq('id', window.BL.user.id);
          }
        } catch(e){
          console.warn('[avatar] upload failed, bleibt lokal als base64', e);
        }
      }
    } catch(e){
      alert('Fehler beim Laden des Bildes: ' + e.message);
    } finally {
      setUploadingAvatar(false);
    }
  }

  return (
    <div className="aIn" style={{flex:1, overflowY:'auto', background:T.bg, paddingBottom:80}}>
      {/* Header */}
      <div style={{padding:'18px 22px 14px', display:'flex', alignItems:'center', gap:14}}>
        <div style={{position:'relative', cursor:'pointer'}} onClick={()=>!uploadingAvatar && avatarInputRef.current?.click()}>
          <Avatar a={state.me.avatar} size={62} name={state.me.name} src={state.me.avatarUrl}/>
          <div style={{
            position:'absolute', bottom:-2, right:-2, width:24, height:24, borderRadius:'50%',
            background: uploadingAvatar ? T.muted : T.green, color:'#fff',
            display:'flex', alignItems:'center', justifyContent:'center',
            border:'2px solid #fff', fontSize:11, fontWeight:800,
            boxShadow:'0 2px 6px rgba(0,0,0,.15)',
          }}>{uploadingAvatar ? '⏳' : '📷'}</div>
          <input
            ref={avatarInputRef}
            type="file"
            accept="image/*"
            style={{display:'none'}}
            onChange={e => { handleAvatarFile(e.target.files[0]); e.target.value=''; }}
          />
        </div>
        <div style={{flex:1, minWidth:0}}>
          <div style={{display:'flex', gap:6, alignItems:'center', flexWrap:'wrap'}}>
            <div style={{fontFamily:'Fraunces, serif', fontSize:22, fontWeight:700, letterSpacing:'-.4px'}}>{state.me.name||'Du'}</div>
            {state.me.verified && <span style={{color:T.care, fontSize:13}}>✓</span>}
            <TierBadge tier={state.me.tier}/>
          </div>
          <div style={{fontSize:12, color:T.sec, fontWeight:500}}>{state.me.bezirk} · @{state.me.handle||'du'}</div>
          {!state.me.avatarUrl && (
            <button onClick={()=>avatarInputRef.current?.click()} style={{
              marginTop:6, background:'none', border:'none', padding:0, cursor:'pointer',
              fontSize:11.5, color:T.green, fontWeight:700, fontFamily:'inherit',
            }}>📷 Profilfoto hinzufügen</button>
          )}
        </div>
        <button onClick={onSettings} style={{width:34, height:34, borderRadius:10, background:'#fff', border:`1px solid ${T.bdr}`, fontSize:14, cursor:'pointer'}}>⚙</button>
      </div>

      {/* Stats */}
      <div style={{padding:'0 18px', display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:8, marginBottom:14}}>
        <Stat l="Posts" v={state.me.stats.posts}/>
        <Stat l="Geholfen" v={state.me.stats.helps}/>
        <Stat l="Bewertungen" v={`${state.me.stats.score?'4.8':'—'}`} sub={`${state.me.stats.ratings} ⭐`}/>
      </div>

      {/* Botschafter:in Banner — Pionier-Belohnung */}
      {ambassador?.isAmbassador && (
        <div style={{margin:'4px 18px 14px', padding:'16px 18px', borderRadius:16,
          background:`linear-gradient(135deg, ${T.green} 0%, #166435 70%, #0F5C2B 100%)`,
          color:'#fff', position:'relative', overflow:'hidden'}}>
          <div style={{position:'absolute', top:-25, right:-25, width:120, height:120, borderRadius:'50%', background:'rgba(255,255,255,.07)'}}></div>
          <div style={{position:'relative', zIndex:1}}>
            <div style={{display:'flex', alignItems:'center', gap:9, marginBottom:8}}>
              <div style={{width:38, height:38, borderRadius:11, background:'rgba(255,255,255,.18)', display:'flex', alignItems:'center', justifyContent:'center', fontSize:20}}>🏅</div>
              <div>
                <div style={{fontSize:10.5, fontWeight:800, letterSpacing:'.5px', color:'rgba(255,255,255,.85)'}}>BEZIRKS-BOTSCHAFTER:IN</div>
                <div style={{fontFamily:'Fraunces, serif', fontSize:18, fontWeight:700, letterSpacing:'-.3px', lineHeight:1.1}}>
                  {ambassador.rank === 1 ? 'Erste:r in' : `#${ambassador.rank} in`} {state.me.bezirk}
                </div>
              </div>
            </div>
            <div style={{fontSize:12.5, color:'rgba(255,255,255,.85)', fontWeight:500, lineHeight:1.45}}>
              Du gehörst zu den ersten 5 Pionier:innen deines Ortes — danke, dass du {state.me.bezirk} mitgestaltest! <strong style={{color:'#fff'}}>6 Monate Premium gratis</strong> als Dankeschön. 🌱
            </div>
          </div>
        </div>
      )}

      {/* Premium upsell */}
      {state.me.tier==='buerger' && (
        <div style={{margin:'4px 18px 14px', padding:'14px 16px', background:`linear-gradient(135deg, ${T.ink}, ${T.inkSoft})`, borderRadius:14, color:'#fff', display:'flex', justifyContent:'space-between', alignItems:'center', cursor:'pointer'}} onClick={onUpgrade}>
          <div>
            <div style={{fontSize:11, fontWeight:800, color:T.gold, letterSpacing:'.4px', marginBottom:2}}>✦ PREMIUM</div>
            <div style={{fontSize:14, fontWeight:700}}>Deals posten · Featured Slot</div>
            <div style={{fontSize:11, color:'#A8A59E', fontWeight:500, marginTop:2}}>Ab 15 € / Monat — für Gewerbe</div>
          </div>
          <div style={{fontSize:18}}>›</div>
        </div>
      )}

      {/* Geschäftsprofil-Link */}
      <div onClick={onBusiness} className="cp" style={{margin:'4px 18px 14px', padding:'14px 16px', background:'#fff', border:`1px solid ${T.bdr}`, borderRadius:14, display:'flex', alignItems:'center', gap:12, cursor:'pointer'}}>
        <div style={{width:42, height:42, borderRadius:11, background:T.goldL, display:'flex', alignItems:'center', justifyContent:'center', fontSize:20, flexShrink:0}}>🏪</div>
        <div style={{flex:1, minWidth:0}}>
          <div style={{fontSize:14, fontWeight:700, color:T.text}}>Geschäftsprofil</div>
          <div style={{fontSize:11.5, color:T.sec, fontWeight:500, marginTop:1}}>{['basic','pro','premium'].includes(state.me.tier) ? 'Deine Geschäftsseite bearbeiten' : 'Eigene Seite für dein Gewerbe einrichten'}</div>
        </div>
        <div style={{fontSize:18, color:T.muted}}>›</div>
      </div>

      {/* Tabs */}
      <div style={{padding:'4px 18px 12px', display:'flex', gap:6}}>
        {[{k:'overview',l:'Posts'},{k:'bookmarks',l:'Gemerkt'},{k:'ratings',l:'Bewertungen'}].map(t=>(
          <button key={t.k} onClick={()=>setTab(t.k)} style={{padding:'8px 13px', borderRadius:10, border:'none', background: tab===t.k?T.text:T.bdrSoft, color:tab===t.k?'#fff':T.text, fontSize:12.5, fontWeight:700, cursor:'pointer'}}>{t.l}</button>
        ))}
      </div>

      <div style={{padding:'0 18px'}}>
        {tab==='overview' && (myPosts.length===0
          ? <Empty icon="📝" title="Noch keine Posts" sub="Erstelle deinen ersten Post über den +-Button."/>
          : <div style={{display:'flex',flexDirection:'column',gap:9}}>{myPosts.map(p=><PostCard key={p.id} item={p} onTap={()=>onSelect(p)}/>)}</div>
        )}
        {tab==='bookmarks' && (state.me.bookmarks.length===0
          ? <Empty icon="★" title="Keine Lesezeichen" sub="Tippe das ☆-Symbol auf Posts, die du dir merken willst."/>
          : <div style={{display:'flex',flexDirection:'column',gap:9}}>{state.posts.filter(p=>state.me.bookmarks.includes(p.id)).map(p=><PostCard key={p.id} item={p} onTap={()=>onSelect(p)}/>)}</div>
        )}
        {tab==='ratings' && (state.ratings.length===0
          ? <Empty icon="⭐" title="Noch keine Bewertungen" sub="Bewertungen erscheinen hier nach abgeschlossenen Transaktionen."/>
          : <div style={{display:'flex',flexDirection:'column',gap:8}}>{state.ratings.map(r=>(
              <div key={r.id} style={{padding:'12px 13px',background:'#fff',border:`1px solid ${T.bdr}`,borderRadius:12}}>
                <div style={{display:'flex',justifyContent:'space-between',marginBottom:5}}>
                  <div style={{fontSize:13,fontWeight:700}}>{r.context||'Transaktion'}</div>
                  <div style={{color:T.gold,fontSize:13}}>{'★'.repeat(r.stars)}{'☆'.repeat(5-r.stars)}</div>
                </div>
                {r.comment && <div style={{fontSize:12.5,color:T.sec,fontWeight:500,lineHeight:1.5}}>{r.comment}</div>}
              </div>
            ))}</div>
        )}
      </div>
    </div>
  );
}

function Stat({l,v,sub}){
  return (
    <div style={{padding:'12px 12px', background:'#fff', border:`1px solid ${T.bdr}`, borderRadius:12, textAlign:'center'}}>
      <div style={{fontFamily:'Fraunces, serif', fontSize:22, fontWeight:700, letterSpacing:'-.5px'}}>{v}</div>
      <div style={{fontSize:10.5, color:T.muted, fontWeight:700, letterSpacing:'.3px', textTransform:'uppercase', marginTop:2}}>{l}</div>
      {sub && <div style={{fontSize:10, color:T.sec, fontWeight:600, marginTop:1}}>{sub}</div>}
    </div>
  );
}

function SettingsScreen({onBack}){
  const state = window._appState;
  const A = window.AppStore.actions;
  const [bezirkOpen, setBezirkOpen] = useState(false);
  return (
    <div className="aIn" style={{flex:1,overflowY:'auto',background:T.bg}}>
      <div style={{padding:'12px 14px', display:'flex',alignItems:'center',gap:11}}>
        <button onClick={onBack} style={{width:34, height:34, borderRadius:10, background:'#fff', border:`1px solid ${T.bdr}`, fontSize:16, cursor:'pointer'}}>‹</button>
        <div style={{fontFamily:'Fraunces, serif', fontSize:22, fontWeight:700, letterSpacing:'-.4px'}}>Einstellungen</div>
      </div>
      <div style={{padding:'10px 18px 80px'}}>
        <PushToggle/>
        <SettingRow l="Dark Mode" toggle={false} onToggle={()=>alert('Bald verfügbar')}/>
        <SettingRow l="Bezirk ändern" sub={state.me.bezirk} onClick={()=>setBezirkOpen(true)}/>
        <SettingRow l="Daten exportieren" sub="DSGVO-konform" onClick={()=>{
          const blob = new Blob([JSON.stringify(state,null,2)], {type:'application/json'});
          const url = URL.createObjectURL(blob);
          const a = document.createElement('a'); a.href=url; a.download='bezirklive-export.json'; a.click();
        }}/>

        {/* Rechtliches */}
        <div style={{fontSize:11, fontWeight:800, color:T.muted, letterSpacing:'.5px', margin:'20px 0 8px', textTransform:'uppercase'}}>Rechtliches</div>
        <SettingRow l="Impressum" onClick={()=>window.open('/impressum.html','_blank')}/>
        <SettingRow l="Datenschutzerklärung" onClick={()=>window.open('/datenschutz.html','_blank')}/>
        <SettingRow l="AGB / Nutzungsbedingungen" onClick={()=>window.open('/agb.html','_blank')}/>
        <SettingRow l="Kontakt" sub="info@bezirklive.at" onClick={()=>window.open('mailto:info@bezirklive.at','_blank')}/>

        {/* Admin (nur für Admins sichtbar) */}
        <AdminLink/>

        {/* Account */}
        <div style={{fontSize:11, fontWeight:800, color:T.muted, letterSpacing:'.5px', margin:'20px 0 8px', textTransform:'uppercase'}}>Account</div>
        <SettingRow l="App zurücksetzen" sub="Löscht alle lokalen Daten" danger onClick={()=>{ if(confirm('Wirklich alle lokalen Daten löschen? Dein Cloud-Account bleibt erhalten.')){ A.reset(); location.reload(); }}}/>
        {window.Cloud?.user && (
          <SettingRow l="Abmelden" sub={window.Cloud.user.email} danger onClick={()=>{ if(confirm('Wirklich abmelden?')){ window.Cloud.signOut(); }}}/>
        )}
        {window.BL?.user && (
          <SettingRow
            l="🗑 Konto endgültig löschen"
            sub="DSGVO Art. 17 — Recht auf Vergessen"
            danger
            onClick={async ()=>{
              const c = prompt('⚠️ ACHTUNG: Diese Aktion ist UNWIDERRUFLICH!\n\nAlle deine Posts, Kommentare, Chats und dein Profil werden permanent gelöscht.\n\nTippe LÖSCHEN (in Großbuchstaben) zum Bestätigen:');
              if (c !== 'LÖSCHEN' && c !== 'LOESCHEN') { if (c !== null) alert('Abgebrochen — Konto nicht gelöscht.'); return; }
              try {
                // 1. RPC um Profil + cascading FK-deletes
                if (window.BL.client){
                  await window.BL.client.rpc('delete_my_account');
                }
                // 2. Lokale Daten wegen Datensparsamkeit
                A.reset();
                // 3. Sign out
                await window.BL.signOut();
                alert('✓ Dein Konto wurde gelöscht. Falls du noch eine E-Mail von uns siehst, dauert die endgültige Löschung der Auth-Daten bis zu 24h.');
                location.href = '/';
              } catch(e){
                alert('Fehler beim Löschen: ' + (e.message || 'Unbekannt') + '\n\nBitte kontaktiere uns unter info@bezirklive.at — wir löschen dein Konto manuell.');
              }
            }}
          />
        )}
        <div style={{fontSize:11, color:T.muted, fontWeight:600, textAlign:'center', marginTop:24, lineHeight:1.6}}>bezirklive.at · v1.1.0<br/>AbdeX e.U. · Bruck an der Leitha 🇦🇹</div>
      </div>
      <BezirkChangeSheet open={bezirkOpen} onClose={()=>setBezirkOpen(false)}/>
    </div>
  );
}

// ─── Bezirk wechseln: echte Orts-Suche (OSM) statt Freitext ───
function BezirkChangeSheet({open, onClose}){
  const state = window._appState;
  const A = window.AppStore.actions;
  const [q, setQ] = useState('');
  const [results, setResults] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (!open || q.trim().length < 2) { setResults([]); return; }
    let cancelled = false;
    const t = setTimeout(async () => {
      setLoading(true);
      try {
        const r = await fetch(`https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(q)}&countrycodes=at&format=json&limit=8&addressdetails=1&accept-language=de`);
        const arr = r.ok ? await r.json() : [];
        if (cancelled) return;
        const seen = new Set();
        const mapped = arr.map(d => {
          const a = d.address || {};
          const name = a.suburb || a.city_district || a.town || a.village || a.municipality || a.county || d.display_name.split(',')[0];
          const plz = a.postcode || '';
          const type = (a.suburb||a.city_district) ? 'bezirk' : (a.city||a.town) ? 'stadt' : a.village ? 'dorf' : 'bezirk';
          const key = (name+'|'+plz).toLowerCase();
          if (seen.has(key)) return null; seen.add(key);
          return { name, plz, state: a.state||'', type };
        }).filter(Boolean);
        setResults(mapped);
      } catch(e){ setResults([]); }
      finally { if (!cancelled) setLoading(false); }
    }, 350);
    return () => { cancelled = true; clearTimeout(t); };
  }, [q, open]);

  function pick(r){
    A.updateMe({ bezirk: r.name, plz: r.plz || state.me.plz, locationType: r.type });
    onClose();
  }

  return (
    <Sheet open={open} onClose={onClose} title="Bezirk wechseln">
      <div style={{padding:'4px 22px 32px'}}>
        <div style={{fontSize:13, color:T.sec, fontWeight:500, lineHeight:1.5, marginBottom:14}}>
          Wähle deinen Ort aus der Liste, damit du mit den richtigen Nachbar:innen verbunden bist.
        </div>
        <Input value={q} onChange={setQ} placeholder="z.B. Bruck an der Leitha, Göttlesbrunn…" autoFocus/>
        {loading && <div style={{fontSize:12, color:T.muted, fontWeight:600, padding:'8px 2px'}}>Suche…</div>}
        <div style={{maxHeight:280, overflowY:'auto', marginTop:6}}>
          {results.map((r,i)=>(
            <div key={i} onClick={()=>pick(r)} className="cp" style={{padding:'12px 14px', borderRadius:11, border:`1px solid ${T.bdr}`, marginBottom:7, cursor:'pointer', background: state.me.bezirk===r.name?T.greenL:'#fff', display:'flex', justifyContent:'space-between', alignItems:'center', gap:10}}>
              <div style={{minWidth:0}}>
                <div style={{fontSize:14, fontWeight:700, color:T.text}}>{r.name}</div>
                <div style={{fontSize:11, color:T.muted, fontWeight:500, marginTop:1}}>{r.plz && <strong style={{color:T.sec}}>{r.plz}</strong>}{r.plz && r.state && ' · '}{r.state}</div>
              </div>
              {state.me.bezirk===r.name && <span style={{color:T.green, fontWeight:800}}>✓</span>}
            </div>
          ))}
          {!loading && q.trim().length>=2 && results.length===0 && (
            <div style={{fontSize:12.5, color:T.muted, fontWeight:600, padding:'12px 2px', textAlign:'center'}}>Nichts gefunden — andere Schreibweise probieren.</div>
          )}
        </div>
      </div>
    </Sheet>
  );
}

function SettingRow({l, sub, toggle, onToggle, onClick, danger}){
  return (
    <div onClick={onClick} style={{padding:'14px 14px', background:'#fff', borderRadius:12, border:`1px solid ${T.bdr}`, marginBottom:7, display:'flex', alignItems:'center', justifyContent:'space-between', cursor: onClick?'pointer':'default'}}>
      <div>
        <div style={{fontSize:14, fontWeight:700, color: danger?T.red:T.text}}>{l}</div>
        {sub && <div style={{fontSize:11, color:T.sec, fontWeight:500, marginTop:1}}>{sub}</div>}
      </div>
      {toggle!==undefined && (
        <div onClick={e=>{e.stopPropagation(); onToggle(!toggle);}} style={{width:42, height:24, borderRadius:14, background:toggle?T.green:T.bdr, position:'relative', cursor:'pointer', transition:'background .2s'}}>
          <div style={{width:20, height:20, borderRadius:'50%', background:'#fff', position:'absolute', top:2, left:toggle?20:2, transition:'left .2s', boxShadow:'0 1px 3px rgba(0,0,0,.15)'}}/>
        </div>
      )}
      {onClick && toggle===undefined && <div style={{color:T.muted, fontSize:18}}>›</div>}
    </div>
  );
}

// ─── PushToggle: echte Push-Benachrichtigungen ──────────────
function PushToggle(){
  const [status, setStatus] = useState('default');
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    if (window.Push?.getStatus) window.Push.getStatus().then(setStatus);
  }, []);

  const on = status === 'subscribed';

  async function toggle(){
    if (busy) return;
    setBusy(true);
    try {
      if (on){
        await window.Push.unsubscribe();
        setStatus('default');
        window.AppStore.actions.updateMe({ pushEnabled: false });
      } else {
        await window.Push.subscribe();
        setStatus('subscribed');
        window.AppStore.actions.updateMe({ pushEnabled: true });
      }
    } catch(e){
      alert(e.message || 'Konnte Benachrichtigungen nicht aktivieren.');
      if (window.Push?.getStatus) window.Push.getStatus().then(setStatus);
    } finally { setBusy(false); }
  }

  if (status === 'unsupported'){
    return <SettingRow l="Push-Benachrichtigungen" sub="Von diesem Browser nicht unterstützt"/>;
  }
  if (status === 'denied'){
    return <SettingRow l="Push-Benachrichtigungen" sub="In den Browser-Einstellungen blockiert"/>;
  }
  return (
    <SettingRow
      l="Push-Benachrichtigungen"
      sub={busy ? 'Moment…' : on ? 'Aktiv — du wirst benachrichtigt' : 'Tippe zum Aktivieren'}
      toggle={on}
      onToggle={toggle}
    />
  );
}

// ─── AdminLink: zeigt sich nur wenn User Admin ist ──────────
function AdminLink(){
  const [isAdmin, setIsAdmin] = useState(false);
  useEffect(() => {
    (async () => {
      if (!window.BL?.user || !window.BL.client) return;
      try {
        const { data } = await window.BL.client.from('profiles').select('is_admin').eq('id', window.BL.user.id).single();
        if (data?.is_admin) setIsAdmin(true);
      } catch(e) {}
    })();
  }, []);
  if (!isAdmin) return null;
  return (
    <>
      <div style={{fontSize:11, fontWeight:800, color:T.muted, letterSpacing:'.5px', margin:'20px 0 8px', textTransform:'uppercase'}}>Moderation</div>
      <SettingRow l="🛡 Admin-Panel" sub="Meldungen prüfen, Inhalte moderieren" onClick={()=>window.open('/admin-live.html','_blank')}/>
    </>
  );
}

// ───────────────────────────────────────────────────────────────
// NOTIFICATIONS / HELP
// ───────────────────────────────────────────────────────────────
function HelpScreen({onSelect, onCompose}){
  const state = window._appState;
  const A = window.AppStore.actions;
  const sosPosts = state.posts.filter(p=>p.type==='sos' && p.status==='aktiv');
  return (
    <div className="aIn" style={{flex:1, overflowY:'auto', background:T.bg, paddingBottom:80}}>
      <div style={{padding:'18px 22px 12px'}}>
        <div style={{fontFamily:'Fraunces, serif', fontSize:28, fontWeight:700, letterSpacing:'-.6px', color:T.care}}>Soforthilfe</div>
        <div style={{fontSize:13, color:T.sec, fontWeight:500, marginTop:3}}>{sosPosts.length} aktive Anfragen in {state.me.bezirk.replace('Graz-','')}</div>
      </div>
      <div style={{padding:'4px 18px 14px'}}>
        <Btn full kind="care" size="lg" onClick={onCompose}>+ Hilfe anfragen</Btn>
      </div>
      <div style={{padding:'0 18px'}}>
        {sosPosts.length===0 ? <Empty icon="🤝" title="Aktuell keine Anfragen" sub="Wenn jemand Hilfe braucht, taucht es hier auf."/> :
          <div style={{display:'flex',flexDirection:'column',gap:9}}>
            {sosPosts.map(p=><PostCard key={p.id} item={p} onTap={()=>onSelect(p)}/>)}
          </div>
        }
      </div>
    </div>
  );
}

function PremiumScreen({onBack}){
  const state = window._appState;
  const A = window.AppStore.actions;
  const [plan,setPlan] = useState('pro');
  const [billing,setBilling] = useState('monthly');
  const PLANS = [
    {k:'basic', l:'Basic', p:29, py:290, sub:'Für kleine Geschäfte', f:[
      '1 Deal pro Woche (~4/Mo)',
      'Profil-Badge BASIC',
      'Eigene Geschäftsseite',
      'Bewertungen sammeln',
      'Standard-Sichtbarkeit im Feed',
    ]},
    {k:'pro', l:'Pro', p:79, py:790, sub:'Für aktive Gewerbe', popular:true, f:[
      '1 Deal pro Tag (~30/Mo)',
      '2 Featured-Slots / Monat',
      'Profil + Live-Stats Dashboard',
      'Push-Reichweiten-Boost',
      'Priorität im Feed',
      'Direkter Chat mit Kunden',
    ]},
    {k:'premium', l:'Premium', p:149, py:1490, sub:'Maximale Reichweite', f:[
      'Unlimitierte Deals',
      '8 Featured-Slots / Monat',
      'Hero-Slot rotierend',
      'Dedicated Push-Kampagnen',
      'Detaillierte Analytics + Export',
      'Persönlicher Account-Manager',
      'Erweiterter Bezirks-Reach',
    ]},
  ];
  const sel = PLANS.find(p=>p.k===plan);
  const price = billing==='yearly' ? sel.py : sel.p;
  const monthly = billing==='yearly' ? Math.round(sel.py/12) : sel.p;

  return (
    <div className="aIn" style={{flex:1, overflowY:'auto', background:T.ink, color:'#fff'}}>
      <div style={{padding:'12px 14px'}}>
        <button onClick={onBack} style={{width:34, height:34, borderRadius:10, background:'#1F1F25', color:'#fff', border:'none', fontSize:16, cursor:'pointer'}}>‹</button>
      </div>
      <div style={{padding:'14px 22px 32px'}}>
        <div style={{fontSize:11, fontWeight:800, color:T.gold, letterSpacing:'.5px', marginBottom:8}}>✦ BEZIRK.LIVE PREMIUM</div>
        <div style={{fontFamily:'Fraunces, serif', fontSize:32, fontWeight:700, letterSpacing:'-1px', lineHeight:1.1, marginBottom:10}}>Pushe dein<br/>Geschäft.</div>
        <div style={{fontSize:13.5, color:'#A8A59E', lineHeight:1.55, marginBottom:18, fontWeight:500}}>Erreiche Tausende Nachbarn mit Deals, Angeboten und Featured-Slots.</div>

        <div style={{display:'flex', gap:6, padding:4, background:'#1A1A22', borderRadius:11, marginBottom:18}}>
          <button onClick={()=>setBilling('monthly')} style={{flex:1, padding:'8px', border:'none', borderRadius:8, background: billing==='monthly'?'#2A2A35':'transparent', color:'#fff', fontSize:12, fontWeight:700, cursor:'pointer'}}>Monatlich</button>
          <button onClick={()=>setBilling('yearly')} style={{flex:1, padding:'8px', border:'none', borderRadius:8, background: billing==='yearly'?'#2A2A35':'transparent', color:'#fff', fontSize:12, fontWeight:700, cursor:'pointer', position:'relative'}}>
            Jährlich
            <span style={{position:'absolute', top:-6, right:6, background:T.gold, color:T.ink, fontSize:9, fontWeight:800, padding:'1px 5px', borderRadius:4}}>-17%</span>
          </button>
        </div>

        <div style={{display:'flex', flexDirection:'column', gap:10, marginBottom:20}}>
          {PLANS.map(p=>{
            const m = billing==='yearly' ? Math.round(p.py/12) : p.p;
            return (
              <div key={p.k} onClick={()=>setPlan(p.k)} className="cp" style={{padding:'14px 16px', background: plan===p.k?'#2A2A35':'#1A1A22', border:`2px solid ${plan===p.k?T.gold:'#2A2A35'}`, borderRadius:14, cursor:'pointer', position:'relative'}}>
                {p.popular && <div style={{position:'absolute', top:-9, left:14, background:T.gold, color:T.ink, fontSize:9.5, fontWeight:800, padding:'3px 8px', borderRadius:5, letterSpacing:'.4px'}}>BELIEBT</div>}
                <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:8}}>
                  <div>
                    <div style={{fontSize:16, fontWeight:800}}>{p.l}</div>
                    <div style={{fontSize:11, color:'#A8A59E', fontWeight:500, marginTop:1}}>{p.sub}</div>
                  </div>
                  <div style={{textAlign:'right'}}>
                    <span style={{fontFamily:'Fraunces, serif', fontSize:24, fontWeight:700}}>€{m}</span>
                    <span style={{fontSize:11, color:'#A8A59E', fontWeight:600}}> / Mo</span>
                    {billing==='yearly' && <div style={{fontSize:10, color:T.gold, fontWeight:700}}>€{p.py}/Jahr</div>}
                  </div>
                </div>
                {p.f.map(x=>(
                  <div key={x} style={{fontSize:12, color:'#C8C5BE', fontWeight:500, marginBottom:3, display:'flex', gap:6}}>
                    <span style={{color:T.gold, flexShrink:0}}>✓</span><span>{x}</span>
                  </div>
                ))}
              </div>
            );
          })}
        </div>

        <Btn full size="lg" kind="primary" style={{background:T.gold, color:T.ink, borderColor:T.gold}} onClick={()=>{
          A.upgradeTier(plan);
          A.updateMe({verified:true});
          alert(`✓ Stripe-Zahlung simuliert · Du bist jetzt ${plan.toUpperCase()}!\n\nGebucht: €${price} ${billing==='yearly'?'/Jahr':'/Monat'}`);
          onBack();
        }}>Mit Stripe bezahlen — €{price}{billing==='yearly'?' /Jahr':' /Mo'}</Btn>
        <div style={{fontSize:11, color:'#666', textAlign:'center', marginTop:10, fontWeight:500, lineHeight:1.5}}>Jederzeit kündbar · 14 Tage Geld-zurück-Garantie<br/>Stripe-Verschlüsselung · Rechnung als PDF</div>
      </div>
    </div>
  );
}

Object.assign(window, { ComposeSheet, InboxScreen, ChatScreen, RatingModal, ProfileScreen, SettingsScreen, HelpScreen, PremiumScreen });
