import { create } from 'zustand';
import { persist } from 'zustand/middleware';

// ── Layout constants (shared with panel components) ─────────────────
export const FAB_LEFT = 24;
export const FAB_SIZE = 48;
export const PANEL_GAP = 8;
export const PANEL_EXPANDED_WIDTH = 340;
export const PANEL_EXPANDED_HEIGHT = 480;
export const PANEL_MINIMIZED_WIDTH = 160;
export const PANEL_TITLE_HEIGHT = 44;
export const MAX_PANELS = 3;

export const CHANNELS = [
  { value: 'general', label: 'General' },
  { value: 'shifts', label: 'Shifts' },
  { value: 'canvassing', label: 'Canvassing' },
  { value: 'campaigns', label: 'Campaigns' },
] as const;

// ── Types ───────────────────────────────────────────────────────────
export interface ChatPanel {
  id: string;
  channel: string;
  isMinimized: boolean;
}

interface ChatWidgetState {
  panels: ChatPanel[];
  pickerOpen: boolean;

  // Transient runtime state (fetched once per session, shared by all panels)
  rcServiceUrl: string | null;
  rcAuthToken: string | null;
  rcEnabled: boolean | null;
  rcOnline: boolean | null;
}

interface ChatWidgetActions {
  openChannel: (channel: string) => void;
  closePanel: (id: string) => void;
  minimizePanel: (id: string) => void;
  expandPanel: (id: string) => void;
  closeAll: () => void;
  togglePicker: () => void;
  closePicker: () => void;
  setRCState: (data: {
    serviceUrl: string;
    authToken: string;
    enabled: boolean;
    online: boolean;
  }) => void;
  clearRCState: () => void;
}

// ── V1 → V2 migration helper ───────────────────────────────────────
interface V1Persisted {
  isOpen?: boolean;
  isMinimized?: boolean;
  activeChannel?: string;
}

function migrateV1(stored: V1Persisted): { panels: ChatPanel[] } {
  if ('isOpen' in stored && stored.isOpen && stored.activeChannel) {
    return {
      panels: [
        {
          id: `panel-${stored.activeChannel}`,
          channel: stored.activeChannel,
          isMinimized: stored.isMinimized ?? false,
        },
      ],
    };
  }
  return { panels: [] };
}

// ── Store ───────────────────────────────────────────────────────────
export const useChatWidgetStore = create<ChatWidgetState & ChatWidgetActions>()(
  persist(
    (set, get) => ({
      panels: [],
      pickerOpen: false,

      rcServiceUrl: null,
      rcAuthToken: null,
      rcEnabled: null,
      rcOnline: null,

      openChannel: (channel) => {
        const { panels } = get();
        const existing = panels.find((p) => p.channel === channel);
        if (existing) {
          // Already open — expand it
          set({
            panels: panels.map((p) =>
              p.id === existing.id ? { ...p, isMinimized: false } : p,
            ),
          });
          return;
        }
        if (panels.length >= MAX_PANELS) return;
        set({
          panels: [
            ...panels,
            { id: `panel-${channel}`, channel, isMinimized: false },
          ],
        });
      },

      closePanel: (id) =>
        set({ panels: get().panels.filter((p) => p.id !== id) }),

      minimizePanel: (id) =>
        set({
          panels: get().panels.map((p) =>
            p.id === id ? { ...p, isMinimized: true } : p,
          ),
        }),

      expandPanel: (id) =>
        set({
          panels: get().panels.map((p) =>
            p.id === id ? { ...p, isMinimized: false } : p,
          ),
        }),

      closeAll: () => set({ panels: [] }),

      togglePicker: () => set({ pickerOpen: !get().pickerOpen }),
      closePicker: () => set({ pickerOpen: false }),

      setRCState: ({ serviceUrl, authToken, enabled, online }) =>
        set({
          rcServiceUrl: serviceUrl,
          rcAuthToken: authToken,
          rcEnabled: enabled,
          rcOnline: online,
        }),

      clearRCState: () =>
        set({
          rcServiceUrl: null,
          rcAuthToken: null,
          rcEnabled: null,
          rcOnline: null,
        }),
    }),
    {
      name: 'cml-chat-widget',
      version: 2,
      partialize: (state) => ({
        panels: state.panels,
      }),
      migrate: (persisted, version) => {
        if (version < 2) {
          const migrated = migrateV1(persisted as V1Persisted);
          return { panels: migrated.panels } as ChatWidgetState & ChatWidgetActions;
        }
        return persisted as ChatWidgetState & ChatWidgetActions;
      },
    },
  ),
);
