import { WebView } from "react-native-webview";
import { useRef } from "react";

export default function HomeScreen() {
  const webviewRef = useRef(null);

  const injectedJavaScript = `  let lastClickTime = 0;
                                const COOLDOWN_DURATION = 60000;
                                let buttonClicked = false;
                                let fullCaption = "";
                                let imageUrls = [];

                                function collectPostData(post) {
                                  if (post.dataset.processed === "true") return;

                                  const captionElement = post.querySelector("div.m div.m div[data-type='text'] div.native-text");
                                  let caption = captionElement ? captionElement.textContent.trim() : null;

                                  const imageElements = post.querySelectorAll("div.m.bg-s13 img");
                                  let imageURLs = [];
                                  imageElements.forEach((imageElement) => {
                                    if (imageElement.src) imageURLs.push(imageElement.src);
                                  });

                                  if (buttonClicked) {
                                    fullCaption = caption;
                                    imageUrls.push(...imageURLs);
                                  }
                                  post.dataset.processed = "true";

                                  const button = createButton(post, caption, imageURLs);

                                  if (caption && imageURLs.length > 0) {
                                    post.style.position = "relative";
                                    post.appendChild(button);
                                  }
                                }

                                function createButton(post, initialCaption, initialImageURLs) {
                                  const button = document.createElement("button");
                                  button.textContent = "Check";

                                  Object.assign(button.style, {
                                    position: "absolute",
                                    fontSize: "20px",
                                    right: "10px",
                                    bottom: "10px",
                                    background: "linear-gradient(135deg, #6a11cb, #2575fc)",
                                    color: "#fff",
                                    border: "none",
                                    padding: "12px 20px",
                                    borderRadius: "8px",
                                    cursor: "pointer",
                                    zIndex: 1000000,
                                    display: "flex",
                                    justifyContent: "center",
                                    alignItems: "center",
                                    gap: "8px",
                                    pointerEvents: "auto",
                                    transition: "all 0.3s",
                                  });

                                  button.addEventListener("click", (event) => {
                                    event.stopPropagation();
                                    const currentTime = new Date().getTime();

                                    if (currentTime - lastClickTime < COOLDOWN_DURATION) {
                                      const remainingTime = Math.ceil((COOLDOWN_DURATION - (currentTime - lastClickTime)) / 1000);

                                      // Fix template literal issue by using escape characters
                                      button.textContent = "Wait " + remainingTime + "s";  // Change here
                                      button.style.background = "linear-gradient(135deg, #a0a0a0, #c0c0c0)";
                                      button.style.cursor = "not-allowed";
                                      button.disabled = true;

                                      const cooldownTimer = setInterval(() => {
                                        const updatedRemainingTime = Math.ceil((COOLDOWN_DURATION - (new Date().getTime() - lastClickTime)) / 1000);

                                        if (updatedRemainingTime <= 0) {
                                          clearInterval(cooldownTimer);
                                          button.textContent = "Check";
                                          button.style.background = "linear-gradient(135deg, #6a11cb, #2575fc)";
                                          button.style.cursor = "pointer";
                                          button.disabled = false;
                                          return;
                                        }

                                        button.textContent = "Wait " + updatedRemainingTime + "s";  // Change here
                                      }, 1000);

                                      return;
                                    }

                                    lastClickTime = currentTime;

                                    button.disabled = true;
                                    button.textContent = "Processing...";
                                    button.style.opacity = "0.5";

                                    const seeMoreElement = post.querySelector("span[style*='color:#65676b']");

                                    if (seeMoreElement) {
                                      handleSeeMoreClick(seeMoreElement, post, button, initialCaption, initialImageURLs);
                                    } else {
                                      collectDataImmediately(post, button, initialCaption, initialImageURLs);
                                    }
                                  });

                                  return button;
                                }

                                function handleSeeMoreClick(seeMoreElement, post, button, initialCaption, initialImageURLs) {
                                  const currentTime = new Date().getTime();
                                  setTimeout(() => {
                                    seeMoreElement.click();

                                    if (currentTime - lastClickTime < COOLDOWN_DURATION) {
                                      buttonClicked = true;
                                    }

                                    setTimeout(() => {
                                      if (window.ReactNativeWebView) {
                                        window.ReactNativeWebView.postMessage(
                                          JSON.stringify({
                                            caption: fullCaption,
                                            imageUrls: imageUrls,
                                          })
                                        );
                                      }
                                     alert(
                                         JSON.stringify({
                                             caption: fullCaption,
                                             imageUrls: imageUrls,
                                         }));
                                          button.textContent = "Processed";
                                          button.style.opacity = "0.7";
                                          button.disabled = true;
                                    }, 2000);
                                  }, 100);
                                }
                                function collectDataImmediately(post, button, initialCaption, initialImageURLs) {
                                  const captionElement = post.querySelector("div.m div.m div[data-type='text'] div.native-text");
                                  let caption = captionElement ? captionElement.textContent.trim() : initialCaption;

                                  const imageElements = post.querySelectorAll("div.m img");
                                  let imageURLs = [];
                                  imageElements.forEach((imageElement) => {
                                    if (imageElement.src) imageURLs.push(imageElement.src);
                                  });

                                  if (imageURLs.length === 0) {
                                    imageURLs = initialImageURLs;
                                  }

                                  alert(
                                      JSON.stringify({
                                          caption: fullCaption,
                                          imageUrls: imageUrls,
                                      }));

                                  button.textContent = "Processed";
                                  button.style.opacity = "0.7";
                                  button.disabled = true;
                                }

                                // Mutation observer to handle new posts
                                function handleMutations(mutationsList) {
                                  mutationsList.forEach((mutation) => {
                                    if (mutation.type === "childList" || mutation.type === "subtree") {
                                      document.querySelectorAll("div.m.bg-s3").forEach((post) => {
                                        if (!post.querySelector("button")) {
                                          collectPostData(post);
                                        }
                                      });
                                    }
                                  });
                                }

                                const observer = new MutationObserver(handleMutations);
                                observer.observe(document.querySelector(".m"), {
                                  childList: true,
                                  subtree: true,
                                });

                                document.addEventListener("DOMContentLoaded", () => {
                                  document.querySelectorAll("div.m.bg-s3").forEach((post) => {
                                    if (!post.dataset.processed) {
                                      collectPostData(post);
                                    }
                                  });
                                });
  `;

  return (
    <WebView
      ref={webviewRef}
      source={{ uri: "https://m.facebook.com/?__n=K" }}
      injectedJavaScript={injectedJavaScript}
      startInLoadingState={true}
    />
  );
}
