export type AnalyticsConsentStatus = 'granted' | 'denied' | 'pending';

/** Versioned so policy/copy changes can force a fresh choice later. */
export const CONSENT_STORAGE_KEY = 'hesychia_analytics_consent_v1';
/** Pre-#37 key from beta Tianji baseline (#42); migrated once on read. */
const LEGACY_CONSENT_STORAGE_KEY = 'hesychia_analytics_consent';

export const ANALYTICS_CONSENT_CHANGED_EVENT = 'hesychia-analytics-consent-changed';

/** Prod + beta builds only (CRA NODE_ENV is production for both). */
export const isAnalyticsEnvironment = (): boolean => {
  const deployEnv = process.env.REACT_APP_DEPLOY_ENV;
  if (deployEnv === 'production' || deployEnv === 'beta') return true;
  // Fallback: production builds that omit DEPLOY_ENV still load tracker when a website id is set.
  return (
    process.env.NODE_ENV === 'production' &&
    Boolean(process.env.REACT_APP_TIANJI_WEBSITE_ID)
  );
};

const readStoredConsent = (): AnalyticsConsentStatus | null => {
  try {
    const current = localStorage.getItem(CONSENT_STORAGE_KEY);
    if (current === 'granted' || current === 'denied') return current;

    const legacy = localStorage.getItem(LEGACY_CONSENT_STORAGE_KEY);
    if (legacy === 'granted' || legacy === 'denied') {
      localStorage.setItem(CONSENT_STORAGE_KEY, legacy);
      localStorage.removeItem(LEGACY_CONSENT_STORAGE_KEY);
      return legacy;
    }
  } catch {
    /* localStorage unavailable */
  }

  return null;
};

export const getAnalyticsConsent = (): AnalyticsConsentStatus => {
  if (!isAnalyticsEnvironment()) return 'granted';
  return readStoredConsent() ?? 'pending';
};

export const hasAnalyticsConsent = (): boolean => getAnalyticsConsent() === 'granted';

export const isAnalyticsConsentResolved = (): boolean => getAnalyticsConsent() !== 'pending';

export const setAnalyticsConsent = (status: 'granted' | 'denied'): void => {
  try {
    localStorage.setItem(CONSENT_STORAGE_KEY, status);
    localStorage.removeItem(LEGACY_CONSENT_STORAGE_KEY);
  } catch {
    /* localStorage unavailable */
  }

  window.dispatchEvent(
    new CustomEvent(ANALYTICS_CONSENT_CHANGED_EVENT, { detail: status }),
  );
};
