var _CookieOutlinedIcon, _BrandingCssThemeProv;
import * as React from 'react';
import Button from '@mui/material/Button';
import Fade from '@mui/material/Fade';
import Paper from '@mui/material/Paper';
import Box from '@mui/material/Box';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import useLocalStorageState from '@mui/utils/useLocalStorageState';
import { alpha } from '@mui/system';
import Portal from '@mui/material/Portal';
import TrapFocus from '@mui/material/Unstable_TrapFocus';
import CookieOutlinedIcon from '@mui/icons-material/CookieOutlined';
import { BrandingCssThemeProvider } from "../branding/BrandingCssVarsProvider.js";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
const COOKIE_CONSENT_KEY = 'docs-cookie-consent';
function getDoNotTrack() {
  if (typeof window === 'undefined') {
    return false;
  }
  // Check for Do Not Track (DNT)
  return navigator.doNotTrack === '1' || window.doNotTrack === '1';
}

// DNT doesn't change during a session, so we can use a simple external store
const subscribeToNothing = () => () => {};
const getDoNotTrackSnapshot = () => getDoNotTrack();
const getDoNotTrackServerSnapshot = () => true; // Assume DNT until we know the actual value

function useDoNotTrack() {
  return React.useSyncExternalStore(subscribeToNothing, getDoNotTrackSnapshot, getDoNotTrackServerSnapshot);
}
const AnalyticsContext = /*#__PURE__*/React.createContext({
  consentStatus: null,
  hasAnalyticsConsent: false,
  needsConsent: false,
  setAnalyticsConsent: () => {},
  setEssentialOnly: () => {}
});
export function useAnalyticsConsent() {
  return React.useContext(AnalyticsContext);
}
export function CookieConsentDialog() {
  const {
    needsConsent,
    setAnalyticsConsent,
    setEssentialOnly
  } = useAnalyticsConsent();
  const [show, setShow] = React.useState(false);
  React.useEffect(() => {
    if (needsConsent) {
      // Double rAF to ensure the initial opacity: 0 state is painted before transitioning
      const frame = requestAnimationFrame(() => {
        requestAnimationFrame(() => {
          setShow(true);
        });
      });
      return () => cancelAnimationFrame(frame);
    }
    setShow(false);
    return undefined;
  }, [needsConsent]);
  return /*#__PURE__*/_jsx(Portal, {
    children: /*#__PURE__*/_jsx(TrapFocus, {
      open: needsConsent,
      disableAutoFocus: true,
      disableEnforceFocus: true,
      children: /*#__PURE__*/_jsx(Fade, {
        in: show,
        unmountOnExit: true,
        children: /*#__PURE__*/_jsx(Paper, {
          role: "dialog",
          "aria-modal": "false",
          "aria-labelledby": "cookie-consent-dialog-title",
          "aria-describedby": "cookie-consent-dialog-description",
          variant: "outlined",
          tabIndex: -1,
          sx: theme => ({
            position: 'fixed',
            bottom: 0,
            right: 0,
            p: 2,
            m: 2,
            maxWidth: 340,
            pointerEvents: 'auto',
            boxShadow: theme.shadows[2],
            zIndex: theme.zIndex.snackbar,
            ...(theme.applyDarkStyles ? theme.applyDarkStyles({
              bgcolor: 'primaryDark.900'
            }) : {
              [theme.getColorSchemeSelector?.('dark') || '&.mode-dark']: {
                bgcolor: 'primaryDark.900'
              }
            })
          }),
          children: /*#__PURE__*/_jsxs(Stack, {
            direction: "column",
            spacing: 3,
            sx: {
              justifyContent: 'flex-start'
            },
            children: [/*#__PURE__*/_jsxs(Stack, {
              spacing: 1,
              sx: {
                flexShrink: 1,
                alignSelf: {
                  xs: 'flex-start',
                  sm: 'center'
                }
              },
              children: [/*#__PURE__*/_jsx(Box, {
                sx: theme => ({
                  borderRadius: '50%',
                  bgcolor: alpha(theme.palette.primary.main, 0.1),
                  p: 1,
                  display: 'inline-block',
                  width: 40,
                  height: 40,
                  mb: -1,
                  alignSelf: {
                    xs: 'center',
                    sm: 'flex-start'
                  }
                }),
                children: _CookieOutlinedIcon || (_CookieOutlinedIcon = /*#__PURE__*/_jsx(CookieOutlinedIcon, {
                  color: "primary",
                  strokeWidth: 1.5
                }))
              }), /*#__PURE__*/_jsxs(Stack, {
                spacing: 0.5,
                children: [/*#__PURE__*/_jsx(Typography, {
                  variant: "subtitle2",
                  id: "cookie-consent-dialog-title",
                  sx: {
                    textAlign: {
                      xs: 'center',
                      sm: 'start'
                    }
                  },
                  children: "Cookie Preferences"
                }), /*#__PURE__*/_jsx(Typography, {
                  id: "cookie-consent-dialog-description",
                  variant: "body2",
                  sx: {
                    textAlign: {
                      xs: 'center',
                      sm: 'start'
                    }
                  },
                  children: "We use cookies to understand site usage and improve our content. This includes third-party analytics."
                })]
              })]
            }), /*#__PURE__*/_jsxs(Stack, {
              direction: "row",
              spacing: 1,
              sx: {
                justifyContent: 'flex-start'
              },
              children: [/*#__PURE__*/_jsx(Button, {
                onClick: setAnalyticsConsent,
                variant: "contained",
                size: "small",
                children: "Allow analytics"
              }), /*#__PURE__*/_jsx(Button, {
                onClick: setEssentialOnly,
                size: "small",
                children: "Essential only"
              })]
            })]
          })
        })
      })
    })
  });
}
function updateGoogleConsent(hasAnalytics) {
  if (typeof window !== 'undefined' && typeof window.gtag === 'function') {
    window.gtag('consent', 'update', {
      ad_storage: 'denied',
      ad_user_data: 'denied',
      ad_personalization: 'denied',
      analytics_storage: hasAnalytics ? 'granted' : 'denied'
    });

    // Initialize Apollo when analytics consent is granted
    const win = window;
    if (hasAnalytics && typeof win.initApollo === 'function') {
      win.initApollo();
    }
  }
}
export function AnalyticsProvider({
  children
}) {
  const [consentStatus, setConsentStatus] = useLocalStorageState(COOKIE_CONSENT_KEY, null);
  const doNotTrack = useDoNotTrack();

  // Respect Do Not Track - don't show dialog and treat as essential only
  const needsConsent = consentStatus === null && !doNotTrack;

  // Update Google consent when status changes or on mount if already set
  React.useEffect(() => {
    if (doNotTrack) {
      // DNT is enabled - always deny analytics
      updateGoogleConsent(false);
    } else if (consentStatus !== null) {
      updateGoogleConsent(consentStatus === 'analytics');
    }
  }, [consentStatus, doNotTrack]);
  const setAnalyticsConsent = React.useCallback(() => {
    setConsentStatus('analytics');
  }, [setConsentStatus]);
  const setEssentialOnly = React.useCallback(() => {
    setConsentStatus('essential');
  }, [setConsentStatus]);
  const contextValue = React.useMemo(() => ({
    consentStatus: doNotTrack ? 'essential' : consentStatus,
    hasAnalyticsConsent: !doNotTrack && consentStatus === 'analytics',
    needsConsent,
    setAnalyticsConsent,
    setEssentialOnly
  }), [consentStatus, doNotTrack, needsConsent, setAnalyticsConsent, setEssentialOnly]);
  return /*#__PURE__*/_jsxs(AnalyticsContext.Provider, {
    value: contextValue,
    children: [children, _BrandingCssThemeProv || (_BrandingCssThemeProv = /*#__PURE__*/_jsx(BrandingCssThemeProvider, {
      children: /*#__PURE__*/_jsx(CookieConsentDialog, {})
    }))]
  });
}