// social-feed.jsx — wspólne UI social + Feed/Tablica + Post (szczegół) + Composer
const { useState: uF } = React;

// placeholder zdjęcia (paski + opis mono)
function SocPhoto({ 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>
  );
}

// Badge typu posta — kolor (hex) + ikona + tekst
function PostBadge({ type, size = 'md' }) {
  const t = POST_TYPES[type]; if (!t) return null;
  const sz2 = size === 'sm' ? 'text-[11px] px-2 py-0.5 gap-1' : 'text-xs px-2.5 py-1 gap-1.5';
  return (
    <span className={`inline-flex items-center font-display font-700 rounded-pill ${sz2}`} style={{ color: t.hex, background: t.hex + '1f' }}>
      {t.pulse
        ? <span className="relative flex w-2 h-2"><span className="absolute inline-flex h-full w-full rounded-full opacity-75 animate-ping" style={{ background: t.hex }} /><span className="relative inline-flex rounded-full h-2 w-2" style={{ background: t.hex }} /></span>
        : <Icon name={t.icon} size={size === 'sm' ? 12 : 13} stroke={2.4} />}
      <span className="leading-none whitespace-nowrap">{t.label}</span>
    </span>
  );
}

// Pasek reakcji
function ReactionBar({ post, ctx, compact }) {
  const state = ctx.reactions[post.id] || { my: post.myReaction, counts: post.reactions };
  const toggle = (rid) => ctx.react(post.id, rid, post);
  const total = Object.values(state.counts).reduce((a, b) => a + b, 0);
  if (compact) {
    return (
      <div className="flex items-center gap-3 text-text-muted">
        <button onClick={() => toggle('lubie')} className={`focusable inline-flex items-center gap-1 text-[12px] font-display font-600 active:scale-90 transition ${state.my ? 'text-brand' : ''}`}>
          <Icon name="thumbsUp" size={15} fill={!!state.my} stroke={2} />{total > 0 ? total : ''}
        </button>
        <span className="inline-flex items-center gap-1 text-[12px]"><Icon name="messageCircle" size={15} />{post.comments}</span>
      </div>
    );
  }
  return (
    <div className="flex items-center gap-1.5 flex-wrap">
      {REACTIONS.map(r => {
        const on = state.my === r.id, c = state.counts[r.id] || 0;
        return (
          <button key={r.id} aria-label={r.label} aria-pressed={on} onClick={() => toggle(r.id)}
            className={`focusable inline-flex items-center gap-1.5 h-9 px-3 rounded-pill border text-[13px] font-display font-600 transition active:scale-95
              ${on ? 'border-brand bg-brand/10 text-brand' : 'border-border bg-surface text-text-secondary hover:border-text-muted'}`}>
            <Icon name={r.icon} size={16} fill={on} stroke={2} />{r.label}{c > 0 && <span className="text-[12px] opacity-80">{c}</span>}
          </button>
        );
      })}
    </div>
  );
}

// Menu ⋯ (zgłoś / edytuj / usuń)
function PostMenu({ post, ctx, own }) {
  const [open, setOpen] = uF(false);
  return (
    <div className="relative">
      <IconBtn name="more" label="Więcej opcji" size={20} className="!w-9 !h-9" onClick={() => setOpen(!open)} />
      {open && (
        <>
          <div className="fixed inset-0 z-40" onClick={() => setOpen(false)} />
          <div className="absolute right-0 top-10 z-50 w-44 bg-surface border border-border rounded-lg shadow-lg p-1.5 anim-fade">
            {own ? <>
              <button onClick={() => { setOpen(false); ctx.toast({ msg: 'Edycja posta', icon: 'pencil', tone: 'info' }); }} className="focusable w-full flex items-center gap-2.5 px-3 h-9 rounded-md text-[13px] font-600 text-text hover:bg-surface-muted"><Icon name="pencil" size={16} />Edytuj</button>
              <button onClick={() => { setOpen(false); ctx.toast({ msg: 'Post usunięty', icon: 'trash' }); }} className="focusable w-full flex items-center gap-2.5 px-3 h-9 rounded-md text-[13px] font-600 text-danger hover:bg-danger/8"><Icon name="trash" size={16} />Usuń</button>
            </> : (
              <button onClick={() => { setOpen(false); ctx.report(post); }} className="focusable w-full flex items-center gap-2.5 px-3 h-9 rounded-md text-[13px] font-600 text-danger hover:bg-danger/8"><Icon name="flag" size={16} />Zgłoś</button>
            )}
          </div>
        </>
      )}
    </div>
  );
}

// ── POST CARD (3 układy: komfortowy / kompaktowy / magazyn) ──
function PostCard({ post, ctx }) {
  const layout = ctx.feedLayout, senior = ctx.senior;
  const t = POST_TYPES[post.type];
  const open = () => ctx.go('post', { id: post.id });
  const reported = ctx.reported[post.id];

  if (reported) return (
    <Card className="p-4 anim-fade">
      <div className="flex items-center gap-3 text-text-muted">
        <Icon name="eyeOff" size={20} /><div className="flex-1"><p className="font-display font-700 text-[13px] text-text-secondary">Ten post został ukryty do weryfikacji</p><p className="text-[12px]">Dziękujemy za zgłoszenie — moderator je sprawdzi.</p></div>
      </div>
    </Card>
  );

  // KOMPAKTOWY
  if (layout === 'kompakt') {
    return (
      <div className="bg-surface border border-border rounded-lg shadow-sm p-3 hover:bg-surface-muted/40 transition">
        <button onClick={open} className="focusable w-full text-left">
          <div className="flex items-center gap-2 mb-1.5">
            <Avatar name={post.author} size={28} />
            <span className={`font-display font-700 text-text ${sz(senior,'text-[13px]','text-[15px]')}`}>{post.author}</span>
            <span className="text-[11px] text-text-muted">· {post.flat}</span>
            <span className="ml-auto"><PostBadge type={post.type} size="sm" /></span>
          </div>
          {post.title && <p className={`font-display font-700 text-text leading-tight ${sz(senior,'text-[14px]','text-[15px]')}`}>{post.title}</p>}
          <p className={`text-text-secondary leading-snug line-clamp-1 ${sz(senior,'text-[14px]','text-[13.5px]')}`}>{post.body}</p>
        </button>
        <div className="flex items-center justify-between mt-2"><span className="text-[11px] text-text-muted">{post.time}</span><ReactionBar post={post} ctx={ctx} compact /></div>
      </div>
    );
  }

  // MAGAZYN (image-forward)
  if (layout === 'magazyn' && post.photos > 0) {
    return (
      <div className="bg-surface border border-border rounded-xl shadow-sm overflow-hidden hover:shadow-md hover:-translate-y-0.5 transition-all">
        <button onClick={open} className="focusable w-full text-left block">
          <div className="relative"><SocPhoto label={t.label + ' · zdjęcie'} h={172} rounded="rounded-none" />
            <span className="absolute top-3 left-3"><PostBadge type={post.type} /></span>
            {post.resolved && <span className="absolute top-3 right-3 inline-flex items-center gap-1 text-[11px] font-700 px-2 py-1 rounded-pill bg-success text-white"><Icon name="check" size={12} stroke={3} />Rozwiązane</span>}
          </div>
          <div className="px-4 pt-4">
            {post.title && <p className={`font-display font-700 text-text leading-tight ${sz(senior,'text-[16px]','text-[17px]')}`} style={{ textWrap: 'pretty' }}>{post.title}</p>}
            <p className={`text-text-secondary leading-snug mt-1 line-clamp-2 ${sz(senior,'text-[15px]','text-[14px]')}`}>{post.body}</p>
            <div className="flex items-center gap-2 mt-3"><Avatar name={post.author} size={26} /><span className="text-[12px] text-text-secondary font-600">{post.author}</span><span className="text-[11px] text-text-muted">· {post.flat} · {post.time}</span></div>
          </div>
        </button>
        <div className="px-4 pb-4 pt-3"><div className="pt-3 border-t border-border"><ReactionBar post={post} ctx={ctx} compact /></div></div>
      </div>
    );
  }

  // KOMFORTOWY (domyślny)
  return (
    <div className="bg-surface border border-border rounded-xl shadow-sm p-4 hover:shadow-md transition-all">
      <div className="flex items-center gap-2.5 mb-2.5">
        <Avatar name={post.author} size={senior ? 44 : 40} />
        <div className="flex-1 min-w-0">
          <p className={`font-display font-700 text-text leading-tight ${sz(senior,'text-[15px]','text-[15px]')}`}>{post.author} <span className="font-500 text-text-muted text-[13px]">· {post.flat}</span></p>
          <p className="text-[12px] text-text-muted">{post.time}</p>
        </div>
        <PostBadge type={post.type} />
        <PostMenu post={post} ctx={ctx} />
      </div>
      <button onClick={open} className="focusable block w-full text-left">
        {post.title && <p className={`font-display font-700 text-text leading-snug ${sz(senior,'text-[18px]','text-[17px]')}`} style={{ textWrap: 'pretty' }}>{post.title}</p>}
        <p className={`text-text leading-relaxed mt-1 ${sz(senior,'text-[17px]','text-[15px]')}`} style={{ textWrap: 'pretty' }}>{post.body}</p>
        {post.market && <div className="flex items-center gap-2 mt-2.5">{post.market.free ? <span className="font-display font-800 text-[15px]" style={{ color: '#059669' }}>Za darmo</span> : post.market.price && <span className="font-display font-800 text-text text-[15px]">{post.market.price}</span>}<Badge tone="success" dot size="sm">{post.market.status}</Badge></div>}
        {post.resolved && <span className="inline-flex items-center gap-1.5 mt-2.5 text-[12px] font-display font-700 text-success"><Icon name="checkCircle" size={14} stroke={2.4} />Rozwiązane</span>}
        {post.photos > 0 && <div className={`grid gap-2 mt-3 ${post.photos > 1 ? 'grid-cols-2' : 'grid-cols-1'}`}>{Array.from({ length: Math.min(post.photos, 2) }).map((_, i) => <SocPhoto key={i} label={`${t.label} · zdjęcie ${i + 1}`} h={post.photos > 1 ? 120 : 180} />)}</div>}
      </button>
      <div className="flex items-center justify-between mt-3.5">
        <ReactionBar post={post} ctx={ctx} />
        <button onClick={open} className="focusable inline-flex items-center gap-1.5 h-9 px-3 rounded-pill text-text-secondary hover:bg-surface-muted text-[13px] font-display font-600 active:scale-95"><Icon name="messageCircle" size={17} />{post.comments}</button>
      </div>
    </div>
  );
}

// ════════════════════ FEED / TABLICA ════════════════════
const FEED_TABS = [['tablica', 'Tablica'], ['market', 'Marketplace'], ['wydarzenia', 'Wydarzenia'], ['zwierzaki', 'Zwierzaki']];
function Feed({ ctx }) {
  const [filter, setFilter] = uF('all');
  const [scope, setScope] = uF('wspolnota');
  const loading = ctx.flags.loading, empty = ctx.flags.emptyFeed;
  const unread = 3;

  const types = [['all', 'Wszystko', null]].concat(Object.entries(POST_TYPES).filter(([k]) => k !== 'live').map(([k, v]) => [k, v.label, v]));
  const list = FEED.filter(p => filter === 'all' || p.type === filter);
  const pinned = list.filter(p => p.pinned), rest = list.filter(p => !p.pinned);

  return (
    <div className="flex flex-col h-full bg-bg">
      {/* górny pasek */}
      <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]">
          <div><h1 className="font-display font-800 text-text text-[24px] leading-none">Społeczność</h1><p className="text-[12px] text-text-muted mt-0.5">Zielone Tarasy · sąsiedzi</p></div>
          <button aria-label={`Powiadomienia, ${unread} nowe`} onClick={() => ctx.toast({ msg: 'Centrum powiadomień', icon: 'bell', tone: 'info' })} className="focusable relative w-11 h-11 rounded-pill flex items-center justify-center text-text-secondary hover:bg-surface-muted active:scale-90">
            <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>
      {/* zakładki */}
      <div className="shrink-0 flex gap-1 px-4 border-b border-border">
        {FEED_TABS.map(([k, l]) => (
          <button key={k} onClick={() => k === 'tablica' ? null : ctx.setTab(k)}
            className={`focusable relative px-3 py-2.5 text-[14px] font-display font-700 transition ${k === 'tablica' ? 'text-brand' : 'text-text-muted hover:text-text'}`}>
            {l}{k === 'tablica' && <span className="absolute left-2 right-2 -bottom-px h-0.5 rounded bg-brand" />}
          </button>
        ))}
      </div>

      <div className="flex-1 overflow-auto app-scroll px-4 pb-28">
        {/* selektor zasięgu + filtry */}
        <div className="flex gap-2 overflow-x-auto app-scroll py-3 -mx-4 px-4">
          {[['wspolnota', 'Cała wspólnota', 'users'], ['budynek', 'Mój budynek', 'building'], ['klatka', 'Moja klatka', 'home']].map(([k, l, ic]) =>
            <Chip key={k} active={scope === k} icon={ic} onClick={() => setScope(k)}>{l}</Chip>)}
        </div>
        <div className="flex gap-2 overflow-x-auto app-scroll pb-3 -mx-4 px-4">
          {types.map(([k, l, v]) => (
            <button key={k} onClick={() => setFilter(k)}
              className={`focusable shrink-0 inline-flex items-center gap-1.5 h-8 px-3 rounded-pill text-[12.5px] font-display font-600 border transition active:scale-95 ${filter === k ? 'text-white border-transparent' : 'bg-surface border-border text-text-secondary'}`}
              style={filter === k ? { background: v ? v.hex : 'rgb(var(--c-text))' } : {}}>
              {v && <Icon name={v.icon} size={14} stroke={2.2} />}{l}
            </button>
          ))}
        </div>

        {/* live info */}
        {!loading && !empty && filter === 'all' && (
          <div className="mb-3 rounded-xl border border-accent-warm/30 bg-accent-warm/8 p-3">
            <div className="flex items-center gap-2 mb-2"><PostBadge type="live" size="sm" /><span className="text-[12px] text-text-muted ml-auto">krótkie wpisy sytuacyjne</span></div>
            {LIVE_INFO.map(li => (
              <div key={li.id} className="flex items-center gap-2 py-1.5 text-[13px]">
                <span className="text-text leading-snug flex-1">{li.text}</span>
                <button onClick={() => ctx.toast({ msg: 'Potwierdzono — widzę to', icon: 'check' })} className="focusable shrink-0 text-[11px] font-display font-700 text-accent-warm px-2 py-1 rounded-pill bg-accent-warm/15 active:scale-95">Widzę to · {li.confirms}</button>
              </div>
            ))}
          </div>
        )}

        {loading ? (
          <div className="space-y-3 pt-1">{[0,1,2].map(i => <Card key={i} className="p-4"><div className="flex gap-2.5 mb-3"><Sk w={40} h={40} r={20} /><div className="flex-1"><Sk w="50%" h={14} /><Sk w="30%" h={11} className="mt-1.5" /></div></div><Sk w="95%" h={16} /><Sk w="80%" h={16} className="mt-2" /><Sk w="100%" h={120} r={12} className="mt-3" /></Card>)}</div>
        ) : empty ? (
          <EmptyState icon="users" title="Tu zaczyna się Wasza społeczność" action={<Btn icon="plus" onClick={() => ctx.openComposer()}>Napisz pierwszy post</Btn>}>Bądź pierwszy — przywitaj sąsiadów albo zadaj pytanie. Najlepsze osiedla zaczynają się od jednego „cześć".</EmptyState>
        ) : (
          <div className="space-y-3">
            {pinned.map(p => (
              <div key={p.id} className="relative">
                <span className="absolute -top-2 left-3 z-10 inline-flex items-center gap-1 text-[10px] font-display font-700 text-accent-warm bg-bg px-2 py-0.5 rounded-pill"><Icon name="pin" size={11} />Przypięte</span>
                <div className="rounded-xl ring-1 ring-accent/30"><PostCard post={p} ctx={ctx} /></div>
              </div>
            ))}
            {rest.map(p => <PostCard key={p.id} post={p} ctx={ctx} />)}
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { SocPhoto, PostBadge, ReactionBar, PostMenu, PostCard, Feed, FEED_TABS });
