// Agent Builder — Agendar / Contato (RD Station embedded form)

const RD_FORM_ID = "form-contato-agent-builder-03f76eaa0e890f1510e6";
const RD_TOKEN = "UA-148000340-1";
const RD_SCRIPT = "https://d335luupugsy2.cloudfront.net/js/rdstation-forms/stable/rdstation-forms.min.js";

function ContactForm({ eyebrow = "Agende uma demonstração", title = "Tudo pronto para conhecer o Agent Builder", text = "Preencha as informações e agende sua demonstração.", points, anchorId = "agendar" }) {
  const mounted = useRef(false);
  const POINTS = points || ["Demonstração guiada por especialista", "Casos de uso aplicados ao seu negócio", "Sem compromisso"];

  useEffect(() => {
    if (mounted.current) return;
    mounted.current = true;

    const init = () => {
      try {
        if (window.RDStationForms) {
          new window.RDStationForms(RD_FORM_ID, RD_TOKEN).createForm();
          // Remove our loading placeholder once the form has been injected.
          const tryClean = (n) => {
            const host = document.getElementById(RD_FORM_ID);
            const ph = host && host.querySelector(".agendar-loading");
            const hasForm = host && host.querySelector("form");
            if (ph && hasForm) { ph.remove(); return; }
            if (n < 40) setTimeout(() => tryClean(n + 1), 150);
          };
          tryClean(0);
        }
      } catch (e) { /* RD Station handles its own errors */ }
    };

    // Reuse the library if it's already on the page; otherwise inject it once.
    const existing = document.querySelector('script[src="' + RD_SCRIPT + '"]');
    if (window.RDStationForms) {
      init();
    } else if (existing) {
      existing.addEventListener("load", init);
    } else {
      const s = document.createElement("script");
      s.type = "text/javascript";
      s.src = RD_SCRIPT;
      s.async = true;
      s.addEventListener("load", init);
      document.body.appendChild(s);
    }
  }, []);

  return (
    <section className="agendar" id={anchorId}>
      <div className="container">
        <Reveal className="agendar-card">
          <div className="agendar-grid">
            <div className="agendar-copy">
              <Eyebrow>{eyebrow}</Eyebrow>
              <h2>{title}</h2>
              <p>{text}</p>
              <ul className="agendar-points">
                {POINTS.map((pt) => (
                  <li key={pt}><Check /> {pt}</li>
                ))}
              </ul>
            </div>
            <div className="agendar-formwrap">
              <div role="main" id={RD_FORM_ID}>
                <div className="agendar-loading">Carregando formulário…</div>
              </div>
            </div>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

Object.assign(window, { ContactForm });
