// social-post.jsx — Post (szczegół + komentarze) i Composer (2 warianty)
const { useState: uP } = React;

// pasek aplikacji
function SocBar({ title, onBack, right, sub }) {
  return (
    <header className="shrink-0 pt-[52px] 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>
  );
}

// ════════════════════ POST — SZCZEGÓŁ + KOMENTARZE ════════════════════
function PostDetail({ ctx, params }) {
  const post = FEED.find(p => p.id === params.id);
  const t = POST_TYPES[post.type], senior = ctx.senior;
  const reported = ctx.reported[post.id];
  const [comments, setComments] = uP(COMMENTS[post.id] || []);
  const [draft, setDraft] = uP('');
  const send = () => { if (!draft.trim()) return; setComments([...comments, { id: Date.now(), author: SOC_USER.name, flat: SOC_USER.flat, time: 'teraz', text: draft.trim(), reactions: 0 }]); setDraft(''); ctx.toast({ msg: 'Komentarz dodany', icon: 'check' }); };

  return (
    <div className="flex flex-col h-full bg-bg">
      <SocBar title={t.label} onBack={ctx.back} right={<PostMenu post={post} ctx={ctx} own={post.author === SOC_USER.name} />} />
      <div className="flex-1 overflow-auto app-scroll" aria-live="polite">
        {reported ? (
          <div className="p-4"><Card className="p-5 text-center">
            <span className="inline-flex items-center justify-center w-14 h-14 rounded-full bg-surface-muted text-text-muted mx-auto mb-3"><Icon name="eyeOff" size={28} /></span>
            <p className="font-display font-700 text-text text-[16px]">Ten post został ukryty do weryfikacji</p>
            <p className="text-[13px] text-text-secondary mt-1.5">Zgłoszenie trafiło do moderatora. Dziękujemy, że dbasz o społeczność.</p>
            <Btn variant="secondary" className="mt-4" icon="arrowLeft" onClick={ctx.back}>Wróć do tablicy</Btn>
          </Card></div>
        ) : (
          <div className="px-4 pb-4">
            {/* nagłówek */}
            <div className="flex items-center gap-2.5 pt-4 mb-3">
              <Avatar name={post.author} size={44} />
              <div className="flex-1 min-w-0"><p className="font-display font-700 text-text 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} />
            </div>
            {post.title && <h2 className={`font-display font-800 text-text leading-tight ${sz(senior,'text-[22px]','text-[20px]')}`} style={{ textWrap: 'balance' }}>{post.title}</h2>}
            <p className={`text-text leading-relaxed mt-1.5 ${sz(senior,'text-[18px]','text-[16px]')}`} style={{ textWrap: 'pretty' }}>{post.body}</p>
            {post.resolved && <div className="mt-3"><Banner tone="success" icon="checkCircle" title="Rozwiązane">Sprawa została zamknięta przez autora.</Banner></div>}
            {post.photos > 0 && <div className={`grid gap-2 mt-3 ${post.photos > 1 ? 'grid-cols-2' : 'grid-cols-1'}`}>{Array.from({ length: post.photos }).map((_, i) => <SocPhoto key={i} label={`${t.label} · zdjęcie ${i + 1}`} h={post.photos > 1 ? 130 : 200} />)}</div>}

            <div className="py-3.5 border-y border-border mt-4"><ReactionBar post={post} ctx={ctx} /></div>

            {/* komentarze */}
            <h3 className="font-display font-700 text-text text-[15px] mt-4 mb-3">Komentarze · {comments.length}</h3>
            <div className="space-y-3">
              {comments.length === 0 && <p className="text-[13px] text-text-muted text-center py-4">Brak komentarzy. Bądź pierwszy!</p>}
              {comments.map(c => (
                <div key={c.id} className="flex gap-2.5">
                  <Avatar name={c.author} size={34} />
                  <div className="flex-1 min-w-0">
                    <div className="bg-surface border border-border rounded-xl rounded-tl-sm p-3">
                      <div className="flex items-center justify-between gap-2"><span className="font-display font-700 text-[13px] text-text">{c.author} <span className="font-500 text-text-muted">· {c.flat}</span></span></div>
                      <p className={`text-text-secondary mt-1 leading-snug ${sz(senior,'text-[15px]','text-[13.5px]')}`}>{c.text}</p>
                    </div>
                    <div className="flex items-center gap-3 mt-1 px-1">
                      <span className="text-[11px] text-text-muted">{c.time}</span>
                      <button onClick={() => ctx.toast({ msg: 'Dzięki!', icon: 'handHeart' })} className="focusable text-[11px] font-display font-600 text-text-muted hover:text-brand inline-flex items-center gap-1"><Icon name="thumbsUp" size={13} />{c.reactions || ''}</button>
                      <button onClick={() => ctx.toast({ msg: 'Zgłoszono komentarz', icon: 'flag', tone: 'info' })} className="focusable text-[11px] font-display font-600 text-text-muted hover:text-danger">Zgłoś</button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>

      {/* sticky pole komentarza */}
      {!reported && (
        <div className="shrink-0 px-3 pt-2.5 pb-7 bg-surface/90 backdrop-blur-xl border-t border-border flex items-center gap-2">
          <IconBtn name="paperclip" label="Załącz zdjęcie" size={20} />
          <input value={draft} onChange={e => setDraft(e.target.value)} onKeyDown={e => e.key === 'Enter' && send()} placeholder="Napisz komentarz…" className="focusable flex-1 h-11 px-4 rounded-pill bg-surface-muted border border-border text-[14px] text-text placeholder:text-text-muted" />
          <button aria-label="Wyślij" onClick={send} disabled={!draft.trim()} className="focusable w-11 h-11 rounded-pill bg-brand text-brand-fg flex items-center justify-center disabled:opacity-40 active:scale-90 transition shrink-0"><Icon name="send" size={19} /></button>
        </div>
      )}
    </div>
  );
}

// ════════════════════ COMPOSER (krokowy / jednoekranowy) ════════════════════
const COMPOSER_TYPES = ['pytanie', 'polecam', 'dyskusja', 'wydarzenie', 'zguba', 'market'];
const SCOPE_OPTS = [['wspolnota', 'Cała wspólnota', 248], ['budynek', 'Mój budynek', 96], ['klatka', 'Moja klatka', 24]];

function TypePicker({ type, setType, senior }) {
  return (
    <div className="grid grid-cols-3 gap-2.5">
      {COMPOSER_TYPES.map(k => {
        const v = POST_TYPES[k], on = type === k;
        return (
          <button key={k} onClick={() => setType(k)} className={`focusable flex flex-col items-center gap-2 py-3.5 rounded-lg border-2 transition active:scale-95 ${on ? '' : 'border-border bg-surface hover:border-text-muted'}`}
            style={on ? { borderColor: v.hex, background: v.hex + '14' } : {}}>
            <span className="w-10 h-10 rounded-[12px] flex items-center justify-center" style={{ background: on ? v.hex : v.hex + '1f', color: on ? '#fff' : v.hex }}><Icon name={v.icon} size={20} /></span>
            <span className={`font-display font-700 ${sz(senior,'text-[12px]','text-[12px]')}`} style={{ color: on ? v.hex : 'rgb(var(--c-text-secondary))' }}>{v.label}</span>
          </button>
        );
      })}
    </div>
  );
}

// pola kontekstowe zależne od typu
function ContextFields({ type, st, set }) {
  if (type === 'market') return (
    <div className="space-y-3 anim-rise">
      <div><label className="text-[13px] font-display font-700 text-text">Rodzaj</label>
        <div className="flex gap-2 mt-1.5 flex-wrap">{['Oddam', 'Sprzedam', 'Kupię', 'Pożyczę'].map(s => <Chip key={s} active={st.subtype === s} onClick={() => set('subtype', s)}>{s}</Chip>)}</div></div>
      <div className="flex items-center gap-3">
        <div className="flex-1"><label className="text-[13px] font-display font-700 text-text">Cena</label>
          <input value={st.free ? '' : (st.price || '')} disabled={st.free} onChange={e => set('price', e.target.value)} placeholder="np. 120 zł" className="focusable w-full h-11 px-4 mt-1.5 rounded-md bg-surface border border-border text-[14px] text-text placeholder:text-text-muted disabled:bg-surface-muted" /></div>
        <button onClick={() => set('free', !st.free)} className={`focusable mt-7 inline-flex items-center gap-2 h-11 px-4 rounded-md border text-[13px] font-display font-700 ${st.free ? 'border-emerald-500 bg-emerald-500/10' : 'border-border bg-surface text-text-secondary'}`} style={st.free ? { color: '#059669', borderColor: '#059669', background: '#0596691a' } : {}}><Icon name={st.free ? 'checkCircle' : 'gift'} size={17} />Za darmo</button>
      </div>
    </div>
  );
  if (type === 'wydarzenie') return (
    <div className="grid grid-cols-2 gap-3 anim-rise">
      <div><label className="text-[13px] font-display font-700 text-text">Data</label><input type="date" value={st.date || ''} onChange={e => set('date', e.target.value)} className="focusable w-full h-11 px-3 mt-1.5 rounded-md bg-surface border border-border text-[14px] text-text" /></div>
      <div><label className="text-[13px] font-display font-700 text-text">Godzina</label><input type="time" value={st.htime || ''} onChange={e => set('htime', e.target.value)} className="focusable w-full h-11 px-3 mt-1.5 rounded-md bg-surface border border-border text-[14px] text-text" /></div>
      <div className="col-span-2"><label className="text-[13px] font-display font-700 text-text">Miejsce</label><input value={st.place || ''} onChange={e => set('place', e.target.value)} placeholder="np. Sala wspólna, dziedziniec…" className="focusable w-full h-11 px-4 mt-1.5 rounded-md bg-surface border border-border text-[14px] text-text placeholder:text-text-muted" /></div>
    </div>
  );
  if (type === 'zguba') return (
    <div className="anim-rise"><label className="text-[13px] font-display font-700 text-text">Lokalizacja na osiedlu</label>
      <input value={st.place || ''} onChange={e => set('place', e.target.value)} placeholder="np. plac zabaw, parking bud. B…" className="focusable w-full h-11 px-4 mt-1.5 rounded-md bg-surface border border-border text-[14px] text-text placeholder:text-text-muted" /></div>
  );
  return null;
}

function PhotoAdder({ photos, setPhotos }) {
  return (
    <div className="flex gap-2.5 flex-wrap">
      {photos.map((p, i) => (
        <div key={i} className="relative"><SocPhoto label="zdjęcie" h={72} className="w-[72px]" rounded="rounded-md" />
          <button aria-label="Usuń" onClick={() => setPhotos(photos.filter((_, j) => j !== i))} className="absolute -top-1.5 -right-1.5 w-6 h-6 rounded-full bg-text text-bg flex items-center justify-center shadow"><Icon name="x" size={12} stroke={2.6} /></button></div>
      ))}
      {photos.length < 4 && <button onClick={() => setPhotos([...photos, 1])} className="focusable w-[72px] h-[72px] rounded-md border-2 border-dashed border-border flex flex-col items-center justify-center gap-0.5 text-text-muted hover:border-brand hover:text-brand transition active:scale-95"><Icon name="camera" size={22} /><span className="text-[10px] font-display font-600">Dodaj</span></button>}
    </div>
  );
}

function Composer({ ctx }) {
  const stepped = ctx.composerMode === 'krokowy', senior = ctx.senior;
  const [step, setStep] = uP(stepped ? 1 : 2);
  const [type, setType] = uP(null);
  const [body, setBody] = uP('');
  const [photos, setPhotos] = uP([]);
  const [scope, setScope] = uP('wspolnota');
  const [ctxFields, setCtxFields] = uP({ free: false });
  const setF = (k, v) => setCtxFields(s => ({ ...s, [k]: v }));
  const count = SCOPE_OPTS.find(s => s[0] === scope)[2];

  const publish = () => { ctx.closeComposer(); ctx.toast({ msg: 'Opublikowano post', icon: 'check' }); ctx.celebrate(); };
  const canPublish = type && body.trim().length > 2;

  // KROK 1 (tylko tryb krokowy): wybór typu
  if (stepped && step === 1) {
    return (
      <div className="px-1 pb-2">
        <p className="text-[13px] text-text-secondary mb-3">Co chcesz dodać?</p>
        <TypePicker type={type} setType={(k) => { setType(k); setStep(2); }} senior={senior} />
      </div>
    );
  }

  return (
    <div className="px-1 pb-2">
      {/* tryb jednoekranowy: picker u góry; krokowy: nagłówek wybranego typu z możliwością zmiany */}
      {!stepped ? (
        <div className="mb-4"><p className="text-[13px] font-display font-700 text-text mb-2">Typ posta</p><TypePicker type={type} setType={setType} senior={senior} /></div>
      ) : (
        <button onClick={() => setStep(1)} className="focusable inline-flex items-center gap-2 mb-3 text-[13px] font-display font-600 text-brand"><Icon name="chevronLeft" size={16} />Zmień typ {type && <PostBadge type={type} size="sm" />}</button>
      )}

      <div className="flex items-start gap-2.5 mb-3"><Avatar name={SOC_USER.name} size={38} />
        <textarea autoFocus value={body} onChange={e => setBody(e.target.value)} rows={senior ? 4 : 3} placeholder={type === 'pytanie' ? 'O co chcesz zapytać sąsiadów?' : 'Podziel się czymś z sąsiadami…'}
          className={`focusable flex-1 p-3 rounded-md bg-surface border border-border text-text placeholder:text-text-muted resize-none leading-relaxed ${sz(senior,'text-[17px]','text-[15px]')}`} /></div>

      {type && <div className="mb-4"><ContextFields type={type} st={ctxFields} set={setF} /></div>}

      <div className="mb-4"><PhotoAdder photos={photos} setPhotos={setPhotos} /></div>

      <div className="mb-4">
        <p className="text-[13px] font-display font-700 text-text mb-2">Zasięg</p>
        <div className="flex gap-2">{SCOPE_OPTS.map(([k, l, n]) => <button key={k} onClick={() => setScope(k)} className={`focusable flex-1 py-2.5 rounded-lg border text-[12.5px] font-display font-700 transition ${scope === k ? 'border-brand bg-brand/8 text-brand' : 'border-border bg-surface text-text-secondary'}`}>{l}<span className="block text-[10px] font-500 text-text-muted">{n} osób</span></button>)}</div>
      </div>

      <p className="text-[12px] text-text-muted flex items-center gap-1.5 mb-3"><Icon name="info" size={13} />Obowiązuje regulamin społeczności</p>
      <div className="flex gap-2.5">
        <Btn variant="secondary" block onClick={() => { ctx.closeComposer(); ctx.toast({ msg: 'Zapisano roboczy', icon: 'bookmark', tone: 'info' }); }}>Zapisz roboczy</Btn>
        <Btn block icon="send" disabled={!canPublish} onClick={publish}>Opublikuj</Btn>
      </div>
    </div>
  );
}

Object.assign(window, { SocBar, PostDetail, Composer, TypePicker, COMPOSER_TYPES });
