import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import type { TourSectionId, SectionProgress } from '@/components/tour/types';

interface TourState {
  /** Schema version for migration */
  storeVersion: number;
  /** Legacy flag — kept for backward compat */
  tourCompleted: boolean;
  /** Per-section progress map */
  sections: Record<string, SectionProgress>;
  /** Currently active section (ephemeral, not persisted) */
  activeSectionId: TourSectionId | null;
  /** Current step within active section (ephemeral) */
  activeStep: number;
  /** Tour Hub drawer open state (ephemeral) */
  hubOpen: boolean;
}

interface TourActions {
  openHub: () => void;
  closeHub: () => void;
  launchSection: (sectionId: TourSectionId, totalSteps: number) => void;
  setStep: (step: number) => void;
  completeActiveSection: () => void;
  pauseActiveSection: () => void;
  resetSection: (sectionId: TourSectionId) => void;
  resetAllSections: () => void;
  /** Legacy compat */
  completeTour: () => void;
  resetTour: () => void;
}

export const useTourStore = create<TourState & TourActions>()(
  persist(
    (set, get) => ({
      storeVersion: 2,
      tourCompleted: false,
      sections: {},
      activeSectionId: null,
      activeStep: 0,
      hubOpen: false,

      openHub: () => set({ hubOpen: true }),
      closeHub: () => set({ hubOpen: false }),

      launchSection: (sectionId, totalSteps) => {
        const existing = get().sections[sectionId];
        const startStep = existing && !existing.completed ? existing.currentStep : 0;
        set({
          activeSectionId: sectionId,
          activeStep: startStep,
          hubOpen: false,
          sections: {
            ...get().sections,
            [sectionId]: {
              currentStep: startStep,
              totalSteps,
              completed: false,
              lastActiveAt: new Date().toISOString(),
            },
          },
        });
      },

      setStep: (step) => {
        const { activeSectionId, sections } = get();
        if (!activeSectionId) return;
        const existing = sections[activeSectionId] || { currentStep: 0, totalSteps: 0, completed: false, lastActiveAt: null };
        set({
          activeStep: step,
          sections: {
            ...sections,
            [activeSectionId]: {
              ...existing,
              currentStep: step,
              lastActiveAt: new Date().toISOString(),
            },
          },
        });
      },

      completeActiveSection: () => {
        const { activeSectionId, sections } = get();
        if (!activeSectionId) return;
        const existing = sections[activeSectionId] || { currentStep: 0, totalSteps: 0, completed: false, lastActiveAt: null };
        set({
          activeSectionId: null,
          activeStep: 0,
          sections: {
            ...sections,
            [activeSectionId]: {
              ...existing,
              completed: true,
              lastActiveAt: new Date().toISOString(),
            },
          },
        });
      },

      pauseActiveSection: () => {
        set({ activeSectionId: null, activeStep: 0 });
      },

      resetSection: (sectionId) => {
        const { sections } = get();
        const updated = { ...sections };
        delete updated[sectionId];
        set({ sections: updated });
      },

      resetAllSections: () => {
        set({ sections: {}, tourCompleted: false });
      },

      // Legacy compat — maps to getting-started section
      completeTour: () => {
        set({
          tourCompleted: true,
          sections: {
            ...get().sections,
            'getting-started': {
              currentStep: 0,
              totalSteps: 7,
              completed: true,
              lastActiveAt: new Date().toISOString(),
            },
          },
        });
      },

      resetTour: () => {
        const { sections } = get();
        const updated = { ...sections };
        delete updated['getting-started'];
        set({ tourCompleted: false, sections: updated });
      },
    }),
    {
      name: 'cml-tour',
      version: 2,
      migrate: (persisted: unknown, version: number) => {
        if (version < 2) {
          // Old shape: { tourCompleted: boolean, tourVersion: number }
          const old = persisted as { tourCompleted?: boolean } | null;
          const wasCompleted = old?.tourCompleted === true;
          return {
            storeVersion: 2,
            tourCompleted: wasCompleted,
            sections: wasCompleted
              ? { 'getting-started': { currentStep: 0, totalSteps: 7, completed: true, lastActiveAt: null } }
              : {},
            activeSectionId: null,
            activeStep: 0,
            hubOpen: false,
          };
        }
        return persisted as TourState & TourActions;
      },
      partialize: (state) => ({
        storeVersion: state.storeVersion,
        tourCompleted: state.tourCompleted,
        sections: state.sections,
      }) as unknown as TourState & TourActions,
    }
  )
);
