(function(){
  const VERSION = '0.12.2';
  const BUILD = 'app-0122-full';
  const API = '/api';

  function byId(id){ return document.getElementById(id); }
  function token(){ return localStorage.getItem('gobao-auth-token') || localStorage.getItem('gobao_token') || ''; }
  function userId(){ return localStorage.getItem('gobao-user-id') || 'main'; }
  function saveSession(data){
    if(data && data.token){
      localStorage.setItem('gobao-auth-token', data.token);
      localStorage.setItem('gobao_token', data.token);
    }
    if(data && data.user){
      localStorage.setItem('gobao-user-id', data.user.userId || data.user.user_id || data.user.username || 'main');
      localStorage.setItem('gobao-user-name', data.user.displayName || data.user.username || 'GO宝用户');
    }
  }
  function clearSession(){
    ['gobao-auth-token','gobao_token','gobao-user-id','gobao-user-name'].forEach(k => localStorage.removeItem(k));
  }
  async function api(path, options){
    options = options || {};
    const headers = Object.assign({}, options.headers || {});
    if(options.body && !headers['content-type']) headers['content-type'] = 'application/json';
    if(token()) headers.authorization = 'Bearer ' + token();
    const response = await fetch(API + path, Object.assign({cache:'no-store', headers}, options));
    const data = await response.json().catch(() => ({ok:false,error:'服务器返回不是 JSON'}));
    if(!response.ok || data.ok === false) throw new Error(data.error || data.message || ('HTTP ' + response.status));
    return data;
  }
  function setText(id, text, kind){
    const el = byId(id);
    if(!el) return;
    el.textContent = text;
    el.className = 'msg' + (kind ? ' ' + kind : '');
  }
  function nav(active){
    const items = [
      ['home','完整版','/gobao-login.html?v=app-0122-full'],
      ['chat','聊天','/gobao-login.html?v=app-0122-full'],
      ['tasks','任务','/gobao-login.html?v=app-0122-full'],
      ['automation','自动化','/gobao-login.html?v=app-0122-full'],
      ['me','我的','/gobao-login.html?v=app-0122-full']
    ];
    document.write('<nav class="nav">' + items.map(item => '<a class="'+(item[0]===active?'active':'')+'" href="'+item[2]+'">'+item[1]+'</a>').join('') + '</nav>');
  }
  function requireAuth(){
    if(!token()) location.replace('/login.html?v=' + BUILD);
  }
  async function clearOldCaches(){
    try{
      if('serviceWorker' in navigator){
        const regs = await navigator.serviceWorker.getRegistrations();
        await Promise.all(regs.map(r => r.unregister()));
      }
      if('caches' in window){
        const names = await caches.keys();
        await Promise.all(names.filter(n => n.indexOf('gobao') === 0).map(n => caches.delete(n)));
      }
    }catch(e){}
  }
  async function checkLatest(targetId){
    setText(targetId || 'status', '正在检测最新版...');
    try{
      const r = await fetch('/version.json?v=' + Date.now(), {cache:'no-store'});
      const v = await r.json();
      if(v.version && v.version !== VERSION){
        await clearOldCaches();
        setText(targetId || 'status', '发现新版本 ' + v.version + '，正在更新入口...', 'ok');
        const next = v.fullUrl || '/login.html';
        location.href = next + (next.indexOf('?') >= 0 ? '&' : '?') + 't=' + Date.now();
        return v;
      }
      setText(targetId || 'status', '已是最新版 ' + VERSION, 'ok');
      return v;
    }catch(e){
      setText(targetId || 'status', '检测失败：' + e.message, 'error');
      throw e;
    }
  }
  function openAccessibility(){
    try{
      if(window.GoBaoAndroid && window.GoBaoAndroid.openAccessibilitySettings){
        window.GoBaoAndroid.openAccessibilitySettings();
        return true;
      }
    }catch(e){}
    return false;
  }
  window.GOBAO = {VERSION, BUILD, api, token, userId, saveSession, clearSession, setText, nav, requireAuth, checkLatest, openAccessibility, clearOldCaches};
})();
