import React, { useState, useEffect, createContext, useContext } from 'react';

// Create a context to share the WASM module across components
export const WasmContext = createContext(null);

// Hook to access WASM module
export function useWasm() {
  return useContext(WasmContext);
}

// Component that loads and initializes the WASM module
export function WasmProvider({ children }) {
  const [wasmModule, setWasmModule] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  
  useEffect(() => {
    async function loadWasm() {
      try {
        setLoading(true);
        
        // Instead of using dynamic imports which require correct MIME types,
        // we'll use fetch to load the JavaScript file as text and eval it
        const wasmJsPath = chrome.runtime.getURL('wasm/wasm_app.js');
        console.log('Loading WASM JS from:', wasmJsPath);
        
        // Load the JavaScript file
        const jsResponse = await fetch(wasmJsPath);
        if (!jsResponse.ok) {
          throw new Error(`Failed to load WASM JS: ${jsResponse.status} ${jsResponse.statusText}`);
        }
        
        // Get the JavaScript code as text
        const jsCode = await jsResponse.text();
        
        // Create a function to execute the code in an isolated scope
        let wasmModuleExports = {};
        const moduleFunction = new Function('exports', jsCode + '\nreturn { initSync, default: __wbg_init, init_rhai_env, init_session, lock_session, add_keypair, select_keypair, sign, run_rhai };');
        
        // Execute the function to get the exports
        const wasmModule = moduleFunction(wasmModuleExports);
        
        // Initialize WASM with the binary
        const wasmBinaryPath = chrome.runtime.getURL('wasm/wasm_app_bg.wasm');
        console.log('Initializing WASM with binary:', wasmBinaryPath);
        
        const binaryResponse = await fetch(wasmBinaryPath);
        if (!binaryResponse.ok) {
          throw new Error(`Failed to load WASM binary: ${binaryResponse.status} ${binaryResponse.statusText}`);
        }
        
        const wasmBinary = await binaryResponse.arrayBuffer();
        
        // Initialize the WASM module
        await wasmModule.default(wasmBinary);
        
        // Initialize the WASM environment
        if (typeof wasmModule.init_rhai_env === 'function') {
          wasmModule.init_rhai_env();
        }
        
        console.log('WASM module loaded successfully');
        setWasmModule(wasmModule);
        setLoading(false);
      } catch (error) {
        console.error('Failed to load WASM module:', error);
        setError(error.message || 'Failed to load WebAssembly module');
        setLoading(false);
      }
    }
    
    loadWasm();
  }, []);
  
  if (loading) {
    return <div className="wasm-loading">Loading WebAssembly module...</div>;
  }
  
  if (error) {
    return <div className="wasm-error">Error: {error}</div>;
  }
  
  return (
    <WasmContext.Provider value={wasmModule}>
      {children}
    </WasmContext.Provider>
  );
}
