import { useEffect, useMemo, useRef } from "react";

import { useLocalization } from "../../../shared/localization/LocalizationContext";
import { isDevelopment } from "../../../shared/utils/environment";

const B2B_AGENT_URL = isDevelopment()
  ? "http://localhost:3001/app/buyer-bulk-ops-agent"
  : "https://buyer-bulk-ops-agent.vercel.app/app/buyer-bulk-ops-agent";

interface B2BAgentLayoutProps {
  vtexIdclientAutCookie: string;
  account: string;
  locale?: string;
  customerId?: string;
  userId?: string;
}

const containerStyle: React.CSSProperties = {
  display: "flex",
  flexDirection: "column",
  width: "100%",
  height: "100vh",
  overflow: "hidden",
};

const iframeStyle: React.CSSProperties = {
  flex: 1,
  width: "100%",
  height: "100%",
  border: "none",
};

export const B2BAgentLayout = ({
  vtexIdclientAutCookie,
  account,
  locale,
  customerId,
  userId,
}: B2BAgentLayoutProps) => {
  const { t } = useLocalization();
  const iframeRef = useRef<HTMLIFrameElement>(null);

  const agentOrigin = useMemo(() => new URL(B2B_AGENT_URL).origin, []);

  useEffect(() => {
    function postAuthToIframe() {
      const targetWindow = iframeRef.current?.contentWindow;
      if (!targetWindow) return;

      // We send only the token (not the full Cookie header) to reduce exposure.
      targetWindow.postMessage(
        {
          type: "AUTH_TOKEN_UPDATE",
          vtexIdclientAutCookie,
          account,
          locale,
          customerId,
          userId,
        },
        agentOrigin
      );
    }

    function onMessage(event: MessageEvent) {
      // Only accept messages coming from the iframe's origin.
      if (event.origin !== agentOrigin) return;

      // Ensure the message is from the iframe window we embedded.
      if (event.source !== iframeRef.current?.contentWindow) return;

      // Handshake: child tells it is ready; parent responds by sending auth.
      if (event.data?.type === "B2B_AGENT_READY") {
        postAuthToIframe();
      }
    }

    window.addEventListener("message", onMessage);

    // Fallback: try once after iframe load in case READY was missed.
    const iframe = iframeRef.current;
    const onLoad = () => {
      // Small delay to allow the iframe app to attach its message listener.
      setTimeout(() => {
        postAuthToIframe();
      }, 150);
    };

    if (iframe) iframe.addEventListener("load", onLoad);

    // If token changes while iframe is already up, proactively resend.
    // This is safe because we still constrain by agentOrigin.
    if (iframeRef.current?.contentWindow && vtexIdclientAutCookie) {
      // Delay to avoid racing the initial mount.
      setTimeout(() => {
        postAuthToIframe();
      }, 1);
    }

    return () => {
      window.removeEventListener("message", onMessage);
      if (iframe) iframe.removeEventListener("load", onLoad);
    };
  }, [vtexIdclientAutCookie, customerId, userId, agentOrigin]);

  return (
    <section style={containerStyle} data-fs-bp-b2b-agent>
      <iframe
        ref={iframeRef}
        style={iframeStyle}
        data-fs-bp-b2b-agent-iframe
        src={B2B_AGENT_URL}
        title={t("b2bAgent.titles.b2bAgent")}
        allow="clipboard-read; clipboard-write"
        sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-modals"
      />
    </section>
  );
};
