'use client';

import { useSession } from 'next-auth/react';
import { useState, useMemo } from 'react';

const ACTIVE_CLUB_KEY = 'activeClubId';

function getStoredClubId(): string | null {
  if (typeof window === 'undefined') return null;
  return localStorage.getItem(ACTIVE_CLUB_KEY);
}

function determineActiveId(clubs: Record<string, string> | undefined, currentId: string | null): string | null {
  if (!clubs || Object.keys(clubs).length === 0) return null;
  
  const stored = getStoredClubId();
  if (stored && clubs[stored]) return stored;
  
  if (currentId && clubs[currentId]) return currentId;
  
  return Object.keys(clubs)[0];
}

export interface ActiveClubData {
  activeClubId: string | null;
  role: string | null;
  clubs: Record<string, string> | null;
  setActiveClub: (clubId: string) => void;
}

export function useActiveClub(): ActiveClubData {
  const { data: session, status } = useSession();
  
  const [activeClubId, setActiveClubIdState] = useState<string | null>(getStoredClubId);
  
  const computedActiveId = useMemo(() => {
    if (status !== 'authenticated' || !session?.user?.clubs) return activeClubId;
    return determineActiveId(session.user.clubs, activeClubId);
  }, [session, status, activeClubId]);

  const setActiveClub = (clubId: string) => {
    if (session?.user?.clubs && session.user.clubs[clubId]) {
      localStorage.setItem(ACTIVE_CLUB_KEY, clubId);
      setActiveClubIdState(clubId);
    }
  };

  const clubs = session?.user?.clubs || null;
  const role = computedActiveId && clubs ? clubs[computedActiveId] : null;

  return {
    activeClubId: computedActiveId,
    role,
    clubs,
    setActiveClub,
  };
}
