/* ============================================================
   Visor interactivo de workflows n8n para el lightbox.
   Cárgalo como <script type="text/babel" src="n8n-viewer.jsx">
   ANTES de automatizaciones-app.jsx.
   ============================================================ */

// Carga el web component oficial de n8n una sola vez, recién
// cuando se abre el primer modal (lazy load real).
let _n8nDemoScript = null;
function loadN8nDemo() {
  if (!_n8nDemoScript) {
    _n8nDemoScript = new Promise((ok, err) => {
      const s = document.createElement('script');
      s.type = 'module';
      // versión fijada: el fix de altura de abajo depende de clases internas del shadow DOM
      s.src = 'https://cdn.jsdelivr.net/npm/@n8n_io/n8n-demo-component@1.0.20/n8n-demo.bundled.js';
      s.integrity = 'sha384-aFom9fiO8R2aGLz5XooQK70H33kayU/NpPVVA0OayjMc7Qg+gePQOJOEINwGSx1q';
      s.crossOrigin = 'anonymous';
      s.onload = ok;
      s.onerror = (e) => {
        // un fallo puntual del CDN no debe quedar cacheado: sin esto, todos los
        // visores posteriores mostrarían el error hasta recargar la página
        _n8nDemoScript = null;
        s.remove();
        err(e);
      };
      document.head.appendChild(s);
    });
  }
  return _n8nDemoScript;
}

/**
 * <N8nViewer src="workflows/01-asistente-rrhh-whatsapp.json" />
 * Renderizar SOLO dentro del lightbox (nunca en las tarjetas).
 */
function N8nViewer({ src }) {
  const hostRef = React.useRef(null);
  const [status, setStatus] = React.useState('loading');

  React.useEffect(() => {
    let alive = true;
    setStatus('loading');

    Promise.all([
      loadN8nDemo(),
      fetch(src).then(r => {
        if (!r.ok) throw new Error('HTTP ' + r.status);
        return r.text();
      }),
    ])
      .then(([, json]) => {
        if (!alive || !hostRef.current) return;
        const el = document.createElement('n8n-demo');
        el.setAttribute('workflow', json);
        el.setAttribute('theme', 'dark');
        el.setAttribute('clicktointeract', 'true');   // evita robar el scroll de la página
        el.setAttribute('hidecanvaserrors', 'true');
        el.setAttribute('collapseformobile', 'false');
        hostRef.current.replaceChildren(el);
        // El web component fija su iframe a 300px en el shadow DOM (hoja adoptada);
        // se inyecta un <style> para que llene la altura del lightbox.
        const fillShadow = (tries) => {
          if (!alive) return;
          if (el.shadowRoot) {
            const fix = document.createElement('style');
            fix.textContent = '.embedded_workflow,.canvas-container,.embedded_workflow_iframe{height:100% !important;}';
            el.shadowRoot.appendChild(fix);
          } else if (tries > 0) {
            requestAnimationFrame(() => fillShadow(tries - 1));
          }
        };
        fillShadow(60);
        setStatus('ok');
      })
      .catch(() => alive && setStatus('error'));

    return () => { alive = false; };
  }, [src]);

  return (
    <div className="n8nviewer">
      <div className="n8nviewer__host" ref={hostRef} />
      {status !== 'ok' && (
        <div className="n8nviewer__msg">
          {status === 'loading' ? 'Loading workflow…' : 'Couldn\'t load the preview'}
        </div>
      )}
    </div>
  );
}

/* ---- CSS: pégalo en el <style> de la página ----

.n8nviewer { position: relative; height: min(62vh, 560px); background: var(--navy-900); }
.n8nviewer__host { height: 100%; }
.n8nviewer__host n8n-demo { display: block; height: 100%; }
.n8nviewer__msg { position: absolute; inset: 0; display: grid; place-items: center;
  font-family: var(--font-mono); font-size: 13px; color: var(--text-dim); pointer-events: none; }
@media (max-width: 640px) { .n8nviewer { height: 56vh; } }

--------------------------------------------------- */
