// database.jsx — главный раздел, bento-сетка

const TagChip = ({ tag, compact = false }) => (
  <span className={`tag ${tag.color}`}>
    {!compact && <span className="tag-dot" />}
    {tag.name}
  </span>
);

const AvatarStack = ({ people, max = 3 }) => {
  const visible = people.slice(0, max);
  const extra = people.length - visible.length;
  return (
    <div className="avatar-stack">
      {visible.map((p) => (
        <span key={p.id} className={`avatar ${p.av}`} title={p.name}>
          {p.name.split(' ').map(s => s[0]).join('').slice(0, 2)}
        </span>
      ))}
      {extra > 0 && (
        <span className="avatar" style={{ background: 'var(--paper-2)', color: 'var(--text-2)' }}>
          +{extra}
        </span>
      )}
    </div>
  );
};

// Bento sizing patterns — повторяющийся ритм
const bentoPattern = [
  { size: 'size-feature', fill: 'fill-ink', watermark: '01' },
  { size: 'size-square', fill: '', watermark: null },
  { size: 'size-square', fill: 'fill-cream', watermark: null },
  { size: 'size-wide', fill: 'fill-cobalt', watermark: '02' },
  { size: 'size-square', fill: '', watermark: null },
  { size: 'size-tall', fill: 'fill-coral', watermark: '03' },
  { size: 'size-square', fill: '', watermark: null },
  { size: 'size-square', fill: 'fill-cream', watermark: null },
  { size: 'size-wide', fill: '', watermark: null },
  { size: 'size-square', fill: 'fill-ink', watermark: '04' },
  { size: 'size-square', fill: '', watermark: null },
  { size: 'size-square', fill: '', watermark: null },
];

const ArticleCard = ({ article, idx, onOpen }) => {
  const section = window.findSection(article.section);
  const sectionLabel = window.getSectionLabel(article.section);
  const tags = article.tags.map(t => window.findTag(t)).filter(Boolean);
  const people = article.responsibles.map(p => window.findPerson(p)).filter(Boolean);
  const pattern = bentoPattern[idx % bentoPattern.length];
  const coverSrc = article.content?.coverSrc || null;
  const hasCover = Boolean(coverSrc);

  return (
    <article
      className={`article-card ${pattern.size} ${hasCover ? 'has-cover' : pattern.fill}`}
      onClick={() => onOpen(article)}
    >
      {hasCover && (
        <div
          className="article-card-cover-fill"
          style={{ backgroundImage: `url("${coverSrc}")` }}
          aria-hidden="true"
        />
      )}

      {!hasCover && pattern.watermark && (
        <span className="article-card-watermark">{pattern.watermark}</span>
      )}

      <div className="article-card-section">
        <Icon name={section?.icon || 'file'} size={11} />
        {sectionLabel !== '—' ? sectionLabel : 'Без раздела'}
        <span className="article-card-section-dot" />
        <span style={{ fontFamily: 'var(--font-mono)' }}>{article.readMin} мин</span>
      </div>

      <h3 className="article-card-title">{article.title}</h3>

      {(pattern.size === 'size-feature' || pattern.size === 'size-wide' || pattern.size === 'size-tall') && (
        <p className="article-card-desc">{article.desc}</p>
      )}

      <div className="article-card-bottom">
        <AvatarStack people={people} max={3} />
        <div className="article-card-meta">
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
            <Icon name="eye" size={11} /> {article.views.toLocaleString('ru')}
          </span>
        </div>
      </div>

      <div className="article-card-arrow">
        <Icon name="arrowRight" size={14} />
      </div>
    </article>
  );
};

const ArticleRow = ({ article, onOpen }) => {
  const sectionLabel = window.getSectionLabel(article.section);
  const tags = article.tags.map(t => window.findTag(t)).filter(Boolean);
  const people = article.responsibles.map(p => window.findPerson(p)).filter(Boolean);

  return (
    <div className="article-row" onClick={() => onOpen(article)}>
      <div className="article-row-title">
        <div className="article-row-icon">
          {String(article.id).replace(/\D/g, '').padStart(2, '0')}
        </div>
        <div style={{ minWidth: 0, flex: 1 }}>
          <div className="article-row-title-text">{article.title}</div>
          <div style={{ fontSize: 12, color: 'var(--text-3)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', marginTop: 2 }}>
            {article.desc}
          </div>
        </div>
      </div>
      <div style={{ display: 'flex', gap: 5, flexWrap: 'wrap' }}>
        {tags.slice(0, 2).map(t => <TagChip key={t.id} tag={t} compact />)}
      </div>
      <div>{sectionLabel !== '—' && <span className="tag">{sectionLabel}</span>}</div>
      <AvatarStack people={people} max={3} />
      <div className={`status status-${article.status}`} style={{ fontSize: 11.5 }}>
        {article.status === 'published' && 'Опубл.'}
        {article.status === 'draft' && 'Черновик'}
        {article.status === 'review' && 'Ревью'}
      </div>
      <button className="topbar-icon-btn" onClick={(e) => e.stopPropagation()}>
        <Icon name="more" size={14} />
      </button>
    </div>
  );
};

const SectionPill = ({ section, active, onClick }) => (
  <button className={`filter-pill ${active ? 'active' : ''}`} onClick={onClick}>
    <Icon name={section.icon} size={13} />
    <span>{section.name}</span>
    <span className="filter-pill-count">{section.count}</span>
  </button>
);

const DatabaseView = ({ onOpenArticle, onCreate, searchQuery, filter = 'all', title, onNavigateDrafts, onNavigateArticles, initialSection = null }) => {
  const [activeSection, setActiveSection] = React.useState(initialSection || 'all');
  const [view, setView] = React.useState('grid');
  const [sort, setSort] = React.useState('updated');
  const [tagFilter, setTagFilter] = React.useState(null);
  const [tagsModalOpen, setTagsModalOpen] = React.useState(false);
  const [, tagsTick] = React.useReducer((n) => n + 1, 0);

  React.useEffect(() => {
    if (initialSection) setActiveSection(initialSection);
  }, [initialSection]);

  const baseList = React.useMemo(() => {
    let list = [...window.ARTICLES];
    if (filter === 'drafts') list = list.filter(a => a.status === 'draft' && !a.deletedAt);
    else if (filter === 'favorites') list = list.filter((a) => window.KB.isBookmarked(a.id) && !a.deletedAt && window.KB.canViewArticle(a));
    else if (filter === 'mandatory') list = list.filter(a => a.isMandatory && !a.deletedAt);
    else if (filter === 'trash') list = list.filter(a => a.deletedAt);
    else if (filter === 'recent') {
      const ids = window.KB.getRecentIds();
      list = ids.map(id => window.ARTICLES.find(a => a.id === id)).filter(Boolean);
    } else {
      list = list.filter(a => !a.deletedAt && (
        window.KB.isPublicArticle(a)
        || (a.status === 'review' && window.KB.canViewArticle(a))
      ));
    }
    return list;
  }, [filter]);

  const filtered = React.useMemo(() => {
    let list = [...baseList];
    if (activeSection !== 'all') list = list.filter((a) => window.articleMatchesSection(a, activeSection));
    if (tagFilter) list = list.filter(a => a.tags.includes(tagFilter));
    if (searchQuery) {
      const q = searchQuery.toLowerCase();
      list = list.filter(a => a.title.toLowerCase().includes(q) || (a.desc || '').toLowerCase().includes(q));
    }
    if (sort === 'views') list.sort((a, b) => b.views - a.views);
    if (sort === 'title') list.sort((a, b) => a.title.localeCompare(b.title));
    if (sort === 'updated') list.sort((a, b) => new Date(b.updatedAt || 0) - new Date(a.updatedAt || 0));
    return list;
  }, [baseList, activeSection, tagFilter, searchQuery, sort]);

  const totalArticles = window.ARTICLES.filter(a => !a.deletedAt).length;
  const sectionCount = window.getRootSections().length;
  const filterSections = React.useMemo(() => {
    const allSection = window.findSection('all');
    const roots = window.getRootSections();
    return [
      allSection ? { ...allSection, count: baseList.length } : { id: 'all', name: 'Все статьи', icon: 'grid', count: baseList.length },
      ...roots.map((s) => ({
        ...s,
        count: baseList.filter((a) => window.articleMatchesSection(a, s.id)).length,
      })),
    ];
  }, [baseList]);

  const activeRootId = React.useMemo(() => {
    if (activeSection === 'all') return 'all';
    const s = window.findSection(activeSection);
    return s?.parentId || activeSection;
  }, [activeSection]);

  const subsectionFilters = React.useMemo(() => {
    if (activeRootId === 'all') return [];
    return window.getSubsections(activeRootId);
  }, [activeRootId]);
  const now = new Date();
  const timeStr = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;

  const pageTitle = title || 'База знаний';

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">
            {pageTitle}
          </h1>
          <p className="page-sub">
            Живая библиотека процессов, регламентов и шаблонов.{' '}
            <span className="text-mono text-xs">{totalArticles} статей · {sectionCount} разделов · обновлено сегодня в {timeStr}</span>
          </p>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="btn btn-ghost">
            <Icon name="download" size={14} /> Экспорт
          </button>
          <button type="button" className="btn btn-ghost" onClick={() => setTagsModalOpen(true)}>
            <Icon name="filter" size={14} /> Теги
          </button>
          {filter === 'all' && onNavigateDrafts && (
            <button className="btn btn-ghost" onClick={onNavigateDrafts}>
              <Icon name="edit" size={14} />
              Черновики
              <span className="filter-pill-count" style={{ marginLeft: 4 }}>
                {window.ARTICLES.filter(a => a.status === 'draft' && !a.deletedAt).length}
              </span>
            </button>
          )}
          {filter === 'drafts' && onNavigateArticles && (
            <button className="btn btn-ghost" onClick={onNavigateArticles}>
              <Icon name="file" size={14} /> Все статьи
            </button>
          )}
          <button className="btn btn-primary" onClick={onCreate}>
            <Icon name="plus" size={14} /> Создать статью
          </button>
        </div>
      </div>

      {filter !== 'trash' && filter !== 'recent' && (
        <>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: subsectionFilters.length ? 8 : 14 }}>
            {filterSections.map((s) => (
              <SectionPill
                key={s.id}
                section={s}
                active={activeRootId === s.id}
                onClick={() => setActiveSection(s.id)}
              />
            ))}
          </div>
          {subsectionFilters.length > 0 && (
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 14, paddingLeft: 4 }}>
              <button
                type="button"
                className={`filter-pill filter-pill--sub ${activeSection === activeRootId ? 'active' : ''}`}
                onClick={() => setActiveSection(activeRootId)}
              >
                Все в разделе
              </button>
              {subsectionFilters.map((s) => (
                <SectionPill
                  key={s.id}
                  section={{
                    ...s,
                    count: baseList.filter((a) => a.section === s.id).length,
                  }}
                  active={activeSection === s.id}
                  onClick={() => setActiveSection(s.id)}
                />
              ))}
            </div>
          )}
        </>
      )}

      {/* Toolbar */}
      <div className="toolbar">
        <span className="text-xs text-mono text-3" style={{ marginRight: 6 }}>теги</span>
        {window.TAGS.slice(0, 6).map(t => (
          <button
            key={t.id}
            className={`tag ${t.color}`}
            style={{
              cursor: 'pointer',
              opacity: tagFilter && tagFilter !== t.id ? 0.4 : 1,
              outline: tagFilter === t.id ? '2px solid var(--ink)' : 'none',
              outlineOffset: 2,
            }}
            onClick={() => setTagFilter(tagFilter === t.id ? null : t.id)}
          >
            {t.name}
          </button>
        ))}

        <div style={{ width: 1, height: 18, background: 'var(--border)', margin: '0 6px' }} />

        <button className="filter-pill" onClick={() => setSort(sort === 'updated' ? 'views' : sort === 'views' ? 'title' : 'updated')}>
          <Icon name="sort" size={12} />
          {sort === 'updated' && 'По дате'}
          {sort === 'views' && 'По популярности'}
          {sort === 'title' && 'По алфавиту'}
        </button>

        <div className="view-toggle" style={{ marginLeft: 'auto' }}>
          <button className={view === 'grid' ? 'active' : ''} onClick={() => setView('grid')}>
            <Icon name="grid" size={12} /> Bento
          </button>
          <button className={view === 'list' ? 'active' : ''} onClick={() => setView('list')}>
            <Icon name="list" size={12} /> Таблица
          </button>
        </div>
      </div>

      {/* Результаты */}
      {filtered.length === 0 && (
        <div className="empty-state">
          <Icon name="file" size={32} style={{ color: 'var(--text-3)', marginBottom: 12 }} />
          <p style={{ marginBottom: 16 }}>
            {filter === 'trash' ? 'Корзина пуста' : filter === 'drafts' ? 'Черновиков пока нет' : 'Статей пока нет. Создайте первую!'}
          </p>
          {filter !== 'trash' && (
            <button className="btn btn-primary" onClick={onCreate}>
              <Icon name="plus" size={14} /> Создать статью
            </button>
          )}
        </div>
      )}

      {view === 'grid' && filtered.length > 0 && (
        <div className="bento-grid">
          {filtered.map((a, i) => <ArticleCard key={a.id} article={a} idx={i} onOpen={onOpenArticle} />)}
        </div>
      )}

      {view === 'list' && filtered.length > 0 && (
        <div className="article-table">
          <div className="article-row header">
            <div>Название</div>
            <div>Теги</div>
            <div>Раздел</div>
            <div>Ответственные</div>
            <div>Статус</div>
            <div></div>
          </div>
          {filtered.map(a => <ArticleRow key={a.id} article={a} onOpen={onOpenArticle} />)}
        </div>
      )}

      <TagsModal
        open={tagsModalOpen}
        onClose={() => setTagsModalOpen(false)}
        onChange={tagsTick}
      />
    </div>
  );
};

window.DatabaseView = DatabaseView;
window.ArticleCard = ArticleCard;
window.AvatarStack = AvatarStack;
window.TagChip = TagChip;
