'use client';

import { useSyncExternalStore, type ReactNode } from 'react';
import { readConsent, subscribeConsent } from '@/lib/analytics/consent';

// Renders the tracking scripts only when allowed: always when the cookie
// banner is off (`required` false), otherwise once the shopper accepted.
// Nothing renders on the server or the first client render (no cookie
// access there), so hydration always matches.
export default function ConsentGate({ required, children }: { required: boolean; children: ReactNode }) {
  const consent = useSyncExternalStore(subscribeConsent, readConsent, () => null);
  const hydrated = useSyncExternalStore(noopSubscribe, () => true, () => false);

  if (!hydrated) return null;
  if (required && consent !== 'granted') return null;
  return children;
}

const noopSubscribe = () => () => {};
