// Shared screens: Meldungen Kanban, Chat, News, Calendar, Wasch, Docs, Settings
const MeldungenKanban = ({onOpen, ctx}) => {
  const [view, setView] = React.useState('kanban');
  const [tickets, setTickets] = React.useState([]);

  React.useEffect(() => {
    Store.getTickets().then(ts => setTickets(ts.length ? ts : TICKETS));
  }, [ctx?.dataTick]);

  const byStatus = Object.keys(STATUS_LABELS).reduce((acc,s)=>{acc[s]=tickets.filter(t=>t.status===s); return acc;},{});

  return (
    <>
      <PageHeader
        eyebrow="§ 03 · Alle Liegenschaften"
        title="Schadens­meldungen"
        sub="12 aktive Tickets · 3 dringend · 1 Notfall · Ø Bearbeitungszeit 3.4 Tage"
        actions={<>
          <div style={{display:'flex', border:'1px solid var(--ink-200)', borderRadius:4, padding:2, background:'#fff'}}>
            <button className={`btn btn-ghost btn-sm ${view==='kanban'?'btn-primary':''}`} onClick={()=>setView('kanban')}>Kanban</button>
            <button className={`btn btn-ghost btn-sm ${view==='list'?'btn-primary':''}`} onClick={()=>setView('list')}>Liste</button>
          </div>
          <Search placeholder="Ticket, Mieter, Adresse..."/>
          <Button leftIcon="filter">Filter</Button>
          <Button variant="primary" leftIcon="plus">Meldung erfassen</Button>
        </>}
      />
      <div className="pagebody">
        {view==='kanban' ? (
          <div className="kanban">
            {Object.entries(STATUS_LABELS).map(([k,v])=>(
              <div key={k} className="kcol">
                <div className="kcol-head">
                  <span className={`badge ${v.tone}`} style={{padding:'1px 7px'}}><span className="d"/>{v.label}</span>
                  <span className="n">{byStatus[k].length}</span>
                </div>
                <div className="kcol-body">
                  {byStatus[k].map(t=>(
                    <div key={t.id} className="ticket" onClick={()=>onOpen&&onOpen(t.id)}>
                      <div className="flex justify-between items-center">
                        <span className="ticket-id">{t.id}</span>
                        <UrgencyBadge u={t.urgency}/>
                      </div>
                      <div className="ticket-title">{t.title}</div>
                      <div className="ticket-meta">
                        <span className="badge badge-outline" style={{padding:'1px 6px'}}><span>{t.category||t.cat||'—'}</span></span>
                      </div>
                      <div className="ticket-foot">
                        <span className="text-xs text-muted">{t.unit||t.mieter||'—'}</span>
                        <span className="text-xs text-muted font-mono">{t.created_at ? new Date(t.created_at).toLocaleDateString('de-CH') : (t.date||'')}</span>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>
        ) : (
          <Card>
            <table className="tbl">
              <thead><tr><th>ID</th><th>Titel</th><th>Kategorie</th><th>Dringlichkeit</th><th>Mieter</th><th>Liegenschaft</th><th>Status</th><th>Gemeldet</th></tr></thead>
              <tbody>
                {tickets.map(t=>(
                  <tr key={t.id} onClick={()=>onOpen&&onOpen(t.id)} style={{cursor:'pointer'}}>
                    <td className="mono text-xs">{t.id}</td>
                    <td style={{fontWeight:500}}>{t.title}</td>
                    <td>{t.category||t.cat||'—'}</td>
                    <td><UrgencyBadge u={t.urgency}/></td>
                    <td className="text-xs">{t.unit||t.mieter||'—'}</td>
                    <td><StatusBadge status={t.status}/></td>
                    <td className="mono text-xs text-muted">{t.created_at ? new Date(t.created_at).toLocaleDateString('de-CH') : (t.date||'')}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </Card>
        )}
      </div>
    </>
  );
};

const LiegenschaftsChat = ({inline, onNav}) => {
  const [active, setActive] = React.useState('L-001');
  const [msg, setMsg] = React.useState('');
  const chats = [
    {id:'L-001', name:'Rämistrasse 42', members:11, last:'Hauswart-Schlüssel reicht völlig.', when:'11:50', unread:0},
    {id:'L-002', name:'Länggass. 78', members:8, last:'@Peter wegen Waschmaschine 3.OG', when:'gestern', unread:2},
    {id:'L-003', name:'Spalenring 134', members:14, last:'Danke für die schnelle Rückmeldung!', when:'gestern', unread:0},
    {id:'L-005', name:'Zürcherstr. 205', members:13, last:'Termin Schimmel 3.OG bestätigt', when:'2 T.', unread:0},
    {id:'DM-AM', name:'Andrea Meier', members:'1:1', last:'Können Sie mir den Mietvertrag zusenden?', when:'3 T.', unread:1, dm:true},
  ];

  const content = (
    <div className="chat" style={inline?{height:'640px', marginTop:0}:undefined}>
      <div className="chat-list">
        <div style={{padding:14, borderBottom:'1px solid var(--ink-200)'}}>
          <div className="text-xs text-muted font-mono mb-8">ALLE CHATS</div>
          <Search placeholder="Chat durchsuchen..."/>
        </div>
        {chats.map(c=>(
          <div key={c.id} className={`chat-list-item ${c.id===active?'is-active':''}`} onClick={()=>setActive(c.id)}>
            <div className="flex justify-between items-center">
              <div className="flex gap-8 items-center">
                {c.dm?<Avatar initials="AM" tone="gold"/>:<Avatar initials={c.name.slice(0,2)} tone="ink"/>}
                <div>
                  <div style={{fontSize:13, fontWeight:500}}>{c.name}</div>
                  <div className="text-xs text-muted">{c.dm?'Direktnachricht':`${c.members} Teilnehmer`}</div>
                </div>
              </div>
              <div style={{textAlign:'right'}}>
                <div className="text-xs text-muted font-mono">{c.when}</div>
                {c.unread>0 && <div style={{background:'var(--ch-red)', color:'#fff', borderRadius:9, padding:'1px 7px', fontSize:10, marginTop:4, display:'inline-block'}}>{c.unread}</div>}
              </div>
            </div>
            <div className="text-xs text-muted mt-8" style={{overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap'}}>{c.last}</div>
          </div>
        ))}
      </div>

      <div className="chat-main">
        <div className="chat-head">
          <div>
            <div style={{fontSize:14, fontWeight:600, letterSpacing:'-0.01em'}}>Rämistrasse 42 · Liegenschafts-Chat</div>
            <div className="text-xs text-muted mt-4">11 Teilnehmer · 9 online · Moderiert durch Verwaltung</div>
          </div>
          <div className="flex gap-8">
            <Button size="sm" leftIcon="pin">Angepinnt (2)</Button>
            <Button size="sm" variant="ghost"><Icon name="settings" size={14}/></Button>
          </div>
        </div>
        <div className="chat-msgs">
          <div className="pin">
            <b>Angepinnt · Peter (Hauswart)</b> · Notfall­nummer ausserhalb Bürozeiten: 044 999 88 77. Bei Wasser­schäden immer zuerst Hauptventil UG zudrehen.
          </div>
          {CHAT_MESSAGES.map(m=>(
            <div key={m.id} className={`msg ${m.me?'me':''}`}>
              <Avatar initials={m.initials} tone={m.role==='Hauswart'?'green':m.role.includes('Sach')?'red':'gold'} size="lg"/>
              <div>
                {!m.me && <div className="msg-name">{m.from} · <span style={{color:'var(--ink-400)'}}>{m.role}</span></div>}
                <div className="msg-bubble">{m.text}</div>
                <div className="msg-time">{m.time} {m.me && '· gelesen von 8'}</div>
              </div>
            </div>
          ))}
        </div>
        <div className="chat-input">
          <Icon name="paperclip" className="text-muted"/>
          <input placeholder="Nachricht an Rämistrasse 42..." value={msg} onChange={e=>setMsg(e.target.value)}/>
          <Button size="sm"><Icon name="image" size={14}/></Button>
          <Button variant="primary" size="sm" rightIcon="send">Senden</Button>
        </div>
      </div>

      <div className="chat-side">
        <div className="page-eyebrow mb-12">TEILNEHMER · 11</div>
        <div className="v-stack gap-8">
          <div className="flex items-center gap-8"><Avatar initials="LK" tone="red"/> <div><div style={{fontSize:12.5, fontWeight:500}}>Laura Keller</div><div className="text-xs text-muted">Verwaltung</div></div></div>
          <div className="flex items-center gap-8"><Avatar initials="PA" tone="green"/> <div><div style={{fontSize:12.5, fontWeight:500}}>Peter Aeschlimann</div><div className="text-xs text-muted">Hauswart</div></div></div>
          {['AM','RH','SF','MG','JS','FW','BL'].map((ini,i)=>(
            <div key={i} className="flex items-center gap-8"><Avatar initials={ini}/> <div><div style={{fontSize:12.5}}>{['Andrea Meier','Reto Huber','Sandra Frei','Marco Gasser','Johannes Stucki','Flavio Widmer','Beatrice Lehmann'][i]}</div><div className="text-xs text-muted">Mieter</div></div></div>
          ))}
        </div>
        <div className="hairline"/>
        <div className="page-eyebrow mb-12">DATEIEN & FOTOS</div>
        <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:6}}>
          {[1,2,3,4].map(i=><div key={i} className="stripe" style={{aspectRatio:'1', borderRadius:3}}>IMG</div>)}
        </div>
      </div>
    </div>
  );

  if (inline) return content;

  return (
    <>
      <PageHeader
        eyebrow="§ 04 · Kommunikation"
        title="Liegenschafts-Chat"
        sub="Ein Chat pro Liegenschaft · moderiert · Direktnachrichten verfügbar"
      />
      <div style={{padding:'0 32px 24px'}}>{content}</div>
    </>
  );
};

const NEWS_TONE = {urgent:'crit', event:'warn', info:'neutral'};
const NEWS_LABEL = {urgent:'DRINGEND', event:'TERMIN', info:'INFO'};

const SchwarzesBrett = ({standalone, propId, ctx}) => {
  const [posts, setPosts] = React.useState([]);
  const [showForm, setShowForm] = React.useState(false);
  const [form, setForm] = React.useState({title:'', body:'', type:'info', pinned:false});
  const [saving, setSaving] = React.useState(false);

  const load = () => Store.getNews(propId||null).then(ps => setPosts(ps.length ? ps : NEWS));
  React.useEffect(() => { load(); }, [propId, ctx?.dataTick]);

  const submit = async () => {
    if (!form.title || saving) return;
    setSaving(true);
    try {
      const n = await Store.createNews({...form, pinned: form.pinned?1:0, propId: propId||null});
      setPosts(prev => [n, ...prev.filter(p => p.id)]);
      setShowForm(false); setForm({title:'', body:'', type:'info', pinned:false});
    } catch(e) { alert(e.message); }
    setSaving(false);
  };

  const del = async (id) => {
    if (!id || typeof id === 'number') return; // don't delete mock
    if (!confirm('Post löschen?')) return;
    await Store.deleteNews(id);
    setPosts(prev => prev.filter(p => p.id !== id));
  };

  const content = (
    <div className="grid-dash">
      <div className="v-stack gap-0">
        {showForm && (
          <div style={{background:'#fff',border:'1px solid var(--ink-200)',borderRadius:6,padding:20,marginBottom:16}}>
            <h3 style={{fontSize:15,fontWeight:600,margin:'0 0 16px'}}>Neuer Post</h3>
            <div className="v-stack gap-10">
              <div className="flex gap-8 mb-4">
                {['info','event','urgent'].map(t=>(
                  <button key={t} onClick={()=>setForm(f=>({...f,type:t}))} style={{
                    flex:1,padding:'8px 12px',borderRadius:4,fontSize:12,fontWeight:500,cursor:'pointer',
                    border:'1px solid '+(form.type===t?'var(--ink-900)':'var(--ink-200)'),
                    background:form.type===t?'var(--ink-900)':'#fff',
                    color:form.type===t?'#fff':'var(--ink-700)'
                  }}>{NEWS_LABEL[t]}</button>
                ))}
              </div>
              <div className="field"><label>Titel *</label><input type="text" value={form.title} onChange={e=>setForm(f=>({...f,title:e.target.value}))} placeholder="Betreff des Posts" autoFocus/></div>
              <div className="field"><label>Text</label><textarea value={form.body} onChange={e=>setForm(f=>({...f,body:e.target.value}))} placeholder="Inhalt der Mitteilung…" style={{width:'100%',minHeight:80,padding:'8px 10px',border:'1px solid var(--ink-200)',borderRadius:4,fontSize:13,resize:'vertical'}}/></div>
              <label style={{fontSize:13,display:'flex',alignItems:'center',gap:8,cursor:'pointer'}}>
                <input type="checkbox" checked={form.pinned} onChange={e=>setForm(f=>({...f,pinned:e.target.checked}))}/> Angepinnt (immer oben)
              </label>
              <div className="flex gap-8 mt-4">
                <button className="btn btn-ghost" onClick={()=>setShowForm(false)}>Abbrechen</button>
                <button className="btn btn-primary btn-full" onClick={submit} disabled={!form.title||saving}>{saving?'Wird publiziert…':'Publizieren'}</button>
              </div>
            </div>
          </div>
        )}
        {posts.length === 0 && !showForm && (
          <div style={{padding:'40px 0',textAlign:'center',color:'var(--ink-400)',fontSize:13}}>Noch keine Posts vorhanden.</div>
        )}
        {posts.map((n,i)=>(
          <div key={n.id||i} className={`news-item ${n.type||'info'}`}>
            <div className="news-head">
              <div>
                <div className="flex gap-8 items-center">
                  <Badge tone={NEWS_TONE[n.type]||'neutral'} dot={false}>{NEWS_LABEL[n.type]||'INFO'}</Badge>
                  {n.pinned>0 && <Badge dot={false} tone="info">Angepinnt</Badge>}
                </div>
                <div className="news-title mt-8">{n.title}</div>
              </div>
              <div style={{display:'flex',alignItems:'center',gap:8}}>
                <span className="news-meta">{n.created_at ? new Date(n.created_at).toLocaleDateString('de-CH') : (n.date||'')}</span>
                {n.id && typeof n.id === 'string' && <button className="btn btn-ghost btn-sm" onClick={()=>del(n.id)}><Icon name="x" size={13}/></button>}
              </div>
            </div>
            {n.body && <div className="news-body">{n.body}</div>}
            <div className="news-read-by">
              <span style={{fontSize:12,color:'var(--ink-500)'}}>{n.author_name || n.author || '—'}</span>
            </div>
          </div>
        ))}
      </div>
      <div className="v-stack gap-16">
        <Card title="Neuer Post">
          <div className="v-stack gap-8">
            <Button leftIcon="alert" style={{justifyContent:'flex-start'}} onClick={()=>{setForm(f=>({...f,type:'urgent'}));setShowForm(true);}}>Dringend / Wichtig</Button>
            <Button leftIcon="calendar" style={{justifyContent:'flex-start'}} onClick={()=>{setForm(f=>({...f,type:'event'}));setShowForm(true);}}>Termin / Event</Button>
            <Button leftIcon="pin" style={{justifyContent:'flex-start'}} onClick={()=>{setForm(f=>({...f,type:'info'}));setShowForm(true);}}>Allgemeine Info</Button>
          </div>
        </Card>
      </div>
    </div>
  );

  if (standalone) return (
    <>
      <PageHeader eyebrow="§ 05 · Kommunikation" title="Schwarzes Brett" sub="Digitales News-Board · mit Lese­bestätigung"
        actions={<Button variant="primary" leftIcon="plus" onClick={()=>setShowForm(true)}>Neuer Post</Button>}/>
      <div className="pagebody">{content}</div>
    </>
  );
  return content;
};

const KalenderView = () => {
  // April 2026: April 1 is Wednesday, 30 days
  // 0=Mo ... 6=So
  const firstDow = 2; // Wed
  const daysInMonth = 30;
  const cells = [];
  for (let i=0; i<firstDow; i++) cells.push({out:true, n: 31-firstDow+i+1});
  for (let i=1; i<=daysInMonth; i++) cells.push({out:false, n:i});
  while (cells.length % 7 !== 0) cells.push({out:true, n: cells.length-daysInMonth-firstDow+1});
  while (cells.length < 35) cells.push({out:true, n: cells.length-daysInMonth-firstDow+1});

  return (
    <>
      <PageHeader
        eyebrow="§ 06 · Planung"
        title="Kalender · April 2026"
        sub="Besichtigungen, Wartungen, Handwerker­termine – alle Liegenschaften"
        actions={<>
          <div style={{display:'flex', border:'1px solid var(--ink-200)', borderRadius:4, padding:2, background:'#fff'}}>
            <button className="btn btn-ghost btn-sm">Monat</button>
            <button className="btn btn-ghost btn-sm">Woche</button>
            <button className="btn btn-ghost btn-sm">Liste</button>
          </div>
          <Button leftIcon="chevron-left" variant="ghost"/>
          <Button size="sm">Heute</Button>
          <Button rightIcon="chevron-right" variant="ghost"/>
          <Button variant="primary" leftIcon="plus">Termin</Button>
        </>}
      />
      <div className="pagebody">
        <div className="grid-dash">
          <div className="cal">
            <div className="cal-head">
              {['Mo','Di','Mi','Do','Fr','Sa','So'].map(d=><div key={d}>{d}</div>)}
            </div>
            <div className="cal-grid">
              {cells.map((c,i)=>{
                const evs = !c.out ? EVENTS.filter(e=>e.day===c.n) : [];
                return (
                  <div key={i} className={`cal-cell ${c.out?'out':''} ${c.n===22 && !c.out?'today':''}`}>
                    <span className="day-num">{c.n}</span>
                    {evs.map(e=>(
                      <div key={e.id} className={`cal-ev ${e.type==='red'?'red':e.type==='gold'?'gold':e.type==='green'?'green':''}`}>
                        <div className="font-mono" style={{fontSize:9,opacity:0.8}}>{e.time}</div>
                        <div>{e.title}</div>
                      </div>
                    ))}
                  </div>
                );
              })}
            </div>
          </div>

          <div className="v-stack gap-16">
            <Card title="Nächste 7 Tage">
              <div className="v-stack gap-12">
                {EVENTS.slice(0,5).map(e=>(
                  <div key={e.id} className="flex gap-12" style={{padding:'10px 0', borderBottom:'1px solid var(--ink-150)'}}>
                    <div style={{width:42, textAlign:'center', padding:'6px 0', background:'var(--paper)', borderRadius:4, border:'1px solid var(--ink-150)'}}>
                      <div className="text-xs font-mono text-muted">APR</div>
                      <div style={{fontSize:14, fontWeight:500}}>{e.day.toString().padStart(2,'0')}</div>
                    </div>
                    <div className="flex-1">
                      <div style={{fontSize:12.5, fontWeight:500}}>{e.title}</div>
                      <div className="text-xs text-muted mt-4">{e.time} Uhr · Rämistrasse 42</div>
                    </div>
                  </div>
                ))}
              </div>
            </Card>
            <Card title="Legende">
              <div className="v-stack gap-8 text-xs">
                <div className="flex items-center gap-8"><span style={{width:10,height:10,background:'var(--ch-red)',borderRadius:2}}/> Dringend / Unterbruch</div>
                <div className="flex items-center gap-8"><span style={{width:10,height:10,background:'var(--gold)',borderRadius:2}}/> Wartung / Service</div>
                <div className="flex items-center gap-8"><span style={{width:10,height:10,background:'var(--ok)',borderRadius:2}}/> Hausbesprechung</div>
                <div className="flex items-center gap-8"><span style={{width:10,height:10,background:'var(--ink-700)',borderRadius:2}}/> Besichtigung / Handwerker</div>
              </div>
            </Card>
          </div>
        </div>
      </div>
    </>
  );
};

const WaschkueheView = () => {
  const [data, setData] = React.useState(WASCH_DATA);
  const toggle = (d, s) => {
    const x = [...data.map(r=>[...r])];
    if (x[d][s] === null) x[d][s] = 'mine';
    else if (x[d][s] === 'mine') x[d][s] = null;
    setData(x);
  };
  const mineCount = data.flat().filter(v=>v==='mine').length;

  return (
    <>
      <PageHeader
        eyebrow="§ 07 · Rämistrasse 42"
        title="Waschküche · KW 17"
        sub={`2 Waschmaschinen · 1 Tumbler · Max. 3 Slots pro Woche · Sie haben ${mineCount} Slots reserviert`}
        actions={<>
          <Button leftIcon="chevron-left" variant="ghost"/>
          <Button>Diese Woche</Button>
          <Button rightIcon="chevron-right" variant="ghost"/>
        </>}
      />
      <div className="pagebody">
        <div className="grid-dash">
          <div>
            <div className="wk-grid">
              <div className="wk-h"></div>
              {WASCH_DAYS.map(d=><div key={d} className="wk-h">{d}</div>)}
              {WASCH_SLOTS.map((slot, sIdx)=>(
                <React.Fragment key={slot}>
                  <div className="wk-t">{slot}</div>
                  {WASCH_DAYS.map((_, dIdx)=>{
                    const v = data[dIdx][sIdx];
                    const free = v===null;
                    const mine = v==='mine';
                    const service = v==='service';
                    return (
                      <div key={dIdx}
                        className={`wk-slot ${free?'free':''} ${mine?'mine':''} ${!free && !mine?'taken':''}`}
                        onClick={()=>free || mine ? toggle(dIdx,sIdx) : null}>
                        {free && <><div style={{fontWeight:500, color:'var(--ok-ink)'}}>FREI</div><div className="tag" style={{color:'var(--ok-ink)'}}>buchen</div></>}
                        {mine && <><div style={{fontWeight:600}}>MEIN SLOT</div><div className="tag">bestätigt</div></>}
                        {service && <><div style={{fontWeight:500}}>Service</div><div className="who">gesperrt</div></>}
                        {!free && !mine && !service && <><div style={{fontWeight:500}}>Belegt</div><div className="who">{v}</div></>}
                      </div>
                    );
                  })}
                </React.Fragment>
              ))}
            </div>
          </div>

          <div className="v-stack gap-16">
            <Card title="Ihre Buchungen">
              <div className="v-stack gap-8">
                {data.flatMap((row,d)=>row.map((v,s)=>v==='mine'?{d,s}:null)).filter(Boolean).map(b=>(
                  <div key={`${b.d}-${b.s}`} className="flex justify-between items-center" style={{padding:'10px 0', borderBottom:'1px solid var(--ink-150)'}}>
                    <div>
                      <div style={{fontSize:13, fontWeight:500}}>{WASCH_DAYS[b.d]} · {WASCH_SLOTS[b.s]} Uhr</div>
                      <div className="text-xs text-muted mt-4">Maschine A · 4 Std. 45 Min.</div>
                    </div>
                    <Button size="sm" variant="ghost" onClick={()=>toggle(b.d,b.s)}>Stornieren</Button>
                  </div>
                ))}
              </div>
            </Card>
            <Card title="Regeln">
              <div className="v-stack gap-8 text-xs" style={{lineHeight:1.55}}>
                <div>⋅ Max. <b>3 Slots pro Woche</b> pro Mietpartei</div>
                <div>⋅ Stornierung bis <b>2 Stunden vorher</b> möglich</div>
                <div>⋅ Nicht genutzte Slots nach 30 Min. freigegeben</div>
                <div>⋅ Reinigung: Mieter nach jedem Slot</div>
                <div>⋅ Service­slots durch Hauswart gesperrt</div>
              </div>
            </Card>
          </div>
        </div>
      </div>
    </>
  );
};

const DokumenteView = ({scope, propId, ctx}) => {
  const [docs, setDocs] = React.useState([]);
  const [showForm, setShowForm] = React.useState(false);
  const [form, setForm] = React.useState({name:'', kind:'Mietvertrag', url:'', unit_label:''});
  const [saving, setSaving] = React.useState(false);

  const KINDS = ['Mietvertrag','Nebenkostenabrechnungen','Protokoll','Hausordnung','Versicherung','Reglement','Pläne','Sonstiges'];

  const load = () => Store.getDocuments(propId||null).then(ds => setDocs(ds.length ? ds : DOCS));
  React.useEffect(() => { load(); }, [propId, ctx?.dataTick]);

  const submit = async () => {
    if (!form.name || saving) return;
    setSaving(true);
    try {
      const d = await Store.createDocument({...form, propId: propId||null});
      setDocs(prev => [d, ...prev]);
      setShowForm(false); setForm({name:'', kind:'Mietvertrag', url:'', unit_label:''});
    } catch(e) { alert(e.message); }
    setSaving(false);
  };

  const del = async (id) => {
    if (!id || typeof id === 'number') return;
    if (!confirm('Dokument löschen?')) return;
    await Store.deleteDocument(id);
    setDocs(prev => prev.filter(d => d.id !== id));
  };

  const content = (
    <div className="grid-dash">
      <div>
        {showForm && (
          <div style={{background:'#fff',border:'1px solid var(--ink-200)',borderRadius:6,padding:20,marginBottom:16}}>
            <h3 style={{fontSize:15,fontWeight:600,margin:'0 0 16px'}}>Dokument erfassen</h3>
            <div className="v-stack gap-10">
              <div className="field-row">
                <div className="field"><label>Name *</label><input type="text" value={form.name} onChange={e=>setForm(f=>({...f,name:e.target.value}))} placeholder="z.B. Mietvertrag Meyer 2024" autoFocus/></div>
                <div className="field"><label>Art</label>
                  <select value={form.kind} onChange={e=>setForm(f=>({...f,kind:e.target.value}))} style={{width:'100%',padding:'8px 10px',border:'1px solid var(--ink-200)',borderRadius:4,fontSize:13,background:'#fff'}}>
                    {KINDS.map(k=><option key={k} value={k}>{k}</option>)}
                  </select>
                </div>
              </div>
              <div className="field"><label>Einheit / Bezug</label><input type="text" value={form.unit_label} onChange={e=>setForm(f=>({...f,unit_label:e.target.value}))} placeholder="z.B. WE-12 · 2.OG links"/></div>
              <div className="field"><label>URL / Link</label><input type="url" value={form.url} onChange={e=>setForm(f=>({...f,url:e.target.value}))} placeholder="https://..."/></div>
              <div className="flex gap-8 mt-4">
                <button className="btn btn-ghost" onClick={()=>setShowForm(false)}>Abbrechen</button>
                <button className="btn btn-primary btn-full" onClick={submit} disabled={!form.name||saving}>{saving?'Wird gespeichert…':'Speichern'}</button>
              </div>
            </div>
          </div>
        )}
        <div className="doc-list">
          <div className="doc-row head"><span/><span>Name</span><span>Art</span><span>Bezug</span><span>Datum</span><span/></div>
          {docs.length === 0 && !showForm && (
            <div style={{padding:'40px 0',textAlign:'center',color:'var(--ink-400)',fontSize:13}}>Noch keine Dokumente vorhanden.</div>
          )}
          {docs.map((d,i)=>(
            <div key={d.id||i} className="doc-row">
              <span className="doc-icon pdf">PDF</span>
              <div>
                <div style={{fontSize:13, fontWeight:500}}>
                  {d.url ? <a href={d.url} target="_blank" rel="noopener noreferrer" style={{color:'inherit',textDecoration:'underline',textUnderlineOffset:3}}>{d.name}</a> : d.name}
                </div>
                <div className="text-xs text-muted mt-4">{d.uploaded_by_name ? `Hochgeladen von ${d.uploaded_by_name}` : 'Verwaltung'}</div>
              </div>
              <span><Badge tone="neutral" dot={false}>{d.kind||'Dokument'}</Badge></span>
              <span className="text-xs text-muted">{d.unit_label||d.unit||'—'}</span>
              <span className="text-xs font-mono text-muted">{d.created_at ? new Date(d.created_at).toLocaleDateString('de-CH') : (d.date||'')}</span>
              <span className="text-right">
                {d.id && typeof d.id === 'string' && <button className="btn btn-ghost btn-sm" onClick={()=>del(d.id)}><Icon name="x" size={13}/></button>}
              </span>
            </div>
          ))}
        </div>
      </div>
      <div className="v-stack gap-16">
        <Card title="Dokument erfassen">
          <div className="v-stack gap-8">
            <div style={{color:'var(--ink-500)',fontSize:12.5,lineHeight:1.5}}>Hinterlegen Sie Links zu Dokumenten in Ihrer Cloud-Ablage (OneDrive, Google Drive, Dropbox, etc.).</div>
            <Button leftIcon="plus" onClick={()=>setShowForm(true)}>Dokument hinzufügen</Button>
          </div>
        </Card>
        <Card title="Kategorien">
          <div className="v-stack gap-4">
            {KINDS.slice(0,6).map(k=>(
              <div key={k} className="flex justify-between" style={{padding:'6px 0',fontSize:13}}>
                <span>{k}</span>
                <span className="font-mono text-muted">{docs.filter(d=>(d.kind||'Sonstiges')===k).length}</span>
              </div>
            ))}
          </div>
        </Card>
      </div>
    </div>
  );

  if (scope) return content;

  return (
    <>
      <PageHeader eyebrow="§ 08 · Ablage" title="Dokumenten­verwaltung" sub={`${docs.length} Dokumente · strukturiert nach Liegenschaft und Wohneinheit`}
        actions={<Button variant="primary" leftIcon="plus" onClick={()=>setShowForm(true)}>Dokument hinzufügen</Button>}/>
      <div className="pagebody">{content}</div>
    </>
  );
};

Object.assign(window, {MeldungenKanban, LiegenschaftsChat, SchwarzesBrett, KalenderView, WaschkueheView, DokumenteView});
