import { useState, useMemo, useEffect, useCallback } from 'react';
import { useAnalytics } from '@/hooks/useAnalytics';

type CtaVariant = 'gradient' | 'neutral';

const STORAGE_KEY = 'marketing_cta_variant_v1';

function determineVariant(): CtaVariant {
  if (typeof window === 'undefined') {
    return 'gradient';
  }

  const stored = window.localStorage.getItem(STORAGE_KEY);
  if (stored === 'gradient' || stored === 'neutral') {
    return stored;
  }

  const assigned: CtaVariant = Math.random() < 0.5 ? 'gradient' : 'neutral';
  try {
    window.localStorage.setItem(STORAGE_KEY, assigned);
  } catch (error) {
    // localStorage may be unavailable; ignore and fallback to the assigned variant in memory
    console.warn('Unable to persist CTA variant assignment', error);
  }
  return assigned;
}

export function useCtaExperiment(placement: string) {
  const { trackEvent } = useAnalytics();
  const [variant] = useState<CtaVariant>(() => determineVariant());

  const trackingLabel = useMemo(() => `${placement}:${variant}`, [placement, variant]);

  useEffect(() => {
    if (typeof window === 'undefined') {
      return;
    }

    trackEvent({
      category: 'marketing_experiment',
      action: 'cta_impression',
      name: trackingLabel,
    });
  }, [trackEvent, trackingLabel]);

  const trackClick = useCallback(() => {
    trackEvent({
      category: 'marketing_experiment',
      action: 'cta_click',
      name: trackingLabel,
    });
  }, [trackEvent, trackingLabel]);

  return {
    variant,
    trackClick,
  };
}
