'use client';

import { createContext, useContext, useState, useEffect, useCallback } from 'react';
import { useAuth } from './AuthContext';

interface PlanFeaturesContextType {
  features: string[];
  hasFeature: (key: string) => boolean;
  loading: boolean;
  refresh: () => void;
}

const PlanFeaturesContext = createContext<PlanFeaturesContextType>({
  features: [],
  hasFeature: () => true,
  loading: true,
  refresh: () => {},
});

export function usePlanFeatures() {
  return useContext(PlanFeaturesContext);
}

export function PlanFeaturesProvider({ children }: { children: React.ReactNode }) {
  const { restaurantId, userRecord, loading: authLoading } = useAuth();
  const [features, setFeatures] = useState<string[]>([]);
  const [featuresLoading, setFeaturesLoading] = useState(true);

  const load = useCallback(() => {
    if (authLoading) return;
    const role = userRecord?.role;
    if (!restaurantId || role === 'superadmin' || role === 'support') {
      setFeatures([]);
      setFeaturesLoading(false);
      return;
    }
    setFeaturesLoading(true);
    fetch('/api/billing', { credentials: 'include' })
      .then(r => r.ok ? r.json() : null)
      .then(data => {
        const f = data?.subscription?.features;
        if (Array.isArray(f)) setFeatures(f);
        else setFeatures([]);
      })
      .catch(() => setFeatures([]))
      .finally(() => setFeaturesLoading(false));
  }, [restaurantId, userRecord, authLoading]);

  useEffect(() => {
    load();
  }, [load]);

  const loading = authLoading || featuresLoading;

  const hasFeature = useCallback((key: string) => {
    if (authLoading || featuresLoading) return true;
    const role = userRecord?.role;
    if (role === 'superadmin' || role === 'support') return true;
    return features.includes(key);
  }, [features, authLoading, featuresLoading, userRecord]);

  return (
    <PlanFeaturesContext.Provider value={{ features, hasFeature, loading, refresh: load }}>
      {children}
    </PlanFeaturesContext.Provider>
  );
}
