/**** 
* Plugins
****/ 
var tween = LK.import("@upit/tween.v1");
var storage = LK.import("@upit/storage.v1", {
	cash: 1000,
	rank: 1,
	highScore: 0
});
/**** 
* Classes
****/ 
var BetButton = Container.expand(function (amount, label) {
	var self = Container.call(this);
	var background = self.attachAsset('betButton', {
		anchorX: 0.5,
		anchorY: 0.5
	});
	self.amount = amount;
	var text = new Text2(label, {
		size: 36,
		fill: 0xFFFFFF
	});
	text.anchor.set(0.5, 0.5);
	self.addChild(text);
	self.down = function (x, y, obj) {
		background.alpha = 0.7;
	};
	self.up = function (x, y, obj) {
		background.alpha = 1;
		if (currentCash >= self.amount) {
			currentBet = self.amount;
			currentCash -= self.amount; // Deduct bet amount from cash
			updateBetDisplay();
			updateCashDisplay(); // Update cash display
			showMessage("Bet set: $" + currentBet);
		} else {
			showMessage("Not enough cash to place this bet!");
		}
	};
	return self;
});
var Bullet = Container.expand(function () {
	var self = Container.call(this);
	var bulletGraphics = self.attachAsset('bullet', {
		anchorX: 0.5,
		anchorY: 0.5
	});
	self.speed = 20;
	self.active = true;
	self.update = function () {
		if (self.active) {
			self.y -= self.speed;
			// Remove bullet when it leaves the screen
			if (self.y < -50) {
				self.active = false;
			}
		}
	};
	return self;
});
var ChatButton = Container.expand(function () {
	var self = Container.call(this);
	var background = self.attachAsset('betButton', {
		anchorX: 0.5,
		anchorY: 0.5
	});
	var text = new Text2("Chat", {
		size: 36,
		fill: 0xFFFFFF
	});
	text.anchor.set(0.5, 0.5);
	self.addChild(text);
	self.down = function (x, y, obj) {
		background.alpha = 0.7;
	};
	self.up = function (x, y, obj) {
		background.alpha = 1;
		groupChat.visible = !groupChat.visible; // Toggle visibility of the chat window
	};
	return self;
});
var Crosshair = Container.expand(function () {
	var self = Container.call(this);
	// Create a crosshair with a circle and two lines
	var circle = self.attachAsset('crosshair', {
		anchorX: 0.5,
		anchorY: 0.5,
		alpha: 0.3
	});
	var horizontalLine = self.attachAsset('crosshairLine', {
		anchorX: 0.5,
		anchorY: 0.5,
		alpha: 0.8
	});
	var verticalLine = self.attachAsset('crosshairLine', {
		anchorX: 0.5,
		anchorY: 0.5,
		rotation: Math.PI / 2,
		alpha: 0.8
	});
	return self;
});
var DialogueButton = Container.expand(function () {
	var self = Container.call(this);
	var background = self.attachAsset('betButton', {
		anchorX: 0.5,
		anchorY: 0.5
	});
	var text = new Text2("Can I get more money?", {
		size: 36,
		fill: 0xFFFFFF
	});
	text.anchor.set(0.5, 0.5);
	self.addChild(text);
	self.down = function (x, y, obj) {
		background.alpha = 0.7;
	};
	self.up = function (x, y, obj) {
		background.alpha = 1;
		requestMoreMoney();
	};
	return self;
});
var Enemy = Container.expand(function () {
	var self = Container.call(this);
	var enemyGraphics = self.attachAsset('enemyCartel', {
		anchorX: 0.5,
		anchorY: 0.5
	});
	self.speed = 3;
	self.direction = 1; // 1 for right, -1 for left
	self.active = true;
	self.shootInterval = Math.floor(Math.random() * 100) + 50; // Random shoot interval
	self.shootCounter = 0;
	self.update = function () {
		if (self.active) {
			self.x += self.speed * self.direction;
			if (self.x > 1950 || self.x < 100) {
				self.direction *= -1;
			}
			self.shootCounter++;
			if (self.shootCounter >= self.shootInterval) {
				self.shootCounter = 0;
				self.shoot();
			}
		}
	};
	self.shoot = function () {
		var bullet = new Bullet();
		bullet.x = self.x;
		bullet.y = self.y;
		bullet.speed = -20; // Enemy bullets move upwards
		bullets.push(bullet);
		game.addChild(bullet);
	};
	return self;
});
var GroupChat = Container.expand(function () {
	var self = Container.call(this);
	var chatWindow = self.attachAsset('panel', {
		anchorX: 1,
		anchorY: 0.5,
		alpha: 0.9,
		x: 2048,
		y: 2732 / 2
	});
	var chatMessages = [];
	var chatInput = new Text2("", {
		size: 30,
		fill: 0xFFFFFF
	});
	chatInput.anchor.set(0.5, 0.5);
	chatInput.x = 2048 - 400;
	chatInput.y = 50;
	chatWindow.addChild(chatInput);
	self.addMessage = function (message) {
		if (chatMessages.length >= 5) {
			chatMessages.shift().destroy();
		}
		var messageText = new Text2(message, {
			size: 30,
			fill: 0xFFFFFF
		});
		messageText.anchor.set(0.5, 0.5);
		messageText.x = 2048 - 400;
		messageText.y = 100 + chatMessages.length * 40;
		chatWindow.addChild(messageText);
		chatMessages.push(messageText);
	};
	self.sendMessage = function (message) {
		self.addMessage("You: " + message);
		// Simulate cartel members responding
		LK.setTimeout(function () {
			var responses = ["Interesting idea!", "Let's do it!", "I disagree.", "Maybe later."];
			var randomResponse = responses[Math.floor(Math.random() * responses.length)];
			self.addMessage("Cartel Member: " + randomResponse);
		}, 1000);
	};
	return self;
});
var Target = Container.expand(function () {
	var self = Container.call(this);
	// Create target with three concentric circles
	var outerRing = self.attachAsset('playerCartel', {
		anchorX: 0.5,
		anchorY: 0.5
	});
	var middleRing = self.attachAsset('targetMiddle', {
		anchorX: 0.5,
		anchorY: 0.5
	});
	var innerRing = self.attachAsset('targetInner', {
		anchorX: 0.5,
		anchorY: 0.5
	});
	self.speed = 3;
	self.direction = 1; // 1 for right, -1 for left
	self.active = true;
	self.points = 10; // Base points for hitting this target
	self.hit = function (bulletX, bulletY) {
		var dx = bulletX - self.x;
		var dy = bulletY - self.y;
		var distance = Math.sqrt(dx * dx + dy * dy);
		// Check which ring was hit
		if (distance < 20) {
			// Bullseye!
			return self.points * 3;
		} else if (distance < 40) {
			// Middle ring
			return self.points * 2;
		} else if (distance < 60) {
			// Outer ring
			return self.points;
		}
		return 0; // Miss
	};
	self.update = function () {
		if (self.active) {
			self.x += self.speed * self.direction;
			// Bounce off screen edges
			if (self.x > 1950 || self.x < 100) {
				self.direction *= -1;
			}
		}
	};
	return self;
});
/**** 
* Initialize Game
****/ 
var game = new LK.Game({
	backgroundColor: 0x222222
});
/**** 
* Game Code
****/ 
var dialogueButton = new DialogueButton();
dialogueButton.x = 100; // Position at middle left
dialogueButton.y = 2732 / 2;
game.addChild(dialogueButton);
function requestMoreMoney() {
	var responses = ["Yes, you can!", "No, not now!"];
	var randomResponse = responses[Math.floor(Math.random() * responses.length)];
	showMessage("Cartel Member: " + randomResponse, 2000);
	if (randomResponse === "Yes, you can!") {
		currentCash += 600;
		updateCashDisplay();
	}
}
// Define cartel members for each country
var cartelMembers = {
	"Mexico": ["Los Zetas (Carlos)", "Sinaloa Cartel (Miguel)", "Jalisco New Generation (Juan)", "Gulf Cartel (Luis)", "Tijuana Cartel (Pedro)"],
	"Germany": ["Berlin Syndicate (Hans)", "Fritz's Crew (Fritz)", "Klaus' Gang (Klaus)", "Gunter's Group (Gunter)", "Dieter's Division (Dieter)"],
	"Honduras": ["Honduran Connection (Jose)", "Manuel's Mob (Manuel)", "Ramon's Ring (Ramon)", "Carlos' Clan (Carlos)", "Luis' League (Luis)"],
	"Cuba": ["Cuban Network (Raul)", "Ernesto's Ensemble (Ernesto)", "Fidel's Faction (Fidel)", "Che's Circle (Che)", "Camilo's Cartel (Camilo)"],
	"America": ["American Outfit (John)", "Mike's Mob (Mike)", "Steve's Syndicate (Steve)", "Bob's Band (Bob)", "Tom's Troop (Tom)"],
	"South Korea": ["Seoul Syndicate (Sang Jae)", "Min Ho's Mob (Min Ho)", "Ji Hoon's Gang (Ji Hoon)", "Hyun Woo's Crew (Hyun Woo)", "Jin Soo's Squad (Jin Soo)"]
};
// Game variables
var selectedName = ""; // Initialize selectedName in the global scope
function openChatWindow() {
	var chatOptions = ["Attack!", "Fire!", "Retreat!", "Hold Position!"];
	var nameOptions = cartelMembers[currentCountry];
	var chatWindow = LK.getAsset('panel', {
		anchorX: 0.5,
		anchorY: 0.5,
		alpha: 0.9,
		x: 2048 / 2,
		y: 2732 / 2
	});
	game.addChild(chatWindow);
	var selectedName = nameOptions[0]; // Default to the first name
	for (var i = 0; i < nameOptions.length; i++) {
		var nameText = new Text2(nameOptions[i], {
			size: 40,
			fill: 0xFFFFFF
		});
		nameText.anchor.set(0.5, 0.5);
		nameText.x = 2048 / 2 - 200;
		nameText.y = 2732 / 2 - 100 + i * 50;
		chatWindow.addChild(nameText);
		nameText.down = function (name) {
			return function (x, y, obj) {
				selectedName = name;
			};
		}(nameOptions[i]);
	}
	for (var i = 0; i < chatOptions.length; i++) {
		var optionText = new Text2(chatOptions[i], {
			size: 40,
			fill: 0xFFFFFF
		});
		optionText.anchor.set(0.5, 0.5);
		optionText.x = 2048 / 2;
		optionText.y = 2732 / 2 - 100 + i * 50;
		chatWindow.addChild(optionText);
		optionText.down = function (option) {
			return function (x, y, obj) {
				sendChatMessage(option);
				chatWindow.destroy();
			};
		}(chatOptions[i]);
	}
}
function sendChatMessage(message) {
	showMessage(selectedName + ": " + message, 2000);
	// Simulate cartel members responding
	LK.setTimeout(function () {
		var responses = ["Roger that!", "On it!", "Negative!", "Holding!"];
		var randomResponse = responses[Math.floor(Math.random() * responses.length)];
		var cartelMembers = {
			"Mexico": ["Carlos", "Miguel", "Juan", "Luis", "Pedro"],
			"Germany": ["Hans", "Fritz", "Klaus", "Gunter", "Dieter"],
			"Honduras": ["Jose", "Manuel", "Ramon", "Carlos", "Luis"],
			"Cuba": ["Raul", "Ernesto", "Fidel", "Che", "Camilo"],
			"America": ["John", "Mike", "Steve", "Bob", "Tom"],
			"South Korea": ["Sang Jae", "Min Ho", "Ji Hoon", "Hyun Woo", "Jin Soo"]
		};
		var randomName = cartelMembers[currentCountry][Math.floor(Math.random() * cartelMembers[currentCountry].length)];
		showMessage(randomName + ": " + randomResponse, 2000);
	}, 1000);
}
var currentRound = 1;
var currentDay = 1; // Initialize day counter to 1 when the game starts
var currentCash = 1000;
var currentRank = storage.rank;
var highScore = storage.highScore;
var currentBet = 0;
var currentScore = 0;
var bullets = [];
var targets = [];
var shotsRemaining = 0;
var maxShots = 70; // Maximum shots before reload
var shotsFired = 0; // Track shots fired
var isRoundActive = false;
var messageTimeout = null;
// Create game UI elements
var crosshair = new Crosshair();
game.addChild(crosshair);
// Cartel names and countries
var cartels = [{
	name: "Los Zetas",
	country: "Mexico"
}, {
	name: "Sinaloa Cartel",
	country: "Mexico"
}, {
	name: "Jalisco New Generation",
	country: "Mexico"
}, {
	name: "Gulf Cartel",
	country: "Mexico"
}, {
	name: "Tijuana Cartel",
	country: "Mexico"
}, {
	name: "Berlin Syndicate",
	country: "Germany"
}, {
	name: "Honduran Connection",
	country: "Honduras"
}, {
	name: "Cuban Network",
	country: "Cuba"
}, {
	name: "American Outfit",
	country: "America"
}, {
	name: "Seoul Cartel",
	country: "South Korea"
}];
var currentCartel = "";
var currentCountry = "Mexico"; // Default to a valid country
// Create cartel display
var cartelText = new Text2("Cartel: None", {
	size: 40,
	fill: 0xFFFFFF
});
cartelText.anchor.set(0, 0);
LK.gui.bottomLeft.addChild(cartelText);
cartelText.x = 20;
cartelText.y = -50;
// Create friendly members display
var friendlyMembersText = new Text2("Members: 0", {
	size: 40,
	fill: 0xFFFFFF
});
friendlyMembersText.anchor.set(0, 0);
LK.gui.bottomLeft.addChild(friendlyMembersText);
friendlyMembersText.x = 20;
friendlyMembersText.y = -100;
// Initialize friendly members count
var friendlyMembersCount = 0;
// Function to update friendly members display
function updateFriendlyMembersDisplay() {
	friendlyMembersText.setText("Members: " + friendlyMembersCount);
}
// Function to handle friendly members joining or leaving
function updateFriendlyMembers() {
	if (Math.random() < 0.5) {
		// 50% chance a member leaves
		if (friendlyMembersCount > 0) {
			friendlyMembersCount--;
			showMessage("A member has left the cartel.", 2000);
		}
	} else {
		// 50% chance a new member joins
		friendlyMembersCount++;
		showMessage("A new member has joined the cartel!", 2000);
	}
	updateFriendlyMembersDisplay();
}
// Call updateFriendlyMembers every 5 seconds
LK.setInterval(updateFriendlyMembers, 5000);
// Create join cartel button
var joinCartelButton = new BetButton(0, "Join a New Cartel");
joinCartelButton.x = 2048 / 2;
joinCartelButton.y = 2732 - 100;
game.addChild(joinCartelButton);
// Create plane button to join different countries
var planeButton = new BetButton(0, "Join a Country");
planeButton.x = 2048 / 2;
planeButton.y = 2732 - 150;
game.addChild(planeButton);
// Join cartel button functionality
joinCartelButton.down = function (x, y, obj) {
	// Select a random cartel
	var selectedCartel = cartels[Math.floor(Math.random() * cartels.length)];
	currentCartel = selectedCartel.name;
	currentCountry = selectedCartel.country;
	// Update cartel display
	cartelText.setText("Cartel: " + currentCartel + " (" + currentCountry + ")");
};
// Plane button functionality
planeButton.down = function (x, y, obj) {
	// Select a random country and cartel
	var selectedCartel = cartels[Math.floor(Math.random() * cartels.length)];
	currentCartel = selectedCartel.name;
	currentCountry = selectedCartel.country;
	// Update cartel display
	cartelText.setText("Cartel: " + currentCartel + " (" + currentCountry + ")");
};
// Create cash display
var cashText = new Text2("Cash: $" + currentCash, {
	size: 40,
	fill: 0xFFFFFF
});
cashText.anchor.set(0, 0);
LK.gui.topRight.addChild(cashText);
cashText.x = -250;
cashText.y = 20;
// Create round display
var roundText = new Text2("Round: " + currentRound, {
	size: 40,
	fill: 0xFFFFFF
});
roundText.anchor.set(0.5, 0);
LK.gui.top.addChild(roundText);
roundText.y = 20;
// Create shots remaining display
var shotsText = new Text2("Shots: 0", {
	size: 40,
	fill: 0xFFFFFF
});
shotsText.anchor.set(1, 0);
LK.gui.topLeft.addChild(shotsText);
shotsText.x = 250;
shotsText.y = 20;
// Create bet display
var betText = new Text2("Bet: $0", {
	size: 40,
	fill: 0xFFFFFF
});
betText.anchor.set(0, 0);
LK.gui.topRight.addChild(betText);
betText.x = -250;
betText.y = 70;
// Create score display
var scoreText = new Text2("Score: 0", {
	size: 40,
	fill: 0xFFFFFF
});
scoreText.anchor.set(1, 0);
LK.gui.topLeft.addChild(scoreText);
scoreText.x = 250;
scoreText.y = 70;
// Create day display
var dayText = new Text2("Day: " + currentDay, {
	size: 40,
	fill: 0xFFFFFF
});
dayText.anchor.set(0.5, 0);
LK.gui.top.addChild(dayText);
dayText.y = 170;
// Create rank display
var rankText = new Text2("Rank: " + getRankTitle(currentRank), {
	size: 40,
	fill: 0xFFFFFF
});
rankText.anchor.set(0.5, 0);
LK.gui.top.addChild(rankText);
rankText.y = 70;
// Create message display
var messageText = new Text2("", {
	size: 50,
	fill: 0xFFFFFF
});
messageText.anchor.set(0.5, 0.5);
LK.gui.center.addChild(messageText);
// Create clock display
var clockText = new Text2("Time: 00:00", {
	size: 40,
	fill: 0xFFFFFF
});
clockText.anchor.set(0.5, 0);
LK.gui.top.addChild(clockText);
clockText.y = 120;
// Create load game button
var loadGameButton = new BetButton(0, "Load Game");
loadGameButton.x = 2048 / 2;
loadGameButton.y = 2732 - 250;
game.addChild(loadGameButton);
// Create start round button
var startButton = new BetButton(0, "Start Round");
startButton.x = 2048 / 2;
startButton.y = 2732 - 200;
game.addChild(startButton);
// Create reload button
var reloadButton = new BetButton(0, "Reload");
reloadButton.x = 2048 / 2 + 200;
reloadButton.y = 2732 - 200;
game.addChild(reloadButton);
// Create chat button
var chatButton = new ChatButton();
chatButton.x = 2048 / 2 - 300;
chatButton.y = 2732 - 200;
game.addChild(chatButton);
// Initialize group chat
var groupChat = new GroupChat();
game.addChild(groupChat);
// Example of sending a message
chatButton.up = function (x, y, obj) {
	groupChat.sendMessage("Let's plan our next move!");
};
// Load game button functionality
loadGameButton.down = function (x, y, obj) {
	currentDay = 1; // Reset day counter to 1
	currentRank = 1; // Set rank to Rookie
	updateRankDisplay();
	dayText.setText("Day: " + currentDay); // Update day display
	showMessage("Game loaded! Day set to 1 and rank set to Rookie.", 3000);
};
// Reload button functionality
reloadButton.down = function (x, y, obj) {
	if (!isRoundActive) {
		shotsRemaining = maxShots; // Reset shots remaining to max
		shotsFired = 0; // Reset shots fired counter
		updateShotsDisplay();
		showMessage("Reloaded!", 2000);
	}
};
// Create betting UI
var betPanel = LK.getAsset('panel', {
	anchorX: 0.5,
	anchorY: 0.5,
	alpha: 0.8,
	x: 2048 / 2,
	y: 2732 / 2
});
game.addChild(betPanel);
var betTitle = new Text2("Place Your Bet", {
	size: 60,
	fill: 0xFFFFFF
});
betTitle.anchor.set(0.5, 0);
betTitle.x = 2048 / 2;
betTitle.y = 2732 / 2 - 120;
game.addChild(betTitle);
// Bet buttons
var betAmounts = [10, 50, 100, 500];
var betButtons = [];
for (var i = 0; i < betAmounts.length; i++) {
	var betButton = new BetButton(betAmounts[i], "$" + betAmounts[i]);
	betButton.x = 2048 / 2 - 300 + i * 200;
	betButton.y = 2732 / 2;
	game.addChild(betButton);
	betButtons.push(betButton);
}
// Start button functionality
startButton.down = function (x, y, obj) {
	if (!isRoundActive) {
		if (currentBet > 0) {
			startRound();
		} else {
			showMessage("Place a bet first!");
		}
	}
};
// Helper functions
function updateCashDisplay() {
	cashText.setText("Cash: $" + currentCash);
	storage.cash = currentCash;
}
function updateBetDisplay() {
	betText.setText("Bet: $" + currentBet);
}
function updateScoreDisplay() {
	scoreText.setText("Score: " + currentScore);
}
function updateShotsDisplay() {
	shotsText.setText("Shots: " + shotsRemaining);
}
function updateRoundDisplay() {
	roundText.setText("Round: " + currentRound);
}
function updateRankDisplay() {
	rankText.setText("Rank: " + getRankTitle(currentRank));
	storage.rank = currentRank;
}
function getRankTitle(rank) {
	var titles = ["Rookie", "Marksman", "Sharpshooter", "Expert", "Assassin", "Hitman", "Legend"];
	return titles[Math.min(rank - 1, titles.length - 1)];
}
function showMessage(text, duration) {
	messageText.setText(text);
	if (messageTimeout) {
		LK.clearTimeout(messageTimeout);
	}
	if (duration !== undefined) {
		messageTimeout = LK.setTimeout(function () {
			messageText.setText("");
			messageTimeout = null;
		}, duration);
	}
}
function createTarget() {
	var target = new Target();
	if (Math.random() < 0.5) {
		target.attachAsset('thirdPartyCartel', {
			anchorX: 0.5,
			anchorY: 0.5
		});
	}
	target.x = Math.random() * (1800 - 200) + 200; // Random position
	target.y = 2532; // Position friendly cartel at the bottom
	target.speed = 2 + currentRound * 0.5; // Speed increases with rounds
	target.points = 10 * currentRound; // Points increase with rounds
	game.addChild(target);
	targets.push(target);
	return target;
}
function clearAllTargets() {
	for (var i = targets.length - 1; i >= 0; i--) {
		targets[i].destroy();
	}
	targets = [];
}
function clearAllBullets() {
	for (var i = bullets.length - 1; i >= 0; i--) {
		bullets[i].destroy();
	}
	bullets = [];
}
function shoot(x, y) {
	if (shotsRemaining <= 0 || !isRoundActive || shotsFired >= maxShots) {
		if (shotsFired >= maxShots) {
			showMessage("Reloading...", 2000);
			return;
		}
		return;
	}
	shotsFired++; // Increment shots fired counter
	// Decrease shots remaining
	var bullet = new Bullet();
	bullet.x = x;
	bullet.y = 2732 - 100; // Start from bottom
	bullets.push(bullet);
	game.addChild(bullet);
	// Decrease shots remaining
	shotsRemaining--;
	updateShotsDisplay();
	// Play shoot sound
	LK.getSound('shoot').play();
	// Check if round is over
	if (shotsRemaining <= 0) {
		LK.setTimeout(function () {
			endRound();
		}, 1500); // Wait for bullets to finish
	}
}
function startRound() {
	// Reset round state
	isRoundActive = true;
	if (currentDay === 1 && currentRound === 1) {
		currentRank = 1; // Set rank to Rookie
		updateRankDisplay();
	}
	currentScore = 0;
	updateScoreDisplay();
	clearAllTargets();
	clearAllBullets();
	// Deduct bet amount
	currentCash -= currentBet;
	updateCashDisplay();
	// Set up targets for this round
	var numTargets = Math.min(2 + currentRound, 8);
	for (var i = 0; i < numTargets; i++) {
		createTarget();
	}
	// Set up enemies for this round
	var numEnemies = Math.min(1 + currentRound, 5);
	for (var i = 0; i < numEnemies; i++) {
		var enemy = new Enemy();
		enemy.x = Math.random() * (1800 - 200) + 200; // Random position
		enemy.y = 200; // Position enemies at the top
		game.addChild(enemy);
		targets.push(enemy);
	}
	// Set up shots
	shotsRemaining = 5 + currentRound;
	updateShotsDisplay();
	// Hide betting panel
	betPanel.visible = false;
	betTitle.visible = false;
	for (var j = 0; j < betButtons.length; j++) {
		betButtons[j].visible = false;
	}
	// Show round start message
	showMessage("Round " + currentRound + " - FIRE!", 2000);
	// Update button text
	startButton.children[1].setText("Firing...");
}
function endRound() {
	isRoundActive = false;
	shotsFired = 0; // Reset shots fired counter
	// Check if player won anything
	var winnings = calculateWinnings();
	if (winnings > 0) {
		currentCash += winnings;
		updateCashDisplay();
		showMessage("You won $" + winnings + "!", 3000);
		LK.getSound('win').play();
		// Check for rank up
		if (currentScore > highScore) {
			highScore = currentScore;
			storage.highScore = highScore;
			if (currentRank < 7 && currentScore >= currentRank * 1000) {
				currentRank++;
				updateRankDisplay();
				showMessage("RANK UP! You're now a " + getRankTitle(currentRank), 3000);
			}
		}
		// Advance to next round
		currentRound++;
		updateRoundDisplay();
	} else {
		showMessage("You lost your bet!", 3000);
		LK.getSound('lose').play();
		// Check for game over
		if (currentCash <= 0) {
			showMessage("GAME OVER! You're broke!", 3000);
			LK.setTimeout(function () {
				// Reset game
				currentCash = 1000;
				currentRound = 1;
				currentBet = 0;
				updateCashDisplay();
				updateRoundDisplay();
				updateBetDisplay();
				LK.showGameOver();
			}, 3000);
			return;
		}
	}
	// Intermission period of 30 seconds before showing betting panel again
	showMessage("Intermission: Prepare for the next round!", 30000);
	LK.setTimeout(function () {
		// Show betting panel again
		betPanel.visible = true;
		betTitle.visible = true;
		for (var i = 0; i < betButtons.length; i++) {
			betButtons[i].visible = true;
		}
		startButton.children[1].setText("Start Round");
		currentBet = 0;
		updateBetDisplay();
	}, 30000); // 30 seconds intermission
}
function calculateWinnings() {
	// Calculate winnings based on bet and score
	var hitRatio = currentScore / (5 + currentRound);
	if (hitRatio >= 0.8) {
		// Excellent shooting
		return currentBet * 3;
	} else if (hitRatio >= 0.6) {
		// Good shooting
		return currentBet * 2;
	} else if (hitRatio >= 0.4) {
		// Decent shooting
		return currentBet * 1.5;
	} else if (hitRatio >= 0.2) {
		// Poor shooting
		return currentBet;
	}
	// Bad shooting, no winnings
	return 0;
}
// Handle game input
game.down = function (x, y, obj) {
	if (isRoundActive) {
		shoot(x, y);
	}
};
game.move = function (x, y, obj) {
	crosshair.x = x;
	crosshair.y = y;
};
// Game update loop
game.update = function () {
	// Update clock
	var inGameMinutes = Math.floor(LK.ticks / 60) % 60;
	var inGameHours = Math.floor(LK.ticks / 3600) % 24;
	clockText.setText("Time: " + (inGameHours < 10 ? "0" : "") + inGameHours + ":" + (inGameMinutes < 10 ? "0" : "") + inGameMinutes);
	// Update bullets
	for (var i = bullets.length - 1; i >= 0; i--) {
		var bullet = bullets[i];
		if (!bullet.active) {
			bullet.destroy();
			bullets.splice(i, 1);
			continue;
		}
		// Check for collisions with targets
		for (var j = targets.length - 1; j >= 0; j--) {
			var target = targets[j];
			if (!(target instanceof Target)) {
				continue;
			} // Ensure target is an instance of Target class
			if (bullet.active && target.active) {
				var points = target.hit(bullet.x, bullet.y);
				if (points > 0) {
					// Hit!
					bullet.active = false;
					// Add points
					currentScore += points;
					updateScoreDisplay();
					// Visual feedback
					LK.effects.flashObject(target, 0xFFFFFF, 300);
					// Play hit sound
					LK.getSound('hit').play();
					// Show points
					var pointsText = new Text2("+" + points, {
						size: 40,
						fill: 0xFFFF00
					});
					pointsText.anchor.set(0.5, 0.5);
					pointsText.x = bullet.x;
					pointsText.y = bullet.y;
					game.addChild(pointsText);
					// Animate points text
					tween(pointsText, {
						alpha: 0,
						y: pointsText.y - 50
					}, {
						duration: 800,
						onFinish: function onFinish() {
							pointsText.destroy();
						}
					});
					break;
				}
			}
		}
	}
	// Advance day and rank every in-game day (5 minutes in real life)
	if (LK.ticks % (60 * 5 * 60) === 0) {
		currentDay++; // Increment day counter
		dayText.setText("Day: " + currentDay); // Update day display
		// 5 minutes in real life
		currentRank++;
		updateRankDisplay();
		showMessage("New Day! Rank increased to " + getRankTitle(currentRank), 3000);
	}
	// Update targets
	for (var k = targets.length - 1; k >= 0; k--) {
		targets[k].update();
	}
};
currentDay = 1; // Reset day counter to 1 every time the player loads into the game
dayText.setText("Day: " + currentDay); // Update day display
LK.playMusic('bgMusic');
showMessage("Place your bet and start the round!", 3000); /**** 
* Plugins
****/ 
var tween = LK.import("@upit/tween.v1");
var storage = LK.import("@upit/storage.v1", {
	cash: 1000,
	rank: 1,
	highScore: 0
});
/**** 
* Classes
****/ 
var BetButton = Container.expand(function (amount, label) {
	var self = Container.call(this);
	var background = self.attachAsset('betButton', {
		anchorX: 0.5,
		anchorY: 0.5
	});
	self.amount = amount;
	var text = new Text2(label, {
		size: 36,
		fill: 0xFFFFFF
	});
	text.anchor.set(0.5, 0.5);
	self.addChild(text);
	self.down = function (x, y, obj) {
		background.alpha = 0.7;
	};
	self.up = function (x, y, obj) {
		background.alpha = 1;
		if (currentCash >= self.amount) {
			currentBet = self.amount;
			currentCash -= self.amount; // Deduct bet amount from cash
			updateBetDisplay();
			updateCashDisplay(); // Update cash display
			showMessage("Bet set: $" + currentBet);
		} else {
			showMessage("Not enough cash to place this bet!");
		}
	};
	return self;
});
var Bullet = Container.expand(function () {
	var self = Container.call(this);
	var bulletGraphics = self.attachAsset('bullet', {
		anchorX: 0.5,
		anchorY: 0.5
	});
	self.speed = 20;
	self.active = true;
	self.update = function () {
		if (self.active) {
			self.y -= self.speed;
			// Remove bullet when it leaves the screen
			if (self.y < -50) {
				self.active = false;
			}
		}
	};
	return self;
});
var ChatButton = Container.expand(function () {
	var self = Container.call(this);
	var background = self.attachAsset('betButton', {
		anchorX: 0.5,
		anchorY: 0.5
	});
	var text = new Text2("Chat", {
		size: 36,
		fill: 0xFFFFFF
	});
	text.anchor.set(0.5, 0.5);
	self.addChild(text);
	self.down = function (x, y, obj) {
		background.alpha = 0.7;
	};
	self.up = function (x, y, obj) {
		background.alpha = 1;
		groupChat.visible = !groupChat.visible; // Toggle visibility of the chat window
	};
	return self;
});
var Crosshair = Container.expand(function () {
	var self = Container.call(this);
	// Create a crosshair with a circle and two lines
	var circle = self.attachAsset('crosshair', {
		anchorX: 0.5,
		anchorY: 0.5,
		alpha: 0.3
	});
	var horizontalLine = self.attachAsset('crosshairLine', {
		anchorX: 0.5,
		anchorY: 0.5,
		alpha: 0.8
	});
	var verticalLine = self.attachAsset('crosshairLine', {
		anchorX: 0.5,
		anchorY: 0.5,
		rotation: Math.PI / 2,
		alpha: 0.8
	});
	return self;
});
var DialogueButton = Container.expand(function () {
	var self = Container.call(this);
	var background = self.attachAsset('betButton', {
		anchorX: 0.5,
		anchorY: 0.5
	});
	var text = new Text2("Can I get more money?", {
		size: 36,
		fill: 0xFFFFFF
	});
	text.anchor.set(0.5, 0.5);
	self.addChild(text);
	self.down = function (x, y, obj) {
		background.alpha = 0.7;
	};
	self.up = function (x, y, obj) {
		background.alpha = 1;
		requestMoreMoney();
	};
	return self;
});
var Enemy = Container.expand(function () {
	var self = Container.call(this);
	var enemyGraphics = self.attachAsset('enemyCartel', {
		anchorX: 0.5,
		anchorY: 0.5
	});
	self.speed = 3;
	self.direction = 1; // 1 for right, -1 for left
	self.active = true;
	self.shootInterval = Math.floor(Math.random() * 100) + 50; // Random shoot interval
	self.shootCounter = 0;
	self.update = function () {
		if (self.active) {
			self.x += self.speed * self.direction;
			if (self.x > 1950 || self.x < 100) {
				self.direction *= -1;
			}
			self.shootCounter++;
			if (self.shootCounter >= self.shootInterval) {
				self.shootCounter = 0;
				self.shoot();
			}
		}
	};
	self.shoot = function () {
		var bullet = new Bullet();
		bullet.x = self.x;
		bullet.y = self.y;
		bullet.speed = -20; // Enemy bullets move upwards
		bullets.push(bullet);
		game.addChild(bullet);
	};
	return self;
});
var GroupChat = Container.expand(function () {
	var self = Container.call(this);
	var chatWindow = self.attachAsset('panel', {
		anchorX: 1,
		anchorY: 0.5,
		alpha: 0.9,
		x: 2048,
		y: 2732 / 2
	});
	var chatMessages = [];
	var chatInput = new Text2("", {
		size: 30,
		fill: 0xFFFFFF
	});
	chatInput.anchor.set(0.5, 0.5);
	chatInput.x = 2048 - 400;
	chatInput.y = 50;
	chatWindow.addChild(chatInput);
	self.addMessage = function (message) {
		if (chatMessages.length >= 5) {
			chatMessages.shift().destroy();
		}
		var messageText = new Text2(message, {
			size: 30,
			fill: 0xFFFFFF
		});
		messageText.anchor.set(0.5, 0.5);
		messageText.x = 2048 - 400;
		messageText.y = 100 + chatMessages.length * 40;
		chatWindow.addChild(messageText);
		chatMessages.push(messageText);
	};
	self.sendMessage = function (message) {
		self.addMessage("You: " + message);
		// Simulate cartel members responding
		LK.setTimeout(function () {
			var responses = ["Interesting idea!", "Let's do it!", "I disagree.", "Maybe later."];
			var randomResponse = responses[Math.floor(Math.random() * responses.length)];
			self.addMessage("Cartel Member: " + randomResponse);
		}, 1000);
	};
	return self;
});
var Target = Container.expand(function () {
	var self = Container.call(this);
	// Create target with three concentric circles
	var outerRing = self.attachAsset('playerCartel', {
		anchorX: 0.5,
		anchorY: 0.5
	});
	var middleRing = self.attachAsset('targetMiddle', {
		anchorX: 0.5,
		anchorY: 0.5
	});
	var innerRing = self.attachAsset('targetInner', {
		anchorX: 0.5,
		anchorY: 0.5
	});
	self.speed = 3;
	self.direction = 1; // 1 for right, -1 for left
	self.active = true;
	self.points = 10; // Base points for hitting this target
	self.hit = function (bulletX, bulletY) {
		var dx = bulletX - self.x;
		var dy = bulletY - self.y;
		var distance = Math.sqrt(dx * dx + dy * dy);
		// Check which ring was hit
		if (distance < 20) {
			// Bullseye!
			return self.points * 3;
		} else if (distance < 40) {
			// Middle ring
			return self.points * 2;
		} else if (distance < 60) {
			// Outer ring
			return self.points;
		}
		return 0; // Miss
	};
	self.update = function () {
		if (self.active) {
			self.x += self.speed * self.direction;
			// Bounce off screen edges
			if (self.x > 1950 || self.x < 100) {
				self.direction *= -1;
			}
		}
	};
	return self;
});
/**** 
* Initialize Game
****/ 
var game = new LK.Game({
	backgroundColor: 0x222222
});
/**** 
* Game Code
****/ 
var dialogueButton = new DialogueButton();
dialogueButton.x = 100; // Position at middle left
dialogueButton.y = 2732 / 2;
game.addChild(dialogueButton);
function requestMoreMoney() {
	var responses = ["Yes, you can!", "No, not now!"];
	var randomResponse = responses[Math.floor(Math.random() * responses.length)];
	showMessage("Cartel Member: " + randomResponse, 2000);
	if (randomResponse === "Yes, you can!") {
		currentCash += 600;
		updateCashDisplay();
	}
}
// Define cartel members for each country
var cartelMembers = {
	"Mexico": ["Los Zetas (Carlos)", "Sinaloa Cartel (Miguel)", "Jalisco New Generation (Juan)", "Gulf Cartel (Luis)", "Tijuana Cartel (Pedro)"],
	"Germany": ["Berlin Syndicate (Hans)", "Fritz's Crew (Fritz)", "Klaus' Gang (Klaus)", "Gunter's Group (Gunter)", "Dieter's Division (Dieter)"],
	"Honduras": ["Honduran Connection (Jose)", "Manuel's Mob (Manuel)", "Ramon's Ring (Ramon)", "Carlos' Clan (Carlos)", "Luis' League (Luis)"],
	"Cuba": ["Cuban Network (Raul)", "Ernesto's Ensemble (Ernesto)", "Fidel's Faction (Fidel)", "Che's Circle (Che)", "Camilo's Cartel (Camilo)"],
	"America": ["American Outfit (John)", "Mike's Mob (Mike)", "Steve's Syndicate (Steve)", "Bob's Band (Bob)", "Tom's Troop (Tom)"],
	"South Korea": ["Seoul Syndicate (Sang Jae)", "Min Ho's Mob (Min Ho)", "Ji Hoon's Gang (Ji Hoon)", "Hyun Woo's Crew (Hyun Woo)", "Jin Soo's Squad (Jin Soo)"]
};
// Game variables
var selectedName = ""; // Initialize selectedName in the global scope
function openChatWindow() {
	var chatOptions = ["Attack!", "Fire!", "Retreat!", "Hold Position!"];
	var nameOptions = cartelMembers[currentCountry];
	var chatWindow = LK.getAsset('panel', {
		anchorX: 0.5,
		anchorY: 0.5,
		alpha: 0.9,
		x: 2048 / 2,
		y: 2732 / 2
	});
	game.addChild(chatWindow);
	var selectedName = nameOptions[0]; // Default to the first name
	for (var i = 0; i < nameOptions.length; i++) {
		var nameText = new Text2(nameOptions[i], {
			size: 40,
			fill: 0xFFFFFF
		});
		nameText.anchor.set(0.5, 0.5);
		nameText.x = 2048 / 2 - 200;
		nameText.y = 2732 / 2 - 100 + i * 50;
		chatWindow.addChild(nameText);
		nameText.down = function (name) {
			return function (x, y, obj) {
				selectedName = name;
			};
		}(nameOptions[i]);
	}
	for (var i = 0; i < chatOptions.length; i++) {
		var optionText = new Text2(chatOptions[i], {
			size: 40,
			fill: 0xFFFFFF
		});
		optionText.anchor.set(0.5, 0.5);
		optionText.x = 2048 / 2;
		optionText.y = 2732 / 2 - 100 + i * 50;
		chatWindow.addChild(optionText);
		optionText.down = function (option) {
			return function (x, y, obj) {
				sendChatMessage(option);
				chatWindow.destroy();
			};
		}(chatOptions[i]);
	}
}
function sendChatMessage(message) {
	showMessage(selectedName + ": " + message, 2000);
	// Simulate cartel members responding
	LK.setTimeout(function () {
		var responses = ["Roger that!", "On it!", "Negative!", "Holding!"];
		var randomResponse = responses[Math.floor(Math.random() * responses.length)];
		var cartelMembers = {
			"Mexico": ["Carlos", "Miguel", "Juan", "Luis", "Pedro"],
			"Germany": ["Hans", "Fritz", "Klaus", "Gunter", "Dieter"],
			"Honduras": ["Jose", "Manuel", "Ramon", "Carlos", "Luis"],
			"Cuba": ["Raul", "Ernesto", "Fidel", "Che", "Camilo"],
			"America": ["John", "Mike", "Steve", "Bob", "Tom"],
			"South Korea": ["Sang Jae", "Min Ho", "Ji Hoon", "Hyun Woo", "Jin Soo"]
		};
		var randomName = cartelMembers[currentCountry][Math.floor(Math.random() * cartelMembers[currentCountry].length)];
		showMessage(randomName + ": " + randomResponse, 2000);
	}, 1000);
}
var currentRound = 1;
var currentDay = 1; // Initialize day counter to 1 when the game starts
var currentCash = 1000;
var currentRank = storage.rank;
var highScore = storage.highScore;
var currentBet = 0;
var currentScore = 0;
var bullets = [];
var targets = [];
var shotsRemaining = 0;
var maxShots = 70; // Maximum shots before reload
var shotsFired = 0; // Track shots fired
var isRoundActive = false;
var messageTimeout = null;
// Create game UI elements
var crosshair = new Crosshair();
game.addChild(crosshair);
// Cartel names and countries
var cartels = [{
	name: "Los Zetas",
	country: "Mexico"
}, {
	name: "Sinaloa Cartel",
	country: "Mexico"
}, {
	name: "Jalisco New Generation",
	country: "Mexico"
}, {
	name: "Gulf Cartel",
	country: "Mexico"
}, {
	name: "Tijuana Cartel",
	country: "Mexico"
}, {
	name: "Berlin Syndicate",
	country: "Germany"
}, {
	name: "Honduran Connection",
	country: "Honduras"
}, {
	name: "Cuban Network",
	country: "Cuba"
}, {
	name: "American Outfit",
	country: "America"
}, {
	name: "Seoul Cartel",
	country: "South Korea"
}];
var currentCartel = "";
var currentCountry = "Mexico"; // Default to a valid country
// Create cartel display
var cartelText = new Text2("Cartel: None", {
	size: 40,
	fill: 0xFFFFFF
});
cartelText.anchor.set(0, 0);
LK.gui.bottomLeft.addChild(cartelText);
cartelText.x = 20;
cartelText.y = -50;
// Create friendly members display
var friendlyMembersText = new Text2("Members: 0", {
	size: 40,
	fill: 0xFFFFFF
});
friendlyMembersText.anchor.set(0, 0);
LK.gui.bottomLeft.addChild(friendlyMembersText);
friendlyMembersText.x = 20;
friendlyMembersText.y = -100;
// Initialize friendly members count
var friendlyMembersCount = 0;
// Function to update friendly members display
function updateFriendlyMembersDisplay() {
	friendlyMembersText.setText("Members: " + friendlyMembersCount);
}
// Function to handle friendly members joining or leaving
function updateFriendlyMembers() {
	if (Math.random() < 0.5) {
		// 50% chance a member leaves
		if (friendlyMembersCount > 0) {
			friendlyMembersCount--;
			showMessage("A member has left the cartel.", 2000);
		}
	} else {
		// 50% chance a new member joins
		friendlyMembersCount++;
		showMessage("A new member has joined the cartel!", 2000);
	}
	updateFriendlyMembersDisplay();
}
// Call updateFriendlyMembers every 5 seconds
LK.setInterval(updateFriendlyMembers, 5000);
// Create join cartel button
var joinCartelButton = new BetButton(0, "Join a New Cartel");
joinCartelButton.x = 2048 / 2;
joinCartelButton.y = 2732 - 100;
game.addChild(joinCartelButton);
// Create plane button to join different countries
var planeButton = new BetButton(0, "Join a Country");
planeButton.x = 2048 / 2;
planeButton.y = 2732 - 150;
game.addChild(planeButton);
// Join cartel button functionality
joinCartelButton.down = function (x, y, obj) {
	// Select a random cartel
	var selectedCartel = cartels[Math.floor(Math.random() * cartels.length)];
	currentCartel = selectedCartel.name;
	currentCountry = selectedCartel.country;
	// Update cartel display
	cartelText.setText("Cartel: " + currentCartel + " (" + currentCountry + ")");
};
// Plane button functionality
planeButton.down = function (x, y, obj) {
	// Select a random country and cartel
	var selectedCartel = cartels[Math.floor(Math.random() * cartels.length)];
	currentCartel = selectedCartel.name;
	currentCountry = selectedCartel.country;
	// Update cartel display
	cartelText.setText("Cartel: " + currentCartel + " (" + currentCountry + ")");
};
// Create cash display
var cashText = new Text2("Cash: $" + currentCash, {
	size: 40,
	fill: 0xFFFFFF
});
cashText.anchor.set(0, 0);
LK.gui.topRight.addChild(cashText);
cashText.x = -250;
cashText.y = 20;
// Create round display
var roundText = new Text2("Round: " + currentRound, {
	size: 40,
	fill: 0xFFFFFF
});
roundText.anchor.set(0.5, 0);
LK.gui.top.addChild(roundText);
roundText.y = 20;
// Create shots remaining display
var shotsText = new Text2("Shots: 0", {
	size: 40,
	fill: 0xFFFFFF
});
shotsText.anchor.set(1, 0);
LK.gui.topLeft.addChild(shotsText);
shotsText.x = 250;
shotsText.y = 20;
// Create bet display
var betText = new Text2("Bet: $0", {
	size: 40,
	fill: 0xFFFFFF
});
betText.anchor.set(0, 0);
LK.gui.topRight.addChild(betText);
betText.x = -250;
betText.y = 70;
// Create score display
var scoreText = new Text2("Score: 0", {
	size: 40,
	fill: 0xFFFFFF
});
scoreText.anchor.set(1, 0);
LK.gui.topLeft.addChild(scoreText);
scoreText.x = 250;
scoreText.y = 70;
// Create day display
var dayText = new Text2("Day: " + currentDay, {
	size: 40,
	fill: 0xFFFFFF
});
dayText.anchor.set(0.5, 0);
LK.gui.top.addChild(dayText);
dayText.y = 170;
// Create rank display
var rankText = new Text2("Rank: " + getRankTitle(currentRank), {
	size: 40,
	fill: 0xFFFFFF
});
rankText.anchor.set(0.5, 0);
LK.gui.top.addChild(rankText);
rankText.y = 70;
// Create message display
var messageText = new Text2("", {
	size: 50,
	fill: 0xFFFFFF
});
messageText.anchor.set(0.5, 0.5);
LK.gui.center.addChild(messageText);
// Create clock display
var clockText = new Text2("Time: 00:00", {
	size: 40,
	fill: 0xFFFFFF
});
clockText.anchor.set(0.5, 0);
LK.gui.top.addChild(clockText);
clockText.y = 120;
// Create load game button
var loadGameButton = new BetButton(0, "Load Game");
loadGameButton.x = 2048 / 2;
loadGameButton.y = 2732 - 250;
game.addChild(loadGameButton);
// Create start round button
var startButton = new BetButton(0, "Start Round");
startButton.x = 2048 / 2;
startButton.y = 2732 - 200;
game.addChild(startButton);
// Create reload button
var reloadButton = new BetButton(0, "Reload");
reloadButton.x = 2048 / 2 + 200;
reloadButton.y = 2732 - 200;
game.addChild(reloadButton);
// Create chat button
var chatButton = new ChatButton();
chatButton.x = 2048 / 2 - 300;
chatButton.y = 2732 - 200;
game.addChild(chatButton);
// Initialize group chat
var groupChat = new GroupChat();
game.addChild(groupChat);
// Example of sending a message
chatButton.up = function (x, y, obj) {
	groupChat.sendMessage("Let's plan our next move!");
};
// Load game button functionality
loadGameButton.down = function (x, y, obj) {
	currentDay = 1; // Reset day counter to 1
	currentRank = 1; // Set rank to Rookie
	updateRankDisplay();
	dayText.setText("Day: " + currentDay); // Update day display
	showMessage("Game loaded! Day set to 1 and rank set to Rookie.", 3000);
};
// Reload button functionality
reloadButton.down = function (x, y, obj) {
	if (!isRoundActive) {
		shotsRemaining = maxShots; // Reset shots remaining to max
		shotsFired = 0; // Reset shots fired counter
		updateShotsDisplay();
		showMessage("Reloaded!", 2000);
	}
};
// Create betting UI
var betPanel = LK.getAsset('panel', {
	anchorX: 0.5,
	anchorY: 0.5,
	alpha: 0.8,
	x: 2048 / 2,
	y: 2732 / 2
});
game.addChild(betPanel);
var betTitle = new Text2("Place Your Bet", {
	size: 60,
	fill: 0xFFFFFF
});
betTitle.anchor.set(0.5, 0);
betTitle.x = 2048 / 2;
betTitle.y = 2732 / 2 - 120;
game.addChild(betTitle);
// Bet buttons
var betAmounts = [10, 50, 100, 500];
var betButtons = [];
for (var i = 0; i < betAmounts.length; i++) {
	var betButton = new BetButton(betAmounts[i], "$" + betAmounts[i]);
	betButton.x = 2048 / 2 - 300 + i * 200;
	betButton.y = 2732 / 2;
	game.addChild(betButton);
	betButtons.push(betButton);
}
// Start button functionality
startButton.down = function (x, y, obj) {
	if (!isRoundActive) {
		if (currentBet > 0) {
			startRound();
		} else {
			showMessage("Place a bet first!");
		}
	}
};
// Helper functions
function updateCashDisplay() {
	cashText.setText("Cash: $" + currentCash);
	storage.cash = currentCash;
}
function updateBetDisplay() {
	betText.setText("Bet: $" + currentBet);
}
function updateScoreDisplay() {
	scoreText.setText("Score: " + currentScore);
}
function updateShotsDisplay() {
	shotsText.setText("Shots: " + shotsRemaining);
}
function updateRoundDisplay() {
	roundText.setText("Round: " + currentRound);
}
function updateRankDisplay() {
	rankText.setText("Rank: " + getRankTitle(currentRank));
	storage.rank = currentRank;
}
function getRankTitle(rank) {
	var titles = ["Rookie", "Marksman", "Sharpshooter", "Expert", "Assassin", "Hitman", "Legend"];
	return titles[Math.min(rank - 1, titles.length - 1)];
}
function showMessage(text, duration) {
	messageText.setText(text);
	if (messageTimeout) {
		LK.clearTimeout(messageTimeout);
	}
	if (duration !== undefined) {
		messageTimeout = LK.setTimeout(function () {
			messageText.setText("");
			messageTimeout = null;
		}, duration);
	}
}
function createTarget() {
	var target = new Target();
	if (Math.random() < 0.5) {
		target.attachAsset('thirdPartyCartel', {
			anchorX: 0.5,
			anchorY: 0.5
		});
	}
	target.x = Math.random() * (1800 - 200) + 200; // Random position
	target.y = 2532; // Position friendly cartel at the bottom
	target.speed = 2 + currentRound * 0.5; // Speed increases with rounds
	target.points = 10 * currentRound; // Points increase with rounds
	game.addChild(target);
	targets.push(target);
	return target;
}
function clearAllTargets() {
	for (var i = targets.length - 1; i >= 0; i--) {
		targets[i].destroy();
	}
	targets = [];
}
function clearAllBullets() {
	for (var i = bullets.length - 1; i >= 0; i--) {
		bullets[i].destroy();
	}
	bullets = [];
}
function shoot(x, y) {
	if (shotsRemaining <= 0 || !isRoundActive || shotsFired >= maxShots) {
		if (shotsFired >= maxShots) {
			showMessage("Reloading...", 2000);
			return;
		}
		return;
	}
	shotsFired++; // Increment shots fired counter
	// Decrease shots remaining
	var bullet = new Bullet();
	bullet.x = x;
	bullet.y = 2732 - 100; // Start from bottom
	bullets.push(bullet);
	game.addChild(bullet);
	// Decrease shots remaining
	shotsRemaining--;
	updateShotsDisplay();
	// Play shoot sound
	LK.getSound('shoot').play();
	// Check if round is over
	if (shotsRemaining <= 0) {
		LK.setTimeout(function () {
			endRound();
		}, 1500); // Wait for bullets to finish
	}
}
function startRound() {
	// Reset round state
	isRoundActive = true;
	if (currentDay === 1 && currentRound === 1) {
		currentRank = 1; // Set rank to Rookie
		updateRankDisplay();
	}
	currentScore = 0;
	updateScoreDisplay();
	clearAllTargets();
	clearAllBullets();
	// Deduct bet amount
	currentCash -= currentBet;
	updateCashDisplay();
	// Set up targets for this round
	var numTargets = Math.min(2 + currentRound, 8);
	for (var i = 0; i < numTargets; i++) {
		createTarget();
	}
	// Set up enemies for this round
	var numEnemies = Math.min(1 + currentRound, 5);
	for (var i = 0; i < numEnemies; i++) {
		var enemy = new Enemy();
		enemy.x = Math.random() * (1800 - 200) + 200; // Random position
		enemy.y = 200; // Position enemies at the top
		game.addChild(enemy);
		targets.push(enemy);
	}
	// Set up shots
	shotsRemaining = 5 + currentRound;
	updateShotsDisplay();
	// Hide betting panel
	betPanel.visible = false;
	betTitle.visible = false;
	for (var j = 0; j < betButtons.length; j++) {
		betButtons[j].visible = false;
	}
	// Show round start message
	showMessage("Round " + currentRound + " - FIRE!", 2000);
	// Update button text
	startButton.children[1].setText("Firing...");
}
function endRound() {
	isRoundActive = false;
	shotsFired = 0; // Reset shots fired counter
	// Check if player won anything
	var winnings = calculateWinnings();
	if (winnings > 0) {
		currentCash += winnings;
		updateCashDisplay();
		showMessage("You won $" + winnings + "!", 3000);
		LK.getSound('win').play();
		// Check for rank up
		if (currentScore > highScore) {
			highScore = currentScore;
			storage.highScore = highScore;
			if (currentRank < 7 && currentScore >= currentRank * 1000) {
				currentRank++;
				updateRankDisplay();
				showMessage("RANK UP! You're now a " + getRankTitle(currentRank), 3000);
			}
		}
		// Advance to next round
		currentRound++;
		updateRoundDisplay();
	} else {
		showMessage("You lost your bet!", 3000);
		LK.getSound('lose').play();
		// Check for game over
		if (currentCash <= 0) {
			showMessage("GAME OVER! You're broke!", 3000);
			LK.setTimeout(function () {
				// Reset game
				currentCash = 1000;
				currentRound = 1;
				currentBet = 0;
				updateCashDisplay();
				updateRoundDisplay();
				updateBetDisplay();
				LK.showGameOver();
			}, 3000);
			return;
		}
	}
	// Intermission period of 30 seconds before showing betting panel again
	showMessage("Intermission: Prepare for the next round!", 30000);
	LK.setTimeout(function () {
		// Show betting panel again
		betPanel.visible = true;
		betTitle.visible = true;
		for (var i = 0; i < betButtons.length; i++) {
			betButtons[i].visible = true;
		}
		startButton.children[1].setText("Start Round");
		currentBet = 0;
		updateBetDisplay();
	}, 30000); // 30 seconds intermission
}
function calculateWinnings() {
	// Calculate winnings based on bet and score
	var hitRatio = currentScore / (5 + currentRound);
	if (hitRatio >= 0.8) {
		// Excellent shooting
		return currentBet * 3;
	} else if (hitRatio >= 0.6) {
		// Good shooting
		return currentBet * 2;
	} else if (hitRatio >= 0.4) {
		// Decent shooting
		return currentBet * 1.5;
	} else if (hitRatio >= 0.2) {
		// Poor shooting
		return currentBet;
	}
	// Bad shooting, no winnings
	return 0;
}
// Handle game input
game.down = function (x, y, obj) {
	if (isRoundActive) {
		shoot(x, y);
	}
};
game.move = function (x, y, obj) {
	crosshair.x = x;
	crosshair.y = y;
};
// Game update loop
game.update = function () {
	// Update clock
	var inGameMinutes = Math.floor(LK.ticks / 60) % 60;
	var inGameHours = Math.floor(LK.ticks / 3600) % 24;
	clockText.setText("Time: " + (inGameHours < 10 ? "0" : "") + inGameHours + ":" + (inGameMinutes < 10 ? "0" : "") + inGameMinutes);
	// Update bullets
	for (var i = bullets.length - 1; i >= 0; i--) {
		var bullet = bullets[i];
		if (!bullet.active) {
			bullet.destroy();
			bullets.splice(i, 1);
			continue;
		}
		// Check for collisions with targets
		for (var j = targets.length - 1; j >= 0; j--) {
			var target = targets[j];
			if (!(target instanceof Target)) {
				continue;
			} // Ensure target is an instance of Target class
			if (bullet.active && target.active) {
				var points = target.hit(bullet.x, bullet.y);
				if (points > 0) {
					// Hit!
					bullet.active = false;
					// Add points
					currentScore += points;
					updateScoreDisplay();
					// Visual feedback
					LK.effects.flashObject(target, 0xFFFFFF, 300);
					// Play hit sound
					LK.getSound('hit').play();
					// Show points
					var pointsText = new Text2("+" + points, {
						size: 40,
						fill: 0xFFFF00
					});
					pointsText.anchor.set(0.5, 0.5);
					pointsText.x = bullet.x;
					pointsText.y = bullet.y;
					game.addChild(pointsText);
					// Animate points text
					tween(pointsText, {
						alpha: 0,
						y: pointsText.y - 50
					}, {
						duration: 800,
						onFinish: function onFinish() {
							pointsText.destroy();
						}
					});
					break;
				}
			}
		}
	}
	// Advance day and rank every in-game day (5 minutes in real life)
	if (LK.ticks % (60 * 5 * 60) === 0) {
		currentDay++; // Increment day counter
		dayText.setText("Day: " + currentDay); // Update day display
		// 5 minutes in real life
		currentRank++;
		updateRankDisplay();
		showMessage("New Day! Rank increased to " + getRankTitle(currentRank), 3000);
	}
	// Update targets
	for (var k = targets.length - 1; k >= 0; k--) {
		targets[k].update();
	}
};
currentDay = 1; // Reset day counter to 1 every time the player loads into the game
dayText.setText("Day: " + currentDay); // Update day display
LK.playMusic('bgMusic');
showMessage("Place your bet and start the round!", 3000);