// Hauswart screens
const HauswartDashboard = ({onNav, ctx}) => {
  const [tasks, setTasks] = React.useState(HAUSWART_TASKS);
  const [tickets, setTickets] = React.useState([]);
  const toggle = (id) => setTasks(tasks.map(t=>t.id===id?{...t, done:!t.done}:t));

  const firstName = ctx?.session?.name?.split(' ')[0] || 'Hauswart';
  const now = new Date();
  const dateStr = now.toLocaleDateString('de-CH', {weekday:'long', day:'numeric', month:'long'});

  React.useEffect(() => {
    Store.getTickets().then(ts => setTickets(ts.filter(t => t.status !== 'erledigt')));
  }, [ctx?.dataTick]);

  return (
    <>
      <PageHeader
        eyebrow={`§ Hauswart · ${dateStr}`}
        title={`Guten Tag, ${firstName}`}
        sub={`${tasks.filter(t=>t.due==='Heute').length} Aufgaben heute · ${tickets.length} offene Meldungen`}
        actions={<Button variant="primary" leftIcon="camera">Aufgabe mit Foto melden</Button>}
      />
      <div className="pagebody">
        <div className="kpi-grid">
          <KPI label="Heute" value={String(tasks.filter(t=>t.due==='Heute').length)} unit="Aufg." delta={`${tasks.filter(t=>t.due==='Heute'&&t.done).length} erledigt`} deltaDir="up"/>
          <KPI label="Offene Meldungen" value={String(tickets.length)} delta={tickets.filter(t=>t.urgency==='dringend').length + ' dringend'}/>
          <KPI label="Diese Woche" value={String(tasks.length)} unit="Aufg."/>
        </div>

        <div className="grid-dash mt-16">
          <div className="v-stack gap-16">
            <Card title="Heute · Aufgabenliste" action={<Button size="sm" leftIcon="calendar">Woche</Button>}>
              <div className="v-stack gap-4">
                {tasks.filter(t=>t.due==='Heute').map(t=>(
                  <div key={t.id} style={{display:'flex', alignItems:'center', gap:14, padding:'12px 4px', borderBottom:'1px solid var(--ink-150)'}}>
                    <button onClick={()=>toggle(t.id)} style={{
                      width:22, height:22, borderRadius:4, border:'1.5px solid '+(t.done?'var(--ok)':'var(--ink-300)'),
                      background:t.done?'var(--ok)':'transparent', color:'#fff', cursor:'pointer',
                      display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0
                    }}>
                      {t.done && <Icon name="check" size={14} stroke={2.5}/>}
                    </button>
                    <div className="flex-1">
                      <div style={{fontSize:13.5, fontWeight:500, textDecoration:t.done?'line-through':'none', color:t.done?'var(--ink-400)':'var(--ink-900)'}}>{t.title}</div>
                      <div className="text-xs text-muted mt-4 flex gap-8">
                        <span>{t.type}</span><span>·</span><span className="font-mono">{t.prop}</span>
                        {t.ticket && <><span>·</span><span className="font-mono text-muted">{t.ticket}</span></>}
                      </div>
                    </div>
                    {!t.done && <Button size="sm" leftIcon="camera">Foto</Button>}
                  </div>
                ))}
              </div>
              {tasks.filter(t=>t.due!=='Heute').length > 0 && <>
                <div className="hairline"/>
                <div className="page-eyebrow mb-12">DIESE WOCHE</div>
                <div className="v-stack gap-4">
                  {tasks.filter(t=>t.due!=='Heute').map(t=>(
                    <div key={t.id} style={{display:'flex', alignItems:'center', gap:14, padding:'10px 4px'}}>
                      <div style={{width:22, height:22, borderRadius:4, border:'1.5px solid var(--ink-300)', flexShrink:0}}/>
                      <div className="flex-1">
                        <div style={{fontSize:13}}>{t.title}</div>
                        <div className="text-xs text-muted mt-4"><span className="font-mono">{t.prop}</span> · {t.type}</div>
                      </div>
                      <div className="text-xs text-muted font-mono">{t.due}</div>
                    </div>
                  ))}
                </div>
              </>}
            </Card>

            <Card title="Zugewiesene Meldungen" action={<Badge tone={tickets.length?'crit':'ok'}>{tickets.length}</Badge>}>
              {tickets.length === 0 ? (
                <div style={{padding:'20px 0', textAlign:'center', color:'var(--ink-400)', fontSize:13}}>Keine offenen Meldungen.</div>
              ) : (
                <table className="tbl">
                  <tbody>
                    {tickets.map(t=>(
                      <tr key={t.id}>
                        <td style={{width:90}}><span className="mono text-xs">{t.id}</span></td>
                        <td>
                          <div style={{fontWeight:500}}>{t.title}</div>
                          <div className="text-xs text-muted mt-4">{t.unit||'—'} · {t.category}</div>
                        </td>
                        <td><UrgencyBadge u={t.urgency}/></td>
                        <td><Badge tone={STATUS_LABELS[t.status]?.tone?.replace('badge-','')||'neutral'} dot={false}>{STATUS_LABELS[t.status]?.label||t.status}</Badge></td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              )}
            </Card>
          </div>

          <div className="v-stack gap-16">
            <Card title="Reinigungsplan · diese Woche">
              <div className="v-stack gap-8">
                {[
                  {d:'Mo',l:'Treppenhaus',w:'EG–2.OG',s:'done'},
                  {d:'Di',l:'Waschküche',w:'Reinigung + Service',s:'open'},
                  {d:'Mi',l:'Aussen­bereich',w:'Garten & Wege',s:'open'},
                  {d:'Do',l:'Treppenhaus',w:'3.OG–DG',s:'open'},
                  {d:'Fr',l:'Container',w:'Abfall & Recycling',s:'open'},
                ].map((r,i)=>(
                  <div key={i} className="flex gap-12" style={{padding:'8px 0', borderBottom:i<4?'1px solid var(--ink-150)':'none'}}>
                    <div style={{width:28, height:28, borderRadius:4, background:r.s==='done'?'var(--ok)':'var(--ink-100)', color:r.s==='done'?'#fff':'var(--ink-700)', display:'flex', alignItems:'center', justifyContent:'center', fontSize:11, fontWeight:600}}>{r.d}</div>
                    <div className="flex-1">
                      <div style={{fontSize:12, fontWeight:500}}>{r.l}</div>
                      <div className="text-xs text-muted">{r.w}</div>
                    </div>
                    {r.s==='done'?<Badge tone="ok" dot={false}>erledigt</Badge>:<Badge tone="neutral" dot={false}>offen</Badge>}
                  </div>
                ))}
              </div>
            </Card>

            <Card title="Konto">
              {[['Name', ctx?.session?.name], ['E-Mail', ctx?.session?.email], ['Rolle', 'Hauswart']].map(([k,v])=>(
                <div key={k} style={{padding:'8px 0', borderBottom:'1px solid var(--ink-150)', display:'flex', justifyContent:'space-between'}}>
                  <span className="text-xs text-muted">{k}</span>
                  <span style={{fontSize:13}}>{v||'—'}</span>
                </div>
              ))}
            </Card>
          </div>
        </div>
      </div>
    </>
  );
};

Object.assign(window, {HauswartDashboard});
