/* ═══════════════════════════════════════════════════════════════
   bezirk.live — Screens Part 1: Onboarding, Feed, Detail
   ═══════════════════════════════════════════════════════════════ */

// ───────────────────────────────────────────────────────────────
// ONBOARDING (5 Schritte)
// ───────────────────────────────────────────────────────────────
function OnboardingFlow({onComplete}){
  // Prefill from invite param: ?ort=bruck-an-der-leitha → bezirk = "Bruck an der Leitha"
  const invite = (typeof window.parseInviteOrt === 'function') ? window.parseInviteOrt() : null;
  const [step,setStep] = useState(0);
  const [data,setData] = useState({
    name:'',
    handle:'',
    plz:'',
    bezirk: invite ? invite.name : '',
    locationType:'bezirk',
    interests:[],
    phone:'',
    avatarUrl: null,
    invitedFrom: invite ? invite.name : null,
  });

  // Wenn von Invite-Link kommend, Bezirks-Step überspringen (bezirk ist schon gesetzt)
  const skipBezirk = !!invite;

  const next = ()=>{
    setStep(s => {
      const nextStep = s + 1;
      // 3 = Bezirks-Step → wenn skipBezirk, eins weiter springen
      if (nextStep === 3 && skipBezirk) return 4;
      return nextStep;
    });
  };
  const finish = ()=>{
    onComplete({
      name: data.name || 'Du',
      handle: data.handle || data.name.toLowerCase().replace(/\s/g,'') || 'du',
      bezirk: data.bezirk,
      plz: data.plz,
      interests: data.interests,
      verified: !!data.phone,
      avatarUrl: data.avatarUrl,
    });
  };

  const totalSteps = skipBezirk ? 5 : 6;
  const visualStep = skipBezirk && step > 3 ? step - 1 : step;

  return (
    <div style={{flex:1, background:T.bg, display:'flex', flexDirection:'column', position:'relative'}}>
      {/* Progress */}
      <div style={{display:'flex', gap:6, padding:'24px 22px 8px'}}>
        {Array.from({length: totalSteps}).map((_,i)=>(
          <div key={i} style={{flex:1, height:3, background: i<=visualStep?T.green:T.bdr, borderRadius:2}}/>
        ))}
      </div>
      <div style={{flex:1, overflowY:'auto', padding:'20px 22px 100px'}}>
        {step===0 && <OnbWelcome data={data} onNext={next}/>}
        {step===1 && <OnbName data={data} setData={setData} onNext={next}/>}
        {step===2 && <OnbAvatar data={data} setData={setData} onNext={next}/>}
        {step===3 && !skipBezirk && <OnbBezirk data={data} setData={setData} onNext={next}/>}
        {step===4 && <OnbPhone data={data} setData={setData} onNext={next}/>}
        {step===5 && <OnbInterests data={data} setData={setData} onNext={finish}/>}
      </div>
    </div>
  );
}

function OnbAvatar({data, setData, onNext}){
  const [uploading, setUploading] = useState(false);
  const fileRef = useRef(null);

  async function handleFile(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; }
    setUploading(true);
    try {
      // Read as data URL — Upload erfolgt am Ende des Onboardings durch wrapped action
      const dataUrl = await new Promise((res, rej) => {
        const r = new FileReader();
        r.onload = e => res(e.target.result);
        r.onerror = rej;
        r.readAsDataURL(file);
      });
      setData({...data, avatarUrl: dataUrl});
    } catch(e){
      alert('Fehler beim Laden: ' + e.message);
    } finally {
      setUploading(false);
    }
  }

  return (
    <div className="aIn">
      <div style={{fontFamily:'Fraunces, serif', fontSize:30, fontWeight:700, letterSpacing:'-1px', marginBottom:8}}>Zeig dein Gesicht.</div>
      <div style={{fontSize:14, color:T.sec, marginBottom:24, fontWeight:500, lineHeight:1.55, textWrap:'pretty'}}>
        Profile mit echtem Foto bekommen <strong style={{color:T.text}}>5× mehr Vertrauen</strong>. Du kannst es jederzeit ändern oder weglassen.
      </div>

      {/* Avatar Preview */}
      <div style={{display:'flex', justifyContent:'center', marginBottom:24}}>
        <div style={{position:'relative', cursor:'pointer'}} onClick={()=>!uploading && fileRef.current?.click()}>
          {data.avatarUrl ? (
            <img src={data.avatarUrl} alt="" style={{
              width:140, height:140, borderRadius:'50%', objectFit:'cover',
              border:`4px solid #fff`, boxShadow:'0 8px 24px rgba(10,74,36,.18)',
            }}/>
          ) : (
            <div style={{
              width:140, height:140, borderRadius:'50%',
              background:`linear-gradient(135deg, ${T.greenL}, #D0E4D8)`,
              display:'flex', alignItems:'center', justifyContent:'center',
              fontSize:48, color:T.green,
              border:`4px solid #fff`, boxShadow:'0 8px 24px rgba(10,74,36,.10)',
            }}>📷</div>
          )}
          <div style={{
            position:'absolute', bottom:6, right:6, width:40, height:40, borderRadius:'50%',
            background: uploading ? T.muted : T.green, color:'#fff',
            display:'flex', alignItems:'center', justifyContent:'center',
            border:'3px solid #fff', fontSize:18, fontWeight:800,
            boxShadow:'0 4px 12px rgba(0,0,0,.15)',
          }}>{uploading ? '⏳' : data.avatarUrl ? '✓' : '+'}</div>
          <input
            ref={fileRef}
            type="file"
            accept="image/*"
            style={{display:'none'}}
            onChange={e=>{ handleFile(e.target.files[0]); e.target.value=''; }}
          />
        </div>
      </div>

      <Btn full kind="primary" size="lg" onClick={()=>fileRef.current?.click()} disabled={uploading}>
        {data.avatarUrl ? '📷 Foto ändern' : '📷 Foto wählen'}
      </Btn>
      <button onClick={onNext} style={{
        width:'100%', marginTop:10, padding:'14px',
        background:'transparent', border:'none', cursor:'pointer',
        fontSize:13.5, fontWeight:600, color:T.sec, fontFamily:'inherit',
      }}>
        {data.avatarUrl ? 'Weiter →' : 'Überspringen — später hinzufügen'}
      </button>
    </div>
  );
}

function OnbWelcome({data, onNext}){
  const invitedFrom = data?.invitedFrom;
  return (
    <div className="aIn" style={{paddingTop:30}}>
      <div style={{width:74, height:74, borderRadius:18, background:`linear-gradient(135deg, ${T.green}, #166435)`, display:'flex', alignItems:'center', justifyContent:'center', color:'#fff', fontFamily:'Fraunces, serif', fontWeight:700, fontSize:38, marginBottom:30, boxShadow:'0 12px 30px rgba(10,74,36,.25)'}}>b.</div>

      {invitedFrom && (
        <div style={{display:'inline-flex', alignItems:'center', gap:7, padding:'5px 12px', background:T.greenL, color:T.green, borderRadius:18, fontSize:10.5, fontWeight:800, letterSpacing:'.5px', marginBottom:14}}>
          <span style={{width:6, height:6, borderRadius:'50%', background:T.green}}></span>
          DEIN ORT IST EINGESTELLT
        </div>
      )}

      {invitedFrom ? (
        <>
          <h1 style={{fontFamily:'Fraunces, serif', fontSize:36, fontWeight:700, letterSpacing:'-1.3px', lineHeight:1.05, marginBottom:8}}>
            Willkommen<br/>in <span style={{color:T.green}}>{invitedFrom}</span>.
          </h1>
          <p style={{fontSize:15, color:T.sec, lineHeight:1.6, marginBottom:24, fontWeight:500, textWrap:'pretty'}}>
            Wir richten dein Profil in <strong style={{color:T.text}}>nur 3 Schritten</strong> ein — Name, Verifizierung & Interessen. Dann legst du los.
          </p>
        </>
      ) : (
        <>
          <h1 style={{fontFamily:'Fraunces, serif', fontSize:42, fontWeight:700, letterSpacing:'-1.5px', lineHeight:1.05, marginBottom:14}}>Dein Bezirk.<br/>Lokal. Sofort.</h1>
          <p style={{fontSize:15, color:T.sec, lineHeight:1.6, marginBottom:30, fontWeight:500}}>Hilfe von Nachbarn. Angebote vom Greißler ums Eck. Deals nur für deinen Bezirk. Echte Menschen, echte Verbindungen — kein Algorithmus, der dich auseinandertreibt.</p>
        </>
      )}

      <div style={{display:'flex', flexDirection:'column', gap:8, marginBottom:24}}>
        {[
          {i:'🤝', t:'Soforthilfe', s:'Babysitter, Einkauf, Hund Gassi'},
          {i:'⚡', t:'Deals & Angebote', s:'Lokale Geschäfte, exklusiv'},
          {i:'💬', t:'Bezirk fragt', s:'Empfehlungen, Tipps, Diskussionen'},
        ].map(x=>(
          <div key={x.t} style={{display:'flex', gap:14, padding:'12px 14px', background:'#fff', border:`1px solid ${T.bdr}`, borderRadius:13}}>
            <div style={{fontSize:24}}>{x.i}</div>
            <div><div style={{fontSize:14, fontWeight:700}}>{x.t}</div><div style={{fontSize:12, color:T.sec, fontWeight:500}}>{x.s}</div></div>
          </div>
        ))}
      </div>
      <Btn full kind="primary" size="lg" onClick={onNext}>Los geht's</Btn>
    </div>
  );
}

function OnbName({data, setData, onNext}){
  const ok = data.name.trim().length>=2;
  return (
    <div className="aIn">
      <div style={{fontFamily:'Fraunces, serif', fontSize:30, fontWeight:700, letterSpacing:'-1px', marginBottom:8}}>Wie heißt du?</div>
      <div style={{fontSize:14, color:T.sec, marginBottom:24, fontWeight:500}}>Deine Nachbarn sehen deinen Vornamen. Echte Namen schaffen Vertrauen.</div>
      <Input label="Vorname" value={data.name} onChange={v=>setData({...data, name:v})} placeholder="z.B. Anna" max={30}/>
      <Input label="Handle (optional)" value={data.handle} onChange={v=>setData({...data, handle:v})} placeholder="annak" max={20} prefix="@" hint="Wird nur in deinem Profil-Link verwendet"/>
      <Btn full kind="primary" size="lg" disabled={!ok} onClick={onNext}>Weiter</Btn>
    </div>
  );
}

// ─── Geo lookup helpers (OpenStreetMap Nominatim — gratis, kein Key) ───
async function geoLookupPLZ(plz){
  try {
    const r = await fetch(`https://nominatim.openstreetmap.org/search?postalcode=${encodeURIComponent(plz)}&country=AT&format=json&limit=10&addressdetails=1&accept-language=de`);
    if (!r.ok) return [];
    const arr = await r.json();
    const seen = new Set();
    return 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 type = locationType(a);
      const key = (name+'|'+(a.state||'')).toLowerCase();
      if (seen.has(key)) return null;
      seen.add(key);
      return { plz, name, state: a.state || '', type, lat: +d.lat, lon: +d.lon, full: d.display_name };
    }).filter(Boolean);
  } catch(e){ return []; }
}
async function geoReverse(lat, lon){
  try {
    const r = await fetch(`https://nominatim.openstreetmap.org/reverse?lat=${lat}&lon=${lon}&format=json&addressdetails=1&accept-language=de&zoom=14`);
    if (!r.ok) return null;
    const d = await r.json();
    const a = d.address || {};
    return {
      plz: a.postcode || '',
      name: a.suburb || a.city_district || a.town || a.village || a.municipality || a.county || '',
      state: a.state || '',
      type: locationType(a),
      lat, lon,
      full: d.display_name,
    };
  } catch(e){ return null; }
}
async function geoSearch(q){
  try {
    const r = await fetch(`https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(q)}&countrycodes=at&format=json&limit=8&addressdetails=1&accept-language=de`);
    if (!r.ok) return [];
    const arr = await r.json();
    const seen = new Set();
    return 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 = locationType(a);
      const key = (name+'|'+plz).toLowerCase();
      if (seen.has(key)) return null;
      seen.add(key);
      return { plz, name, state: a.state || '', type, lat: +d.lat, lon: +d.lon, full: d.display_name };
    }).filter(Boolean);
  } catch(e){ return []; }
}

// Heuristik: Stadt / Dorf / Bezirk aus OSM-Adress-Daten ableiten
function locationType(a){
  if (!a) return 'bezirk';
  if (a.suburb || a.city_district || a.neighbourhood) return 'bezirk';   // innerhalb einer Stadt
  if (a.city)    return 'stadt';
  if (a.town)    return 'stadt';
  if (a.village) return 'dorf';
  if (a.hamlet)  return 'dorf';
  if (a.municipality) return 'dorf';
  return 'bezirk';
}

// User-facing label: "Stadt fragt", "Dorf fragt", "Bezirk fragt"
function forumLabel(type){
  return type === 'stadt' ? 'Stadt fragt'
       : type === 'dorf'  ? 'Dorf fragt'
       : 'Bezirk fragt';
}
window.forumLabel = forumLabel;

function OnbBezirk({data, setData, onNext}){
  const [search,setSearch] = useState('');
  const [results,setResults] = useState([]);     // current Treffer-Liste
  const [loading,setLoading] = useState(false);
  const [gpsErr,setGpsErr] = useState('');
  const [hint,setHint] = useState('');           // "Treffer für 2460", etc.

  // PLZ auto-lookup (debounced) — sobald 4 Ziffern
  useEffect(()=>{
    const plz = (data.plz||'').trim();
    if (!/^\d{4}$/.test(plz)){
      // bei <4 Ziffern: zeige nur Suchergebnisse
      if (!search) setResults([]);
      return;
    }
    let cancelled = false;
    setLoading(true);
    setHint('');
    geoLookupPLZ(plz).then(rows=>{
      if (cancelled) return;
      setLoading(false);
      if (rows.length === 0){
        setHint(`Keine Treffer für PLZ ${plz} — gib unten den Ort ein.`);
        setResults([]);
      } else {
        setHint(`Treffer für ${plz}`);
        setResults(rows);
        // Automatisch ersten Vorschlag wählen, wenn noch nichts ausgewählt
        if (!data.bezirk){
          setData(d=>({...d, bezirk: rows[0].name, locationType: rows[0].type || 'bezirk'}));
        }
      }
    });
    return ()=>{ cancelled=true; };
  }, [data.plz]);

  // Freitext-Suche (debounced)
  useEffect(()=>{
    if (!search || search.length < 2) return;
    const t = setTimeout(()=>{
      setLoading(true);
      geoSearch(search).then(rows=>{
        setLoading(false);
        if (rows.length){
          setHint(`Treffer für „${search}"`);
          setResults(rows);
        } else {
          setHint(`Nichts gefunden für „${search}"`);
        }
      });
    }, 350);
    return ()=>clearTimeout(t);
  }, [search]);

  // GPS Standort
  async function useGPS(){
    setGpsErr(''); setHint('');
    if (!navigator.geolocation){ setGpsErr('GPS nicht verfügbar.'); return; }
    setLoading(true);
    navigator.geolocation.getCurrentPosition(async pos=>{
      const loc = await geoReverse(pos.coords.latitude, pos.coords.longitude);
      setLoading(false);
      if (!loc || !loc.name){ setGpsErr('Konnte Standort nicht zuordnen — bitte PLZ eingeben.'); return; }
      setData(d=>({...d, plz: loc.plz || d.plz, bezirk: loc.name, locationType: loc.type || 'bezirk' }));
      setHint(`✓ ${loc.name}${loc.plz?' · '+loc.plz:''}${loc.state?' · '+loc.state:''}`);
      setResults([loc]);
    }, err=>{
      setLoading(false);
      setGpsErr(err.code===1 ? 'Standort blockiert — bitte PLZ eingeben.' : 'GPS fehlgeschlagen — bitte PLZ eingeben.');
    }, { enableHighAccuracy:false, timeout:8000, maximumAge:60000 });
  }

  const showList = results.length > 0;

  return (
    <div className="aIn">
      <div style={{fontFamily:'Fraunces, serif', fontSize:30, fontWeight:700, letterSpacing:'-1px', marginBottom:8}}>Wo wohnst du?</div>
      <div style={{fontSize:14, color:T.sec, marginBottom:16, fontWeight:500}}>Du siehst nur Posts in deinem Bezirk und Umgebung — bis zu 20 km.</div>

      {/* GPS Button */}
      <button onClick={useGPS} disabled={loading} style={{
        width:'100%', padding:'14px 16px', marginBottom:14, display:'flex', alignItems:'center', gap:12,
        background:'#fff', border:`1.5px solid ${T.green}`, borderRadius:13, cursor:'pointer',
        color:T.green, fontWeight:700, fontSize:14, fontFamily:'inherit',
      }}>
        <span style={{fontSize:20}}>📍</span>
        <span style={{flex:1, textAlign:'left'}}>{loading?'Suche Standort…':'Mein Standort automatisch erkennen'}</span>
        <span style={{fontSize:18}}>›</span>
      </button>
      {gpsErr && <div style={{fontSize:12, color:'#B91C1C', fontWeight:600, marginBottom:10}}>⚠ {gpsErr}</div>}

      <div style={{display:'flex', alignItems:'center', gap:10, margin:'4px 0 12px'}}>
        <div style={{flex:1, height:1, background:T.bdr}}></div>
        <div style={{fontSize:11, color:T.muted, fontWeight:700, letterSpacing:'.5px'}}>ODER MANUELL</div>
        <div style={{flex:1, height:1, background:T.bdr}}></div>
      </div>

      <Input label="PLZ" value={data.plz} onChange={v=>setData({...data, plz:v.replace(/\D/g,'')})} placeholder="z.B. 2460, 1010, 8010" max={4}/>
      <Input label="Ort oder Bezirk suchen" value={search} onChange={setSearch} placeholder="z.B. Bruck an der Leitha, Geidorf"/>

      {hint && <div style={{fontSize:12, color:T.sec, fontWeight:600, margin:'-6px 0 10px'}}>{hint}</div>}

      {showList && (
        <div style={{maxHeight:220, overflowY:'auto', border:`1px solid ${T.bdr}`, borderRadius:11, marginBottom:18, background:'#fff'}}>
          {results.map((b,i)=>{
            const selected = data.bezirk===b.name && (!b.plz || data.plz===b.plz);
            return (
              <div key={i} onClick={()=>setData({...data, bezirk:b.name, plz:b.plz||data.plz, locationType:b.type||'bezirk'})}
                style={{padding:'12px 14px', borderBottom:i<results.length-1?`1px solid ${T.bdr}`:'none', cursor:'pointer',
                display:'flex', justifyContent:'space-between', alignItems:'center', gap:10, background: selected?T.greenL:'transparent'}}>
                <div style={{minWidth:0, flex:1}}>
                  <div style={{fontSize:14, fontWeight: selected?700:600, color:T.text}}>{b.name}</div>
                  <div style={{fontSize:11, color:T.muted, fontWeight:500, marginTop:2, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap'}}>
                    {b.plz && <span style={{fontWeight:700, color:T.sec}}>{b.plz}</span>}
                    {b.plz && b.state && ' · '}
                    {b.state}
                  </div>
                </div>
                {selected && <span style={{color:T.green, fontWeight:700, fontSize:18}}>✓</span>}
              </div>
            );
          })}
        </div>
      )}

      {!showList && data.bezirk && !loading && (
        <div style={{padding:'12px 14px', marginBottom:18, background:T.greenL, borderRadius:11, fontSize:13, fontWeight:600, color:T.green}}>
          ✓ Aktuell ausgewählt: <strong>{data.bezirk}</strong>{data.plz?' · '+data.plz:''}
        </div>
      )}

      <Btn full kind="primary" size="lg" disabled={!data.bezirk} onClick={onNext}>Weiter</Btn>
    </div>
  );
}

function OnbPhone({data, setData, onNext}){
  const [code,setCode] = useState('');
  const [sent,setSent] = useState(false);
  const ok = data.phone.length>=10;
  return (
    <div className="aIn">
      <div style={{fontFamily:'Fraunces, serif', fontSize:30, fontWeight:700, letterSpacing:'-1px', marginBottom:8}}>Verifiziere dich</div>
      <div style={{fontSize:14, color:T.sec, marginBottom:20, fontWeight:500}}>Verifizierte Nutzer haben höhere Erfolgsraten. Deine Nummer ist privat.</div>
      <Input label="Telefonnummer" value={data.phone} onChange={v=>setData({...data, phone:v})} placeholder="+43 660 1234567" type="tel"/>
      {!sent
        ? <Btn full kind="secondary" disabled={!ok} onClick={()=>setSent(true)}>Code senden</Btn>
        : <>
            <Input label="6-stelliger Code" value={code} onChange={setCode} placeholder="123456" max={6}/>
            <div style={{fontSize:12, color:T.green, fontWeight:600, marginBottom:12}}>✓ Code gesendet (Demo: gib irgendwas ein)</div>
            <Btn full kind="primary" size="lg" disabled={code.length<3} onClick={onNext}>Verifizieren & weiter</Btn>
          </>
      }
      <div style={{textAlign:'center', marginTop:14}}>
        <a style={{fontSize:12, color:T.muted, fontWeight:600, cursor:'pointer'}} onClick={onNext}>Später verifizieren →</a>
      </div>
    </div>
  );
}

function OnbInterests({data, setData, onNext}){
  const [agb, setAgb] = useState(false);
  const toggle = k => {
    setData({...data, interests: data.interests.includes(k) ? data.interests.filter(x=>x!==k) : [...data.interests, k]});
  };
  return (
    <div className="aIn">
      <div style={{fontFamily:'Fraunces, serif', fontSize:30, fontWeight:700, letterSpacing:'-1px', marginBottom:8}}>Was interessiert dich?</div>
      <div style={{fontSize:14, color:T.sec, marginBottom:20, fontWeight:500}}>Wir zeigen dir relevante Posts zuerst. Du kannst es später ändern.</div>
      <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:9, marginBottom:18}}>
        {SEED_INTERESTS.map(i=>{
          const on = data.interests.includes(i.k);
          return (
            <div key={i.k} onClick={()=>toggle(i.k)} className="cp" style={{
              padding:'14px 12px', background: on?T.greenL:'#fff', border:`1.5px solid ${on?T.green:T.bdr}`,
              borderRadius:13, cursor:'pointer', display:'flex', alignItems:'center', gap:9,
            }}>
              <div style={{fontSize:22}}>{i.i}</div>
              <div style={{fontSize:13, fontWeight:700, color: on?T.green:T.text}}>{i.l}</div>
            </div>
          );
        })}
      </div>

      <label style={{display:'flex', gap:10, alignItems:'flex-start', padding:'12px 14px', background:'#fff', border:`1.5px solid ${agb?T.green:T.bdr}`, borderRadius:12, cursor:'pointer', marginBottom:14}}>
        <input type="checkbox" checked={agb} onChange={e=>setAgb(e.target.checked)} style={{marginTop:2, width:18, height:18, accentColor:T.green, cursor:'pointer', flexShrink:0}}/>
        <span style={{fontSize:12.5, color:T.sec, fontWeight:500, lineHeight:1.5}}>
          Ich akzeptiere die <a href="/agb.html" target="_blank" rel="noopener" style={{color:T.green, fontWeight:700}}>Nutzungs­bedingungen</a> und die <a href="/datenschutz.html" target="_blank" rel="noopener" style={{color:T.green, fontWeight:700}}>Datenschutz­erklärung</a>.
        </span>
      </label>

      <Btn full kind="primary" size="lg" disabled={data.interests.length===0 || !agb} onClick={onNext}>Fertig — App starten</Btn>
    </div>
  );
}

// ───────────────────────────────────────────────────────────────
// EMPTY BEZIRK HERO — wenn User Pionier in seinem Bezirk ist
// ───────────────────────────────────────────────────────────────
function EmptyBezirkHero({bezirk, totalUsers, onInvite, onCompose}){
  const slug = (typeof window.bezirkSlug === 'function') ? window.bezirkSlug(bezirk) : '';
  const inviteUrl = `${location.origin}${slug ? '?ort='+slug : ''}`;
  const inviteText = encodeURIComponent(
    `Hey! Ich hab gerade „bezirk.live" entdeckt — der digitale Dorfplatz für ${bezirk}. ` +
    `Hilfe von Nachbarn, Tausch, lokale Diskussionen. Echte Leute, kein Spam. ` +
    `Mach mit: ${inviteUrl}`
  );

  function nativeShare(){
    if (navigator.share){
      navigator.share({
        title: `${bezirk} ist auf bezirk.live`,
        text: `Der digitale Dorfplatz für ${bezirk} — mach mit!`,
        url: inviteUrl,
      }).then(() => onInvite && onInvite()).catch(()=>{});
    } else {
      // Fallback: open WhatsApp
      window.open(`https://wa.me/?text=${inviteText}`, '_blank');
      onInvite && onInvite();
    }
  }

  return (
    <div style={{margin:'10px 18px 16px', borderRadius:18, overflow:'hidden', boxShadow:'0 8px 24px rgba(10,74,36,.18)'}}>
      {/* Top: green hero */}
      <div style={{background:`linear-gradient(135deg, ${T.green} 0%, #166435 60%, #0F5C2B 100%)`, padding:'24px 22px 22px', color:'#fff', position:'relative', overflow:'hidden'}}>
        {/* Decorative dots */}
        <div style={{position:'absolute', top:-20, right:-20, width:140, height:140, borderRadius:'50%', background:'rgba(255,255,255,.06)'}}></div>
        <div style={{position:'absolute', bottom:-40, left:-30, width:160, height:160, borderRadius:'50%', background:'rgba(255,255,255,.04)'}}></div>

        <div style={{position:'relative', zIndex:1}}>
          <div style={{display:'inline-flex', alignItems:'center', gap:7, padding:'5px 11px', background:'rgba(255,255,255,.16)', borderRadius:20, fontSize:10.5, fontWeight:800, letterSpacing:'.5px', marginBottom:14}}>
            <span style={{width:6, height:6, borderRadius:'50%', background:'#7FE8A8'}}></span>
            DU BIST PIONIER:IN
          </div>
          <div style={{fontFamily:'Fraunces, serif', fontSize:26, fontWeight:700, letterSpacing:'-.7px', lineHeight:1.1, marginBottom:8}}>
            Erste:r in<br/>{bezirk}
          </div>
          <div style={{fontSize:13.5, color:'rgba(255,255,255,.85)', fontWeight:500, lineHeight:1.5, marginBottom:18, textWrap:'pretty'}}>
            Dein Bezirk wartet auf dich. Lade Nachbarn ein, mach den ersten Post — und werde <strong style={{color:'#fff'}}>offizielle:r Bezirks-Botschafter:in</strong> (Premium 6 Monate gratis).
          </div>

          {/* Two buttons */}
          <div style={{display:'flex', gap:8}}>
            <button
              onClick={nativeShare}
              style={{flex:1, padding:'12px 14px', background:'#fff', color:T.green, borderRadius:11, fontSize:13.5, fontWeight:800, textAlign:'center', textDecoration:'none', display:'flex', alignItems:'center', justifyContent:'center', gap:7, border:'none', cursor:'pointer', fontFamily:'inherit'}}>
              <span style={{fontSize:16}}>📤</span> Nachbarn einladen
            </button>
            <button onClick={onCompose} style={{
              padding:'12px 14px', background:'rgba(255,255,255,.18)', color:'#fff',
              border:'1.5px solid rgba(255,255,255,.35)', borderRadius:11, fontSize:13.5, fontWeight:700,
              cursor:'pointer', fontFamily:'inherit',
            }}>
              ✦ Posten
            </button>
          </div>
          <div style={{marginTop:10, padding:'7px 11px', background:'rgba(0,0,0,.20)', borderRadius:8, fontSize:11, color:'rgba(255,255,255,.85)', fontWeight:600, display:'flex', alignItems:'center', gap:6, justifyContent:'center'}}>
            <span style={{fontSize:11}}>🔗</span>
            <span style={{fontFamily:'monospace'}}>{inviteUrl.replace(/^https?:\/\//,'')}</span>
          </div>
        </div>
      </div>

      {/* Bottom: progress stripe */}
      <div style={{background:'#fff', padding:'14px 18px', display:'flex', alignItems:'center', gap:14, borderTop:'1px solid rgba(0,0,0,.05)'}}>
        <div style={{display:'flex', alignItems:'center', gap:-8}}>
          {[0,1,2].map(i=>(
            <div key={i} style={{
              width:30, height:30, borderRadius:'50%', border:'2.5px solid #fff',
              background:`linear-gradient(135deg, ${['#A8C8A0','#D4C4A4','#A8C0D8'][i]}, ${['#5A9060','#A08858','#5880A8'][i]})`,
              marginLeft: i===0?0:-8, display:'flex', alignItems:'center', justifyContent:'center',
              fontSize:11, fontWeight:800, color:'#fff',
            }}>{['A','M','S'][i]}</div>
          ))}
        </div>
        <div style={{flex:1, minWidth:0}}>
          <div style={{fontSize:12.5, fontWeight:700, color:T.text}}>Lade 3 Nachbarn ein</div>
          <div style={{fontSize:11, color:T.sec, fontWeight:500, marginTop:1}}>
            Schalt deinen Botschafter:innen-Status frei
          </div>
        </div>
        <div style={{fontSize:11, fontWeight:800, color:T.amber, background:T.amberL, padding:'5px 9px', borderRadius:7}}>
          0 / 3
        </div>
      </div>
    </div>
  );
}

// ───────────────────────────────────────────────────────────────
// FEED (Home)
// ───────────────────────────────────────────────────────────────
function FeedScreen({onSelect, onCompose}){
  const state = window._appState;
  const [filter,setFilter] = useState('all');
  const [radius,setRadius] = useState(10);
  const [memberCount, setMemberCount] = useState(null);

  // Echte Mitgliederzahl des Bezirks aus der Cloud holen
  useEffect(() => {
    const bz = state.me.bezirk;
    if (!bz || !window.BL?.client) return;
    let cancelled = false;
    window.BL.client.from('profiles').select('id', { count:'exact', head:true }).eq('bezirk', bz)
      .then(({ count }) => { if (!cancelled && count != null) setMemberCount(count); })
      .catch(()=>{});
    return () => { cancelled = true; };
  }, [state.me.bezirk]);
  const TABS = [
    {k:'all',     l:'Alle',     i:'◆'},
    {k:'deal',    l:'Deals',    i:'⚡'},
    {k:'angebot', l:'Angebote', i:'✦'},
    {k:'sos',     l:'Hilfe',    i:'🤝'},
    {k:'gesuch',  l:'Gesuche',  i:'🔍'},
    {k:'frage',   l:'Fragen',   i:'💬'},
  ];

  // Filter hidden posts from feed (auto-hide nach 3 Meldungen)
  const allPosts = state.posts.filter(p => (p.status==='aktiv' || !p.status) && !p.hidden);

  // ─── PIONIER-CHECK: Sind Posts in meinem Bezirk? ──────────
  // Wir gelten als "Pionier" wenn KEIN Post in unserem Bezirk existiert
  // (Vereinfachte Logik: matched bezirk-Name; demo-data ist Graz-zentriert,
  //  in production filtert das per echtem Bezirk-Match)
  const myBezirk = state.me.bezirk || '';
  const sameBezirk = (p) => {
    if (!p.bezirk || !myBezirk) return false;
    return p.bezirk.toLowerCase().trim() === myBezirk.toLowerCase().trim();
  };
  const myBezirkPosts = allPosts.filter(sameBezirk);
  const isPioneer = myBezirk && myBezirkPosts.length === 0;

  // HYPERLOKAL: Hauptfeed zeigt NUR Posts aus dem eigenen Ort.
  // (Demo-Modus ohne echten Bezirk-Match → alle zeigen.)
  const cloudOn = !!(window.BEZIRKLIVE_CONFIG && window.BEZIRKLIVE_CONFIG.isConfigured());
  const scopedPosts = cloudOn ? myBezirkPosts : allPosts;

  const filteredByCat = filter==='all' ? scopedPosts : scopedPosts.filter(p=>p.type===filter);
  const filteredByDist = filteredByCat.filter(p=>(p.distance||0) <= radius);

  // Premium first, then private; deals always at top
  const premium = filteredByDist.filter(p=>p.type==='deal' || p.type==='angebot' && (p.ownerTier==='basic'||p.ownerTier==='pro'||p.ownerTier==='premium'));
  const rest = filteredByDist.filter(p=>!premium.includes(p));

  // Hero rotation: pick one premium based on hour (but NOT shown if pioneer)
  const hero = (!isPioneer && premium.length>0) ? premium[new Date().getHours() % premium.length] : null;
  const others = premium.filter(p=>p.id!==(hero?.id));

  const sosActive = scopedPosts.filter(p=>p.type==='sos' && (p.status==='aktiv'||!p.status)).slice(0,2);
  const sosCount = scopedPosts.filter(p=>p.type==='sos' && (p.status==='aktiv'||!p.status)).length;

  // For pioneer mode: show "inspiration posts" from other bezirke
  const inspirationPosts = isPioneer
    ? allPosts.filter(p => !sameBezirk(p))
    : [];

  function handleInvite(){
    // could track invite count in store for the badge progress
    try { window.AppStore.actions.notify && window.AppStore.actions.notify({type:'system', title:'Einladung geteilt', body:'Sobald 3 Nachbarn beitreten, wird dein Botschafter-Status freigeschaltet.'}); } catch(e){}
  }

  return (
    <div className="aIn" style={{flex:1, overflowY:'auto', background:T.bg, paddingBottom:80}}>
      {/* Header */}
      <div style={{padding:'14px 18px 10px', display:'flex', alignItems:'center', justifyContent:'space-between'}}>
        <div>
          <div style={{display:'flex', alignItems:'center', gap:8}}>
            <div style={{width:30, height:30, borderRadius:8, background:`linear-gradient(135deg, ${T.green}, #166435)`, display:'flex', alignItems:'center', justifyContent:'center', color:'#fff', fontFamily:'Fraunces, serif', fontWeight:700, fontSize:14}}>b.</div>
            <div>
              <div style={{fontFamily:'Fraunces, serif', fontSize:21, fontWeight:700, letterSpacing:'-.5px', lineHeight:1}}>{(state.me.bezirk||'Dein Bezirk').replace('Graz-','')}</div>
              <div style={{fontSize:10.5, color:T.muted, fontWeight:700, letterSpacing:'.3px', marginTop:1}}>
                {isPioneer ? '🌱 Pionier:in · neu hier' : `${myBezirkPosts.length} aktive Posts`}
              </div>
            </div>
          </div>
        </div>
        {!isPioneer && !cloudOn && (
          <select value={radius} onChange={e=>setRadius(parseInt(e.target.value))} style={{padding:'7px 10px', borderRadius:10, border:`1px solid ${T.bdr}`, fontSize:12, fontWeight:700, background:'#fff', color:T.text, cursor:'pointer'}}>
            <option value={1}>1 km</option><option value={5}>5 km</option><option value={10}>10 km</option><option value={20}>20 km</option>
          </select>
        )}
      </div>

      {/* PIONIER HERO */}
      {isPioneer && (
        <EmptyBezirkHero
          bezirk={myBezirk}
          totalUsers={1}
          onInvite={handleInvite}
          onCompose={onCompose}
        />
      )}

      {/* Tabs (immer sichtbar — auch im Pionier-Modus für volle App-UX) */}
      <div style={{padding:'4px 14px 12px'}}>
        <div style={{
          display:'grid',
          gridTemplateColumns:'repeat(6, 1fr)',
          gap:3,
          background:'rgba(12,12,10,.05)',
          borderRadius:14,
          padding:4,
        }}>
          {TABS.map(tab=>{
            const on = filter===tab.k;
            return (
              <button key={tab.k} onClick={()=>setFilter(tab.k)} style={{
                padding:'7px 4px',
                borderRadius:10,
                border:'none',
                background: on ? '#fff' : 'transparent',
                color: on ? T.green : T.sec,
                fontSize:10.5, fontWeight:700, cursor:'pointer',
                fontFamily:'inherit',
                boxShadow: on ? '0 1px 4px rgba(0,0,0,.10), 0 0 0 1px rgba(0,0,0,.04)' : 'none',
                display:'flex', flexDirection:'column', alignItems:'center', gap:3,
                transition:'all .15s cubic-bezier(.22,1,.36,1)',
                letterSpacing:'.1px',
              }}>
                <div style={{
                  fontSize:14, lineHeight:1,
                  filter: on ? 'none' : 'grayscale(.3) opacity(.7)',
                }}>{tab.i}</div>
                <div style={{whiteSpace:'nowrap'}}>{tab.l}</div>
              </button>
            );
          })}
        </div>
      </div>

      {/* ═══ BEZIRKS-FORUM ═══════════════════════════════════ */}
      {/* Wenn "Fragen" Tab aktiv: zeigt den permanenten Ort-fragt-Header */}
      {filter==='frage' && myBezirk && (() => {
        // Smart fallback: aus dem Bezirks-Namen ableiten, falls locationType fehlt
        const guessType = (b) => {
          if (!b) return 'bezirk';
          if (b.includes('-')) return 'bezirk';       // Wien-Mariahilf, Graz-Geidorf
          // Bekannte österreichische Städte (Hauptliste)
          const cities = ['wien','graz','linz','salzburg','innsbruck','klagenfurt','villach','st. pölten','sankt pölten','wels','steyr','dornbirn','feldkirch','bregenz','wiener neustadt','krems','leoben','kapfenberg','hallein','bruck an der leitha','eisenstadt','baden','mödling','amstetten','lustenau','spittal','kufstein','schwaz','lienz','wörgl','neusiedl am see','mattersburg','oberwart','tulln','korneuburg','melk','traun','leonding','traiskirchen','perchtoldsdorf','knittelfeld','köflach','feldbach','weiz','liezen','bischofshofen','st. johann','zell am see','rust'];
          if (cities.includes(b.toLowerCase())) return 'stadt';
          return 'dorf';
        };
        const myType = state.me.locationType || guessType(myBezirk);
        const typeLabel = myType==='stadt' ? 'STADT' : myType==='dorf' ? 'DORF' : 'BEZIRK';
        return (
        <div style={{margin:'2px 18px 14px'}}>
          <div style={{
            background:`linear-gradient(135deg, ${T.green} 0%, #166435 70%, #0F5C2B 100%)`,
            borderRadius:16, padding:'22px 20px 18px', color:'#fff',
            position:'relative', overflow:'hidden',
            boxShadow:'0 6px 20px rgba(10,74,36,.20)',
          }}>
            {/* Deko */}
            <div style={{position:'absolute', top:-30, right:-30, width:160, height:160, borderRadius:'50%', background:'rgba(255,255,255,.06)'}}></div>
            <div style={{position:'absolute', bottom:-50, left:-40, width:170, height:170, borderRadius:'50%', background:'rgba(255,255,255,.04)'}}></div>

            <div style={{position:'relative', zIndex:1}}>
              <div style={{display:'flex', gap:6, marginBottom:12}}>
                <div style={{display:'inline-flex', alignItems:'center', gap:6, padding:'3px 9px', background:'rgba(255,255,255,.20)', borderRadius:14, fontSize:9.5, fontWeight:800, letterSpacing:'.6px'}}>
                  {typeLabel}
                </div>
                <div style={{display:'inline-flex', alignItems:'center', gap:5, padding:'3px 9px', background:'rgba(255,255,255,.10)', borderRadius:14, fontSize:9.5, fontWeight:700, letterSpacing:'.4px', color:'rgba(255,255,255,.85)'}}>
                  <span style={{width:5, height:5, borderRadius:'50%', background:'#7FE8A8'}}></span>
                  PERMANENTE GRUPPE
                </div>
              </div>

              <div style={{fontFamily:'Fraunces, serif', fontSize:30, fontWeight:700, letterSpacing:'-.8px', lineHeight:1.05, marginBottom:4}}>
                {myBezirk}
              </div>
              <div style={{fontFamily:'Fraunces, serif', fontSize:30, fontWeight:700, letterSpacing:'-.8px', lineHeight:1.05, fontStyle:'italic', color:'rgba(255,255,255,.7)', marginBottom:12}}>
                fragt.
              </div>

              <div style={{fontSize:13.5, color:'rgba(255,255,255,.85)', fontWeight:500, lineHeight:1.5, marginBottom:16, textWrap:'pretty'}}>
                Der digitale Dorfplatz für deinen Ort. Stell Fragen, diskutier mit Nachbarn, hilf bei lokalen Themen — öffentlich, sicher und ohne Werbung.
              </div>

              <div style={{display:'flex', gap:14, fontSize:11.5, fontWeight:700, marginBottom:14, padding:'8px 0', borderTop:'1px solid rgba(255,255,255,.15)', borderBottom:'1px solid rgba(255,255,255,.15)'}}>
                <div><span style={{fontSize:15, fontWeight:800}}>{allPosts.filter(p=>p.type==='frage' && p.bezirk===myBezirk).length}</span> <span style={{color:'rgba(255,255,255,.7)', fontSize:10.5, fontWeight:600}}>Diskussionen</span></div>
                <div style={{width:1, background:'rgba(255,255,255,.2)'}}></div>
                <div><span style={{fontSize:15, fontWeight:800}}>{memberCount != null ? memberCount : 1}</span> <span style={{color:'rgba(255,255,255,.7)', fontSize:10.5, fontWeight:600}}>{memberCount === 1 ? 'Mitglied' : 'Mitglieder'}</span></div>
                <div style={{width:1, background:'rgba(255,255,255,.2)'}}></div>
                <div><span style={{fontSize:15, fontWeight:800}}>∞</span> <span style={{color:'rgba(255,255,255,.7)', fontSize:10.5, fontWeight:600}}>kostenlos</span></div>
              </div>

              <button onClick={onCompose} style={{
                width:'100%', padding:'13px 14px', background:'#fff', color:T.green,
                border:'none', borderRadius:12, fontSize:14, fontWeight:800, cursor:'pointer',
                fontFamily:'inherit', display:'flex', alignItems:'center', justifyContent:'center', gap:8,
                boxShadow:'0 2px 8px rgba(0,0,0,.10)',
              }}>
                <span style={{fontSize:16}}>✦</span> Diskussion starten
              </button>
            </div>
          </div>

          {/* Pinned Hint */}
          <div style={{marginTop:10, padding:'10px 12px', background:T.greenL, border:`1px solid ${T.green}20`, borderRadius:10, fontSize:11.5, color:T.green, fontWeight:600, lineHeight:1.45, display:'flex', gap:8}}>
            <span style={{fontSize:14, flexShrink:0}}>📌</span>
            <span>Sei respektvoll, keine Werbung, kein Spam. <strong>Hier wohnt die Stimme deines Ortes.</strong></span>
          </div>
        </div>
        );
      })()}

      {/* Inspiration aus anderen Bezirken (Pionier-Modus) */}
      {isPioneer && (() => {
        const filteredInspiration = filter==='all'
          ? inspirationPosts
          : inspirationPosts.filter(p => p.type === filter);
        return filteredInspiration.length > 0 ? (
          <div style={{padding:'4px 18px 14px'}}>
            <div style={{display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom:10}}>
              <div style={{fontSize:11, fontWeight:800, letterSpacing:'.4px', color:T.sec}}>SO LÄUFT'S IN ANDEREN BEZIRKEN</div>
            </div>
            <div style={{display:'flex', flexDirection:'column', gap:9}}>
              {filteredInspiration.map(p=>(
                <PostCard key={p.id} item={p} onTap={()=>onSelect(p)}/>
              ))}
            </div>
            <div style={{marginTop:14, padding:'14px 16px', background:'#fff', border:`1.5px dashed ${T.bdr}`, borderRadius:13, textAlign:'center'}}>
              <div style={{fontSize:13, fontWeight:700, color:T.text, marginBottom:4}}>Mach den ersten Post in {myBezirk}</div>
              <div style={{fontSize:11.5, color:T.sec, fontWeight:500, marginBottom:10}}>Frag deine Nachbarn etwas, biete was an, oder teile einen Deal.</div>
              <button onClick={onCompose} style={{padding:'10px 18px', background:T.green, color:'#fff', border:'none', borderRadius:10, fontSize:13, fontWeight:700, cursor:'pointer'}}>+ Ersten Post erstellen</button>
            </div>
          </div>
        ) : (
          <div style={{padding:'24px 18px'}}>
            <Empty icon="🌱" title={`Noch keine ${TABS.find(t=>t.k===filter)?.l || 'Posts'} in deinem Bezirk`} sub="Sei der/die Erste! Tippe + um zu starten." action={<Btn kind="primary" onClick={onCompose}>+ Ersten Post erstellen</Btn>}/>
          </div>
        );
      })()}

      {/* SOS Strip */}
      {!isPioneer && filter==='all' && sosActive.length>0 && (
        <div style={{padding:'4px 18px 10px'}}>
          <div style={{display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom:8}}>
            <div style={{fontSize:11, fontWeight:800, letterSpacing:'.4px', color:T.care}}>🤝 AKTIVE HILFSANFRAGEN</div>
            <a style={{fontSize:11, color:T.muted, fontWeight:700, cursor:'pointer'}} onClick={()=>setFilter('sos')}>Alle {sosCount} →</a>
          </div>
          <div style={{display:'flex', flexDirection:'column', gap:7}}>
            {sosActive.map(p=>(
              <div key={p.id} onClick={()=>onSelect(p)} className="cp" style={{padding:'11px 13px', background:T.careL, border:`1px solid ${T.care}22`, borderRadius:12, display:'flex', gap:11, alignItems:'center', cursor:'pointer'}}>
                <div style={{width:36, height:36, borderRadius:10, background:'#fff', display:'flex', alignItems:'center', justifyContent:'center', fontSize:18, flexShrink:0}}>{p.icon||'🤝'}</div>
                <div style={{flex:1, minWidth:0}}>
                  <div style={{display:'flex', gap:6, alignItems:'center', marginBottom:2}}>
                    <span style={{fontSize:9.5, fontWeight:800, color:T.care, letterSpacing:'.3px'}}>{p.sosCategory||'HILFE'}</span>
                    {p.urgency==='heute' && <span style={{fontSize:9, fontWeight:800, color:'#fff', background:T.care, padding:'1px 5px', borderRadius:4}}>HEUTE</span>}
                  </div>
                  <div style={{fontSize:13, fontWeight:700, color:T.text, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap'}}>{p.title}</div>
                  <div style={{fontSize:11, color:T.sec, fontWeight:500, marginTop:1, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap'}}>{p.distance > 0 ? p.distance+' km · ' : ''}{timeAgo(p.createdAt)}</div>
                </div>
                <div style={{fontSize:18, color:T.care}}>›</div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Hero */}
      {hero && filter==='all' && (
        <div style={{padding:'8px 18px 14px'}}>
          <div onClick={()=>onSelect(hero)} className="cp" style={{position:'relative', borderRadius:18, overflow:'hidden', cursor:'pointer', boxShadow:'0 4px 14px rgba(0,0,0,.06)'}}>
            <div style={{height:200, background:`linear-gradient(135deg, ${hero.gradient[0]}, ${hero.gradient[1]})`, display:'flex', alignItems:'center', justifyContent:'center', fontSize:80}}>{hero.icon}</div>
            <div style={{position:'absolute', top:12, left:12, background:'rgba(255,255,255,.95)', padding:'4px 9px', borderRadius:6, fontSize:10, fontWeight:800, color:T.gold, letterSpacing:'.3px'}}>✦ GESPONSERT</div>
            {hero.savings && <div style={{position:'absolute', top:12, right:12, background:T.amber, color:'#fff', padding:'4px 9px', borderRadius:6, fontSize:11, fontWeight:800}}>-{hero.savings}%</div>}
            <div style={{padding:'14px 16px', background:'#fff'}}>
              <div style={{display:'flex', gap:7, marginBottom:7}}>
                <Badge type={hero.type} sm/>
                <TierBadge tier={hero.ownerTier}/>
              </div>
              <div style={{fontFamily:'Fraunces, serif', fontSize:21, fontWeight:700, letterSpacing:'-.4px', lineHeight:1.15, marginBottom:5}}>{hero.title}</div>
              <div style={{fontSize:12.5, color:T.sec, fontWeight:500, marginBottom:8}}>{hero.sub}</div>
              <div style={{display:'flex', justifyContent:'space-between', alignItems:'center'}}>
                <div style={{fontSize:13, fontWeight:700, color:T.text}}>{hero.owner}{hero.distance > 0 ? ' · '+hero.distance+' km' : ''}</div>
                {hero.price && <div style={{display:'flex', gap:6, alignItems:'baseline'}}><span style={{fontSize:18, fontWeight:800, color:T.amber}}>€ {hero.price}</span>{hero.originalPrice && <span style={{fontSize:12, color:T.muted, textDecoration:'line-through'}}>€ {hero.originalPrice}</span>}</div>}
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Posts list */}
      {!isPioneer && (
      <div style={{padding:'0 18px'}}>
        {filteredByDist.length===0 && (
          <Empty icon="🔍" title="Hier ist's noch ruhig" sub={`Keine Posts in ${radius} km. Erweitere den Radius oder erstelle den ersten Post.`} action={<Btn kind="primary" onClick={onCompose}>Ersten Post erstellen</Btn>}/>
        )}
        <div style={{display:'flex', flexDirection:'column', gap:9}}>
          {(filter==='all' ? others : filteredByDist).filter(p=>p.id!==(hero?.id)).map(p=>(
            <PostCard key={p.id} item={p} onTap={()=>onSelect(p)}/>
          ))}
        </div>
      </div>
      )}
    </div>
  );
}

function PostCard({item, onTap}){
  const rem = useCountdown(item.expiresAt);
  return (
    <div onClick={onTap} className="cp" style={{
      background:'#fff', borderRadius:14, padding:'12px 14px',
      border:`1px solid ${T.bdr}`, display:'flex', gap:12, cursor:'pointer',
      position:'relative',
    }}>
      <div style={{
        width:64, height:64, borderRadius:11, flexShrink:0,
        background:`linear-gradient(135deg, ${item.gradient?.[0]||'#E0E0DD'}, ${item.gradient?.[1]||'#A8A59E'})`,
        display:'flex', alignItems:'center', justifyContent:'center', fontSize:30,
        position:'relative', overflow:'hidden',
      }}>
        {item.icon}
        <StatusOverlay status={item.status}/>
      </div>
      <div style={{flex:1, minWidth:0}}>
        <div style={{display:'flex', gap:5, marginBottom:4, flexWrap:'wrap'}}>
          <Badge type={item.type} sm/>
          {item.savings && <span style={{fontSize:10, fontWeight:800, color:T.amber, background:T.amberL, padding:'1.5px 5px', borderRadius:4}}>-{item.savings}%</span>}
          {item.urgency==='heute' && <span style={{fontSize:10, fontWeight:800, color:'#fff', background:T.care, padding:'1.5px 5px', borderRadius:4}}>HEUTE</span>}
        </div>
        <div style={{fontSize:14, fontWeight:700, color:T.text, lineHeight:1.3, marginBottom:3, overflow:'hidden', display:'-webkit-box', WebkitLineClamp:2, WebkitBoxOrient:'vertical'}}>{item.title}</div>
        <div style={{fontSize:11.5, color:T.sec, fontWeight:500, display:'flex', gap:7, alignItems:'center'}}>
          <span>{item.owner}</span>
          {item.distance > 0 && <><span style={{color:T.muted}}>·</span><span>{item.distance} km</span></>}
          {item.bezirk && !(item.distance > 0) && <><span style={{color:T.muted}}>·</span><span>{(item.bezirk||'').replace(/^Graz-/,'')}</span></>}
          {rem && rem!=='abgelaufen' && (item.type==='deal' || item.type==='sos') && <><span style={{color:T.muted}}>·</span><span style={{color:item.type==='sos'?T.care:T.amber, fontWeight:700}}>{rem}</span></>}
        </div>
      </div>
      {item.price !== undefined && item.price !== null && (item.type==='deal' || item.type==='angebot') && (
        <div style={{display:'flex', flexDirection:'column', alignItems:'flex-end', justifyContent:'center', gap:2}}>
          <div style={{fontSize:15, fontWeight:800, color: item.priceLabel==='Gratis'?T.green:T.text}}>{fmtPrice(item.price, item.priceLabel)}</div>
          {item.originalPrice && <div style={{fontSize:10.5, color:T.muted, textDecoration:'line-through'}}>€ {item.originalPrice}</div>}
        </div>
      )}
    </div>
  );
}

// ───────────────────────────────────────────────────────────────
// DETAIL SCREEN
// ───────────────────────────────────────────────────────────────
function DetailScreen({post, onBack, onChat}){
  const state = window._appState;
  const A = window.AppStore.actions;
  const rem = useCountdown(post.expiresAt);
  const isOwn = post.ownerId === 'me';
  const bookmarked = state.me.bookmarks.includes(post.id);
  const [statusOpen,setStatusOpen] = useState(false);
  const [contacted,setContacted] = useState(false);
  const [reportOpen, setReportOpen] = useState(false);

  useEffect(()=>{ A.incrementView(post.id); },[post.id]);

  const handleContact = ()=>{
    const chatId = A.startChat(post);
    setContacted(true);
    setTimeout(()=>onChat(chatId), 250);
  };

  return (
    <div style={{flex:1, overflowY:'auto', background:T.bg, paddingBottom:24}}>
      {/* Header */}
      <div style={{position:'sticky', top:0, zIndex:10, background:'rgba(246,244,239,.95)', backdropFilter:'blur(10px)', padding:'12px 14px', display:'flex', justifyContent:'space-between', alignItems:'center'}}>
        <button onClick={onBack} style={{width:34, height:34, borderRadius:10, background:'#fff', border:`1px solid ${T.bdr}`, fontSize:16, cursor:'pointer'}}>‹</button>
        <button onClick={()=>A.toggleBookmark(post.id)} style={{width:34, height:34, borderRadius:10, background:'#fff', border:`1px solid ${T.bdr}`, fontSize:14, cursor:'pointer'}}>{bookmarked?'★':'☆'}</button>
      </div>

      {/* Image */}
      <div style={{height:280, background:`linear-gradient(135deg, ${post.gradient?.[0]||'#E0E0DD'}, ${post.gradient?.[1]||'#A8A59E'})`, display:'flex', alignItems:'center', justifyContent:'center', fontSize:120, position:'relative', margin:'0 18px', borderRadius:18, overflow:'hidden'}}>
        {post.icon}
        <StatusOverlay status={post.status}/>
        {post.savings && <div style={{position:'absolute', top:14, right:14, background:T.amber, color:'#fff', padding:'5px 10px', borderRadius:8, fontSize:13, fontWeight:800}}>-{post.savings}%</div>}
      </div>

      {/* Body */}
      <div style={{padding:'18px 20px'}}>
        <div style={{display:'flex', gap:7, marginBottom:9, flexWrap:'wrap'}}>
          <Badge type={post.type}/>
          <TierBadge tier={post.ownerTier}/>
          {post.urgency==='heute' && <span style={{fontSize:10, fontWeight:800, color:'#fff', background:T.care, padding:'3px 8px', borderRadius:6}}>HEUTE</span>}
        </div>
        <div style={{fontFamily:'Fraunces, serif', fontSize:26, fontWeight:700, letterSpacing:'-.6px', lineHeight:1.15, marginBottom:6}}>{post.title}</div>
        <div style={{fontSize:14, color:T.sec, fontWeight:500, marginBottom:14}}>{post.sub}</div>

        {/* Meta row */}
        <div style={{display:'flex', gap:10, marginBottom:18, padding:'10px 0', borderTop:`1px solid ${T.bdr}`, borderBottom:`1px solid ${T.bdr}`, fontSize:12, color:T.sec, fontWeight:600}}>
          <span>📍 {post.distance > 0 ? post.distance + ' km' : (post.bezirk||'').replace(/^Graz-/,'') || 'Dein Ort'}</span>
          <span style={{color:T.muted}}>·</span>
          <span>👁 {post.views||0}</span>
          {rem && rem!=='abgelaufen' && <><span style={{color:T.muted}}>·</span><span style={{color: post.type==='sos'?T.care:T.amber, fontWeight:700}}>⏱ {rem}</span></>}
        </div>

        {/* Price/SOS */}
        {(post.type==='deal' || post.type==='angebot') && (
          <div style={{padding:'14px 16px', background:T.amberL, borderRadius:12, marginBottom:18, display:'flex', justifyContent:'space-between', alignItems:'center'}}>
            <div>
              <div style={{fontSize:11, color:T.amber, fontWeight:800, letterSpacing:'.3px', marginBottom:2}}>{post.savings?'AKTIONSPREIS':'PREIS'}</div>
              <div style={{display:'flex', alignItems:'baseline', gap:8}}>
                <span style={{fontFamily:'Fraunces, serif', fontSize:28, fontWeight:700, color:T.amber, letterSpacing:'-.5px'}}>{fmtPrice(post.price, post.priceLabel)}</span>
                {post.originalPrice && <span style={{fontSize:14, color:T.muted, textDecoration:'line-through'}}>€ {post.originalPrice}</span>}
              </div>
            </div>
            {post.redemptionLimit && <div style={{textAlign:'right'}}><div style={{fontSize:11, color:T.amber, fontWeight:700}}>{post.redemptions||0}/{post.redemptionLimit}</div><div style={{fontSize:10, color:T.sec, fontWeight:600}}>eingelöst</div></div>}
          </div>
        )}

        {post.type==='sos' && (
          <div style={{padding:'14px 16px', background:T.careL, borderRadius:12, marginBottom:18}}>
            <div style={{fontSize:11, color:T.care, fontWeight:800, letterSpacing:'.3px', marginBottom:6}}>HILFE-ANFRAGE</div>
            <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:10, fontSize:12.5}}>
              <div><div style={{color:T.sec, fontWeight:600, fontSize:11}}>Wann</div><div style={{fontWeight:700}}>{post.urgency==='heute'?'Heute':post.urgency==='morgen'?'Morgen':post.urgency} {post.timeFrom}–{post.timeTo}</div></div>
              <div><div style={{color:T.sec, fontWeight:600, fontSize:11}}>Bezahlung</div><div style={{fontWeight:700}}>{post.paymentAmount}</div></div>
            </div>
          </div>
        )}

        {/* Description */}
        <div style={{fontSize:14, color:T.text, lineHeight:1.6, marginBottom:20, fontWeight:500, whiteSpace:'pre-wrap'}}>{post.description}</div>

        {/* Owner */}
        <div style={{padding:'14px 14px', background:'#fff', border:`1px solid ${T.bdr}`, borderRadius:13, display:'flex', alignItems:'center', gap:12, marginBottom:18}}>
          <Avatar a={post.ownerAvatar} src={post.ownerAvatarUrl} size={44} name={post.owner}/>
          <div style={{flex:1, minWidth:0}}>
            <div style={{display:'flex', gap:5, alignItems:'center', flexWrap:'wrap'}}>
              <div style={{fontSize:14, fontWeight:700}}>{post.owner}</div>
              {post.ownerVerified && <span style={{color:T.care, fontSize:13}}>✓</span>}
              <TierBadge tier={post.ownerTier}/>
            </div>
            <div style={{fontSize:11, color:T.sec, fontWeight:600, marginTop:1}}>{post.bezirk} · seit Mai 2024 · ⭐ 4.8 (24)</div>
          </div>
        </div>

        {/* Actions — bei Fragen: KEINE 1-on-1 Nachricht, sondern öffentliche Diskussion */}
        {!isOwn && post.type !== 'frage' && (
          <div style={{display:'flex', flexDirection:'column', gap:9}}>
            <Btn full kind={post.type==='sos'?'care':'primary'} size="lg" onClick={handleContact} disabled={post.status!=='aktiv'}>
              {post.status!=='aktiv'?'Nicht mehr verfügbar': contacted?'✓ Chat geöffnet': post.type==='sos'?'Helfen anbieten':'Nachricht senden'}
            </Btn>
            <Btn full kind="ghost" onClick={()=>setReportOpen(true)}>⚑ Melden</Btn>
          </div>
        )}

        {isOwn && (
          <div style={{padding:'14px 14px', background:T.greenL, borderRadius:13}}>
            <div style={{fontSize:11, color:T.green, fontWeight:800, letterSpacing:'.3px', marginBottom:8}}>DEIN POST</div>
            <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:8, marginBottom:10}}>
              <Btn kind="secondary" size="sm" onClick={()=>setStatusOpen(true)}>Status ändern</Btn>
              <Btn kind="secondary" size="sm" onClick={()=>{ if(confirm('Wirklich löschen?')){ A.deletePost(post.id); onBack(); }}}>Löschen</Btn>
            </div>
            <div style={{fontSize:12, color:T.sec, fontWeight:500}}>👁 {post.views||0} Views · ⭐ {post.bookmarks||0} Bookmarks · 💬 {(post.comments||[]).length} Antworten</div>
          </div>
        )}

        {/* ─── ÖFFENTLICHE DISKUSSION (für ALLE Posts) ─── */}
        <CommentThread post={post} isOwn={isOwn} alwaysOpen={post.type==='frage'}/>
      </div>

      <Sheet open={statusOpen} onClose={()=>setStatusOpen(false)} title="Status ändern">
        <div style={{padding:'4px 22px 32px', display:'flex', flexDirection:'column', gap:8}}>
          {[
            {k:'aktiv', l:'✓ Aktiv', c:T.green},
            {k:'reserviert', l:'⏸ Reserviert', c:T.amber},
            {k: post.type==='sos'?'hilfe-gefunden': post.type==='angebot'?'abgeholt':'erledigt', l:'✓ Erledigt / Abgeschlossen', c:T.green},
            {k:'abgelaufen', l:'× Schließen', c:T.muted},
          ].map(s=>(
            <button key={s.k} onClick={()=>{A.markPostStatus(post.id, s.k); setStatusOpen(false);}} style={{
              padding:'14px 16px', borderRadius:11, border:`1px solid ${T.bdr}`, background: post.status===s.k?T.bg:'#fff',
              fontSize:14, fontWeight:700, color:s.c, cursor:'pointer', textAlign:'left',
            }}>{s.l}</button>
          ))}
        </div>
      </Sheet>

      <ReportSheet
        open={reportOpen}
        onClose={()=>setReportOpen(false)}
        targetType="post"
        targetId={post.id}
        targetTitle={post.title}
      />
    </div>
  );
}

// ───────────────────────────────────────────────────────────────
// COMMENT THREAD — öffentliche Diskussion unter Posts
// (Facebook-Gruppe-Style: alle sehen alle Antworten + nested replies)
// ───────────────────────────────────────────────────────────────
function CommentThread({post, isOwn, alwaysOpen}){
  const state = window._appState;
  const A = window.AppStore.actions;
  const [text, setText] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [loading, setLoading] = useState(false);
  const allComments = post.comments || [];

  // ─── Cloud-Sync: Comments laden + Realtime abonnieren ───
  useEffect(() => {
    if (!window.Cloud) return;
    let cleanup = null;
    setLoading(true);
    (async () => {
      await window.Cloud.loadCommentsForPost(post.id);
      setLoading(false);
      cleanup = window.Cloud.subscribeCommentsForPost(post.id);
    })();
    return () => { if (cleanup) cleanup(); };
  }, [post.id]);

  // Group: top-level + children
  const topLevel = allComments.filter(c => !c.parentId).slice().sort((a,b)=>{
    // Best answer first, then by time
    if (a.bestAnswer && !b.bestAnswer) return -1;
    if (!a.bestAnswer && b.bestAnswer) return 1;
    return a.t - b.t;
  });

  function submit(){
    if (!text.trim()) return;
    setSubmitting(true);
    A.addComment(post.id, text.trim());
    setText('');
    setTimeout(()=>setSubmitting(false), 200);
  }

  const isFrage = post.type === 'frage';
  const hasBest = allComments.some(c => c.bestAnswer);

  return (
    <div style={{marginTop: alwaysOpen?6:24, paddingTop:18, borderTop:`1px solid ${T.bdr}`}}>
      <div style={{display:'flex', alignItems:'baseline', justifyContent:'space-between', marginBottom:14}}>
        <div style={{fontFamily:'Fraunces, serif', fontSize:18, fontWeight:700, letterSpacing:'-.3px'}}>
          {isFrage
            ? (allComments.length===0 ? 'Diskussion starten' : `Antworten · ${allComments.length}`)
            : (allComments.length===0 ? 'Kommentare' : `Kommentare · ${allComments.length}`)
          }
        </div>
        {allComments.length>0 && (
          <div style={{fontSize:11, color:T.muted, fontWeight:700, letterSpacing:'.3px'}}>ÖFFENTLICH</div>
        )}
      </div>

      {/* Composer */}
      <div style={{display:'flex', gap:10, alignItems:'flex-start', marginBottom: allComments.length?18:8}}>
        <Avatar a={state.me.avatar} src={state.me.avatarUrl} size={36} name={state.me.name||'Du'}/>
        <div style={{flex:1, minWidth:0}}>
          <textarea
            value={text}
            onChange={e=>setText(e.target.value)}
            placeholder={isFrage?'Deine Antwort an die Nachbarn…':'Schreib einen Kommentar…'}
            rows={text.length>50?3:2}
            style={{
              width:'100%', padding:'10px 12px', borderRadius:12,
              border:`1.5px solid ${T.bdr}`, background:'#fff',
              fontSize:13.5, fontFamily:'inherit', color:T.text, fontWeight:500,
              resize:'none', outline:'none', lineHeight:1.45,
            }}
          />
          <div style={{display:'flex', justifyContent:'flex-end', marginTop:7}}>
            <button onClick={submit} disabled={!text.trim() || submitting} style={{
              padding:'7px 16px', background: text.trim()?T.green:T.bdrSoft,
              color: text.trim()?'#fff':T.muted, border:'none', borderRadius:9,
              fontSize:12.5, fontWeight:700, cursor: text.trim()?'pointer':'not-allowed',
              fontFamily:'inherit',
            }}>{submitting?'…':'Antworten'}</button>
          </div>
        </div>
      </div>

      {/* Comments list */}
      {topLevel.length===0 ? (
        <div style={{padding:'18px 14px', textAlign:'center', background:T.bg, borderRadius:11, border:`1.5px dashed ${T.bdr}`}}>
          <div style={{fontSize:32, marginBottom:6}}>💭</div>
          <div style={{fontSize:13, fontWeight:700, color:T.text, marginBottom:3}}>Sei der/die Erste</div>
          <div style={{fontSize:12, color:T.sec, fontWeight:500}}>Antworte als erste:r Nachbar:in — andere folgen.</div>
        </div>
      ) : (
        <div style={{display:'flex', flexDirection:'column', gap:18}}>
          {topLevel.map(c => {
            const replies = allComments.filter(r => r.parentId === c.id).slice().sort((a,b)=>a.t-b.t);
            return (
              <CommentItem
                key={c.id}
                comment={c}
                replies={replies}
                postId={post.id}
                postOwnerId={post.ownerId}
                postType={post.type}
                isAuthor={c.authorId===state.me.id || c.authorId==='me'}
                postOwnerIsMe={post.ownerId==='me' || post.ownerId===state.me.id}
                showBestAnswerToggle={isFrage}
              />
            );
          })}
        </div>
      )}
    </div>
  );
}

function CommentItem({comment, replies, postId, postOwnerId, postType, isAuthor, postOwnerIsMe, showBestAnswerToggle, isReply}){
  const state = window._appState;
  const A = window.AppStore.actions;
  const [replyOpen, setReplyOpen] = useState(false);
  const [replyText, setReplyText] = useState('');
  const [reportOpen, setReportOpen] = useState(false);
  const reacted = comment.reactions?.reactedByMe;
  const helpfulCount = comment.reactions?.helpful || 0;
  const isBest = comment.bestAnswer;

  function submitReply(){
    if (!replyText.trim()) return;
    A.addComment(postId, replyText.trim(), comment.id);
    setReplyText('');
    setReplyOpen(false);
  }

  return (
    <div style={{display:'flex', gap:10, alignItems:'flex-start'}}>
      <Avatar a={comment.authorAvatar} src={comment.authorAvatarUrl} size={isReply?28:34} name={comment.authorName}/>
      <div style={{flex:1, minWidth:0}}>
        {/* Bubble */}
        <div style={{
          background: isBest ? T.greenL : '#fff',
          border: isBest ? `1.5px solid ${T.green}` : `1px solid ${T.bdr}`,
          borderRadius:14, padding:'10px 13px',
          position:'relative',
        }}>
          {isBest && (
            <div style={{position:'absolute', top:-9, left:12, padding:'2px 8px', background:T.green, color:'#fff', borderRadius:6, fontSize:9.5, fontWeight:800, letterSpacing:'.4px', display:'inline-flex', alignItems:'center', gap:4}}>
              <span>⭐</span> BESTE ANTWORT
            </div>
          )}
          <div style={{display:'flex', gap:6, alignItems:'baseline', flexWrap:'wrap', marginBottom:3, marginTop: isBest?4:0}}>
            <span style={{fontSize:13, fontWeight:700, color:T.text}}>{comment.authorName}</span>
            {comment.authorVerified && <span style={{color:T.care, fontSize:11}}>✓</span>}
            {comment.authorTier && comment.authorTier!=='buerger' && <TierBadge tier={comment.authorTier}/>}
            {comment.authorId === postOwnerId && (
              <span style={{fontSize:9, fontWeight:800, color:T.green, background:T.greenL, padding:'1px 5px', borderRadius:4, letterSpacing:'.3px'}}>FRAGESTELLER:IN</span>
            )}
          </div>
          <div style={{fontSize:13.5, color:T.text, fontWeight:500, lineHeight:1.5, whiteSpace:'pre-wrap', wordWrap:'break-word'}}>{comment.text}</div>
        </div>

        {/* Actions row */}
        <div style={{display:'flex', gap:14, alignItems:'center', padding:'5px 13px 0', fontSize:11.5, fontWeight:700, flexWrap:'wrap'}}>
          <span style={{color:T.muted}}>{timeAgo(comment.t)}</span>
          <button onClick={()=>A.toggleCommentReaction(postId, comment.id)} style={{
            background:'none', border:'none', cursor:'pointer', padding:0,
            color: reacted?T.green:T.sec, fontWeight:700, fontSize:11.5,
            display:'inline-flex', alignItems:'center', gap:4,
            fontFamily:'inherit',
          }}>
            <span>👍</span> Hilfreich{helpfulCount>0 && ` · ${helpfulCount}`}
          </button>
          {!isReply && (
            <button onClick={()=>setReplyOpen(o=>!o)} style={{
              background:'none', border:'none', cursor:'pointer', padding:0,
              color: replyOpen?T.green:T.sec, fontWeight:700, fontSize:11.5, fontFamily:'inherit',
            }}>↪ Antworten</button>
          )}
          {showBestAnswerToggle && postOwnerIsMe && !isReply && (
            <button onClick={()=>A.markBestAnswer(postId, comment.id)} style={{
              background:'none', border:'none', cursor:'pointer', padding:0,
              color: isBest?T.green:T.amber, fontWeight:700, fontSize:11.5, fontFamily:'inherit',
            }}>{isBest ? '⭐ Beste Antwort' : '⭐ Als beste markieren'}</button>
          )}
          {isAuthor && (
            <button onClick={()=>{ if(confirm('Kommentar löschen?')) A.deleteComment(postId, comment.id); }} style={{
              background:'none', border:'none', cursor:'pointer', padding:0,
              color:T.muted, fontWeight:600, fontSize:11.5, fontFamily:'inherit',
            }}>Löschen</button>
          )}
          {!isAuthor && (
            <button onClick={()=>setReportOpen(true)} style={{
              background:'none', border:'none', cursor:'pointer', padding:0,
              color:T.muted, fontWeight:600, fontSize:11.5, fontFamily:'inherit',
            }}>⚑ Melden</button>
          )}
        </div>

        {/* Reply composer */}
        {replyOpen && (
          <div style={{display:'flex', gap:8, alignItems:'flex-start', marginTop:10, marginLeft:0}}>
            <Avatar a={state.me.avatar} src={state.me.avatarUrl} size={28} name={state.me.name||'Du'}/>
            <div style={{flex:1, minWidth:0}}>
              <textarea
                value={replyText}
                onChange={e=>setReplyText(e.target.value)}
                placeholder={`Antwort an ${comment.authorName}…`}
                rows={2}
                autoFocus
                style={{
                  width:'100%', padding:'8px 11px', borderRadius:10,
                  border:`1.5px solid ${T.bdr}`, background:'#fff',
                  fontSize:13, fontFamily:'inherit', color:T.text, fontWeight:500,
                  resize:'none', outline:'none', lineHeight:1.45,
                }}
              />
              <div style={{display:'flex', justifyContent:'flex-end', gap:8, marginTop:6}}>
                <button onClick={()=>{ setReplyOpen(false); setReplyText(''); }} style={{
                  padding:'5px 12px', background:'transparent', color:T.sec, border:`1px solid ${T.bdr}`,
                  borderRadius:8, fontSize:11.5, fontWeight:700, cursor:'pointer', fontFamily:'inherit',
                }}>Abbrechen</button>
                <button onClick={submitReply} disabled={!replyText.trim()} style={{
                  padding:'5px 14px', background: replyText.trim()?T.green:T.bdrSoft,
                  color: replyText.trim()?'#fff':T.muted, border:'none',
                  borderRadius:8, fontSize:11.5, fontWeight:700, cursor: replyText.trim()?'pointer':'not-allowed',
                  fontFamily:'inherit',
                }}>Antworten</button>
              </div>
            </div>
          </div>
        )}

        {/* Replies (nested, 1 level) */}
        {replies && replies.length > 0 && (
          <div style={{marginTop:14, marginLeft:0, paddingLeft:14, borderLeft:`2px solid ${T.bdr}`, display:'flex', flexDirection:'column', gap:14}}>
            {replies.map(r => (
              <CommentItem
                key={r.id}
                comment={r}
                replies={[]}
                postId={postId}
                postOwnerId={postOwnerId}
                postType={postType}
                isAuthor={r.authorId===state.me.id || r.authorId==='me'}
                postOwnerIsMe={postOwnerIsMe}
                showBestAnswerToggle={false}
                isReply={true}
              />
            ))}
          </div>
        )}
      </div>

      <ReportSheet
        open={reportOpen}
        onClose={()=>setReportOpen(false)}
        targetType="comment"
        targetId={comment.id}
        targetTitle={comment.text}
      />
    </div>
  );
}

Object.assign(window, { OnboardingFlow, FeedScreen, DetailScreen, PostCard, CommentThread, ReportSheet });

// ───────────────────────────────────────────────────────────────
// REPORT SHEET — Inhalte/Kommentare/Profile melden
// ───────────────────────────────────────────────────────────────
function ReportSheet({open, onClose, targetType, targetId, targetTitle}){
  const [reason, setReason] = useState('');
  const [details, setDetails] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [done, setDone] = useState(false);

  useEffect(() => {
    if (!open){
      // Reset state nach kurzer Verzögerung (für Animation)
      const t = setTimeout(() => { setReason(''); setDetails(''); setDone(false); }, 300);
      return () => clearTimeout(t);
    }
  }, [open]);

  if (!open) return null;

  const reasons = [
    { k:'spam',         l:'Spam oder Werbung',           i:'⚡' },
    { k:'beleidigend',  l:'Beleidigend / Hetze',         i:'🚫' },
    { k:'falsch',       l:'Falschmeldung / Betrug',      i:'⚠️' },
    { k:'illegal',      l:'Illegal / Strafbar',          i:'🔒' },
    { k:'sexual',       l:'Sexueller Inhalt',            i:'🔞' },
    { k:'sonstiges',    l:'Sonstiges',                   i:'📝' },
  ];

  async function submit(){
    if (!reason) { alert('Bitte einen Grund auswählen.'); return; }
    setSubmitting(true);
    try {
      const isCloudTarget = typeof targetId === 'string' && targetId.length > 30 && targetId.includes('-');
      if (window.BL?.user && window.BL.client && isCloudTarget){
        const { error } = await window.BL.client.from('reports').insert({
          reporter_id: window.BL.user.id,
          target_type: targetType,
          target_id: targetId,
          reason,
          details: details.trim() || null,
        });
        if (error && error.code !== '23505'){
          // 23505 = unique-Constraint (schon mal gemeldet) — kein Fehler
          throw error;
        }
      }
      setDone(true);
    } catch(e){
      console.error('[report] submit error', e);
      alert('Konnte Meldung nicht senden: ' + (e.message || 'Unbekannt'));
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <div onClick={onClose} style={{position:'fixed', inset:0, background:'rgba(0,0,0,.55)', zIndex:90, display:'flex', alignItems:'flex-end', justifyContent:'center'}}>
      <div onClick={e=>e.stopPropagation()} className="aSheet" style={{
        width:'100%', maxWidth:520, maxHeight:'85vh', overflowY:'auto',
        background:'#fff', borderRadius:'22px 22px 0 0', padding:'22px 22px 28px',
        boxShadow:'0 -20px 60px rgba(0,0,0,.25)',
      }}>
        {done ? (
          <div style={{textAlign:'center', padding:'24px 12px'}}>
            <div style={{fontSize:54, marginBottom:14}}>✓</div>
            <div style={{fontFamily:'Fraunces, serif', fontSize:24, fontWeight:700, letterSpacing:'-.5px', marginBottom:8}}>Meldung gesendet</div>
            <div style={{fontSize:14, color:T.sec, fontWeight:500, lineHeight:1.55, marginBottom:24}}>
              Danke! Wir prüfen die Meldung innerhalb von 48 Stunden. Bei <strong style={{color:T.text}}>3 Meldungen</strong> wird der Inhalt automatisch versteckt, bis wir geprüft haben.
            </div>
            <Btn full kind="primary" onClick={onClose}>Schließen</Btn>
          </div>
        ) : (
          <>
            <div style={{display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:6}}>
              <div style={{fontFamily:'Fraunces, serif', fontSize:22, fontWeight:700, letterSpacing:'-.4px'}}>Inhalt melden</div>
              <button onClick={onClose} style={{background:'none', border:'none', fontSize:20, color:T.muted, cursor:'pointer', padding:0}}>×</button>
            </div>
            <div style={{fontSize:13, color:T.sec, fontWeight:500, marginBottom:18, lineHeight:1.45}}>
              {targetTitle && <>Du meldest: <strong style={{color:T.text}}>„{targetTitle.slice(0,80)}{targetTitle.length>80?'…':''}"</strong><br/></>}
              Wir prüfen jede Meldung. Bei wiederholten Falschmeldungen kann dein Account eingeschränkt werden.
            </div>

            <div style={{fontSize:12, fontWeight:700, color:T.sec, marginBottom:8, letterSpacing:'.2px'}}>GRUND</div>
            <div style={{display:'flex', flexDirection:'column', gap:6, marginBottom:18}}>
              {reasons.map(r => (
                <button key={r.k} onClick={()=>setReason(r.k)} style={{
                  padding:'12px 14px', borderRadius:11, border:`1.5px solid ${reason===r.k?T.red:T.bdr}`,
                  background: reason===r.k?T.redL:'#fff', cursor:'pointer', textAlign:'left',
                  display:'flex', alignItems:'center', gap:10, fontFamily:'inherit',
                  color: reason===r.k?T.red:T.text, fontSize:14, fontWeight:600,
                }}>
                  <span style={{fontSize:18}}>{r.i}</span>
                  <span>{r.l}</span>
                  {reason===r.k && <span style={{marginLeft:'auto', color:T.red, fontWeight:800}}>✓</span>}
                </button>
              ))}
            </div>

            <div style={{fontSize:12, fontWeight:700, color:T.sec, marginBottom:6}}>DETAILS (OPTIONAL)</div>
            <textarea
              value={details}
              onChange={e=>setDetails(e.target.value)}
              placeholder="Was genau ist das Problem?"
              rows={3}
              maxLength={500}
              style={{
                width:'100%', padding:'10px 12px', borderRadius:11,
                border:`1.5px solid ${T.bdr}`, background:'#fff',
                fontSize:13.5, fontFamily:'inherit', color:T.text, fontWeight:500,
                resize:'none', outline:'none', lineHeight:1.45, marginBottom:14,
              }}
            />

            <Btn full kind="primary" size="lg" disabled={!reason || submitting} onClick={submit} style={{background: reason?T.red:T.bdrSoft, color: reason?'#fff':T.muted, borderColor:'transparent'}}>
              {submitting ? 'Meldung wird gesendet…' : 'Meldung absenden'}
            </Btn>
            <div style={{fontSize:11, color:T.muted, fontWeight:600, textAlign:'center', marginTop:10, lineHeight:1.5}}>
              Bei akuten Bedrohungen sofort die Polizei rufen: <strong>133</strong>
            </div>
          </>
        )}
      </div>
    </div>
  );
}