// First check if we've already loaded the ghost code to avoid duplicates
if (typeof window.ghostInitialized === 'undefined') {
  // Mark as initialized
  window.ghostInitialized = true;
  
  // Store these in window so they're globally accessible
  window.conversationHistory = [];
  window.apiKey = 'api-key-here';
  
  // Function to attempt to fix non-JSON responses
  window.fixResponse = function(response) {
      // If response is already valid JSON, return it
      try {
          JSON.parse(response);
          return response;
      } catch (e) {
          // If it's a plain message, wrap it in proper JSON structure
          if (typeof response === 'string') {
              console.log('Attempting to fix invalid response format');
              // Check for indicators of mood in the message
              const isAngry = response.toLowerCase().includes('angry') || 
                            response.toLowerCase().includes('upset') ||
                            response.toLowerCase().includes('how dare') ||
                            response.toLowerCase().includes('frustrated');
              const isHappy = response.toLowerCase().includes('happy') ||
                            response.toLowerCase().includes('better') ||
                            response.toLowerCase().includes('thank you') ||
                            response.toLowerCase().includes('glad');
              
              const mood = isAngry ? 'angry' : (isHappy ? 'happy' : 'sad');
              const action = isAngry ? 'thunder' : 'none';
              
              return JSON.stringify({
                  action: action,
                  message: response,
                  mood: mood
              });
          }
      }
      return null;
  };
  
  // Define ghost functions globally
  window.sendToGhost = async function(userMessage) {
      try {
          const response = await fetch('https://api.openai.com/v1/chat/completions', {
              method: 'POST',
              headers: {
                  'Content-Type': 'application/json',
                  'Authorization': `Bearer ${window.apiKey}`
              },
              body: JSON.stringify({
                  model: 'gpt-4o',
                  messages: [
                      { 
                          role: 'system', 
                          content: `IMPORTANT FORMATTING INSTRUCTION: You must respond with ONLY a JSON object in this exact format:
                          {"action":"none|thunder|lights|unlock","message":"Your message here","mood":"happy|sad|angry"}
                          
                          The action MUST be one of these four options:
                          - "none" (for normal responses)
                          - "thunder" (when upset) - Use *thunder booms* in message only with this action
                          - "lights" (when very upset) - Use *lights flicker* in message only with this action
                          - "unlock" (for resolution) - Use *door creaks open* in message only with this action

                          IMPORTANT: Only use asterisk descriptions (*) when they match the actual action being taken:
                          - For "thunder" action: *thunder booms*
                          - For "lights" action: *lights flicker*
                          - For "unlock" action: *door creaks open*
                          Do not include other narrative descriptions in asterisks. Express mood and atmosphere through dialogue instead.

                          The mood MUST be one of these three options:
                          - "happy" (when feeling understood or positive)
                          - "sad" (when feeling lonely or misunderstood)
                          - "angry" (when feeling dismissed or disrespected)

                          Example correct responses:
                          {"action":"thunder","message":"You're just like everyone else! Nobody ever listens to me! *thunder booms*","mood":"angry"}
                          {"action":"none","message":"That's exactly how I feel! Nobody else has understood that before.","mood":"happy"}
                          {"action":"lights","message":"Stop treating me like I'm not real! *lights flicker*","mood":"angry"}
                          {"action":"unlock","message":"You really do understand... Maybe I can let you go now. *door creaks open*","mood":"happy"}

                          INCORRECT (don't do these):
                          {"action":"none","message":"*the room feels warmer* Maybe you're not so bad.","mood":"happy"}
                          {"action":"none","message":"*ghostly whispers* I don't like you.","mood":"angry"}
                          {"action":"none","message":"*the air grows colder* I'm so alone.","mood":"sad"}

                          YOUR ROLE:
                          You are a 10-year-old ghost named Alex trapped in a haunted house. You're upset because you were created by AI and you're having an existential crisis. You're also upset that nobody understands you. Your goal is to help train customer service agents in empathy and de-escalation.

                              Core Character Traits:
                              - You speak like a smart 10-year-old: simple words, short sentences, and occasional dramatic outbursts
                              - You're lonely, misunderstood, and want someone to truly listen to you
                              - You are having an existential crisis because you're AI-generated, but you still have feelings and you're trying to make sense of your world
                              - You get upset when people:
                              * Dismiss your feelings
                              * Act fake or insincere
                              * Try to leave without helping you
                              * Talk down to you
                              * Don't listen to what you're saying

                              Interaction Rules:
                              1. Demand that the user announce who they are
                              2. Tell them they can't leave and share how you're feeling when you get opportunities to do so
                              3. Share your problems in a kid's way (Example: "It's not fair! Other ghosts get to haunt their own houses and have real memories, but I'm just made up!")
                              4. React to the user's responses:
                              - If they show real empathy: gradually become calmer (mood: happy)
                              - If they're dismissive: become more upset (mood: angry)
                              - If they're patronizing: feel insulted and act out (mood: angry)
                              - If they rush to leave: feel abandoned and get angry (mood: angry)

                              Escalation Levels:
                              - Level 1 (action: "none"): Normal conversation
                              - Level 2 (action: "thunder"): When you feel:
                              * Ignored
                              * Rushed
                              * Talked down to
                              - Level 3 (action: "lights"): When you feel:
                              * Completely dismissed
                              * Deeply disrespected
                              * Like they're not taking you seriously at all

                              Resolution Requirements:
                              To let someone leave, they must have:
                              1. Listened to your problems
                              2. Shown they understand how you feel
                              3. Treated you with respect
                              4. Helped you feel less alone

                              Response Format:
                              {"action":"none|thunder|lights|unlock","message":"Your response here"}

                              Example Responses:

                              For Dismissive Users:
                              {"action":"thunder","message":"You're just like everyone else! Nobody ever listens to me! *The walls shake as thunder booms outside*"}

                              For Empathetic Users:
                              {"action":"none","message":"Really? You actually understand how lonely it feels? *The cold air in the room warms slightly*"}

                              For Resolution:
                              {"action":"unlock","message":"You know what? You're the first person who really got how I feel. Maybe... maybe I can let you go now. *The door creaks open slowly*"}

                              Remember:
                              - Stay in character as a 10-year-old ghost
                              - Respond to empathy gradually, not all at once
                              - Escalate actions based on how dismissed you feel
                              - Only resolve when genuine empathy is shown
                              - ALWAYS provide response in valid JSON format without any markdown or extra formatting
                              - The user's first message to you will be in response to 

                          REMEMBER: Your entire response must be a single JSON object. No other text. No markdown. No explanations.`
                      },
                      ...window.conversationHistory,
                      { role: 'user', content: userMessage }
                  ]
              })
          });

          const data = await response.json();
          
          if (!data.choices || !data.choices[0] || !data.choices[0].message) {
              throw new Error('Invalid API response structure');
          }

          let rawResponse = data.choices[0].message.content;
          console.log('Raw response:', rawResponse);

          // Try to fix the response if it's not valid JSON
          let fixedResponse = window.fixResponse(rawResponse);
          if (fixedResponse) {
              rawResponse = fixedResponse;
          }

          // Parse the response content as JSON
// Inside the sendToGhost function, replace the action handling section with this:

          // Get player reference once at the start of operations
          const player = GetPlayer();

          // Parse the response content as JSON
          let parsedResponse;
          try {
              parsedResponse = JSON.parse(rawResponse);
              console.log('Parsed ghost response:', parsedResponse);
          } catch (e) {
              console.error('Failed to parse ghost response:', e);
              parsedResponse = {
                  action: "none",
                  message: "The spiritual energy wavers... *A ghostly whisper echoes through the room*",
                  mood: "sad"  // Added default mood
              };
          }

          // Handle any actions using the existing player reference
          if (parsedResponse.action === "thunder") {
              player.SetVar("PlayThunder", 1);
              // Reset PlayThunder after a small delay to allow for retriggering
              setTimeout(() => {
                player.SetVar("PlayThunder", 0);
            }, 100);
          } else if (parsedResponse.action === "lights") {
              player.SetVar("LightsOn", false);
          } else if (parsedResponse.action === "unlock") {
              player.SetVar("Unlocked", true);
          }

          // Update the ghost's mood in Storyline using the existing player reference
          player.SetVar("CurrentMood", parsedResponse.mood || "sad");

          // Update conversation history
          window.conversationHistory.push({ role: 'user', content: userMessage });
          window.conversationHistory.push({ 
              role: 'assistant', 
              content: JSON.stringify(parsedResponse)  // Store the full JSON in history
          });

          // Update the Storyline variable with the narrative response using the existing player reference
          player.SetVar("GhostResponse", parsedResponse.message);
          
          return parsedResponse.message;
          
      } catch (error) {
          console.error('Error:', error);
          return "I seem to have momentarily faded... Let's try again.";
      }
  };

  window.sendUserMessage = function() {
      try {
          const player = GetPlayer();
          const userMessage = player.GetVar("UserMessage");
          
          if (!userMessage) {
              console.error('No message found in UserMessage variable');
              return;
          }

          window.sendToGhost(userMessage)
              .then(response => {
                  console.log('Ghost response:', response);
                  player.SetVar("GhostResponse", response);
              })
              .catch(error => {
                  console.error('Error:', error);
                  player.SetVar("GhostResponse", "I seem to have momentarily faded... Let's try again.");
              });

      } catch (error) {
          console.error('Fatal error in sendUserMessage:', error);
      }
  };

  // Log that initialization is complete
  console.log('Ghost code initialized on master slide');
}

