/* ============================================================
   CAPITALIZE HUB — VIDEOS PAGE  (ch-videos.jsx)
   Full video library — uses REST API
   ============================================================ */

function VideosPage() {
  const [category, setCategory] = React.useState('all');
  const [search, setSearch] = React.useState('');
  const [videos, setVideos] = React.useState([]);
  const [categories, setCategories] = React.useState([]);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    Promise.all([
      fetch('/api/videos').then(r => r.json()),
      fetch('/api/categories').then(r => r.json()),
    ])
      .then(([vids, cats]) => {
        setVideos(Array.isArray(vids) ? vids : []);
        setCategories(Array.isArray(cats) ? cats : []);
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  const categoryTabs = [
    { id: 'all', label: 'Todos' },
    ...categories.map(c => ({ id: String(c.id), label: c.name })),
  ];

  const filtered = videos.filter(v => {
    const matchCat = category === 'all' || String(v.catId || v.category_id) === category;
    const titleMatch = (v.title || '').toLowerCase().includes(search.toLowerCase());
    const tagMatch = (v.tag || v.category_name || '').toLowerCase().includes(search.toLowerCase());
    return matchCat && (titleMatch || tagMatch);
  });

  return (
    <main>
      {/* Header */}
      <section className="section" style={{ paddingBottom: 32 }}>
        <div className="container">
          <Reveal>
            <div className="label label-brand">Central de Conteúdo</div>
            <h2 style={{ marginBottom: 8 }}>Todos os vídeos</h2>
            <p style={{ fontSize: '0.9rem', maxWidth: 440, marginBottom: 32 }}>
              Tutoriais, demonstrações e novidades para você dominar a plataforma.
            </p>
          </Reveal>

          {/* Filters */}
          <Reveal delay={0.05}>
            <div className="flex gap-md" style={{ flexWrap: 'wrap', alignItems: 'center' }}>
              <input
                className="input"
                style={{ maxWidth: 280 }}
                placeholder="Buscar vídeos..."
                value={search}
                onChange={e => setSearch(e.target.value)}
              />
              <div className="tabs">
                {categoryTabs.map(c => (
                  <button key={c.id} className={`tab${category === c.id ? ' active' : ''}`} onClick={() => setCategory(c.id)}>
                    {c.label}
                  </button>
                ))}
              </div>
            </div>
          </Reveal>
        </div>
      </section>

      {/* Video grid */}
      <section className="section" style={{ paddingTop: 0 }}>
        <div className="container">
          {loading ? (
            <div style={{ textAlign: 'center', padding: '64px 0' }}>
              <p style={{ color: 'var(--text-muted)' }}>Carregando vídeos...</p>
            </div>
          ) : filtered.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '64px 0' }}>
              <p style={{ color: 'var(--text-muted)' }}>Nenhum vídeo encontrado.</p>
            </div>
          ) : (
            <div className="grid-3">
              {filtered.map((v, i) => (
                <Reveal key={v.id} delay={i * 0.06}>
                  <a className="video-card" href="#">
                    <div className="video-thumb">
                      <img src={v.thumb} alt={v.title} loading="lazy" />
                      <div className="video-play"><Icons.play /></div>
                      {v.duration && (
                        <span style={{
                          position: 'absolute', bottom: 8, right: 8,
                          fontFamily: "'Geist Mono', monospace", fontSize: '0.65rem',
                          background: 'rgba(0,0,0,.65)', color: '#fff',
                          padding: '3px 8px', borderRadius: 4,
                        }}>{v.duration}</span>
                      )}
                    </div>
                    <div className="video-tag">{v.tag || v.category_name || ''}</div>
                    <div className="video-title">{v.title}</div>
                  </a>
                </Reveal>
              ))}
            </div>
          )}
        </div>
      </section>

      {/* CTA */}
      <section className="section section-dark" style={{ textAlign: 'center' }}>
        <div className="container" style={{ maxWidth: 500 }}>
          <Reveal>
            <h3 style={{ marginBottom: 12 }}>Quer ver a plataforma ao vivo?</h3>
            <p style={{ marginBottom: 24 }}>Agende uma demonstração gratuita e personalizada.</p>
            <a className="btn btn-primary" href="#">Agendar demonstração →</a>
          </Reveal>
        </div>
      </section>
    </main>
  );
}
