const TK='hd_token',UK='hd_user';
export const setAuth=(t,u)=>{sessionStorage.setItem(TK,t);sessionStorage.setItem(UK,JSON.stringify(u))};
export const getToken=()=>sessionStorage.getItem(TK);
export const getUser=()=>{try{return JSON.parse(sessionStorage.getItem(UK))}catch{return null}};
export const clearAuth=()=>{sessionStorage.removeItem(TK);sessionStorage.removeItem(UK)};
export const isLoggedIn=()=>!!getToken();

export async function api(url,opts={}){
  const h={...opts.headers};const t=getToken();
  if(t)h['Authorization']=`Bearer ${t}`;
  if(!(opts.body instanceof FormData))h['Content-Type']='application/json';
  const r=await fetch(url,{...opts,headers:h});
  if(r.status===401){clearAuth();location.hash='#login';throw new Error('Sesion expirada')}
  return r;
}
export async function GET(u){return(await api(u)).json()}
export async function POST(u,d){return(await api(u,{method:'POST',body:JSON.stringify(d)})).json()}
export async function PUT(u,d){return(await api(u,{method:'PUT',body:JSON.stringify(d)})).json()}

export function fmtDate(iso){if(!iso)return'-';return new Date(iso).toLocaleString('es-CO',{timeZone:'America/Bogota',year:'numeric',month:'short',day:'numeric',hour:'2-digit',minute:'2-digit',hour12:true})}
export function ago(iso){if(!iso)return'-';const m=Math.floor((Date.now()-new Date(iso).getTime())/6e4);if(m<60)return`hace ${m}m`;if(m<1440)return`hace ${Math.floor(m/60)}h`;return`hace ${Math.floor(m/1440)}d`}
