/**
 * Kill Switch module — React context + hook for kill switch in React Native apps.
 * Fail-open: if the check fails, the app is assumed to be enabled.
 */

import React, { createContext, useContext, useState, useCallback, useEffect } from 'react';
import type { PlatformSDK } from '../core.js';

export interface KillSwitchState {
  disabled: boolean;
  reason?: string;
  isLoading: boolean;
}

interface KillSwitchContextType extends KillSwitchState {
  check: () => Promise<void>;
}

const KillSwitchContext = createContext<KillSwitchContextType | null>(null);

export function useKillSwitch(): KillSwitchContextType {
  const ctx = useContext(KillSwitchContext);
  if (!ctx) throw new Error('useKillSwitch must be used within a KillSwitchProvider');
  return ctx;
}

interface KillSwitchProviderProps {
  sdk: PlatformSDK;
  /** Poll interval in ms (default: 300000 = 5 min) */
  pollInterval?: number;
  children: React.ReactNode;
}

export function KillSwitchProvider({
  sdk,
  pollInterval = 300_000,
  children,
}: KillSwitchProviderProps): React.JSX.Element {
  const [state, setState] = useState<KillSwitchState>({
    disabled: false,
    isLoading: true,
  });

  const check = useCallback(async () => {
    try {
      const res = await sdk.fetch('/settings/kill-switch');
      if (res.ok) {
        const data = (await res.json()) as {
          disabled?: boolean;
          reason?: string;
          message?: string;
        };
        setState({
          disabled: data.disabled ?? false,
          reason: data.reason ?? data.message,
          isLoading: false,
        });
      } else {
        // Fail-open
        setState(s => ({ ...s, disabled: false, isLoading: false }));
      }
    } catch {
      // Fail-open on network error
      setState(s => ({ ...s, disabled: false, isLoading: false }));
    }
  }, [sdk]);

  useEffect(() => {
    check();
    const id = setInterval(check, pollInterval);
    return () => clearInterval(id);
  }, [check, pollInterval]);

  const value: KillSwitchContextType = { ...state, check };
  return React.createElement(KillSwitchContext.Provider, { value }, children);
}
