'use client';

import { useEffect, useState } from 'react';
import { createBrowserClient } from '@/shared/db/supabase-client';
import type { User, Session } from './types';

// --- ASA GENERATED START ---
// Auth hooks for client components.
// --- ASA GENERATED END ---

// --- USER CODE START ---

export function useUser() {
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const supabase = createBrowserClient();

    supabase.auth.getUser().then(({ data: { user } }) => {
      setUser(user as User | null);
      setLoading(false);
    });

    const { data: { subscription } } = supabase.auth.onAuthStateChange(
      (_event, session) => {
        setUser(session?.user as User | null ?? null);
        setLoading(false);
      },
    );

    return () => subscription.unsubscribe();
  }, []);

  return { user, loading };
}

export function useSession() {
  const [session, setSession] = useState<Session | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const supabase = createBrowserClient();

    supabase.auth.getSession().then(({ data: { session } }) => {
      setSession(session as Session | null);
      setLoading(false);
    });

    const { data: { subscription } } = supabase.auth.onAuthStateChange(
      (_event, session) => {
        setSession(session as Session | null);
        setLoading(false);
      },
    );

    return () => subscription.unsubscribe();
  }, []);

  return { session, loading };
}

// --- USER CODE END ---
