import { ActivityIndicator, Button, Modal, SafeAreaView, View ,Text} from "react-native";
import React,{ useState } from 'react';
import { CadreProps } from "./type";
import WebView from "react-native-webview";
import { styles } from "./style";
import {CloseBtnVP, LoaderVPView,ButtonAccess} from "./component";
import { WEBVIEW_ERROR_HOOK, captureException } from "./sentry";

const Cadre: React.FC<CadreProps> = (props:CadreProps) => {
    const [onLoading,setOnLoading] = useState(true);
    const [log,setLog] = useState("");

    const playerOriginMatch = props.uri.match(/^https?:\/\/[^/]+/);
    const playerOrigin = playerOriginMatch ? playerOriginMatch[0] : '';

    return (
      <Modal
      animationType="slide"
      transparent={false}
      visible={true}
      >
        <SafeAreaView style={{ flex: 1 }}>
          <WebView
            source={{ uri: props.uri }}
            // VPAID creatives are rendered into iframes with `srcdoc=`, whose
            // URL is `about:srcdoc`. The default whitelist (`http(s)://*`)
            // blocks them and the player falls back to the MP4.
            originWhitelist={['*']}
            style={{ flex: 1 }}
            injectedJavaScriptBeforeContentLoaded={WEBVIEW_ERROR_HOOK}
            onShouldStartLoadWithRequest={(request) => {
              // Sub-frames (VPAID srcdoc, trackers) are always allowed.
              if (request.isTopFrame === false) return true;
              // After the ad ends the SDK shows "Accéder au contenu", so
              // top-frame clicks (advertiser CTA) become legitimate.
              if (props.isValidVisible) return true;
              // During playback the user has no way out of an advertiser
              // page (no SDK button yet) — keep navigation inside the player.
              return !!playerOrigin && request.url.startsWith(playerOrigin);
            }}
            setSupportMultipleWindows={false}
            onMessage={(event: { nativeEvent: { data: any; }; })=>{
              setLog(log+"/n"+event.nativeEvent.data);
              props.onMessage(event.nativeEvent.data)
            }}
            onLoad={()=>{ setOnLoading(false) }}
            onError={(event) => {
              const { description, code, url } = event.nativeEvent || ({} as any);
              captureException(new Error(`WebView load error: ${description || 'unknown'}`), {
                source: 'webview-load',
                extra: { code, url, uri: props.uri },
              });
            }}
            onHttpError={(event) => {
              const { statusCode, description, url } = event.nativeEvent || ({} as any);
              if (statusCode && statusCode >= 400) {
                captureException(new Error(`WebView HTTP ${statusCode}: ${description || ''}`.trim()), {
                  source: 'webview-load',
                  extra: { statusCode, url, uri: props.uri },
                });
              }
            }}
            onRenderProcessGone={(event) => {
              const detail = (event.nativeEvent || ({} as any)).didCrash;
              captureException(new Error(`WebView render process gone (didCrash=${detail})`), {
                source: 'webview-render',
                extra: { didCrash: detail, uri: props.uri },
              });
            }}
            cacheEnabled={false}
            allowsInlineMediaPlayback={true}
          />
          {onLoading && (
            <LoaderVPView/>
          )}
          {props.isValidVisible && (
            <View style={styles.btnAccessContent}>
              <ButtonAccess title={props.labelValidate} onPress={()=>{props.onOpenContenu()}}/>
            </View>
          )}
          {props.isCloseVisible && (
            <View style={styles.btnClose}><CloseBtnVP onPress={props.onClose}/></View>
          )}
        </SafeAreaView>
      </Modal>
    );
  };
  
  export default Cadre;


