import { createContext, useContext, useState, useEffect, useCallback } from '@wordpress/element';
const LicenseContext = createContext({
  currentTier: 'free',
  isDeveloperMode: false,
  isTierActive: () => false,
  checkLicense: () => {},
  loading: true,
});

export const LicenseProvider = ({ children }) => {
  const [currentTier, setCurrentTier] = useState('free');
  const [isDeveloperMode, setIsDeveloperMode] = useState(false);
  const [licenseStatus, setLicenseStatus] = useState('inactive');
  const [loading, setLoading] = useState(true);

  const checkLicense = useCallback(async () => {
    setCurrentTier('free');
    setLicenseStatus('inactive');
    setIsDeveloperMode(false);
    setLoading(false);
  }, []);

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

  const isTierActive = (requiredTier) => {
    // In developer mode, all tiers are active
    if (isDeveloperMode) {
      return true;
    }

    // Normalize tier names (remove _plus suffix for comparison)
    const normalizeTier = (tier) => {
      const normalized = tier.replace(/_plus$/, '');
      return normalized === 'core' ? 'pro' : normalized;
    };

    const tierOrder = ['free', 'pro', 'business', 'agency'];
    const normalizedCurrent = normalizeTier(currentTier);
    const normalizedRequired = normalizeTier(requiredTier);

    // Premium tiers require an actively valid license state.
    const hasActiveLicense = ['active', 'grace'].includes(licenseStatus);
    if (normalizedRequired !== 'free' && !hasActiveLicense) {
      return false;
    }

    const currentIndex = tierOrder.indexOf(normalizedCurrent);
    const requiredIndex = tierOrder.indexOf(normalizedRequired);

    return currentIndex >= requiredIndex;
  };

  // Helper properties for common tier checks
  const isPro = isTierActive('pro');
  const isBusinessOrHigher = isTierActive('business');
  const isAgency = isTierActive('agency');
  const isLicenseActive = ['active', 'grace'].includes(licenseStatus);

  return (
    <LicenseContext.Provider
      value={{
        currentTier,
        isDeveloperMode,
        isTierActive,
        checkLicense,
        loading,
        isPro,
        isBusinessOrHigher,
        isAgency,
        isLicenseActive,
        licenseStatus,
      }}
    >
      {children}
    </LicenseContext.Provider>
  );
};

export const useLicense = () => {
  const context = useContext(LicenseContext);
  if (!context) {
    throw new Error('useLicense must be used within a LicenseProvider');
  }
  return context;
};
