// lib/awareness/collective/context/PolicyContext.tsx
import React, { createContext, useContext, useEffect, useMemo, useState } from 'react';
import { policyManager } from '@/lib/core/policies';
import type { PolicyContextState, Policy } from '@/lib/core/policies/types';
import { detectDeviceKind } from '@/lib/core/policies/detectors';
import { logPolicyApplied } from '@/lib/telemetry/policy.telemetry';

const Ctx = createContext<PolicyContextState | null>(null);

export const PolicyProvider: React.FC<React.PropsWithChildren> = ({ children }) => {
  const initial = policyManager.getCached() ?? policyManager.compute();
  const [policy, setPolicy] = useState<Policy>(initial);
  const [device, setDevice] = useState(detectDeviceKind());

  useEffect(() => {
    const onResize = () => {
      const nextDevice = detectDeviceKind();
      setDevice(nextDevice);
      const nextPolicy = policyManager.compute(nextDevice);
      setPolicy(nextPolicy);
      logPolicyApplied(nextPolicy);
    };
    window.addEventListener('resize', onResize);
    // أول تسجيل للحالة الحالية
    logPolicyApplied(initial);
    return () => window.removeEventListener('resize', onResize);
  }, []);

  const api = useMemo<PolicyContextState>(() => ({
    policy,
    device,
    setOverrides: (o) => {
      policyManager.setOverrides(o);
      const next = policyManager.compute(device);
      setPolicy(next);
      logPolicyApplied(next);
    },
    clearOverrides: () => {
      policyManager.clearOverrides();
      const next = policyManager.compute(device);
      setPolicy(next);
      logPolicyApplied(next);
    }
  }), [policy, device]);

  return <Ctx.Provider value={api}>{children}</Ctx.Provider>;
};

export function usePolicyContext() {
  const v = useContext(Ctx);
  if (!v) throw new Error('usePolicyContext must be used within PolicyProvider');
  return v;
}
