import * as htmlToImage from "html-to-image";

class ScreenShotTool {
  public async capture(selector: string) {
    const currentUrl: string = encodeURIComponent(window.location.href);

    try {
      const dialogElement = document.querySelector(selector);

      const contentElement =
        dialogElement?.querySelector(".modal-content") ?? dialogElement;

      // console.log(contentElement);

      if (!contentElement) {
        console.error("Dialog content not found");
        window.location.href = `/support/create?from=${currentUrl}`;
        return;
      }

      // Sleep 120ms
      await new Promise((resolve) => setTimeout(resolve, 120));

      const dataUrl = await htmlToImage.toPng(contentElement as HTMLElement, {
        filter: (node) => {
          if (node instanceof HTMLImageElement) {
            const src = node.src || "";
            return (
              node.complete &&
              node.naturalWidth !== 0 &&
              !src.includes("id.1s.co.za")
            );
          }
          return true;
        },
        onImageErrorHandler: (event, options) => {
            console.log(event)
            console.log(options)
        },

        style: {
          transform: "scale(1)",
          transformOrigin: "top left",
        },
        cacheBust: true,
      });

      // console.log(dataUrl)

      // console.log("Screenshot captured with dom-to-image");
      sessionStorage.setItem("supportScreenshot", dataUrl);
      window.location.href = `/support/create?from=${currentUrl}`;
    } catch (error) {
      console.error("Screenshot capture failed:", error);
      console.log(error)
      alert("Screenshot capture failed. Please try again or contact support.");
    }
  }
}

let toolInstance: ScreenShotTool | null = null;

export default function useScreenShotter(): ScreenShotTool {
  if (!toolInstance) {
    toolInstance = new ScreenShotTool();
  }
  return toolInstance;
}
