import { create } from 'zustand';

export interface AuthState {
  token: string | null;
  username: string | null;
  role: 'admin' | 'user' | null;
  login: (token: string) => void;
  logout: () => void;
}

function decodeJwtPayload(token: string): { sub?: string; username?: string; role?: string } {
  try {
    const base64 = token.split('.')[1];
    const json = atob(base64);
    return JSON.parse(json);
  } catch {
    return {};
  }
}

export const useAuthStore = create<AuthState>()((set) => ({
  token: localStorage.getItem('token'),
  username: (() => {
    const t = localStorage.getItem('token');
    if (!t) return null;
    const p = decodeJwtPayload(t);
    return p.username ?? p.sub ?? null;
  })(),
  role: (() => {
    const t = localStorage.getItem('token');
    if (!t) return null;
    const r = decodeJwtPayload(t).role;
    return r === 'admin' ? 'admin' : r === 'user' ? 'user' : null;
  })(),

  login: (token: string) => {
    const payload = decodeJwtPayload(token);
    localStorage.setItem('token', token);
    set({
      token,
      username: payload.username ?? payload.sub ?? null,
      role: payload.role === 'admin' ? 'admin' : 'user',
    });
  },

  logout: () => {
    localStorage.removeItem('token');
    set({ token: null, username: null, role: null });
  },
}));
