// [TSM.ID].[11031972] -- All Rights Reserved. Proprietary & Confidential.
import { createContext, useContext, useState, useEffect, useCallback } from 'react';

const WasmContext = createContext();

export function WasmProvider({ children }) {
  const [wasmModule, setWasmModule] = useState(null);
  const [isWasmReady, setIsWasmReady] = useState(false);
  const [wasmLogs, setWasmLogs] = useState([]);

  const addLog = useCallback((msg) => {
    setWasmLogs(prev => [...prev, `[${new Date().toLocaleTimeString()}] ${msg}`]);
  }, []);

  useEffect(() => {
    async function loadWasm() {
      try {
        // Menggunakan Vite ignore agar kompilator tidak gagal jika file ini baru akan ada saat di-build oleh Docker.
        const wasm = await import(/* @vite-ignore */ '/sdk/xcu_wasm_sdk.js');
        
        // Inisialisasi Biner WASM
        if (wasm.default) {
            await wasm.default();
        }
        
        setWasmModule(wasm);
        setIsWasmReady(true);
        addLog("WASM SDK (Alien Tech) berhasil disuntikkan ke dalam V8 Engine Browser.");
      } catch (err) {
        console.error("Gagal memuat XCU WASM SDK:", err);
        addLog("PERINGATAN: Modul WASM gagal dimuat. Kriptografi Pasca-Kuantum offline.");
      }
    }

    loadWasm();
  }, [addLog]);

  const triggerPostQuantumShield = async () => {
    if (!wasmModule) return addLog("GAGAL: Modul WASM tidak aktif.");
    try {
      addLog("Membangkitkan Lattice-based Kyber-1024 Keypair...");
      await wasmModule.enable_post_quantum_shield();
      addLog("POST-QUANTUM SHIELD ACTIVATED. Semua koneksi kini kebal terhadap komputer Kuantum.");
    } catch (e) {
      addLog(`ERROR: ${e.message}`);
    }
  };

  const triggerAegisMatrix = async () => {
    if (!wasmModule) return addLog("GAGAL: Modul WASM tidak aktif.");
    try {
      addLog("Menyuntikkan Sandi Morse Mikroskopis (1% Opacity) ke Canvas...");
      await wasmModule.enable_aegis_forensic_watermark("TSM-" + Math.random().toString(16).substr(2, 8).toUpperCase());
      addLog("AEGIS MATRIX ENGAGED. Identitas penonton terkunci pada layar secara fisik.");
    } catch (e) {
      addLog(`ERROR: ${e.message}`);
    }
  };

  return (
    <WasmContext.Provider value={{ isWasmReady, wasmLogs, triggerPostQuantumShield, triggerAegisMatrix }}>
      {children}
    </WasmContext.Provider>
  );
}

export function useWasm() {
  return useContext(WasmContext);
}
