// screens3.jsx — rezerwacje, uchwała/głosowanie, powiadomienia, więcej
const { useState: u3 } = React;

// ════════════════════ REZERWACJE (B7) ════════════════════
const BUSY_DAYS = { 7: 'full', 3: 'some', 14: 'some', 21: 'some' };
function Rezerwacje({ ctx }) {
  const [resId, setResId] = u3('sala');
  const [day, setDay] = u3(12);
  const res = RESOURCES.find(r => r.id === resId);

  // czerwiec 2026 — siatka (poniedziałek pierwszy)
  const first = new Date(2026, 5, 1).getDay(); // 0=nd
  const offset = (first + 6) % 7;
  const daysInMonth = 30;
  const cells = [...Array(offset).fill(null), ...Array.from({length: daysInMonth}, (_,i)=>i+1)];

  const slots = ['09:00','10:00','11:00','12:00','13:00','14:00','15:00','16:00','17:00','18:00'];
  const busySlots = { 3: ['09:00','10:00','11:00'], 14: ['15:00','16:00','17:00','18:00'], 21: ['09:00','12:00','17:00'] };
  const isFull = BUSY_DAYS[day] === 'full';
  const dayBusy = busySlots[day] || [];
  const [slot, setSlot] = u3(null);

  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]"><div className="flex items-center gap-1">{ctx.hasStack && <IconBtn name="arrowLeft" label="Wstecz" onClick={ctx.back} className="-ml-1" />}<h1 className="font-display font-800 text-text text-[26px]">Rezerwacje</h1></div>
          <IconBtn name="list" label="Moje rezerwacje" onClick={() => ctx.toast({ msg: 'Moje rezerwacje — wkrótce', icon: 'calendar', tone: 'info' })} /></div>
      </header>
      <div className="flex-1 overflow-auto app-scroll px-4 pb-28">
        {/* wybór zasobu */}
        <div className="flex gap-2.5 overflow-x-auto app-scroll -mx-4 px-4 py-2">
          {RESOURCES.map(r => {
            const on = r.id === resId;
            return (
              <button key={r.id} onClick={() => { setResId(r.id); setSlot(null); }}
                className={`focusable shrink-0 w-[108px] flex flex-col items-center gap-2 p-3 rounded-lg border transition-all active:scale-95 ${on ? 'border-brand bg-brand/8' : 'border-border bg-surface'}`}>
                <span className={`w-11 h-11 rounded-[13px] flex items-center justify-center ${on ? 'bg-brand text-brand-fg' : 'bg-surface-muted text-text-secondary'}`}><Icon name={r.icon} size={22} /></span>
                <span className={`text-[12px] font-display font-700 text-center leading-tight ${on ? 'text-text' : 'text-text-secondary'}`}>{r.label}</span>
              </button>
            );
          })}
        </div>

        {/* reguły */}
        <div className="flex items-center gap-2 mt-2 mb-4 text-[12px] text-text-secondary flex-wrap">
          <span className="inline-flex items-center gap-1 bg-surface-muted rounded-pill px-2.5 py-1"><Icon name="clock" size={13} className="text-text-muted" />{res.rule}</span>
          <span className="inline-flex items-center gap-1 bg-surface-muted rounded-pill px-2.5 py-1"><Icon name="wallet" size={13} className="text-text-muted" />{res.fee}</span>
        </div>

        {res.needsApproval && <div className="mb-4"><Banner tone="info" icon="info" title="Wymaga akceptacji zarządcy">Rezerwacja tego zasobu zostanie potwierdzona po zatwierdzeniu przez administrację.</Banner></div>}

        {/* kalendarz */}
        <Card className="p-4">
          <div className="flex items-center justify-between mb-3">
            <IconBtn name="chevronLeft" label="Poprzedni miesiąc" size={18} className="!w-8 !h-8" />
            <p className="font-display font-700 text-text text-[15px]">Czerwiec 2026</p>
            <IconBtn name="chevronRight" label="Następny miesiąc" size={18} className="!w-8 !h-8" />
          </div>
          <div className="grid grid-cols-7 gap-1 text-center mb-1">{['Pn','Wt','Śr','Cz','Pt','So','Nd'].map(d => <span key={d} className="text-[11px] font-display font-700 text-text-muted">{d}</span>)}</div>
          <div className="grid grid-cols-7 gap-1">
            {cells.map((d,i) => {
              if (!d) return <span key={i} />;
              const b = BUSY_DAYS[d], on = d === day, isToday = false;
              return (
                <button key={i} onClick={() => { setDay(d); setSlot(null); }}
                  className={`focusable relative aspect-square rounded-md text-[13px] font-display font-600 flex items-center justify-center transition active:scale-90
                    ${on ? 'bg-brand text-brand-fg' : b === 'full' ? 'bg-surface-muted text-text-muted' : 'text-text hover:bg-surface-muted'}`}>
                  {d}
                  {!on && b && <span className={`absolute bottom-1 w-1 h-1 rounded-full ${b==='full'?'bg-danger':'bg-warning'}`} />}
                </button>
              );
            })}
          </div>
          <div className="flex gap-4 mt-3 pt-3 border-t border-border text-[11px] text-text-muted">
            <span className="inline-flex items-center gap-1.5"><span className="w-2 h-2 rounded-full bg-warning" />Częściowo zajęty</span>
            <span className="inline-flex items-center gap-1.5"><span className="w-2 h-2 rounded-full bg-danger" />Brak miejsc</span>
          </div>
        </Card>

        {/* sloty */}
        <h2 className="font-display font-700 text-text text-[16px] mt-5 mb-3">Wolne terminy · {day} czerwca</h2>
        {isFull
          ? <EmptyState icon="calendar" title="Brak wolnych terminów" action={<Btn variant="secondary" size="sm" onClick={()=>setDay(12)}>Pokaż inny dzień</Btn>}>Wszystkie terminy w tym dniu są już zajęte.</EmptyState>
          : <div className="grid grid-cols-3 gap-2.5">
              {slots.map(s => { const taken = dayBusy.includes(s); const on = slot === s;
                return <button key={s} disabled={taken} onClick={() => setSlot(s)}
                  className={`focusable h-12 rounded-pill text-[14px] font-display font-700 border transition active:scale-95
                    ${taken ? 'bg-surface-muted text-text-muted border-border line-through opacity-60 cursor-not-allowed'
                      : on ? 'bg-brand text-brand-fg border-brand shadow-sm' : 'bg-surface text-text border-border hover:border-brand'}`}>{s}</button>;
              })}
            </div>}
      </div>

      {!isFull && (
        <div className="shrink-0 px-4 pt-3 pb-7 bg-surface/90 backdrop-blur-xl border-t border-border">
          <Btn block size="lg" icon="calendar" disabled={!slot} onClick={() => { ctx.toast({ msg: res.needsApproval ? 'Wysłano prośbę o rezerwację' : `Zarezerwowano: ${res.label}, ${slot}`, icon: 'check' }); setSlot(null); }}>
            {slot ? `Zarezerwuj — ${day} czerwca, ${slot}` : 'Wybierz termin'}
          </Btn>
        </div>
      )}
    </div>
  );
}

// ════════════════════ UCHWAŁA + GŁOSOWANIE (C2) ════════════════════
function Uchwala({ ctx }) {
  const r = RESOLUTION;
  const [asTenant, setAsTenant] = u3(false);
  const voted = ctx.vote;
  const canVote = !asTenant;
  const total = r.results.za + r.results.przeciw + r.results.wstrzym;
  const pct = (n) => Math.round((n / total) * 100);

  const VoteBtn = ({ k, label, t, icon }) => {
    const on = voted === k;
    return (
      <button onClick={() => ctx.castVote(k)} disabled={!!voted}
        className={`focusable flex-1 flex flex-col items-center gap-1.5 py-4 rounded-lg border-2 transition-all active:scale-95 disabled:cursor-default
          ${on ? `${tone(t).bg} border-current ${tone(t).text}` : voted ? 'border-border bg-surface opacity-50' : 'border-border bg-surface hover:border-current ' + tone(t).text}`}>
        <Icon name={icon} size={26} stroke={2} fill={on} />
        <span className={`font-display font-700 text-[13px] ${on ? '' : voted ? 'text-text-muted' : 'text-text'}`}>{label}</span>
      </button>
    );
  };

  return (
    <div className="flex flex-col h-full bg-bg">
      <AppBar title="Uchwała" onBack={ctx.back} right={
        <button onClick={()=>setAsTenant(!asTenant)} className="focusable text-[11px] font-display font-600 text-text-muted px-2.5 py-1.5 rounded-pill bg-surface-muted">{asTenant ? 'Podgląd: najemca' : 'Podgląd: właściciel'}</button>
      } />
      <div className="flex-1 overflow-auto app-scroll px-4 pb-10">
        <div className="pt-3 flex items-center gap-2">
          <Badge tone="accent" icon="vote">{r.number}</Badge>
          {r.status === 'trwa' ? <Badge tone="success" dot>Głosowanie trwa</Badge> : <Badge tone="text-muted">Zakończone</Badge>}
        </div>
        <h1 className="font-display font-800 text-text text-[23px] leading-tight mt-3" style={{ textWrap: 'balance' }}>{r.title}</h1>
        <p className="text-[13px] text-text-secondary flex items-center gap-1.5 mt-2"><Icon name="clock" size={14} className="text-text-muted" />{r.deadline}</p>

        <div className="my-4"><Banner tone="info" icon="info" title={r.mode}>Siła głosu zależy od wielkości udziału w nieruchomości wspólnej.</Banner></div>

        <div className="text-[16px] leading-[1.6] text-text whitespace-pre-line">{r.body}</div>
        <div className="mt-4 space-y-2">{r.attachments.map((a,i) => <Attachment key={i} name={a.name} />)}</div>

        {/* karta głosowania */}
        <div className="mt-6 rounded-xl border border-border bg-surface p-4 shadow-sm">
          {!canVote ? (
            <div className="text-center py-3">
              <span className="inline-flex items-center justify-center w-12 h-12 rounded-full bg-surface-muted text-text-muted mb-2"><Icon name="info" size={24} /></span>
              <p className="font-display font-700 text-text text-[15px]">Głosować mogą tylko właściciele</p>
              <p className="text-[13px] text-text-secondary mt-1">Jako najemca masz wgląd w treść uchwały, ale nie bierzesz udziału w głosowaniu.</p>
            </div>
          ) : !voted ? (<>
            <p className="font-display font-800 text-text text-[16px] text-center mb-3">Jak głosujesz?</p>
            <div className="flex gap-2.5">
              <VoteBtn k="za" label="Za" t="success" icon="thumbsUp" />
              <VoteBtn k="przeciw" label="Przeciw" t="danger" icon="thumbsDown" />
              <VoteBtn k="wstrzym" label="Wstrzymuję" t="text-secondary" icon="minus" />
            </div>
          </>) : (<>
            <div className="anim-pop flex items-center gap-2.5 justify-center mb-4 text-success">
              <span className="text-success"><DrawCheck size={30} stroke={3.4} ring={false} /></span>
              <span className="font-display font-700 text-[15px]">Twój głos został oddany: {{za:'Za',przeciw:'Przeciw',wstrzym:'Wstrzymuję się'}[voted]}</span>
            </div>
            {/* wynik */}
            <p className="text-[12px] font-display font-700 text-text-muted uppercase tracking-wide mb-2">Wyniki na żywo</p>
            {[['za','Za','success'],['przeciw','Przeciw','danger'],['wstrzym','Wstrzymuję się','text-secondary']].map(([k,l,t]) => (
              <div key={k} className="mb-2.5">
                <div className="flex justify-between text-[13px] mb-1"><span className="font-display font-600 text-text">{l}</span><span className="font-mono text-text-secondary">{pct(r.results[k])}%</span></div>
                <div className="h-2.5 rounded-full bg-surface-muted overflow-hidden"><div className={`h-full rounded-full ${tone(t).dot}`} style={{ width: `${pct(r.results[k])}%`, animation: 'om-grow .8s cubic-bezier(.22,1,.36,1) both' }} /></div>
              </div>
            ))}
            <div className="flex items-center justify-between mt-4 pt-3 border-t border-border text-[13px]">
              <div><p className="text-text-muted text-[11px]">Frekwencja</p><p className="font-display font-700 text-text">{r.results.frekwencja}% udziałów</p></div>
              <Badge tone={r.results.frekwencja >= 50 ? 'success' : 'warning'} icon={r.results.frekwencja >= 50 ? 'checkCircle' : 'clock'}>{r.results.frekwencja >= 50 ? 'Kworum osiągnięte' : 'Brak kworum'}</Badge>
            </div>
          </>)}
        </div>
      </div>
    </div>
  );
}

// ════════════════════ POWIADOMIENIA (B13) ════════════════════
function Powiadomienia({ ctx }) {
  const [items, setItems] = u3(NOTIFICATIONS);
  return (
    <div className="flex flex-col h-full bg-bg">
      <AppBar title="Powiadomienia" onBack={ctx.back} right={
        <button onClick={() => setItems(items.map(n => ({ ...n, unread: false })))} className="focusable text-[12px] font-display font-600 text-brand px-2 py-1.5">Oznacz jako przeczytane</button>} />
      <div className="flex-1 overflow-auto app-scroll px-4 pt-3 pb-10">
        <div className="space-y-2">
          {items.map(n => (
            <button key={n.id} onClick={() => setItems(items.map(x => x.id===n.id?{...x,unread:false}:x))}
              className={`focusable w-full text-left flex gap-3 p-3.5 rounded-xl border transition active:scale-[.99] ${n.unread ? 'bg-surface border-border shadow-sm' : 'bg-transparent border-transparent'}`}>
              <span className={`shrink-0 w-10 h-10 rounded-[12px] flex items-center justify-center ${tone(n.color).bg} ${tone(n.color).text}`}><Icon name={n.icon} size={20} /></span>
              <div className="flex-1 min-w-0">
                <p className={`text-[14px] leading-snug ${n.unread ? 'font-display font-700 text-text' : 'text-text-secondary'}`}>{n.title}</p>
                <p className="text-[13px] text-text-muted leading-snug mt-0.5">{n.desc}</p>
                <p className="text-[11px] text-text-muted mt-1">{n.time}</p>
              </div>
              {n.unread && <span className="shrink-0 w-2.5 h-2.5 rounded-full bg-brand mt-1.5" />}
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

// ════════════════════ WIĘCEJ / MENU ════════════════════
function Wiecej({ ctx }) {
  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>
  );
  const soon = () => ctx.toast({ msg: 'Funkcja dostępna wkrótce', icon: 'info', tone: 'info' });
  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="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>

        <Card className="overflow-hidden divide-y divide-border mb-5">
          <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')} />
          <Row icon="vote" t="accent" label="Uchwały i ankiety" sub="Głosowania wspólnoty" badge="1" onClick={() => ctx.go('uchwala')} />
          <Row icon="users" t="cat-zielone" label="Forum sąsiedzkie" sub="Tablica ogłoszeń mieszkańców" onClick={soon} />
          <Row icon="wallet" t="accent-warm" label="Opłaty" sub="Saldo i historia płatności" onClick={soon} />
        </Card>

        <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 · wersja prototypowa</p>
      </div>
    </div>
  );
}

// ── Dokumenty ──
function Dokumenty({ ctx }) {
  return (
    <div className="flex flex-col h-full bg-bg">
      <AppBar title="Dokumenty" onBack={ctx.back} />
      <div className="flex-1 overflow-auto app-scroll px-4 pt-3 pb-10">
        <div className="relative mb-4">
          <Icon name="search" size={18} className="absolute left-3.5 top-1/2 -translate-y-1/2 text-text-muted" />
          <input placeholder="Szukaj dokumentu…" 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>
        <div className="grid grid-cols-2 gap-2.5">
          {DOC_CATS.map(d => (
            <button key={d.label} onClick={() => ctx.toast({ msg: `${d.label} — ${d.count} plików`, icon: 'fileText', tone: 'info' })}
              className="focusable text-left p-4 rounded-xl bg-surface border border-border shadow-sm hover:-translate-y-0.5 hover:shadow-md transition active:scale-[.98]">
              <span className="flex items-center justify-center w-11 h-11 rounded-[13px] bg-info/12 text-info mb-3"><Icon name={d.icon} size={22} /></span>
              <p className="font-display font-700 text-text text-[15px]">{d.label}</p>
              <p className="text-[12px] text-text-muted mt-0.5">{d.count} plików</p>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

// ── Kontakty (click-to-call) ──
function Kontakty({ ctx }) {
  return (
    <div className="flex flex-col h-full bg-bg">
      <AppBar title="Kontakty" onBack={ctx.back} />
      <div className="flex-1 overflow-auto app-scroll px-4 pt-3 pb-10">
        <div className="space-y-2.5">
          {CONTACTS.map((c,i) => (
            <Card key={i} className="p-4 flex items-center gap-3">
              <Avatar name={c.name} size={44} />
              <div className="flex-1 min-w-0"><p className="font-display font-700 text-text text-[15px]">{c.name}</p><p className="text-[12px] text-text-muted">{c.role}</p><p className="text-[13px] text-text-secondary font-mono mt-0.5">{c.phone}</p></div>
              <a href={`tel:${c.phone.replace(/\s/g,'')}`} aria-label={`Zadzwoń do ${c.name}`}
                className="focusable w-11 h-11 rounded-pill bg-brand text-brand-fg flex items-center justify-center shrink-0 active:scale-90 transition shadow-sm"><Icon name="phone" size={20} /></a>
            </Card>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Rezerwacje, Uchwala, Powiadomienia, Wiecej, Dokumenty, Kontakty });
