/* integrations/DocuSignEmbedded.jsx — embedded certification signing.
   Real flow: edge fn docusign-create-envelope → recipient view URL in an
   <iframe class="ds-frame">; detect completion via the iframe return event
   (?event=signing_complete) and by polling applications.signed_at.
   Always degrades to a simulated signing so the flow completes without a
   real DocuSign account. Highest-anxiety step — voice stays warm + plain.
   Globals: React, Portal, Icon, window.portalSupabase, window.portalAnalytics.
   Exposes: DocuSignEmbedded (global). */
/* eslint-disable */
const { useState: useDS, useEffect: useEDS, useRef: useRefDS } = React;

function DocuSignEmbedded({ applicationId, application, onSigned }) {
  const alreadySigned = !!(application && application.signed_at);
  const [signed, setSigned] = useDS(alreadySigned);
  const [busy, setBusy] = useDS(false);
  const [signingUrl, setSigningUrl] = useDS(null);
  const [error, setError] = useDS(null);
  const iframeRef = useRefDS(null);
  const pollRef = useRefDS(null);

  const configured = !window.PORTAL_DEMO && !!window.portalSupabase;

  function clearPoll() {
    if (pollRef.current) { clearInterval(pollRef.current); pollRef.current = null; }
  }
  useEDS(function () { return clearPoll; }, []);

  function markSigned() {
    clearPoll();
    setSigned(true);
    setSigningUrl(null);
    setBusy(false);
    window.portalAnalytics && window.portalAnalytics.log("docusign_envelope_signed", {
      step: "stage2", metadata: { application_id: applicationId }
    });
    onSigned && onSigned();
  }

  // Listen for the DocuSign return: iframe redirects to a return URL with
  // ?event=signing_complete. We can't read cross-origin URLs, so we also
  // poll signed_at below; this catches same-origin return pages + postMessage.
  useEDS(function () {
    if (!signingUrl) return;
    function onMsg(e) {
      try {
        const d = e.data;
        const ev = (d && (d.event || d.docusignEvent)) ||
          (typeof d === "string" && d.indexOf("signing_complete") !== -1 ? "signing_complete" : null);
        if (ev === "signing_complete") markSigned();
      } catch (err) {}
    }
    window.addEventListener("message", onMsg);

    // Poll signed_at every 4s as the reliable cross-origin fallback.
    const sb = window.portalSupabase;
    if (sb) {
      pollRef.current = setInterval(async function () {
        try {
          const { data } = await sb.from("applications").select("signed_at").eq("id", applicationId).maybeSingle();
          if (data && data.signed_at) markSigned();
        } catch (err) {}
      }, 4000);
    }
    return function () { window.removeEventListener("message", onMsg); clearPoll(); };
  }, [signingUrl]);

  function tryReadIframeReturn() {
    // Same-origin return pages only; cross-origin throws and we ignore.
    try {
      const f = iframeRef.current;
      const url = f && f.contentWindow && f.contentWindow.location && f.contentWindow.location.href;
      if (url && url.indexOf("event=signing_complete") !== -1) markSigned();
    } catch (err) {}
  }

  function simulateSign() {
    setBusy(true);
    setError(null);
    setTimeout(function () { markSigned(); }, 800);
  }

  async function startReal() {
    setError(null);
    setBusy(true);
    try {
      const sb = window.portalSupabase;
      const { data, error: ierr } = await sb.functions.invoke("docusign-create-envelope", {
        body: { application_id: applicationId }
      });
      if (ierr) throw ierr;
      const url = data && data.signing_url;
      if (!url) throw new Error("no-signing-url");
      setSigningUrl(url);
      setBusy(false);
      window.portalAnalytics && window.portalAnalytics.log("docusign_envelope_sent", {
        step: "stage2", metadata: { application_id: applicationId }
      });
    } catch (err) {
      console.warn("[portal] DocuSign unavailable, falling back to demo signing:", err && err.message);
      // Degrade gracefully — let them complete via the demo path.
      setBusy(false);
      simulateSign();
    }
  }

  // Persistent signed confirmation.
  if (signed) {
    return (
      <div className="ds-placeholder done">
        <div className="dsp-icon"><Icon name="check" size={22} /></div>
        <div className="dsp-title">Certification signed</div>
        <p className="dsp-sub">Thank you — that's the last signature we need. We have everything to review your application.</p>
      </div>
    );
  }

  // Active embedded signing iframe.
  if (signingUrl) {
    return (
      <div>
        <iframe
          ref={iframeRef}
          className="ds-frame"
          src={signingUrl}
          title="Sign your certification"
          onLoad={tryReadIframeReturn}
        />
        <div className="tb-text" style={{ marginTop: 8 }}>
          <Icon name="lock" size={13} className="lock" /> Secure signing by DocuSign. This page updates automatically when you're done.
        </div>
      </div>
    );
  }

  // Pre-signing / DEMO / not-configured placeholder.
  return (
    <div className="ds-placeholder">
      <div className="dsp-icon"><Icon name="pen" size={22} /></div>
      <div className="dsp-title">One quick signature</div>
      <p className="dsp-sub">You'll sign a brief certification — bankruptcy, eviction, and accuracy disclosures — right here. No printing.</p>
      {error && <div className="field-err"><Icon name="alert" size={13} /> {error}</div>}
      <button
        type="button"
        className="btn block"
        onClick={configured ? startReal : simulateSign}
        disabled={busy}
      >
        {busy
          ? <span className="spinner" aria-label="Preparing" />
          : (configured
              ? <span><Icon name="pen" size={15} /> Review &amp; sign certification</span>
              : "Sign certification (demo)")}
      </button>
    </div>
  );
}
