const Auth = (function(){
  const TOKEN_KEY = 'atulya_token';
  const REFRESH_KEY = 'atulya_refresh';
  const DEVICE_KEY = 'device_id';
  function getDeviceId(){ let d = localStorage.getItem(DEVICE_KEY); if (!d){ d = 'dev-' + Math.random().toString(36).slice(2,12); localStorage.setItem(DEVICE_KEY, d); } return d; }
  function saveToken(t){ localStorage.setItem(TOKEN_KEY, t); }
  function saveRefresh(r){ localStorage.setItem(REFRESH_KEY, r); }
  function getToken(){ return localStorage.getItem(TOKEN_KEY); }
  function getRefresh(){ return localStorage.getItem(REFRESH_KEY); }
  function clear(){ localStorage.removeItem(TOKEN_KEY); localStorage.removeItem(REFRESH_KEY); }

  async function login(username, password, device_label='Web Client'){
    const payload = { username, password, device_id: getDeviceId(), device_label, platform: navigator.userAgent };
    const res = await fetch((window.API_BASE||'') + '/api/auth.php?action=token_login', { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(payload) });
    if (!res.ok) throw new Error('login failed');
    const j = await res.json();
    if (j.status==1){ saveToken(j.token); saveRefresh(j.refresh_token); localStorage.setItem('role', j.role||'Guest'); localStorage.setItem('user_id', j.user_id||''); }
    return j;
  }

  async function refreshToken(){ const r = getRefresh(); if (!r) return false;
    try {
      const payload = { refresh: r, device_id: getDeviceId() };
      const res = await fetch((window.API_BASE||'') + '/api/auth.php?action=refresh', { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(payload) });
      if (!res.ok) return false;
      const j = await res.json();
      if (j.status==1){ saveToken(j.token); saveRefresh(j.refresh_token); return true; }
      return false;
    } catch(e){ console.warn('refresh failed', e); return false; }
  }

  function authHeaders(){ const t=getToken(); return t? {'Authorization':'Bearer '+t} : {}; }
  async function logout(){ clear(); localStorage.removeItem('role'); localStorage.removeItem('user_id'); window.location.href = '/login.php'; }

  return { login, refreshToken, authHeaders, logout, getDeviceId, getToken };
})();
window.Auth = Auth;
