/* ============================================================
   rawbt.js — Helper untuk print via RawBT
   Mendukung: Intent URI (HTTPS-safe) & HTTP API
   ============================================================ */

const RawBT = {

  isHTTPS()   { return location.protocol === 'https:'; },
  isAndroid() { return /Android/i.test(navigator.userAgent); },
  isIOS()     { return /iPhone|iPad|iPod/i.test(navigator.userAgent); },

  /**
   * Ambil ESC/POS base64 dari server CI3
   * @param {string} url  — URL endpoint get_rawbt_data
   */
  async fetchBase64(url) {
    const res  = await fetch(url);
    if (!res.ok) throw new Error('Server error: ' + res.status);
    const json = await res.json();
    if (json.status !== 'ok') throw new Error(json.message || 'Gagal ambil data');
    return json.base64;
  },

  /**
   * METODE 1 — Intent URI (rawbt: scheme)
   * ✅ Bekerja di HTTPS
   * ✅ Android only
   * ✅ Paling direkomendasikan untuk hosted app
   */
  async printIntent(base64) {
    const uri = 'rawbt:data:application/octet-stream;base64,' + base64;

    return new Promise((resolve, reject) => {
      let opened = false;

      // Jika halaman kehilangan fokus → app RawBT terbuka
      const onBlur = () => {
        opened = true;
        clearTimeout(timer);
        resolve({ method: 'intent', ok: true });
      };

      const timer = setTimeout(() => {
        window.removeEventListener('blur', onBlur);
        if (!opened) {
          reject(new Error(
            'RawBT tidak merespons. Pastikan aplikasi RawBT sudah terinstall di perangkat ini.'
          ));
        }
      }, 3000);

      window.addEventListener('blur', onBlur, { once: true });

      // Trigger deep link
      window.location.href = uri;
    });
  },

  /**
   * METODE 2 — HTTP POST ke RawBT localhost/IP
   * ⚠️ Hanya bekerja di HTTP (tidak HTTPS)
   * ✅ Browser & printer di device yang sama atau 1 jaringan
   */
  async printHTTP(base64, ip = '127.0.0.1', port = 8080) {
    if (this.isHTTPS()) {
      throw new Error(
        'Metode HTTP diblokir browser karena app diakses via HTTPS. ' +
        'Gunakan metode Intent URI.'
      );
    }

    const raw = Uint8Array.from(atob(base64), c => c.charCodeAt(0));
    const res = await fetch(`http://${ip}:${port}`, {
      method:  'POST',
      headers: { 'Content-Type': 'application/octet-stream' },
      body:    raw,
    });

    if (!res.ok) throw new Error(`RawBT error HTTP ${res.status}`);
    return { method: 'http', ok: true };
  },

  /**
   * Auto: pilih metode terbaik sesuai environment
   */
  async printAuto(base64, ip = '127.0.0.1') {
    if (this.isAndroid() || this.isHTTPS()) {
      return await this.printIntent(base64);
    }
    return await this.printHTTP(base64, ip);
  },
};
