// Posts list — grid + filters.
const { useState: useStatePo } = React;

function Posts({ org, data, onOpen }) {
  const { Button, IconButton, Card, Badge, Pill, TextInput, SectionHead, EmptyState } = window.UI;
  const I = window.Icons;
  const { SlideThumb } = window.Carousel;

  const [filter, setFilter] = useStatePo('all');
  const [net, setNet] = useStatePo('all');
  const [q, setQ] = useStatePo('');

  const filtered = data.posts.filter((p) => {
    if (filter !== 'all' && p.status !== filter) return false;
    if (net !== 'all') {
      if (net === 'ig' && !(p.network === 'ig' || p.network === 'both')) return false;
      if (net === 'tg' && !(p.network === 'tg' || p.network === 'both')) return false;
    }
    if (q && !p.title.toLowerCase().includes(q.toLowerCase())) return false;
    return true;
  });

  return (
    <div className="max-w-[1280px] mx-auto px-5 sm:px-8 py-8">
      <SectionHead
        kicker="посты"
        title="Все карусели"
        sub="Черновики, готовые к публикации, и уже отправленные."
        right={<Button icon={<I.Sparkles size={14}/>} onClick={() => onOpen.navigate('generate')}>Новая карусель</Button>}
      />

      <div className="flex flex-wrap items-center gap-2 mb-6">
        <div className="flex items-center gap-2 overflow-x-auto no-scrollbar">
          {[
            { v: 'all', label: 'Все', count: data.posts.length },
            { v: 'pending', label: 'Ждут одобрения', count: data.posts.filter(p => p.status === 'pending').length },
            { v: 'ready', label: 'Готовы', count: data.posts.filter(p => p.status === 'ready').length },
            { v: 'draft', label: 'Черновики', count: data.posts.filter(p => p.status === 'draft').length },
            { v: 'sent', label: 'Опубликованы', count: data.posts.filter(p => p.status === 'sent').length },
          ].map((f) => (
            <Pill key={f.v} active={filter === f.v} onClick={() => setFilter(f.v)}>{f.label} <span className="text-[11px] opacity-60 tabular-nums">{f.count}</span></Pill>
          ))}
        </div>
        <div className="hidden sm:block w-px h-6 bg-ink-200 mx-1"/>
        <div className="flex items-center gap-1.5">
          <Pill active={net === 'all'} onClick={() => setNet('all')}>Все сети</Pill>
          <Pill active={net === 'ig'} onClick={() => setNet('ig')}>
            <span className="inline-flex items-center gap-1.5"><I.Instagram size={12}/> Instagram</span>
          </Pill>
          <Pill active={net === 'tg'} onClick={() => setNet('tg')}>
            <span className="inline-flex items-center gap-1.5"><I.Telegram size={12}/> Telegram</span>
          </Pill>
        </div>
        <div className="flex-1"/>
        <div className="w-full sm:w-72">
          <TextInput value={q} onChange={setQ} placeholder="Поиск по теме…" icon={<I.Search size={14}/>} size="sm"/>
        </div>
      </div>

      {filtered.length === 0 ? (
        <EmptyState icon={<I.Grid size={22}/>} title="Ничего не нашли" sub="Попробуйте другой фильтр или поиск."/>
      ) : (
        <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4">
          {filtered.map((p) => (
            <button key={p.id} onClick={() => onOpen.preview(p.id)} className="text-left group">
              <div className="rounded-2xl border border-ink-200 bg-white p-3 shadow-soft hover:shadow-card transition-all group-hover:-translate-y-0.5">
                <div className="w-full" style={{ aspectRatio: '4/5' }}>
                  <SlideThumb cover={{ ...p.cover, title: p.title }} brand={org.brand} w="100%" h="100%"/>
                </div>
                <div className="mt-3 flex items-start justify-between gap-2">
                  <div className="min-w-0">
                    <div className="text-[13.5px] font-semibold truncate">{p.title}</div>
                    <div className="text-[11.5px] text-ink-500 mt-0.5">{p.slides} слайдов · {p.date}</div>
                  </div>
                  <Badge variant={p.status === 'pending' ? 'accent' : p.status}>
                    {p.status === 'ready' ? 'готов' : p.status === 'draft' ? 'черн.' : p.status === 'pending' ? 'ждёт' : 'отпр.'}
                  </Badge>
                </div>
                <div className="mt-2 flex items-center gap-1.5">
                  {window.NetworkChip && <window.NetworkChip net={p.network || 'ig'}/>}
                </div>
              </div>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

window.Screens = window.Screens || {};
window.Screens.Posts = Posts;
