// === GHL Native Form Modal — embeds GoHighLevel forms with full embed attributes ===
const { useState, useEffect, useRef } = React;

const GHL_FORMS = {
  call: {
    id: 'b3mVFZEuBBhOF4t9aCDP',
    src: 'https://api.leadconnectorhq.com/widget/form/b3mVFZEuBBhOF4t9aCDP',
    formName: 'Agendar llamada - one twenty',
    height: 600,
    title: 'Agenda tu llamada',
    sub: 'Diagnóstico de 15 min · sin venta',
  },
  guide: {
    id: '1DqR5kEJpv27ZCvUjYR0',
    src: 'https://api.leadconnectorhq.com/widget/form/1DqR5kEJpv27ZCvUjYR0',
    formName: 'Guía inversionista - one twenty',
    height: 463,
    title: 'Recibir la guía Top 10',
    sub: 'Las 10 mejores preconstrucciones de Miami',
  },
};

function GhlFormModal({ type, onClose }) {
  const cfg = GHL_FORMS[type];
  const containerRef = useRef(null);

  useEffect(() => {
    if (!cfg) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);

    // Build the iframe with the exact attributes GHL's embed script expects.
    // We do it via innerHTML so the embed script picks up the data-* attributes
    // (some versions of form_embed.js wire listeners on parse).
    if (containerRef.current) {
      containerRef.current.innerHTML = `
        <iframe
          src="${cfg.src}"
          style="width:100%;height:100%;border:none;border-radius:0"
          id="inline-${cfg.id}"
          data-layout='{"id":"INLINE"}'
          data-trigger-type="alwaysShow"
          data-trigger-value=""
          data-activation-type="alwaysActivated"
          data-activation-value=""
          data-deactivation-type="neverDeactivate"
          data-deactivation-value=""
          data-form-name="${cfg.formName}"
          data-height="${cfg.height}"
          data-layout-iframe-id="inline-${cfg.id}"
          data-form-id="${cfg.id}"
          title="${cfg.formName}"
        ></iframe>
      `;
    }

    // Inject GHL embed script (idempotent: remove + re-add so it re-scans new iframes)
    const old = document.querySelector('script[data-ghl-embed]');
    if (old) old.remove();
    const s = document.createElement('script');
    s.src = 'https://link.msgsndr.com/js/form_embed.js';
    s.async = true;
    s.setAttribute('data-ghl-embed', 'true');
    document.body.appendChild(s);

    return () => document.removeEventListener('keydown', onKey);
  }, [type, onClose]);

  if (!cfg) return null;

  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal modal-ghl" onClick={(e) => e.stopPropagation()}>
        <div className="modal-head">
          <div>
            <div style={{ fontFamily: 'Instrument Serif, serif', fontSize: 20, color: 'var(--ink)', lineHeight: 1.1 }}>
              {cfg.title}
            </div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 2 }}>{cfg.sub}</div>
          </div>
          <button className="modal-close" onClick={onClose} aria-label="Cerrar">✕</button>
        </div>
        <div className="modal-body ghl-body" ref={containerRef}></div>
      </div>
    </div>
  );
}

window.GhlFormModal = GhlFormModal;
