import { createContext, useContext, useState, useCallback, useEffect } from 'react';
import { base44 } from '@/api/base44Client';

/**
 * Experience mode = Guided (default, plain-language, one action per screen)
 * or Advanced (full professional controls). Both share the same underlying
 * project data — switching never loses work. Persisted on the user record.
 */
const ExperienceModeContext = createContext({ mode: 'guided', setMode: async () => {}, loading: false });

export function useExperienceMode() {
  return useContext(ExperienceModeContext);
}

export default function ExperienceModeProvider({ user, children }) {
  const [mode, setModeState] = useState(user?.experienceMode === 'advanced' ? 'advanced' : 'guided');
  const [loading, setLoading] = useState(false);

  // Keep in sync if the user record refreshes (e.g. after onboarding).
  useEffect(() => {
    setModeState(user?.experienceMode === 'advanced' ? 'advanced' : 'guided');
  }, [user?.experienceMode]);

  const setMode = useCallback(async (m) => {
    setModeState(m);
    try {
      await base44.auth.updateMe({ experienceMode: m });
    } catch {
      // Persist failure is non-fatal — local mode still applies for this session.
    }
  }, []);

  return (
    <ExperienceModeContext.Provider value={{ mode, setMode, loading }}>
      {children}
    </ExperienceModeContext.Provider>
  );
}