// catalog.jsx — Картотека Делегата: filterable agent listing

function Catalog({ navigate }) {
  const [activeCategory, setActiveCategory] = React.useState('all');
  const [activeGrade, setActiveGrade] = React.useState('all');
  const [search, setSearch] = React.useState('');
  const [view, setView] = React.useState('cards'); // 'cards' | 'list'

  const categories = ['all', ...new Set(AGENTS.map((a) => a.speciality))];
  const grades = ['all', 'Базовый', 'Старший', 'Стратегический'];

  const filtered = AGENTS.filter((a) => {
    if (activeCategory !== 'all' && a.speciality !== activeCategory) return false;
    if (activeGrade !== 'all' && a.grade !== activeGrade) return false;
    if (search && !`${a.title} ${a.speciality} ${a.headline}`.toLowerCase().includes(search.toLowerCase())) return false;
    return true;
  });

  return (
    <div className="page">
      {/* Page header — document style */}
      <section style={{ padding: '56px 0 40px', borderBottom: '1px solid var(--rule)' }}>
        <div className="container-wide">
          <div className="mono" style={{ fontSize: 12, letterSpacing: '0.16em', color: 'var(--ink-3)', textTransform: 'uppercase', marginBottom: 16 }}>
            Делегат / Реестр специалистов
          </div>
          <div className="m-row-stack" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'end', gap: 64 }}>
            <h1 className="serif" style={{ fontSize: 'var(--fs-h1)', lineHeight: 1 }}>
              Картотека
            </h1>
            <p className="muted-2" style={{ fontSize: 17, maxWidth: 480, lineHeight: 1.55, marginBottom: 6 }}>
              Девять специалистов, открытых для дел. Каждое досье ниже содержит образцы работ, условия найма и границы компетенции.
            </p>
          </div>
        </div>
      </section>

      {/* Filter bar */}
      <section style={{ padding: '24px 0', borderBottom: '1px solid var(--rule)', background: 'var(--paper-2)', position: 'sticky', top: 56, zIndex: 50 }}>
        <div className="container-wide m-filter-bar" style={{ display: 'flex', gap: 32, alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap' }}>
          <div style={{ display: 'flex', gap: 4, alignItems: 'center', flex: 1, minWidth: 280, maxWidth: 360 }}>
            <Glyph name="search" size={18} color="var(--ink-3)" />
            <input
              type="text"
              placeholder="Поиск по реестру…"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              style={{
                background: 'transparent',
                border: 0,
                outline: 0,
                fontFamily: 'var(--font-body)',
                fontSize: 15,
                padding: '8px 12px',
                color: 'var(--ink)',
                width: '100%',
              }}
            />
          </div>

          <div style={{ display: 'flex', gap: 24, alignItems: 'center', flexWrap: 'wrap' }}>
            <FilterGroup label="Специальность" items={categories} value={activeCategory} onChange={setActiveCategory} />
            <FilterGroup label="Уровень" items={grades} value={activeGrade} onChange={setActiveGrade} />
            <div style={{ display: 'flex', borderLeft: '1px solid var(--rule)', paddingLeft: 16, gap: 4 }}>
              <ViewButton active={view === 'cards'} onClick={() => setView('cards')}>Карточки</ViewButton>
              <ViewButton active={view === 'list'} onClick={() => setView('list')}>Список</ViewButton>
            </div>
          </div>
        </div>
      </section>

      {/* Results */}
      <section style={{ padding: '48px 0' }}>
        <div className="container-wide">
          <div className="mono" style={{ fontSize: 12, letterSpacing: '0.14em', color: 'var(--ink-3)', textTransform: 'uppercase', marginBottom: 32 }}>
            В реестре · {String(filtered.length).padStart(2, '0')} из {String(AGENTS.length).padStart(2, '0')}
          </div>

          {view === 'cards' ? (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(320px, 1fr))', gap: 24 }}>
              {filtered.map((a) => <AgentCard key={a.id} agent={a} navigate={navigate} />)}
            </div>
          ) : (
            <div style={{ borderTop: '2px solid var(--ink)' }}>
              {filtered.map((a) => <AgentListRow key={a.id} agent={a} navigate={navigate} />)}
            </div>
          )}

          {filtered.length === 0 && (
            <div style={{ padding: 80, textAlign: 'center', color: 'var(--ink-3)' }}>
              <div className="serif" style={{ fontSize: 28 }}>В картотеке нет такого дела.</div>
              <p style={{ marginTop: 12 }}>Попробуйте изменить критерии поиска.</p>
            </div>
          )}
        </div>
      </section>

      {/* Custom agent CTA */}
      <section style={{ padding: '64px 0', background: 'var(--paper-2)', borderTop: '1px solid var(--rule)' }}>
        <div className="container-wide" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 48, alignItems: 'center' }}>
          <div>
            <div className="eyebrow" style={{ marginBottom: 12 }}>Особое поручение</div>
            <h3 className="serif" style={{ fontSize: 32, letterSpacing: '-0.015em', marginBottom: 14 }}>
              Нет нужной роли в реестре?
            </h3>
            <p className="muted-2" style={{ fontSize: 16, maxWidth: 480, lineHeight: 1.6 }}>
              Для тарифа «Корпус» мы собираем кастомного агента под вашу отрасль. Срок&nbsp;— от двух недель. Если запрос типовой&nbsp;— добавим в публичную картотеку.
            </p>
          </div>
          <div style={{ textAlign: 'right' }}>
            <button className="btn btn-primary">Оставить заявку <Glyph name="arrow" size={16} /></button>
          </div>
        </div>
      </section>
    </div>
  );
}

function FilterGroup({ label, items, value, onChange }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
      <span className="mono" style={{ fontSize: 11, letterSpacing: '0.12em', color: 'var(--ink-3)', textTransform: 'uppercase' }}>{label}</span>
      <div style={{ display: 'flex', gap: 0, border: '1px solid var(--rule)', borderRadius: 4, overflow: 'hidden' }}>
        {items.map((it) => (
          <button
            key={it}
            onClick={() => onChange(it)}
            style={{
              padding: '6px 12px',
              fontSize: 13,
              fontFamily: 'var(--font-body)',
              background: value === it ? 'var(--ink)' : 'transparent',
              color: value === it ? 'var(--paper)' : 'var(--ink-2)',
              border: 0,
              borderLeft: items.indexOf(it) > 0 ? '1px solid var(--rule)' : 0,
              cursor: 'pointer',
              transition: 'background 150ms',
            }}
          >
            {it === 'all' ? 'Все' : it}
          </button>
        ))}
      </div>
    </div>
  );
}

function ViewButton({ active, onClick, children }) {
  return (
    <button
      onClick={onClick}
      style={{
        padding: '6px 12px',
        fontSize: 13,
        background: active ? 'var(--ink)' : 'transparent',
        color: active ? 'var(--paper)' : 'var(--ink-2)',
        border: 0,
        borderRadius: 2,
        cursor: 'pointer',
        fontFamily: 'var(--font-body)',
      }}
    >
      {children}
    </button>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// AgentCard — document-style card. NOT an app store icon.
// ─────────────────────────────────────────────────────────────────────────────

function AgentCard({ agent, navigate }) {
  const [hover, setHover] = React.useState(false);
  return (
    <article
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      onClick={() => navigate('dossier', { id: agent.id })}
      style={{
        background: 'var(--paper)',
        border: '1px solid var(--rule)',
        padding: 24,
        cursor: 'pointer',
        transition: 'transform 200ms cubic-bezier(.4,0,.2,1), border-color 200ms, box-shadow 200ms',
        transform: hover ? 'translateY(-3px)' : 'none',
        borderColor: hover ? 'var(--ink)' : 'var(--rule)',
        boxShadow: hover ? '0 12px 32px rgba(0,0,0,0.06)' : 'none',
        display: 'flex',
        flexDirection: 'column',
        position: 'relative',
      }}
    >
      {/* corner case-no */}
      <div className="mono" style={{ position: 'absolute', top: 14, right: 16, fontSize: 10, letterSpacing: '0.12em', color: 'var(--ink-3)' }}>
        ДЕЛО № {agent.no}
      </div>

      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 16, marginBottom: 20 }}>
        <Monogram agent={agent} size={64} />
        <div style={{ marginTop: 4 }}>
          <div className="mono" style={{ fontSize: 11, letterSpacing: '0.12em', color: 'var(--ink-3)', textTransform: 'uppercase' }}>
            {agent.speciality}
          </div>
          <div className="serif" style={{ fontSize: 26, fontWeight: 700, letterSpacing: '-0.015em', marginTop: 4, lineHeight: 1 }}>
            AI-{agent.title}
          </div>
          <div className="muted" style={{ fontSize: 13, marginTop: 4 }}>
            {agent.grade} специалист
          </div>
        </div>
      </div>

      <p style={{ fontSize: 14, color: 'var(--ink-2)', lineHeight: 1.55, marginBottom: 18, minHeight: 64 }}>
        {agent.headline}
      </p>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 6, padding: '14px 0', borderTop: '1px solid var(--rule)', borderBottom: '1px solid var(--rule)', marginBottom: 18 }}>
        {agent.skills.slice(0, 3).map((s, i) => (
          <div key={i} style={{ display: 'flex', gap: 10, alignItems: 'baseline', fontSize: 13, color: 'var(--ink-2)' }}>
            <span className="mono" style={{ fontSize: 10, color: 'var(--ink-3)', flexShrink: 0 }}>—</span>
            <span>{s}</span>
          </div>
        ))}
      </div>

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'end' }}>
        <div>
          <div className="mono" style={{ fontSize: 10, letterSpacing: '0.1em', color: 'var(--ink-3)', textTransform: 'uppercase', marginBottom: 2 }}>
            Найм
          </div>
          <div className="mono" style={{ fontSize: 18, fontWeight: 500, color: 'var(--ink)' }}>
            от {rub(agent.price)}<span style={{ fontSize: 13, color: 'var(--ink-3)' }}>/мес</span>
          </div>
        </div>
        <button
          onClick={(e) => { e.stopPropagation(); navigate('dossier', { id: agent.id }); }}
          style={{
            background: hover ? 'var(--forest)' : 'transparent',
            color: hover ? 'var(--paper)' : 'var(--ink)',
            border: '1px solid ' + (hover ? 'var(--forest)' : 'var(--ink)'),
            padding: '8px 14px',
            fontSize: 13,
            cursor: 'pointer',
            borderRadius: 4,
            fontFamily: 'var(--font-body)',
            transition: 'all 200ms',
            display: 'flex',
            alignItems: 'center',
            gap: 6,
          }}
        >
          Досье <span style={{ opacity: 0.6 }}>→</span>
        </button>
      </div>
    </article>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// AgentListRow — table-of-contents style
// ─────────────────────────────────────────────────────────────────────────────

function AgentListRow({ agent, navigate }) {
  const [hover, setHover] = React.useState(false);
  return (
    <div
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      onClick={() => navigate('dossier', { id: agent.id })}
      style={{
        display: 'grid',
        gridTemplateColumns: '60px 80px 1.2fr 2fr 160px 160px',
        alignItems: 'center',
        gap: 24,
        padding: '20px 8px',
        borderBottom: '1px solid var(--rule)',
        cursor: 'pointer',
        background: hover ? 'var(--paper-2)' : 'transparent',
        transition: 'background 150ms',
      }}
    >
      <div className="mono" style={{ fontSize: 13, color: 'var(--ink-3)', letterSpacing: '0.1em' }}>
        № {agent.no}
      </div>
      <Monogram agent={agent} size={44} />
      <div>
        <div className="serif" style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-0.015em' }}>
          AI-{agent.title}
        </div>
        <div className="muted" style={{ fontSize: 13, marginTop: 2 }}>
          {agent.speciality} · {agent.grade}
        </div>
      </div>
      <p style={{ fontSize: 14, color: 'var(--ink-2)' }}>{agent.headline}</p>
      <div className="mono" style={{ fontSize: 15, color: 'var(--ink)' }}>
        от {rub(agent.price)}/мес
      </div>
      <div style={{ textAlign: 'right' }}>
        <span style={{ color: hover ? 'var(--forest)' : 'var(--ink-3)', transition: 'color 150ms' }}>
          Открыть досье →
        </span>
      </div>
    </div>
  );
}

window.Catalog = Catalog;
