import { useEffect, useState } from 'react';
import { useAuth } from '../components/AuthContext';
import {
    fetchCanonicalLifecycleSnapshot,
    type CanonicalLifecycleSnapshot
} from '../lib/canonicalLifecycleApi';

const REFRESH_INTERVAL_MS = 30_000;

export const useCanonicalLifecycle = (profileId?: string) => {
    const { session, user } = useAuth();
    const [snapshot, setSnapshot] = useState<CanonicalLifecycleSnapshot | null>(null);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);

    useEffect(() => {
        if (!user || !session?.access_token) {
            setSnapshot(null);
            setError(null);
            setLoading(false);
            return;
        }

        let cancelled = false;
        const token = session.access_token;

        const load = async () => {
            if (cancelled) return;
            setLoading(true);
            try {
                const next = await fetchCanonicalLifecycleSnapshot({
                    token,
                    profileId
                });
                if (cancelled) return;
                setSnapshot(next);
                setError(null);
            } catch (err: any) {
                if (cancelled) return;
                setSnapshot(null);
                setError(String(err?.message || 'Failed to load canonical lifecycle snapshot'));
            } finally {
                if (!cancelled) setLoading(false);
            }
        };

        void load();
        const timer = window.setInterval(() => {
            void load();
        }, REFRESH_INTERVAL_MS);

        return () => {
            cancelled = true;
            window.clearInterval(timer);
        };
    }, [profileId, session?.access_token, user]);

    return { snapshot, loading, error };
};
