import React, { createContext, useContext, useEffect, useState, useCallback } from 'react';
import { useAuth } from '@/lib/AuthContext';
import { accountService } from '@/services/accountService';
import { hasPermission as checkPerm, roleHomePath } from '@/config/permissions';

const AccountContext = createContext(null);

export const AccountProvider = ({ children }) => {
  const { user, isAuthenticated, authChecked } = useAuth();
  const [account, setAccount] = useState(null);
  const [loading, setLoading] = useState(true);

  const refresh = useCallback(async () => {
    if (!user) return;
    setLoading(true);
    try {
      const acc = await accountService.resolveForCurrentUser(user, user.full_name || user.email);
      setAccount(acc);
    } catch (e) { console.error('account resolve failed', e); }
    setLoading(false);
  }, [user]);

  useEffect(() => {
    if (isAuthenticated && authChecked && user) refresh();
    else if (!isAuthenticated && authChecked) { setAccount(null); setLoading(false); }
  }, [isAuthenticated, authChecked, user, refresh]);

  const value = {
    account,
    loading,
    refresh,
    hasRole: (...roles) => account && roles.includes(account.role),
    hasPermission: (perm) => checkPerm(account, perm),
    homePath: account ? roleHomePath(account.role) : '/login',
    isOwnerOrAdmin: account && (account.role === 'owner_admin' || account.role === 'admin'),
    isSuspended: account && account.account_status === 'Suspended',
  };
  return <AccountContext.Provider value={value}>{children}</AccountContext.Provider>;
};

export const useAccount = () => {
  const ctx = useContext(AccountContext);
  if (!ctx) throw new Error('useAccount must be used within AccountProvider');
  return ctx;
};