/**
 * Comic Store - Zustand State Management
 * 
 * Global state for the entire comic project with localStorage persistence
 */

import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import type { 
  ComicStore, 
  UserMode, 
  ComicScript, 
  Character, 
  PanelImage, 
  PageLayout, 
  SpeechBubble,
  WorkflowStep,
  ExportFormat,
  PageSizeName,
  ColorProfile
} from '@/types';

const generateProjectId = (): string => {
  return `proj_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
};

const initialState = {
  project: {
    projectId: generateProjectId(),
    projectName: 'Untitled Comic',
    createdAt: new Date().toISOString(),
    lastModified: new Date().toISOString(),
  },
  userMode: 'casual' as UserMode,
  storyIdea: '',
  storyGenre: 'action',
  targetAudience: 'general',
  artStyle: 'manga',
  script: null as ComicScript | null,
  characters: [] as Character[],
  panelImages: {} as Record<string, PanelImage>,
  characterRefImages: {} as Record<string, string>,
  pageLayouts: [] as PageLayout[],
  speechBubbles: {} as Record<string, SpeechBubble[]>,
  exportFormat: 'pdf' as ExportFormat,
  pageSize: 'a4' as PageSizeName,
  colorProfile: 'rgb' as ColorProfile,
  workflow: {
    currentStep: 'story-input' as WorkflowStep,
    completedSteps: [] as WorkflowStep[],
    isGenerating: false,
    generationProgress: 0,
    error: null as string | null,
  },
};

export const useComicStore = create<ComicStore>()(
  persist(
    (set) => ({
      ...initialState,

      // ─── Actions ───
      setUserMode: (mode: UserMode) => {
        set((state) => ({
          userMode: mode,
          project: { ...state.project, lastModified: new Date().toISOString() },
        }));
      },

      setStoryIdea: (idea: string) => {
        set((state) => ({
          storyIdea: idea,
          project: { ...state.project, lastModified: new Date().toISOString() },
        }));
      },

      setStoryGenre: (genre: string) => {
        set((state) => ({
          storyGenre: genre,
          project: { ...state.project, lastModified: new Date().toISOString() },
        }));
      },

      setTargetAudience: (audience: string) => {
        set((state) => ({
          targetAudience: audience,
          project: { ...state.project, lastModified: new Date().toISOString() },
        }));
      },

      setArtStyle: (style: string) => {
        set((state) => ({
          artStyle: style,
          project: { ...state.project, lastModified: new Date().toISOString() },
        }));
      },

      setScript: (script: ComicScript | null) => {
        set((state) => ({
          script,
          project: { ...state.project, lastModified: new Date().toISOString() },
          workflow: {
            ...state.workflow,
            currentStep: script ? 'character-setup' : 'story-input',
            completedSteps: script 
              ? [...state.workflow.completedSteps, 'story-input', 'generating-script']
              : state.workflow.completedSteps,
          },
        }));
      },

      setCharacters: (characters: Character[]) => {
        set((state) => ({
          characters,
          project: { ...state.project, lastModified: new Date().toISOString() },
        }));
      },

      setPanelImage: (panelId: string, image: PanelImage) => {
        set((state) => ({
          panelImages: { ...state.panelImages, [panelId]: image },
          project: { ...state.project, lastModified: new Date().toISOString() },
        }));
      },

      setCharacterRefImage: (characterId: string, url: string) => {
        set((state) => ({
          characterRefImages: { ...state.characterRefImages, [characterId]: url },
          characters: state.characters.map(c => 
            c.id === characterId ? { ...c, referenceImageUrl: url } : c
          ),
          project: { ...state.project, lastModified: new Date().toISOString() },
        }));
      },

      setPageLayouts: (layouts: PageLayout[]) => {
        set((state) => ({
          pageLayouts: layouts,
          project: { ...state.project, lastModified: new Date().toISOString() },
          workflow: {
            ...state.workflow,
            currentStep: layouts.length > 0 ? 'speech-bubbles' : 'layout',
            completedSteps: layouts.length > 0 
              ? [...state.workflow.completedSteps, 'layout']
              : state.workflow.completedSteps,
          },
        }));
      },

      setSpeechBubbles: (panelId: string, bubbles: SpeechBubble[]) => {
        set((state) => ({
          speechBubbles: { ...state.speechBubbles, [panelId]: bubbles },
          project: { ...state.project, lastModified: new Date().toISOString() },
        }));
      },

      setExportFormat: (format: ExportFormat) => {
        set({ exportFormat: format });
      },

      setPageSize: (size: PageSizeName) => {
        set({ pageSize: size });
      },

      setWorkflowStep: (step: WorkflowStep) => {
        set((state) => ({
          workflow: {
            ...state.workflow,
            currentStep: step,
            completedSteps: state.workflow.completedSteps.includes(step)
              ? state.workflow.completedSteps
              : [...state.workflow.completedSteps, step],
          },
        }));
      },

      setWorkflowError: (error: string | null) => {
        set((state) => ({
          workflow: { ...state.workflow, error, isGenerating: false },
        }));
      },

      setGenerationProgress: (progress: number) => {
        set((state) => ({
          workflow: { ...state.workflow, generationProgress: progress },
        }));
      },

      resetProject: () => {
        set({
          ...initialState,
          project: {
            projectId: generateProjectId(),
            projectName: 'Untitled Comic',
            createdAt: new Date().toISOString(),
            lastModified: new Date().toISOString(),
          },
        });
      },
    }),
    {
      name: 'comic-creator-storage',
      partialize: (state) => ({
        project: state.project,
        userMode: state.userMode,
        storyIdea: state.storyIdea,
        storyGenre: state.storyGenre,
        targetAudience: state.targetAudience,
        artStyle: state.artStyle,
        script: state.script,
        characters: state.characters,
        panelImages: state.panelImages,
        characterRefImages: state.characterRefImages,
        pageLayouts: state.pageLayouts,
        speechBubbles: state.speechBubbles,
        exportFormat: state.exportFormat,
        pageSize: state.pageSize,
        colorProfile: state.colorProfile,
        workflow: {
          currentStep: state.workflow.currentStep,
          completedSteps: state.workflow.completedSteps,
          error: state.workflow.error,
        },
      }),
    }
  )
);
