// social-more.jsx — Marketplace, Wydarzenie (RSVP+potluck), Zwierzaki, Regulamin
const { useState: uMo } = React;

// ════════════════════ MARKETPLACE — LISTA ════════════════════
function Marketplace({ ctx }) {
  const [sub, setSub] = uMo('all');
  const subs = [['all', 'Wszystko'], ['Oddam', 'Oddam za darmo'], ['Sprzedam', 'Sprzedam'], ['Kupię', 'Kupię'], ['Pożyczę', 'Pożyczę']];
  const list = MARKET.filter(m => sub === 'all' || m.subtype === sub);
  const gb = GROUP_BUY, gbPct = Math.round(gb.have / gb.need * 100);

  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="flex items-center justify-between min-h-[44px]"><h1 className="font-display font-800 text-text text-[24px]">Marketplace</h1>
          <IconBtn name="arrowLeft" label="Wstecz" onClick={ctx.back} className="-ml-1 order-first" /></div>
      </header>
      <div className="shrink-0 flex gap-2 overflow-x-auto app-scroll px-4 py-2.5">
        {subs.map(([k, l]) => <Chip key={k} active={sub === k} onClick={() => setSub(k)} tone={k === 'Oddam' ? 'success' : null}>{l}</Chip>)}
      </div>
      <div className="flex-1 overflow-auto app-scroll px-4 pb-28">
        {/* zakup grupowy */}
        {sub === 'all' && (
          <div className="rounded-xl border border-border bg-surface shadow-sm p-4 mb-4">
            <div className="flex items-center gap-2 mb-1.5"><span className="w-8 h-8 rounded-[10px] flex items-center justify-center" style={{ background: '#7C3AED1f', color: '#7C3AED' }}><Icon name="users" size={17} /></span><span className="font-display font-800 text-[12px] uppercase tracking-wide" style={{ color: '#7C3AED' }}>Zakup grupowy</span></div>
            <p className="font-display font-700 text-text text-[15px]">{gb.title}</p>
            <p className="text-[13px] text-text-secondary mt-0.5 leading-snug">{gb.desc}</p>
            <div className="flex items-center justify-between text-[12px] mt-3 mb-1"><span className="font-display font-700 text-text">{gb.have}/{gb.need} osób</span><span className="text-text-muted">{gb.deadline}</span></div>
            <div className="h-2.5 rounded-full bg-surface-muted overflow-hidden"><div className="h-full rounded-full bg-accent" style={{ width: gbPct + '%', animation: 'om-grow .8s cubic-bezier(.22,1,.36,1) both' }} /></div>
            <Btn block size="sm" className="mt-3" icon="plus" onClick={() => ctx.toast({ msg: 'Dołączono do zakupu grupowego', icon: 'check' })}>Dołącz</Btn>
          </div>
        )}

        {list.length === 0 ? (
          <EmptyState icon="shoppingBag" title="Nic tu jeszcze nie ma" action={<Btn icon="plus" onClick={() => ctx.openComposer('market')}>Wystaw przedmiot</Btn>}>Zacznij wymianę z sąsiadami — oddaj, sprzedaj lub pożycz coś, czego nie używasz.</EmptyState>
        ) : (
          <div className="grid grid-cols-2 gap-3">
            {list.map(m => (
              <button key={m.id} onClick={() => ctx.toast({ msg: 'Otwieram ogłoszenie', icon: 'shoppingBag', tone: 'info' })} className="focusable text-left bg-surface border border-border rounded-xl shadow-sm overflow-hidden hover:shadow-md hover:-translate-y-0.5 transition-all active:scale-[.98]">
                <div className="relative">{m.label ? <SocPhoto label={m.label} h={110} rounded="rounded-none" /> : <div className="h-[110px] flex items-center justify-center bg-surface-muted text-text-muted"><Icon name="shoppingBag" size={28} /></div>}
                  <span className="absolute top-2 left-2 text-[10px] font-display font-700 px-2 py-0.5 rounded-pill text-white" style={{ background: '#059669' }}>{m.subtype}</span>
                  {m.status === 'Zarezerwowane' && <span className="absolute inset-0 bg-bg/55 flex items-center justify-center"><span className="text-[12px] font-display font-700 text-text bg-surface px-2.5 py-1 rounded-pill border border-border">Zarezerwowane</span></span>}
                </div>
                <div className="p-2.5">
                  <p className="font-display font-700 text-text text-[13px] leading-tight line-clamp-2" style={{ minHeight: 34 }}>{m.title}</p>
                  <p className="font-display font-800 text-[14px] mt-1" style={{ color: m.free ? '#059669' : 'rgb(var(--c-text))' }}>{m.free ? 'Za darmo' : m.price || '—'}</p>
                  <div className="flex items-center gap-1.5 mt-2"><Avatar name={m.author} size={20} /><span className="text-[11px] text-text-muted truncate">{m.flat} · {m.time}</span></div>
                </div>
              </button>
            ))}
          </div>
        )}
        <p className="text-[11px] text-text-muted text-center mt-4 flex items-center justify-center gap-1.5"><Icon name="shield" size={13} />Transakcje między mieszkańcami — zachowaj ostrożność</p>
      </div>
    </div>
  );
}

// ════════════════════ WYDARZENIA — LISTA ════════════════════
function Events({ ctx }) {
  const ah = ADHOC;
  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="flex items-center gap-1 min-h-[44px]"><IconBtn name="arrowLeft" label="Wstecz" onClick={ctx.back} className="-ml-1" /><h1 className="font-display font-800 text-text text-[24px] flex-1">Wydarzenia</h1></div>
      </header>
      <div className="flex-1 overflow-auto app-scroll px-4 pt-2 pb-28">
        {/* ad-hoc dziś */}
        <p className="text-[12px] font-display font-700 text-text-muted uppercase tracking-wide mb-2">Dzieje się dziś</p>
        <div className="rounded-xl p-4 mb-5 border border-accent-warm/30 bg-accent-warm/8">
          <div className="flex items-center gap-2 mb-1"><PostBadge type="live" size="sm" /></div>
          <p className="font-display font-700 text-text text-[16px]">{ah.title}</p>
          <p className="text-[13px] text-text-secondary">{ah.place}</p>
          <div className="flex items-center gap-3 mt-3">
            <div className="flex -space-x-2">{ah.going.slice(0, 4).map((n, i) => <span key={i} className="ring-2 ring-bg rounded-full"><Avatar name={n} size={28} /></span>)}</div>
            <span className="text-[13px] font-display font-700 text-text">{ah.have}/{ah.need} chętnych</span>
            <Btn size="sm" className="ml-auto" onClick={() => ctx.toast({ msg: 'Dołączono — jest 5/6!', icon: 'check' })}>Dołącz</Btn>
          </div>
        </div>
        <p className="text-[12px] font-display font-700 text-text-muted uppercase tracking-wide mb-2">Nadchodzące</p>
        <div className="space-y-2.5">
          {SOC_EVENTS.map(e => (
            <button key={e.id} onClick={() => ctx.go('event', { id: e.id })} className="focusable w-full text-left bg-surface border border-border rounded-xl shadow-sm p-3 flex items-center gap-3 hover:shadow-md hover:-translate-y-0.5 transition-all active:scale-[.99]">
              <div className="shrink-0 w-14 h-14 rounded-[14px] flex flex-col items-center justify-center text-white" style={{ background: '#7C3AED' }}><span className="font-display font-800 text-[20px] leading-none">{e.day}</span><span className="text-[10px] font-700 tracking-wide">{e.month}</span></div>
              <div className="flex-1 min-w-0"><p className="font-display font-700 text-text text-[15px] leading-tight">{e.title}</p><p className="text-[12px] text-text-muted mt-0.5">{e.time} · {e.place}</p>
                <div className="flex items-center gap-2 mt-1.5"><div className="flex -space-x-1.5">{e.attendees.slice(0, 3).map((n, i) => <span key={i} className="ring-2 ring-surface rounded-full"><Avatar name={n} size={20} /></span>)}</div><span className="text-[11px] text-text-secondary font-600">Idzie {e.going}</span></div>
              </div>
              <Icon name="chevronRight" size={18} className="text-text-muted shrink-0" />
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

// ════════════════════ WYDARZENIE — SZCZEGÓŁ (RSVP + potluck) ════════════════════
function EventDetail({ ctx, params }) {
  const e = SOC_EVENT;
  const senior = ctx.senior;
  const [rsvp, setRsvp] = uMo(null);
  const [potluck, setPotluck] = uMo(e.potluck);
  const counts = { ...e.rsvp };
  if (rsvp) counts[rsvp] += 1;
  const claim = (i) => { setPotluck(potluck.map((p, j) => j === i ? { ...p, who: SOC_USER.name } : p)); ctx.toast({ msg: 'Dopisano Ciebie 🙂', icon: 'check' }); };

  const RsvpBtn = ({ k, label, icon, hex }) => {
    const on = rsvp === k;
    return <button onClick={() => { setRsvp(k); ctx.toast({ msg: 'Zapisano odpowiedź', icon: 'check' }); }}
      className={`focusable flex-1 flex flex-col items-center gap-1 py-3 rounded-lg border-2 transition active:scale-95 ${on ? 'text-white' : 'border-border bg-surface text-text-secondary hover:border-text-muted'}`}
      style={on ? { background: hex, borderColor: hex } : {}}><Icon name={icon} size={20} fill={on} />{label}</button>;
  };

  return (
    <div className="flex flex-col h-full bg-bg">
      <SocBar title="Wydarzenie" onBack={ctx.back} right={<IconBtn name="bookmark" label="Zapisz" />} />
      <div className="flex-1 overflow-auto app-scroll px-4 pb-28">
        {/* hero */}
        <div className="flex items-center gap-3.5 pt-4">
          <div className="shrink-0 w-[72px] h-[72px] rounded-[18px] flex flex-col items-center justify-center text-white shadow-md" style={{ background: '#7C3AED' }}>
            <span className="font-display font-800 text-[28px] leading-none">{e.day}</span><span className="text-[11px] font-700 tracking-wide">{e.month}</span></div>
          <div className="flex-1 min-w-0"><PostBadge type="wydarzenie" size="sm" /><h2 className={`font-display font-800 text-text leading-tight mt-1 ${sz(senior,'text-[22px]','text-[20px]')}`}>{e.title}</h2><p className="text-[13px] text-text-secondary mt-0.5">{e.weekday}, {e.time}</p></div>
        </div>
        <div className="flex flex-col gap-1.5 mt-3 text-[13px] text-text-secondary">
          <span className="inline-flex items-center gap-2"><Icon name="mapPin" size={15} className="text-text-muted" />{e.place}</span>
          <span className="inline-flex items-center gap-2"><Avatar name={e.organizer} size={20} />Organizuje: {e.organizer}</span>
        </div>
        <p className={`text-text leading-relaxed mt-3 ${sz(senior,'text-[17px]','text-[15px]')}`} style={{ textWrap: 'pretty' }}>{e.desc}</p>

        {/* RSVP */}
        <div className="mt-5 rounded-xl border border-border bg-surface p-4 shadow-sm">
          <div className="flex items-center justify-between mb-3">
            <p className="font-display font-700 text-text text-[15px]">Idzie {counts.ide} sąsiadów</p>
            <div className="flex -space-x-2">{e.attendees.slice(0, 5).map((n, i) => <span key={i} className="ring-2 ring-surface rounded-full"><Avatar name={n} size={28} /></span>)}<span className="w-7 h-7 rounded-full bg-surface-muted ring-2 ring-surface flex items-center justify-center text-[10px] font-700 text-text-secondary">+{counts.ide - 5}</span></div>
          </div>
          <div className="flex gap-2.5"><RsvpBtn k="ide" label="Będę" icon="checkCircle" hex="#16A34A" /><RsvpBtn k="moze" label="Może" icon="helpCircle" hex="#D97706" /><RsvpBtn k="nie" label="Nie będę" icon="x" hex="#64748B" /></div>
        </div>

        {/* potluck */}
        <div className="mt-4">
          <h3 className="font-display font-700 text-text text-[15px] mb-2.5">Kto co przynosi</h3>
          <div className="space-y-2">
            {potluck.map((p, i) => (
              <div key={i} className="flex items-center gap-3 p-3 rounded-lg border border-border bg-surface">
                <span className={`w-9 h-9 rounded-[10px] flex items-center justify-center shrink-0 ${p.who ? 'bg-brand/12 text-brand' : 'bg-surface-muted text-text-muted'}`}><Icon name={p.who ? 'check' : 'gift'} size={17} stroke={p.who ? 2.6 : 2} /></span>
                <div className="flex-1 min-w-0"><p className="font-display font-700 text-text text-[14px]">{p.item}</p>{p.who && <p className="text-[12px] text-text-muted">{p.who}</p>}</div>
                {!p.who && <button onClick={() => claim(i)} className="focusable text-[12px] font-display font-700 text-brand px-3 h-8 rounded-pill bg-brand/10 active:scale-95">Dopisz się</button>}
              </div>
            ))}
          </div>
          <button onClick={() => ctx.toast({ msg: 'Dodaj pozycję do listy', icon: 'plus', tone: 'info' })} className="focusable w-full mt-2 py-2.5 rounded-lg border border-dashed border-border text-[13px] font-display font-600 text-text-secondary hover:border-brand hover:text-brand transition flex items-center justify-center gap-1.5"><Icon name="plus" size={16} />Dodaj pozycję</button>
        </div>
      </div>
      <div className="shrink-0 px-4 pt-3 pb-7 bg-surface/90 backdrop-blur-xl border-t border-border flex gap-2.5">
        <Btn variant="secondary" block icon="clock" onClick={() => ctx.toast({ msg: 'Przypomnimy Ci dzień wcześniej', icon: 'check' })}>Przypomnij mi</Btn>
        <Btn block icon="calendar" onClick={() => ctx.toast({ msg: 'Dodano do kalendarza', icon: 'check' })}>Do kalendarza</Btn>
      </div>
    </div>
  );
}

// ════════════════════ KĄCIK ZWIERZAKÓW ════════════════════
function Pets({ ctx }) {
  const alert = ctx.flags.petAlert && PET_ALERT.active;
  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="flex items-center gap-1 min-h-[44px]"><IconBtn name="arrowLeft" label="Wstecz" onClick={ctx.back} className="-ml-1" /><h1 className="font-display font-800 text-text text-[24px] flex-1">Kącik zwierzaków</h1></div>
      </header>
      <div className="flex-1 overflow-auto app-scroll px-4 pt-2 pb-28">
        {/* PILNY ALERT */}
        {alert && (
          <div className="rounded-xl p-4 mb-5 text-white shadow-md anim-rise" style={{ background: '#E11D48' }}>
            <div className="flex items-center gap-2 mb-2"><Icon name="alert" size={18} stroke={2.4} /><span className="font-display font-800 text-[12px] uppercase tracking-wide">Pilne — zaginął pupil</span></div>
            <div className="flex gap-3">
              <div className="shrink-0"><SocPhoto label={PET_ALERT.label} h={84} className="w-[84px]" rounded="rounded-lg" /></div>
              <div className="flex-1 min-w-0"><p className="font-display font-800 text-[18px] leading-tight">Zaginął: {PET_ALERT.name}</p><p className="text-[13px] opacity-90 mt-0.5">{PET_ALERT.breed}</p><p className="text-[12px] opacity-90 mt-1.5"><b>Ostatnio:</b> {PET_ALERT.lastSeen}</p></div>
            </div>
            <Btn block className="mt-3 !bg-white !text-rose-600" icon="mapPin" onClick={() => ctx.toast({ msg: 'Dzięki! Powiadomiliśmy właściciela', icon: 'check' })}>Widziałem!</Btn>
          </div>
        )}

        {/* nasze zwierzaki */}
        <h3 className="font-display font-700 text-text text-[15px] mb-2.5">Zwierzaki z osiedla</h3>
        <div className="grid grid-cols-2 gap-3 mb-5">
          {PETS.map(p => (
            <div key={p.id} className="bg-surface border border-border rounded-xl shadow-sm overflow-hidden">
              <SocPhoto label={p.label} h={96} rounded="rounded-none" />
              <div className="p-3"><div className="flex items-center gap-1.5"><span style={{ color: '#FB7185' }}><Icon name="pawPrint" size={15} /></span><p className="font-display font-700 text-text text-[14px]">{p.name}</p></div><p className="text-[12px] text-text-muted mt-0.5">{p.owner} · {p.flat}</p></div>
            </div>
          ))}
        </div>

        {/* spacery */}
        <div className="rounded-xl border border-border bg-surface p-4 mb-5 flex items-center gap-3">
          <span className="w-11 h-11 rounded-[13px] flex items-center justify-center shrink-0" style={{ background: '#FB71851f', color: '#FB7185' }}><Icon name="pawPrint" size={22} /></span>
          <div className="flex-1"><p className="font-display font-700 text-text text-[14px]">Szukam towarzysza na spacer</p><p className="text-[12px] text-text-muted">Dobierzcie się w pary do wspólnych spacerów z psami.</p></div>
          <Btn size="sm" variant="secondary" onClick={() => ctx.toast({ msg: 'Dołączasz do grupy spacerowej', icon: 'check', tone: 'info' })}>Dołącz</Btn>
        </div>

        {/* polecani */}
        <h3 className="font-display font-700 text-text text-[15px] mb-2.5">Polecani przez sąsiadów</h3>
        <div className="space-y-2.5">
          {VETS.map((v, i) => (
            <Card key={i} className="p-3.5 flex items-center gap-3">
              <span className="w-10 h-10 rounded-[12px] bg-surface-muted text-text-secondary flex items-center justify-center shrink-0"><Icon name="heart" size={19} /></span>
              <div className="flex-1 min-w-0"><p className="font-display font-700 text-text text-[14px]">{v.name}</p><p className="text-[12px] text-text-muted">{v.cat}</p></div>
              <div className="text-right"><span className="inline-flex items-center gap-1 text-[13px] font-display font-700 text-text"><Icon name="star" size={14} fill className="text-accent-warm" />{v.rating}</span><p className="text-[11px] text-text-muted">{v.reviews} opinii</p></div>
            </Card>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Marketplace, Events, EventDetail, Pets });
