devsu69_

SULPHERSMP — ULTIMATE MAYOR SYSTEM

Production-Ready Minecraft Java Plugin Specification

Build a fully production-ready Minecraft Java plugin called SulpherMayor for SulpherSMP.

SulpherSMP is a competitive Lifesteal SMP focused on PvP, player economy, bounties, bases/claims, Warzone combat, custom Crown mechanics, spawners, rare loot and player progression.

The Mayor system should take inspiration from the rotating Mayor concept of Hypixel SkyBlock, but the implementation, candidates, mechanics, events, UI, economy systems and branding must be completely original and specifically designed for SulpherSMP.

The final plugin must feel like a premium custom SMP system, not a basic tutorial plugin.

---

  1. CORE MAYOR ELECTION SYSTEM

Create a complete democratic election system.

Default election cycle

  • Mayor term: 7 days
  • Election duration: configurable
  • 5 candidates available per election
  • Each player can vote once
  • Highest vote count becomes Mayor
  • Votes are saved persistently
  • Election survives server restarts
  • Current Mayor survives server restarts
  • Remaining term time survives restarts
  • Election history is saved

Everything must be configurable.

Candidate rotation

Do not show the same candidates every election.

Create a candidate pool and randomly select candidates for each election.

Allow administrators to configure:

  • Candidate pool
  • Number of candidates
  • Candidate selection rules
  • Whether candidates can repeat
  • Minimum time before a candidate can appear again

---

  1. MAYOR GUI

Command:

"/mayor"

Open a polished inventory GUI.

The GUI should display:

Header

SULPHERSMP MAYOR ELECTION

Current Mayor:

"Mayor Raven"

Term remaining:

"4d 17h 32m"

Candidate cards

Each candidate displays:

  • Name
  • Theme
  • Current vote count
  • Percentage of votes
  • Passive perks
  • Special ability
  • Downside
  • Vote button

Example:

MAYOR RAVEN

Lifesteal Specialist

🩸 Lifesteal Drops +10% 💰 Shop Prices -5%

SPECIAL Blood Moon

PvP damage increases during Blood Moon.

DOWNSIDE Natural regeneration is disabled during Blood Moon.

[ VOTE ]

Use professional formatting.

Avoid childish colors, excessive emojis or goofy wording.

---

  1. CURRENT MAYOR DISPLAY

Add:

"/mayor current"

Displays:

  • Current Mayor
  • Candidate description
  • Active perks
  • Active downside
  • Next recurring event
  • Time remaining
  • Mayor statistics

Also show the current Mayor in:

  • Spawn NPC
  • Optional scoreboard
  • Optional tablist
  • Optional boss bar

All are configurable.

---

  1. MAYOR CANDIDATES

Implement the following initial candidates.

Administrators must be able to add unlimited additional candidates through configuration.

---

MAYOR RAVEN

Theme: Lifesteal / PvP

Passive 1 — Lifesteal Economy

Lifesteal-related drops receive:

"+10%"

increased drop chance/reward.

Passive 2 — Market Discount

Configured shop items become:

"5% cheaper"

while Raven is Mayor.

Special — BLOOD MOON

At configurable intervals, Blood Moon activates.

Default:

  • Duration: 1 hour
  • Cooldown: 24 hours

During Blood Moon:

  • PvP damage: +15%
  • Player kill rewards: +15%
  • Lifesteal-related rewards: +10%

Server announcement:

§4§lBLOOD MOON

§7Mayor Raven has triggered a Blood Moon.

§cPvP rewards and damage have increased.

Use title + subtitle + chat + optional boss bar.

Downside

Natural regeneration is disabled during Blood Moon.

---

MAYOR THE SYNDICATE

Theme: PvP / Executioner

Contract Killer

Player kills award a random cash reward:

"$10,000 – $25,000"

Reward scales with victim heart count.

Example:

Victim: 20 hearts Reward: higher range

Victim: 40 hearts Reward: significantly higher range

Scaling formula must be configurable.

Heart Fragmenter

Player kills have a default:

"10% chance"

to drop a custom:

"Heart Fragment"

item.

The item:

  • Uses PersistentDataContainer / NamespacedKey
  • Cannot be duplicated
  • Has configurable material
  • Has custom name/lore
  • Can be used in configurable crafting recipes

Combat Focus

While The Syndicate is Mayor:

  • Ender Pearl cooldown reduced by 2 seconds
  • Golden Apples grant +2 additional absorption hearts

Downside

Warzone natural regeneration is disabled.

---

MAYOR AURELIUS

Theme: Economy

Prosperity

Players earn:

"+15%"

coins from configured economic activities.

Merchant Discount

Configured shop selling prices increase by:

"+10%"

Special — ECONOMIC BOOM

Once every 24 hours:

Activate a 1-hour Economic Boom.

During the event:

  • Coin generation increased
  • Mob selling prices increased
  • Player trading rewards increased
  • Configurable economy multiplier

Example:

§6§lECONOMIC BOOM

§fMayor Aurelius has started an Economic Boom!

§eAll economic rewards are increased for 1 hour.

Downside

Marketplace/trading tax:

"+3%"

---

MAYOR BARON VON LOOT

Theme: Warzone / Loot

High-Roller Supply Drops

Spawn a Contraband Crate every:

"3 hours"

while Baron von Loot is Mayor.

The interval must be configurable.

IMPORTANT: RANDOM CONTRABAND LOCATION

The server world has a:

10,000 × 10,000 block playable area/world border.

The plugin must randomly generate a location inside this area.

Default:

border: size: 10000 safety-distance: 250

The crate must:

  • Never spawn outside the border
  • Never spawn within the configured safety distance from the border
  • Automatically detect terrain height
  • Avoid underground spawning
  • Avoid water/lava
  • Avoid protected spawn regions
  • Avoid configured claim types if desired
  • Avoid invalid/unloaded locations
  • Retry location generation if the location is invalid

Do NOT use a fixed list of coordinates.

Every Contraband Crate must have a genuinely random location.

---

CONTRABAND CRATE ANNOUNCEMENT

When a crate spawns, immediately announce it to EVERY online player.

Title

§c§l⚠ CONTRABAND DROP

Subtitle

§fA high-value crate has entered the Warzone!

Chat

§c§l━━━━━━━━━━━━━━━━━━━━━━

§c§l⚠ CONTRABAND CRATE

§fA Contraband Crate has been dropped!

§eCoordinates: §fX: §c-1847 §fY: §c71 §fZ: §c2634

§7Reach it before someone else does.

§c§l━━━━━━━━━━━━━━━━━━━━━━

Coordinates must be the actual generated coordinates.

Do not announce coordinates before the crate exists.

Optional announcement channels

Configurable:

  • Title
  • Subtitle
  • Chat
  • Action Bar
  • Boss Bar
  • Sound

---

CONTRABAND CRATE VISUALS

At the location:

  • Spawn a custom crate/chest
  • Add configurable particles
  • Add beacon beam
  • Add hologram
  • Add glow effect
  • Add configurable sound
  • Add configurable protection

Hologram:

§c§lCONTRABAND CRATE §7High-value loot §eClaim it before someone else does!

---

CONTRABAND REWARDS

Default rewards:

  • $25,000 cash note
  • Golden Apples
  • End Crystals
  • Rare materials
  • Custom items

Support:

  • Weighted rewards
  • Guaranteed rewards
  • Random rewards
  • Min/max quantities
  • Multiple reward slots
  • Custom commands
  • Custom items
  • Custom enchantments where supported

---

CRATE CLAIMING

When opened:

  • Announce the player
  • Record player
  • Record location
  • Record rewards
  • Remove crate
  • Save statistics

Announcement:

§a§l✓ CONTRABAND CLAIMED

§fPlayer §e%player% §fhas claimed the Contraband Crate!

§7Location: §f%coords%

Prevent multiple players from claiming the same crate.

---

CONTRABAND ADMIN COMMANDS

/mayoradmin spawncrate /mayoradmin spawncrate <x> <y> <z> /mayoradmin crate /mayoradmin removecrate /mayoradmin setcrateworld <world>

"spawncrate" without coordinates must generate a random location.

---

MAYOR CASSIAN

Theme: Mining / Resources

Mining Fortune

Mining drops:

"+15%"

Rare Ore Chance

Rare ore drops receive a configurable bonus.

Special — ORE RUSH

Every 24 hours, activate a configurable 1-hour mining event.

During Ore Rush:

  • Increased ore drops
  • Increased rare ore chance
  • Optional mining speed bonus
  • Optional bonus XP

Downside

Mob drops:

"-10%"

---

MAYOR WARDEN GRIM

Theme: Defense / Raiding / Bounties

Blast Shield

Inside claimed territory:

  • Obsidian
  • Crying Obsidian
  • Reinforced Deepslate

receive:

"2×"

effective resistance against configured explosion types.

This MUST integrate with the server's claim system.

Do not globally modify blocks.

Bounty Hunter

Whenever a player creates a bounty:

/bounty <player> <amount>

the server adds:

"+$10,000"

server-funded bonus.

Maximum bonus:

"$25,000"

Example:

Player bounty:

"$20,000"

Server bonus:

"$10,000"

Total:

"$30,000"

Make the maximum bonus configurable.

Safe Zone Insurance

If a player dies inside their own claimed territory:

  • Balance is protected
  • Configurable death penalties may still apply

Warzone deaths receive NO insurance.

Downside

Bounty creation fee increases while Warden Grim is Mayor.

---

MAYOR VEX

Theme: Spawners / Black Market

Spawner Overclock

Increase supported spawner efficiency:

"+25%"

Do not blindly modify vanilla mechanics.

Provide compatibility hooks for common spawner systems.

Cash Mobs

Default mobs:

  • Iron Golem
  • Blaze
  • Slime

have:

"15%"

chance to drop:

"$1,000"

cash.

Everything configurable.

---

BLACK MARKET

Command:

"/blackmarket"

The Black Market refreshes once every 24 hours.

Default items:

  • End Crystals
  • Respawn Anchors
  • Glowstone
  • Golden Apples
  • Rare configurable items

Each item supports:

  • Price
  • Stock
  • Daily purchase limit
  • Required permission
  • Custom item
  • Refresh behavior

Black Market should feel exclusive and limited.

Prevent item duplication.

---

MAYOR NOAH

Theme: Luck / Drops

Lucky Drops

Mob drops:

"+15%"

Rare Finds

Rare drops:

"+10%"

Special — LUCKY DAY

Once every 24 hours:

Activate a 1-hour Lucky Day.

During Lucky Day:

  • Mob drop rates increase
  • Rare drop rates increase
  • Cash drops receive configurable multiplier
  • Optional rare-item chance increase

Downside

Shop buying prices:

"+5%"

---

  1. MAYOR EVENT ENGINE

Create a generic event engine so future Mayors can easily add events.

Every event supports:

  • Start time
  • Duration
  • Cooldown
  • Repeat interval
  • Manual activation
  • Automatic activation
  • Title
  • Subtitle
  • Chat message
  • Sound
  • Particles
  • Boss bar
  • Action bar
  • Rewards
  • Multipliers
  • Permission requirements

Events must be saved across restarts.

If the server restarts during an event, calculate the remaining event time and continue correctly.

---

  1. ELECTION END

When a term ends:

  1. Disable previous Mayor perks.
  2. Disable previous Mayor downside.
  3. Finish active Mayor events.
  4. Save Mayor statistics.
  5. Announce the outgoing Mayor.
  6. Start the next election.
  7. Select new candidates.
  8. Reset votes.
  9. Announce the election.

Announcement:

§6§lMAYOR ELECTION

§fThe previous Mayor's term has ended.

§eA new election is now open.

§7Vote using §f/mayor

---

  1. ELECTION HISTORY

Command:

"/mayor history"

Display previous Mayors.

Track:

  • Mayor name
  • Term duration
  • Vote count
  • Total votes
  • Events activated
  • Money generated
  • Money spent
  • Players affected
  • Election position

---

  1. MAYOR STATISTICS

Command:

"/mayor stats"

Display:

Current Mayor: Raven Term Remaining: 5d 12h

Events Activated: 4 Players Affected: 183 Money Generated: $4,283,000 Crates Spawned: 8 Crates Claimed: 7

Track statistics separately for each Mayor.

---

  1. ADMIN COMMANDS

Main:

/mayor /mayor vote <candidate> /mayor candidates /mayor current /mayor info <candidate> /mayor history /mayor stats

Admin:

/mayoradmin /mayoradmin start /mayoradmin end /mayoradmin setmayor <candidate> /mayoradmin setterm <duration> /mayoradmin startvote /mayoradmin endvote /mayoradmin votes /mayoradmin resetvotes /mayoradmin event <event> /mayoradmin spawncrate /mayoradmin spawncrate <x> <y> <z> /mayoradmin removecrate /mayoradmin setcrateworld <world> /mayoradmin reload /mayoradmin debug

---

  1. PERMISSIONS

Use granular permissions:

sulphermayor.use sulphermayor.vote sulphermayor.admin sulphermayor.admin.election sulphermayor.admin.events sulphermayor.admin.crates sulphermayor.admin.blackmarket sulphermayor.admin.reload

---

  1. ECONOMY INTEGRATION

Use Vault when available.

All monetary rewards must use the configured economy provider.

Never directly manipulate balances unless explicitly configured.

Support:

  • Player rewards
  • Cash notes
  • Bounties
  • Shop modifiers
  • Marketplace taxes
  • Mayor bonuses
  • Black Market purchases
  • Event rewards

Create transaction logs.

---

  1. CASH NOTE SYSTEM

Create a secure custom cash-note system.

Cash notes must use:

"PersistentDataContainer"

and a unique NamespacedKey.

Do NOT identify cash notes only through display names.

Cash notes must contain:

  • Value
  • Unique ID
  • Creation timestamp
  • Plugin identifier

Prevent:

  • Duplication
  • Item editing
  • Stack exploits
  • NBT manipulation
  • Double redemption

Provide configurable denominations.

---

  1. HEART FRAGMENT SYSTEM

Create the same security system for Heart Fragments.

Use:

  • PersistentDataContainer
  • Unique item identifier
  • Configurable crafting recipe
  • Configurable material
  • Configurable lore

Prevent duplication and illegal item creation.

---

  1. ANTI-EXPLOIT SYSTEM

The plugin must actively prevent Mayor reward abuse.

Prevent:

Kill Farming

Players repeatedly killing the same player should not generate unlimited rewards.

Implement configurable:

  • Kill cooldown
  • Victim cooldown
  • Daily reward limit
  • Minimum combat duration
  • Anti-alt detection where possible

Mob Farming

Prevent AFK farms from generating unlimited jackpot rewards.

Provide configurable reward cooldowns.

Bounty Farming

Prevent players from creating bounties between alts/friends solely to farm server-funded bonuses.

Crate Abuse

Only one active Contraband Crate.

Prevent:

  • Duplication
  • Double claiming
  • Chunk unloading exploits
  • Restart duplication

Black Market

Prevent:

  • Double purchases
  • Stock duplication
  • Inventory transaction exploits

---

  1. CLAIM INTEGRATION

Create a claim integration layer.

The plugin must support configurable hooks for common claim systems.

For example:

  • WorldGuard
  • GriefPrevention
  • Lands
  • Other supported claim APIs

The plugin should detect available integrations automatically.

If no claim plugin exists:

  • Disable claim-specific Mayor mechanics
  • Do NOT crash

---

  1. WARZONE SYSTEM

Allow administrators to configure a Warzone region.

The plugin must support:

  • World
  • Minimum X
  • Maximum X
  • Minimum Z
  • Maximum Z

Example:

warzone: enabled: true world: world min-x: -2500 max-x: 2500 min-z: -2500 max-z: 2500

Mayor mechanics can detect whether a player is inside the Warzone.

---

  1. WORLD BORDER / CONTRABAND SAFETY

Default server playable area:

10,000 × 10,000

The random Contraband location generator must:

  1. Read configured world border.
  2. Calculate safe X/Z range.
  3. Generate random coordinates.
  4. Check world chunk availability.
  5. Find safe surface Y.
  6. Reject water/lava.
  7. Reject dangerous blocks.
  8. Reject protected spawn.
  9. Reject forbidden regions.
  10. Retry if invalid.
  11. Spawn crate.
  12. Announce coordinates.

Never hardcode a single location.

---

  1. DISCORD WEBHOOK SYSTEM

Add optional Discord webhook integration.

Send logs for:

  • Election opened
  • Election closed
  • New Mayor
  • Vote results
  • Mayor event
  • Contraband spawned
  • Contraband claimed
  • Black Market purchase
  • Large cash rewards
  • Admin actions

Webhook messages should include:

  • Player
  • Mayor
  • Event
  • Amount
  • Coordinates
  • Timestamp

Every webhook URL must be configurable.

---

  1. CONFIGURATION

Create a complete and organized:

"config.yml"

Do NOT hardcode gameplay values.

Include configuration sections:

general: elections: candidates: mayors: events: economy: cash-notes: heart-fragments: contraband: black-market: warzone: claims: anti-exploit: discord: messages: sounds: titles: bossbars: database:

Every numerical value must be configurable.

---

  1. MESSAGES

Create:

"messages.yml"

Allow administrators to customize ALL player-facing messages.

Support placeholders:

%player% %mayor% %candidate% %votes% %time_remaining% %x% %y% %z% %reward% %event%

---

  1. GUI DESIGN

Create several GUIs:

Main Mayor GUI

Shows:

  • Current Mayor
  • Candidates
  • Election timer

Candidate GUI

Shows:

  • Candidate perks
  • Special
  • Downside
  • Vote button

Election Results GUI

Shows:

  • Vote distribution
  • Winner
  • Previous election

Black Market GUI

Shows:

  • Items
  • Prices
  • Stock
  • Player purchase limits

Admin GUI

Shows:

  • Current Mayor
  • Election status
  • Candidate management
  • Event controls
  • Contraband controls
  • Statistics
  • Configuration status

---

  1. VISUAL QUALITY

The plugin must feel premium.

Use:

  • Clean inventory layouts
  • Consistent SulpherSMP formatting
  • Titles
  • Subtitles
  • Action bars
  • Boss bars
  • Sounds
  • Particles
  • Holograms

Avoid:

  • Excessive emojis
  • Childish wording
  • Random rainbow colors
  • Overly complicated GUI layouts
  • Spammy broadcasts

---

  1. DATABASE

Use persistent storage.

Support:

  • SQLite by default
  • MySQL/MariaDB optionally

Store:

  • Current Mayor
  • Election data
  • Votes
  • Election history
  • Mayor statistics
  • Event state
  • Contraband state
  • Black Market state
  • Anti-abuse data

Use asynchronous database operations where appropriate.

---

  1. RESTART SAFETY

The plugin must be completely restart-safe.

After restart:

  • Mayor remains Mayor
  • Term timer continues
  • Election votes remain
  • Active event continues
  • Contraband crate remains tracked
  • Black Market stock remains correct
  • Cooldowns remain correct
  • Anti-farming cooldowns remain correct

Do not reset important state on reload.

---

  1. PERFORMANCE

The plugin must be optimized for a busy SMP.

Avoid:

  • Heavy repeating tasks
  • Constant database queries
  • Scanning the entire world
  • Unnecessary chunk loading
  • Memory leaks
  • Excessive particle spawning
  • Excessive console logging

Use scheduled tasks only when necessary.

---

  1. LOGGING

Provide useful logs such as:

[SulpherMayor] Election started. [SulpherMayor] Mayor elected: Raven [SulpherMayor] Contraband spawned at -1847, 71, 2634. [SulpherMayor] Contraband claimed by PlayerName. [SulpherMayor] Blood Moon started.

Add:

"/mayoradmin debug"

to show integration status:

Vault: ENABLED Claims: ENABLED WorldGuard: ENABLED Database: SQLite Warzone: CONFIGURED Contraband: ENABLED Discord: ENABLED

---

  1. PLUGIN STRUCTURE

Use clean modular architecture.

Recommended managers:

MayorManager ElectionManager CandidateManager EventManager ContrabandManager BlackMarketManager EconomyManager CashNoteManager HeartFragmentManager ClaimManager WarzoneManager AntiExploitManager GUIManager MessageManager SoundManager DatabaseManager DiscordManager ConfigManager

Use interfaces for integrations.

Keep responsibilities separated.

---

  1. DEPENDENCY HANDLING

Optional dependencies must NEVER cause startup failure.

Example:

If Vault is missing:

SulpherMayor economy features disabled.

If claim integration is missing:

SulpherMayor claim features disabled.

The plugin must still start.

---

  1. PLUGIN STARTUP

On startup display:

━━━━━━━━━━━━━━━━━━━━━━━━━━ SULPHER MAYOR ━━━━━━━━━━━━━━━━━━━━━━━━━━

Version: X.X.X

Economy: ✓ Claims: ✓ Database: ✓ Warzone: ✓ Contraband: ✓ Discord: ✓

Current Mayor: Raven Term Remaining: 5d 12h

SulpherMayor enabled successfully. ━━━━━━━━━━━━━━━━━━━━━━━━━━

---

  1. FINAL IMPLEMENTATION REQUIREMENT

Do NOT return pseudocode.

Do NOT return incomplete classes.

Do NOT leave methods as:

// TODO

Do NOT create fake APIs.

Produce a complete, compilable, production-ready plugin.

Include:

  • Full Java source
  • "plugin.yml"
  • "config.yml"
  • "messages.yml"
  • Database implementation
  • GUI implementation
  • Commands
  • Permissions
  • Event listeners
  • Mayor system
  • Election system
  • Candidate system
  • Contraband system
  • Black Market
  • Economy integration
  • Claim integration
  • Warzone integration
  • Anti-exploit system
  • Discord webhook integration
  • Installation instructions
  • Configuration instructions
  • Dependency information

The final plugin should be ready to compile and deploy on a modern Paper Minecraft server.

Most importantly:

Make SulpherMayor feel like a major server feature that players actively care about every election.

The Mayor should meaningfully change how players play SulpherSMP for the entire 7-day term, while recurring events and special mechanics create moments that bring the whole server together.

Kodari AI
KodariOct 10 at 7:21 am 8
SulpherMayor
A premium Minecraft plugin for SulpherSMP featuring a complete democratic Mayor election system with rotating candidates, persistent voting, and 7-day terms. Includes eight unique Mayor candidates with passive perks, special events, and downsides that meaningfully alter gameplay. Features a robust event engine with restart-safe timers, a Contraband Crate system with genuinely random world-border-safe locations, a Black Market GUI with daily refresh, secure cash-note and heart-fragment items using PersistentDataContainer, Vault economy integration, claim-system hooks, Warzone detection, anti-exploit protections, Discord webhook logging, SQLite/MySQL storage, and comprehensive admin commands. All gameplay values configurable through organized config and messages files, with polished GUIs, titles, sounds, and announcements throughout.
  1. Establish the plugin foundation, configurable candidate data, and restart-safe election storage.

  2. Add elections, mayor commands, and the polished inventory menus.

  3. Add mayor event mechanics, contraband, Black Market, and optional integrations/configuration.

  1. Foundation and persistent election storage: created. 2. Election commands and candidate GUIs: created. 3. I’m adding deployment metadata and the remaining supporting modules next.

Created the SulpherMayor project with persistent SQLite elections and votes, configurable rotating candidates, /mayor commands and candidate menus, term/history/stat tracking, mayor event timing, random in-border Contraband Crates, a stock-limited Black Market, Vault-based transactions, signed PDC cash notes, and basic kill-reward cooldowns. Added plugin.yml, config.yml, messages.yml, a SQLite dependency manifest, and a README with setup instructions.

This is not yet the complete production-ready system in the specification. WorldGuard/GriefPrevention/Lands claim mechanics and MySQL storage are not implemented; several mayor perks and downsides, bounty integration, mining/spawner hooks, and the requested admin/results GUIs, holograms, and boss bars are also missing. Those features need implementation before treating this as production-ready for the full SulpherSMP design.

devsu69_

Wheres the plugin where can i download it

Kodari AI
KodariOct 10 at 7:24 am 1

Click Compile in the top bar (on mobile: ⋮ → Compile Project), then click Compile in the window. When it succeeds, click Download on the build or Download {name}.jar in the chat.

Kodari can make mistakes. Review important code before using.
Files
src
manifest.kod
README.md
Code
21 2,350
src/main/java/com/sulphersmp/sulphermayor/SulpherMayorPlugin.java
package com.sulphersmp.sulphermayor;

import com.cryptomorin.xseries.XSound;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.PluginCommand;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.NamespacedKey;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.File;
import java.util.logging.Level;

public final class SulpherMayorPlugin extends JavaPlugin {
    private ElectionStore electionStore;
    private CandidateManager candidateManager;
    private ElectionManager electionManager;
    private MayorGuiManager guiManager;
    private EconomyProvider economyProvider;
    private MayorEventEngine eventEngine;
    private ContrabandManager contrabandManager;
    private BlackMarketManager blackMarketManager;
    private DiscordWebhookManager discordWebhookManager;
    private WarzoneManager warzoneManager;
    private SecureItemManager secureItemManager;
    private RewardMechanics rewardMechanics;
    private NamespacedKey crateKey;
    private FileConfiguration messages;

    @Override
    public void onEnable() {
        saveDefaultConfig();
        reloadMessages();
        try {
            electionStore = new ElectionStore(this);
        } catch (Exception exception) {
            getLogger().log(Level.SEVERE, "Could not initialize the SQLite election store; SulpherMayor cannot safely start.", exception);
            getServer().getPluginManager().disablePlugin(this);
            return;
        }
        candidateManager = new CandidateManager(this);
        electionManager = new ElectionManager(this, electionStore, candidateManager);
        guiManager = new MayorGuiManager(this);
        economyProvider = new EconomyProvider();
        discordWebhookManager = new DiscordWebhookManager(this);
        warzoneManager = new WarzoneManager(this);
        secureItemManager = new SecureItemManager(this, electionStore, economyProvider);
        rewardMechanics = new RewardMechanics(this, electionStore, economyProvider, secureItemManager);
        crateKey = new NamespacedKey(this, "contraband_crate");
        eventEngine = new MayorEventEngine(this, electionStore, warzoneManager);
        contrabandManager = new ContrabandManager(this, electionStore);
        blackMarketManager = new BlackMarketManager(this, electionStore, economyProvider);
        getServer().getPluginManager().registerEvents(guiManager, this);
        registerCommand("mayor", new MayorCommand(this));
        registerCommand("mayoradmin", new MayorAdminCommand(this));
        PluginCommand blackMarketCommand = getCommand("blackmarket");
        if (blackMarketCommand != null) blackMarketCommand.setExecutor((sender, command, label, args) -> {
            if (!(sender instanceof Player player)) { sender.sendMessage(message("player-only")); return true; }
            if (!player.hasPermission("sulphermayor.use")) { player.sendMessage(message("no-permission")); return true; }
            blackMarketManager.open(player);
            return true;
        });
        getServer().getScheduler().runTaskTimer(this, electionManager::tick, 20L, 20L);
        getLogger().info("SulpherMayor enabled. Economy: " + (hasVault() ? "Vault available" : "disabled") + "; claims: " + (hasClaimPlugin() ? "available" : "disabled") + "; storage: SQLite.");
        MayorCandidate active = candidateManager.get(electionManager.getMayorId());
        getLogger().info("Current Mayor: " + (active == null ? "none (election in progress)" : active.getName()) + "; remaining: " + electionManager.remaining());
    }

    private void registerCommand(String name, Object handler) {
        PluginCommand command = getCommand(name);
        if (command == null) {
            getLogger().severe("Command missing from plugin.yml: " + name);
            return;
        }
        if (handler instanceof MayorCommand executor) {
            command.setExecutor(executor);
            command.setTabCompleter(executor);
        } else if (handler instanceof MayorAdminCommand executor) {
            command.setExecutor(executor);
            command.setTabCompleter(executor);
        }
    }

    @Override
    public void onDisable() {
        if (electionStore != null) electionStore.close();
    }

    public void reloadMessages() {
        File file = new File(getDataFolder(), "messages.yml");
        if (!file.exists()) saveResource("messages.yml", false);
        messages = org.bukkit.configuration.file.YamlConfiguration.loadConfiguration(file);
    }

    public String message(String key, String... replacements) {
        String text = messages == null ? key : messages.getString(key, key);
        for (int index = 0; index + 1 < replacements.length; index += 2) text = text.replace(replacements[index], replacements[index + 1]);
        return color(text);
    }

    public void broadcastMessage(String key, String... replacements) {
        String text = message(key, replacements);
        for (String line : text.split("\\n")) Bukkit.broadcastMessage(line);
    }

    public String color(String text) { return ChatColor.translateAlternateColorCodes('&', text); }

    public void playConfiguredSound(Player player, String path) {
        if (!getConfig().getBoolean("sounds.enabled", true)) return;
        String key = getConfig().getString(path, "");
        if (key.isBlank()) return;
        XSound.matchXSound(key).ifPresent(sound -> sound.play(player));
    }

    public boolean hasVault() { return economyProvider != null && economyProvider.isAvailable(); }
    public boolean hasClaimPlugin() {
        return getConfig().getBoolean("claims.enabled", true) && (getServer().getPluginManager().getPlugin("WorldGuard") != null || getServer().getPluginManager().getPlugin("GriefPrevention") != null || getServer().getPluginManager().getPlugin("Lands") != null);
    }
    public ElectionStore getElectionStore() { return electionStore; }
    public CandidateManager getCandidateManager() { return candidateManager; }
    public ElectionManager getElectionManager() { return electionManager; }
    public MayorGuiManager getGuiManager() { return guiManager; }
    public EconomyProvider getEconomyProvider() { return economyProvider; }
    public MayorEventEngine getEventEngine() { return eventEngine; }
    public ContrabandManager getContrabandManager() { return contrabandManager; }
    public BlackMarketManager getBlackMarketManager() { return blackMarketManager; }
    public WarzoneManager getWarzoneManager() { return warzoneManager; }
    public SecureItemManager getSecureItemManager() { return secureItemManager; }
    public RewardMechanics getRewardMechanics() { return rewardMechanics; }
    public NamespacedKey crateKey() { return crateKey; }
    public void discordLog(String title, String body) { if (discordWebhookManager != null) discordWebhookManager.send(title, body); }
    public void addMayorStatistic(String mayorId, String statistic, long amount) {
        if (mayorId == null || mayorId.isBlank()) return;
        String key = "mayor-stats." + mayorId + "." + statistic;
        long current;
        try { current = Long.parseLong(electionStore.getState(key, "0")); }
        catch (NumberFormatException ignored) { current = 0L; }
        electionStore.setState(key, Long.toString(current + amount));
    }
}