import { createContext, useContext, useState, useEffect, useCallback } from '@wordpress/element';

const EditorLicenseContext = createContext({
  currentTier: 'free',
  isDeveloperMode: false,
  isTierActive: () => false,
  loading: true,
});

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

  useEffect(() => {
    // Use localized data from WordPress
    if (window.prorankSeoEditor && window.prorankSeoEditor.license) {
      const nextTier = window.prorankSeoEditor.license.tier || 'free';
      setCurrentTier(nextTier === 'core' ? 'pro' : nextTier);
      setIsDeveloperMode(window.prorankSeoEditor.license.is_developer_mode === true);
    } else if (window.prorankSeoAdmin && window.prorankSeoAdmin.license) {
      const nextTier = window.prorankSeoAdmin.license.tier || 'free';
      setCurrentTier(nextTier === 'core' ? 'pro' : nextTier);
      setIsDeveloperMode(window.prorankSeoAdmin.license.is_developer_mode === true);
    } else {
      // Safe production fallback: never unlock paid features when license data is unavailable.
      setCurrentTier('free');
      setIsDeveloperMode(false);
    }
    setLoading(false);
  }, []);

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

    const tierOrder = ['free', 'pro', 'business', 'agency'];
    const currentIndex = tierOrder.indexOf(currentTier);
    const requiredIndex = tierOrder.indexOf(requiredTier);
    return currentIndex >= requiredIndex;
  }, [isDeveloperMode, currentTier]);

  return (
    <EditorLicenseContext.Provider
      value={{ currentTier, isDeveloperMode, isTierActive, loading }}
    >
      {children}
    </EditorLicenseContext.Provider>
  );
};

export const useEditorLicense = () => {
  const context = useContext(EditorLicenseContext);
  if (!context) {
    throw new Error('useEditorLicense must be used within an EditorLicenseProvider');
  }
  return context;
};
