<script lang="ts">
  import type { PicletGeneratorProps, PicletWorkflowState, CaptionType, CaptionLength, PicletStats } from '$lib/types';
  import type { PicletInstance } from '$lib/db/schema';
  import UploadStep from './UploadStep.svelte';
  import WorkflowProgress from './WorkflowProgress.svelte';
  import PicletResult from './PicletResult.svelte';
  import { removeBackground } from '$lib/utils/professionalImageProcessing';
  import { extractPicletMetadata } from '$lib/services/picletMetadata';
  import { savePicletInstance, monsterToPicletInstance } from '$lib/db/piclets';
  import { PicletType, TYPE_DATA } from '$lib/types/picletTypes';
  
  interface Props extends PicletGeneratorProps {}
  
  let { joyCaptionClient, zephyrClient, fluxClient, qwenClient }: Props = $props();
  
  let state: PicletWorkflowState = $state({
    currentStep: 'upload',
    userImage: null,
    imageCaption: null,
    picletConcept: null,
    picletStats: null,
    imagePrompt: null,
    picletImage: null,
    error: null,
    isProcessing: false
  });
  
  const IMAGE_GENERATION_PROMPT = (concept: string) => `Extract ONLY the visual appearance from this monster concept and describe it in one concise sentence:
"${concept}"

Focus on: colors, body shape, eyes, limbs, mouth, and key visual features. Omit backstory, abilities, and non-visual details.`;
  

  async function importPiclet(picletData: PicletInstance) {
    state.isProcessing = true;
    state.currentStep = 'complete';
    
    try {
      // Save the imported piclet
      const savedId = await savePicletInstance(picletData);
      
      // Create a success state similar to generation
      state.picletImage = {
        imageUrl: picletData.imageUrl,
        imageData: picletData.imageData,
        seed: 0,
        prompt: 'Imported piclet'
      };
      
      // Show import success
      state.isProcessing = false;
      alert(`Successfully imported ${picletData.nickname || picletData.typeId}!`);
      
      // Reset to allow another import/generation
      setTimeout(() => reset(), 2000);
    } catch (error) {
      state.error = `Failed to import piclet: ${error}`;
      state.isProcessing = false;
    }
  }

  async function handleImageSelected(file: File) {
    if (!joyCaptionClient || !fluxClient) {
      state.error = "Services not connected. Please wait...";
      return;
    }
    
    state.userImage = file;
    state.error = null;
    
    // Check if this is a piclet card with metadata
    const picletData = await extractPicletMetadata(file);
    if (picletData) {
      // Import existing piclet
      await importPiclet(picletData);
    } else {
      // Generate new piclet
      startWorkflow();
    }
  }
  
  async function startWorkflow() {
    state.isProcessing = true;
    
    try {
      // Step 1: Generate detailed object description with joy-caption
      await captionImage();
      await new Promise(resolve => setTimeout(resolve, 100)); // Small delay for state update
      
      // Step 2: Generate free-form monster concept with qwen3
      await generateConcept();
      await new Promise(resolve => setTimeout(resolve, 100)); // Small delay for state update
      
      // Step 3: Generate structured monster stats based on both caption and concept
      await generateStats();
      await new Promise(resolve => setTimeout(resolve, 100)); // Small delay for state update
      
      // Step 4: Generate image prompt with qwen3
      await generateImagePrompt();
      await new Promise(resolve => setTimeout(resolve, 100)); // Small delay for state update
      
      // Step 5: Generate monster image
      await generateMonsterImage();
      
      // Step 6: Auto-save the piclet
      await autoSavePiclet();
      
      state.currentStep = 'complete';
    } catch (err) {
      console.error('Workflow error:', err);
      
      // Check for GPU quota error
      if (err && typeof err === 'object' && 'message' in err) {
        const errorMessage = String(err.message);
        if (errorMessage.includes('exceeded your GPU quota') || errorMessage.includes('GPU quota')) {
          state.error = 'GPU quota exceeded! You need to sign in with Hugging Face for free GPU time, or upgrade to Hugging Face Pro for more quota.';
        } else {
          state.error = errorMessage;
        }
      } else if (err instanceof Error) {
        state.error = err.message;
      } else {
        state.error = 'An unknown error occurred';
      }
    } finally {
      state.isProcessing = false;
    }
  }
  
  function handleAPIError(error: any): never {
    console.error('API Error:', error);
    
    // Check if it's a GPU quota error
    if (error && typeof error === 'object' && 'message' in error) {
      const errorMessage = String(error.message);
      if (errorMessage.includes('exceeded your GPU quota') || errorMessage.includes('GPU quota')) {
        throw new Error('GPU quota exceeded! You need to sign in with Hugging Face for free GPU time, or upgrade to Hugging Face Pro for more quota.');
      }
      throw new Error(errorMessage);
    }
    
    // Check if error has a different structure (like the status object from the logs)
    if (error && typeof error === 'object' && 'type' in error && error.type === 'status') {
      const statusError = error as any;
      if (statusError.message && statusError.message.includes('GPU quota')) {
        throw new Error('GPU quota exceeded! You need to sign in with Hugging Face for free GPU time, or upgrade to Hugging Face Pro for more quota.');
      }
      throw new Error(statusError.message || 'API request failed');
    }
    
    throw error;
  }
  
  async function captionImage() {
    state.currentStep = 'captioning';
    
    if (!joyCaptionClient || !state.userImage) {
      throw new Error('Caption service not available or no image provided');
    }
    
    try {
      const output = await joyCaptionClient.predict("/stream_chat", [
        state.userImage,  // input_image
        "Descriptive",  // caption_type
        "long",  // caption_length
        [],  // extra_options
        "",  // name_input
        ""  // custom_prompt (empty for default descriptive captioning)
      ]);
      
      const [, caption] = output.data;
      // Store the detailed object description
      state.imageCaption = caption;
      console.log('Detailed object description generated:', caption);
    } catch (error) {
      handleAPIError(error);
    }
  }
  
  async function generateConcept() {
    state.currentStep = 'conceptualizing';
    
    if (!qwenClient || !state.imageCaption) {
      throw new Error('Qwen service not available or no image caption provided');
    }
    
    const conceptPrompt = `Based on this detailed object description, create a Pokémon-style monster that transforms the object into an imaginative creature. The monster should clearly be inspired by the object's appearance but reimagined as a living monster.

Object description: "${state.imageCaption}"

Guidelines:
- Take the object's key visual elements (colors, shapes, materials) incorporating all of them into a single creature design
- Add eyes (can be glowing, mechanical, multiple, etc.) positioned where they make sense
- Include limbs (legs, arms, wings, tentacles) that grow from or replace parts of the object
- Add a mouth, beak, or feeding apparatus if appropriate
- Add creature elements like tail, fins, claws, horns, etc where fitting

Format your response exactly as follows:

# Object Rarity
{Assess how rare the object is based on real-world availability and value. Rare objects give strong monsters while common objects give weak ones. Use: common, uncommon, rare, or legendary}

# Monster Name
{Creative name that hints at the original object}

## Monster Visual Description
{Detailed physical description showing how the object becomes a creature. Ensure the creature uses all the unique attributes of the object. Include colors, shapes, materials, eyes, limbs, mouth, and distinctive features. This section should be comprehensive as it will be used for both stats generation and image creation.}`;
    
    try {
      // Create the required state structure based on qwen.html
      const defaultState = {
        "conversation_contexts": {},
        "conversations": [],
        "conversation_id": "",
      };
      
      // Create default settings based on qwen.html with max thinking tokens
      const defaultSettings = {
        "model": "qwen3-235b-a22b",
        "sys_prompt": "You are a creative monster designer specializing in transforming everyday objects into imaginative Pokémon-style creatures. Follow the exact format provided and create detailed, engaging descriptions that bring these monsters to life.",
        "thinking_budget": 38
      };
      
      // Create thinking button state
      const thinkingBtnState = {
        "enable_thinking": true
      };
      
      console.log('Generating monster concept with qwen3...');
      
      // Call the add_message function (fn_index 13)
      const output = await qwenClient.predict(13, [
        conceptPrompt,          // input_value
        defaultSettings,        // settings_form_value  
        thinkingBtnState,       // thinking_btn_state_value
        defaultState            // state_value
      ]);
      
      console.log('Qwen3 concept response:', output);
      
      // Extract the response text from the output
      let responseText = "";
      if (output && output.data && Array.isArray(output.data)) {
        // The chatbot response is at index 5 in the outputs array
        const chatbotUpdate = output.data[5];
        
        if (chatbotUpdate && chatbotUpdate.value && Array.isArray(chatbotUpdate.value)) {
          const chatHistory = chatbotUpdate.value;
          
          if (chatHistory.length > 0) {
            // Get the last message (assistant's response)
            const lastMessage = chatHistory[chatHistory.length - 1];
            
            if (lastMessage && lastMessage.content && Array.isArray(lastMessage.content)) {
              // Extract text content from the message
              const textContents = lastMessage.content
                .filter((item: any) => item.type === "text")
                .map((item: any) => item.content)
                .join("\n");
              responseText = textContents || "Response received but no text content found";
            } else if (lastMessage && lastMessage.role === "assistant") {
              // Fallback - if content structure is different
              responseText = JSON.stringify(lastMessage, null, 2);
            }
          }
        }
      }
      
      if (!responseText || responseText.trim() === '') {
        throw new Error('Failed to generate monster concept');
      }
      
      state.picletConcept = responseText;
      console.log('Monster concept generated:', responseText);
    } catch (error) {
      handleAPIError(error);
    }
  }
  
  async function generateImagePrompt() {
    state.currentStep = 'promptCrafting';
    
    if (!qwenClient || !state.picletConcept || !state.imageCaption) {
      throw new Error('Qwen service not available or no concept/caption available for prompt generation');
    }
    
    // Extract the Monster Visual Description from the structured concept
    const visualDescMatch = state.picletConcept.match(/## Monster Visual Description\s*\n([\s\S]*?)(?=##|$)/);
    
    if (visualDescMatch && visualDescMatch[1]) {
      state.imagePrompt = visualDescMatch[1].trim();
      console.log('Extracted visual description for image generation:', state.imagePrompt);
      return; // Skip qwen3 call since we have the description
    }
    
    // Fallback: if format parsing fails, use qwen3 to extract visual description
    const imagePromptPrompt = `Based on this monster concept, extract ONLY the visual description for image generation:

MONSTER CONCEPT:
"""
${state.picletConcept}
"""

Create a concise visual description (1-3 sentences, max 100 words). Focus only on colors, shapes, materials, eyes, limbs, mouth, and distinctive features. Omit all non-visual information like abilities and backstory.`;
    
    try {
      // Create the required state structure based on qwen.html
      const defaultState = {
        "conversation_contexts": {},
        "conversations": [],
        "conversation_id": "",
      };
      
      // Create default settings based on qwen.html
      const defaultSettings = {
        "model": "qwen3-235b-a22b",
        "sys_prompt": "You are an expert at creating concise visual descriptions for image generation. Extract ONLY visual appearance details and describe them in 1-2 sentences (max 50 words). Focus on colors, shape, eyes, limbs, and distinctive features. Omit all non-visual information like abilities, personality, or backstory.",
        "thinking_budget": 38
      };
      
      // Create thinking button state
      const thinkingBtnState = {
        "enable_thinking": true
      };
      
      console.log('Generating image prompt with qwen3...');
      
      // Call the add_message function (fn_index 13)
      const output = await qwenClient.predict(13, [
        imagePromptPrompt,      // input_value
        defaultSettings,        // settings_form_value  
        thinkingBtnState,       // thinking_btn_state_value
        defaultState            // state_value
      ]);
      
      console.log('Qwen3 image prompt response:', output);
      
      // Extract the response text from the output using the same pattern as generateConcept
      let responseText = "";
      if (output && output.data && Array.isArray(output.data)) {
        // The chatbot response is at index 5 in the outputs array
        const chatbotUpdate = output.data[5];
        
        if (chatbotUpdate && chatbotUpdate.value && Array.isArray(chatbotUpdate.value)) {
          const chatHistory = chatbotUpdate.value;
          
          if (chatHistory.length > 0) {
            // Get the last message (assistant's response)
            const lastMessage = chatHistory[chatHistory.length - 1];
            
            if (lastMessage && lastMessage.content && Array.isArray(lastMessage.content)) {
              // Extract text content from the message
              const textContents = lastMessage.content
                .filter((item: any) => item.type === "text")
                .map((item: any) => item.content)
                .join("\n");
              responseText = textContents || "Response received but no text content found";
            } else if (lastMessage && lastMessage.role === "assistant") {
              // Fallback - if content structure is different
              responseText = JSON.stringify(lastMessage, null, 2);
            }
          }
        }
      }
      
      if (!responseText || responseText.trim() === '') {
        throw new Error('Failed to generate image prompt');
      }
      
      state.imagePrompt = responseText.trim();
      console.log('Image prompt generated:', state.imagePrompt);
    } catch (error) {
      handleAPIError(error);
    }
  }
  
  async function generateMonsterImage() {
    state.currentStep = 'generating';
    
    if (!fluxClient || !state.imagePrompt || !state.picletStats) {
      throw new Error('Image generation service not available or no prompt/stats');
    }
    
    // The image prompt should already be generated by generateImagePrompt() in the workflow
    
    // Get tier for image quality enhancement
    const tier = state.picletStats.tier || 'medium';
    const tierDescriptions = {
      low: 'simple and basic design',
      medium: 'detailed and well-crafted design', 
      high: 'highly detailed and impressive design with special effects',
      legendary: 'extremely detailed and majestic design with dramatic lighting and aura effects'
    };
    
    try {
      const output = await fluxClient.predict("/infer", [
        `${state.imagePrompt}\nNow generate a Pokémon-Anime-style image of the monster in an idle pose with a white background. This is a ${tier} tier monster with ${tierDescriptions[tier as keyof typeof tierDescriptions]}. The monster should not be attacking or in motion. The full monster must be visible within the frame.`,
        0,      // seed
        true,   // randomizeSeed
        1024,   // width
        1024,   // height
        4       // steps
      ]);
      
      const [image, usedSeed] = output.data;
      let url: string | undefined;
      
      if (typeof image === "string") url = image;
      else if (image && image.url) url = image.url;
      else if (image && image.path) url = image.path;
      
      if (url) {
        // Process the image to remove background using professional AI method
        console.log('Processing image for background removal...');
        try {
          const transparentBase64 = await removeBackground(url);
          state.picletImage = {
            imageUrl: url,
            imageData: transparentBase64,
            seed: usedSeed,
            prompt: state.imagePrompt
          };
          console.log('Background removal completed successfully');
        } catch (processError) {
          console.error('Failed to process image for background removal:', processError);
          // Fallback to original image
          state.picletImage = {
            imageUrl: url,
            seed: usedSeed,
            prompt: state.imagePrompt
          };
        }
      } else {
        throw new Error('Failed to generate monster image');
      }
    } catch (error) {
      handleAPIError(error);
    }
  }
  
  async function generateStats() {
    state.currentStep = 'statsGenerating';
    
    if (!qwenClient || !state.picletConcept || !state.imageCaption) {
      throw new Error('Qwen service not available or no concept/caption available for stats generation');
    }
    
    // Default tier (will be set from the generated stats)
    let tier: 'low' | 'medium' | 'high' | 'legendary' = 'medium';
    
    // Extract monster name and rarity from the structured concept
    const monsterNameMatch = state.picletConcept.match(/# Monster Name\s*\n([\s\S]*?)(?=^##|$)/m);
    const monsterName = monsterNameMatch ? monsterNameMatch[1].trim() : 'Unknown Monster';
    
    const rarityMatch = state.picletConcept.match(/# Object Rarity\s*\n([\s\S]*?)(?=^#)/m);
    const objectRarity = rarityMatch ? rarityMatch[1].trim().toLowerCase() : 'common';
    
    // Create stats prompt using both the detailed object description and monster concept
    const statsPrompt = `Based on this detailed object description and monster concept, generate a JSON object with battle stats and abilities:

ORIGINAL OBJECT DESCRIPTION:
"${state.imageCaption}"

MONSTER CONCEPT:
"${state.picletConcept}"

The object rarity has been assessed as: ${objectRarity}

Use this rarity level to determine appropriate stats:

Next, determine the monster's type based on its concept and appearance. Choose the most appropriate type from these options:
• BEAST: Vertebrate wildlife — mammals, birds, reptiles. Raw physicality, instincts, region-based variants.
• BUG: Arthropods — butterflies, beetles, mantises. Agile swarms, precision strikes, metamorph evolutions.
• AQUATIC: Life that swims, dives, sloshes, seeps — fish, octopus, sentient puddles. Tides, mist, pressure.
• FLORA: Plants and fungi — blooming or decaying. Growth, spores, vines, seasonal shifts.
• MINERAL: Stones, crystals, metals — earth's depths. Durability, reflective armor, seismic shocks.
• SPACE: Stars, moon, cosmic objects — not of this world. Celestial energy and cosmic forces.
• MACHINA: Engineered devices — gadgets to machinery. Gears, circuits, drones, power surges.
• STRUCTURE: Buildings, bridges, monuments — architectural titans. Fortification, terrain shaping.
• CULTURE: Art, fashion, toys, symbols — creative expressions. Buffs, debuffs, illusion, stories.
• CUISINE: Dishes, drinks, culinary art — flavors and aromas. Temperature, restorative, spicy offense.

The output should be formatted as a JSON instance that conforms to the JSON schema below.

\`\`\`json
{
  "properties": {
    "name": {"type": "string", "description": "Creative name for the monster that hints at the original object"},
    "rarity": {"type": "string", "enum": ["common", "uncommon", "rare", "legendary"], "description": "Rarity of the original object based on real-world availability and value"},
    "picletType": {"type": "string", "enum": ["beast", "bug", "aquatic", "flora", "mineral", "space", "machina", "structure", "culture", "cuisine"], "description": "The type that best matches this monster's concept, appearance, and nature"},
    "height": {"type": "number", "minimum": 0.1, "maximum": 50.0, "description": "Height of the piclet in meters (e.g., 1.2, 0.5, 10.0)"},
    "weight": {"type": "number", "minimum": 0.1, "maximum": 10000.0, "description": "Weight of the piclet in kilograms (e.g., 25.4, 150.0, 0.8)"},
    "HP": {"type": "integer", "minimum": 0, "maximum": 100, "description": "Health/vitality stat (0=fragile, 100=incredibly tanky)"},
    "defence": {"type": "integer", "minimum": 0, "maximum": 100, "description": "Defensive/armor stat (0=paper thin, 100=impenetrable fortress)"},
    "attack": {"type": "integer", "minimum": 0, "maximum": 100, "description": "Physical attack power (0=harmless, 100=devastating force)"},
    "speed": {"type": "integer", "minimum": 0, "maximum": 100, "description": "Movement and reaction speed (0=immobile, 100=lightning fast)"},
    "monsterLore": {"type": "string", "description": "Write a background story for this monster including its personality, habitat, behavior, and lore (2-3 sentences)"},
    "specialPassiveTraitDescription": {"type": "string", "description": "Describe a passive ability that gives this monster a unique advantage in battle"},
    "attackActionName": {"type": "string", "description": "Name of the monster's primary damage-dealing attack (e.g., 'Flame Burst', 'Toxic Bite')"},
    "attackActionDescription": {"type": "string", "description": "Describe how this attack damages the opponent and any special effects"},
    "buffActionName": {"type": "string", "description": "Name of the monster's self-enhancement ability (e.g., 'Iron Defense', 'Speed Boost')"},
    "buffActionDescription": {"type": "string", "description": "Describe which stats are boosted and how this improves the monster's battle performance"},
    "debuffActionName": {"type": "string", "description": "Name of the monster's enemy-weakening ability (e.g., 'Intimidate', 'Slow Poison')"},
    "debuffActionDescription": {"type": "string", "description": "Describe which enemy stats are lowered and how this weakens the opponent"},
    "specialActionName": {"type": "string", "description": "Name of the monster's ultimate move (one use per battle)"},
    "specialActionDescription": {"type": "string", "description": "Describe this powerful finishing move and its dramatic effects in battle"}
  },
  "required": ["name", "rarity", "picletType", "height", "weight", "HP", "defence", "attack", "speed", "monsterLore", "specialPassiveTraitDescription", "attackActionName", "attackActionDescription", "buffActionName", "buffActionDescription", "debuffActionName", "debuffActionDescription", "specialActionName", "specialActionDescription"]
}
\`\`\`

Base the HP, defence, attack, and speed stats on the rarity level:
- common: stats should be 10-40
- uncommon: stats should be 30-60
- rare: stats should be 50-80
- legendary: stats should be 70-100

Write your response within \`\`\`json\`\`\``;
    
    console.log('Generating monster stats with qwen3');
    
    try {
      // Create the required state structure based on qwen.html
      const defaultState = {
        "conversation_contexts": {},
        "conversations": [],
        "conversation_id": "",
      };
      
      // Create default settings based on qwen.html
      const defaultSettings = {
        "model": "qwen3-235b-a22b",
        "sys_prompt": "You are a game designer specializing in monster stats and abilities. You must ONLY output valid JSON that matches the provided schema exactly. Do not include any text before or after the JSON. Do not include null values in your JSON response. Your entire response should be wrapped in a ```json``` code block.",
        "thinking_budget": 38
      };
      
      // Create thinking button state
      const thinkingBtnState = {
        "enable_thinking": true
      };
      
      // Call the add_message function (fn_index 13)
      const output = await qwenClient.predict(13, [
        statsPrompt,            // input_value
        defaultSettings,        // settings_form_value  
        thinkingBtnState,       // thinking_btn_state_value
        defaultState            // state_value
      ]);
      
      console.log('Qwen3 stats response:', output);
      
      // Extract the response text from the output using the same pattern as generateConcept
      let responseText = "";
      if (output && output.data && Array.isArray(output.data)) {
        // The chatbot response is at index 5 in the outputs array
        const chatbotUpdate = output.data[5];
        
        if (chatbotUpdate && chatbotUpdate.value && Array.isArray(chatbotUpdate.value)) {
          const chatHistory = chatbotUpdate.value;
          
          if (chatHistory.length > 0) {
            // Get the last message (assistant's response)
            const lastMessage = chatHistory[chatHistory.length - 1];
            
            if (lastMessage && lastMessage.content && Array.isArray(lastMessage.content)) {
              // Extract text content from the message
              const textContents = lastMessage.content
                .filter((item: any) => item.type === "text")
                .map((item: any) => item.content)
                .join("\n");
              responseText = textContents || "Response received but no text content found";
            } else if (lastMessage && lastMessage.role === "assistant") {
              // Fallback - if content structure is different
              responseText = JSON.stringify(lastMessage, null, 2);
            }
          }
        }
      }
      
      if (!responseText || responseText.trim() === '') {
        throw new Error('Failed to generate monster stats');
      }
      
      console.log('Stats output:', responseText);
      let jsonString = responseText;
      
      // Extract JSON from the response (remove markdown if present)
      let cleanJson = jsonString;
      if (jsonString.includes('```')) {
        const matches = jsonString.match(/```(?:json)?\s*([\s\S]*?)```/);
        if (matches) {
          cleanJson = matches[1];
        } else {
          // If no closing ```, just remove the opening ```json
          cleanJson = jsonString.replace(/^```(?:json)?\s*/, '').replace(/```\s*$/, '');
        }
      }
      
      try {
        // Remove any trailing text after the JSON object
        const jsonMatch = cleanJson.match(/^\s*\{[\s\S]*?\}\s*/);
        if (jsonMatch) {
          cleanJson = jsonMatch[0];
        }
        
        const parsedStats = JSON.parse(cleanJson.trim());
        
        // Remove any extra fields not in our schema
        const allowedFields = ['name', 'rarity', 'picletType', 'height', 'weight', 'HP', 'defence', 'attack', 'speed',
          'monsterLore', 'specialPassiveTraitDescription', 'attackActionName', 'attackActionDescription',
          'buffActionName', 'buffActionDescription', 'debuffActionName', 'debuffActionDescription',
          'specialActionName', 'specialActionDescription', 'boostActionName', 'boostActionDescription',
          'disparageActionName', 'disparageActionDescription'];
        
        for (const key in parsedStats) {
          if (!allowedFields.includes(key)) {
            delete parsedStats[key];
          }
        }
        
        // Map rarity to tier
        if (parsedStats.rarity) {
          const tierMap: { [key: string]: 'low' | 'medium' | 'high' | 'legendary' } = {
            'common': 'low',
            'uncommon': 'medium',
            'rare': 'high',
            'legendary': 'legendary'
          };
          tier = tierMap[parsedStats.rarity.toLowerCase()] || 'medium';
        }
        
        // Add the description and tier that we extracted/mapped
        // Use the name from the structured concept, or fall back to JSON response
        if (!parsedStats.name) {
          parsedStats.name = monsterName;
        }
        parsedStats.description = parsedStats.monsterLore || 'A mysterious creature with unknown origins.';
        parsedStats.tier = tier;
        
        // Ensure numeric fields are actually numbers
        const numericFields = ['HP', 'defence', 'attack', 'speed'];
        
        for (const field of numericFields) {
          if (parsedStats[field] !== undefined) {
            // Convert string numbers to actual numbers
            parsedStats[field] = parseInt(parsedStats[field]);
            
            // Clamp to 0-100 range
            parsedStats[field] = Math.max(0, Math.min(100, parsedStats[field]));
          }
        }
        
        // Map field names from schema to interface
        if (parsedStats.specialPassiveTraitDescription) {
          parsedStats.specialPassiveTrait = parsedStats.specialPassiveTraitDescription;
          delete parsedStats.specialPassiveTraitDescription;
        }
        
        // Handle potential old field names from LLM
        if (parsedStats.boostActionName) {
          parsedStats.buffActionName = parsedStats.boostActionName;
          delete parsedStats.boostActionName;
        }
        if (parsedStats.boostActionDescription) {
          parsedStats.buffActionDescription = parsedStats.boostActionDescription;
          delete parsedStats.boostActionDescription;
        }
        if (parsedStats.disparageActionName) {
          parsedStats.debuffActionName = parsedStats.disparageActionName;
          delete parsedStats.disparageActionName;
        }
        if (parsedStats.disparageActionDescription) {
          parsedStats.debuffActionDescription = parsedStats.disparageActionDescription;
          delete parsedStats.disparageActionDescription;
        }
        
        const stats: PicletStats = parsedStats;
        state.picletStats = stats;
        console.log('Monster stats generated:', stats);
        console.log('Monster stats JSON:', JSON.stringify(stats, null, 2));
      } catch (parseError) {
        console.error('Failed to parse JSON:', parseError, 'Raw output:', cleanJson);
        throw new Error('Failed to parse monster stats JSON');
      }
    } catch (error) {
      handleAPIError(error);
    }
  }
  
  async function autoSavePiclet() {
    if (!state.picletImage || !state.imageCaption || !state.picletConcept || !state.imagePrompt || !state.picletStats) {
      console.error('Cannot auto-save: missing required data');
      return;
    }
    
    try {
      // Create a clean copy of stats to ensure it's serializable
      const cleanStats = JSON.parse(JSON.stringify(state.picletStats));
      
      const picletData = {
        name: state.picletStats.name,
        imageUrl: state.picletImage.imageUrl,
        imageData: state.picletImage.imageData,
        imageCaption: state.imageCaption,
        concept: state.picletConcept,
        imagePrompt: state.imagePrompt,
        stats: cleanStats,
        createdAt: new Date()
      };
      
      // Check for any non-serializable data
      console.log('Checking piclet data for serializability:');
      console.log('- name type:', typeof picletData.name);
      console.log('- imageUrl type:', typeof picletData.imageUrl);
      console.log('- imageData type:', typeof picletData.imageData, picletData.imageData ? `length: ${picletData.imageData.length}` : 'null/undefined');
      console.log('- imageCaption type:', typeof picletData.imageCaption);
      console.log('- concept type:', typeof picletData.concept);
      console.log('- imagePrompt type:', typeof picletData.imagePrompt);
      console.log('- stats:', cleanStats);
      
      // Convert to PicletInstance format and save
      const picletInstance = await monsterToPicletInstance(picletData);
      const id = await savePicletInstance(picletInstance);
      console.log('Piclet auto-saved with ID:', id);
    } catch (err) {
      console.error('Failed to auto-save piclet:', err);
      console.error('Piclet data that failed to save:', {
        name: state.picletStats?.name,
        hasImageUrl: !!state.picletImage?.imageUrl,
        hasImageData: !!state.picletImage?.imageData,
        hasStats: !!state.picletStats
      });
      // Don't throw - we don't want to interrupt the workflow
    }
  }
  
  function reset() {
    state = {
      currentStep: 'upload',
      userImage: null,
      imageCaption: null,
      picletConcept: null,
      picletStats: null,
      imagePrompt: null,
      picletImage: null,
      error: null,
      isProcessing: false
    };
  }
</script>

<div class="piclet-generator">
  
  {#if state.currentStep !== 'upload'}
    <WorkflowProgress currentStep={state.currentStep} error={state.error} />
  {/if}
  
  {#if state.currentStep === 'upload'}
    <UploadStep 
      onImageSelected={handleImageSelected}
      isProcessing={state.isProcessing}
    />
  {:else if state.currentStep === 'complete'}
    <PicletResult workflowState={state} onReset={reset} />
  {:else}
    <div class="processing-container">
      <div class="spinner"></div>
      <p class="processing-text">
        {#if state.currentStep === 'captioning'}
          Analyzing your image...
        {:else if state.currentStep === 'conceptualizing'}
          Creating monster concept...
        {:else if state.currentStep === 'statsGenerating'}
          Generating battle stats...
        {:else if state.currentStep === 'promptCrafting'}
          Creating image prompt...
        {:else if state.currentStep === 'generating'}
          Generating your Piclet...
        {/if}
      </p>
    </div>
  {/if}
</div>

<style>
  .piclet-generator {
    width: 100%;
    max-width: 1200px;
    margin: 0 auto;
    padding: 2rem;
  }
  
  
  .processing-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 3rem 1rem;
  }
  
  .spinner {
    width: 60px;
    height: 60px;
    border: 3px solid #f3f3f3;
    border-top: 3px solid #007bff;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 2rem;
  }
  
  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }
  
  .processing-text {
    font-size: 1.2rem;
    color: #333;
    margin-bottom: 2rem;
  }
  
</style>