// screens.jsx — wspólne elementy + ekrany rdzenia mieszkańca
const { useState: uS, useEffect: uE, useRef: uR } = React;

const TOPPAD = 'pt-[52px]';

// Pasek aplikacji ekranów szczegółowych (z przyciskiem wstecz)
function AppBar({ title, onBack, right, sub }) {
  return (
    <header className={`shrink-0 ${TOPPAD} px-3 pb-2.5 bg-surface/85 backdrop-blur-xl border-b border-border z-20`}>
      <div className="flex items-center gap-1 min-h-[44px]">
        {onBack && <IconBtn name="arrowLeft" label="Wstecz" onClick={onBack} className="-ml-1" />}
        <div className="flex-1 min-w-0 px-1">
          <h1 className="font-display font-700 text-text text-[18px] leading-tight truncate">{title}</h1>
          {sub && <p className="text-[12px] text-text-muted truncate">{sub}</p>}
        </div>
        {right}
      </div>
    </header>
  );
}

// Górny pasek ekranów głównych (nazwa wspólnoty + dzwonek)
function HomeBar({ ctx, title }) {
  const unread = NOTIFICATIONS.filter(n => n.unread).length;
  return (
    <header className={`shrink-0 ${TOPPAD} px-4 pb-2 bg-bg/80 backdrop-blur-xl z-20`}>
      <div className="flex items-center justify-between min-h-[44px]">
        <div className="flex items-center gap-2.5">
          <div className="w-9 h-9 rounded-[11px] bg-brand flex items-center justify-center shadow-sm">
            <Icon name="building" size={20} className="text-brand-fg" stroke={2.2} />
          </div>
          <div className="leading-none">
            <p className="text-[11px] text-text-muted font-display font-600">Wspólnota</p>
            <p className="font-display font-800 text-text text-[15px] -mt-0.5">{title || USER.community}</p>
          </div>
        </div>
        <button aria-label={`Powiadomienia, ${unread} nieprzeczytane`} onClick={() => ctx.go('powiadomienia')}
          className="focusable relative w-11 h-11 rounded-pill flex items-center justify-center text-text-secondary hover:bg-surface-muted active:scale-90 transition">
          <Icon name="bell" size={22} />
          {unread > 0 && <span className="absolute top-1.5 right-1.5 min-w-[18px] h-[18px] px-1 rounded-full bg-danger text-white text-[10px] font-700 flex items-center justify-center border-2 border-bg">{unread}</span>}
        </button>
      </div>
    </header>
  );
}

// Placeholder zdjęcia (paski + opis mono)
function Photo({ label, h = 150, className = '', rounded = 'rounded-lg' }) {
  return (
    <div className={`relative overflow-hidden ${rounded} border border-border flex items-center justify-center ${className}`}
      style={{ height: h, backgroundImage: 'repeating-linear-gradient(135deg, rgb(var(--c-surface-muted)) 0 11px, rgb(var(--c-bg)) 11px 22px)' }}>
      <span className="font-mono text-[10px] text-text-muted bg-surface/85 px-2 py-1 rounded-md border border-border">{label}</span>
    </div>
  );
}

// ── KARTA OGŁOSZENIA ──
function AnnCard({ a, ctx, compact }) {
  const cat = ANN_CATS[a.cat];
  const acked = ctx.acked[a.id] || a.acked;
  return (
    <button onClick={() => ctx.go('ogloszenie', { id: a.id })}
      className="focusable w-full text-left bg-surface border border-border rounded-xl shadow-sm p-4 hover:shadow-md hover:-translate-y-0.5 transition-all duration-200 active:scale-[.99]">
      <div className="flex items-center justify-between gap-2 mb-2">
        <Badge tone={cat.color} icon={cat.icon}>{cat.label}</Badge>
        <div className="flex items-center gap-1.5">
          {a.pinned && <span className="text-accent-warm" title="Przypięte"><Icon name="pin" size={15} /></span>}
          <span className="text-[12px] text-text-muted">{a.time}</span>
        </div>
      </div>
      <h3 className="font-display font-700 text-text text-[16px] leading-snug" style={{ textWrap: 'pretty' }}>{a.title}</h3>
      {!compact && <p className="text-[14px] text-text-secondary mt-1 leading-snug line-clamp-2">{a.excerpt}</p>}
      <div className="flex items-center justify-between mt-3 pt-3 border-t border-border">
        <span className="text-[12px] text-text-muted truncate">{a.author}</span>
        {a.requireAck && (acked
          ? <span className="inline-flex items-center gap-1 text-[12px] font-display font-700 text-success"><Icon name="checkCircle" size={14} stroke={2.4} />Potwierdzono</span>
          : <span className="inline-flex items-center gap-1 text-[12px] font-display font-700 text-warning"><Icon name="clock" size={14} stroke={2.4} />Wymaga potwierdzenia</span>)}
      </div>
    </button>
  );
}

// ── KARTA USTERKI (wiersz) ──
function FaultRow({ f, ctx }) {
  const cat = FAULT_CATS[f.cat], st = FAULT_STATUS[f.status];
  return (
    <button onClick={() => ctx.go('usterka', { id: f.id })}
      className="focusable w-full text-left bg-surface border border-border rounded-xl shadow-sm p-3.5 hover:shadow-md hover:-translate-y-0.5 transition-all active:scale-[.99]">
      <div className="flex gap-3">
        <span className={`shrink-0 w-11 h-11 rounded-[13px] flex items-center justify-center ${tone(cat.color).bg} ${tone(cat.color).text}`}>
          <Icon name={cat.icon} size={22} stroke={2} />
        </span>
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 mb-0.5">
            <span className="font-mono text-[11px] text-text-muted">#{f.id}</span>
            <Badge tone={st.tone} dot size="sm">{st.label}</Badge>
          </div>
          <h3 className="font-display font-700 text-text text-[15px] leading-tight line-clamp-1">{f.title}</h3>
          <p className="text-[12px] text-text-muted mt-0.5 truncate">{f.location} · {f.time}</p>
        </div>
        <Icon name="chevronRight" size={18} className="text-text-muted self-center shrink-0" />
      </div>
    </button>
  );
}

// ════════════════════ PULPIT (B1) ════════════════════
function Pulpit({ ctx }) {
  const fresh = ctx.flags.fresh, loading = ctx.flags.loading;
  const myFaults = FAULTS.filter(f => f.mine && f.status !== 'zamkniete');
  const alertAnn = ANNOUNCEMENTS.find(a => a.cat === 'awaria' && a.pinned);
  const recent = ANNOUNCEMENTS.slice(0, 2);

  const Quick = ({ icon, label, t, onClick, featured }) => (
    <button onClick={onClick}
      className={`focusable flex-1 flex flex-col items-center gap-2 p-3 rounded-lg border transition-all active:scale-95
        ${featured ? 'bg-brand text-brand-fg border-brand shadow-sm' : 'bg-surface border-border text-text hover:border-text-muted'}`}>
      <span className={`flex items-center justify-center w-11 h-11 rounded-[13px] ${featured ? 'bg-white/20' : tone(t).bg + ' ' + tone(t).text}`}>
        <Icon name={icon} size={22} stroke={2} />
      </span>
      <span className="font-display font-700 text-[12px] leading-tight text-center">{label}</span>
    </button>
  );

  return (
    <div className="flex flex-col h-full bg-bg">
      <HomeBar ctx={ctx} />
      <div className="flex-1 overflow-auto app-scroll px-4 pb-28">
        {/* powitanie */}
        <div className="pt-1 pb-3">
          <h1 className="font-display font-800 text-text text-[26px] leading-tight">Dzień dobry, {USER.name.split(' ')[0]}</h1>
          <p className="text-[13px] text-text-secondary flex items-center gap-1.5 mt-0.5"><Icon name="mapPin" size={14} className="text-text-muted" />{USER.flat}</p>
        </div>

        {ctx.flags.offline && <div className="mb-3"><Banner tone="text-secondary" icon="wifiOff" title="Jesteś offline">Pokazujemy ostatnio wczytane treści. Część akcji jest niedostępna.</Banner></div>}

        {/* baner alertu */}
        {alertAnn && !ctx.flags.offline && (
          <button onClick={() => ctx.go('ogloszenie', { id: alertAnn.id })}
            className="focusable w-full text-left mb-4 anim-rise rounded-xl p-4 bg-danger text-white shadow-md active:scale-[.99] relative overflow-hidden">
            <div className="absolute -right-6 -top-6 w-28 h-28 rounded-full bg-white/10" />
            <div className="flex items-center gap-2 mb-1 relative">
              <Icon name="alert" size={18} stroke={2.4} />
              <span className="font-display font-800 text-[12px] tracking-wide uppercase">Komunikat awaryjny</span>
            </div>
            <p className="font-display font-700 text-[15px] leading-snug relative">{alertAnn.title}</p>
            <span className="inline-flex items-center gap-1 text-[12px] font-600 mt-2 opacity-90 relative">Zobacz szczegóły <Icon name="chevronRight" size={14} /></span>
          </button>
        )}

        {/* szybkie akcje */}
        <div className="flex gap-2.5 mb-5">
          <Quick icon="wrench" label="Zgłoś usterkę" featured onClick={() => ctx.go('nowa-usterka')} />
          <Quick icon="calendar" label="Zarezerwuj" t="accent" onClick={() => ctx.setTab('rezerwacje')} />
          <Quick icon="fileText" label="Dokumenty" t="info" onClick={() => ctx.go('dokumenty')} />
        </div>

        {/* ostatnie ogłoszenia */}
        <SectionHead title="Ostatnie ogłoszenia" action="Wszystkie" onAction={() => ctx.setTab('ogloszenia')} />
        <div className="space-y-2.5 mb-6">
          {loading
            ? [0,1].map(i => <Card key={i} className="p-4"><Sk w="40%" h={20} r={9} /><Sk w="90%" h={16} className="mt-3" /><Sk w="70%" h={16} className="mt-2" /></Card>)
            : recent.map(a => <AnnCard key={a.id} a={a} ctx={ctx} />)}
        </div>

        {/* moje sprawy */}
        <SectionHead title="Moje sprawy" action={!fresh && myFaults.length ? 'Wszystkie' : null} onAction={() => ctx.go('usterki')} />
        <div className="mb-6">
          {loading ? <Card className="p-3.5"><div className="flex gap-3"><Sk w={44} h={44} r={13} /><div className="flex-1"><Sk w="50%" h={14} /><Sk w="80%" h={16} className="mt-2" /></div></div></Card>
          : fresh || myFaults.length === 0
            ? <Card className="overflow-hidden"><EmptyState icon="checkCircle" title="Brak otwartych spraw" action={<Btn size="sm" icon="wrench" onClick={() => ctx.go('nowa-usterka')}>Zgłoś usterkę</Btn>}>Gdy zgłosisz usterkę, zobaczysz tu jej status na bieżąco.</EmptyState></Card>
            : <div className="space-y-2.5">{myFaults.map(f => <FaultRow key={f.id} f={f} ctx={ctx} />)}</div>}
        </div>

        {/* nadchodzące rezerwacje */}
        {!fresh && !loading && UPCOMING.length > 0 && (<>
          <SectionHead title="Nadchodzące rezerwacje" />
          <Card className="p-4 mb-6 flex items-center gap-3">
            <span className="w-11 h-11 rounded-[13px] bg-accent/12 text-accent flex items-center justify-center shrink-0"><Icon name="calendar" size={22} /></span>
            <div className="flex-1 min-w-0">
              <p className="font-display font-700 text-text text-[15px]">{UPCOMING[0].resource}</p>
              <p className="text-[13px] text-text-secondary">{UPCOMING[0].date} · {UPCOMING[0].time}</p>
            </div>
            <Badge tone="success" dot size="sm">Potwierdzona</Badge>
          </Card>
        </>)}

        {/* głosowanie */}
        {!loading && (
          <button onClick={() => ctx.go('uchwala')} className="focusable w-full text-left rounded-xl p-4 anim-rise relative overflow-hidden border border-accent/30 bg-gradient-to-br from-accent/12 to-brand/10 active:scale-[.99]">
            <div className="flex items-center gap-2 mb-1.5"><span className="text-accent"><Icon name="vote" size={20} stroke={2.2} /></span><span className="font-display font-800 text-accent text-[12px] uppercase tracking-wide">Twój głos się liczy</span></div>
            <p className="font-display font-700 text-text text-[15px] leading-snug">{RESOLUTION.title}</p>
            <p className="text-[13px] text-text-secondary mt-0.5">{RESOLUTION.deadline}</p>
            <span className="inline-flex items-center gap-1 mt-3 text-[13px] font-display font-700 text-brand">{ctx.vote ? 'Zobacz wynik' : 'Oddaj głos'}<Icon name="chevronRight" size={15} /></span>
          </button>
        )}
      </div>
    </div>
  );
}

// ════════════════════ OGŁOSZENIA — LISTA (B2) ════════════════════
function Ogloszenia({ ctx }) {
  const [filter, setFilter] = uS('all');
  const [q, setQ] = uS('');
  const loading = ctx.flags.loading;
  const cats = [['all','Wszystkie',null,null], ...Object.entries(ANN_CATS).map(([k,v]) => [k, v.label, v.color, v.icon])];
  let list = ANNOUNCEMENTS.filter(a => (filter === 'all' || a.cat === filter) && (!q || a.title.toLowerCase().includes(q.toLowerCase())));
  const pinned = list.filter(a => a.pinned), rest = list.filter(a => !a.pinned);

  return (
    <div className="flex flex-col h-full bg-bg">
      <header className={`shrink-0 ${TOPPAD} px-4 pb-2 bg-bg/80 backdrop-blur-xl z-20`}>
        <div className="flex items-center justify-between min-h-[44px] mb-2">
          <h1 className="font-display font-800 text-text text-[26px]">Ogłoszenia</h1>
        </div>
        <div className="relative">
          <Icon name="search" size={18} className="absolute left-3.5 top-1/2 -translate-y-1/2 text-text-muted" />
          <input value={q} onChange={e => setQ(e.target.value)} placeholder="Szukaj w ogłoszeniach…"
            className="focusable w-full h-11 pl-11 pr-4 rounded-pill bg-surface border border-border text-[14px] text-text placeholder:text-text-muted" />
        </div>
      </header>
      <div className="shrink-0 flex gap-2 overflow-x-auto app-scroll px-4 py-2.5">
        {cats.map(([k,label,color,icon]) => <Chip key={k} active={filter === k} onClick={() => setFilter(k)} icon={icon} tone={color}>{label}</Chip>)}
      </div>

      <div className="flex-1 overflow-auto app-scroll px-4 pb-28">
        {loading ? <div className="space-y-2.5 pt-1">{[0,1,2].map(i => <Card key={i} className="p-4"><Sk w="40%" h={20} r={9} /><Sk w="90%" h={16} className="mt-3" /><Sk w="65%" h={16} className="mt-2" /></Card>)}</div>
        : list.length === 0
          ? <EmptyState icon="search" title="Brak wyników" action={<Btn variant="secondary" size="sm" onClick={() => { setFilter('all'); setQ(''); }}>Wyczyść filtry</Btn>}>Nie znaleźliśmy ogłoszeń dla wybranych filtrów.</EmptyState>
          : <>
            {pinned.length > 0 && (<div className="mb-4">
              <p className="flex items-center gap-1.5 text-[12px] font-display font-700 text-text-muted uppercase tracking-wide mb-2 mt-1"><Icon name="pin" size={13} />Przypięte</p>
              <div className="space-y-2.5">{pinned.map(a => <AnnCard key={a.id} a={a} ctx={ctx} />)}</div>
            </div>)}
            <div className="space-y-2.5">{rest.map(a => <AnnCard key={a.id} a={a} ctx={ctx} />)}</div>
          </>}
      </div>
    </div>
  );
}

// ════════════════════ OGŁOSZENIE — SZCZEGÓŁ (B3) ════════════════════
function OgloszenieDetail({ ctx, params }) {
  const a = ANNOUNCEMENTS.find(x => x.id === params.id);
  const cat = ANN_CATS[a.cat];
  const acked = ctx.acked[a.id] || (a.acked ? a.ackDate : null);
  const [busy, setBusy] = uS(false);
  const confirm = () => { setBusy(true); setTimeout(() => { setBusy(false); ctx.ack(a.id); ctx.toast({ msg: 'Potwierdzono zapoznanie się', icon: 'check' }); ctx.celebrate(); }, 700); };

  return (
    <div className="flex flex-col h-full bg-bg">
      <AppBar title={cat.label} onBack={ctx.back} right={<IconBtn name="more" label="Więcej" />} />
      <div className="flex-1 overflow-auto app-scroll px-4 pb-32">
        <div className="pt-3">
          <Badge tone={cat.color} icon={cat.icon}>{cat.label}</Badge>
          <h1 className="font-display font-800 text-text text-[24px] leading-tight mt-3" style={{ textWrap: 'balance' }}>{a.title}</h1>
          <div className="flex flex-wrap items-center gap-x-3 gap-y-1 mt-3 text-[13px] text-text-secondary">
            <span className="inline-flex items-center gap-1.5"><Avatar name={a.author} size={22} />{a.author}</span>
            <span className="inline-flex items-center gap-1 text-text-muted"><Icon name="clock" size={14} />{a.date}</span>
            <span className="inline-flex items-center gap-1 text-text-muted"><Icon name="users" size={14} />{a.scope}</span>
          </div>
        </div>
        <div className="h-px bg-border my-4" />
        <div className="text-[17px] leading-[1.65] text-text whitespace-pre-line" style={{ fontFamily: 'Inter' }}>{a.body}</div>
        {a.attachments.length > 0 && (<div className="mt-5">
          <p className="text-[12px] font-display font-700 text-text-muted uppercase tracking-wide mb-2">Załączniki</p>
          <div className="space-y-2">{a.attachments.map((at,i) => <Attachment key={i} name={at.name} />)}</div>
        </div>)}
      </div>

      {/* przyklejony pasek potwierdzenia */}
      {a.requireAck && (
        <div className="shrink-0 px-4 pt-3 pb-7 bg-surface/90 backdrop-blur-xl border-t border-border">
          {acked
            ? <div className="anim-pop flex items-center justify-center gap-2.5 h-[52px] rounded-pill bg-success/12 text-success font-display font-700" role="status" aria-live="polite">
                <span className="text-success"><DrawCheck size={26} stroke={3.4} ring={false} /></span>
                Potwierdzono ({acked || a.ackDate})
              </div>
            : <Btn block size="lg" loading={busy} icon={busy ? null : 'checkCircle'} onClick={confirm}>Potwierdzam zapoznanie się</Btn>}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { AppBar, HomeBar, Photo, AnnCard, FaultRow, Pulpit, Ogloszenia, OgloszenieDetail, TOPPAD });
