// AGENTFORGE-IA — Marketplace
const Marketplace = ({ data, openAgent, openCategory, activeCategory, setActiveCategory }) => {
  const [q, setQ] = React.useState('');
  const [sort, setSort] = React.useState('popular');
  const cats = Array.isArray(data?.categories) ? data.categories : [];
  const agents = Array.isArray(data?.agents) ? data.agents : [];
  const resultsRef = React.useRef(null);

  const selectCategory = (id) => {
    setActiveCategory(id);
    setTimeout(() => {
      if (resultsRef.current) {
        resultsRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' });
      }
    }, 60);
  };

  // Contadores reales por categoría
  const catCounts = React.useMemo(() => {
    const counts = {};
    agents.forEach(a => { counts[a.cat] = (counts[a.cat] || 0) + 1; });
    return counts;
  }, [agents]);

  const featured = React.useMemo(() => {
    if (agents.length === 0) {
      return null;
    }
    return [...agents]
      .sort((a, b) => (Number(b.runs) || 0) - (Number(a.runs) || 0))[0] || null;
  }, [agents]);
  const filtered = agents.filter(a => {
    if (activeCategory && activeCategory !== 'all' && a.cat !== activeCategory) return false;
    const name = (a.name || '').toLowerCase();
    const tagline = (a.tagline || '').toLowerCase();
    if (q && !(name.includes(q.toLowerCase()) || tagline.includes(q.toLowerCase()))) return false;
    return true;
  }).sort((a,b) => sort === 'popular'
    ? (Number(b.runs) || 0) - (Number(a.runs) || 0)
    : sort === 'rating'
      ? (Number(b.rating) || 0) - (Number(a.rating) || 0)
      : (Number(b.runs) || 0) - (Number(a.runs) || 0));

  const totalAgents = agents.length;
  const visibleCats = cats.filter(c => (catCounts[c.id] || 0) > 0);

  return (
    <div>
      <div className="page-head">
        <h1>Marketplace</h1>
        <span className="crumbs mono">explorar <span>›</span> <span style={{ color: 'var(--ink)' }}>{totalAgents} agentes · {visibleCats.length} categorías</span></span>
        <div className="actions">
          <button className="btn btn-ghost"><Icon name="upload" size={13} /> Publicar agente</button>
          <button className="btn"><Icon name="filter" size={13} /> Filtros</button>
        </div>
      </div>

      <div style={{ padding: '24px 28px 8px' }}>
        <div className="mp-search">
          <Icon name="search" size={16} />
          <input
            placeholder='Prueba "resumir tickets de soporte semanalmente" o "revisor de PRs con Linear"'
            value={q} onChange={e => setQ(e.target.value)}
          />
          <span className="mono" style={{ color: 'var(--ink-4)', fontSize: 11 }}>⌘K</span>
        </div>
        <div style={{ display: 'flex', gap: 8, marginTop: 10, flexWrap: 'wrap', alignItems: 'center' }}>
          <span className="mono" style={{ fontSize: 10.5, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.08em', marginRight: 4 }}>Tendencias</span>
          {['triaje de tickets','brief SEO','revisor de PRs','onboarding','investigación profunda','redlines de contratos'].map(t => (
            <button key={t} className="chip" onClick={() => setQ(t)}><span className="dot" style={{ background: 'var(--brand)' }} />{t}</button>
          ))}
        </div>
      </div>

      <div className="section" style={{ paddingBottom: 8 }}>
        <div className="section-title">
          <span>Explorar por categoría</span>
          <span style={{ color: 'var(--ink-4)' }}>·</span>
          <span style={{ color: 'var(--ink-3)', textTransform: 'none', letterSpacing: 0, fontFamily: 'var(--sans)' }}>{totalAgents} agentes en {visibleCats.length} categorías</span>
          <span className="line" />
          <select className="mono" style={{ background: 'transparent', color: 'var(--ink-3)', border: '1px solid var(--line)', padding: '4px 8px', borderRadius: 6, fontSize: 11 }} value={sort} onChange={e => setSort(e.target.value)}>
            <option value="popular">Más populares</option>
            <option value="rating">Mejor valorados</option>
            <option value="new">Más recientes</option>
          </select>
        </div>
        <div className="cat-grid">
          <button className={'cat-card cat-all' + (activeCategory === 'all' ? ' active' : '')} onClick={() => selectCategory('all')}>
            <div className="cat-icon" style={{ background: 'linear-gradient(135deg, var(--brand), var(--brand-2))', color: '#1a0a04' }}><Icon name="sparkles" size={18} stroke={2} /></div>
            <div className="cat-name">Todos los agentes</div>
            <div className="cat-count mono">{totalAgents}</div>
            <div className="cat-meta">Curado por Forge</div>
          </button>
          {visibleCats.map(c => (
            <button key={c.id} className={'cat-card' + (activeCategory === c.id ? ' active' : '')} onClick={() => selectCategory(c.id)} style={{ '--accent': c.accent }}>
              <div className="cat-icon" style={{ color: c.accent, background: `${c.accent}1a`, borderColor: `${c.accent}33` }}>
                <Icon name={c.icon} size={18} stroke={1.8} />
              </div>
              <div className="cat-name">{c.name}</div>
              <div className="cat-count mono">{catCounts[c.id] || 0}</div>
              <div className="cat-meta">agentes</div>
              <div className="cat-spark"><Icon name="arrow-right" size={12} /></div>
            </button>
          ))}
        </div>
      </div>

      <div className="section" style={{ paddingTop: 8, paddingBottom: 8 }}>
        <div className="section-title"><span>Destacado esta semana</span><span className="line" /></div>
        {featured ? (
        <div className="featured-card" onClick={() => openAgent(featured.id)}>
          <div className="featured-left">
            <div className="featured-tag">
              <span className="tag warn"><Icon name="fire" size={11} /> ELECCIÓN DEL EDITOR</span>
              <span className="tag">investigación</span>
            </div>
            <h2 className="featured-title">{featured.name || 'Agente destacado'}</h2>
            <p className="featured-desc">{featured.tagline || 'Agente recomendado por actividad y adopción.'} Planificación multietapa, fuentes recursivas y citas trazables.</p>
            <div className="featured-meta mono">
              <span><Icon name="play" size={12} /> {(Math.max(0, Number(featured.runs) || 0)/1000).toFixed(0)} k ejecuciones</span>
              <span><Icon name="star" size={12} /> {Number(featured.rating || 0).toString().replace('.', ',')} ({Number(featured.reviews) || 0})</span>
              <span><Icon name="verified" size={12} /> {featured.author || 'Forge Labs'}</span>
            </div>
            <div style={{ display:'flex', gap: 8, marginTop: 16 }}>
              <button className="btn btn-primary" onClick={e => { e.stopPropagation(); openAgent(featured.id); }}><Icon name="play" size={13} /> Probar ahora</button>
              <button className="btn" onClick={e => { e.stopPropagation(); openAgent(featured.id); }}><Icon name="download" size={13} /> Comprar</button>
            </div>
          </div>
          <div className="featured-right">
            <div className="featured-vis grid-bg">
              <div className="vis-node v-1"><Icon name="globe" size={14} /> web.search</div>
              <div className="vis-node v-2"><Icon name="flask" size={14} /> arxiv.fetch</div>
              <div className="vis-node v-3"><Icon name="memory" size={14} /> memo.synth</div>
              <div className="vis-node v-c"><Icon name="sparkles" size={16} /> Investigación Profunda</div>
              <svg className="vis-edges" viewBox="0 0 320 220" preserveAspectRatio="none">
                <path d="M60 50 Q160 60 220 110" />
                <path d="M50 110 Q140 120 220 110" />
                <path d="M60 170 Q160 160 220 110" />
              </svg>
            </div>
          </div>
        </div>
        ) : (
        <div className="featured-card">
          <div className="featured-left">
            <h2 className="featured-title">Sin agente destacado</h2>
            <p className="featured-desc">Todavía no hay agentes suficientes para destacar uno en esta sección.</p>
          </div>
        </div>
        )}
      </div>

      <div ref={resultsRef} className="section" style={{ paddingTop: 8 }}>
        <div className="section-title">
          <span>{activeCategory && activeCategory !== 'all' ? cats.find(c=>c.id===activeCategory)?.name : 'Agentes destacados'}</span>
          <span style={{ color: 'var(--ink-4)' }}>·</span>
          <span style={{ color: 'var(--ink-3)', textTransform: 'none', letterSpacing: 0, fontFamily: 'var(--sans)' }}>{filtered.length} resultados</span>
          <span className="line" />
          {activeCategory && activeCategory !== 'all' && (
            <button className="btn btn-ghost btn-sm" onClick={() => selectCategory('all')}><Icon name="x" size={11} /> limpiar</button>
          )}
        </div>
        <div className="agent-grid">
          {filtered.map(a => <AgentCard key={a.id} a={a} cat={cats.find(c => c.id === a.cat)} onOpen={() => openAgent(a.id)} />)}
        </div>
      </div>
    </div>
  );
};

function AgentCard({ a, cat, onOpen }) {
  const tools = (Array.isArray(a.tools) ? a.tools : []).filter(t => !/slack|zendesk/i.test(String(t)));
  const runs = Number(a.runs) || 0;
  const rating = Number(a.rating) || 0;
  const reviews = Number(a.reviews) || 0;

  return (
    <div className="agent-card" onClick={onOpen}>
      <div className="agent-card-head">
        <div className="agent-icon" style={{ color: a.color, background: `${a.color}1a`, borderColor: `${a.color}33` }}>
          <Icon name={cat?.icon || 'sparkles'} size={16} stroke={1.8} />
        </div>
        <div className="agent-card-meta">
          <div className="agent-card-name">
            {a.name}
            {a.verified && <span data-tip="Verificado por Forge"><Icon name="verified" size={13} style={{ color: 'var(--brand)' }} /></span>}
          </div>
          <div className="agent-card-author mono">{a.author} · {cat?.name}</div>
        </div>
        <div className="agent-card-price mono">{String(a.price || '').toLowerCase().includes('gratis') ? 'De pago' : a.price}</div>
      </div>
      <p className="agent-card-tagline">{a.tagline}</p>
      <div className="agent-card-tools">
        {tools.slice(0,3).map(t => <span key={t} className="tag">{t}</span>)}
        {tools.length > 3 && <span className="tag">+{tools.length - 3}</span>}
      </div>
      <div className="agent-card-foot mono">
        <span><Icon name="play" size={11} /> {runs > 999 ? (runs/1000).toFixed(0)+' k' : runs}</span>
        <span><Icon name="star" size={11} /> {rating.toString().replace('.', ',')}</span>
        <span><Icon name="users" size={11} /> {reviews}</span>
        <button className="btn btn-sm" onClick={e => { e.stopPropagation(); onOpen(); }}>Comprar</button>
      </div>
    </div>
  );
}

window.Marketplace = Marketplace;
