'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';

export function useAccountSession() {
  const [session, setSession] = useState(null);
  const router = useRouter();

  useEffect(() => {
    let alive = true;
    fetch('/api/auth/session', { cache: 'no-store' })
      .then((res) => res.json())
      .then((data) => { if (alive) setSession(data?.user || null); })
      .catch(() => { if (alive) setSession(null); });
    return () => { alive = false; };
  }, []);

  async function signOut() {
    await fetch('/api/auth/session', { method: 'DELETE' }).catch(() => null);
    router.replace('/login');
    router.refresh();
  }

  return { session, signOut };
}
