import { useEffect } from "react";

import { OPT_IN_ALL_EVENT, getUserDecision } from "@devowl-wp/cookie-consent-web-client";

import type { BannerContext } from "../../contexts/banner.js";

/**
 * Listen to consents of `@devowl-wp/cookie-consent-web-client` as they can be set without
 * UI through our React components (e.g. Georestriction or custom predecision gateway). We need to update
 * those changes to the consent within our React state so "Change privacy settings" works as expected.
 */
function useBannerConsentListener(contextValue: BannerContext["contextValue"], decisionCookieName: string) {
    useEffect(() => {
        const listener = () => {
            const consent = getUserDecision(decisionCookieName);
            consent && contextValue.set({ consent: consent.consent, isConsentGiven: true });
        };

        document.addEventListener(OPT_IN_ALL_EVENT, listener);
        return () => {
            document.removeEventListener(OPT_IN_ALL_EVENT, listener);
        };
    }, []);
}

export { useBannerConsentListener };
