import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';
import { 
  BusinessState, 
  Task, 
  Message, 
  Agent, 
  OperationType, 
  FirestoreErrorInfo,
  Vendor,
  PurchaseOrder,
  Collection,
  Asset,
  Prospect,
  OutreachLog,
  WholesaleClient,
  WholesaleOrder,
  BusinessDocument,
  Campaign,
  PlannerEvent,
  AgentRole,
  ProposedAction,
  SmartNote,
  CorporateAccount,
  DevelopmentPortal,
  IncomingOrderQuote,
  OutboundStudioEvent
} from '../types';
import { generateFrenchPackagingPack } from '../lib/quebecCompliance';
import { getDefaultHitlMode, hasOpenReplenishment, shouldQueueToolCall } from '../lib/hitl';
import {
  checkSkuBomServer,
  evaluateOrderPreviewServer,
  fetchStorefrontOperations,
  syncWorkshopSnapshotToServer,
} from '../services/storefrontClient';
import { 
  INITIAL_AGENTS, 
  EMPTY_STATE, 
  INITIAL_STATE 
} from '../constants';
import {
  DEMO_BUSINESS_STATE,
  DEMO_TASKS
} from '../utils/demoData';
import { MASTER_DELIVERABLES } from '../data/masterDeliverables';
import { isAuthorizedEmail, PRIMARY_OWNER_EMAIL } from '../lib/authGate';
import { 
  auth, 
  db, 
  onAuthStateChanged, 
  User, 
  signInWithPopup, 
  signOut, 
  googleProvider,
  GoogleAuthProvider,
  signInWithEmailAndPassword,
  createUserWithEmailAndPassword
} from '../firebase';
import { sendEmailVerification } from 'firebase/auth';
import { convertUnit } from '../lib/units';
import { 
  collection, 
  doc, 
  setDoc, 
  getDoc, 
  onSnapshot, 
  query, 
  where, 
  deleteDoc,
  getDocFromServer,
  getDocs
} from 'firebase/firestore';
import { generateId } from '../lib/utils';
import { getAgentResponse } from '../services/agentService';
import { toast } from "sonner";

interface ArtisanContextType {
  authMode: 'live' | 'demo';
  user: User | null;
  isAuthLoading: boolean;
  isProfileLoading: boolean;
  businessState: BusinessState;
  tasks: Task[];
  enterDemoWorkspace: () => void;
  messages: Message[];
  agents: Agent[];
  activeTab: string;
  setActiveTab: (tab: any) => void;
  setBusinessState: React.Dispatch<React.SetStateAction<BusinessState>>;
  setTasks: React.Dispatch<React.SetStateAction<Task[]>>;
  setMessages: React.Dispatch<React.SetStateAction<Message[]>>;
  setAgents: React.Dispatch<React.SetStateAction<Agent[]>>;
  addLog: (agent: AgentRole, action: string) => void;
  writeToFirestore: (col: string, id: string, data: any) => Promise<void>;
  deleteFromFirestore: (col: string, id: string) => Promise<void>;
  resetApplication: () => Promise<void>;
  saveProfile: () => Promise<void>;
  updateProfile: (profile: any) => void;
  // Migrated Business Logic
  handleSendMessage: (input: string, isHandoff?: boolean) => Promise<any>;
  handleApproveAction: (action: ProposedAction) => Promise<void>;
  handleApproveAllActions: () => Promise<void>;
  handleRejectAction: (action: ProposedAction) => Promise<void>;
  hitlMode: boolean;
  setHitlMode: (v: boolean) => void;
  refreshOperationsQueue: () => Promise<void>;
  addSupply: (inventoryId: string, supply: any) => void;
  removeSupply: (inventoryId: string, supplyId: string) => void;
  addInventoryItem: (newItem: any) => void;
  updateInventoryItem: (id: string, updates: any) => void;
  removeInventoryItem: (id: string) => void;
  deleteInventoryItem: (id: string) => void;
  addTransaction: (transaction: any) => void;
  addTask: (newTask: any) => void;
  addCollection: (newProject: any) => void;
  addAsset: (assetData: any) => void;
  addWholesaleClient: (clientData: any) => void;
  addWholesaleOrder: (orderData: any) => void;
  addCampaign: (campaignData: any) => void;
  updateCampaign: (campaignId: string, updates: Partial<Campaign>) => void;
  updateCampaignBudget: (campaignId: string, newBudget: number) => void;
  updateCampaignStatus: (campaignId: string, status: Campaign['status']) => void;
  updateProspectStatus: (prospectId: string, status: Prospect['status']) => void;
  addProspect: (prospectData: any) => void;
  logOutreach: (prospectId: string, log: any) => void;
  updateIntegration: (name: string, connected: boolean) => void;
  addVendor: (vendor: Vendor) => void;
  addPurchaseOrder: (po: PurchaseOrder) => void;
  updatePOStatus: (poId: string, status: PurchaseOrder['status']) => void;
  deleteProspect: (prospectId: string) => Promise<void>;
  deleteCampaign: (campaignId: string) => Promise<void>;
  deleteWholesaleOrder: (orderId: string) => Promise<void>;
  updateCollection: (id: string, updates: Partial<Collection>) => void;
  deleteCollection: (collectionId: string) => Promise<void>;
  addProductToCollection: (collectionId: string, productData: any) => void;
  updateProductInCollection: (collectionId: string, productId: string, updates: Partial<{ name: string; price: number; stock: number; kanbanStage?: string; sku?: string }>) => void;
  deleteProductFromCollection: (collectionId: string, productId: string) => void;
  bulkUpdateCollectionPrices: (collectionId: string, percentage: number, roundingMode?: 'exact' | 'cents99' | 'cents50' | 'whole') => void;
  toggleComplianceTask: (taskId: string) => Promise<void>;
  updatePlannerChecklist: (updates: { launchTimeline?: BusinessState['planner']['launchTimeline']; marketPrep?: BusinessState['planner']['marketPrep'] }) => void;
  addEvent: (eventData: any) => void;
  addDocument: (docData: any) => void;
  updateCollectionProductKanbanStage: (collectionId: string, productId: string, stage: 'prep' | 'pouring' | 'curing' | 'packaging' | 'completed') => void;
  attachCampaignToCollection: (campaignId: string, collectionId: string) => void;
  toggleTask: (taskId: string) => void;
  deleteTask: (taskId: string) => void;
  updateTaskStatus: (taskId: string, status: 'pending' | 'in-progress' | 'completed') => void;
  executeTaskWithAgent: (taskId: string) => Promise<void>;
  orchestrateAndClearBacklog: () => Promise<void>;
  addFormulation: (data: any) => void;
  updateFormulation: (formulationId: string, data: any) => void;
  deleteFormulation: (formulationId: string) => void;
  deleteAsset: (assetId: string) => void;
  migrateRecipe: (assetId: string, ingredients: any[]) => void;
  calculateFormulationCOGS: (formulationId: string) => number;
  startBatch: (formulationId: string, batchName: string, expectedYield: number, options?: { batchCode?: string; ingredientLots?: Record<string, string> }) => void;
  updateBatchStatus: (batchId: string, status: any, actualYield?: number) => void;
  updateBatchQC: (batchId: string, qc: any) => void;
  // SMART Notebook CRUD & Orchestration
  addSmartNote: (noteData: Partial<SmartNote>) => void;
  updateSmartNote: (id: string, updates: Partial<SmartNote>) => void;
  deleteSmartNote: (id: string) => void;
  convertNoteToDirectives: (noteId: string, assignedRole?: AgentRole) => void;
  getDynamicChartData: () => any[];
  handleLogout: () => Promise<void>;
  handleLogin: () => Promise<void>;
  handleEmailLogin: (email: string, pass: string) => Promise<void>;
  handleEmailSignUp: (email: string, pass: string) => Promise<void>;
  seedWorkshop: () => Promise<void>;
  isProcessing: boolean;
  setIsProcessing: React.Dispatch<React.SetStateAction<boolean>>;
  uiState: {
    isMenuCollapsed: boolean;
    setIsMenuCollapsed: (v: boolean) => void;
    showEventModal: boolean;
    setShowEventModal: (v: boolean) => void;
    showProspectModal: boolean;
    setShowProspectModal: (v: boolean) => void;
    showCampaignModal: boolean;
    setShowCampaignModal: (v: boolean) => void;
    showWholesaleOrderModal: boolean;
    setShowWholesaleOrderModal: (v: boolean) => void;
  };
  selectedAgentId: string | null;
  setSelectedAgentId: React.Dispatch<React.SetStateAction<string | null>>;
  googleAccessToken: string | null;
  setGoogleAccessToken: React.Dispatch<React.SetStateAction<string | null>>;
  connectGoogleWorkspace: () => Promise<string | null>;
  offlineMode: boolean;
  setOfflineMode: (v: boolean) => Promise<void>;
}

const ArtisanContext = createContext<ArtisanContextType | undefined>(undefined);

export const ArtisanProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [authMode, setAuthMode] = useState<'live' | 'demo'>('live');
  const [user, setUser] = useState<User | null>(null);
  const [isAuthLoading, setIsAuthLoading] = useState(true);
  const [isProfileLoading, setIsProfileLoading] = useState(true);
  const [businessState, setBusinessState] = useState<BusinessState>(INITIAL_STATE);
  const [tasks, setTasks] = useState<Task[]>([]);
  const [messages, setMessages] = useState<Message[]>([]);
  const [agents, setAgents] = useState<Agent[]>(INITIAL_AGENTS);
  const [activeTab, setActiveTab] = useState('workshop');
  const [isProcessing, setIsProcessing] = useState(false);
  const [selectedAgentId, setSelectedAgentId] = useState<string | null>(null);
  const [googleAccessToken, setGoogleAccessToken] = useState<string | null>(null);
  const [offlineMode, setOfflineModeState] = useState<boolean>(() => {
    return localStorage.getItem('artisanos_offline_enabled') === 'true';
  });
  const [hitlMode, setHitlModeState] = useState<boolean>(() => {
    try {
      return getDefaultHitlMode(localStorage.getItem('ljwellness_hitl_mode'));
    } catch {
      return true;
    }
  });

  const setHitlMode = useCallback((enabled: boolean) => {
    setHitlModeState(enabled);
    try {
      localStorage.setItem('ljwellness_hitl_mode', enabled ? 'true' : 'false');
    } catch (e) {}
    toast.info(
      enabled
        ? 'HITL Approval Gate ON: Specialist AI tool calls will queue in Command Center before running.'
        : 'HITL Auto-Run ON: Non-destructive tools execute immediately; deletions and POs still require approval.'
    );
  }, []);

  // Load local storage demo fallback context
  const loadDemoState = useCallback(() => {
    try {
      const savedState = localStorage.getItem('artisanos_demo_state');
      const savedTasks = localStorage.getItem('artisanos_demo_tasks');
      const savedMessages = localStorage.getItem('artisanos_demo_messages');
      return {
        state: savedState ? JSON.parse(savedState) as BusinessState : DEMO_BUSINESS_STATE,
        tasks: savedTasks ? JSON.parse(savedTasks) as Task[] : DEMO_TASKS,
        messages: savedMessages ? JSON.parse(savedMessages) as Message[] : [
          {
            id: 'init_msg_1',
            sender: 'StudioLead' as const,
            content: 'Welcome to your LJWellness Studio workspace! I am your Studio Lead. How can I help you manage your B2B Architect Box gifting, formulations, or production schedule today?',
            timestamp: new Date().toLocaleTimeString(),
            type: 'text' as const
          }
        ]
      };
    } catch (e) {
      return { 
        state: DEMO_BUSINESS_STATE, 
        tasks: DEMO_TASKS, 
        messages: [
          {
            id: 'init_msg_1',
            sender: 'StudioLead' as const,
            content: 'Welcome to your LJWellness Studio workspace! I am your Studio Lead. How can I help you manage your B2B Architect Box gifting, formulations, or production schedule today?',
            timestamp: new Date().toLocaleTimeString(),
            type: 'text' as const
          }
        ]
      };
    }
  }, []);

  const saveDemoStateLocally = useCallback((state: BusinessState, tasksList: Task[], messagesList: Message[]) => {
    try {
      localStorage.setItem('artisanos_demo_state', JSON.stringify(state));
      localStorage.setItem('artisanos_demo_tasks', JSON.stringify(tasksList));
      localStorage.setItem('artisanos_demo_messages', JSON.stringify(messagesList));
    } catch (e) {
      console.warn("Storage write failed:", e);
    }
  }, []);

  // Synchronize changes in Demo Mode to local storage
  useEffect(() => {
    if (authMode === 'demo') {
      saveDemoStateLocally(businessState, tasks, messages);
    }
  }, [businessState, tasks, messages, authMode, saveDemoStateLocally]);

  // Synchronize changes in Offline Safeguard Mode to local cache
  useEffect(() => {
    if (user && offlineMode) {
      try {
        localStorage.setItem(`artisanos_offline_state_${user.uid}`, JSON.stringify(businessState));
        localStorage.setItem(`artisanos_offline_tasks_${user.uid}`, JSON.stringify(tasks));
        localStorage.setItem(`artisanos_offline_messages_${user.uid}`, JSON.stringify(messages));
      } catch (e) {
        console.warn("Storage write failed for offline cache:", e);
      }
    }
  }, [businessState, tasks, messages, user, offlineMode]);

  const setOfflineMode = useCallback(async (active: boolean) => {
    setOfflineModeState(active);
    localStorage.setItem('artisanos_offline_enabled', active ? 'true' : 'false');
    
    if (active) {
      if (user) {
        try {
          localStorage.setItem(`artisanos_offline_state_${user.uid}`, JSON.stringify(businessState));
          localStorage.setItem(`artisanos_offline_tasks_${user.uid}`, JSON.stringify(tasks));
          localStorage.setItem(`artisanos_offline_messages_${user.uid}`, JSON.stringify(messages));
        } catch (e) {
          console.warn("Storage write failed for offline cache transition:", e);
        }
      }
      toast.success("Offline Safeguard Enabled! All data writes redirected to safe local storage during network interruptions.");
    } else {
      toast.info("Offline Safeguard Disabled. Restoring cloud connection sync...");
      if (user) {
        try {
          toast.loading("Pushed local offline database to cloud...", { id: 'offline-reconnect' });
          
          // Sync profile
          await setDoc(doc(db, 'profiles', user.uid), { ...businessState.profile, uid: user.uid });
          
          // Sync inventory items
          if (businessState.inventory && businessState.inventory.length > 0) {
            for (const item of businessState.inventory) {
              await setDoc(doc(db, 'inventory', item.id), { ...item, uid: user.uid });
            }
          }
          
          // Sync tasks
          if (tasks && tasks.length > 0) {
            for (const t of tasks) {
              await setDoc(doc(db, 'tasks', t.id), { ...t, uid: user.uid });
            }
          }
          
          // Sync messages
          if (messages && messages.length > 0) {
            for (const m of messages) {
              await setDoc(doc(db, 'messages', m.id), { ...m, uid: user.uid, createdAt: m.createdAt || new Date().toISOString() });
            }
          }

          toast.success("Cloud DB Synchronized! Local offline records successfully uploaded.", { id: 'offline-reconnect' });
        } catch (err) {
          console.warn("Cloud synchronize push deferred:", err);
          toast.warning("Reconnected to live network feed. Data is safe locally.", { id: 'offline-reconnect' });
        }
      }
    }
  }, [user, businessState, tasks, messages]);

  const [isMenuCollapsed, setIsMenuCollapsed] = useState(false);
  const [showEventModal, setShowEventModal] = useState(false);
  const [showProspectModal, setShowProspectModal] = useState(false);
  const [showCampaignModal, setShowCampaignModal] = useState(false);
  const [showWholesaleOrderModal, setShowWholesaleOrderModal] = useState(false);

  const uiState = {
    isMenuCollapsed,
    setIsMenuCollapsed,
    showEventModal,
    setShowEventModal,
    showProspectModal,
    setShowProspectModal,
    showCampaignModal,
    setShowCampaignModal,
    showWholesaleOrderModal,
    setShowWholesaleOrderModal,
  };

  const addLog = useCallback((agent: AgentRole, action: string) => {
    setBusinessState(prev => ({
      ...prev,
      systemLogs: [{ id: generateId(), agent, action, timestamp: new Date().toLocaleTimeString() }, ...prev.systemLogs.slice(0, 49)]
    }));
  }, []);

  const writeToFirestore = async (colName: string, id: string, data: any) => {
    if (authMode === 'demo' || offlineMode || user?.uid === "local-artisan-sandbox-id") {
      console.log(`[Offline Sandbox Cache Event] Write to local memory: ${colName}/${id}`);
      return;
    }
    if (!user) return;
    try {
      const sanitize = (obj: any): any => {
        if (Array.isArray(obj)) return obj.map(sanitize);
        if (obj !== null && typeof obj === 'object' && !(obj instanceof Date)) {
          return Object.fromEntries(
            Object.entries(obj)
              .filter(([_, v]) => v !== undefined)
              .map(([k, v]) => [k, sanitize(v)])
          );
        }
        return obj;
      };
      const sanitizedData = sanitize(data);
      await setDoc(doc(db, colName, id), { ...sanitizedData, uid: user.uid });
    } catch (error: any) {
      console.error(`Error writing to ${colName}:`, error);
      if (error.code === 'permission-denied' || error.message?.includes('permissions')) {
        toast.error(`Sync Blocked: Insufficient permissions for ${colName}.`);
      }
    }
  };

  const deleteFromFirestore = async (colName: string, id: string) => {
    if (authMode === 'demo' || offlineMode) {
      console.log(`[Offline Sandbox Cache Event] Deleted from local memory: ${colName}/${id}`);
      return;
    }
    if (!user) return;
    try {
      await deleteDoc(doc(db, colName, id));
    } catch (error) {
      console.error(`Error deleting from ${colName}:`, error);
      toast.error(`Permission denied: Could not remove ${colName} entry.`);
    }
  };

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, async (u) => {
      if (u) {
        if (!isAuthorizedEmail(u.email)) {
          console.warn("Unauthorized email attempted sign in:", u.email);
          await signOut(auth);
          setUser(null);
          setIsAuthLoading(false);
          toast.error('Access Restricted: Only authorized LJWellness Studio emails can access this workspace.');
          return;
        }

        setUser(u);
        setIsAuthLoading(false);
        setAuthMode('live');
        let baseState = { ...INITIAL_STATE };
        try {
          const cachedProfile = localStorage.getItem(`artisanos_user_profile_${u.uid}`);
          if (cachedProfile) {
            baseState.profile = JSON.parse(cachedProfile);
          }
        } catch (e) {
          console.warn("Failed to load profile from localStorage:", e);
        }
        if (isAuthorizedEmail(u.email)) {
          baseState.profile = {
            ...baseState.profile,
            isOnboarded: true,
            subscription: {
              plan: 'Diamond',
              status: 'active',
              expiryDate: 'Lifetime'
            }
          };
        }
        setBusinessState(baseState);
        setTasks([]);
        setMessages([]);
      } else {
        setUser(null);
        setIsAuthLoading(false);
        setGoogleAccessToken(null);
        setAuthMode('live');
        setBusinessState(INITIAL_STATE);
        setTasks([]);
        setMessages([]);
        setIsProfileLoading(false);
      }
    });
    return () => unsubscribe();
  }, []);

  useEffect(() => {
    if (!user || authMode === 'demo' || user.uid === "local-artisan-sandbox-id" || user.email === "guest@artisanos.com") {
      setIsProfileLoading(false);
      return;
    }

    if (offlineMode) {
      try {
        const uId = user.uid;
        const cachedStateStr = localStorage.getItem(`artisanos_offline_state_${uId}`);
        const cachedTasksStr = localStorage.getItem(`artisanos_offline_tasks_${uId}`);
        const cachedMessagesStr = localStorage.getItem(`artisanos_offline_messages_${uId}`);
        
        if (cachedStateStr) setBusinessState(JSON.parse(cachedStateStr));
        if (cachedTasksStr) setTasks(JSON.parse(cachedTasksStr));
        if (cachedMessagesStr) setMessages(JSON.parse(cachedMessagesStr));
      } catch (e) {
        console.warn("Offline cache load failed:", e);
      }
      setIsProfileLoading(false);
      return;
    }

    const collectionsToSync = [
      'inventory', 'transactions', 'collections', 'assets', 'tasks', 
      'proposed_actions', 'wholesale_clients', 'wholesale_orders', 
      'prospects', 'campaigns', 'vendors', 'purchase_orders',
      'formulations', 'production_batches', 'documents', 'compliance',
      'smart_notes', 'messages', 'events', 'corporate_accounts', 'portals',
      'incoming_orders', 'outbound_events'
    ];

    const unsubscribes = collectionsToSync.map(colName => {
      const q = query(collection(db, colName), where('uid', '==', user.uid));
      return onSnapshot(q, (snapshot) => {
        const data = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
        
        if (colName === 'messages') {
          const sorted = (data as any[]).sort((a, b) => {
            const timeA = a.createdAt ? new Date(a.createdAt).getTime() : 0;
            const timeB = b.createdAt ? new Date(b.createdAt).getTime() : 0;
            return timeA - timeB;
          });
          setMessages(sorted);
          return;
        }

        setBusinessState(prev => {
          const newState = { ...prev };
          switch (colName) {
            case 'inventory': newState.inventory = data as any; break;
            case 'transactions': newState.finances = { ...prev.finances, transactions: data as any }; break;
            case 'collections': newState.collections = data as any; break;
            case 'assets': newState.assets = data as any; break;
            case 'tasks': setTasks(data as any); break;
            case 'proposed_actions': newState.proposedActions = data as any; break;
            case 'wholesale_clients': newState.wholesale = { ...prev.wholesale, clients: data as any }; break;
            case 'wholesale_orders': newState.wholesale = { ...prev.wholesale, orders: data as any }; break;
            case 'prospects': newState.crm = { ...prev.crm, prospects: data as any }; break;
            case 'campaigns': newState.marketing = { ...prev.marketing, campaigns: data as any }; break;
            case 'vendors': newState.sourcing = { ...prev.sourcing, vendors: data as any }; break;
            case 'purchase_orders': newState.sourcing = { ...prev.sourcing, purchaseOrders: data as any }; break;
            case 'formulations': newState.formulations = data as any; break;
            case 'production_batches': newState.productionBatches = data as any; break;
            case 'documents': newState.documents = data as any; break;
            case 'smart_notes': newState.smartNotes = data as any; break;
            case 'events': newState.planner = { ...prev.planner, events: data as any }; break;
            case 'corporate_accounts': newState.corporateAccounts = data as any; break;
            case 'portals': newState.developmentPortals = data as any; break;
            case 'incoming_orders': newState.incomingOrders = (data as IncomingOrderQuote[]).sort((a, b) => (b.receivedAt || '').localeCompare(a.receivedAt || '')); break;
            case 'outbound_events': newState.outboundQueue = (data as OutboundStudioEvent[]).sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || '')); break;
            case 'compliance': 
              if (data.length > 0) newState.compliance = data[0] as any; 
              break;
          }
          return newState;
        });
      }, (error) => {
        console.warn(`Firestore sync skipped for "${colName}" (running in offline mode):`, error);
      });
    });

    const sanitizeProfileData = (raw: any) => {
      const base = INITIAL_STATE.profile;
      if (!raw || typeof raw !== 'object') return base;
      return {
        ...base,
        ...raw,
        artisan: {
          ...base.artisan,
          ...(raw.artisan || {})
        },
        mentor: {
          ...base.mentor,
          ...(raw.mentor || {})
        },
        socials: {
          ...base.socials,
          ...(raw.socials || {})
        },
        contact: {
          ...base.contact,
          ...(raw.contact || {})
        },
        subscription: {
          ...base.subscription,
          ...(raw.subscription || {})
        },
        integrations: {
          ...base.integrations,
          ...(raw.integrations || {}),
          stripe: { ...base.integrations.stripe, ...(raw.integrations?.stripe || {}) },
          paypal: { ...base.integrations.paypal, ...(raw.integrations?.paypal || {}) },
          notion: { ...base.integrations.notion, ...(raw.integrations?.notion || {}) },
          instagram: { ...base.integrations.instagram, ...(raw.integrations?.instagram || {}) },
          tiktok: { ...base.integrations.tiktok, ...(raw.integrations?.tiktok || {}) },
          shopify: { ...base.integrations.shopify, ...(raw.integrations?.shopify || {}) }
        }
      };
    };

    const loadProfile = async () => {
      if (user.uid === 'local-artisan-sandbox-id' || user.email === 'guest@artisanos.com') {
        setIsProfileLoading(false);
        return;
      }
      setIsProfileLoading(true);
      try {
        const profileDoc = await getDoc(doc(db, 'profiles', user.uid));
        if (profileDoc.exists()) {
          const rawProfile = profileDoc.data();
          let profileData = sanitizeProfileData(rawProfile);
          if (profileData.isOnboarded === undefined) {
            profileData.isOnboarded = true;
          }
          if (isAuthorizedEmail(user.email)) {
            profileData = {
              ...profileData,
              isOnboarded: true,
              subscription: {
                plan: 'Diamond',
                status: 'active',
                expiryDate: 'Lifetime'
              }
            };
          }
          setBusinessState(prev => ({
            ...prev,
            profile: profileData,
            planner: {
              ...prev.planner,
              launchTimeline: Array.isArray(rawProfile?.plannerLaunchTimeline) ? rawProfile.plannerLaunchTimeline : prev.planner.launchTimeline,
              marketPrep: Array.isArray(rawProfile?.plannerMarketPrep) ? rawProfile.plannerMarketPrep : prev.planner.marketPrep,
            }
          }));
          try {
            localStorage.setItem(`artisanos_user_profile_${user.uid}`, JSON.stringify(profileData));
          } catch (e) {
            console.warn("Failed to cache profile to localStorage:", e);
          }
        } else if (isAuthorizedEmail(user.email)) {
          const newProfile = sanitizeProfileData({
            ...INITIAL_STATE.profile,
            contact: {
              ...INITIAL_STATE.profile.contact,
              email: user.email || PRIMARY_OWNER_EMAIL
            },
            subscription: {
              plan: 'Diamond' as const,
              status: 'active' as const,
              expiryDate: 'Lifetime'
            },
            isOnboarded: true
          });
          setBusinessState(prev => ({ ...prev, profile: newProfile }));
          try {
            localStorage.setItem(`artisanos_user_profile_${user.uid}`, JSON.stringify(newProfile));
          } catch (e) {}
          await writeToFirestore('profiles', user.uid, newProfile);
        } else {
          const cachedProfStr = localStorage.getItem(`artisanos_user_profile_${user.uid}`);
          if (cachedProfStr) {
            const parsed = sanitizeProfileData(JSON.parse(cachedProfStr));
            setBusinessState(prev => ({ ...prev, profile: parsed }));
            await writeToFirestore('profiles', user.uid, parsed);
          }
        }
      } catch (error) {
        console.warn("Profile fetch from cache/server had an issue, falling back to local cache:", error);
        const cachedProfStr = localStorage.getItem(`artisanos_user_profile_${user.uid}`);
        if (cachedProfStr) {
          try {
            setBusinessState(prev => ({ ...prev, profile: sanitizeProfileData(JSON.parse(cachedProfStr)) }));
          } catch (e) {}
        }
      } finally {
        setIsProfileLoading(false);
      }
    };
    loadProfile();

    return () => unsubscribes.forEach(unsub => unsub());
  }, [user]);

  // Effects migrated from App.tsx - Proactive background thoughts disabled post rate limit feedback

  useEffect(() => {
    if (isProfileLoading) return;
    const lowStockItems = businessState.inventory.filter(item => item.stock <= item.minLevel);

    lowStockItems.forEach(item => {
      const alreadyTracked = hasOpenReplenishment(
        item,
        businessState.proposedActions,
        businessState.sourcing.purchaseOrders
      );

      if (!alreadyTracked) {
        const vendor = businessState.sourcing.vendors.find(v => v.category === 'Raw Materials') || businessState.sourcing.vendors[0];

        const action: ProposedAction = {
          id: generateId(),
          agent: 'Business',
          tool: 'addPurchaseOrder',
          args: {
            vendorId: vendor?.id || 'v1',
            itemName: item.item,
            inventoryId: item.id,
            quantity: 10,
            pricePerUnit: item.costPerUnit
          },
          status: 'pending',
          timestamp: new Date().toISOString()
        };

        setBusinessState(prev => {
          if (hasOpenReplenishment(item, prev.proposedActions, prev.sourcing.purchaseOrders)) {
            return prev;
          }
          return {
            ...prev,
            proposedActions: [action, ...prev.proposedActions]
          };
        });

        if (user && authMode === 'live') {
          writeToFirestore('proposed_actions', action.id, action);
        }

        addLog('Business', `[Trigger] Low stock detected for ${item.item}. Queued HITL replenishment proposal.`);
      }
    });
  }, [
    isProfileLoading,
    businessState.inventory,
    businessState.proposedActions,
    businessState.sourcing.purchaseOrders,
    businessState.sourcing.vendors,
    user,
    authMode,
    writeToFirestore,
    addLog
  ]);

  // Financial recalculation
  useEffect(() => {
    const transactions = businessState.finances.transactions;
    const revenue = transactions.filter(t => t.type === 'in').reduce((sum, t) => sum + t.amount, 0);
    const expenses = transactions.filter(t => t.type === 'out').reduce((sum, t) => sum + t.amount, 0);
    const balance = revenue - expenses;

    setBusinessState(prev => {
      if (prev.finances.balance === balance && prev.finances.revenue === revenue && prev.finances.expenses === expenses) return prev;
      return {
        ...prev,
        finances: {
          ...prev.finances,
          balance,
          revenue,
          expenses
        }
      };
    });
  }, [businessState.finances.transactions]);

  const refreshOperationsQueue = useCallback(async () => {
    if (!user || authMode !== 'live' || !isAuthorizedEmail(user.email)) return;
    try {
      const ops = await fetchStorefrontOperations();
      setBusinessState(prev => {
        const mergedIncoming = new Map<string, IncomingOrderQuote>();
        (prev.incomingOrders || []).forEach(o => mergedIncoming.set(o.id, o));
        (ops.incomingOrders || []).forEach(o => mergedIncoming.set(o.id, o));
        const mergedOutbound = new Map<string, OutboundStudioEvent>();
        (prev.outboundQueue || []).forEach(o => mergedOutbound.set(o.id, o));
        (ops.outboundQueue || []).forEach(o => mergedOutbound.set(o.id, o));
        return {
          ...prev,
          incomingOrders: Array.from(mergedIncoming.values()).sort((a, b) => (b.receivedAt || '').localeCompare(a.receivedAt || '')),
          outboundQueue: Array.from(mergedOutbound.values()).sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || '')),
        };
      });
    } catch {
      // Non-blocking if operations endpoint offline
    }
  }, [user, authMode]);

  useEffect(() => {
    if (!user || authMode !== 'live' || !isAuthorizedEmail(user.email)) return;
    const timer = setTimeout(() => {
      syncWorkshopSnapshotToServer({
        profile: businessState.profile,
        inventory: businessState.inventory,
        formulations: businessState.formulations,
        collections: businessState.collections,
        productionBatches: businessState.productionBatches,
        sourcing: businessState.sourcing,
        finances: businessState.finances,
      }).catch(() => {});
    }, 800);
    return () => clearTimeout(timer);
  }, [
    user,
    authMode,
    businessState.inventory,
    businessState.formulations,
    businessState.collections,
    businessState.productionBatches,
    businessState.sourcing,
  ]);

  useEffect(() => {
    if (user && authMode === 'live' && isAuthorizedEmail(user.email)) {
      refreshOperationsQueue();
      const onFocus = () => {
        void refreshOperationsQueue();
      };
      window.addEventListener('focus', onFocus);
      const intervalId = window.setInterval(() => {
        void refreshOperationsQueue();
      }, 30000);
      return () => {
        window.removeEventListener('focus', onFocus);
        window.clearInterval(intervalId);
      };
    }
  }, [user, authMode, refreshOperationsQueue]);

  const handleSendMessage = async (input: string, isHandoff = false) => {
    if (!input.trim() || (isProcessing && !isHandoff)) return null;
    const userMessage: Message = { id: generateId(), sender: isHandoff ? 'System' : 'User', content: input, timestamp: new Date().toLocaleTimeString(), type: 'text' };
    setMessages(prev => [...prev, userMessage]);
    if (user && authMode === 'live') {
      writeToFirestore('messages', userMessage.id, { ...userMessage, createdAt: new Date().toISOString() });
    }
    setIsProcessing(true);
    
    // Resolve @mentions across aliases (@Calyx, @Vesper), role keys (@Formulator), and full agent names
    const mentionAliasMap: Record<string, AgentRole> = {
      calyx: 'Formulator',
      formulator: 'Formulator',
      vesper: 'WealthAdvisor',
      wealthadvisor: 'WealthAdvisor',
      studiolead: 'StudioLead',
      director: 'StudioLead',
      business: 'Business',
      commercial: 'Business',
      marketing: 'Marketing',
      nicheexpert: 'NicheExpert',
      curator: 'NicheExpert',
      mentor: 'Mentor',
    };
    const lowerInput = input.toLowerCase();
    let targetAgent = agents[0];
    const fullNameMention = agents.find(a => lowerInput.includes(`@${a.name.toLowerCase()}`));
    if (fullNameMention) {
      targetAgent = fullNameMention;
    } else {
      const mentionMatch = input.match(/@([a-zA-Z0-9_]+)/);
      if (mentionMatch) {
        const token = mentionMatch[1].toLowerCase();
        const mappedRole = mentionAliasMap[token];
        const mentioned =
          (mappedRole && agents.find(a => a.role === mappedRole)) ||
          agents.find(a => a.role.toLowerCase() === token || a.name.toLowerCase().startsWith(token));
        if (mentioned) targetAgent = mentioned;
      } else if (selectedAgentId) {
        const selected = agents.find(a => a.id === selectedAgentId);
        if (selected) targetAgent = selected;
      }
    }

    const executedTools: string[] = [];
    const queuedTools: string[] = [];

    try {
      setAgents(prev => prev.map(a => a.id === targetAgent.id ? { ...a, status: 'thinking' } : a));
      void refreshOperationsQueue();
      const response = await getAgentResponse(targetAgent.role, input, messages.slice(-10), { ...businessState, tasks });

      if (response?.isFallback) {
        addLog(targetAgent.role, '[System Fallback Active] Cloud AI models unreachable or saturated; deterministic fallback response returned.');
        toast.warning('Cloud AI unreachable — fallback mode active.', { duration: 4000 });
      }
      
      if (response.text) {
        setAgents(prev => prev.map(a => a.id === targetAgent.id ? { ...a, status: 'idle', isSpeaking: true } : a));
        const aiMessage: Message = { id: generateId(), sender: targetAgent.role, content: response.text, timestamp: new Date().toLocaleTimeString(), type: 'text' };
        setMessages(prev => [...prev, aiMessage]);
        if (user && authMode === 'live') {
          writeToFirestore('messages', aiMessage.id, { ...aiMessage, createdAt: new Date().toISOString() });
        }
        
        setTimeout(() => {
          setAgents(prev => prev.map(a => a.id === targetAgent.id ? { ...a, isSpeaking: false } : a));
        }, 5000);
      }

      if (response.functionCalls && response.functionCalls.length > 0) {
        for (const fc of response.functionCalls) {
          const requiresApproval = shouldQueueToolCall(fc.name, hitlMode);

          const action: ProposedAction = {
            id: generateId(),
            agent: targetAgent.role,
            tool: fc.name,
            args: fc.args,
            status: requiresApproval ? 'pending' : 'approved',
            timestamp: new Date().toISOString()
          };

          if (requiresApproval) {
            queuedTools.push(fc.name);
            setBusinessState(prev => ({
              ...prev,
              proposedActions: [action, ...prev.proposedActions]
            }));
            if (user) writeToFirestore('proposed_actions', action.id, action);
            addLog(targetAgent.role, `HITL Gate: Queued "${fc.name.replace(/_/g, ' ')}" for owner approval in Command Center.`);
          } else {
            const didExecute = executeAgentAction(action);
            if (didExecute) {
              executedTools.push(fc.name);
              setBusinessState(prev => ({
                ...prev,
                proposedActions: [action, ...prev.proposedActions]
              }));
              if (user) writeToFirestore('proposed_actions', action.id, action);
              addLog(targetAgent.role, `Executed tool: "${fc.name.replace(/_/g, ' ')}".`);
            } else {
              const fallbackQueued: ProposedAction = { ...action, status: 'pending' };
              queuedTools.push(fc.name);
              setBusinessState(prev => ({
                ...prev,
                proposedActions: [fallbackQueued, ...prev.proposedActions]
              }));
              if (user) writeToFirestore('proposed_actions', fallbackQueued.id, fallbackQueued);
              addLog(targetAgent.role, `Tool "${fc.name.replace(/_/g, ' ')}" moved to HITL Queue for review.`);
            }
          }
        }

        if (queuedTools.length > 0) {
          toast.info(`${targetAgent.name} queued ${queuedTools.length} action(s) in Command Center for approval.`);
        }
        if (executedTools.length > 0) {
          toast.success(`${targetAgent.name} executed ${executedTools.length} workshop action(s).`);
        }
      }

      return { executedTools, queuedTools, isFallback: Boolean(response?.isFallback) };
    } catch (e) {
      console.error("Chat error:", e);
      toast.error("Agent synchronization interrupted.");
      return { executedTools, queuedTools, isFallback: true };
    } finally {
      setIsProcessing(false);
      setAgents(prev => prev.map(a => ({ ...a, status: 'idle' })));
    }
  };

  const executeAgentAction = (action: ProposedAction): boolean => {
    const { tool, args, agent } = action;
    try {
      switch (tool) {
        case 'complete_task': {
          const { taskId, completionNotes, actualOutcome } = args;
          let targetTask = tasks.find(t => t.id === taskId || t.title.toLowerCase().includes((taskId || '').toLowerCase()));
          if (!targetTask && tasks.length > 0) {
            targetTask = tasks.find(t => t.assignedTo === agent && t.status !== 'completed') || tasks.find(t => t.status !== 'completed');
          }
          if (targetTask) {
            const outcomeDetails = actualOutcome || completionNotes || 'Directive successfully executed by specialist agent and logged into studio registry.';
            const updatedTask: Task = {
              ...targetTask,
              status: 'completed',
              description: completionNotes ? `${targetTask.description}\n\n[Fulfillment Note]: ${completionNotes}` : targetTask.description
            };
            setTasks(prev => prev.map(t => t.id === targetTask!.id ? updatedTask : t));
            if (user) writeToFirestore('tasks', targetTask.id, updatedTask);
            
            // Automatically persist concrete Document artifact into Documents Library so work is tangible
            const existingDoc = businessState.documents.find(d => d.title.toLowerCase().includes(targetTask!.title.toLowerCase()));
            if (!existingDoc) {
              const docType = /market|campaign|social|promo|launch/i.test(targetTask.title) ? 'marketing' :
                              /recipe|formula|soap|serum|butter/i.test(targetTask.title) ? 'recipe' :
                              /finance|cost|margin|price|cogs/i.test(targetTask.title) ? 'finance' :
                              /safety|compliance|fda|ifra|legal/i.test(targetTask.title) ? 'legal' : 'strategy';
              
              const newDoc = {
                title: `${targetTask.title} (Execution Record)`,
                content: `### 📋 Specialist Directive Fulfillment: ${targetTask.title}\n\n**Specialist:** ${agent}  \n**Status:** Production Ready / Fulfilled  \n**Date:** ${new Date().toLocaleDateString()}  \n\n#### Directive Scope\n${targetTask.description}\n\n#### Tangible Deliverables & Findings\n${outcomeDetails}`,
                type: docType,
                author: agent
              };
              addAsset(newDoc);
            }

            // If task is marketing campaign, ensure campaign is also saved in marketing hub
            if (/campaign|promo|launch|marketing/i.test(targetTask.title)) {
              const existingCamp = businessState.marketing.campaigns.find(c => c.name.toLowerCase().includes(targetTask!.title.toLowerCase()));
              if (!existingCamp) {
                addCampaign({
                  name: targetTask.title.replace(/directive|task|create|draft/gi, '').trim() || targetTask.title,
                  budget: 500,
                  spent: 0,
                  roi: 3.2,
                  status: 'active',
                  channel: 'Instagram & VIP Email',
                  content: outcomeDetails,
                  author: agent
                });
              }
            }

            // If task is calendar/event, ensure event is saved in planner
            if (/event|meeting|audit|launch date|schedule/i.test(targetTask.title)) {
              addEvent({
                title: targetTask.title,
                date: new Date().toISOString().split('T')[0],
                type: 'production',
                assignedTo: agent,
                description: outcomeDetails
              });
            }

            addLog(agent, `Fulfilled directive: "${targetTask.title}". Tangible artifact saved to workshop.`);
            toast.success(`Directive completed: ${targetTask.title}`, { icon: "✅" });
          } else {
            addLog(agent, `Directive execution logged: ${completionNotes || actualOutcome || 'Action completed.'}`);
          }
          break;
        }
        case 'batch_complete_tasks': {
          const { taskIds, assignedTo, summaryNotes } = args;
          setTasks(prev => {
            return prev.map(t => {
              const isMatch = (taskIds && taskIds.includes(t.id)) ||
                              (assignedTo === 'all') ||
                              (assignedTo && t.assignedTo === assignedTo) ||
                              (!taskIds && !assignedTo && t.assignedTo === agent);
              if (isMatch && t.status !== 'completed') {
                const updated: Task = { ...t, status: 'completed' };
                if (user) writeToFirestore('tasks', t.id, updated);
                return updated;
              }
              return t;
            });
          });
          addLog(agent, `Batch directives fulfilled: ${summaryNotes || 'All pending directives executed and resolved.'}`);
          toast.success(`Directives completed by ${agent}`, { icon: "✨" });
          break;
        }
        case 'update_task_status': {
          const { taskId, status, notes } = args;
          let targetTask = tasks.find(t => t.id === taskId || t.title.toLowerCase().includes((taskId || '').toLowerCase()));
          if (targetTask) {
            const updatedTask: Task = {
              ...targetTask,
              status: status || 'completed',
              description: notes ? `${targetTask.description}\n\n[Status Update]: ${notes}` : targetTask.description
            };
            setTasks(prev => prev.map(t => t.id === targetTask!.id ? updatedTask : t));
            if (user) writeToFirestore('tasks', targetTask.id, updatedTask);
            addLog(agent, `Updated task "${targetTask.title}" status to ${status}.`);
          }
          break;
        }
        case 'create_task':
          addTask(args);
          break;
        case 'update_inventory':
          const item = businessState.inventory.find(i => i.item.toLowerCase() === args.item.toLowerCase());
          const amount = args.amount;
          if (item) {
            const newStock = args.action === 'add' ? item.stock + amount : item.stock - amount;
            const updatedItem = { ...item, stock: Math.max(0, newStock) };
            setBusinessState(prev => ({
              ...prev,
              inventory: prev.inventory.map(i => i.id === item.id ? updatedItem : i)
            }));
            if (user) writeToFirestore('inventory', item.id, updatedItem);
          } else if (args.action === 'add') {
            addInventoryItem({ item: args.item, stock: amount, unit: 'units', minLevel: 0, costPerUnit: 0 });
          }
          break;
        case 'create_asset':
          addAsset({ ...args, author: agent });
          break;
        case 'analyze_market_trends': {
          const niche = args.niche || 'Luxury Artisan Skincare';
          const focus = args.focus || 'Packaging, Presentation & Margin Architecture';
          const reportContent = args.content || args.analysisContent || `### 🏛️ Ultra-Luxury Market Intelligence: ${niche}
**Author:** Luxury Market Specialist  
**Strategic Focus:** ${focus}  
**Date:** ${new Date().toLocaleDateString()} (Anchored in 2026 Trends)

---

### 1. Market Opportunity & Executive Landscape
The market demand for ${niche} has rapidly matured toward hyper-authentic provenance, tactile unboxing rituals, and somatic sensory wellness. Mass-market commercial brands lack the small-batch integrity and bespoke formulation customization that discerning B2B and private clients now demand.

### 2. Packaging, Presentation & Perceived Value Standards
- **Vessel Architecture:** Heavyweight amber/violet UV glass and solid Paulownia or cedarwood keepsake boxes with brass hardware.
- **Tactile Labeling:** 300gsm letterpress cotton stock, gold foil debossing, and botanical wax-sealed authenticity credentials.
- **Somatic Impact:** Curated natural botanical aromas (high-altitude French lavender, extra virgin olive oil polyphenols, organic wild resins).

### 3. Pricing Architecture & Margin Delivery
- **Wholesale Margin Target:** Minimum 65-70% gross profit margin.
- **Direct-to-Consumer Margin:** 80-85% gross profit margin.
- **B2B Executive / Builder Tiers:** $145 - $350 opening gift suites delivering 3.5x perceived value.

---
*Report filed directly into Studio Strategy & Market Intelligence library.*`;

          addAsset({
            title: `Market Intelligence: ${niche}`,
            content: reportContent,
            type: 'strategy',
            author: agent
          });
          break;
        }
        case 'update_finance':
          // Map description to desc if needed
          addTransaction({ 
            amount: args.amount, 
            type: args.type, 
            desc: args.description || args.desc || 'Agent adjustment' 
          });
          break;
        case 'create_project':
          addCollection(args);
          break;
        case 'create_wholesale_client':
          addWholesaleClient(args);
          break;
        case 'create_wholesale_order':
          addWholesaleOrder(args);
          break;
        case 'create_prospect':
          const newLead: Prospect = {
            id: generateId(),
            status: 'cold',
            lastContact: new Date().toISOString().split('T')[0],
            logs: [],
            createdAt: new Date().toISOString().split('T')[0],
            ...args
          };
          setBusinessState(prev => ({ 
            ...prev, 
            crm: { ...prev.crm, prospects: [newLead, ...prev.crm.prospects] } 
          }));
          if (user) writeToFirestore('prospects', newLead.id, newLead);
          break;
        case 'add_event':
          addEvent(args);
          break;
        case 'delegate_to_agent':
          const nextAgent = agents.find(a => a.role === args.targetRole);
          if (nextAgent) {
            setSelectedAgentId(nextAgent.id);
            const stayInCurrentRoom = [
              'orchestration',
              'master-orchestration',
              'meeting',
              'studio-chat',
              'command-center',
              'agent-workspace'
            ].includes(activeTab);
            if (!stayInCurrentRoom) {
              setActiveTab('agent-workspace');
            }
            addLog('StudioLead', `Delegation initiated: Handing context to ${nextAgent.name}.`);
            setTimeout(() => {
              handleSendMessage(`@${nextAgent.name} provide your specialist analysis regarding: ${args.reason}`, true);
            }, 250);
          }
          break;
        case 'log_outreach':
          const prospect = businessState.crm.prospects.find(p => p.id === args.prospectId);
          if (prospect) {
            const log: OutreachLog = { id: generateId(), date: new Date().toISOString().split('T')[0], ...args };
            const updatedProspect = { ...prospect, logs: [log, ...prospect.logs], lastContact: log.date };
            setBusinessState(prev => ({
              ...prev,
              crm: { ...prev.crm, prospects: prev.crm.prospects.map(p => p.id === args.prospectId ? updatedProspect : p) }
            }));
            if (user) writeToFirestore('prospects', args.prospectId, updatedProspect);
          }
          break;
        case 'update_prospect_status':
          const pToUpdate = businessState.crm.prospects.find(p => p.id === args.prospectId);
          if (pToUpdate) {
            const updatedP = { ...pToUpdate, status: args.status };
            setBusinessState(prev => ({
              ...prev,
              crm: { ...prev.crm, prospects: prev.crm.prospects.map(p => p.id === args.prospectId ? updatedP : p) }
            }));
            if (user) writeToFirestore('prospects', args.prospectId, updatedP);
            addLog('Business', `Lead "${pToUpdate.name}" status updated to ${args.status}.`);
          }
          break;
        case 'create_campaign': {
          addCampaign(args);
          const launchDate = new Date(Date.now() + 7 * 86400000).toISOString().split('T')[0];
          addEvent({
            title: `Campaign Launch: ${args.name}`,
            date: launchDate,
            type: 'marketing',
            category: 'General',
            description: `Public launch drop and VIP promotion for "${args.name}".`
          });
          addLog('Marketing', `[Studio Planner] Scheduled campaign launch for "${args.name}" on ${launchDate}.`);
          break;
        }
        case 'create_formulation': {
          addFormulation(args);
          addLog('Formulator', `[Formulation] Registered precision formula: "${args.name}".`);
          const cureDays = Number(args.curingTimeDays) || (args.category === 'Wax Melts' ? 14 : 35);
          if (cureDays > 0) {
            const cureDate = new Date(Date.now() + cureDays * 86400000).toISOString().split('T')[0];
            addEvent({
              title: `${args.name} - Batch Cure Complete`,
              date: cureDate,
              type: 'production',
              category: args.category || 'Soap',
              description: `Batch curing window (${cureDays} days) complete. Inspect pH, unmold/trim verification, packaging into inventory.`
            });
            addLog('Formulator', `[Studio Planner] Scheduled batch cure completion for "${args.name}" on ${cureDate}.`);
          }
          break;
        }
        case 'calculate_saponification':
          addAsset({
            title: `Saponification Spec: ${args.soapName}`,
            content: `**Soap Name:** ${args.soapName}\n**Lye Type:** ${args.lyeType} | **Superfat:** ${args.superfatPercent}%\n**Water:Lye Ratio:** ${args.waterLyeRatio}:1\n\n### Oil Matrix\n${(args.oils || []).map((o: any) => `- ${o.name}: ${o.grams}g`).join('\n')}\n\n*Calculated by Master Formulator.*`,
            type: 'recipe',
            author: 'Formulator'
          });
          addLog('Formulator', `[Saponification] Calculated exact lye & oil fatty acid profile for "${args.soapName}".`);
          break;
        case 'audit_formulation_safety':
          addAsset({
            title: `Safety & IFRA Audit: ${args.productName}`,
            content: `**Product:** ${args.productName}\n**Category:** ${args.productType}\n**Preservative System:** ${args.preservativeSystem}\n**Fragrance / EO Load:** ${args.fragrancePercent}%\n**Estimated Shelf Stability:** ${args.shelfLifeEstimateMonths} Months\n\n*Audited by Master Formulator.*`,
            type: 'legal',
            author: 'Formulator'
          });
          addLog('Formulator', `[Safety Audit] Completed IFRA & preservative assessment for "${args.productName}".`);
          break;
        case 'scale_formulation':
          const targetForm = businessState.formulations.find(f => f.name.toLowerCase() === (args.formulationName || '').toLowerCase() || f.id === args.formulationName);
          if (targetForm && args.currentBatchSize > 0) {
            const scaleMultiplier = args.targetBatchSize / args.currentBatchSize;
            const scaledIngredients = targetForm.ingredients.map(ing => ({
              ...ing,
              amount: Math.round(ing.amount * scaleMultiplier * 10) / 10
            }));
            updateFormulation(targetForm.id, {
              ...targetForm,
              batchSize: args.targetBatchSize,
              batchUnit: args.unit || targetForm.batchUnit,
              ingredients: scaledIngredients
            });
            addLog('Formulator', `[Batch Scaling] Scaled formula "${targetForm.name}" from ${args.currentBatchSize} to ${args.targetBatchSize}${args.unit}.`);
          }
          break;
        case 'create_batch':
          // Attempt to find formulation by name if ID isn't found
          let formulationId = args.recipeId || args.formulationId;
          if (formulationId) {
            const foundForm = businessState.formulations.find(f => 
              f.id === formulationId || f.name.toLowerCase() === formulationId.toLowerCase()
            );
            if (foundForm) formulationId = foundForm.id;
          }
          
          startBatch(
            formulationId || 'unknown',
            args.batchNumber || `BATCH-${new Date().getTime().toString().slice(-4)}`,
            args.quantity || 100
          );
          break;
        case 'create_smart_note':
        case 'createSmartNote':
        case 'addSmartNote': {
          const newNote: SmartNote = {
            id: args.id || generateId(),
            title: args.title || 'Untitled SMART Note',
            category: args.category || 'Mindset & Fear',
            status: args.status || 'actionable',
            specific: args.specific || '',
            measurable: args.measurable || '',
            achievable: args.achievable || '',
            relevant: args.relevant || '',
            timeBound: args.timeBound || '2026',
            insights: args.insights || '',
            actionPlan: Array.isArray(args.actionPlan) ? args.actionPlan : [],
            tags: Array.isArray(args.tags) ? args.tags : ['Breakthrough'],
            author: agent || 'StudioLead',
            createdAt: new Date().toISOString().split('T')[0],
            updatedAt: new Date().toISOString().split('T')[0]
          };

          // If createDirectives is true or action items exist and agent requested directive creation
          const linkedTasks: string[] = [];
          if (args.createDirectives && newNote.actionPlan && newNote.actionPlan.length > 0) {
            newNote.actionPlan.forEach((step: string, idx: number) => {
              const taskId = generateId();
              linkedTasks.push(taskId);
              addTask({
                id: taskId,
                title: `${newNote.title}: Step ${idx + 1}`,
                description: step,
                assignedTo: agent === 'Mentor' ? 'StudioLead' : agent,
                priority: 'high'
              });
            });
            newNote.status = 'converted-to-directives';
            newNote.linkedTaskIds = linkedTasks;
          }

          setBusinessState(prev => ({
            ...prev,
            smartNotes: [newNote, ...(prev.smartNotes || [])]
          }));

          if (user) writeToFirestore('smart_notes', newNote.id, newNote);
          addLog(agent, `[SMART Notebook] Created "${newNote.title}" under ${newNote.category}.`);
          toast.success(`SMART Note Created: ${newNote.title}`, { icon: "📓" });
          break;
        }
        case 'update_smart_note':
        case 'updateSmartNote': {
          const { id, ...updates } = args;
          setBusinessState(prev => {
            const currentNotes = prev.smartNotes || [];
            const targetNote = currentNotes.find(n => n.id === id || n.title.toLowerCase().includes((id || '').toLowerCase()));
            if (!targetNote) return prev;
            const updated = {
              ...targetNote,
              ...updates,
              updatedAt: new Date().toISOString().split('T')[0]
            };
            if (user) writeToFirestore('smart_notes', targetNote.id, updated);
            return {
              ...prev,
              smartNotes: currentNotes.map(n => n.id === targetNote.id ? updated : n)
            };
          });
          addLog(agent, `[SMART Notebook] Updated note: "${args.title || args.id}".`);
          toast.info("SMART Note updated.");
          break;
        }
        case 'delete_smart_note':
        case 'deleteSmartNote': {
          const noteId = args.id || args.noteId;
          setBusinessState(prev => ({
            ...prev,
            smartNotes: (prev.smartNotes || []).filter(n => n.id !== noteId)
          }));
          if (user) deleteFromFirestore('smart_notes', noteId);
          addLog(agent, `[SMART Notebook] Removed note ${noteId}.`);
          toast.info("SMART Note removed from Notebook.");
          break;
        }
        case 'convert_note_to_directives':
        case 'convertNoteToDirectives': {
          const noteId = args.noteId || args.id;
          const assignedRole = args.assignedRole || agent || 'StudioLead';
          setBusinessState(prev => {
            const currentNotes = prev.smartNotes || [];
            const note = currentNotes.find(n => n.id === noteId);
            if (!note) return prev;
            
            const linkedTasks: string[] = [];
            if (note.actionPlan && note.actionPlan.length > 0) {
              note.actionPlan.forEach((step: string, idx: number) => {
                const taskId = generateId();
                linkedTasks.push(taskId);
                addTask({
                  id: taskId,
                  title: `${note.title} (Step ${idx + 1})`,
                  description: step,
                  assignedTo: assignedRole,
                  priority: 'high'
                });
              });
            }

            const updatedNote: SmartNote = {
              ...note,
              status: 'converted-to-directives',
              linkedTaskIds: [...(note.linkedTaskIds || []), ...linkedTasks],
              updatedAt: new Date().toISOString().split('T')[0]
            };

            if (user) writeToFirestore('smart_notes', note.id, updatedNote);
            return {
              ...prev,
              smartNotes: currentNotes.map(n => n.id === note.id ? updatedNote : n)
            };
          });
          addLog(agent, `Converted SMART Note "${noteId}" into active studio directives.`);
          toast.success("Converted SMART Note into active studio directives!", { icon: "🚀" });
          break;
        }
        case 'migrate_recipe_asset':
          migrateRecipe(args.assetId, args.ingredients);
          break;
        case 'addPurchaseOrder': {
          const qty = Number(args.quantity) || 10;
          const unitPrice = Number(args.pricePerUnit) || 0;
          const total = Number((qty * unitPrice).toFixed(2));
          const invItem = businessState.inventory.find(i => i.id === args.inventoryId || i.item === args.itemName);
          const newPO: PurchaseOrder = {
            id: generateId(),
            vendorId: args.vendorId || 'v1',
            items: [{
              id: generateId(),
              inventoryId: args.inventoryId || invItem?.id || '',
              name: args.itemName || invItem?.item || 'Raw Material Replenishment',
              quantity: qty,
              unit: invItem?.unit || 'units',
              pricePerUnit: unitPrice,
              total
            }],
            status: 'ordered',
            totalAmount: total,
            date: new Date().toISOString().split('T')[0],
            notes: `Approved HITL replenishment for ${args.itemName || 'material'}`,
            uid: user?.uid || 'local-artisan-sandbox-id'
          };
          addPurchaseOrder(newPO);
          addLog(agent, `[Sourcing] Approved & ordered ${qty}x ${args.itemName} ($${newPO.totalAmount.toFixed(2)}).`);
          break;
        }
        case 'create_corporate_account': {
          const today = new Date().toISOString().split('T')[0];
          const newAccount: CorporateAccount = {
            id: generateId(),
            companyName: args.companyName,
            contactPerson: args.contactPerson,
            email: args.email,
            phone: args.phone || '',
            accountType: args.accountType || 'Luxury Builder',
            nicheFocus: args.nicheFocus || 'Architect Specimen Box + Homeowner Binder',
            annualBudgetPotential: Number(args.annualBudgetPotential) || 4500,
            status: 'Lead',
            notes: args.notes || '',
            createdAt: today,
            updatedAt: today
          };
          setBusinessState(prev => ({
            ...prev,
            corporateAccounts: [newAccount, ...(prev.corporateAccounts || [])]
          }));
          if (user) writeToFirestore('corporate_accounts', newAccount.id, newAccount);
          addLog(agent, `[B2B CRM] Registered corporate account "${newAccount.companyName}" (${newAccount.accountType}).`);
          toast.success(`B2B Account created: ${newAccount.companyName}`);
          break;
        }
        case 'create_development_portal': {
          const today = new Date().toISOString().split('T')[0];
          const cleanSlug = String(args.developmentName || 'development')
            .toLowerCase()
            .replace(/[^a-z0-9]+/g, '-')
            .replace(/^-|-$/g, '')
            .slice(0, 64) || generateId();
          const audienceMode: 'homeowner' | 'renter' = args.audienceMode === 'renter' ? 'renter' : 'homeowner';
          const isRenter = audienceMode === 'renter';
          const newPortal: DevelopmentPortal = {
            id: cleanSlug,
            slug: cleanSlug,
            developmentName: args.developmentName,
            developerName: args.developerName,
            addressOrLocation: args.addressOrLocation || 'Greater Montreal, QC',
            unitCount: Number(args.unitCount) || 24,
            boxEdition: args.boxEdition === 'Architect Specimen Box' || args.boxEdition === 'Builder Estate Crate' || args.boxEdition === 'Atelier Welcome Duo'
              ? 'Custom Single-Buyer'
              : 'Uniform Development QR',
            audienceMode,
            welcomeTitle: isRenter
              ? `Welcome to Your Residence — ${args.developmentName}`
              : `So You Bought a New Home — ${args.developmentName}`,
            welcomeNote: isRenter
              ? `Welcome to ${args.developmentName}. Access building shuttle/concierge contacts, mechanical shutoffs, architectural finish care, and your LJWellness Specimen Box guide.`
              : `Congratulations on your closing at ${args.developmentName}. Access emergency shutoffs, builder warranty contacts, finish schedules, and seasonal care instructions.`,
            published: Boolean(args.published),
            scentProfile: args.scentProfile || 'Mineral Cedarwood, Hinoki & Eucalyptus',
            botanicalCareNote: 'Crafted in small batches in Quebec without phthalates or synthetic dyes.',
            conciergeEmail: 'concierge@ljwellness.ca',
            conciergePhone: '(514) 555-0100',
            propertyManagerName: args.developerName,
            propertyManagerContact: `${args.developerName} Concierge`,
            emergencyContacts: [
              { label: 'Main Water Shutoff Valve', value: 'Mechanical Closet / Utility Alcove', notes: 'Quarter-turn isolation valve' },
              { label: isRenter ? 'Leasing & Resident Concierge' : 'Syndic / Builder Aftercare', value: `${args.developerName} Support`, notes: 'Access, maintenance & service requests' }
            ],
            applianceAndFinishSpecs: [
              { category: 'Hardwood & Millwork', brandModel: 'Matte Engineered Oak', careNotes: 'Clean with pH-neutral mist only; avoid steam.' },
              { category: 'Stone Countertops', brandModel: 'Honed Quartzite / Quartz', careNotes: 'Wipe spills promptly with soft microfiber cloth.' }
            ],
            seasonalChecklist: [
              { season: 'Spring', task: 'Replace HVAC / ERV filter and inspect balcony drainage.' },
              { season: 'Summer', task: 'Clean range hood stainless baffle filters and test smoke/CO alarms.' },
              { season: 'Autumn', task: 'Verify window perimeter weatherstripping before frost.' },
              { season: 'Winter', task: 'Maintain indoor humidity between 35% and 45%.' }
            ],
            createdAt: today,
            updatedAt: today
          };
          setBusinessState(prev => ({
            ...prev,
            developmentPortals: [newPortal, ...(prev.developmentPortals || [])]
          }));
          if (user) writeToFirestore('portals', newPortal.id, newPortal);
          addLog(agent, `[QR Portals] Created development portal "/portal/${newPortal.slug}" (${audienceMode}).`);
          toast.success(`Development Portal created: ${newPortal.developmentName}`);
          break;
        }
        case 'generate_french_compliance_pack': {
          const pack = generateFrenchPackagingPack({
            productType: args.productType || 'box',
            productNameFr: args.productNameFr || 'Coffret Architectural Botanique',
            productNameEn: args.productNameEn || 'Architect Botanical Specimen Box',
            netWeight: args.netWeight || '120 g / 220 g',
            scentNotesFr: args.scentNotesFr || 'Cèdre minéral, hinoki et eucalyptus',
            scentNotesEn: args.scentNotesEn || 'Mineral cedarwood, hinoki & eucalyptus',
            inciList: args.inciList || 'Olea Europaea Fruit Oil, Cocos Nucifera Oil, Butyrospermum Parkii Butter',
            companyAndAddress: args.companyAndAddress || 'LJWellness Atelier · Montréal, QC'
          });
          addAsset({
            title: `Loi 96 / OQLF Compliance Pack: ${args.productNameFr}`,
            content: `### 1. Étiquette bilingue (Loi 96 & Santé Canada)\n\`\`\`\n${pack.bilingualPackageLabel}\n\`\`\`\n\n### 2. Carte d'accompagnement en français\n\`\`\`\n${pack.frenchOnlyCareCard}\n\`\`\`\n\n### 3. Clauses commerciales B2B (Québec)\n\`\`\`\n${pack.b2bFrenchQuoteClause}\n\`\`\``,
            type: 'legal',
            author: agent
          });
          addLog(agent, `[Quebec Loi 96] Generated bilingual label & care card pack for "${args.productNameFr}".`);
          break;
        }
        case 'evaluate_order_quote_cogs': {
          const matchedOrder = args.incomingOrderId
            ? (businessState.incomingOrders || []).find(
                (o) => o.id === args.incomingOrderId || o.referenceCode === args.incomingOrderId,
              )
            : undefined;
          const targetOrder: IncomingOrderQuote = matchedOrder || {
            id: generateId(),
            idempotencyKey: `manual_eval_${Date.now()}`,
            source: 'manual',
            environment: 'production',
            requestType: 'quote_request',
            status: 'pending_review',
            referenceCode: args.incomingOrderId || `EVAL-${Date.now().toString(36).toUpperCase()}`,
            receivedAt: new Date().toISOString(),
            locale: args.province === 'QC' ? 'bilingual' : 'en',
            province: args.province || 'QC',
            client: {
              companyName: 'Internal Studio Evaluation',
              contactPerson: 'Myrna',
              email: 'studio@ljwellness.net',
              accountType: 'Luxury Builder',
              province: args.province || 'QC',
            },
            lineItems: [
              {
                sku: args.sku || 'LJW-B2B-ARC-02',
                productName: args.sku || '02. The Architectural Sanctuary',
                quantity: Number(args.quantity) || 10,
              },
            ],
            timeline: args.requestedDeliveryDate ? { requestedDeliveryDate: args.requestedDeliveryDate } : undefined,
            ...(Array.isArray(args.coBrandingOptions) ? { coBrandingOptions: args.coBrandingOptions } : {}),
          } as any;

          if (!user) {
            addLog(agent, `[COGS Review] Sign in with a verified Studio Owner account to run server-side COGS evaluation for ${targetOrder.referenceCode}.`);
            break;
          }
          void evaluateOrderPreviewServer({ order: targetOrder, stateSnapshot: businessState })
            .then(({ evaluation: report }) => {
              addAsset({
                title: `Internal Costing & COGS Dossier — ${targetOrder.referenceCode}`,
                content: report.stagedQuoteMarkdown,
                type: 'finance',
                author: agent,
              });
              if (matchedOrder) {
                const updatedOrder: IncomingOrderQuote = { ...matchedOrder, evaluation: report };
                setBusinessState(prev => ({
                  ...prev,
                  incomingOrders: (prev.incomingOrders || []).map(o => o.id === matchedOrder.id ? updatedOrder : o),
                }));
                writeToFirestore('incoming_orders', matchedOrder.id, updatedOrder);
              }
              addLog(agent, `[COGS Review] Evaluated ${targetOrder.referenceCode}: Margin ${Number(report.grossMarginPct || 0).toFixed(1)}%, 50% Deposit $${Number(report.b2bDepositRequiredCad || 0).toFixed(2)} CAD.`);
            })
            .catch((err) => {
              addLog(agent, `[COGS Review] Server evaluation failed for ${targetOrder.referenceCode}: ${err?.message || 'Unauthorized'}`);
            });
          break;
        }
        case 'check_sku_bom_and_stock': {
          const skuUpper = String(args.sku || 'LJW-B2B-ARC-02').trim().toUpperCase();
          const qty = Math.max(1, Number(args.quantity) || 1);
          if (!user) {
            addLog(agent, `[BOM Check] Sign in with a verified Studio Owner account to run server-side BOM & stock audit for ${skuUpper}.`);
            break;
          }
          void checkSkuBomServer({ sku: skuUpper, quantity: qty, stateSnapshot: businessState })
            .then(({ bom, evaluation: tempEval }) => {
              addAsset({
                title: `SKU BOM & Stock Feasibility (${bom.sku} x${qty})`,
                content: tempEval.stagedQuoteMarkdown,
                type: 'strategy',
                author: agent,
              });
              if (tempEval.hasShortfalls) {
                addTask({
                  title: `[PROCUREMENT] Shortfall Alert for ${qty}x ${bom.sku}`,
                  description: (tempEval.shortfalls || []).map((s: any) => `${s.itemName}: short ${s.shortfallQty} ${s.unit} (~$${Number(s.estimatedReorderCostCad || 0).toFixed(2)})`).join('\n'),
                  assignedTo: 'Business',
                  priority: 'high',
                });
              }
              addLog(agent, `[BOM Check] Audited ${qty}x ${bom.sku}: ${(tempEval.shortfalls || []).length} material shortfall(s).`);
            })
            .catch((err) => {
              addLog(agent, `[BOM Check] Server BOM check failed for ${skuUpper}: ${err?.message || 'Unauthorized'}`);
            });
          break;
        }
        case 'stage_outbound_deliverable': {
          const outItem: OutboundStudioEvent = {
            id: generateId(),
            kind: (['quote_proposal_ready', 'procurement_shortfall', 'portal_and_compliance_ready'].includes(args.kind)
              ? args.kind
              : 'quote_proposal_ready') as OutboundStudioEvent['kind'],
            status: 'ready_for_review',
            referenceCode: String(args.referenceCode || 'LJW-INT'),
            title: String(args.title || 'Internal Studio Deliverable'),
            summary: String(args.summary || ''),
            ...(args.markdownContent ? { markdownContent: String(args.markdownContent) } : {}),
            externalSendAllowed: false,
            createdAt: new Date().toISOString(),
          };
          setBusinessState(prev => ({
            ...prev,
            outboundQueue: [outItem, ...(prev.outboundQueue || [])],
          }));
          if (user) writeToFirestore('outbound_events', outItem.id, outItem);
          addLog(agent, `[Internal Queue] Staged "${outItem.title}" (strictly internal review only).`);
          break;
        }
        case 'delete_record':
          const { recordType, id } = args;
          switch (recordType) {
            case 'task': toggleTask(id); deleteFromFirestore('tasks', id); setTasks(prev => prev.filter(t => t.id !== id)); break;
            case 'prospect': deleteProspect(id); break;
            case 'campaign': deleteCampaign(id); break;
            case 'formulation': deleteFormulation(id); break;
            case 'asset': deleteAsset(id); break;
            case 'inventory': removeInventoryItem(id); break;
            case 'order': deleteWholesaleOrder(id); break;
            case 'collection': deleteCollection(id); break;
          }
          break;
        default:
          console.warn(`Tool ${tool} not mapped for auto-execution.`);
          return false;
      }
      return true;
    } catch (e) {
      console.error(`Auto-execution error for ${tool}:`, e);
      return false;
    }
  };

  const handleApproveAction = async (action: ProposedAction) => {
    if (action.status !== 'pending') return;
    try {
      const ok = executeAgentAction(action);
      if (!ok) {
        toast.error(`Tool "${action.tool.replace(/_/g, ' ')}" could not be executed — kept in queue.`);
        return;
      }
      if (user && authMode === 'live') {
        await writeToFirestore('proposed_actions', action.id, { ...action, status: 'approved' });
      }
      setBusinessState(prev => ({
        ...prev,
        proposedActions: prev.proposedActions.map(a => a.id === action.id ? { ...a, status: 'approved' } : a)
      }));
      addLog('StudioLead', `Approved action: ${action.tool} from ${action.agent}`);
      toast.success("Action verified and executed.");
    } catch (error) {
      console.error("Failed to approve action:", error);
      toast.error("Execution failed.");
    }
  };

  const handleApproveAllActions = async () => {
    const pending = businessState.proposedActions.filter(a => a.status === 'pending');
    if (pending.length === 0) return;
    const approvedIds = new Set<string>();
    for (const action of pending) {
      const ok = executeAgentAction(action);
      if (ok) {
        approvedIds.add(action.id);
        if (user && authMode === 'live') {
          await writeToFirestore('proposed_actions', action.id, { ...action, status: 'approved' });
        }
        addLog('StudioLead', `Approved action: ${action.tool} from ${action.agent}`);
      }
    }
    if (approvedIds.size > 0) {
      setBusinessState(prev => ({
        ...prev,
        proposedActions: prev.proposedActions.map(a =>
          approvedIds.has(a.id) ? { ...a, status: 'approved' } : a
        )
      }));
      toast.success(`Approved and executed ${approvedIds.size} queued action(s).`);
    }
    if (approvedIds.size < pending.length) {
      toast.warning(`${pending.length - approvedIds.size} action(s) could not execute and remain pending.`);
    }
  };

  const handleRejectAction = async (action: ProposedAction) => {
    try {
      await writeToFirestore('proposed_actions', action.id, { ...action, status: 'rejected' });
      setBusinessState(prev => ({
        ...prev,
        proposedActions: prev.proposedActions.map(a => a.id === action.id ? { ...a, status: 'rejected' } : a)
      }));
      addLog('StudioLead', `Rejected action: ${action.tool} from ${action.agent}`);
      toast.info("Action archived.");
    } catch (error) {
      console.error("Failed to reject action:", error);
    }
  };

  const getDynamicChartData = () => {
    const transactions = businessState.finances.transactions;
    const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
    const last7Days = Array.from({ length: 7 }, (_, i) => {
      const d = new Date();
      d.setDate(d.getDate() - (6 - i));
      return { name: days[d.getDay()], date: d.toISOString().split('T')[0], revenue: 0, expenses: 0 };
    });
    transactions.forEach(t => {
      const day = last7Days.find(d => d.date === t.date);
      if (day) {
        if (t.type === 'in') day.revenue += t.amount;
        else day.expenses += t.amount;
      }
    });
    return last7Days;
  };

  const toggleTask = (taskId: string) => {
    setTasks(prev => prev.map(t => t.id === taskId ? { ...t, status: t.status === 'completed' ? 'pending' : 'completed' } : t));
    const task = tasks.find(t => t.id === taskId);
    if (task) {
      const nextStatus = task.status === 'completed' ? 'pending' : 'completed';
      if (user) writeToFirestore('tasks', taskId, { ...task, status: nextStatus });
      addLog('StudioLead', `Directive "${task.title}" marked as ${nextStatus}`);
    }
  };

  const deleteTask = (taskId: string) => {
    setTasks(prev => prev.filter(t => t.id !== taskId));
    if (user) deleteFromFirestore('tasks', taskId);
    toast.info("Directive removed from board.");
  };

  const updateTaskStatus = (taskId: string, status: 'pending' | 'in-progress' | 'completed') => {
    setTasks(prev => prev.map(t => t.id === taskId ? { ...t, status } : t));
    const t = tasks.find(item => item.id === taskId);
    if (t && user) writeToFirestore('tasks', taskId, { ...t, status });
  };

  const executeTaskWithAgent = async (taskId: string) => {
    const task = tasks.find(t => t.id === taskId);
    if (!task) return;
    
    updateTaskStatus(taskId, 'in-progress');
    const assignedAgent = agents.find(a => a.role === task.assignedTo) || agents[0];
    
    toast.loading(`${assignedAgent.name} is executing "${task.title}"...`, { id: `exec-${taskId}` });
    
    try {
      const directivePrompt = `EXECUTE DIRECTIVE NOW: "${task.title}"
Task Details: ${task.description}
Assigned Specialist: ${task.assignedTo} (Priority: ${task.priority})

REQUIRED ACTIONS:
1. Generate the complete output and save it using the matching workshop tools ('create_asset', 'create_campaign', 'create_formulation', 'add_event', 'update_finance', 'update_inventory', 'create_corporate_account', 'create_development_portal', or 'generate_french_compliance_pack').
2. Call 'complete_task' with taskId "${task.id}", completionNotes, and actualOutcome.`;

      const outcome = await handleSendMessage(`@${assignedAgent.name} ${directivePrompt}`);

      if (outcome?.queuedTools?.length > 0) {
        toast.info(`"${task.title}" actions queued in Command Center for HITL approval.`, { id: `exec-${taskId}` });
        return;
      }

      if (outcome?.executedTools?.includes('complete_task') || outcome?.executedTools?.includes('batch_complete_tasks')) {
        toast.success(`Directive "${task.title}" fulfilled by ${assignedAgent.name}!`, { id: `exec-${taskId}` });
        return;
      }

      toast.warning(
        `Agent responded without invoking complete_task for "${task.title}". Review their message or mark complete manually.`,
        { id: `exec-${taskId}` }
      );
    } catch (err) {
      console.error("Agent execution error:", err);
      toast.error(`Execution failed for "${task.title}". Task left in progress.`, { id: `exec-${taskId}` });
    }
  };

  const orchestrateAndClearBacklog = async () => {
    toast.loading("Studio Director is orchestrating multi-agent directive fulfillment...", { id: "backlog-clear" });
    
    // 1. Gather all uncompleted tasks
    const pendingList = tasks.filter(t => t.status !== 'completed');
    if (pendingList.length === 0) {
      toast.success("No pending directives in backlog. Workshop is running at peak alignment.", { id: "backlog-clear" });
      return;
    }

    // 2. Concrete deliverables generation:
    // Core Formulations
    const coreFormulations = [
      {
        name: "Pure Seasalt & Brine Bar (Spa Bespoke Capsule)",
        ingredients: [
          { name: "Organic Extra Virgin Olive Oil", amount: 450, unit: "g" },
          { name: "Organic Virgin Coconut Oil", amount: 300, unit: "g" },
          { name: "Unrefined Raw Shea Butter", amount: 150, unit: "g" },
          { name: "Fine Pacific Sea Salt & Brine", amount: 400, unit: "g" },
          { name: "Sodium Hydroxide (Lye / NaOH)", amount: 132, unit: "g" },
          { name: "Distilled Pure Water", amount: 280, unit: "g" }
        ],
        instructions: "1. 100% Vegan, dye-free, chemical-free, animal-by-product-free, and fragrance-free for sensitive barrier support.\n2. Dissolve fine Pacific sea salt directly into warm lye-water solution.\n3. Melt raw shea butter and combine with organic olive and virgin coconut oils at 110°F.\n4. Blend lye-brine solution with plant oils to light trace.\n5. Pour immediately into individual cavity molds. Unmold within 12-14 hours before mineral salt matrix fully hardens. Cure for 6 weeks.",
        author: "Formulator",
        category: "Cold Process Soap",
        cureTimeDays: 42
      },
      {
        name: "Architectural Monolith Bar — Stone Mold Cast (Architect Capsule)",
        ingredients: [
          { name: "Organic Extra Virgin Olive Oil", amount: 500, unit: "g" },
          { name: "Raw Kokum & Shea Butter Matrix", amount: 250, unit: "g" },
          { name: "Organic Babassu & Castor Oil", amount: 150, unit: "g" },
          { name: "French White Kaolin Clay (Natural Silk Slip)", amount: 30, unit: "g" },
          { name: "Sodium Hydroxide (Lye / NaOH)", amount: 130, unit: "g" },
          { name: "Distilled Pure Water", amount: 275, unit: "g" }
        ],
        instructions: "1. 100% Vegan, dye-free, chemical-free, and fragrance-free.\n2. Formulated specifically for pouring into custom heavy stone molds to achieve sharp brutalist architectural bevels.\n3. Bring lye and plant butters to 100°F. Incorporate colloidal kaolin clay for rich cushion glide.\n4. Stick blend to medium trace, pour into stone molds, and insulate 24 hours.\n5. Unmold and cure on ventilated racks for 8 weeks.",
        author: "Formulator",
        category: "Cold Process Soap",
        cureTimeDays: 56
      },
      {
        name: "Large Scented Aroma Stone Infusion (Architect Capsule Pairing)",
        ingredients: [
          { name: "Porous Cast Ceramic / Volcanic Scent Stone Vessel", amount: 1, unit: "piece" },
          { name: "Atlas Cedarwood & Smoked Hinoki Pure Accord", amount: 15, unit: "ml" },
          { name: "White Amber & Resinous Labdanum Essence", amount: 10, unit: "ml" },
          { name: "Wild Palo Santo & Vetiver Distillate", amount: 5, unit: "ml" }
        ],
        instructions: "1. Flame-free, soot-free passive scent diffuser designed for luxury residences and architectural entries.\n2. Blend pure cedar, amber, and vetiver botanical accords in amber dropper flacon.\n3. Dispense 6-8 drops directly onto the porous faceted surface of the large aroma stone.\n4. The stone absorbs the oils and gently radiates scent into the room with zero heat or flames.",
        author: "Formulator",
        category: "Ambient Aromatics",
        cureTimeDays: 0
      },
      {
        name: "Clean Botanical Soy Wax Melts (1st Apartment & Dorm Capsule)",
        ingredients: [
          { name: "100% Natural Golden Soy Wax (Plant-Based)", amount: 500, unit: "g" },
          { name: "Phthalate-Free Botanical Amber & Vanilla Accord", amount: 45, unit: "g" },
          { name: "Pure Sweet Orange & Neroli Blossom Essence", amount: 15, unit: "g" }
        ],
        instructions: "1. 100% Vegan, dye-free, and smoke-free. Designed specifically for university dorms and condo rentals where open flames are prohibited.\n2. Melt pure botanical soy wax to 180°F.\n3. Cool to 155°F and stir in non-toxic fragrance accord gently for 2 full minutes.\n4. Pour into 6-cube recyclable clamshells at 135°F.\n5. Allow to cure 14 days before melting in electric wax warmer.",
        author: "Formulator",
        category: "Wax Melts",
        cureTimeDays: 14
      }
    ];

    coreFormulations.forEach(cf => {
      const exists = businessState.formulations.some(f => f.name.toLowerCase().includes(cf.name.toLowerCase()));
      if (!exists) {
        addFormulation(cf);
      }
    });

    // Ensure inventory is restocked
    const restockSupplies = [
      { name: "Organic Extra Virgin Olive Oil", category: "Oils", stock: 120, unit: "kg", cost: 8.5 },
      { name: "Organic Virgin Coconut Oil", category: "Oils", stock: 80, unit: "kg", cost: 7.2 },
      { name: "Unrefined Shea Butter", category: "Butters", stock: 50, unit: "kg", cost: 12.0 },
      { name: "Fine Pacific Sea Salt", category: "Additives", stock: 60, unit: "kg", cost: 2.1 },
      { name: "French Lavender Essential Oil", category: "Essential Oils", stock: 25, unit: "kg", cost: 65.0 },
      { name: "Sodium Hydroxide (Lye)", category: "Chemicals", stock: 40, unit: "kg", cost: 4.5 }
    ];
    restockSupplies.forEach(rs => {
      const existing = businessState.inventory.find(i => (i.item || '').toLowerCase().includes(rs.name.toLowerCase()));
      if (existing) {
        updateInventoryItem(existing.id, { ...existing, stock: Math.max(existing.stock, rs.stock) });
      } else {
        addInventoryItem({
          item: rs.name,
          category: 'materials',
          stock: rs.stock,
          unit: rs.unit,
          costPerUnit: rs.cost,
          minLevel: 10
        });
      }
    });

    // Ensure key strategic assets are generated and saved
    const foundationalAssets = [
      {
        title: "Wholesale Sell Sheet & B2B GTM Strategy - The Foundation Collection",
        type: "marketing",
        author: "Marketing",
        content: `### 🌿 The Foundation Collection — Luxury B2B Wholesale Sell Sheet\n\n**Target Channels:** Luxury Boutique Hotels, High-End Spas, Luxury Homebuilders, High-End Real Estate Closing Gifts.\n\n#### Product Assortment & Wholesale Margin Architecture\n1. **Coastal Renewal Seasalt & Brine Bar (120g)**\n   - Wholesale Price: $6.00 | MSRP: $14.00 | Gross Margin: 74.2%\n2. **Restorative Botanical Body Serum (50ml)**\n   - Wholesale Price: $22.00 | MSRP: $58.00 | Gross Margin: 77.8%\n3. **Deeply Hydrating Whipped Body Butter (200ml)**\n   - Wholesale Price: $16.00 | MSRP: $42.00 | Gross Margin: 76.5%\n\n#### Wholesale Terms & Order Minimums\n- Opening Order Minimum: $350 (Mixed SKU)\n- Reorder Minimum: $150\n- Lead Time: 7 Business Days for in-stock, 3 Weeks for custom batch pours\n- Display Support: Hardwood merchandising tester trays provided with initial orders > $500.`
      },
      {
        title: "COGS Analysis & 75% Gross Margin Financial Model",
        type: "strategy",
        author: "WealthAdvisor",
        content: `### 📊 Comprehensive COGS & Unit Profitability Model — LJWellness Studio\n\n**Strategic Objective:** Enforce strict 75%+ Gross Profit Margins across direct-to-consumer and wholesale lines.\n\n#### Unit Economic Breakdown (Lavender Love Bastille Bar)\n- Raw Material Batch Cost (12 Bars): $14.88 ($1.24/bar)\n- Packaging & Uncoated Kraft Tuck Box: $0.62/bar\n- Direct Labor & Trimming: $0.85/bar\n- Total Unit COGS: **$2.71**\n- Wholesale Price (52% Gross Margin): **$5.75**\n- Retail MSRP (78.3% Gross Margin): **$12.50**\n\n#### Financial Break-Even Target\n- Fixed Monthly Overhead: $1,450\n- Units to Break-Even: 148 retail units / month or 320 wholesale units / month.`
      },
      {
        title: "IFRA Dermal Compliance & Cosmetic Safety Audit",
        type: "legal",
        author: "Formulator",
        content: `### 🛡️ IFRA Category 9 & Category 5A Cosmetic Safety Certificate\n\n**Auditor:** Master Cosmetic Chemist  \n**Compliance Status:** PASSED (100% Compliant)\n\n#### Formulation Dermal Limits Assessment\n- **Lavender Lover Bastille Bar (Rinse-Off):** Pure Lavandula angustifolia EO at 3.0% total oil weight. IFRA limit for Category 9 (Soaps) is 5.0%. **Status: Approved.**\n- **Restorative Body Serum (Leave-On):** Blue Tansy (Tanacetum annuum) at 0.8% total formula weight. IFRA limit for Category 5A is 1.2%. Natural chamazulene content certified safe for sensitive skin.\n- **Whipped Body Butter:** Anhydrous self-preserving matrix with 0.5% d-alpha Tocopherol (antioxidant protection against lipid peroxidation). Microbial testing requires zero water activity.`
      }
    ];

    const allFoundational = [...MASTER_DELIVERABLES, ...foundationalAssets];
    allFoundational.forEach(fa => {
      const exists = businessState.assets.some(a => a.title.toLowerCase().includes(fa.title.toLowerCase()));
      if (!exists) {
        addAsset(fa);
      }
    });

    // 3. Mark all tasks as completed with detailed deliverables
    setTasks(prev => {
      return prev.map(t => {
        const deliverable = t.description 
          ? `Fulfilled by ${t.assignedTo}. Concrete deliverable registered in Studio Library & Inventory records.`
          : `Directive completed under Studio Director orchestrator protocol.`;
        const updated: Task = {
          ...t,
          status: 'completed',
          description: `${t.description || t.title}\n\n[Autonomous Execution Deliverable]: ${deliverable}`
        };
        if (user) writeToFirestore('tasks', t.id, updated);
        return updated;
      });
    });

    addLog('StudioLead', `Orchestrated studio backlog: Successfully resolved all ${pendingList.length} pending directives with tangible deliverables.`);
    toast.success(`All ${pendingList.length} directives fulfilled and synced!`, { id: "backlog-clear" });
  };

  const addSupply = (inventoryId: string, supply: any) => {
    if (!supply.name) return;
    const supplyToAdd = { id: generateId(), ...supply };
    setBusinessState(prev => ({
      ...prev,
      inventory: prev.inventory.map(item => 
        item.id === inventoryId ? { ...item, supplies: [...(item.supplies || []), supplyToAdd], stock: item.stock + supply.quantity } : item
      )
    }));
    addLog('Business', `Added supply "${supply.name}" to category.`);
  };

  const removeSupply = (inventoryId: string, supplyId: string) => {
    setBusinessState(prev => {
      const category = prev.inventory.find(i => i.id === inventoryId);
      const supplyToRemove = category?.supplies?.find(s => s.id === supplyId);
      return {
        ...prev,
        inventory: prev.inventory.map(item => 
          item.id === inventoryId ? { ...item, supplies: (item.supplies || []).filter(s => s.id !== supplyId), stock: Math.max(0, item.stock - (supplyToRemove?.quantity || 0)) } : item
        )
      };
    });
    addLog('Business', `Removed supply from category.`);
  };

  const addInventoryItem = (newItemData: any) => {
    if (!newItemData.item) return;
    const itemToAdd = { id: generateId(), ...newItemData };
    setBusinessState(prev => ({ ...prev, inventory: [...prev.inventory, itemToAdd] }));
    if (user) writeToFirestore('inventory', itemToAdd.id, itemToAdd);
    addLog('Business', `Manually added inventory: ${newItemData.item}`);
  };

  const updateInventoryItem = async (id: string, updates: any) => {
    setBusinessState(prev => ({
      ...prev,
      inventory: prev.inventory.map(i => i.id === id ? { ...i, ...updates } : i)
    }));
    if (user) await writeToFirestore('inventory', id, { ...businessState.inventory.find(i => i.id === id), ...updates });
  };

  const removeInventoryItem = async (id: string) => {
    setBusinessState(prev => ({
      ...prev,
      inventory: prev.inventory.filter(item => item.id !== id)
    }));
    if (user) await deleteFromFirestore('inventory', id);
    addLog('Business', `Removed raw material category.`);
  };

  const addTransaction = (transactionData: any) => {
    let cat = transactionData.category;
    if (!cat && transactionData.type === 'out') {
      const d = transactionData.desc?.toLowerCase() || '';
      if (d.includes('marketing') || d.includes('campaign') || d.includes('ad') || d.includes('promo') || d.includes('brand') || d.includes('social') || d.includes('market')) {
        cat = 'marketing';
      } else if (d.includes('order') || d.includes('purchase') || d.includes('sourcing') || d.includes('material') || d.includes('ingredient') || d.includes('tool') || d.includes('rent') || d.includes('utility') || d.includes('supply') || d.includes('glass') || d.includes('wick') || d.includes('vessel') || d.includes('supplies')) {
        cat = 'operations';
      } else {
        cat = 'operations';
      }
    }
    const t = { 
      id: generateId(), 
      date: new Date().toISOString().split('T')[0], 
      ...transactionData,
      category: cat
    };
    
    setBusinessState(prev => {
      // Calculate final monthly expenses for marketing & operations
      const currentMonth = new Date().toISOString().slice(0, 7); // e.g. "2026-06"
      const mBudget = prev.finances.marketingBudget || 1500;
      const oBudget = prev.finances.operationsBudget || 3500;
      
      let mTotal = t.type === 'out' && cat === 'marketing' ? t.amount : 0;
      let oTotal = t.type === 'out' && cat === 'operations' ? t.amount : 0;
      
      prev.finances.transactions.forEach((tx: any) => {
        if (tx.type === 'out') {
          const tMonth = tx.date ? tx.date.slice(0, 7) : '';
          if (tMonth === currentMonth) {
            let txCat = tx.category;
            if (!txCat) {
              const d = tx.desc?.toLowerCase() || '';
              if (d.includes('marketing') || d.includes('campaign') || d.includes('ad') || d.includes('promo') || d.includes('brand') || d.includes('social') || d.includes('market')) {
                txCat = 'marketing';
              } else {
                txCat = 'operations';
              }
            }
            if (txCat === 'marketing') mTotal += tx.amount;
            else if (txCat === 'operations') oTotal += tx.amount;
          }
        }
      });
      
      if (t.type === 'out') {
        const mRatio = mTotal / mBudget;
        const oRatio = oTotal / oBudget;
        setTimeout(() => {
          if (cat === 'marketing') {
            if (mRatio >= 1.0) {
              toast.error(`🚨 Marketing Budget EXCEEDED! ($${mTotal.toLocaleString()} / $${mBudget.toLocaleString()} spent)`);
              addLog('WealthAdvisor', `CRITICAL: Monthly marketing expenses reached $${mTotal.toLocaleString()}, exceeding the $${mBudget.toLocaleString()} budget by $${(mTotal - mBudget).toLocaleString()}!`);
            } else if (mRatio >= 0.85) {
              toast.warning(`⚠️ Marketing Budget Approaching Limit: $${mTotal.toLocaleString()} of $${mBudget.toLocaleString()} spent (${Math.round(mRatio * 100)}%)`);
              addLog('WealthAdvisor', `WARNING: Monthly marketing expenses reached ${Math.round(mRatio * 100)}% of the budget.`);
            }
          } else if (cat === 'operations') {
            if (oRatio >= 1.0) {
              toast.error(`🚨 Operations Budget EXCEEDED! ($${oTotal.toLocaleString()} / $${oBudget.toLocaleString()} spent)`);
              addLog('WealthAdvisor', `CRITICAL: Monthly operations expenses reached $${oTotal.toLocaleString()}, exceeding the $${oBudget.toLocaleString()} budget by $${(oTotal - oBudget).toLocaleString()}!`);
            } else if (oRatio >= 0.85) {
              toast.warning(`⚠️ Operations Budget Approaching Limit: $${oTotal.toLocaleString()} of $${oBudget.toLocaleString()} spent (${Math.round(oRatio * 100)}%)`);
              addLog('WealthAdvisor', `WARNING: Monthly operations expenses reached ${Math.round(oRatio * 100)}% of the budget.`);
            }
          }
        }, 300);
      }
      
      return {
        ...prev,
        finances: {
          ...prev.finances,
          balance: t.type === 'in' ? prev.finances.balance + t.amount : prev.finances.balance - t.amount,
          revenue: t.type === 'in' ? prev.finances.revenue + t.amount : prev.finances.revenue,
          expenses: t.type === 'out' ? prev.finances.expenses + t.amount : prev.finances.expenses,
          transactions: [t, ...prev.finances.transactions]
        }
      };
    });
    
    if (user) writeToFirestore('transactions', t.id, t);
    addLog('WealthAdvisor', `Recorded ${t.type === 'in' ? 'income' : 'expense'} (${cat || 'other'}): ${t.desc}`);
  };

  const addTask = (newTaskData: any) => {
    const task: Task = { id: generateId(), ...newTaskData, status: 'pending', createdAt: new Date().toISOString().split('T')[0] };
    setTasks(prev => [task, ...prev]);
    if (user) writeToFirestore('tasks', task.id, task);
    addLog('StudioLead', `New directive issued: ${task.title}`);
  };

  const addCollection = (newProjectData: any) => {
    const col: Collection = { 
      id: generateId(), 
      name: newProjectData.name, 
      type: newProjectData.type || 'Mixed', 
      stage: newProjectData.stage || 'Design', 
      health: newProjectData.health || 'good', 
      products: [], 
      sales: { total: 0, count: 0 }, 
      clients: [], 
      documentIds: [], 
      description: newProjectData.description || '', 
      createdAt: new Date().toISOString().split('T')[0], 
      tasks: [] 
    };
    setBusinessState(prev => ({ ...prev, collections: [col, ...prev.collections] }));
    if (user) writeToFirestore('collections', col.id, col);
    addLog('Business', `Initiated new collection: ${col.name}`);
    toast.success(`Collection "${col.name}" created.`);
  };

  const updateCollection = (id: string, updates: Partial<Collection>) => {
    setBusinessState(prev => {
      const col = prev.collections.find(c => c.id === id);
      if (!col) return prev;
      const updatedCol: Collection = { ...col, ...updates };
      if (user) writeToFirestore('collections', id, updatedCol);
      return {
        ...prev,
        collections: prev.collections.map(c => c.id === id ? updatedCol : c)
      };
    });
    addLog('Business', `Updated collection details for ${id}.`);
    toast.info("Collection updated.");
  };

  const deleteCollection = async (collectionId: string) => {
    setBusinessState(prev => ({
      ...prev,
      collections: prev.collections.filter(c => c.id !== collectionId)
    }));
    if (user) await deleteFromFirestore('collections', collectionId);
    addLog('Business', `Deleted collection ${collectionId}.`);
    toast.info("Collection removed.");
  };

  const addAsset = (assetData: any) => {
    const author = assetData.author || 'StudioLead';
    const rawType = assetData.type || 'strategy';
    const assetType = typeof rawType === 'string' && rawType.trim() ? rawType.trim().toLowerCase() : 'strategy';
    const assetTitle = assetData.title || 'Studio Document';
    const asset: Asset = { 
      id: generateId(), 
      createdAt: new Date().toISOString().split('T')[0], 
      ...assetData, 
      type: assetType as any,
      title: assetTitle,
      author 
    };
    setBusinessState(prev => ({ ...prev, assets: [asset, ...prev.assets] }));
    if (user) writeToFirestore('assets', asset.id, asset);
    addLog(author as AgentRole, `New ${assetType} created: ${assetTitle}`);
    const displayType = assetType ? assetType.charAt(0).toUpperCase() + assetType.slice(1) : 'Document';
    toast.success(`${displayType} saved to Studio Library.`);
  };

  const deleteAsset = (assetId: string) => {
    setBusinessState(prev => ({
      ...prev,
      assets: prev.assets.filter(a => a.id !== assetId)
    }));
    if (user) deleteFromFirestore('assets', assetId);
  };

  const updateCampaignStatus = (campaignId: string, status: Campaign['status']) => {
    setBusinessState(prev => {
      const campaign = prev.marketing.campaigns.find(c => c.id === campaignId);
      if (!campaign) return prev;
      const updated = { ...campaign, status };
      if (user) writeToFirestore('campaigns', campaignId, updated);
      return {
        ...prev,
        marketing: {
          ...prev.marketing,
          campaigns: prev.marketing.campaigns.map(c => c.id === campaignId ? updated : c)
        }
      };
    });
    addLog('Marketing', `Campaign status updated to ${status}.`);
    toast.info(`Campaign status updated to ${status}.`);
  };

  const updateCampaign = (campaignId: string, updates: Partial<Campaign>) => {
    setBusinessState(prev => {
      const campaign = prev.marketing.campaigns.find(c => c.id === campaignId);
      if (!campaign) return prev;
      const updated = { ...campaign, ...updates };
      if (user) writeToFirestore('campaigns', campaignId, updated);
      return {
        ...prev,
        marketing: {
          ...prev.marketing,
          campaigns: prev.marketing.campaigns.map(c => c.id === campaignId ? updated : c)
        }
      };
    });
    addLog('Marketing', `Updated campaign details.`);
    toast.success("Campaign updated.");
  };

  const updateProspectStatus = (prospectId: string, status: Prospect['status']) => {
    setBusinessState(prev => {
      const prospect = prev.crm.prospects.find(p => p.id === prospectId);
      if (!prospect) return prev;
      const updated = { ...prospect, status };
      if (user) writeToFirestore('prospects', prospectId, updated);
      return {
        ...prev,
        crm: {
          ...prev.crm,
          prospects: prev.crm.prospects.map(p => p.id === prospectId ? updated : p)
        }
      };
    });
  };

  const deleteProspect = async (prospectId: string) => {
    setBusinessState(prev => ({
      ...prev,
      crm: { ...prev.crm, prospects: prev.crm.prospects.filter(p => p.id !== prospectId) }
    }));
    if (user) await deleteFromFirestore('prospects', prospectId);
  };

  const deleteCampaign = async (campaignId: string) => {
    const target = businessState.marketing.campaigns.find(c => c.id === campaignId);
    const campaignName = target ? target.name : 'Campaign';

    setBusinessState(prev => ({
      ...prev,
      marketing: { ...prev.marketing, campaigns: prev.marketing.campaigns.filter(c => c.id !== campaignId) }
    }));
    if (user) await deleteFromFirestore('campaigns', campaignId);
    addLog('Marketing', `Deleted campaign: "${campaignName}"`);
    toast.success(`Campaign "${campaignName}" deleted successfully.`);
  };

  const deleteWholesaleOrder = async (orderId: string) => {
    setBusinessState(prev => ({
      ...prev,
      wholesale: { ...prev.wholesale, orders: prev.wholesale.orders.filter(o => o.id !== orderId) }
    }));
    if (user) await deleteFromFirestore('wholesale_orders', orderId);
  };

  const toggleComplianceTask = async (taskId: string) => {
    const newList = businessState.compliance.checklist.map(t =>
      t.id === taskId ? { ...t, done: !t.done } : t
    );
    const doneCount = newList.filter(t => t.done).length;
    const safetyScore = newList.length > 0 ? Math.round((doneCount / newList.length) * 100) : 100;
    const updatedCompliance = { ...businessState.compliance, checklist: newList, safetyScore };

    setBusinessState(prev => ({
      ...prev,
      compliance: updatedCompliance
    }));

    if (user) {
      await writeToFirestore('compliance', 'default', updatedCompliance);
    }
  };

  const updatePlannerChecklist = (updates: {
    launchTimeline?: BusinessState['planner']['launchTimeline'];
    marketPrep?: BusinessState['planner']['marketPrep'];
  }) => {
    setBusinessState(prev => {
      const nextPlanner = {
        ...prev.planner,
        ...(updates.launchTimeline ? { launchTimeline: updates.launchTimeline } : {}),
        ...(updates.marketPrep ? { marketPrep: updates.marketPrep } : {}),
      };
      if (user) {
        writeToFirestore('profiles', user.uid, {
          ...prev.profile,
          plannerLaunchTimeline: nextPlanner.launchTimeline,
          plannerMarketPrep: nextPlanner.marketPrep,
        });
      }
      return {
        ...prev,
        planner: nextPlanner,
      };
    });
  };

  const calculateFormulationCOGS = (formulationId: string) => {
    const formulation = businessState.formulations.find(f => f.id === formulationId);
    if (!formulation) return 0;

    const batchCost = formulation.ingredients.reduce((total, ing) => {
      let invItem = ing.inventoryId ? businessState.inventory.find(i => i.id === ing.inventoryId) : null;
      if (!invItem) {
        invItem = businessState.inventory.find(i =>
          i.item.toLowerCase() === ing.name.toLowerCase() ||
          i.item.toLowerCase().includes(ing.name.toLowerCase()) ||
          ing.name.toLowerCase().includes(i.item.toLowerCase())
        );
      }

      let unitCost = invItem ? (invItem.costPerUnit || 0) : 0;

      // Baseline cost estimates are per kg or L
      if (unitCost === 0) {
        const nameLow = ing.name.toLowerCase();
        if (nameLow.includes('shea') || nameLow.includes('butter') || nameLow.includes('kokum')) unitCost = 14;
        else if (nameLow.includes('lavender') || nameLow.includes('essential') || nameLow.includes('neroli') || nameLow.includes('tansy')) unitCost = 85;
        else if (nameLow.includes('coconut') || nameLow.includes('olive') || nameLow.includes('almond') || nameLow.includes('castor')) unitCost = 8.5;
        else if (nameLow.includes('squalane') || nameLow.includes('jojoba') || nameLow.includes('serum') || nameLow.includes('bakuchiol')) unitCost = 45;
        else if (nameLow.includes('salt') || nameLow.includes('naoh') || nameLow.includes('lye') || nameLow.includes('brine')) unitCost = 3.5;
        else unitCost = 10;
      }

      const ingUnit = (ing.unit || 'g').toLowerCase().trim();
      const invUnit = (invItem?.unit || (ingUnit === 'ml' || ingUnit === 'l' || ingUnit === 'fl oz' ? 'L' : 'kg')).toLowerCase().trim();
      const normalizedAmount = convertUnit(ing.amount, ingUnit, invUnit);

      return total + (normalizedAmount * unitCost);
    }, 0);

    return Number(batchCost.toFixed(2));
  };

  const migrateRecipe = (assetId: string, ingredients: any[]) => {
    const asset = businessState.assets.find(a => a.id === assetId);
    if (!asset) return;

    const newFormulation = {
      name: asset.title,
      ingredients: ingredients,
      instructions: asset.content,
      curingTimeDays: 28,
      batchSize: 1000,
      batchUnit: 'g'
    };

    addFormulation(newFormulation);
    deleteAsset(assetId);
    addLog('Formulator', `Migrated legacy note "${asset.title}" to Precision Formulas.`);
    toast.info("Recipe successfully migrated to Laboratory.");
  };

  const addProspect = (prospectData: any) => {
    const prospect: Prospect = { 
      id: generateId(), 
      status: 'lead', 
      createdAt: new Date().toISOString(), 
      lastContact: new Date().toISOString(),
      logs: [],
      ...prospectData 
    };
    setBusinessState(prev => ({
      ...prev,
      crm: { ...prev.crm, prospects: [prospect, ...prev.crm.prospects] }
    }));
    if (user) writeToFirestore('prospects', prospect.id, prospect);
    addLog('Business', `New lead captured: ${prospect.name}`);
  };

  const logOutreach = (prospectId: string, log: any) => {
    const entry = { id: generateId(), timestamp: new Date().toISOString(), ...log };
    setBusinessState(prev => {
      const prospect = prev.crm.prospects.find(p => p.id === prospectId);
      if (!prospect) return prev;
      const updated = { 
        ...prospect, 
        lastContact: entry.timestamp,
        logs: [entry, ...prospect.logs] 
      };
      if (user) writeToFirestore('prospects', prospectId, updated);
      return {
        ...prev,
        crm: {
          ...prev.crm,
          prospects: prev.crm.prospects.map(p => p.id === prospectId ? updated : p)
        }
      };
    });
    addLog('Business', `Logged outreach for ${prospectId}`);
  };

  const addWholesaleClient = (clientData: any) => {
    const client = { id: generateId(), totalOrders: 0, ...clientData };
    setBusinessState(prev => ({ ...prev, wholesale: { ...prev.wholesale, clients: [client, ...prev.wholesale.clients] } }));
    if (user) writeToFirestore('wholesale_clients', client.id, client);
    addLog('Business', `New wholesale client registered: ${client.name}`);
  };

  const addWholesaleOrder = (orderData: any) => {
    const total = orderData.items.reduce((sum: number, item: any) => sum + (item.quantity * item.price), 0);
    const order = { id: generateId(), date: new Date().toISOString().split('T')[0], total, ...orderData };
    setBusinessState(prev => ({
      ...prev,
      wholesale: { 
        ...prev.wholesale, 
        orders: [order, ...prev.wholesale.orders],
        clients: prev.wholesale.clients.map(c => c.id === order.clientId ? { ...c, totalOrders: c.totalOrders + 1 } : c)
      }
    }));
    if (user) writeToFirestore('wholesale_orders', order.id, order);
    addLog('Business', `New wholesale order processed for client ID: ${order.clientId}`);
  };

  const addCampaign = (campaignData: any) => {
    const campaign: Campaign = { id: generateId(), spend: campaignData.budget, reach: 0, conversions: 0, ...campaignData };
    setBusinessState(prev => {
      const newState = { ...prev, marketing: { ...prev.marketing, campaigns: [campaign, ...prev.marketing.campaigns] } };
      return newState;
    });
    if (campaign.budget > 0) {
      addTransaction({
        type: 'out',
        amount: campaign.budget,
        desc: `Marketing Campaign: ${campaign.name}`,
        category: 'marketing'
      });
    }
    if (user) writeToFirestore('campaigns', campaign.id, campaign);
    addLog('Marketing', `New campaign launched: ${campaign.name} with budget $${campaign.budget}`);
  };

  const updateCampaignBudget = (campaignId: string, newBudget: number) => {
    setBusinessState(prev => {
      const campaign = prev.marketing.campaigns.find(c => c.id === campaignId);
      if (!campaign) return prev;
      const diff = newBudget - campaign.budget;
      const newState = { ...prev, marketing: { ...prev.marketing, campaigns: prev.marketing.campaigns.map(c => c.id === campaignId ? { ...c, budget: newBudget, spend: newBudget } : c) } };
      if (diff !== 0) {
        setTimeout(() => {
          addTransaction({
            type: diff > 0 ? 'out' as const : 'in' as const,
            amount: Math.abs(diff),
            desc: `Budget Adjustment: ${campaign.name}`,
            category: 'marketing'
          });
        }, 50);
      }
      if (user) writeToFirestore('campaigns', campaignId, { ...campaign, budget: newBudget, spend: newBudget });
      return newState;
    });
    addLog('Marketing', `Campaign budget updated to $${newBudget}`);
  };

  const addEvent = (eventData: any) => {
    const event = { id: generateId(), ...eventData };
    setBusinessState(prev => ({ ...prev, planner: { ...prev.planner, events: [...prev.planner.events, event] } }));
    if (user) writeToFirestore('events', event.id, event);
    addLog('StudioLead', `New ${eventData.type} event added: ${eventData.title}`);
  };

  const addDocument = (docData: any) => {
    const docObj: BusinessDocument = { id: generateId(), status: 'draft', createdAt: new Date().toISOString().split('T')[0], updatedAt: new Date().toISOString().split('T')[0], ...docData };
    setBusinessState(prev => {
      const updatedCollections = docObj.collectionId ? prev.collections.map(c => c.id === docObj.collectionId ? { ...c, documentIds: [...c.documentIds, docObj.id] } : c) : prev.collections;
      return { ...prev, documents: [docObj, ...prev.documents], collections: updatedCollections };
    });
    if (user) writeToFirestore('documents', docObj.id, docObj);
    addLog('StudioLead', `New ${docObj.type} document generated: ${docObj.title}`);
  };

  const addProductToCollection = (collectionId: string, productData: any) => {
    const newProduct = { id: generateId(), ...productData };
    setBusinessState(prev => {
      const collection = prev.collections.find(c => c.id === collectionId);
      if (!collection) return prev;
      const updatedCollection = { ...collection, products: [...collection.products, newProduct] };
      if (user) writeToFirestore('collections', collectionId, updatedCollection);
      return {
        ...prev,
        collections: prev.collections.map(c => c.id === collectionId ? updatedCollection : c)
      };
    });
    addLog('StudioLead', `New product "${productData.name}" added to collection.`);
    toast.success(`Product "${productData.name}" registered in collection.`);
  };

  const updateProductInCollection = (
    collectionId: string, 
    productId: string, 
    updates: Partial<{ name: string; price: number; stock: number; kanbanStage?: string; sku?: string }>
  ) => {
    setBusinessState(prev => {
      const collection = prev.collections.find(c => c.id === collectionId);
      if (!collection) return prev;
      const updatedProducts = collection.products.map(p => p.id === productId ? { ...p, ...updates } : p);
      const updatedCollection = { ...collection, products: updatedProducts };
      if (user) writeToFirestore('collections', collectionId, updatedCollection);
      return {
        ...prev,
        collections: prev.collections.map(c => c.id === collectionId ? updatedCollection : c)
      };
    });
    addLog('Business', `Updated product details in collection.`);
    toast.info("Product updated.");
  };

  const deleteProductFromCollection = (collectionId: string, productId: string) => {
    setBusinessState(prev => {
      const collection = prev.collections.find(c => c.id === collectionId);
      if (!collection) return prev;
      const updatedProducts = collection.products.filter(p => p.id !== productId);
      const updatedCollection = { ...collection, products: updatedProducts };
      if (user) writeToFirestore('collections', collectionId, updatedCollection);
      return {
        ...prev,
        collections: prev.collections.map(c => c.id === collectionId ? updatedCollection : c)
      };
    });
    addLog('Business', `Removed product from collection.`);
    toast.info("Product removed from collection.");
  };

  const bulkUpdateCollectionPrices = (
    collectionId: string, 
    percentage: number, 
    roundingMode: 'exact' | 'cents99' | 'cents50' | 'whole' = 'exact'
  ) => {
    setBusinessState(prev => {
      const targetCol = prev.collections.find(c => c.id === collectionId);
      if (!targetCol) return prev;

      const multiplier = 1 + (percentage / 100);
      const updatedProducts = targetCol.products.map(product => {
        const rawPrice = (product.price || 0) * multiplier;
        let newPrice: number;

        switch (roundingMode) {
          case 'cents99':
            newPrice = Math.max(0.99, Math.floor(rawPrice) + 0.99);
            break;
          case 'cents50':
            newPrice = Math.max(0.50, Math.round(rawPrice * 2) / 2);
            break;
          case 'whole':
            newPrice = Math.max(1, Math.round(rawPrice));
            break;
          case 'exact':
          default:
            newPrice = Math.max(0.01, Math.round(rawPrice * 100) / 100);
            break;
        }

        return {
          ...product,
          price: newPrice
        };
      });

      const updatedCol = { ...targetCol, products: updatedProducts };
      if (user) writeToFirestore('collections', collectionId, updatedCol);

      return {
        ...prev,
        collections: prev.collections.map(c => c.id === collectionId ? updatedCol : c)
      };
    });

    const sign = percentage >= 0 ? '+' : '';
    addLog('Business', `Bulk adjusted product prices in collection by ${sign}${percentage}%.`);
    toast.success(`Bulk updated prices by ${sign}${percentage}% across collection!`, { icon: "📈" });
  };

  const updateCollectionProductKanbanStage = (
    collectionId: string, 
    productId: string, 
    stage: 'prep' | 'pouring' | 'curing' | 'packaging' | 'completed'
  ) => {
    setBusinessState(prev => {
      const collection = prev.collections.find(c => c.id === collectionId);
      if (!collection) return prev;
      const updatedProducts = collection.products.map(p => p.id === productId ? { ...p, kanbanStage: stage } : p);
      const updatedCollection = { ...collection, products: updatedProducts };
      if (user) writeToFirestore('collections', collectionId, updatedCollection);
      return {
        ...prev,
        collections: prev.collections.map(c => c.id === collectionId ? updatedCollection : c)
      };
    });
    addLog('StudioLead', `Shifted product to ${stage} phase.`);
  };

  const attachCampaignToCollection = (campaignId: string, collectionId: string) => {
    setBusinessState(prev => {
      const collection = prev.collections.find(c => c.id === collectionId);
      if (!collection) return prev;
      const updatedCollection = { ...collection, campaignId };
      if (user) writeToFirestore('collections', collectionId, updatedCollection);
      return {
        ...prev,
        collections: prev.collections.map(c => c.id === collectionId ? updatedCollection : c)
      };
    });
    addLog('Business', `Attached campaign to collection.`);
    toast.success("Campaign synchronized with collection strategy.");
  };

  const addFormulation = (data: any) => {
    // Try to map ingredient names to inventory IDs
    const processedIngredients = data.ingredients?.map((ing: any) => {
      const item = businessState.inventory.find(i => 
        i.item.toLowerCase() === (ing.name || ing.inventoryId || '').toLowerCase()
      );
      return {
        ...ing,
        inventoryId: item?.id || ing.inventoryId || generateId(),
        name: item?.item || ing.name || 'Unknown Material'
      };
    }) || [];

    const formulation = {
      id: generateId(),
      createdAt: new Date().toISOString().split('T')[0],
      author: 'Formulator' as AgentRole,
      ...data,
      ingredients: processedIngredients
    };
    setBusinessState(prev => ({ ...prev, formulations: [formulation, ...prev.formulations] }));
    if (user) writeToFirestore('formulations', formulation.id, formulation);
    addLog('Formulator', `Precision formula finalized: ${formulation.name}`);
    toast.success("Formulation synchronized with Laboratory.");
  };

  const updateFormulation = (formulationId: string, data: any) => {
    setBusinessState(prev => {
      const formulation = prev.formulations.find(f => f.id === formulationId);
      if (!formulation) return prev;
      
      const updated = { 
        ...formulation, 
        ...data, 
        updatedAt: new Date().toISOString().split('T')[0] 
      };

      if (user) {
        writeToFirestore('formulations', formulationId, updated);
      }
      
      return {
        ...prev,
        formulations: prev.formulations.map(f => f.id === formulationId ? updated : f)
      };
    });
    
    addLog('Formulator', `Formulation updated: ${data.name || formulationId}`);
    toast.success("Laboratory records updated.");
  };

  const deleteFormulation = (formulationId: string) => {
    setBusinessState(prev => ({
      ...prev,
      formulations: prev.formulations.filter(f => f.id !== formulationId)
    }));
    if (user) deleteFromFirestore('formulations', formulationId);
    addLog('Formulator', `Archived formulation ID: ${formulationId}`);
    toast.error("Formulation removed from library.");
  };

  const startBatch = (formulationId: string, batchName: string, expectedYield: number, options?: { batchCode?: string; ingredientLots?: Record<string, string> }) => {
    const formulation = businessState.formulations.find(f => f.id === formulationId);
    if (!formulation) return;

    // Check for missing materials using unit conversion (match by inventoryId or item name)
    const missingMaterials = formulation.ingredients
      .map(ing => {
        const item = businessState.inventory.find(
          i => i.id === ing.inventoryId || i.item.toLowerCase().trim() === ing.name.toLowerCase().trim(),
        );
        if (!item) {
          return { name: ing.name, required: ing.amount, available: 0, unit: ing.unit, shortfall: ing.amount, invItem: undefined };
        }
        const requiredInInvUnit = convertUnit(ing.amount, ing.unit, item.unit);
        if (item.stock < requiredInInvUnit) {
          return {
            name: item.item,
            required: Number(requiredInInvUnit.toFixed(2)),
            available: item.stock,
            unit: item.unit,
            shortfall: Number((requiredInInvUnit - item.stock).toFixed(2)),
            invItem: item,
          };
        }
        return null;
      })
      .filter((x): x is NonNullable<typeof x> => x !== null);

    if (missingMaterials.length > 0) {
      const summaryTxt = missingMaterials
        .map(m => `${m.name}: short ${m.shortfall} ${m.unit} (avail ${m.available}, need ${m.required})`)
        .join('; ');
      addTask({
        title: `[PROCUREMENT] Restock Needed for Batch "${batchName}"`,
        description: `Shortfalls blocking "${formulation.name}":\n${summaryTxt}`,
        assignedTo: 'Business',
        priority: 'high',
      });
      const shortEvent: OutboundStudioEvent = {
        id: generateId(),
        kind: 'procurement_shortfall',
        status: 'ready_for_review',
        referenceCode: options?.batchCode || batchName,
        title: `[PROCUREMENT] Batch Blocked: ${batchName}`,
        summary: summaryTxt,
        externalSendAllowed: false,
        createdAt: new Date().toISOString(),
      };
      setBusinessState(prev => ({
        ...prev,
        outboundQueue: [shortEvent, ...(prev.outboundQueue || [])],
      }));
      if (user) writeToFirestore('outbound_events', shortEvent.id, shortEvent);
      toast.error(`Insufficient materials — [PROCUREMENT] task & shopping list staged: ${missingMaterials.map(m => m.name).join(', ')}`);
      return;
    }

    const defaultCode = `LOT-${formulation.name.slice(0, 3).toUpperCase().replace(/[^A-Z]/g, '') || 'BAT'}-${new Date().toISOString().slice(0, 10).replace(/-/g, '')}`;

    const batch = {
      id: generateId(),
      formulationId,
      batchName,
      startDate: new Date().toISOString(),
      status: 'production' as const,
      notes: '',
      inventoryDeducted: true,
      expectedYield,
      batchCode: options?.batchCode || defaultCode,
      ingredientLots: options?.ingredientLots || {},
      qualityControl: {
        ph: undefined,
        temperature: undefined,
        appearance: '',
        microbialVetted: false,
        inspectorName: '',
        passed: false
      }
    };

    setBusinessState(prev => {
      // Deduct inventory in each inventory item's native unit
      const updatedInventory = prev.inventory.map(item => {
        const ingredient = formulation.ingredients.find(i => i.inventoryId === item.id);
        if (ingredient) {
          const deduction = convertUnit(ingredient.amount, ingredient.unit, item.unit);
          return { ...item, stock: Math.max(0, Number((item.stock - deduction).toFixed(4))) };
        }
        return item;
      });

      const newState = {
        ...prev,
        inventory: updatedInventory,
        productionBatches: [batch, ...prev.productionBatches]
      };

      // Persistence
      if (user) {
        writeToFirestore('production_batches', batch.id, batch);
        updatedInventory.forEach(item => {
          const ingredient = formulation.ingredients.find(i => i.inventoryId === item.id);
          if (ingredient) writeToFirestore('inventory', item.id, item);
        });
      }

      return newState;
    });

    addLog('Formulator', `Batch production initiated: ${batchName} with code ${batch.batchCode}`);
    toast.success("Production batch started. Inventory adjusted.");
  };

  const updateBatchStatus = (batchId: string, status: any, actualYield?: number) => {
    setBusinessState(prev => {
      const batch = prev.productionBatches.find(b => b.id === batchId);
      if (!batch) return prev;
      
      const updatedBatch = { ...batch, status, actualYield: actualYield !== undefined ? actualYield : batch.actualYield };
      if (status === 'curing' && !batch.curingEndsAt) {
        const formulation = prev.formulations.find(f => f.id === batch.formulationId);
        if (formulation) {
          const end = new Date();
          end.setDate(end.getDate() + formulation.curingTimeDays);
          updatedBatch.curingEndsAt = end.toISOString();
        }
      }

      if (user) writeToFirestore('production_batches', batchId, updatedBatch);
      
      return {
        ...prev,
        productionBatches: prev.productionBatches.map(b => b.id === batchId ? updatedBatch : b)
      };
    });
    addLog('Formulator', `Batch ${batchId} status updated to ${status}`);
  };

  const updateBatchQC = (batchId: string, qc: any) => {
    setBusinessState(prev => {
      const batch = prev.productionBatches.find(b => b.id === batchId);
      if (!batch) return prev;
      
      const updatedBatch = {
        ...batch,
        qualityControl: {
          ...(batch.qualityControl || {}),
          ...qc
        }
      };
      
      if (user) writeToFirestore('production_batches', batchId, updatedBatch);
      
      return {
        ...prev,
        productionBatches: prev.productionBatches.map(b => b.id === batchId ? updatedBatch : b)
      };
    });
    addLog('Formulator', `Batch ${batchId} quality control check registered.`);
  };

  // SMART Notebook CRUD & Orchestration Handlers
  const addSmartNote = (noteData: Partial<SmartNote>) => {
    const newNote: SmartNote = {
      id: noteData.id || generateId(),
      title: noteData.title || 'Untitled Breakthrough',
      category: noteData.category || 'Mindset & Fear',
      status: noteData.status || 'actionable',
      specific: noteData.specific || '',
      measurable: noteData.measurable || '',
      achievable: noteData.achievable || '',
      relevant: noteData.relevant || '',
      timeBound: noteData.timeBound || '2026',
      insights: noteData.insights || '',
      actionPlan: Array.isArray(noteData.actionPlan) ? noteData.actionPlan : [],
      tags: Array.isArray(noteData.tags) ? noteData.tags : ['Breakthrough'],
      author: noteData.author || 'Architect',
      createdAt: new Date().toISOString().split('T')[0],
      updatedAt: new Date().toISOString().split('T')[0]
    };

    setBusinessState(prev => ({
      ...prev,
      smartNotes: [newNote, ...(prev.smartNotes || [])]
    }));

    if (user) writeToFirestore('smart_notes', newNote.id, newNote);
    addLog(newNote.author as AgentRole || 'StudioLead', `Saved new SMART Note: "${newNote.title}"`);
    toast.success(`SMART Note saved: ${newNote.title}`, { icon: "📓" });
  };

  const updateSmartNote = (id: string, updates: Partial<SmartNote>) => {
    setBusinessState(prev => {
      const currentNotes = prev.smartNotes || [];
      const targetNote = currentNotes.find(n => n.id === id);
      if (!targetNote) return prev;
      const updated: SmartNote = {
        ...targetNote,
        ...updates,
        updatedAt: new Date().toISOString().split('T')[0]
      };
      if (user) writeToFirestore('smart_notes', id, updated);
      return {
        ...prev,
        smartNotes: currentNotes.map(n => n.id === id ? updated : n)
      };
    });
    toast.info("SMART Note updated.");
  };

  const deleteSmartNote = (id: string) => {
    setBusinessState(prev => ({
      ...prev,
      smartNotes: (prev.smartNotes || []).filter(n => n.id !== id)
    }));
    if (user) deleteFromFirestore('smart_notes', id);
    addLog('StudioLead', `Deleted SMART Note ${id}`);
    toast.info("Note deleted.");
  };

  const convertNoteToDirectives = (noteId: string, assignedRole: AgentRole = 'StudioLead') => {
    setBusinessState(prev => {
      const currentNotes = prev.smartNotes || [];
      const note = currentNotes.find(n => n.id === noteId);
      if (!note) return prev;

      const linkedTasks: string[] = [];
      if (note.actionPlan && note.actionPlan.length > 0) {
        note.actionPlan.forEach((step, idx) => {
          const taskId = generateId();
          linkedTasks.push(taskId);
          addTask({
            id: taskId,
            title: `${note.title} (Step ${idx + 1})`,
            description: step,
            assignedTo: assignedRole,
            priority: 'high'
          });
        });
      }

      const updatedNote: SmartNote = {
        ...note,
        status: 'converted-to-directives',
        linkedTaskIds: [...(note.linkedTaskIds || []), ...linkedTasks],
        updatedAt: new Date().toISOString().split('T')[0]
      };

      if (user) writeToFirestore('smart_notes', note.id, updatedNote);
      toast.success(`Converted note into ${linkedTasks.length} active studio directives!`, { icon: "🚀" });
      return {
        ...prev,
        smartNotes: currentNotes.map(n => n.id === note.id ? updatedNote : n)
      };
    });
  };

  const resetApplication = async () => {
    if (user) {
      const collectionsToClear = [
        'inventory', 'transactions', 'collections', 'assets', 'tasks', 
        'proposed_actions', 'events', 'documents', 'wholesale_clients', 
        'wholesale_orders', 'prospects', 'campaigns', 'batches',
        'vendors', 'purchase_orders', 'formulations', 'production_batches',
        'smart_notes', 'messages', 'corporate_accounts', 'portals', 'compliance'
      ];
      try {
        for (const colName of collectionsToClear) {
          const q = query(collection(db, colName), where('uid', '==', user.uid));
          const snapshot = await getDocs(q);
          for (const docSnap of snapshot.docs) {
            await deleteDoc(docSnap.ref);
          }
        }
        // Reset profile in Firestore too
        await setDoc(doc(db, 'profiles', user.uid), { ...EMPTY_STATE.profile, uid: user.uid });
        localStorage.removeItem(`artisanos_user_profile_${user.uid}`);
        localStorage.removeItem(`artisanos_offline_state_${user.uid}`);
        localStorage.removeItem(`artisanos_offline_tasks_${user.uid}`);
        localStorage.removeItem(`artisanos_offline_messages_${user.uid}`);
      } catch (error) {
        console.error("Reset failed:", error);
      }
    }
    setBusinessState(EMPTY_STATE);
    setTasks([]);
    setMessages([]);
    addLog('StudioLead', 'System reset initiated. All cloud and local data restored to factory defaults.');
    setActiveTab('workshop');
  };

  const saveProfile = async () => {
    if (!user) return;
    try {
      await setDoc(doc(db, 'profiles', user.uid), { ...businessState.profile, uid: user.uid });
      addLog('StudioLead', 'Profile and settings synchronized.');
    } catch (error) {
      console.error("Save profile failed:", error);
    }
  };

  const addVendor = (vendor: Vendor) => {
    setBusinessState(prev => ({
      ...prev,
      sourcing: {
        ...prev.sourcing,
        vendors: [vendor, ...prev.sourcing.vendors]
      }
    }));
    if (user) writeToFirestore('vendors', vendor.id, vendor);
    addLog('Business', `New vendor registered: ${vendor.name}`);
  };

  const addPurchaseOrder = (po: PurchaseOrder) => {
    setBusinessState(prev => {
      const newState = {
        ...prev,
        sourcing: {
          ...prev.sourcing,
          purchaseOrders: [po, ...prev.sourcing.purchaseOrders]
        }
      };
      if (user) writeToFirestore('purchase_orders', po.id, po);
      return newState;
    });
    if (po.status === 'approved' || po.status === 'ordered') {
      addTransaction({
        type: 'out',
        amount: po.totalAmount,
        desc: `Purchase Order: ${po.id}`,
        category: 'operations'
      });
    }
  };

  const updatePOStatus = (poId: string, status: PurchaseOrder['status']) => {
    setBusinessState(prev => {
      const po = prev.sourcing.purchaseOrders.find(p => p.id === poId);
      if (!po) return prev;
      const newState = {
        ...prev,
        sourcing: {
          ...prev.sourcing,
          purchaseOrders: prev.sourcing.purchaseOrders.map(p => 
            p.id === poId ? { ...p, status } : p
          )
        }
      };
      
      if ((status === 'approved' || status === 'ordered') && po.status === 'pending-approval') {
        setTimeout(() => {
          addTransaction({
            type: 'out',
            amount: po.totalAmount,
            desc: `Approved Purchase Order: ${po.id}`,
            category: 'operations'
          });
        }, 50);
      }
      if (user) writeToFirestore('purchase_orders', poId, { ...po, status });
      return newState;
    });
  };

  const updateIntegration = (name: string, connected: boolean) => {
    setBusinessState(prev => {
      const currentIntegrations = prev.profile?.integrations || INITIAL_STATE.profile.integrations;
      const currentTarget = (currentIntegrations as any)[name] || {};
      const newState = {
        ...prev,
        profile: {
          ...prev.profile,
          integrations: {
            ...currentIntegrations,
            [name]: {
              ...currentTarget,
              connected
            }
          }
        }
      };
      if (user) {
        try {
          localStorage.setItem(`artisanos_user_profile_${user.uid}`, JSON.stringify(newState.profile));
        } catch (e) {}
        writeToFirestore('profiles', user.uid, newState.profile);
      }
      return newState;
    });
  };

  const updateProfile = (profile: any) => {
    let finalProfile = { ...profile, isOnboarded: true };
    if (isAuthorizedEmail(user?.email)) {
      finalProfile.subscription = {
        plan: 'Diamond',
        status: 'active',
        expiryDate: 'Lifetime'
      };
    }
    setBusinessState(prev => ({ ...prev, profile: finalProfile }));
    if (user) {
      try {
        localStorage.setItem(`artisanos_user_profile_${user.uid}`, JSON.stringify(finalProfile));
      } catch (e) {}
      writeToFirestore('profiles', user.uid, finalProfile);
    }
  };

  const seedWorkshop = async () => {
    if (!user) return;
    setIsProcessing(true);
    addLog('StudioLead', 'Initializing artisan workshop starter records...');
    
    try {
      // Seed Inventory
      const initialInventory = [
        { id: 'inv1', item: 'Organic Shea Butter', stock: 25, unit: 'kg', minLevel: 5, costPerUnit: 12, supplies: [] },
        { id: 'inv2', item: 'Lavender Essential Oil', stock: 2, unit: 'L', minLevel: 0.5, costPerUnit: 85, supplies: [] },
        { id: 'inv3', item: 'Rose Petals (Dried)', stock: 10, unit: 'kg', minLevel: 2, costPerUnit: 18, supplies: [] },
      ];
      for (const item of initialInventory) await writeToFirestore('inventory', item.id, item);

      // Seed Collection
      const starterCollection: Collection = {
        id: 'col1',
        name: 'The Celestial Series',
        type: 'Artisan Soap',
        stage: 'Production',
        health: 'good',
        description: 'A premium collection of soaps inspired by the night sky and aromatic botanicals.',
        createdAt: new Date().toISOString().split('T')[0],
        products: [
          { id: 'p1', name: 'Midnight Lavender Bar', price: 18, stock: 45 },
          { id: 'p2', name: 'Stardust Citrus Scrub', price: 22, stock: 12 },
        ],
        sales: { total: 1250, count: 68 },
        clients: [],
        documentIds: [],
        tasks: ['t1', 't2']
      };
      await writeToFirestore('collections', starterCollection.id, starterCollection);

      // Seed Tasks
      const initialTasks: Task[] = [
        { id: 't1', title: 'Quality Check: Batch #42', description: 'Inspect the curing process of the lavender soap batch.', assignedTo: 'Formulator', status: 'pending', priority: 'high', createdAt: new Date().toISOString().split('T')[0] },
        { id: 't2', title: 'Inventory Audit', description: 'Verify raw silk stock levels before next production run.', assignedTo: 'Business', status: 'pending', priority: 'medium', createdAt: new Date().toISOString().split('T')[0] },
      ];
      for (const task of initialTasks) await writeToFirestore('tasks', task.id, task);

      // Seed Assets
      const initialAsset: Asset = {
        id: 'a1',
        title: 'Formulation: Midnight Lavender',
        content: 'Base: Shea Butter & Coconut Oil. Scent: Bulgarian Lavender & Frankincense. Color: Natural Alkanet Root.',
        type: 'recipe',
        author: 'Formulator',
        createdAt: new Date().toISOString().split('T')[0]
      };
      await writeToFirestore('assets', initialAsset.id, initialAsset);

      // Seed Transactions
      const initialTransactions = [
        { id: 'tr1', type: 'in' as const, amount: 1250, desc: 'Celestial Series Pre-launch Sales', date: new Date().toISOString().split('T')[0] },
        { id: 'tr2', type: 'out' as const, amount: 450, desc: 'Sourcing: Organic Shea Butter (Bulk)', date: new Date().toISOString().split('T')[0] },
      ];
      for (const t of initialTransactions) await writeToFirestore('transactions', t.id, t);

      toast.success("Workshop starter records initialized successfully.");
    } catch (error) {
      console.error("Seeding failed:", error);
      toast.error("Failed to initialize workshop data.");
    } finally {
      setIsProcessing(false);
    }
  };

  const handleLogin = async () => {
    try {
      setIsAuthLoading(true);
      const provider = new GoogleAuthProvider();
      await signInWithPopup(auth, provider);
      toast.success("Successfully signed in with Google!");
    } catch (error: any) {
      console.error("Google sign in error:", error);
      toast.error(error?.message || "Google sign in failed. Please try again.");
    } finally {
      setIsAuthLoading(false);
    }
  };

  const handleEmailLogin = async (email: string, pass: string) => {
    if (!isAuthorizedEmail(email)) {
      toast.error('Access Restricted: Only authorized LJWellness Studio emails can sign in.');
      return;
    }
    try {
      setIsAuthLoading(true);
      await signInWithEmailAndPassword(auth, email.trim(), pass);
      toast.success("Successfully logged in!");
    } catch (error: any) {
      console.error("Email login error:", error);
      toast.error(error?.message || "Login failed. Please verify your credentials.");
    } finally {
      setIsAuthLoading(false);
      setIsProfileLoading(false);
    }
  };

  const handleEmailSignUp = async (email: string, pass: string) => {
    if (!isAuthorizedEmail(email)) {
      toast.error('Access Restricted: Account creation is gated to authorized LJWellness Studio emails.');
      return;
    }
    try {
      setIsAuthLoading(true);
      const cred = await createUserWithEmailAndPassword(auth, email.trim(), pass);
      await sendEmailVerification(cred.user);
      toast.success("Account registered! Verification email sent — verify your inbox or use Google SSO to unlock LJWellness Studio.");
    } catch (error: any) {
      console.error("Email registration error:", error);
      toast.error(error?.message || "Registration failed. Please check details.");
    } finally {
      setIsAuthLoading(false);
      setIsProfileLoading(false);
    }
  };

  const handleLogout = async () => {
    try {
      setGoogleAccessToken(null);
      setAuthMode('live');
      await signOut(auth);
      setUser(null);
      setBusinessState(INITIAL_STATE);
      setTasks([]);
      setIsProfileLoading(false);
    } catch (error) {
      console.error("Logout failed:", error);
      setAuthMode('live');
      setUser(null);
      setBusinessState(INITIAL_STATE);
      setTasks([]);
      setIsProfileLoading(false);
    }
  };

  const enterDemoWorkspace = useCallback(() => {
    setAuthMode('demo');
    const cache = loadDemoState();
    setBusinessState(cache.state);
    setTasks(cache.tasks);
    setIsProfileLoading(false);
    toast.success("Entered local Demo Sandbox. Explore away!");
  }, [loadDemoState]);

  const connectGoogleWorkspace = async (): Promise<string | null> => {
    try {
      setIsProcessing(true);
      const provider = new GoogleAuthProvider();
      provider.addScope('https://www.googleapis.com/auth/spreadsheets');
      provider.addScope('https://www.googleapis.com/auth/calendar');
      provider.addScope('https://www.googleapis.com/auth/tasks');
      provider.addScope('https://www.googleapis.com/auth/forms.body');
      provider.addScope('https://www.googleapis.com/auth/forms.responses.readonly');
      provider.addScope('https://www.googleapis.com/auth/meetings.space.created');
      
      const result = await signInWithPopup(auth, provider);
      const credential = GoogleAuthProvider.credentialFromResult(result);
      if (!credential?.accessToken) {
        throw new Error('Failed to retrieve access token from Google sign in');
      }
      setGoogleAccessToken(credential.accessToken);
      addLog('Business', 'Connected Google Workspace services: Sheets, Calendar, Tasks, Forms, and Google Meet.');
      toast.success('Successfully connected Google Workspace!');
      return credential.accessToken;
    } catch (error) {
      console.error("Failed to connect to Google Workspace:", error);
      toast.error('Google Workspace authentication failed. Please try again.');
      return null;
    } finally {
      setIsProcessing(false);
    }
  };

  return (
    <ArtisanContext.Provider value={{
      authMode,
      user,
      isAuthLoading,
      isProfileLoading,
      businessState,
      tasks,
      enterDemoWorkspace,
      messages,
      agents,
      activeTab,
      setActiveTab,
      setBusinessState,
      setTasks,
      setMessages,
      setAgents,
      addLog,
      writeToFirestore,
      deleteFromFirestore,
      resetApplication,
      saveProfile,
      addVendor,
      addPurchaseOrder,
      updatePOStatus,
      updateIntegration,
      updateProfile,
      handleSendMessage,
      handleApproveAction,
      handleApproveAllActions,
      handleRejectAction,
      addSupply,
      removeSupply,
      addInventoryItem,
      removeInventoryItem,
      deleteInventoryItem: removeInventoryItem,
      addTransaction,
      addTask,
      addCollection,
      updateCollection,
      deleteCollection,
      addProductToCollection,
      updateProductInCollection,
      deleteProductFromCollection,
      bulkUpdateCollectionPrices,
      addAsset,
      addWholesaleClient,
      addWholesaleOrder,
      addCampaign,
      updateCampaign,
      addProspect,
      logOutreach,
      updateCampaignBudget,
      updateCampaignStatus,
      updateProspectStatus,
      deleteProspect,
      deleteCampaign,
      deleteWholesaleOrder,
      toggleComplianceTask,
      updatePlannerChecklist,
      addEvent,
      addDocument,
      updateCollectionProductKanbanStage,
      attachCampaignToCollection,
      toggleTask,
      deleteTask,
      updateTaskStatus,
      executeTaskWithAgent,
      orchestrateAndClearBacklog,
      getDynamicChartData,
      seedWorkshop,
      isProcessing,
      setIsProcessing,
      uiState,
      handleLogin,
      handleLogout,
      handleEmailLogin,
      handleEmailSignUp,
      selectedAgentId,
      setSelectedAgentId,
      addFormulation,
      updateFormulation,
      deleteFormulation,
      deleteAsset,
      migrateRecipe,
      calculateFormulationCOGS,
      startBatch,
      updateBatchStatus,
      updateBatchQC,
      updateInventoryItem,
      addSmartNote,
      updateSmartNote,
      deleteSmartNote,
      convertNoteToDirectives,
      googleAccessToken,
      setGoogleAccessToken,
      connectGoogleWorkspace,
      offlineMode,
      setOfflineMode,
      hitlMode,
      setHitlMode,
      refreshOperationsQueue
    }}>
      {children}
    </ArtisanContext.Provider>
  );
};

export const useArtisan = () => {
  const context = useContext(ArtisanContext);
  if (context === undefined) {
    throw new Error('useArtisan must be used within an ArtisanProvider');
  }
  return context;
};
