'use client';

import { createContext, useContext, useMemo, useState, useCallback } from 'react';
import type { FeatureFlag } from './types';
import { resolveAllFlags, loadRuntimeOverrides, saveRuntimeOverride, clearRuntimeOverrides } from './flag-service';

interface FeatureFlagContextValue {
  flags: Record<string, boolean>;
  isEnabled: (key: string) => boolean;
  setOverride: (key: string, value: boolean) => void;
  clearOverrides: () => void;
}

const FeatureFlagContext = createContext<FeatureFlagContextValue | null>(null);

interface FeatureFlagProviderProps {
  flagDefinitions: FeatureFlag[];
  children: React.ReactNode;
}

export function FeatureFlagProvider({ flagDefinitions, children }: FeatureFlagProviderProps) {
  const [runtimeOverrides, setRuntimeOverrides] = useState<Record<string, boolean>>(() => {
    if (typeof window === 'undefined') return {};
    return loadRuntimeOverrides();
  });

  const envOverrides = useMemo(() => {
    const env: Record<string, string> = {};
    if (typeof window !== 'undefined') {
      // Collect NEXT_PUBLIC_FLAG_* env vars injected at build time
      for (const [key, value] of Object.entries(process.env)) {
        if (key.startsWith('NEXT_PUBLIC_FLAG_') && value) {
          env[key] = value;
        }
      }
    }
    return env;
  }, []);

  const flags = useMemo(
    () => resolveAllFlags(flagDefinitions, envOverrides, runtimeOverrides),
    [flagDefinitions, envOverrides, runtimeOverrides]
  );

  const isEnabled = useCallback((key: string) => flags[key] ?? false, [flags]);

  const setOverride = useCallback(
    (key: string, value: boolean) => {
      saveRuntimeOverride(key, value);
      setRuntimeOverrides((prev) => ({ ...prev, [key]: value }));
    },
    []
  );

  const handleClearOverrides = useCallback(() => {
    clearRuntimeOverrides();
    setRuntimeOverrides({});
  }, []);

  const value = useMemo(
    () => ({ flags, isEnabled, setOverride, clearOverrides: handleClearOverrides }),
    [flags, isEnabled, setOverride, handleClearOverrides]
  );

  return (
    <FeatureFlagContext.Provider value={value}>
      {children}
    </FeatureFlagContext.Provider>
  );
}

export function useFeatureFlags(): FeatureFlagContextValue {
  const ctx = useContext(FeatureFlagContext);
  if (!ctx) throw new Error('useFeatureFlags must be used within FeatureFlagProvider');
  return ctx;
}
