/********************************************************************************************
* Copyright (C) 2025 Acoustic, L.P. All rights reserved.
*
* NOTICE: This file contains material that is confidential and proprietary to
* Acoustic, L.P. and/or other developers. No license is granted under any intellectual or
* industrial property rights of Acoustic, L.P. except as may be provided in an agreement with
* Acoustic, L.P. Any unauthorized copying or distribution of content from this file is
* prohibited.
********************************************************************************************/
import React, { useCallback, useEffect, useRef, forwardRef } from "react";
import { View, StyleSheet, Platform, NativeModules, findNodeHandle } from "react-native";
import type { LayoutChangeEvent } from "react-native";
import TLTRN from "../TLTRN";

interface ConnectProps {
    children: React.ReactNode;
    captureKeyboardEvents: boolean;
    navigationRef?: React.RefObject<any>;
}

const Connect = forwardRef<any, ConnectProps>(
    ({ children, captureKeyboardEvents, navigationRef }, ref) => {
      const navigation = navigationRef || useRef(null);
  
  // Handle forwarded ref
  useEffect(() => {
    if (ref && typeof ref === "object" && ref !== null) {
      navigation.current = ref.current;
    } else if (typeof ref === "function") {
      ref(navigation.current);
    }
  }, [ref]);

  const currentRoute = useRef<string | undefined>(undefined);
  const initial = useRef<boolean>(false);

  useEffect(() => {
    TLTRN.interceptKeyboardEvents(captureKeyboardEvents);
  }, [captureKeyboardEvents]);

  useEffect(() => {
    if (
      !navigation.current ||
      typeof navigation.current.addListener !== "function" ||
      typeof navigation.current.getCurrentRoute !== "function"
    ) {
      console.warn(
        "Connect: The Connect component's ref must be a NavigationContainer with a ref."
      );
      return;
    }

    const unsubscribe = navigation.current.addListener("state", () => {
      currentRoute.current = extractName(navigation);
      console.log("State change - ", currentRoute.current);

      if (Platform.OS === "ios" && currentRoute.current) {
        TLTRN.logScreenViewPageName(currentRoute.current);
      } else if (Platform.OS === "android") {
        TLTRN.logScreenViewPageName(currentRoute.current);
        TLTRN.logScreenLayout(currentRoute.current);
      }
    });

    return unsubscribe;
  }, [navigation]);

  const onStartShouldSetResponderCapture = useCallback(
    (event: any) => {
      currentRoute.current = extractName(navigation);
      if (currentRoute.current) {
        TLTRN.logScreenViewPageName(currentRoute.current);
      }
      TLTRN.logClickEvent(event);
      return false;
    },
    [navigation]
  );

  const onLayout = useCallback(
    (event: LayoutChangeEvent) => {
      if (initial.current) {
        return false;
      }
      initial.current = true;

      console.log("event - ", event.nativeEvent);

      currentRoute.current = navigation.current?.getCurrentRoute()?.name;
      if (Platform.OS === "ios" && currentRoute.current) {
        TLTRN.logScreenViewPageName(currentRoute.current);
      } else if (Platform.OS === "android") {
        TLTRN.logScreenLayout(currentRoute.current);
      }
      return true;
    },
    [navigation]
  );

  return (
    <View
      style={styles.connect_main}
      onLayout={onLayout}
      onStartShouldSetResponderCapture={onStartShouldSetResponderCapture}
    >
      {children}
    </View>
  );
});

function extractName(navigation: any): string {
  const routeParams = navigation.current?.getCurrentRoute()?.params;
  if (routeParams) {
    const { name } = routeParams;
    return name || "";
  }
  return navigation.current?.getCurrentRoute()?.name || "";
}

export default Connect;

const styles = StyleSheet.create({
  connect_main: {
    flex: 1,
  },
});