/**
 * @file PolicyContext.tsx
 * Provides reactive environment policy state across the app.
 */
import React, { createContext, useState, useEffect, useContext } from 'react';
import { PolicyManager, PolicySnapshot } from '../lib/policies/PolicyManager';

const defaultPolicy: PolicySnapshot = {
  device: 'desktop',
  performance: 'medium',
  motion: 'full',
  network: 'fast',
  timestamp: new Date().toISOString(),
};

export const PolicyContext = createContext<PolicySnapshot>(defaultPolicy);
export const usePolicy = () => useContext(PolicyContext);

export const PolicyProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [policy, setPolicy] = useState<PolicySnapshot>(defaultPolicy);

  useEffect(() => {
    const detect = () => setPolicy(PolicyManager.detect());
    detect();
    window.addEventListener('resize', detect);
    window.addEventListener('online', detect);
    window.addEventListener('offline', detect);
    return () => {
      window.removeEventListener('resize', detect);
      window.removeEventListener('online', detect);
      window.removeEventListener('offline', detect);
    };
  }, []);

  return <PolicyContext.Provider value={policy}>{children}</PolicyContext.Provider>;
};
