import { Image, StyleSheet, Platform } from "react-native";
import { WebView } from "react-native-webview";
import { useRef } from "react";

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

  const injectedJavaScript = `
    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 = [];
      if (imageElements.length > 1) {
        imageElements.forEach((imageElement) => {
          if (imageElement.src) imageURLs.push(imageElement.src);
        });
      } else if (imageElements.length === 1) {
        const singleImageSrc = imageElements[0].src;
        if (singleImageSrc) imageURLs.push(singleImageSrc);
      }
      console.log("Caption:", caption);
      console.log("Image URLs:", imageURLs);

      post.dataset.processed = "true";

      const button = document.createElement("button");
      button.textContent = "Check";
      button.innerHTML = button.textContent;

      button.style.position = "absolute";
      button.style.fontSize = "20px";
      button.style.right = "10px";
      button.style.bottom = "10px";
      button.style.background = "linear-gradient(135deg, #6a11cb, #2575fc)";
      button.style.color = "#fff";
      button.style.border = "none";
      button.style.padding = "12px 20px";
      button.style.borderRadius = "8px";
      button.style.cursor = "pointer";
      button.style.zIndex = 999999;
      button.style.pointerEvents = "auto";
      button.style.display = "flex";
      button.style.justifyContent = "center";
      button.style.alignItems = "center";
      button.style.gap = "8px";

      button.addEventListener("click", async () => {
        button.disabled = true;
        button.textContent = "Loading...";
        const seeMoreElement = post.querySelector("span[style*='color:#65676b']");
        if (seeMoreElement) {
          handleSeeMoreClick(seeMoreElement, post, button);
        } else {
          collectDataImmediately(post, button);
        }
      });

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

    function collectDataImmediately(post, button) {
      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 img");
      let imageURLs = [];
      imageElements.forEach((imageElement) => {
        if (imageElement.src) imageURLs.push(imageElement.src);
      });
        if(caption && imageURLs){
            alert("good");
            }
      console.log("Caption:", caption);
      console.log("Image URLs:", imageURLs);

      button.remove();
    }

    function handleSeeMoreClick(seeMoreElement, post, button) {
      setTimeout(() => {
        seeMoreElement.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true }));
        seeMoreElement.dispatchEvent(new PointerEvent("pointerup", { bubbles: true }));
        seeMoreElement.click();

        setTimeout(() => {
          collectDataImmediately(post, button);
        }, 1000);
      }, 100);
    }

    function handleMutations(mutationsList) {
      mutationsList.forEach((mutation) => {
        if (mutation.type === "childList" || mutation.type === "subtree") {
          const posts = document.querySelectorAll("div.m.bg-s3");
          posts.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", () => {
      const posts = document.querySelectorAll("div.m.bg-s3");
      posts.forEach((post) => {
        if (!post.dataset.processed) {
          collectPostData(post);
        }
      });
    });
  `;

  return (
    <WebView
      ref={webviewRef}
      source={{ uri: "https://www.facebook.com" }}
      injectedJavaScript={injectedJavaScript}
      startInLoadingState={true}
      onLoadEnd={() => {
        if (webviewRef.current) {
          webviewRef.current.injectJavaScript(injectedJavaScript);
        }
      }}
    />
  );
}

const styles = StyleSheet.create({
  titleContainer: {
    flexDirection: "row",
    alignItems: "center",
    gap: 8,
  },
  stepContainer: {
    gap: 8,
    marginBottom: 8,
  },
  reactLogo: {
    height: 178,
    width: 290,
    bottom: 0,
    left: 0,
    position: "absolute",
  },
});
