import { useEffect, useRef, useState } from 'react';

import { trackEvent } from '@/lib/analytics';
import { EXPERIMENT_EXPOSURE } from '@/lib/event-catalog';

/**
 * A/B test wrapper around PostHog feature flags.
 *
 * Returns the variant string for the given experiment key, or null when
 * PostHog has not yet resolved feature flags (loading state) or when the
 * user is not enrolled in the experiment.
 *
 * Tracks a single EXPERIMENT_EXPOSURE event per component mount so PostHog
 * can attribute conversions to the correct variant. The exposure fires once
 * when the variant first resolves, and never again on re-renders.
 *
 * PostHog feature flag setup:
 *   1. Create a feature flag in PostHog with a multivariate type.
 *   2. Add variant keys (e.g. 'control', 'variant_a') and set rollout percentages.
 *   3. Pass the flag key as `experimentKey` to this hook.
 *
 * Defined experiments:
 *   - 'hero_headline'              : Landing page hero headline copy (control vs variant_a)
 *   - 'primary_cta_copy'           : Primary CTA button text (control vs variant_a)
 *   - 'signup_form_layout'         : Register page layout (control vs variant_a)
 *   - 'onboarding_demo_placement'  : Demo CTA position in onboarding wizard (control: inside GSC card, variant_a: promoted card above GSC)
 *
 * @example
 *   const variant = useExperiment('hero_headline');
 *   // variant === 'control' | 'variant_a' | null (null = loading or not enrolled)
 *   if (variant === 'variant_a') {
 *     return <h1>Rank higher, faster.</h1>;
 *   }
 *   return <h1>Actionable SEO insights powered by your own data.</h1>;
 */
export function useExperiment(experimentKey: string): string | null {
  const [variant, setVariant] = useState<string | null>(null);
  const exposureTracked = useRef(false);

  useEffect(() => {
    if (typeof window === 'undefined' || !window.posthog) {
      return;
    }

    function resolveVariant(): string | null {
      const flag = window.posthog?.getFeatureFlag(experimentKey);
      if (flag === undefined || flag === null) {
        return null;
      }
      // Boolean true maps to 'control' for simple on/off flags used as experiments.
      // Boolean false means the user is not enrolled — return null.
      if (typeof flag === 'boolean') {
        return flag ? 'control' : null;
      }
      return String(flag);
    }

    function applyVariant(resolved: string): void {
      setVariant(resolved);
      if (!exposureTracked.current) {
        exposureTracked.current = true;
        trackEvent(EXPERIMENT_EXPOSURE, { experiment_key: experimentKey, variant: resolved });
      }
    }

    const immediate = resolveVariant();
    if (immediate !== null) {
      applyVariant(immediate);
      return;
    }

    // Flags not yet loaded — subscribe and resolve once PostHog has evaluated them.
    window.posthog?.onFeatureFlags(() => {
      const deferred = resolveVariant();
      if (deferred !== null) {
        applyVariant(deferred);
      }
    });
  }, [experimentKey]);

  return variant;
}
