import loadable from '@loadable/component';
import * as Sentry from '@sentry/react';
import { PostHogProvider } from 'posthog-js/react';
import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
import { AppConfig } from './config/appConfig';
import { checkNativeMethodSupported } from './offlineApp/OfflineAppHelper';
import { offlineAppService } from './offlineApp/OfflineAppService';
import { useAuthStore } from './store';

const originalUserRole = useAuthStore.getState().originalUserRole;
if (
  import.meta.env.VITE_MODE !== 'development' &&
  import.meta.env.VITE_MODE !== 'staging' &&
  import.meta.env.VITE_MODE !== 'demo' &&
  originalUserRole !== 'superadmin'
) {
  // eslint-disable-next-line @typescript-eslint/no-empty-function
  console.log = () => {};
  // eslint-disable-next-line @typescript-eslint/no-empty-function
  console.warn = () => {};
}

// Global debugger utility
declare global {
  // eslint-disable-next-line no-var
  var apConsole: {
    log: (...args: any[]) => void;
    warn: (...args: any[]) => void;
    error: (...args: any[]) => void;
  };
}

// Determine app type for native bridge and sharing console.error to print in native app
const appType = window.navigator?.userAgent?.indexOf('AssessPrepMac') > -1 ? 'mac' : '';
if (appType === 'mac' && checkNativeMethodSupported(appType, 'printLog')) {
  const originalConsoleError = console.error.bind(console);
  console.error = (...args) => {
    // Always call the original console.error
    originalConsoleError(...args);
    try {
      const handler = window?.webkit?.messageHandlers?.macDownloadHelper;
      if (!handler?.postMessage) return;

      const firstArg = args[0];
      let value = '';

      if (firstArg && typeof firstArg === 'object' && 'message' in firstArg) {
        value = firstArg.message;
      } else if (typeof firstArg === 'string') {
        value = firstArg;
      } else {
        value = args
          .map((a) => {
            try {
              if (a instanceof Error && a.message) return a.message;
              if (a && typeof a === 'object' && 'message' in a && a.message) return a.message;
              if (typeof a === 'string') return a;
              return JSON.stringify(a);
            } catch (e) {
              return String(a);
            }
          })
          .join(' ');
      }

      offlineAppService.executeAppMethod({ key: 'printLog', value: JSON.stringify(value) });
    } catch (e) {
      //IMP: Silently ignore errors in the bridge to avoid recursive logging
    }
  };
}

if (AppConfig.mode === 'development1' && typeof window !== 'undefined') {
  const reactScan = loadable.lib(() => import('react-scan'));
  reactScan.load().then((module: any) => {
    console.log('scan enabled');
    module.scan({
      enabled: false,
      log: true, // logs render info to console (default: false)
    });
  });
}
// Check if we're in development/debug mode
const isShowConsoleLogs = !['production', 'demo'].includes(import.meta.env.VITE_MODE || '');

// Create optimized global apConsole object
globalThis.apConsole = {
  log: (...args: any[]) => {
    if (isShowConsoleLogs) {
      console.log('[AP_DEBUG]', ...args);
    }
  },
  warn: (...args: any[]) => {
    if (isShowConsoleLogs) {
      console.warn('[AP_WARN]', ...args);
    }
  },
  error: (...args: any[]) => {
    console.error('[AP_ERROR]', ...args);
  },
};

if (
  import.meta.env.VITE_MODE === 'production' ||
  import.meta.env.VITE_MODE === 'demo' ||
  import.meta.env.VITE_MODE === 'staging' ||
  import.meta.env.VITE_MODE === 'development1'
) {
  const releaseString = `ap-v3-web-${import.meta.env.VITE_RELEASE_ENV}-${
    import.meta.env.VITE_RELEASE_TIME
  }-${import.meta.env.VITE_RELEASE_VERSION}`;
  const envString = `${import.meta.env.VITE_MODE} - ${import.meta.env.VITE_RELEASE_ENV}`;
  console.log('releaseString', releaseString);
  console.log('envString', envString);
  Sentry.init({
    dsn: 'https://44f1080ae131c8fa754d498294b077d4@o444384.ingest.us.sentry.io/4509250748678144',
    integrations: [Sentry.browserTracingIntegration()],
    // Setting this option to true will send default PII data to Sentry.
    // For example, automatic IP address collection on events
    sendDefaultPii: false,
    tracesSampleRate: 0.0, // we don't want transactions - tracks too many
    environment: envString,
    release: releaseString,
    ignoreErrors: [
      'ResizeObserver loop limit exceeded',
      'ResizeObserver loop completed with undelivered notifications',
    ],
  });

  // ReactGA.initialize('UA-71336374-3');
}

// Check if the current browser is Safari
// const isSafari = getBrowserName() === 'Safari';

const options = {
  api_host: import.meta.env.VITE_PUBLIC_POSTHOG_HOST,
  // Disable session recording for Safari browsers
  // Infinite network requests were occurring in Safari, leading to performance issues
  disable_session_recording: true,
  disable_surveys: true,
};

const container = document.getElementById('root') as HTMLElement;
const root = createRoot(container);

const appElement = (
  <PostHogProvider apiKey={import.meta.env.VITE_PUBLIC_POSTHOG_KEY ?? ''} options={options}>
    <App />
  </PostHogProvider>
);

// Disable StrictMode for China region in development to prevent double-invocation issues
// When we subscribe to realtime events, becasue of StrictMode, the event will be invoked twice.
const shouldDisableStrictMode = AppConfig.region === 'china' && AppConfig.mode === 'development';

root.render(
  shouldDisableStrictMode ? appElement : <React.StrictMode>{appElement}</React.StrictMode>
);
