/* EireneEduCloud — AES-256 content protection
   Eirene Technologies Limited
   Uses the locally-bundled CryptoJS (assets/vendor/crypto-js.min.js) — no CDN, fully offline.

   Scheme: AES-256-CBC with a PBKDF2-derived 256-bit key.
   Envelope (JSON):  { v:1, alg:"AES-256-CBC", kdf:"PBKDF2-SHA256", it:<iterations>,
                       salt:<hex>, iv:<hex>, ct:<base64> }
   Decryption happens in-browser at runtime so packaged content is never shipped in clear text. */
(function (w) {
  var C = w.CryptoJS;
  var ITER = 15000;          // PBKDF2 iterations (offline-device friendly)
  var KEYSIZE = 256 / 32;    // 256-bit key in 32-bit words

  function deriveKey(passphrase, saltHex) {
    var salt = C.enc.Hex.parse(saltHex);
    return C.PBKDF2(passphrase, salt, { keySize: KEYSIZE, iterations: ITER, hasher: C.algo.SHA256 });
  }

  var EireneCrypto = {
    available: function () { return !!w.CryptoJS; },

    // Encrypt a string -> envelope object
    encrypt: function (plaintext, passphrase) {
      if (!C) throw new Error('CryptoJS not loaded');
      var saltHex = C.lib.WordArray.random(128 / 8).toString();
      var iv = C.lib.WordArray.random(128 / 8);
      var key = deriveKey(passphrase, saltHex);
      var enc = C.AES.encrypt(plaintext, key, { iv: iv, mode: C.mode.CBC, padding: C.pad.Pkcs7 });
      return {
        v: 1, alg: 'AES-256-CBC', kdf: 'PBKDF2-SHA256', it: ITER,
        salt: saltHex, iv: iv.toString(), ct: enc.toString() // ct is base64
      };
    },

    // Decrypt an envelope object -> string ('' on failure)
    decrypt: function (envelope, passphrase) {
      if (!C) throw new Error('CryptoJS not loaded');
      try {
        var key = deriveKey(passphrase, envelope.salt);
        var dec = C.AES.decrypt(envelope.ct, key, {
          iv: C.enc.Hex.parse(envelope.iv), mode: C.mode.CBC, padding: C.pad.Pkcs7
        });
        return dec.toString(C.enc.Utf8);
      } catch (e) { return ''; }
    },

    // Convenience: encrypt/decrypt a JSON-serialisable object
    encryptObject: function (obj, passphrase) { return this.encrypt(JSON.stringify(obj), passphrase); },
    decryptObject: function (envelope, passphrase) {
      var s = this.decrypt(envelope, passphrase);
      try { return s ? JSON.parse(s) : null; } catch (e) { return null; }
    },

    // SHA-256 integrity digest (hex)
    digest: function (text) { return C ? C.SHA256(text).toString() : ''; }
  };

  w.EireneCrypto = EireneCrypto;
})(window);
