// Eu Faço Parte — Sections part 3: Como fazemos / Como garantimos / CTA / Footer

const AbrigoEducacao = () => (
  <section className="comofazemos" id="comofazemos">
    <div className="section">
      <div className="section-head">
        <div className="head-left">
          <span className="eyebrow"><span className="num">03</span> · {t('abrigo.eyebrow')}</span>
        </div>
        <div className="head-right">
          <h2 className="h-section" dangerouslySetInnerHTML={tHTML('abrigo.title')} />
        </div>
      </div>

      <div className="cf-grid">
        <div className="cf-img-1 cf-img-1--with-overlay">
          <figure className="figure">
            <img
              src="images/acolhimento.jpg"
              alt=""
              onError={(e) => { const ph = document.createElement('div'); ph.className = 'ph cf-ph-1'; e.currentTarget.replaceWith(ph); }}
            />
            <figcaption className="cap"><span className="marker"></span>{t('abrigo.cap')}</figcaption>
          </figure>
          <img className="cf-overlay-illustration" src="images/section-abrigo-educacao.png" alt="" aria-hidden="true" />
        </div>

        <div className="cf-text">
          <p className="lede" dangerouslySetInnerHTML={tHTML('abrigo.lede')} />

          <div className="cf-quote">
            <span className="quotemark">”</span>
            <p dangerouslySetInnerHTML={tHTML('abrigo.quote')} />
          </div>

          <p className="body-text">{t('abrigo.p1')}</p>

          <p className="body-text">{t('abrigo.p2')}</p>
        </div>

        <div className="cf-img-2">
          <figure className="figure">
            <img
              src="images/comofazemos-2.jpg"
              alt=""
              onError={(e) => { const ph = document.createElement('div'); ph.className = 'ph cf-ph-2'; e.currentTarget.replaceWith(ph); }}
            />
            <figcaption className="cap"><span className="marker"></span>{t('abrigo.cap')}</figcaption>
          </figure>
        </div>

        <div className="cf-cta">
          <button className="btn btn-ghost" onClick={() => window.openProjectsModal?.()}>{t('abrigo.cta_projects')} <span className="arrow">→</span></button>
          <button className="btn btn-primary" onClick={() => window.openDonationModal?.()}>{t('abrigo.cta_donate')} <HeartIcon /></button>
        </div>
      </div>
    </div>
  </section>
);

// ---- Animated list ----
const ProtList = () => {
  const [visible, setVisible] = React.useState(false);
  const ref = React.useRef(null);
  const items = [t('protecao.list1'), t('protecao.list2'), t('protecao.list3')];

  React.useEffect(() => {
    const obs = new IntersectionObserver(
      ([e]) => { if (e.isIntersecting) { setVisible(true); obs.disconnect(); } },
      { threshold: 0.4 }
    );
    if (ref.current) obs.observe(ref.current);
    return () => obs.disconnect();
  }, []);

  return (
    <ul className="prot-list" ref={ref}>
      {items.map((item, i) => (
        <li
          key={i}
          style={{
            opacity:   visible ? 1 : 0,
            transform: visible ? 'translateX(0)' : 'translateX(-18px)',
            transition: `opacity 0.45s ease ${i * 120}ms, transform 0.45s ease ${i * 120}ms`,
          }}
        >
          <span className="prot-bullet">→</span> {item}
        </li>
      ))}
    </ul>
  );
};

// ---- Proteção e Ressocialização ----
const Protecao = () => (
  <section className="protecao" id="protecao">
    <div className="section">
      <div className="prot-grid">
        <div className="prot-text">
          <span className="eyebrow"><span className="num">03.2</span> · {t('protecao.eyebrow')}</span>
          <h2 className="h-section" dangerouslySetInnerHTML={tHTML('protecao.title')} />
          <p className="lede" dangerouslySetInnerHTML={tHTML('protecao.lede')} />
          <p className="body-text" dangerouslySetInnerHTML={tHTML('protecao.p1')} />
          <ProtList />
        </div>

        <div className="prot-figure">
          <figure className="figure">
            <img
              src="images/comofazemos-protecao.jpg"
              alt=""
              onError={(e) => { const ph = document.createElement('div'); ph.className = 'ph prot-ph'; e.currentTarget.replaceWith(ph); }}
            />
            <figcaption className="cap"><span className="marker"></span>{t('protecao.cap')}</figcaption>
          </figure>
        </div>
      </div>
    </div>
  </section>
);

// ---- Como garantimos ----
const Conexao = () => (
  <section className="conexao" id="comogarantimos">
    <div className="section">
      <div className="section-head">
        <div className="head-left">
          <span className="eyebrow"><span className="num">04</span> · {t('conexao.eyebrow')}</span>
        </div>
        <div className="head-right">
          <h2 className="h-section" dangerouslySetInnerHTML={tHTML('conexao.title')} />
        </div>
      </div>

      <div className="conex-grid">
        <div className="conex-figure-a">
          <figure className="figure">
            <img
              src="images/surf-sagi.jpg"
              alt=""
              onError={(e) => { const ph = document.createElement('div'); ph.className = 'ph conex-ph'; e.currentTarget.replaceWith(ph); }}
            />
            <figcaption className="cap"><span className="marker"></span>{t('conexao.cap')}</figcaption>
          </figure>
        </div>

        <div className="conex-text conex-text--with-overlay">
          <img className="conex-overlay-illustration" src="images/section-conexao-uniao.png" alt="" aria-hidden="true" />
          <p className="lede" dangerouslySetInnerHTML={tHTML('conexao.lede')} />
          <p className="body-text">{t('conexao.p1')}</p>
          <p className="body-text" dangerouslySetInnerHTML={tHTML('conexao.p2')} />
        </div>

        <div className="conex-figure-b">
        </div>

        <div className="conex-news">
          <div className="news-card">
            <span className="eyebrow"><span className="dot"></span> {t('newsletter.eyebrow')}</span>
            <h3 className="h-card" dangerouslySetInnerHTML={tHTML('newsletter.title')} />
            <p className="body-text">{t('newsletter.body')}</p>
            <NewsletterForm />
          </div>
        </div>
      </div>
    </div>
  </section>
);

// ---- Newsletter form ----
const NewsletterForm = () => {
  const [email, setEmail] = React.useState('');
  const [status, setStatus] = React.useState('idle');
  const [showModal, setShowModal] = React.useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setStatus('sending');
    try {
      const res = await fetch('https://formsubmit.co/ajax/lucas.nadler@eufacoparte.org', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify({
          email,
          _subject: 'Nova inscrição na Newsletter, Eu Faço Parte',
          message: `Nova inscrição na newsletter: ${email} (idioma: ${window.LANG})`,
          _captcha: 'false',
        }),
      });
      if (res.ok) {
        setStatus('idle');
        setEmail('');
        setShowModal(true);
      } else {
        setStatus('error');
      }
    } catch {
      setStatus('error');
    }
  };

  return (
    <>
      <form className="news-form" onSubmit={handleSubmit}>
        <input
          type="email"
          placeholder={t('newsletter.placeholder')}
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          required
        />
        <button type="submit" className="btn btn-primary" disabled={status === 'sending'}>
          {status === 'sending' ? t('newsletter.btn_sending') : t('newsletter.btn')} <span className="arrow">→</span>
        </button>
      </form>
      {status === 'error' && (
        <p style={{ marginTop: '12px', fontFamily: 'var(--mono)', fontSize: '12px', color: 'oklch(0.55 0.18 25)' }}>
          {t('newsletter.error')}
        </p>
      )}

      {showModal && (
        <div className="modal-overlay" onClick={() => setShowModal(false)}
          style={{ display: 'flex', zIndex: 1000 }}>
          <div className="modal-box" onClick={(e) => e.stopPropagation()}
            style={{ maxWidth: '480px', textAlign: 'center', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '20px' }}>
            <span className="eyebrow"><span className="num">✻</span> {t('newsletter.ok_eyebrow')}</span>
            <h2 className="h-section" style={{ margin: 0 }} dangerouslySetInnerHTML={tHTML('newsletter.ok_title')} />
            <p className="body-text" style={{ maxWidth: '38ch' }} dangerouslySetInnerHTML={tHTML('newsletter.ok_body')} />
            <button className="btn btn-primary" onClick={() => setShowModal(false)}>
              {t('newsletter.ok_close')}
            </button>
          </div>
        </div>
      )}
    </>
  );
};

// ---- Manifesto / CTA strip ----
const Manifesto = () => (
  <section className="manifesto" id="doar">
    <div className="section">
      <div className="manifesto-inner">
        <span className="eyebrow"><span className="num">✻</span> {t('manifesto.eyebrow')}</span>
        <h2 className="h-display manifesto-title" dangerouslySetInnerHTML={tHTML('manifesto.title')} />
        <p className="lede manifesto-lede">{t('manifesto.lede')}</p>
        <div className="manifesto-cta">
          <button className="btn btn-primary btn-lg" onClick={() => window.openDonationModal?.()}>{t('manifesto.cta_donate')} <HeartIcon /></button>
          <a href="#contato" className="btn btn-ghost btn-lg">{t('manifesto.cta_partner')} <span className="arrow">→</span></a>
        </div>
      </div>
    </div>
  </section>
);

// ---- Footer ----
const Footer = () => {
  const [encomenda, setEncomenda] = React.useState(null);
  const [nome,      setNome]      = React.useState('');
  const [email,     setEmail]     = React.useState('');
  const [mensagem,  setMensagem]  = React.useState('');
  const [status,    setStatus]    = React.useState('idle');
  const [showOk,    setShowOk]    = React.useState(false);

  React.useEffect(() => {
    window.setLojaEncomenda = (name) => setEncomenda(name);
    return () => { delete window.setLojaEncomenda; };
  }, []);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setStatus('sending');
    try {
      const res = await fetch('https://formsubmit.co/ajax/lucas.nadler@eufacoparte.org', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify({
          nome, email,
          _subject: encomenda ? `Encomenda: ${encomenda}, Eu Faço Parte` : `Contato (${window.LANG}), Eu Faço Parte`,
          mensagem: encomenda ? `Produto de interesse: ${encomenda}\n\n${mensagem}` : mensagem,
          _captcha: 'false',
        }),
      });
      if (res.ok) {
        setNome(''); setEmail(''); setMensagem(''); setEncomenda(null);
        setStatus('idle'); setShowOk(true);
      } else { setStatus('error'); }
    } catch { setStatus('error'); }
  };

  // Footer projects list — usa o array já traduzido de sections-2
  const projLinks = (window.initiatives && window.initiatives.slice) ? window.initiatives.slice(0, 6) : null;

  return (
    <footer className="footer" id="contato">
      <div className="section footer-inner">

        {/* ---- Contact form ---- */}
        <div className="footer-form-area">
          <div className="footer-form-left">
            <span className="eyebrow"><span className="dot"></span> {t('footer.contact_eyebrow')}</span>
            <h2 className="h-section" style={{ marginTop: '12px' }} dangerouslySetInnerHTML={tHTML('footer.contact_title')} />
            <p className="body-text" style={{ marginTop: '16px', maxWidth: '34ch' }}>
              {t('footer.contact_body')}
            </p>
          </div>

          <div className="footer-form-right">
            {showOk ? (
              <div className="footer-form-ok">
                <span className="eyebrow"><span className="num">✻</span> {t('footer.ok_eyebrow')}</span>
                <p className="body-text" style={{ marginTop: '10px' }}>{t('footer.ok_body')}</p>
                <button className="btn btn-ghost" style={{ marginTop: '20px' }} onClick={() => setShowOk(false)}>
                  {t('footer.ok_again')}
                </button>
              </div>
            ) : (
              <form className="footer-contact-form" onSubmit={handleSubmit}>
                <div className="contato-form-cols">
                  <div className="form-field">
                    <label className="form-label">{t('footer.f_name')}</label>
                    <input className="form-input" type="text" placeholder={t('footer.f_name_ph')} value={nome} onChange={e => setNome(e.target.value)} required />
                  </div>
                  <div className="form-field">
                    <label className="form-label">{t('footer.f_email')}</label>
                    <input className="form-input" type="email" placeholder={t('footer.f_email_ph')} value={email} onChange={e => setEmail(e.target.value)} required />
                  </div>
                </div>

                {encomenda && (
                  <div className="form-field">
                    <label className="form-label">{t('footer.f_product')}</label>
                    <div className="form-encomenda">
                      <span className="form-encomenda-name">{encomenda}</span>
                      <button type="button" className="form-encomenda-clear" onClick={() => setEncomenda(null)}>×</button>
                    </div>
                  </div>
                )}

                <div className="form-field">
                  <label className="form-label">{t('footer.f_message')}</label>
                  <textarea className="form-input form-textarea" placeholder={t('footer.f_message_ph')} value={mensagem} onChange={e => setMensagem(e.target.value)} />
                </div>

                {status === 'error' && (
                  <p style={{ fontFamily: 'var(--mono)', fontSize: '12px', color: 'oklch(0.55 0.18 25)' }}>
                    {t('footer.f_error')}
                  </p>
                )}
                <button type="submit" className="btn btn-primary" disabled={status === 'sending'}>
                  {status === 'sending' ? t('footer.f_sending') : t('footer.f_send')} <span className="arrow">→</span>
                </button>
              </form>
            )}
          </div>
        </div>

        <div className="footer-top">
          <div className="footer-brand">
            <img src="assets/logo.png" alt="Eu Faço Parte" />
            <p className="muted footer-tag" dangerouslySetInnerHTML={tHTML('footer.tag')} />
          </div>

          <div className="footer-col">
            <span className="eyebrow">{t('footer.col_nav')}</span>
            <a href={langPath('index.html') + '#top'}>{t('nav.home')}</a>
            <a href={langPath('nossa-historia.html')}>{t('nav.history')}</a>
            <a href={langPath('index.html') + '#oquefazemos'}>{t('nav.what')}</a>
            <a href={langPath('index.html') + '#comofazemos'}>{t('nav.how')}</a>
            <a href={langPath('index.html') + '#comogarantimos'}>{t('nav.guarantee')}</a>
          </div>

          <div className="footer-col">
            <span className="eyebrow">{t('footer.col_projects')}</span>
            <a href={langPath('projeto-surf-sagi.html')}>Surf Sagi</a>
            <a href={langPath('projeto-sagi-vidas.html')}>Sagi Vidas</a>
            <a href={langPath('projeto-anca.html')}>Abrigo ANCA</a>
            <a href={langPath('projeto-artesanato.html')}>Artesanato & Brinquedos</a>
            <a href={langPath('projeto-roupas.html')}>Roupas & Memórias</a>
            <a href={langPath('projeto-sonhos-campo.html')}>Sonhos em Campo</a>
          </div>

          <div className="footer-col">
            <span className="eyebrow">{t('footer.col_contact')}</span>
            <a href="https://www.instagram.com/eufacoparte.ong/">@eufacoparte.ong</a>
            <a href="mailto:contato@eufacoparte.org">contato@eufacoparte.org</a>
            <span className="muted">CNPJ 58.009.272/0001-32</span>
            <span className="muted">Brasil · Suíça</span>
          </div>
        </div>

        <div className="footer-bottom">
          <span className="muted">{t('footer.copyright')}</span>
          <span className="muted">{t('footer.made')}</span>
        </div>
      </div>
    </footer>
  );
};

window.AbrigoEducacao = AbrigoEducacao;
window.Protecao = Protecao;
window.Conexao = Conexao;
window.Manifesto = Manifesto;
window.Footer = Footer;
