// TypeScript; React Navigation with SafeAreaProvider configured.
// iOS 15.4+ or Android API 26+ with WebView 105+.
// npm install react-native-webview@13.16.0 @react-native-community/netinfo@11.4.1
// Install iOS Pods after adding dependencies.
// iOS: configure the following privacy entries in the host app target Info.plist.
// Copy the XML without // into <dict>; customize the purpose strings.
// Attachment photo/video capture needs a camera purpose string.
// <key>NSCameraUsageDescription</key>
// <string>Take photos or record videos to send in chat.</string>
// Attachment video recording with audio needs a microphone purpose string.
// <key>NSMicrophoneUsageDescription</key>
// <string>Record sound for videos you send in chat.</string>
// Configure a photo-library purpose string if the host reads library assets; system-picker-only selection does not need it.
// <key>NSPhotoLibraryUsageDescription</key>
// <string>Access your photo library to select photos and videos to send in chat.</string>

import React, { useEffect, useRef, useState } from 'react';
import { Alert, AppState, Linking, Platform, Pressable, Text, View } from 'react-native';
import { WebView } from 'react-native-webview';
import { useNavigation } from '@react-navigation/native';
import NetInfo from '@react-native-community/netinfo';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

const chatUrl = 'https://knocket.ai/mu/YOUR_IDENTIFIER';
const normalizeChatUrl = (url: string) =>
  url.split(/[?#]/)[0].replace(/\/+$/, '');
const isChat = (url: string) => normalizeChatUrl(url) === normalizeChatUrl(chatUrl);
const getOrigin = (url: string) =>
  url.match(/^https?:\/\/[^/?#\\\s@]+(?=[/?#]|$)/i)?.[0].toLowerCase() || '';
const chatOrigin = getOrigin(chatUrl);
const isChatMessage = (url: string) => !!chatOrigin && getOrigin(url) === chatOrigin;
const external = (url: string) => {
  if (/^(https?:|mailto:|tel:)/i.test(url)) {
    void Linking.openURL(url).catch(() =>
      Alert.alert('Unable to open link', 'Please try again.'));
  }
};
export default function KnocketScreen() {
  const navigation = useNavigation();
  const ref = useRef<WebView | null>(null);
  const [webViewGeneration, setWebViewGeneration] = useState(0);
  const insets = useSafeAreaInsets();
  useEffect(() => {
    const resume = () => {
      ref.current?.injectJavaScript("window.dispatchEvent(new Event('online')); true;");
    };
    const subscription = AppState.addEventListener('change', state => {
      if (state === 'active') resume();
    });
    const unsubscribeNetwork = NetInfo.addEventListener(state => {
      if (AppState.currentState === 'active' && state.isConnected &&
          state.isInternetReachable !== false) resume();
    });
    return () => { subscription.remove(); unsubscribeNetwork(); };
  }, []);
  // The page handles iOS safe areas; keep the WebView full-screen without extra safe-area padding.
  return <View style={{ flex: 1,
    paddingTop: Platform.OS === 'android' ? insets.top : 0,
    paddingBottom: Platform.OS === 'android' ? insets.bottom : 0,
    paddingLeft: Platform.OS === 'android' ? insets.left : 0,
    paddingRight: Platform.OS === 'android' ? insets.right : 0,
  }}><WebView
    key={webViewGeneration}
    ref={ref} source={{ uri: chatUrl }}
    style={{ flex: 1 }}
    javaScriptEnabled domStorageEnabled incognito={false}
    // Keep originWhitelist=['*'] and onShouldStartLoadWithRequest together.
    originWhitelist={['*']}
    allowFileAccess={false}
    automaticallyAdjustContentInsets={false}
    contentInsetAdjustmentBehavior="never"
    allowsInlineMediaPlayback
    mediaPlaybackRequiresUserAction
    renderError={() => <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Unable to load chat. Check your connection and try again.</Text>
      <Pressable accessibilityRole="button" onPress={() => {
        ref.current = null;
        setWebViewGeneration(generation => generation + 1);
      }}><Text>Retry</Text></Pressable>
    </View>}
    mixedContentMode="never" setSupportMultipleWindows
    // Keep the bridge channel and host-control command names unchanged.
    onMessage={event => {
      if (!isChatMessage(event.nativeEvent.url)) return;
      try {
        const message = JSON.parse(event.nativeEvent.data);
        if (!message || typeof message !== 'object' || Array.isArray(message)) return;
        if (message.type === 'closeWebView') {
          if (navigation.canGoBack()) navigation.goBack();
          else Alert.alert('Unable to close chat', 'Open this screen from an app route.');
        } else if (message.type === 'openExternal' && typeof message.url === 'string') {
          external(message.url);
        }
      } catch {}
    }}
    onShouldStartLoadWithRequest={request => {
      if (request.isTopFrame === false) return false;
      if (isChat(request.url)) return true;
      external(request.url);
      return false;
    }}
    onOpenWindow={event => external(event.nativeEvent.targetUrl)}
    // iOS downloads.
    onFileDownload={event => external(event.nativeEvent.downloadUrl)}
    onHttpError={event => {
      if (isChat(event.nativeEvent.url)) {
        Alert.alert('Unable to load chat', 'Check your connection and try again.',
          [{ text: 'Cancel', style: 'cancel' },
           { text: 'Retry', onPress: () => {
             ref.current = null;
             setWebViewGeneration(generation => generation + 1);
           }}]);
      }
    }}
    onContentProcessDidTerminate={() => ref.current?.reload()}
    onRenderProcessGone={() => {
      ref.current = null;
      setWebViewGeneration(generation => generation + 1);
    }}
  /></View>;
}
// Register the screen with the native header hidden.
// <Stack.Screen name="Knocket" component={KnocketScreen} options={{ headerShown: false }} />
// Open from an existing app screen, not as the app root.
// navigation.navigate('Knocket')
// AndroidManifest.xml:
// <uses-permission android:name="android.permission.INTERNET" />
// <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
// <activity android:name=".MainActivity" android:windowSoftInputMode="adjustResize" ... />
// Keep adjustResize; do not add extra system-bar or keyboard padding.