'use client';

import { useMemo } from 'react';

interface UserInfo {
  id: string;
  role: string;
  roles: string[];
  clubId?: string;
}

function decodeJwtPayload(token: string): Record<string, unknown> | null {
  try {
    const parts = token.split('.');
    if (parts.length !== 3) return null;
    const payload = parts[1];
    if (!payload) return null;
    const decoded = atob(payload.replace(/-/g, '+').replace(/_/g, '/'));
    return JSON.parse(decoded) as Record<string, unknown>;
  } catch {
    return null;
  }
}

export function useUser(): UserInfo | null {
  const token = typeof window !== 'undefined' ? localStorage.getItem('fitcrm_access_token') : null;

  return useMemo(() => {
    if (!token) return null;
    const payload = decodeJwtPayload(token);
    if (!payload || !payload.sub) return null;

    return {
      id: payload.sub as string,
      role: (payload.role as string) || '',
      roles: Array.isArray(payload.roles)
        ? (payload.roles as string[])
        : [(payload.role as string) || ''],
      clubId: payload.clubId as string | undefined,
    };
  }, [token]);
}
