'use client';

import React, { createContext, useContext, useEffect, useState } from 'react';
import { behavioralTracker } from '../tracker';

interface TrackingContextType {
  hasConsent: boolean;
  grantConsent: () => void;
  revokeConsent: () => void;
  isLoading: boolean;
}

const TrackingContext = createContext<TrackingContextType | undefined>(undefined);

export const TrackingProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [hasConsent, setHasConsent] = useState(false);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    // Check consent on mount
    setHasConsent(behavioralTracker.hasConsent());
    setIsLoading(false);
  }, []);

  const grantConsent = () => {
    behavioralTracker.grantConsent();
    setHasConsent(true);
  };

  const revokeConsent = () => {
    behavioralTracker.revokeConsent();
    setHasConsent(false);
  };

  return (
    <TrackingContext.Provider value={{ hasConsent, grantConsent, revokeConsent, isLoading }}>
      {children}
    </TrackingContext.Provider>
  );
};

export const useTracking = () => {
  const context = useContext(TrackingContext);
  if (context === undefined) {
    throw new Error('useTracking must be used within a TrackingProvider');
  }
  return context;
};
