/* ============================================================
   CAPITALIZE HUB — LANDING PAGE  (ch-landing.jsx)
   Exact match to brand design — uses REST API
   ============================================================ */

function LandingPage() {
  return (
    <main>
      <HeroSection />
      <ProductsSection />
      <HowItWorks />
      <VideosPreview />
      <CTASection />
    </main>
  );
}

/* ── Hero ─────────────────────────────────────────────────── */
function HeroSection() {
  return (
    <section className="section" style={{ paddingTop: 80, paddingBottom: 80 }}>
      <div className="container">
        <Reveal>
          <div className="label label-brand">Soluções para construção</div>
        </Reveal>

        <Reveal delay={0.05}>
          <h1 style={{ maxWidth: 520, marginBottom: 24 }}>
            Software para{' '}
            <br />
            quem <span style={{ color: 'var(--brand)' }}>constrói.</span>
          </h1>
        </Reveal>

        <Reveal delay={0.1}>
          <p style={{ maxWidth: 460, fontSize: '0.95rem', marginBottom: 32 }}>
            A Capitalize Hub cria e opera soluções digitais prontas para o mercado da construção, imóveis e finanças. Tecnologia de verdade, sem o custo de construir do zero.
          </p>
        </Reveal>

        <Reveal delay={0.15}>
          <div className="flex gap-sm" style={{ flexWrap: 'wrap' }}>
            <a className="btn btn-dark" href="#produtos">
              Conhecer as soluções
            </a>
            <a className="btn btn-outline" href="#videos-preview">
              Ver demonstrações →
            </a>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

/* ── Products ─────────────────────────────────────────────── */
function ProductsSection() {
  const [products, setProducts] = React.useState([]);

  const productMeta = {
    construcao: {
      icon: <Icons.building />,
      title: 'Construção & Obras',
      desc: 'Do orçamento ao canteiro: planeje a obra e acompanhe a execução em tempo real.',
      badge: 'Disponível',
      badgeClass: 'badge-green',
      features: ['Diário de obra', 'Cronograma', 'Custos', 'Equipe'],
    },
    imoveis: {
      icon: <Icons.imoveisIcon />,
      title: 'Imóveis',
      desc: 'Tecnologia para o mercado imobiliário vender e gerir melhor — do primeiro contato ao pós-venda.',
      badge: 'Em breve',
      badgeClass: 'badge-amber',
      features: ['CRM', 'Vendas', 'Portal', 'Análise'],
    },
    financas: {
      icon: <Icons.financasIcon />,
      title: 'Finanças',
      desc: 'Capital e controle financeiro pensados para o setor da construção e do imobiliário.',
      badge: 'Em breve',
      badgeClass: 'badge-amber',
      features: ['Fluxo de caixa', 'Recebíveis', 'Conciliação', 'Relatórios'],
    },
  };

  React.useEffect(() => {
    fetch('/api/products')
      .then(r => r.json())
      .then(data => setProducts(data))
      .catch(() => {});
  }, []);

  const getProductLink = (key) => {
    const found = products.find(p => p.key === key);
    let url = found ? (found.redirect_url || found.link || '') : '';
    if (url && !url.match(/^https?:\/\//i)) url = 'https://' + url;
    return url;
  };

  const handleCardClick = (key) => {
    const link = getProductLink(key);
    if (link) window.open(link, '_blank');
  };

  const productCards = ['construcao', 'imoveis', 'financas'].map(id => ({
    id,
    ...productMeta[id],
  }));

  return (
    <section className="section" id="produtos" style={{ paddingTop: 40 }}>
      <div className="container">
        <Reveal>
          <div className="label">Três frentes, um hub</div>
          <h2 style={{ maxWidth: 440, marginBottom: 40 }}>
            Produtos para cada parte do setor.
          </h2>
        </Reveal>

        <div className="grid-3">
          {productCards.map((p, i) => (
            <Reveal key={i} delay={i * 0.08}>
              <div
                className="card"
                onClick={() => handleCardClick(p.id)}
                style={{
                  height: '100%', display: 'flex', flexDirection: 'column',
                  cursor: getProductLink(p.id) ? 'pointer' : 'default',
                }}
              >
                <div className="flex items-center justify-between" style={{ marginBottom: 20 }}>
                  <div className="product-icon">{p.icon}</div>
                  <span className={`badge ${p.badgeClass}`}>{p.badge}</span>
                </div>

                <h3 style={{ marginBottom: 8 }}>{p.title}</h3>
                <p style={{ fontSize: '0.85rem', marginBottom: 20, flex: 1 }}>{p.desc}</p>

                <div style={{ borderTop: '1px solid var(--border)', paddingTop: 16, display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                  {p.features.map((f, j) => (
                    <span key={j} className="badge" style={{ fontSize: '0.55rem' }}>{f}</span>
                  ))}
                </div>
              </div>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ── How it Works (dark section) ──────────────────────────── */
function HowItWorks() {
  return (
    <section className="section section-dark">
      <div className="container">
        <div className="grid-2">
          <Reveal>
            <div>
              <div className="label">Como funciona</div>
              <h2 style={{ maxWidth: 400 }}>
                Soluções prontas.<br />
                Não sob medida.
              </h2>
            </div>
          </Reveal>

          <Reveal delay={0.1}>
            <p style={{ fontSize: '0.95rem', lineHeight: 1.8 }}>
              Você não espera meses de desenvolvimento nem monta um time de tecnologia. Nossos produtos já estão prontos para rodar na sua operação — é começar e usar.
            </p>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

/* ── Videos Preview ───────────────────────────────────────── */
function VideosPreview() {
  const [videos, setVideos] = React.useState([]);

  React.useEffect(() => {
    fetch('/api/videos')
      .then(r => r.json())
      .then(data => setVideos(Array.isArray(data) ? data.slice(0, 3) : []))
      .catch(() => {});
  }, []);

  return (
    <section className="section" id="videos-preview">
      <div className="container">
        <div className="flex items-center justify-between" style={{ marginBottom: 40, flexWrap: 'wrap', gap: 16 }}>
          <div>
            <Reveal>
              <div className="label">Central de Conteúdo</div>
              <h2>Demonstrações e bastidores.</h2>
            </Reveal>
          </div>
          <Reveal delay={0.1}>
            <button className="btn btn-outline btn-sm" onClick={() => window.__chNav && window.__chNav('videos')}>
              Ver tudo →
            </button>
          </Reveal>
        </div>

        <div className="grid-3">
          {videos.map((v, i) => (
            <Reveal key={v.id || i} delay={i * 0.08}>
              <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>
                </div>
                <div className="video-tag">{v.tag || v.category_name || ''}</div>
                <div className="video-title">{v.title}</div>
              </a>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ── CTA (blue section) ──────────────────────────────────── */
function CTASection() {
  return (
    <section className="section section-blue" style={{ textAlign: 'center' }}>
      <div className="container" style={{ maxWidth: 600 }}>
        <Reveal>
          <h2 style={{ marginBottom: 16, fontSize: 'clamp(2rem, 5vw, 3.2rem)' }}>
            Veja a solução<br />rodando.
          </h2>
          <p style={{ marginBottom: 32, fontSize: '0.95rem' }}>
            Agende uma demonstração e conheça os produtos da Capitalize Hub na prática.
          </p>
          <a className="btn btn-outline" href="https://wa.me/551153044489?text=Ol%C3%A1%2C%20gostaria%20de%20agendar%20uma%20demonstra%C3%A7%C3%A3o%20dos%20produtos%20Capitalize%20Hub" target="_blank" rel="noopener noreferrer" style={{ borderColor: 'rgba(255,255,255,.35)', color: '#fff' }}>
            Agendar demonstração →
          </a>
        </Reveal>
      </div>
    </section>
  );
}
