import Head from 'next/head';

const CDN_BASE = 'https://cdn.jsdelivr.net/npm/';
const PACKAGE_NAME = '@zoomus/websdk';
const PACKAGE_VERSION = '1.8.1';
const PACKAGE_DIR = `${CDN_BASE}${PACKAGE_NAME}@${PACKAGE_VERSION}`;

const ZOOM_DIR = '/dist/lib';
const AV_DIR = '/av';
const VERSION_PREFIX = '5793_';

const ZOOM_RESOURCE = `${PACKAGE_DIR}${ZOOM_DIR}${AV_DIR}${VERSION_PREFIX}`;

function getResource(resource) {
  return `${ZOOM_RESOURCE}${resource}`;
}

const jsResources = [
  'video_s.min.js',
  'sharing_s.min.js',
  'js_audio_process.min.js',
  'js_media.min.js',
];

const wasmResources = [
  'audio.encode.wasm',
  'video.mt.wasm',
  'video.simd.wasm',
  'ideo.decode.wasm',
];

function createJSResourcePreload(src) {
  return (
    <link
      rel="preload"
      href={getResource(src)}
      as="script"
      crossOrigin="anonymous"
    />
  );
}

function createWASMResourcePreload(src) {
  return (
    <link
      rel="preload"
      href={getResource(src)}
      as="fetch"
      type="application/wasm"
      crossOrigin="anonymous"
    />
  );
}

function fetchResources(resource) {
  return fetch(getResource(resource), {
    method: 'GET',
    mode: 'cors',
    keepalive: true,
  });
}

export function ZoomLoader({ onLoad, onSuccess }) {
  useEffect(() => {
    onLoad();
    let mounted = true;
    
    const resources = [
      ..jsResources,
      ..wasmResources,
    ];
    
    Promise.all(resources.map(fetchResource)).then(() => {
      if (mounted) {
         onSuccess();
      }
    });
    
    return () => {
      mounted = false;
    };
  }, [onSuccess]);

  return (
    <Head>
      {/* CDN Preconnect */}
      <link rel="preconnect" href={CDN_BASE} />
      <link rel="dns-prefetch" href={CDN_BASE} />
      {jsResources.map(createJSResourcePreload)}
      {wasmResources.map(createWASMResourcePreload)}
    </Head>
  );
}
