// Heritage Voice PWA Helper
(function() {

// ── SERVICE WORKER ────────────────────────────────────────────
if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/sw.js', { scope: '/' })
      .then(reg => {
        window._swReg = reg;
        // Check for updates
        reg.addEventListener('updatefound', () => {
          const nw = reg.installing;
          nw.addEventListener('statechange', () => {
            if (nw.state === 'installed' && navigator.serviceWorker.controller) {
              // New version available
              if (confirm('Có phiên bản mới! Tải lại để cập nhật?')) {
                nw.postMessage({ type: 'SKIP_WAITING' });
                window.location.reload();
              }
            }
          });
        });
      })
      .catch(err => console.warn('[PWA] SW register failed:', err));
  });
}

// ── NOTIFICATION ──────────────────────────────────────────────
window.HV = window.HV || {};

HV.requestNotification = async function() {
  if (!('Notification' in window)) return false;
  if (Notification.permission === 'granted') return true;
  if (Notification.permission === 'denied') return false;
  const perm = await Notification.requestPermission();
  return perm === 'granted';
};

HV.notify = function(title, body, url) {
  if (Notification.permission !== 'granted') return;
  if (window._swReg) {
    window._swReg.active?.postMessage({
      type: 'GEOFENCE_ALERT', title, body, url,
    });
  } else {
    new Notification('📍 ' + title, { body, icon: '/assets/icon-192.png' });
  }
};

// ── LOCAL TTS (Web Speech API) ────────────────────────────────
HV.tts = {
  _synth: window.speechSynthesis || null,
  _voice: null,
  _ready: false,

  init() {
    if (!this._synth) return;
    const load = () => {
      const voices = this._synth.getVoices();
      this._voice = voices.find(v => v.lang === 'vi-VN')
                 || voices.find(v => v.lang.startsWith('vi'))
                 || null;
      this._ready = true;
    };
    if (this._synth.getVoices().length) load();
    else this._synth.addEventListener('voiceschanged', load, {once:true});
  },

  speak(text, rate=0.88) {
    if (!this._synth) return;
    if (!this._ready) { setTimeout(()=>this.speak(text,rate), 300); return; }
    this._synth.cancel();
    const utt = new SpeechSynthesisUtterance(text);
    utt.lang   = 'vi-VN';
    utt.rate   = rate;
    utt.pitch  = 1.0;
    utt.volume = 1.0;
    if (this._voice) utt.voice = this._voice;
    this._synth.speak(utt);
  },

  stop() { this._synth?.cancel(); },
};

HV.tts.init();

HV.cacheAudio = function(url) {
  if (window._swReg?.active) {
    window._swReg.active.postMessage({ type: 'CACHE_AUDIO', url });
  }
};

// ── INSTALL PROMPT ────────────────────────────────────────────
let _installPrompt = null;

window.addEventListener('beforeinstallprompt', e => {
  e.preventDefault();
  _installPrompt = e;
  // Hiện nút cài app nếu có element #installBtn
  const btn = document.getElementById('installBtn');
  if (btn) btn.style.display = 'flex';
});

HV.install = async function() {
  if (!_installPrompt) return;
  _installPrompt.prompt();
  const result = await _installPrompt.userChoice;
  if (result.outcome === 'accepted') _installPrompt = null;
};

window.addEventListener('appinstalled', () => {
  _installPrompt = null;
  const btn = document.getElementById('installBtn');
  if (btn) btn.style.display = 'none';
});

// ── TOKEN AUTO REFRESH ────────────────────────────────────────
HV.refreshToken = async function() {
  const refresh = localStorage.getItem('hv_refresh_token');
  if (!refresh) return false;
  try {
    const r = await fetch('https://tads.ctv.hanoi.vn/api/auth/refresh', {
      method: 'POST',
      headers: {'Content-Type':'application/json'},
      body: JSON.stringify({refresh_token: refresh}),
    });
    const j = await r.json();
    if (j.success) {
      localStorage.setItem('hv_token', j.data.access_token);
      return true;
    }
  } catch(e) {}
  return false;
};

// Intercept fetch — tự refresh khi 401
const _origFetch = window.fetch;
window.fetch = async function(...args) {
  let res = await _origFetch(...args);
  if (res.status === 401) {
    const ok = await HV.refreshToken();
    if (ok) {
      // Retry với token mới
      const [url, opts = {}] = args;
      const token = localStorage.getItem('hv_token');
      if (token && opts.headers) {
        opts.headers['Authorization'] = 'Bearer ' + token;
      }
      res = await _origFetch(url, opts);
    }
  }
  return res;
};

// Check token mỗi 5 phút
setInterval(async () => {
  const token = localStorage.getItem('hv_token');
  if (!token) return;
  // Decode token kiểm tra exp
  try {
    const payload = JSON.parse(atob(token.split('.')[0]));
    const timeLeft = payload.exp - Math.floor(Date.now()/1000);
    if (timeLeft < 3600) await HV.refreshToken(); // Refresh khi còn < 1 giờ
  } catch(e) {}
}, 5 * 60 * 1000);

})();
