"use strict";

import React, { useEffect, useState } from 'react';
import { ActivityIndicator, Platform, StyleSheet, Text, View } from 'react-native';
import { WebView } from 'react-native-webview';
import * as FileSystem from 'expo-file-system/legacy';
import GViewWebView from './GViewWebView';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
const PdfViewer = ({
  pdfUrl
}) => {
  const [localUri, setLocalUri] = useState(null);
  const [error, setError] = useState(null);
  // Android's WebView has NO native PDF renderer, so a file:// (or direct)
  // PDF loads blank. Route it through Google's gview embed using the
  // (public) remote URL — same approach as DocumentViewer for office docs.
  // iOS WKWebView renders PDFs natively, so we download + show the file.
  const isAndroid = Platform.OS === 'android';
  useEffect(() => {
    if (isAndroid) {
      return;
    }
    let cancelled = false;
    const run = async () => {
      try {
        const target = FileSystem.cacheDirectory + `pdf-${Date.now()}.pdf`;
        const result = await FileSystem.downloadAsync(pdfUrl, target);
        if (cancelled) {
          return;
        }
        setLocalUri(result.uri);
      } catch (e) {
        if (cancelled) {
          return;
        }
        console.log(e?.message);
        setError(e?.message || 'Download failed');
      }
    };
    run();
    return () => {
      cancelled = true;
    };
  }, [pdfUrl, isAndroid]);
  if (isAndroid) {
    return /*#__PURE__*/_jsx(GViewWebView, {
      url: pdfUrl
    });
  }
  if (error) {
    return /*#__PURE__*/_jsx(View, {
      style: styles.center,
      children: /*#__PURE__*/_jsxs(Text, {
        children: ["Couldn't load PDF: ", error]
      })
    });
  }
  if (!localUri) {
    return /*#__PURE__*/_jsx(View, {
      style: styles.center,
      children: /*#__PURE__*/_jsx(ActivityIndicator, {
        size: "large"
      })
    });
  }
  return /*#__PURE__*/_jsx(View, {
    style: styles.container,
    children: /*#__PURE__*/_jsx(WebView, {
      source: {
        uri: localUri
      },
      style: styles.webview,
      originWhitelist: ['*'],
      allowFileAccess: true,
      allowFileAccessFromFileURLs: true,
      allowUniversalAccessFromFileURLs: true
    })
  });
};
export default PdfViewer;
const styles = StyleSheet.create({
  container: {
    flex: 1,
    width: '100%',
    backgroundColor: '#fff'
  },
  webview: {
    flex: 1,
    backgroundColor: '#fff'
  },
  center: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center'
  }
});
//# sourceMappingURL=PdfView.js.map