// unified-home.jsx — zunifikowany Pulpit (miks oficjalne + sąsiedzkie) i hub Więcej
const { useState: uH } = React;

// ════════════════════ ZUNIFIKOWANY PULPIT ════════════════════
function PulpitUnified({ ctx }) {
  const 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 previewPosts = FEED.filter((p) => !p.pinned).slice(0, 2);

  // jedna oś czasu: rezerwacje (oficjalne) + wydarzenia sąsiedzkie
  const upcoming = [
  { kind: 'rez', icon: 'calendar', tone: 'brand', title: UPCOMING[0].resource, sub: `${UPCOMING[0].date} · ${UPCOMING[0].time}`, badge: 'Rezerwacja' },
  { kind: 'event', id: 1, icon: 'sparkles', tone: 'accent', title: 'Grill sąsiedzki', sub: '7 czerwca · sob, 12:00', badge: 'Wydarzenie', going: 24 }];


  return (
    <div className="flex flex-col h-full bg-bg">
      <HomeBar ctx={ctx} />
      <div className="flex-1 overflow-auto app-scroll px-4 pt-3 pb-28">
        {ctx.flags.offline && <div className="mb-3"><Banner tone="text-secondary" icon="wifiOff" title="Jesteś offline">Pokazujemy ostatnio wczytane treści.</Banner></div>}

        {/* baner alertu (oficjalny) */}
        {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.5 relative"><Icon name="alert" size={18} stroke={2.4} className="shrink-0" /><span className="font-display font-800 text-[12px] tracking-wide uppercase whitespace-nowrap">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>
        }

        {/* moje sprawy (oficjalne) */}
        <SectionHead title="Moje sprawy" action={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> :
          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.</EmptyState></Card> :
          <div className="space-y-2.5">{myFaults.map((f) => <FaultRow key={f.id} f={f} ctx={ctx} />)}</div>}
        </div>

        {/* nadchodzące — rezerwacje + wydarzenia sąsiedzkie razem */}
        <SectionHead title="Nadchodzące" action="Wydarzenia" onAction={() => ctx.setTab('wydarzenia')} />
        <div className="space-y-2.5 mb-6">
          {upcoming.map((u, i) =>
          <button key={i} onClick={() => u.kind === 'event' ? ctx.go('event', { id: u.id }) : ctx.toast({ msg: 'Szczegóły rezerwacji', icon: 'calendar', tone: 'info' })}
          className="focusable w-full text-left bg-surface border border-border rounded-xl shadow-sm p-3.5 flex items-center gap-3 hover:shadow-md hover:-translate-y-0.5 transition-all active:scale-[.99]">
              <span className={`w-11 h-11 rounded-[13px] flex items-center justify-center shrink-0 ${tone(u.tone).bg} ${tone(u.tone).text}`}><Icon name={u.icon} size={22} /></span>
              <div className="flex-1 min-w-0"><p className="font-display font-700 text-text text-[15px] leading-tight">{u.title}</p><p className="text-[12.5px] text-text-secondary mt-0.5">{u.sub}</p></div>
              {u.kind === 'event' ?
            <span className="inline-flex items-center gap-1 text-[12px] font-display font-700 text-accent shrink-0">Idzie {u.going}</span> :
            <Badge tone="brand" size="sm">{u.badge}</Badge>}
            </button>
          )}
        </div>

        {/* z życia osiedla — podgląd feedu (sąsiedzkie) */}
        <SectionHead title="Z życia osiedla" action="Cała tablica" onAction={() => ctx.setTab('tablica')} />
        {!loading && LIVE_INFO[0] &&
        <button onClick={() => ctx.toast({ msg: 'Potwierdzono — widzę to', icon: 'check' })} className="focusable w-full text-left mb-2.5 flex items-center gap-2.5 rounded-xl border border-accent-warm/30 bg-accent-warm/8 px-3.5 py-2.5 active:scale-[.99]">
            <PostBadge type="live" size="sm" />
            <span className="text-[13px] text-text leading-snug flex-1 min-w-0 truncate">{LIVE_INFO[0].text}</span>
            <Icon name="chevronRight" size={16} className="text-text-muted shrink-0" />
          </button>
        }
        <div className="space-y-2.5 mb-6">
          {loading ? [0, 1].map((i) => <Card key={i} className="p-3"><div className="flex gap-2 mb-2"><Sk w={28} h={28} r={14} /><Sk w="40%" h={14} /></div><Sk w="90%" h={14} /></Card>) :
          previewPosts.map((p) => <PostCard key={p.id} post={p} ctx={{ ...ctx, feedLayout: 'kompakt' }} />)}
        </div>

        {/* głosowanie (oficjalne) */}
        {!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>);

}

// ════════════════════ WIĘCEJ — HUB OBU ŚWIATÓW ════════════════════
function WiecejUnified({ ctx }) {
  const soon = () => ctx.toast({ msg: 'Funkcja dostępna wkrótce', icon: 'info', tone: 'info' });
  const Row = ({ icon, t, label, sub, onClick, badge }) =>
  <button onClick={onClick} className="focusable w-full flex items-center gap-3.5 px-4 py-3.5 hover:bg-surface-muted transition active:scale-[.99] text-left">
      <span className={`w-10 h-10 rounded-[12px] flex items-center justify-center ${tone(t).bg} ${tone(t).text}`}><Icon name={icon} size={20} /></span>
      <div className="flex-1 min-w-0"><p className="font-display font-700 text-text text-[15px]">{label}</p>{sub && <p className="text-[12px] text-text-muted">{sub}</p>}</div>
      {badge && <Badge tone="danger" size="sm">{badge}</Badge>}
      <Icon name="chevronRight" size={18} className="text-text-muted" />
    </button>;

  return (
    <div className="flex flex-col h-full bg-bg">
      <header className="shrink-0 pt-[52px] px-4 pb-2 bg-bg/80 backdrop-blur-xl z-20"><div className="min-h-[44px] flex items-center"><h1 className="font-display font-800 text-text text-[26px]">Więcej</h1></div></header>
      <div className="flex-1 overflow-auto app-scroll px-4 pt-1 pb-28">
        {/* profil */}
        <Card className="p-4 flex items-center gap-3.5 mb-5">
          <Avatar name={USER.name} size={52} />
          <div className="flex-1 min-w-0"><p className="font-display font-800 text-text text-[16px]">{USER.name}</p><p className="text-[12px] text-text-secondary truncate">{USER.flat}</p><Badge tone="brand" size="sm" className="mt-1">{USER.isOwner ? 'Właściciel' : 'Najemca'}</Badge></div>
          <IconBtn name="pencil" label="Edytuj profil" onClick={soon} />
        </Card>

        {/* sprawy i dom (oficjalne) */}
        <p className="text-[12px] font-display font-700 text-text-muted uppercase tracking-wide mb-2 px-1">Sprawy i dom</p>
        <Card className="overflow-hidden divide-y divide-border mb-5">
          <Row icon="wrench" t="cat-winda" label="Usterki" sub="Moje zgłoszenia i część wspólna" onClick={() => ctx.go('usterki')} />
          <Row icon="calendar" t="info" label="Rezerwacje" sub="Sala, grill, boisko, parking" onClick={() => ctx.go('rezerwacje')} />
          <Row icon="vote" t="accent" label="Uchwały i ankiety" sub="Głosowania wspólnoty" badge="1" onClick={() => ctx.go('uchwala')} />
          <Row icon="fileText" t="info" label="Dokumenty" sub="Regulaminy, uchwały, sprawozdania" onClick={() => ctx.go('dokumenty')} />
          <Row icon="phone" t="cat-czystosc" label="Kontakty" sub="Administracja, awarie, ochrona" onClick={() => ctx.go('kontakty')} />
        </Card>

        {/* społeczność (sąsiedzkie) */}
        <p className="text-[12px] font-display font-700 text-text-muted uppercase tracking-wide mb-2 px-1">Społeczność</p>
        <Card className="overflow-hidden divide-y divide-border mb-5">
          <Row icon="megaphone" t="brand" label="Tablica społeczności" sub="Posty i dyskusje sąsiadów" onClick={() => ctx.setTab('tablica')} />
          <Row icon="shoppingBag" t="cat-zielone" label="Marketplace" sub="Oddam, sprzedam, pożyczę" onClick={() => ctx.go('market')} />
          <Row icon="calendar" t="accent" label="Wydarzenia" sub="Spotkania i wydarzenia osiedla" onClick={() => ctx.go('wydarzenia')} />
          <Row icon="pawPrint" t="danger" label="Kącik zwierzaków" sub="Pupile, spacery, zaginięcia" onClick={() => ctx.go('zwierzaki')} />
          <Row icon="handHeart" t="accent-warm" label="Pomoc sąsiedzka" sub="Prośby, oferty, dojazdy" onClick={soon} />
        </Card>

        {/* ustawienia */}
        <Card className="overflow-hidden divide-y divide-border mb-5">
          <div className="flex items-center gap-3.5 px-4 py-3.5">
            <span className="w-10 h-10 rounded-[12px] bg-surface-muted text-text-secondary flex items-center justify-center"><Icon name={ctx.theme === 'dark' ? 'moon' : 'sun'} size={20} /></span>
            <p className="flex-1 font-display font-700 text-text text-[15px]">Tryb ciemny</p>
            <Toggle checked={ctx.theme === 'dark'} onChange={() => ctx.toggleTheme()} label="Tryb ciemny" />
          </div>
          <Row icon="settings" t="text-secondary" label="Ustawienia i powiadomienia" sub="Kanały, język, prywatność" onClick={soon} />
        </Card>
        <p className="text-center text-[12px] text-text-muted">e‑Osiedle · jedna aplikacja osiedla</p>
      </div>
    </div>);

}

Object.assign(window, { PulpitUnified, WiecejUnified });