import React from "react";
import { get } from "lodash";
import { triggerScripts } from "./scripts";

type PageScriptsProps = {
  trackingPayload: any;
  alreadyParsed?: boolean;
};

export const PageScripts: React.FC<PageScriptsProps> = (props) => {
  React.useEffect(() => {
    const { trackingPayload = {}, alreadyParsed = false } = props;

    const parsedTrackingPayload = alreadyParsed
      ? trackingPayload
      : JSON.parse(unescape(trackingPayload));
    // console.log({ parsedTrackingPayload });

    const renderHead: any = document.getElementById("renderHead");
    const renderPreBody: any = document.getElementById("renderPreBody");
    const renderPostBody: any = document.getElementById("renderPostBody");

    if (renderHead) {
      renderHead.innerHTML = get(parsedTrackingPayload, "head", "");
      triggerScripts(renderHead);
    }

    if (renderPreBody) {
      renderPreBody.innerHTML = get(parsedTrackingPayload, "body", "");
      triggerScripts(renderPreBody);
    }

    if (renderPostBody) {
      renderPostBody.innerHTML = get(parsedTrackingPayload, "bodyEnd", "");
      triggerScripts(renderPostBody);
    }
  }, []);
  return null;
};

export default PageScripts;
