/**** 
* Plugins
****/ 
var tween = LK.import("@upit/tween.v1");
var storage = LK.import("@upit/storage.v1", {
	friendName: "",
	friendshipLevel: 0,
	totalInteractions: 0,
	lastPlayTime: 0
});
/**** 
* Classes
****/ 
var ChatBubble = Container.expand(function () {
	var self = Container.call(this);
	var bubble = self.attachAsset('chatBubble', {
		anchorX: 0.5,
		anchorY: 0.5
	});
	self.messageText = new Text2('', {
		size: 40,
		fill: 0x000000
	});
	self.messageText.anchor.set(0.5, 0.5);
	self.addChild(self.messageText);
	// Create mini button to keep message visible
	var keepButton = self.attachAsset('sendButton', {
		anchorX: 0.5,
		anchorY: 0.5,
		x: 350,
		y: 0,
		width: 60,
		height: 30
	});
	keepButton.tint = 0x32cd32;
	var keepButtonText = new Text2('Keep', {
		size: 16,
		fill: 0xFFFFFF
	});
	keepButtonText.anchor.set(0.5, 0.5);
	keepButtonText.x = 350;
	keepButtonText.y = 0;
	self.addChild(keepButtonText);
	self.visible = false;
	self.fadeTimeout = null;
	self.isPermanent = false;
	self.showMessage = function (message) {
		self.messageText.setText(message);
		self.visible = true;
		self.alpha = 0;
		self.isPermanent = false;
		keepButton.visible = true;
		keepButtonText.visible = true;
		tween(self, {
			alpha: 1
		}, {
			duration: 300
		});
		// Clear any existing timeout
		if (self.fadeTimeout) {
			LK.clearTimeout(self.fadeTimeout);
		}
		// Set new timeout for auto-fade
		self.fadeTimeout = LK.setTimeout(function () {
			if (!self.isPermanent) {
				tween(self, {
					alpha: 0
				}, {
					duration: 300,
					onFinish: function onFinish() {
						self.visible = false;
					}
				});
			}
		}, 3000);
	};
	// Keep button click handler
	keepButton.down = function () {
		self.isPermanent = false;
		keepButton.visible = false;
		keepButtonText.visible = false;
		// Clear the fade timeout
		if (self.fadeTimeout) {
			LK.clearTimeout(self.fadeTimeout);
		}
		// Add visual feedback and fade out
		tween(self, {
			scaleX: 1.1,
			scaleY: 1.1
		}, {
			duration: 100,
			onFinish: function onFinish() {
				tween(self, {
					scaleX: 1,
					scaleY: 1
				}, {
					duration: 100,
					onFinish: function onFinish() {
						// Start fade out animation
						tween(self, {
							alpha: 0
						}, {
							duration: 300,
							onFinish: function onFinish() {
								self.visible = false;
							}
						});
					}
				});
			}
		});
	};
	return self;
});
var ChatInterface = Container.expand(function () {
	var self = Container.call(this);
	// Chat background
	var chatBg = self.attachAsset('chatBackground', {
		anchorX: 0.5,
		anchorY: 1
	});
	chatBg.alpha = 0.9;
	// Input field background
	var inputBg = self.attachAsset('chatInput', {
		anchorX: 0.5,
		anchorY: 1,
		y: -20
	});
	// Send button
	var sendBtn = self.attachAsset('sendButton', {
		anchorX: 0.5,
		anchorY: 1,
		x: 200,
		y: -20
	});
	// Send button text
	var sendText = new Text2('Send', {
		size: 24,
		fill: 0xFFFFFF
	});
	sendText.anchor.set(0.5, 0.5);
	sendText.x = 200;
	sendText.y = -50;
	self.addChild(sendText);
	// Input text display
	var inputText = new Text2('Tap to type...', {
		size: 20,
		fill: 0x666666
	});
	inputText.anchor.set(0.5, 0.5);
	inputText.x = 0;
	inputText.y = -50;
	self.addChild(inputText);
	// Chat messages container
	var messagesContainer = new Container();
	messagesContainer.y = -320;
	self.addChild(messagesContainer);
	// Intelligent chat responses categorized by context and personality
	var chatResponses = {
		greetings: ["Hey there, friend!", "Good to see you again!", "I've been waiting for you!", "You're back! I missed you!"],
		compliments: ["You're absolutely amazing!", "I'm so lucky to have you as a friend!", "You always know how to make me smile!", "You're the coolest person I know!"],
		questions: ["What's been the best part of your day?", "Do you have any fun plans coming up?", "What makes you happiest?", "Tell me about something you love!"],
		encouragement: ["You've got this!", "I believe in you!", "You're doing great!", "Keep being awesome!"],
		jokes: ["Why don't scientists trust atoms? Because they make up everything!", "I told my friend a joke about paper... it was tearable!", "What do you call a bear with no teeth? A gummy bear!"],
		stories: ["I dreamed about flying with butterflies last night!", "I wish we could explore a magical forest together!", "Imagine if we could visit the moon!", "I wonder what it's like to be a dolphin!"],
		empathy: ["I'm here if you need to talk", "Sometimes it's good to share how you feel", "You can always count on me", "I care about you a lot"],
		excitement: ["This is so exciting!", "I can't contain my joy!", "Wow, that's incredible!", "I'm practically bouncing with happiness!"],
		wisdom: ["The best friendships grow stronger over time", "Every day is a new adventure!", "Kindness is like sunshine for the soul", "Laughter really is the best medicine!"]
	};
	// Personality traits that affect responses
	var personalityTraits = {
		humor: 0.7,
		// How often to make jokes
		curiosity: 0.8,
		// How often to ask questions
		empathy: 0.9,
		// How supportive responses are
		energy: 0.6,
		// How enthusiastic responses are
		wisdom: 0.5 // How often to share thoughtful insights
	};
	// Memory system for smarter responses
	var conversationMemory = {
		topics: [],
		// Topics discussed
		playerMoods: [],
		// Detected player moods
		commonWords: {},
		// Frequently used words
		lastInteractions: [],
		// Recent interaction types
		favoriteTopics: [] // Topics that got positive responses
	};
	var messageHistory = [];
	var currentMessage = '';
	var isTyping = false;
	self.visible = false;
	self.show = function () {
		self.visible = true;
		self.alpha = 0;
		tween(self, {
			alpha: 1
		}, {
			duration: 300
		});
	};
	self.hide = function () {
		tween(self, {
			alpha: 0
		}, {
			duration: 300,
			onFinish: function onFinish() {
				self.visible = false;
				// Hide keyboard when chat closes
				if (typeof keyboard !== 'undefined') {
					keyboard.hide();
				}
				isTyping = false;
				currentMessage = '';
				inputText.setText('Tap to type...');
				inputText.fill = 0x666666;
			}
		});
	};
	self.addMessage = function (message, isPlayer) {
		var messageY = messageHistory.length * 40;
		var messageText = new Text2(message, {
			size: 24,
			fill: isPlayer ? 0x0066cc : 0x333333
		});
		messageText.anchor.set(isPlayer ? 1 : 0, 0);
		messageText.x = isPlayer ? 280 : -280;
		messageText.y = messageY;
		messagesContainer.addChild(messageText);
		messageHistory.push(messageText);
		// Keep only last 6 messages
		if (messageHistory.length > 6) {
			var oldMessage = messageHistory.shift();
			messagesContainer.removeChild(oldMessage);
			// Move remaining messages up
			for (var i = 0; i < messageHistory.length; i++) {
				messageHistory[i].y = i * 40;
			}
		}
		// If friend message, increase friendship
		if (!isPlayer) {
			friendshipLevel = Math.min(100, friendshipLevel + 1);
			updateFriendshipBar();
			// Learn from successful interactions
			var lastPlayerMessage = conversationMemory.lastInteractions[conversationMemory.lastInteractions.length - 1];
			if (lastPlayerMessage && lastPlayerMessage.positive) {
				// This type of response worked well, remember it
				conversationMemory.favoriteTopics.push({
					playerMessage: lastPlayerMessage.message,
					response: message,
					success: true
				});
				// Keep only last 20 successful interactions
				if (conversationMemory.favoriteTopics.length > 20) {
					conversationMemory.favoriteTopics.shift();
				}
			}
		}
	};
	self.sendPlayerMessage = function () {
		if (currentMessage.length > 0) {
			self.addMessage(currentMessage, true);
			currentMessage = '';
			inputText.setText('Tap to type...');
			inputText.fill = 0x666666;
			isTyping = false;
			// Friend responds after a delay
			LK.setTimeout(function () {
				var response = generateSmartResponse(currentMessage, {
					friendshipLevel: friendshipLevel
				});
				self.addMessage(friendName + ": " + response, false);
				// Show response in chat bubble above friend's head
				chatBubble.showMessage(response);
				friend.bounce();
			}, 1000 + Math.random() * 1000);
		} else {
			var playerMessages = ["Hi there!", "How are you doing?", "Want to play a game?", "You're awesome!", "I'm having fun!", "Tell me a joke!", "What's your favorite color?", "You're my best friend!", "This is so cool!", "I love chatting with you!"];
			var playerMessage = playerMessages[Math.floor(Math.random() * playerMessages.length)];
			self.addMessage(playerMessage, true);
			// Friend responds after a delay
			LK.setTimeout(function () {
				var response = generateSmartResponse(playerMessage, {
					friendshipLevel: friendshipLevel
				});
				self.addMessage(friendName + ": " + response, false);
				// Show response in chat bubble above friend's head
				chatBubble.showMessage(response);
				friend.bounce();
			}, 1000 + Math.random() * 1000);
		}
	};
	// Input field click handler
	inputBg.down = function () {
		if (!isTyping) {
			isTyping = true;
			currentMessage = '';
			inputText.setText('');
			inputText.fill = 0x000000;
			// Show keyboard when input is tapped
			if (typeof keyboard !== 'undefined') {
				keyboard.show();
			}
		}
	};
	// Add interactive typing function
	self.startTyping = function () {
		if (!isTyping) {
			isTyping = true;
			currentMessage = '';
			inputText.setText('');
			inputText.fill = 0x000000;
		}
	};
	// Add character to current message
	self.addChar = function (_char) {
		if (isTyping) {
			currentMessage += _char;
			inputText.setText(currentMessage);
		}
	};
	// Send button click handler
	sendBtn.down = function () {
		tween(sendBtn, {
			scaleX: 0.95,
			scaleY: 0.95
		}, {
			duration: 100,
			onFinish: function onFinish() {
				tween(sendBtn, {
					scaleX: 1,
					scaleY: 1
				}, {
					duration: 100
				});
			}
		});
		self.sendPlayerMessage();
	};
	return self;
});
var GameButton = Container.expand(function (label) {
	var self = Container.call(this);
	var buttonBg = self.attachAsset('button', {
		anchorX: 0.5,
		anchorY: 0.5
	});
	self.buttonText = new Text2(label, {
		size: 30,
		fill: 0xFFFFFF
	});
	self.buttonText.anchor.set(0.5, 0.5);
	self.addChild(self.buttonText);
	self.down = function (x, y, obj) {
		tween(self, {
			scaleX: 0.95,
			scaleY: 0.95
		}, {
			duration: 100,
			onFinish: function onFinish() {
				tween(self, {
					scaleX: 1,
					scaleY: 1
				}, {
					duration: 100
				});
			}
		});
		if (label === 'Pet') {
			friend.bounce();
			friendshipLevel = Math.min(100, friendshipLevel + 3);
			updateFriendshipBar();
			showRandomMessage();
			LK.getSound('happy').play();
		} else if (label === 'High Five') {
			friend.wiggle();
			friendshipLevel = Math.min(100, friendshipLevel + 5);
			updateFriendshipBar();
			chatBubble.showMessage("High five! You're awesome!");
			LK.getSound('happy').play();
		} else if (label === 'Play') {
			startMiniGame();
		} else if (label === 'Chat') {
			if (chatInterface.visible) {
				chatInterface.hide();
			} else {
				chatInterface.show();
			}
		}
	};
	return self;
});
var OnScreenKeyboard = Container.expand(function () {
	var self = Container.call(this);
	var keyboardBg = self.attachAsset('chatBackground', {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: 1.2,
		scaleY: 0.8
	});
	keyboardBg.alpha = 0.9;
	var keys = [['Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P'], ['A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L'], ['Z', 'X', 'C', 'V', 'B', 'N', 'M', '!', '?']];
	var keyButtons = [];
	var keySize = 60;
	var keySpacing = 65;
	// Create keys
	for (var row = 0; row < keys.length; row++) {
		var keyRow = keys[row];
		var rowWidth = keyRow.length * keySpacing;
		var startX = -rowWidth / 2 + keySpacing / 2;
		for (var col = 0; col < keyRow.length; col++) {
			var keyChar = keyRow[col];
			var keyBtn = LK.getAsset('sendButton', {
				anchorX: 0.5,
				anchorY: 0.5,
				width: keySize,
				height: keySize
			});
			keyBtn.x = startX + col * keySpacing;
			keyBtn.y = row * keySpacing - 60;
			keyBtn.tint = 0x4169e1;
			self.addChild(keyBtn);
			var keyText = new Text2(keyChar, {
				size: 24,
				fill: 0xFFFFFF
			});
			keyText.anchor.set(0.5, 0.5);
			keyText.x = keyBtn.x;
			keyText.y = keyBtn.y;
			self.addChild(keyText);
			// Add click handler
			keyBtn.keyChar = keyChar;
			keyBtn.down = function () {
				if (chatInterface.visible) {
					chatInterface.addChar(this.keyChar);
				}
			};
			keyButtons.push(keyBtn);
		}
	}
	// Space bar
	var spaceBtn = LK.getAsset('sendButton', {
		anchorX: 0.5,
		anchorY: 0.5,
		width: 200,
		height: keySize
	});
	spaceBtn.x = 0;
	spaceBtn.y = 3 * keySpacing - 60;
	spaceBtn.tint = 0x4169e1;
	self.addChild(spaceBtn);
	var spaceText = new Text2('SPACE', {
		size: 20,
		fill: 0xFFFFFF
	});
	spaceText.anchor.set(0.5, 0.5);
	spaceText.x = 0;
	spaceText.y = 3 * keySpacing - 60;
	self.addChild(spaceText);
	spaceBtn.down = function () {
		if (chatInterface.visible) {
			chatInterface.addChar(' ');
		}
	};
	self.visible = false;
	self.show = function () {
		self.visible = true;
		self.alpha = 0;
		tween(self, {
			alpha: 1
		}, {
			duration: 300
		});
	};
	self.hide = function () {
		tween(self, {
			alpha: 0
		}, {
			duration: 300,
			onFinish: function onFinish() {
				self.visible = false;
			}
		});
	};
	return self;
});
var VirtualFriend = Container.expand(function () {
	var self = Container.call(this);
	// Friend graphics
	var body = self.attachAsset('friendBody', {
		anchorX: 0.5,
		anchorY: 0.5
	});
	var head = self.attachAsset('friendHead', {
		anchorX: 0.5,
		anchorY: 0.5,
		y: -150
	});
	var leftEye = self.attachAsset('friendEye', {
		anchorX: 0.5,
		anchorY: 0.5,
		x: -40,
		y: -170
	});
	var rightEye = self.attachAsset('friendEye', {
		anchorX: 0.5,
		anchorY: 0.5,
		x: 40,
		y: -170
	});
	var mouth = self.attachAsset('friendMouth', {
		anchorX: 0.5,
		anchorY: 0.5,
		y: -120
	});
	// Friend properties
	self.mood = 'happy';
	self.lastInteraction = 0;
	self.currentAnimation = null;
	// Animation methods
	self.bounce = function () {
		if (self.currentAnimation) return;
		self.currentAnimation = 'bounce';
		tween(self, {
			y: self.y - 30
		}, {
			duration: 300,
			easing: tween.easeOut,
			onFinish: function onFinish() {
				tween(self, {
					y: self.y + 30
				}, {
					duration: 300,
					easing: tween.easeIn,
					onFinish: function onFinish() {
						self.currentAnimation = null;
					}
				});
			}
		});
	};
	self.wiggle = function () {
		if (self.currentAnimation) return;
		self.currentAnimation = 'wiggle';
		tween(self, {
			rotation: 0.1
		}, {
			duration: 150,
			easing: tween.easeInOut,
			onFinish: function onFinish() {
				tween(self, {
					rotation: -0.1
				}, {
					duration: 150,
					easing: tween.easeInOut,
					onFinish: function onFinish() {
						tween(self, {
							rotation: 0
						}, {
							duration: 150,
							easing: tween.easeInOut,
							onFinish: function onFinish() {
								self.currentAnimation = null;
							}
						});
					}
				});
			}
		});
	};
	self.changeMood = function (newMood) {
		self.mood = newMood;
		if (newMood === 'happy') {
			mouth.scaleY = 1;
			leftEye.scaleY = 1;
			rightEye.scaleY = 1;
		} else if (newMood === 'excited') {
			mouth.scaleY = 1.5;
			leftEye.scaleY = 0.8;
			rightEye.scaleY = 0.8;
		}
	};
	self.down = function (x, y, obj) {
		self.bounce();
		self.changeMood('excited');
		friendshipLevel = Math.min(100, friendshipLevel + 2);
		updateFriendshipBar();
		showRandomMessage();
		LK.getSound('interaction').play();
		LK.setTimeout(function () {
			self.changeMood('happy');
		}, 1000);
	};
	return self;
});
/**** 
* Initialize Game
****/ 
var game = new LK.Game({
	backgroundColor: 0x87CEEB
});
/**** 
* Game Code
****/ 
// Friend names pool
// Initialize storage with defaults
var friendNames = ['Alex', 'Sam', 'Jamie', 'Taylor', 'Jordan', 'Casey', 'Riley', 'Avery', 'Parker', 'Quinn', 'Skyler', 'River', 'Sage', 'Rowan', 'Phoenix', 'Kai'];
// Intelligent chat responses categorized by context and personality (global initialization)
var chatResponses = {
	greetings: ["Hey there, friend!", "Good to see you again!", "I've been waiting for you!", "You're back! I missed you!"],
	compliments: ["You're absolutely amazing!", "I'm so lucky to have you as a friend!", "You always know how to make me smile!", "You're the coolest person I know!"],
	questions: ["What's been the best part of your day?", "Do you have any fun plans coming up?", "What makes you happiest?", "Tell me about something you love!"],
	encouragement: ["You've got this!", "I believe in you!", "You're doing great!", "Keep being awesome!"],
	jokes: ["Why don't scientists trust atoms? Because they make up everything!", "I told my friend a joke about paper... it was tearable!", "What do you call a bear with no teeth? A gummy bear!"],
	stories: ["I dreamed about flying with butterflies last night!", "I wish we could explore a magical forest together!", "Imagine if we could visit the moon!", "I wonder what it's like to be a dolphin!"],
	empathy: ["I'm here if you need to talk", "Sometimes it's good to share how you feel", "You can always count on me", "I care about you a lot"],
	excitement: ["This is so exciting!", "I can't contain my joy!", "Wow, that's incredible!", "I'm practically bouncing with happiness!"],
	wisdom: ["The best friendships grow stronger over time", "Every day is a new adventure!", "Kindness is like sunshine for the soul", "Laughter really is the best medicine!"]
};
// Friendship messages
var friendshipMessages = ["I'm so happy to see you!", "You're the best friend ever!", "This is so much fun!", "I love spending time with you!", "You make me smile!", "Thanks for being my friend!", "Yay! That was awesome!", "I'm having such a great time!", "You're really cool!", "I'm glad we're friends!"];
// Memory system for smarter responses (global initialization)
var conversationMemory = {
	topics: [],
	// Topics discussed
	playerMoods: [],
	// Detected player moods
	commonWords: {},
	// Frequently used words
	lastInteractions: [],
	// Recent interaction types
	favoriteTopics: [] // Topics that got positive responses
};
// Personality traits that affect responses (global initialization)
var personalityTraits = {
	humor: 0.7,
	// How often to make jokes
	curiosity: 0.8,
	// How often to ask questions
	empathy: 0.9,
	// How supportive responses are
	energy: 0.6,
	// How enthusiastic responses are
	wisdom: 0.5 // How often to share thoughtful insights
};
// Game variables
var friendName = storage.friendName;
var friendshipLevel = storage.friendshipLevel;
var totalInteractions = storage.totalInteractions;
var friend;
var chatBubble;
var friendshipBar;
var friendshipFill;
var nameText;
var friendshipText;
var petButton;
var highFiveButton;
var playButton;
var chatButton;
var chatInterface;
var miniGameActive = false;
// Generate random friend name if first time
if (!friendName) {
	friendName = friendNames[Math.floor(Math.random() * friendNames.length)];
	storage.friendName = friendName;
}
// Create friend character
friend = game.addChild(new VirtualFriend());
friend.x = 1024;
friend.y = 1500;
// Create chat bubble
chatBubble = game.addChild(new ChatBubble());
chatBubble.x = 1024;
chatBubble.y = 800;
// Create friendship bar background
friendshipBar = game.addChild(LK.getAsset('friendshipBar', {
	anchorX: 0.5,
	anchorY: 0.5
}));
friendshipBar.x = 1024;
friendshipBar.y = 400;
// Create friendship fill
friendshipFill = game.addChild(LK.getAsset('friendshipFill', {
	anchorX: 0,
	anchorY: 0.5
}));
friendshipFill.x = 824;
friendshipFill.y = 400;
// Create UI text
nameText = new Text2('Meet ' + friendName + '!', {
	size: 60,
	fill: 0xFFFFFF
});
nameText.anchor.set(0.5, 0.5);
nameText.x = 1024;
nameText.y = 200;
game.addChild(nameText);
friendshipText = new Text2('Friendship: ' + friendshipLevel + '%', {
	size: 40,
	fill: 0xFFFFFF
});
friendshipText.anchor.set(0.5, 0.5);
friendshipText.x = 1024;
friendshipText.y = 350;
game.addChild(friendshipText);
// Create buttons
petButton = game.addChild(new GameButton('Pet'));
petButton.x = 1024;
petButton.y = 2200;
highFiveButton = game.addChild(new GameButton('High Five'));
highFiveButton.x = 700;
highFiveButton.y = 2200;
playButton = game.addChild(new GameButton('Play'));
playButton.x = 1348;
playButton.y = 2200;
// Create chat button
chatButton = game.addChild(new GameButton('Chat'));
chatButton.x = 1024;
chatButton.y = 2300;
// Create chat interface
chatInterface = game.addChild(new ChatInterface());
chatInterface.x = 1024;
chatInterface.y = 2600;
// Create on-screen keyboard
var keyboard = game.addChild(new OnScreenKeyboard());
keyboard.x = 1024;
keyboard.y = 2200;
// Functions
function updateFriendshipBar() {
	var fillWidth = friendshipLevel / 100 * 400;
	friendshipFill.width = Math.max(40, fillWidth);
	friendshipText.setText('Friendship: ' + friendshipLevel + '%');
	// Save progress
	storage.friendshipLevel = friendshipLevel;
	storage.totalInteractions = totalInteractions + 1;
	storage.lastPlayTime = Date.now();
}
function showRandomMessage() {
	var message = friendshipMessages[Math.floor(Math.random() * friendshipMessages.length)];
	chatBubble.showMessage(message);
}
// Array of available mini-games
var miniGames = [{
	name: "Rock Paper Scissors",
	start: function start() {
		chatBubble.showMessage("Let's play Rock, Paper, Scissors!");
		LK.setTimeout(function () {
			var playerChoice = Math.floor(Math.random() * 3); // 0=rock, 1=paper, 2=scissors
			var friendChoice = Math.floor(Math.random() * 3);
			var choices = ['Rock', 'Paper', 'Scissors'];
			var resultMessage = '';
			if (playerChoice === friendChoice) {
				resultMessage = "It's a tie! We both chose " + choices[playerChoice] + "!";
				friendshipLevel = Math.min(100, friendshipLevel + 1);
			} else {
				resultMessage = "I chose " + choices[friendChoice] + "! Good game!";
				friendshipLevel = Math.min(100, friendshipLevel + 3);
			}
			chatBubble.showMessage(resultMessage);
			updateFriendshipBar();
			friend.bounce();
			LK.setTimeout(function () {
				miniGameActive = false;
			}, 2000);
		}, 2000);
	}
}, {
	name: "Guess the Number",
	start: function start() {
		chatBubble.showMessage("I'm thinking of a number 1-10!");
		LK.setTimeout(function () {
			var secretNumber = Math.floor(Math.random() * 10) + 1;
			var playerGuess = Math.floor(Math.random() * 10) + 1;
			var resultMessage = '';
			if (playerGuess === secretNumber) {
				resultMessage = "Amazing! You guessed " + secretNumber + " correctly!";
				friendshipLevel = Math.min(100, friendshipLevel + 5);
			} else {
				resultMessage = "Good try! I was thinking " + secretNumber + ", you guessed " + playerGuess + "!";
				friendshipLevel = Math.min(100, friendshipLevel + 2);
			}
			chatBubble.showMessage(resultMessage);
			updateFriendshipBar();
			friend.wiggle();
			LK.setTimeout(function () {
				miniGameActive = false;
			}, 2000);
		}, 2000);
	}
}, {
	name: "Color Match",
	start: function start() {
		chatBubble.showMessage("Let's match colors! Think of your favorite!");
		LK.setTimeout(function () {
			var colors = ['Red', 'Blue', 'Green', 'Yellow', 'Purple', 'Orange'];
			var friendColor = colors[Math.floor(Math.random() * colors.length)];
			var playerColor = colors[Math.floor(Math.random() * colors.length)];
			var resultMessage = '';
			if (friendColor === playerColor) {
				resultMessage = "Wow! We both picked " + friendColor + "!";
				friendshipLevel = Math.min(100, friendshipLevel + 4);
			} else {
				resultMessage = "I picked " + friendColor + ", you picked " + playerColor + "! Cool!";
				friendshipLevel = Math.min(100, friendshipLevel + 2);
			}
			chatBubble.showMessage(resultMessage);
			updateFriendshipBar();
			friend.bounce();
			LK.setTimeout(function () {
				miniGameActive = false;
			}, 2000);
		}, 2000);
	}
}, {
	name: "Quick Math",
	start: function start() {
		chatBubble.showMessage("Let's do some quick math together!");
		LK.setTimeout(function () {
			var num1 = Math.floor(Math.random() * 10) + 1;
			var num2 = Math.floor(Math.random() * 10) + 1;
			var answer = num1 + num2;
			var resultMessage = num1 + " + " + num2 + " = " + answer + "! Great job!";
			friendshipLevel = Math.min(100, friendshipLevel + 3);
			chatBubble.showMessage(resultMessage);
			updateFriendshipBar();
			friend.wiggle();
			LK.setTimeout(function () {
				miniGameActive = false;
			}, 2000);
		}, 2000);
	}
}];
function generateSmartResponse(playerMessage, context) {
	var response = "";
	var responseType = "compliments"; // default
	// Analyze player message for keywords and sentiment
	var message = playerMessage.toLowerCase();
	var isQuestion = message.includes('?') || message.includes('what') || message.includes('how') || message.includes('why');
	var isPositive = message.includes('good') || message.includes('great') || message.includes('awesome') || message.includes('love') || message.includes('happy');
	var isNegative = message.includes('bad') || message.includes('sad') || message.includes('tired') || message.includes('boring');
	// Update conversation memory
	conversationMemory.lastInteractions.push({
		message: playerMessage,
		timestamp: LK.ticks,
		positive: isPositive,
		negative: isNegative
	});
	// Keep only last 10 interactions
	if (conversationMemory.lastInteractions.length > 10) {
		conversationMemory.lastInteractions.shift();
	}
	// Choose response type based on context and friendship level
	if (isQuestion && Math.random() < personalityTraits.curiosity) {
		responseType = "questions";
	} else if (isNegative && Math.random() < personalityTraits.empathy) {
		responseType = "empathy";
	} else if (isPositive && Math.random() < personalityTraits.energy) {
		responseType = "excitement";
	} else if (friendshipLevel > 70 && Math.random() < personalityTraits.wisdom) {
		responseType = "wisdom";
	} else if (Math.random() < personalityTraits.humor) {
		responseType = "jokes";
	} else if (Math.random() < 0.3) {
		responseType = "stories";
	} else if (Math.random() < 0.4) {
		responseType = "questions";
	} else {
		responseType = "compliments";
	}
	// Special responses based on friendship level
	if (friendshipLevel < 20) {
		responseType = "greetings";
	} else if (friendshipLevel > 90) {
		// Mix multiple response types for high friendship
		var responses = chatResponses[responseType];
		var secondType = Math.random() < 0.5 ? "compliments" : "excitement";
		response = responses[Math.floor(Math.random() * responses.length)] + " " + chatResponses[secondType][Math.floor(Math.random() * chatResponses[secondType].length)];
		return response;
	}
	// Get response from selected category
	var responses = chatResponses[responseType];
	response = responses[Math.floor(Math.random() * responses.length)];
	// Add personality flourishes
	if (personalityTraits.energy > 0.7 && Math.random() < 0.3) {
		response += " 🌟";
	}
	return response;
}
function startMiniGame() {
	if (miniGameActive) return;
	miniGameActive = true;
	// Select a random mini-game
	var randomGame = miniGames[Math.floor(Math.random() * miniGames.length)];
	randomGame.start();
}
// Initial greeting
LK.setTimeout(function () {
	chatBubble.showMessage("Hi there! I'm " + friendName + ". Let's be best friends!");
}, 1000);
// Dynamic personality development
function updatePersonality() {
	// Personality grows based on interactions
	var recentInteractions = conversationMemory.lastInteractions.slice(-5);
	var positiveCount = recentInteractions.filter(function (i) {
		return i.positive;
	}).length;
	var negativeCount = recentInteractions.filter(function (i) {
		return i.negative;
	}).length;
	// Adjust personality traits based on recent interactions
	if (positiveCount > negativeCount) {
		personalityTraits.energy = Math.min(1.0, personalityTraits.energy + 0.01);
		personalityTraits.humor = Math.min(1.0, personalityTraits.humor + 0.005);
	}
	if (negativeCount > 0) {
		personalityTraits.empathy = Math.min(1.0, personalityTraits.empathy + 0.01);
	}
	// Friendship level affects personality
	if (friendshipLevel > 50) {
		personalityTraits.wisdom = Math.min(1.0, personalityTraits.wisdom + 0.002);
	}
}
// Smarter periodic interactions
var friendlyTimer = LK.setInterval(function () {
	updatePersonality();
	if (!miniGameActive && Math.random() < 0.3) {
		friend.wiggle();
		// Choose smarter messages based on context
		if (Math.random() < 0.5) {
			var contextualResponse = generateSmartResponse("", {
				friendshipLevel: friendshipLevel
			});
			chatBubble.showMessage(contextualResponse);
		}
	}
}, 8000);
// Game update loop
game.update = function () {
	// Position chat bubble above friend's head
	chatBubble.x = friend.x;
	chatBubble.y = friend.y - 400; // Position above the head
	// Idle animations
	if (LK.ticks % 300 === 0 && !friend.currentAnimation) {
		if (Math.random() < 0.4) {
			friend.bounce();
		}
	}
	// Blink animation
	if (LK.ticks % 180 === 0) {
		var leftEye = friend.children[2];
		var rightEye = friend.children[3];
		leftEye.scaleY = 0.1;
		rightEye.scaleY = 0.1;
		LK.setTimeout(function () {
			leftEye.scaleY = 1;
			rightEye.scaleY = 1;
		}, 100);
	}
}; /**** 
* Plugins
****/ 
var tween = LK.import("@upit/tween.v1");
var storage = LK.import("@upit/storage.v1", {
	friendName: "",
	friendshipLevel: 0,
	totalInteractions: 0,
	lastPlayTime: 0
});
/**** 
* Classes
****/ 
var ChatBubble = Container.expand(function () {
	var self = Container.call(this);
	var bubble = self.attachAsset('chatBubble', {
		anchorX: 0.5,
		anchorY: 0.5
	});
	self.messageText = new Text2('', {
		size: 40,
		fill: 0x000000
	});
	self.messageText.anchor.set(0.5, 0.5);
	self.addChild(self.messageText);
	// Create mini button to keep message visible
	var keepButton = self.attachAsset('sendButton', {
		anchorX: 0.5,
		anchorY: 0.5,
		x: 350,
		y: 0,
		width: 60,
		height: 30
	});
	keepButton.tint = 0x32cd32;
	var keepButtonText = new Text2('Keep', {
		size: 16,
		fill: 0xFFFFFF
	});
	keepButtonText.anchor.set(0.5, 0.5);
	keepButtonText.x = 350;
	keepButtonText.y = 0;
	self.addChild(keepButtonText);
	self.visible = false;
	self.fadeTimeout = null;
	self.isPermanent = false;
	self.showMessage = function (message) {
		self.messageText.setText(message);
		self.visible = true;
		self.alpha = 0;
		self.isPermanent = false;
		keepButton.visible = true;
		keepButtonText.visible = true;
		tween(self, {
			alpha: 1
		}, {
			duration: 300
		});
		// Clear any existing timeout
		if (self.fadeTimeout) {
			LK.clearTimeout(self.fadeTimeout);
		}
		// Set new timeout for auto-fade
		self.fadeTimeout = LK.setTimeout(function () {
			if (!self.isPermanent) {
				tween(self, {
					alpha: 0
				}, {
					duration: 300,
					onFinish: function onFinish() {
						self.visible = false;
					}
				});
			}
		}, 3000);
	};
	// Keep button click handler
	keepButton.down = function () {
		self.isPermanent = false;
		keepButton.visible = false;
		keepButtonText.visible = false;
		// Clear the fade timeout
		if (self.fadeTimeout) {
			LK.clearTimeout(self.fadeTimeout);
		}
		// Add visual feedback and fade out
		tween(self, {
			scaleX: 1.1,
			scaleY: 1.1
		}, {
			duration: 100,
			onFinish: function onFinish() {
				tween(self, {
					scaleX: 1,
					scaleY: 1
				}, {
					duration: 100,
					onFinish: function onFinish() {
						// Start fade out animation
						tween(self, {
							alpha: 0
						}, {
							duration: 300,
							onFinish: function onFinish() {
								self.visible = false;
							}
						});
					}
				});
			}
		});
	};
	return self;
});
var ChatInterface = Container.expand(function () {
	var self = Container.call(this);
	// Chat background
	var chatBg = self.attachAsset('chatBackground', {
		anchorX: 0.5,
		anchorY: 1
	});
	chatBg.alpha = 0.9;
	// Input field background
	var inputBg = self.attachAsset('chatInput', {
		anchorX: 0.5,
		anchorY: 1,
		y: -20
	});
	// Send button
	var sendBtn = self.attachAsset('sendButton', {
		anchorX: 0.5,
		anchorY: 1,
		x: 200,
		y: -20
	});
	// Send button text
	var sendText = new Text2('Send', {
		size: 24,
		fill: 0xFFFFFF
	});
	sendText.anchor.set(0.5, 0.5);
	sendText.x = 200;
	sendText.y = -50;
	self.addChild(sendText);
	// Input text display
	var inputText = new Text2('Tap to type...', {
		size: 20,
		fill: 0x666666
	});
	inputText.anchor.set(0.5, 0.5);
	inputText.x = 0;
	inputText.y = -50;
	self.addChild(inputText);
	// Chat messages container
	var messagesContainer = new Container();
	messagesContainer.y = -320;
	self.addChild(messagesContainer);
	// Intelligent chat responses categorized by context and personality
	var chatResponses = {
		greetings: ["Hey there, friend!", "Good to see you again!", "I've been waiting for you!", "You're back! I missed you!"],
		compliments: ["You're absolutely amazing!", "I'm so lucky to have you as a friend!", "You always know how to make me smile!", "You're the coolest person I know!"],
		questions: ["What's been the best part of your day?", "Do you have any fun plans coming up?", "What makes you happiest?", "Tell me about something you love!"],
		encouragement: ["You've got this!", "I believe in you!", "You're doing great!", "Keep being awesome!"],
		jokes: ["Why don't scientists trust atoms? Because they make up everything!", "I told my friend a joke about paper... it was tearable!", "What do you call a bear with no teeth? A gummy bear!"],
		stories: ["I dreamed about flying with butterflies last night!", "I wish we could explore a magical forest together!", "Imagine if we could visit the moon!", "I wonder what it's like to be a dolphin!"],
		empathy: ["I'm here if you need to talk", "Sometimes it's good to share how you feel", "You can always count on me", "I care about you a lot"],
		excitement: ["This is so exciting!", "I can't contain my joy!", "Wow, that's incredible!", "I'm practically bouncing with happiness!"],
		wisdom: ["The best friendships grow stronger over time", "Every day is a new adventure!", "Kindness is like sunshine for the soul", "Laughter really is the best medicine!"]
	};
	// Personality traits that affect responses
	var personalityTraits = {
		humor: 0.7,
		// How often to make jokes
		curiosity: 0.8,
		// How often to ask questions
		empathy: 0.9,
		// How supportive responses are
		energy: 0.6,
		// How enthusiastic responses are
		wisdom: 0.5 // How often to share thoughtful insights
	};
	// Memory system for smarter responses
	var conversationMemory = {
		topics: [],
		// Topics discussed
		playerMoods: [],
		// Detected player moods
		commonWords: {},
		// Frequently used words
		lastInteractions: [],
		// Recent interaction types
		favoriteTopics: [] // Topics that got positive responses
	};
	var messageHistory = [];
	var currentMessage = '';
	var isTyping = false;
	self.visible = false;
	self.show = function () {
		self.visible = true;
		self.alpha = 0;
		tween(self, {
			alpha: 1
		}, {
			duration: 300
		});
	};
	self.hide = function () {
		tween(self, {
			alpha: 0
		}, {
			duration: 300,
			onFinish: function onFinish() {
				self.visible = false;
				// Hide keyboard when chat closes
				if (typeof keyboard !== 'undefined') {
					keyboard.hide();
				}
				isTyping = false;
				currentMessage = '';
				inputText.setText('Tap to type...');
				inputText.fill = 0x666666;
			}
		});
	};
	self.addMessage = function (message, isPlayer) {
		var messageY = messageHistory.length * 40;
		var messageText = new Text2(message, {
			size: 24,
			fill: isPlayer ? 0x0066cc : 0x333333
		});
		messageText.anchor.set(isPlayer ? 1 : 0, 0);
		messageText.x = isPlayer ? 280 : -280;
		messageText.y = messageY;
		messagesContainer.addChild(messageText);
		messageHistory.push(messageText);
		// Keep only last 6 messages
		if (messageHistory.length > 6) {
			var oldMessage = messageHistory.shift();
			messagesContainer.removeChild(oldMessage);
			// Move remaining messages up
			for (var i = 0; i < messageHistory.length; i++) {
				messageHistory[i].y = i * 40;
			}
		}
		// If friend message, increase friendship
		if (!isPlayer) {
			friendshipLevel = Math.min(100, friendshipLevel + 1);
			updateFriendshipBar();
			// Learn from successful interactions
			var lastPlayerMessage = conversationMemory.lastInteractions[conversationMemory.lastInteractions.length - 1];
			if (lastPlayerMessage && lastPlayerMessage.positive) {
				// This type of response worked well, remember it
				conversationMemory.favoriteTopics.push({
					playerMessage: lastPlayerMessage.message,
					response: message,
					success: true
				});
				// Keep only last 20 successful interactions
				if (conversationMemory.favoriteTopics.length > 20) {
					conversationMemory.favoriteTopics.shift();
				}
			}
		}
	};
	self.sendPlayerMessage = function () {
		if (currentMessage.length > 0) {
			self.addMessage(currentMessage, true);
			currentMessage = '';
			inputText.setText('Tap to type...');
			inputText.fill = 0x666666;
			isTyping = false;
			// Friend responds after a delay
			LK.setTimeout(function () {
				var response = generateSmartResponse(currentMessage, {
					friendshipLevel: friendshipLevel
				});
				self.addMessage(friendName + ": " + response, false);
				// Show response in chat bubble above friend's head
				chatBubble.showMessage(response);
				friend.bounce();
			}, 1000 + Math.random() * 1000);
		} else {
			var playerMessages = ["Hi there!", "How are you doing?", "Want to play a game?", "You're awesome!", "I'm having fun!", "Tell me a joke!", "What's your favorite color?", "You're my best friend!", "This is so cool!", "I love chatting with you!"];
			var playerMessage = playerMessages[Math.floor(Math.random() * playerMessages.length)];
			self.addMessage(playerMessage, true);
			// Friend responds after a delay
			LK.setTimeout(function () {
				var response = generateSmartResponse(playerMessage, {
					friendshipLevel: friendshipLevel
				});
				self.addMessage(friendName + ": " + response, false);
				// Show response in chat bubble above friend's head
				chatBubble.showMessage(response);
				friend.bounce();
			}, 1000 + Math.random() * 1000);
		}
	};
	// Input field click handler
	inputBg.down = function () {
		if (!isTyping) {
			isTyping = true;
			currentMessage = '';
			inputText.setText('');
			inputText.fill = 0x000000;
			// Show keyboard when input is tapped
			if (typeof keyboard !== 'undefined') {
				keyboard.show();
			}
		}
	};
	// Add interactive typing function
	self.startTyping = function () {
		if (!isTyping) {
			isTyping = true;
			currentMessage = '';
			inputText.setText('');
			inputText.fill = 0x000000;
		}
	};
	// Add character to current message
	self.addChar = function (_char) {
		if (isTyping) {
			currentMessage += _char;
			inputText.setText(currentMessage);
		}
	};
	// Send button click handler
	sendBtn.down = function () {
		tween(sendBtn, {
			scaleX: 0.95,
			scaleY: 0.95
		}, {
			duration: 100,
			onFinish: function onFinish() {
				tween(sendBtn, {
					scaleX: 1,
					scaleY: 1
				}, {
					duration: 100
				});
			}
		});
		self.sendPlayerMessage();
	};
	return self;
});
var GameButton = Container.expand(function (label) {
	var self = Container.call(this);
	var buttonBg = self.attachAsset('button', {
		anchorX: 0.5,
		anchorY: 0.5
	});
	self.buttonText = new Text2(label, {
		size: 30,
		fill: 0xFFFFFF
	});
	self.buttonText.anchor.set(0.5, 0.5);
	self.addChild(self.buttonText);
	self.down = function (x, y, obj) {
		tween(self, {
			scaleX: 0.95,
			scaleY: 0.95
		}, {
			duration: 100,
			onFinish: function onFinish() {
				tween(self, {
					scaleX: 1,
					scaleY: 1
				}, {
					duration: 100
				});
			}
		});
		if (label === 'Pet') {
			friend.bounce();
			friendshipLevel = Math.min(100, friendshipLevel + 3);
			updateFriendshipBar();
			showRandomMessage();
			LK.getSound('happy').play();
		} else if (label === 'High Five') {
			friend.wiggle();
			friendshipLevel = Math.min(100, friendshipLevel + 5);
			updateFriendshipBar();
			chatBubble.showMessage("High five! You're awesome!");
			LK.getSound('happy').play();
		} else if (label === 'Play') {
			startMiniGame();
		} else if (label === 'Chat') {
			if (chatInterface.visible) {
				chatInterface.hide();
			} else {
				chatInterface.show();
			}
		}
	};
	return self;
});
var OnScreenKeyboard = Container.expand(function () {
	var self = Container.call(this);
	var keyboardBg = self.attachAsset('chatBackground', {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: 1.2,
		scaleY: 0.8
	});
	keyboardBg.alpha = 0.9;
	var keys = [['Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P'], ['A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L'], ['Z', 'X', 'C', 'V', 'B', 'N', 'M', '!', '?']];
	var keyButtons = [];
	var keySize = 60;
	var keySpacing = 65;
	// Create keys
	for (var row = 0; row < keys.length; row++) {
		var keyRow = keys[row];
		var rowWidth = keyRow.length * keySpacing;
		var startX = -rowWidth / 2 + keySpacing / 2;
		for (var col = 0; col < keyRow.length; col++) {
			var keyChar = keyRow[col];
			var keyBtn = LK.getAsset('sendButton', {
				anchorX: 0.5,
				anchorY: 0.5,
				width: keySize,
				height: keySize
			});
			keyBtn.x = startX + col * keySpacing;
			keyBtn.y = row * keySpacing - 60;
			keyBtn.tint = 0x4169e1;
			self.addChild(keyBtn);
			var keyText = new Text2(keyChar, {
				size: 24,
				fill: 0xFFFFFF
			});
			keyText.anchor.set(0.5, 0.5);
			keyText.x = keyBtn.x;
			keyText.y = keyBtn.y;
			self.addChild(keyText);
			// Add click handler
			keyBtn.keyChar = keyChar;
			keyBtn.down = function () {
				if (chatInterface.visible) {
					chatInterface.addChar(this.keyChar);
				}
			};
			keyButtons.push(keyBtn);
		}
	}
	// Space bar
	var spaceBtn = LK.getAsset('sendButton', {
		anchorX: 0.5,
		anchorY: 0.5,
		width: 200,
		height: keySize
	});
	spaceBtn.x = 0;
	spaceBtn.y = 3 * keySpacing - 60;
	spaceBtn.tint = 0x4169e1;
	self.addChild(spaceBtn);
	var spaceText = new Text2('SPACE', {
		size: 20,
		fill: 0xFFFFFF
	});
	spaceText.anchor.set(0.5, 0.5);
	spaceText.x = 0;
	spaceText.y = 3 * keySpacing - 60;
	self.addChild(spaceText);
	spaceBtn.down = function () {
		if (chatInterface.visible) {
			chatInterface.addChar(' ');
		}
	};
	self.visible = false;
	self.show = function () {
		self.visible = true;
		self.alpha = 0;
		tween(self, {
			alpha: 1
		}, {
			duration: 300
		});
	};
	self.hide = function () {
		tween(self, {
			alpha: 0
		}, {
			duration: 300,
			onFinish: function onFinish() {
				self.visible = false;
			}
		});
	};
	return self;
});
var VirtualFriend = Container.expand(function () {
	var self = Container.call(this);
	// Friend graphics
	var body = self.attachAsset('friendBody', {
		anchorX: 0.5,
		anchorY: 0.5
	});
	var head = self.attachAsset('friendHead', {
		anchorX: 0.5,
		anchorY: 0.5,
		y: -150
	});
	var leftEye = self.attachAsset('friendEye', {
		anchorX: 0.5,
		anchorY: 0.5,
		x: -40,
		y: -170
	});
	var rightEye = self.attachAsset('friendEye', {
		anchorX: 0.5,
		anchorY: 0.5,
		x: 40,
		y: -170
	});
	var mouth = self.attachAsset('friendMouth', {
		anchorX: 0.5,
		anchorY: 0.5,
		y: -120
	});
	// Friend properties
	self.mood = 'happy';
	self.lastInteraction = 0;
	self.currentAnimation = null;
	// Animation methods
	self.bounce = function () {
		if (self.currentAnimation) return;
		self.currentAnimation = 'bounce';
		tween(self, {
			y: self.y - 30
		}, {
			duration: 300,
			easing: tween.easeOut,
			onFinish: function onFinish() {
				tween(self, {
					y: self.y + 30
				}, {
					duration: 300,
					easing: tween.easeIn,
					onFinish: function onFinish() {
						self.currentAnimation = null;
					}
				});
			}
		});
	};
	self.wiggle = function () {
		if (self.currentAnimation) return;
		self.currentAnimation = 'wiggle';
		tween(self, {
			rotation: 0.1
		}, {
			duration: 150,
			easing: tween.easeInOut,
			onFinish: function onFinish() {
				tween(self, {
					rotation: -0.1
				}, {
					duration: 150,
					easing: tween.easeInOut,
					onFinish: function onFinish() {
						tween(self, {
							rotation: 0
						}, {
							duration: 150,
							easing: tween.easeInOut,
							onFinish: function onFinish() {
								self.currentAnimation = null;
							}
						});
					}
				});
			}
		});
	};
	self.changeMood = function (newMood) {
		self.mood = newMood;
		if (newMood === 'happy') {
			mouth.scaleY = 1;
			leftEye.scaleY = 1;
			rightEye.scaleY = 1;
		} else if (newMood === 'excited') {
			mouth.scaleY = 1.5;
			leftEye.scaleY = 0.8;
			rightEye.scaleY = 0.8;
		}
	};
	self.down = function (x, y, obj) {
		self.bounce();
		self.changeMood('excited');
		friendshipLevel = Math.min(100, friendshipLevel + 2);
		updateFriendshipBar();
		showRandomMessage();
		LK.getSound('interaction').play();
		LK.setTimeout(function () {
			self.changeMood('happy');
		}, 1000);
	};
	return self;
});
/**** 
* Initialize Game
****/ 
var game = new LK.Game({
	backgroundColor: 0x87CEEB
});
/**** 
* Game Code
****/ 
// Friend names pool
// Initialize storage with defaults
var friendNames = ['Alex', 'Sam', 'Jamie', 'Taylor', 'Jordan', 'Casey', 'Riley', 'Avery', 'Parker', 'Quinn', 'Skyler', 'River', 'Sage', 'Rowan', 'Phoenix', 'Kai'];
// Intelligent chat responses categorized by context and personality (global initialization)
var chatResponses = {
	greetings: ["Hey there, friend!", "Good to see you again!", "I've been waiting for you!", "You're back! I missed you!"],
	compliments: ["You're absolutely amazing!", "I'm so lucky to have you as a friend!", "You always know how to make me smile!", "You're the coolest person I know!"],
	questions: ["What's been the best part of your day?", "Do you have any fun plans coming up?", "What makes you happiest?", "Tell me about something you love!"],
	encouragement: ["You've got this!", "I believe in you!", "You're doing great!", "Keep being awesome!"],
	jokes: ["Why don't scientists trust atoms? Because they make up everything!", "I told my friend a joke about paper... it was tearable!", "What do you call a bear with no teeth? A gummy bear!"],
	stories: ["I dreamed about flying with butterflies last night!", "I wish we could explore a magical forest together!", "Imagine if we could visit the moon!", "I wonder what it's like to be a dolphin!"],
	empathy: ["I'm here if you need to talk", "Sometimes it's good to share how you feel", "You can always count on me", "I care about you a lot"],
	excitement: ["This is so exciting!", "I can't contain my joy!", "Wow, that's incredible!", "I'm practically bouncing with happiness!"],
	wisdom: ["The best friendships grow stronger over time", "Every day is a new adventure!", "Kindness is like sunshine for the soul", "Laughter really is the best medicine!"]
};
// Friendship messages
var friendshipMessages = ["I'm so happy to see you!", "You're the best friend ever!", "This is so much fun!", "I love spending time with you!", "You make me smile!", "Thanks for being my friend!", "Yay! That was awesome!", "I'm having such a great time!", "You're really cool!", "I'm glad we're friends!"];
// Memory system for smarter responses (global initialization)
var conversationMemory = {
	topics: [],
	// Topics discussed
	playerMoods: [],
	// Detected player moods
	commonWords: {},
	// Frequently used words
	lastInteractions: [],
	// Recent interaction types
	favoriteTopics: [] // Topics that got positive responses
};
// Personality traits that affect responses (global initialization)
var personalityTraits = {
	humor: 0.7,
	// How often to make jokes
	curiosity: 0.8,
	// How often to ask questions
	empathy: 0.9,
	// How supportive responses are
	energy: 0.6,
	// How enthusiastic responses are
	wisdom: 0.5 // How often to share thoughtful insights
};
// Game variables
var friendName = storage.friendName;
var friendshipLevel = storage.friendshipLevel;
var totalInteractions = storage.totalInteractions;
var friend;
var chatBubble;
var friendshipBar;
var friendshipFill;
var nameText;
var friendshipText;
var petButton;
var highFiveButton;
var playButton;
var chatButton;
var chatInterface;
var miniGameActive = false;
// Generate random friend name if first time
if (!friendName) {
	friendName = friendNames[Math.floor(Math.random() * friendNames.length)];
	storage.friendName = friendName;
}
// Create friend character
friend = game.addChild(new VirtualFriend());
friend.x = 1024;
friend.y = 1500;
// Create chat bubble
chatBubble = game.addChild(new ChatBubble());
chatBubble.x = 1024;
chatBubble.y = 800;
// Create friendship bar background
friendshipBar = game.addChild(LK.getAsset('friendshipBar', {
	anchorX: 0.5,
	anchorY: 0.5
}));
friendshipBar.x = 1024;
friendshipBar.y = 400;
// Create friendship fill
friendshipFill = game.addChild(LK.getAsset('friendshipFill', {
	anchorX: 0,
	anchorY: 0.5
}));
friendshipFill.x = 824;
friendshipFill.y = 400;
// Create UI text
nameText = new Text2('Meet ' + friendName + '!', {
	size: 60,
	fill: 0xFFFFFF
});
nameText.anchor.set(0.5, 0.5);
nameText.x = 1024;
nameText.y = 200;
game.addChild(nameText);
friendshipText = new Text2('Friendship: ' + friendshipLevel + '%', {
	size: 40,
	fill: 0xFFFFFF
});
friendshipText.anchor.set(0.5, 0.5);
friendshipText.x = 1024;
friendshipText.y = 350;
game.addChild(friendshipText);
// Create buttons
petButton = game.addChild(new GameButton('Pet'));
petButton.x = 1024;
petButton.y = 2200;
highFiveButton = game.addChild(new GameButton('High Five'));
highFiveButton.x = 700;
highFiveButton.y = 2200;
playButton = game.addChild(new GameButton('Play'));
playButton.x = 1348;
playButton.y = 2200;
// Create chat button
chatButton = game.addChild(new GameButton('Chat'));
chatButton.x = 1024;
chatButton.y = 2300;
// Create chat interface
chatInterface = game.addChild(new ChatInterface());
chatInterface.x = 1024;
chatInterface.y = 2600;
// Create on-screen keyboard
var keyboard = game.addChild(new OnScreenKeyboard());
keyboard.x = 1024;
keyboard.y = 2200;
// Functions
function updateFriendshipBar() {
	var fillWidth = friendshipLevel / 100 * 400;
	friendshipFill.width = Math.max(40, fillWidth);
	friendshipText.setText('Friendship: ' + friendshipLevel + '%');
	// Save progress
	storage.friendshipLevel = friendshipLevel;
	storage.totalInteractions = totalInteractions + 1;
	storage.lastPlayTime = Date.now();
}
function showRandomMessage() {
	var message = friendshipMessages[Math.floor(Math.random() * friendshipMessages.length)];
	chatBubble.showMessage(message);
}
// Array of available mini-games
var miniGames = [{
	name: "Rock Paper Scissors",
	start: function start() {
		chatBubble.showMessage("Let's play Rock, Paper, Scissors!");
		LK.setTimeout(function () {
			var playerChoice = Math.floor(Math.random() * 3); // 0=rock, 1=paper, 2=scissors
			var friendChoice = Math.floor(Math.random() * 3);
			var choices = ['Rock', 'Paper', 'Scissors'];
			var resultMessage = '';
			if (playerChoice === friendChoice) {
				resultMessage = "It's a tie! We both chose " + choices[playerChoice] + "!";
				friendshipLevel = Math.min(100, friendshipLevel + 1);
			} else {
				resultMessage = "I chose " + choices[friendChoice] + "! Good game!";
				friendshipLevel = Math.min(100, friendshipLevel + 3);
			}
			chatBubble.showMessage(resultMessage);
			updateFriendshipBar();
			friend.bounce();
			LK.setTimeout(function () {
				miniGameActive = false;
			}, 2000);
		}, 2000);
	}
}, {
	name: "Guess the Number",
	start: function start() {
		chatBubble.showMessage("I'm thinking of a number 1-10!");
		LK.setTimeout(function () {
			var secretNumber = Math.floor(Math.random() * 10) + 1;
			var playerGuess = Math.floor(Math.random() * 10) + 1;
			var resultMessage = '';
			if (playerGuess === secretNumber) {
				resultMessage = "Amazing! You guessed " + secretNumber + " correctly!";
				friendshipLevel = Math.min(100, friendshipLevel + 5);
			} else {
				resultMessage = "Good try! I was thinking " + secretNumber + ", you guessed " + playerGuess + "!";
				friendshipLevel = Math.min(100, friendshipLevel + 2);
			}
			chatBubble.showMessage(resultMessage);
			updateFriendshipBar();
			friend.wiggle();
			LK.setTimeout(function () {
				miniGameActive = false;
			}, 2000);
		}, 2000);
	}
}, {
	name: "Color Match",
	start: function start() {
		chatBubble.showMessage("Let's match colors! Think of your favorite!");
		LK.setTimeout(function () {
			var colors = ['Red', 'Blue', 'Green', 'Yellow', 'Purple', 'Orange'];
			var friendColor = colors[Math.floor(Math.random() * colors.length)];
			var playerColor = colors[Math.floor(Math.random() * colors.length)];
			var resultMessage = '';
			if (friendColor === playerColor) {
				resultMessage = "Wow! We both picked " + friendColor + "!";
				friendshipLevel = Math.min(100, friendshipLevel + 4);
			} else {
				resultMessage = "I picked " + friendColor + ", you picked " + playerColor + "! Cool!";
				friendshipLevel = Math.min(100, friendshipLevel + 2);
			}
			chatBubble.showMessage(resultMessage);
			updateFriendshipBar();
			friend.bounce();
			LK.setTimeout(function () {
				miniGameActive = false;
			}, 2000);
		}, 2000);
	}
}, {
	name: "Quick Math",
	start: function start() {
		chatBubble.showMessage("Let's do some quick math together!");
		LK.setTimeout(function () {
			var num1 = Math.floor(Math.random() * 10) + 1;
			var num2 = Math.floor(Math.random() * 10) + 1;
			var answer = num1 + num2;
			var resultMessage = num1 + " + " + num2 + " = " + answer + "! Great job!";
			friendshipLevel = Math.min(100, friendshipLevel + 3);
			chatBubble.showMessage(resultMessage);
			updateFriendshipBar();
			friend.wiggle();
			LK.setTimeout(function () {
				miniGameActive = false;
			}, 2000);
		}, 2000);
	}
}];
function generateSmartResponse(playerMessage, context) {
	var response = "";
	var responseType = "compliments"; // default
	// Analyze player message for keywords and sentiment
	var message = playerMessage.toLowerCase();
	var isQuestion = message.includes('?') || message.includes('what') || message.includes('how') || message.includes('why');
	var isPositive = message.includes('good') || message.includes('great') || message.includes('awesome') || message.includes('love') || message.includes('happy');
	var isNegative = message.includes('bad') || message.includes('sad') || message.includes('tired') || message.includes('boring');
	// Update conversation memory
	conversationMemory.lastInteractions.push({
		message: playerMessage,
		timestamp: LK.ticks,
		positive: isPositive,
		negative: isNegative
	});
	// Keep only last 10 interactions
	if (conversationMemory.lastInteractions.length > 10) {
		conversationMemory.lastInteractions.shift();
	}
	// Choose response type based on context and friendship level
	if (isQuestion && Math.random() < personalityTraits.curiosity) {
		responseType = "questions";
	} else if (isNegative && Math.random() < personalityTraits.empathy) {
		responseType = "empathy";
	} else if (isPositive && Math.random() < personalityTraits.energy) {
		responseType = "excitement";
	} else if (friendshipLevel > 70 && Math.random() < personalityTraits.wisdom) {
		responseType = "wisdom";
	} else if (Math.random() < personalityTraits.humor) {
		responseType = "jokes";
	} else if (Math.random() < 0.3) {
		responseType = "stories";
	} else if (Math.random() < 0.4) {
		responseType = "questions";
	} else {
		responseType = "compliments";
	}
	// Special responses based on friendship level
	if (friendshipLevel < 20) {
		responseType = "greetings";
	} else if (friendshipLevel > 90) {
		// Mix multiple response types for high friendship
		var responses = chatResponses[responseType];
		var secondType = Math.random() < 0.5 ? "compliments" : "excitement";
		response = responses[Math.floor(Math.random() * responses.length)] + " " + chatResponses[secondType][Math.floor(Math.random() * chatResponses[secondType].length)];
		return response;
	}
	// Get response from selected category
	var responses = chatResponses[responseType];
	response = responses[Math.floor(Math.random() * responses.length)];
	// Add personality flourishes
	if (personalityTraits.energy > 0.7 && Math.random() < 0.3) {
		response += " 🌟";
	}
	return response;
}
function startMiniGame() {
	if (miniGameActive) return;
	miniGameActive = true;
	// Select a random mini-game
	var randomGame = miniGames[Math.floor(Math.random() * miniGames.length)];
	randomGame.start();
}
// Initial greeting
LK.setTimeout(function () {
	chatBubble.showMessage("Hi there! I'm " + friendName + ". Let's be best friends!");
}, 1000);
// Dynamic personality development
function updatePersonality() {
	// Personality grows based on interactions
	var recentInteractions = conversationMemory.lastInteractions.slice(-5);
	var positiveCount = recentInteractions.filter(function (i) {
		return i.positive;
	}).length;
	var negativeCount = recentInteractions.filter(function (i) {
		return i.negative;
	}).length;
	// Adjust personality traits based on recent interactions
	if (positiveCount > negativeCount) {
		personalityTraits.energy = Math.min(1.0, personalityTraits.energy + 0.01);
		personalityTraits.humor = Math.min(1.0, personalityTraits.humor + 0.005);
	}
	if (negativeCount > 0) {
		personalityTraits.empathy = Math.min(1.0, personalityTraits.empathy + 0.01);
	}
	// Friendship level affects personality
	if (friendshipLevel > 50) {
		personalityTraits.wisdom = Math.min(1.0, personalityTraits.wisdom + 0.002);
	}
}
// Smarter periodic interactions
var friendlyTimer = LK.setInterval(function () {
	updatePersonality();
	if (!miniGameActive && Math.random() < 0.3) {
		friend.wiggle();
		// Choose smarter messages based on context
		if (Math.random() < 0.5) {
			var contextualResponse = generateSmartResponse("", {
				friendshipLevel: friendshipLevel
			});
			chatBubble.showMessage(contextualResponse);
		}
	}
}, 8000);
// Game update loop
game.update = function () {
	// Position chat bubble above friend's head
	chatBubble.x = friend.x;
	chatBubble.y = friend.y - 400; // Position above the head
	// Idle animations
	if (LK.ticks % 300 === 0 && !friend.currentAnimation) {
		if (Math.random() < 0.4) {
			friend.bounce();
		}
	}
	// Blink animation
	if (LK.ticks % 180 === 0) {
		var leftEye = friend.children[2];
		var rightEye = friend.children[3];
		leftEye.scaleY = 0.1;
		rightEye.scaleY = 0.1;
		LK.setTimeout(function () {
			leftEye.scaleY = 1;
			rightEye.scaleY = 1;
		}, 100);
	}
};