import { create } from 'zustand';
import type {
  Campaign,
  MarketingAsset,
  AdInsight,
  LiveOptimizationEvent,
  CatalystSettings,
} from '@/types';

// ── Store Types ────────────────────────────────────────────────────────────────

interface MarketingState {
  campaigns: Campaign[];
  activeAssets: MarketingAsset[];
  adInsights: AdInsight[];
  liveEvents: LiveOptimizationEvent[];
  settings: CatalystSettings;
  activeTab: 'studio' | 'command' | 'intelligence' | 'war-room' | 'marketing' | 'dream-weaver';

  // Actions
  addCampaign: (campaign: Campaign) => void;
  updateCampaign: (id: string, updates: Partial<Campaign>) => void;
  addAsset: (asset: MarketingAsset) => void;
  updateAsset: (id: string, updates: Partial<MarketingAsset>) => void;
  updateInsights: (insights: AdInsight[]) => void;
  pushLiveEvent: (event: LiveOptimizationEvent) => void;
  setMetaSettings: (settings: Partial<CatalystSettings>) => void;
  setActiveTab: (tab: MarketingState['activeTab']) => void;
}

// ── Store ─────────────────────────────────────────────────────────────────────

export const useMarketingStore = create<MarketingState>()((set) => ({
  campaigns: [],
  activeAssets: [],
  adInsights: [],
  liveEvents: [],
  activeTab: 'studio',

  settings: {
    metaAccessToken: '',
    metaAdAccountId: '',
    metaBusinessId: '',
    metaAppId: '',
    whatsappPhoneNumberId: '',
    isConnected: false,
  },

  addCampaign: (campaign) =>
    set((state) => ({ campaigns: [...state.campaigns, campaign] })),

  updateCampaign: (id, updates) =>
    set((state) => ({
      campaigns: state.campaigns.map((c) =>
        c.id === id ? { ...c, ...updates, updatedAt: new Date() } : c
      ),
    })),

  addAsset: (asset) =>
    set((state) => ({ activeAssets: [...state.activeAssets, asset] })),

  updateAsset: (id, updates) =>
    set((state) => ({
      activeAssets: state.activeAssets.map((a) =>
        a.id === id ? { ...a, ...updates } : a
      ),
    })),

  updateInsights: (insights) => set({ adInsights: insights }),

  pushLiveEvent: (event) =>
    set((state) => ({
      // Keep a rolling window of the latest 30 events
      liveEvents: [event, ...state.liveEvents].slice(0, 30),
    })),

  setMetaSettings: (updates) =>
    set((state) => ({
      settings: { ...state.settings, ...updates },
    })),

  setActiveTab: (tab) => set({ activeTab: tab }),
}));
