import React, { useEffect, useState } from "react";
import { config } from "../config";

/**
 * This is based on Rodney Urquhart's example https://github.com/RodneyU215
 * https://github.com/Webflow-Examples/Apps-v2-Hybrid-Auth-Demo/tree/main#key-components
 * https://www.loom.com/share/28afbb72a30e42ca9333a77e65fbd025
 *
 * tl;dr app.nocodelytics.com/webflow_auth.html will post the token with
 * `window.parent.postMessage(token, extensionURL)`
 *
 * This component listens to that event and save the token in local storage
 */
export const AuthIFrame: React.FC = () => {
  const [url, setUrl] = useState<string>();
  const [done, setDone] = useState<boolean>(false);

  const handleMessage = (event: MessageEvent) => {
    if (event.origin.startsWith(config.baseUrl)) {
      localStorage.setItem(config.localstorageKeys.token, event.data);
      console.info(
        `new token received from ${config.authIFrameUrl}`,
        event.data
      );
      window.removeEventListener("message", handleMessage);
      setUrl("");
      setDone(true);
    } else {
      return;
    }
  };

  useEffect(() => {
    window.addEventListener("message", handleMessage);
    setUrl(`${config.authIFrameUrl}`);
    return () => {
      window.removeEventListener("message", handleMessage);
    };
  }, []);

  if (done) {
    return null;
  }
  return url ? <iframe style={{}} src={url} /> : null;
};
