MC/DuneRealmsGUI/src/main/java/com/dunerealms/gui/QuestMenus.java

473 lines
74 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.dunerealms.gui;
import com.google.gson.*;
import java.util.*;
import java.util.function.*;
import org.bukkit.*;
import org.bukkit.entity.Player;
import org.bukkit.event.*;
import org.bukkit.event.inventory.*;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.*;
import org.bukkit.plugin.java.JavaPlugin;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.event.ClickEvent;
/** Presentation and input only: every mutation is revalidated by the central quest engine. */
final class QuestMenus implements Listener {
private final JavaPlugin plugin;private final HouseBridge bridge;private final Consumer<Player> back;
private final Map<UUID,UUID> pending=new HashMap<>();
private final Map<UUID,PolQuestNpc.Role> roleScope=new HashMap<>();
private static final class Panel implements DuneMenuInventory {
final UUID owner;final GuiSession gate;final Map<Integer,Runnable> actions=new HashMap<>();final List<BedrockForms.Choice> choices=new ArrayList<>();final List<String> descriptionNotes=new ArrayList<>();final Inventory inventory;final String title;boolean journalView;String description="Your current J.A.R.V.I.S. mission journal";
Panel(Player p,String title){owner=p.getUniqueId();gate=new GuiSession(owner);this.title=title;inventory=Bukkit.createInventory(this,54,Component.text(title,NamedTextColor.GOLD));}
public Inventory getInventory(){return inventory;}
}
QuestMenus(JavaPlugin plugin,HouseBridge bridge,Consumer<Player> back){this.plugin=plugin;this.bridge=bridge;this.back=back;Bukkit.getPluginManager().registerEvents(this,plugin);}
void quartermaster(Player p,Runnable exchange,Runnable kits){var s=panel(p,"Gurney · Quartermaster");put(s,20,"Exchange","Buy and sell individual items",Material.EMERALD,exchange);put(s,22,"Missions & turn-ins","Collect your House T0 kit or repair its original armour.\nPrepare four parts: one iron ingot, leather, copper ingot and quartz.\nOther missions and rewards use your current central journal.",Material.WRITABLE_BOOK,()->open(p));put(s,24,"Stillsuit kits","Published clan, company and office kits",Material.NETHERITE_CHESTPLATE,kits);put(s,31,"Organisation workshop","Upgrade your held original with researched MK and rarity templates",Material.NETHERITE_UPGRADE_SMITHING_TEMPLATE,()->workshop(p,0));put(s,34,"Gurney\u0027s missions","Current bounty, campaign and ongoing duty missions",Material.BOOK,()->openRole(p,new PolQuestNpc.Role("gurney_halleck","Gurney Halleck",p.getWorld().getName(),"*",Set.of("bounty-jobs","war-service","repeatables","rd"),0)));put(s,49,"Close","Return to the world",Material.ARROW,p::closeInventory);show(p,s);}
private static String text(JsonObject row,String key,String fallback){return row.has(key)&&!row.get(key).isJsonNull()?row.get(key).getAsString():fallback;}
private static String dialogue(JsonObject row,String field,String fallback){return row.has("dialogue")&&row.get("dialogue").isJsonObject()?text(row.getAsJsonObject("dialogue"),field,fallback):fallback;}
private static boolean yes(JsonObject row,String key){return row.has(key)&&!row.get(key).isJsonNull()&&row.get(key).getAsBoolean();}
private static boolean website(JsonObject row){return row.has("executionRequirements")&&!row.get("executionRequirements").isJsonNull()&&yes(row.getAsJsonObject("executionRequirements"),"website")&&!yes(row.getAsJsonObject("executionRequirements"),"minecraft");}
private Panel panel(Player p,String title){var screen=new Panel(p,title);var filler=new ItemStack(Material.GRAY_STAINED_GLASS_PANE);var meta=filler.getItemMeta();meta.displayName(Component.empty());filler.setItemMeta(meta);for(int i=0;i<54;i++)screen.inventory.setItem(i,filler);return screen;}
private Panel journalPanel(Player player,String title){
var screen=panel(player,title);
screen.journalView=true;
return screen;
}
private void put(Panel panel,int slot,String title,String description,Material material,Runnable action){
var item=new ItemStack(material);var meta=item.getItemMeta();meta.displayName(Component.text(title,NamedTextColor.GOLD));meta.lore(Arrays.stream(description.split("\n")).map(line->Component.text(line,NamedTextColor.GRAY)).toList());item.setItemMeta(meta);panel.inventory.setItem(slot,item);
if(action==null){String note="\n\n"+title+"\n"+description;panel.description+=note;panel.descriptionNotes.add(note);}
if(action!=null){panel.actions.put(slot,action);panel.choices.add(new BedrockForms.Choice(title,description,action));}
}
private void show(Player p,Panel screen){if(BedrockForms.isBedrock(p)){BedrockForms.show(plugin,p,screen.title,screen.description,List.copyOf(screen.choices));return;}if(showDevelopmentView(p,screen))return;if(MCGUIMenus.show(p,screen.title,screen.description,screen.inventory,screen.actions,screen.gate))return;p.openInventory(screen.inventory);Bukkit.getScheduler().runTaskLater(plugin,screen.gate::expire,2400L);}
void close(){pending.clear();for(Player p:Bukkit.getOnlinePlayers())if(p.getOpenInventory().getTopInventory().getHolder() instanceof Panel)p.closeInventory();}
private record RefitQuote(JsonObject input,UUID world,long expires){}
private final Map<UUID,RefitQuote> refitQuotes=new HashMap<>();
void missionCommand(Player player,String[] args){
if(args.length==0){open(player);return;}
if(args[0].equalsIgnoreCase("workshop")){workshopCommand(player,args);return;}
String verb=args[0].toLowerCase(Locale.ROOT);
boolean list=verb.equals("list");
boolean starterAction=Set.of("obtain","parts","repair").contains(verb);
boolean roleStep=Set.of("dossier","cargo","partner").contains(verb);
boolean nativeStep=roleStep||Set.of("research","meat","supply","refine").contains(verb);
if((roleStep?args.length<3||args.length>5:list?args.length<2||args.length>4:args.length!=3)||!nativeStep&&!starterAction&&!Set.of("list","show","start","claim","briefing").contains(verb)||
!Set.of("personal","pol").contains(args[1].toLowerCase(Locale.ROOT))){
player.sendMessage("Use /missions list <personal|pol> [page] [branch] or /missions <show|start|claim|briefing> <personal|pol> <id>. POL steps: /missions <research|meat|supply|refine> pol <id>.");
return;
}
String kind=args[1].toLowerCase(Locale.ROOT);
int page;
try{page=list&&args.length>=3?Integer.parseInt(args[2]):1;}catch(NumberFormatException invalid){page=0;}
if(page<1||page>10000){player.sendMessage("Enter a mission page from 1 to 10000.");return;}
int offset=(page-1)*10;
String branchFilter=list&&args.length==4?args[3]:"";
roleScope.remove(player.getUniqueId());
var read=new JsonObject();read.addProperty("action","read");read.addProperty("kind",kind);
request(player,read,data->{
if(!"active".equals(text(data,"state",""))){player.sendMessage("No active quest season is available.");return;}
int listed=0;
for(var value:data.getAsJsonArray("quests")){
var row=value.getAsJsonObject();String id=text(row,"id","");
if(list){
String branch=text(row,"branch","");
if(text(row,"state","").equals("claimed")||!branchFilter.isEmpty()&&!branch.equalsIgnoreCase(branchFilter))continue;
int position=listed++;
if(position>=offset&&position<offset+10)player.sendMessage(id+" · "+text(row,"title","Mission")+" · "+text(row,"state","")+" · "+branch);
continue;
}
if(!id.equalsIgnoreCase(args[2]))continue;
if(website(row)&&!verb.equals("show")){website(player);return;}
String state=text(row,"state","");
if(starterAction){
String expected=verb.equals("obtain")?"S1-H-01":"S1-H-02";
if(kind.equals("personal")&&id.equals(expected)&&(yes(row,"canStart")||Set.of("active","completed","claimed").contains(state))){
starter(player,kind,text(row,"branch",""),0,row,verb,false);
}else player.sendMessage("This starter-equipment action is unavailable for the current mission.");
return;
}
if(roleStep){roleMissionCommand(player,kind,data,row,verb,Arrays.copyOfRange(args,3,args.length));return;}
if(nativeStep){nativeMissionStep(player,kind,row,verb);return;}
if(verb.equals("briefing")){
if(state.equals("active")&&!yes(row,"canClaim")&&text(row,"metric","").equals("citizen-introduction"))recordCitizenBriefing(player);
else player.sendMessage("This mission has no briefing to record.");
return;
}
if(verb.equals("show")){
player.sendMessage(id+" · "+text(row,"title","Mission")+" · "+state);
player.sendMessage(text(row,"objective","Complete the verified objective."));
player.sendMessage("Progress: "+text(row,"progress","0")+" / "+text(row,"target","0"));
if(website(row))website(player);
if(kind.equals("personal")&&id.equals("S1-H-01"))player.sendMessage("Starter kit: /missions obtain personal "+id);
if(kind.equals("personal")&&id.equals("S1-H-02"))player.sendMessage("Starter repair: /missions parts personal "+id+" or /missions repair personal "+id);
if(state.equals("active")&&!yes(row,"canClaim")&&text(row,"metric","").equals("citizen-introduction")){
player.sendMessage(CITIZEN_BRIEFING);
player.sendMessage("Record it with /missions briefing "+kind+" "+id+".");
}
}else if(verb.equals("claim")&&yes(row,"canClaim")||
verb.equals("start")&&yes(row,"canStart")&&!yes(row,"canClaim")&&!Set.of("active","completed","claimed").contains(state)&&
(!row.has("cooldownUntil")||row.get("cooldownUntil").isJsonNull()||row.get("cooldownUntil").getAsLong()<=System.currentTimeMillis())){
act(player,kind,text(row,"branch",""),0,row,verb,false);
}else player.sendMessage("That mission action is unavailable at its current progress.");
return;
}
if(!list)player.sendMessage("That mission is not available to you.");
else if(listed<=offset)player.sendMessage("No missions on this page.");
else if(listed>offset+10)player.sendMessage("Next: /missions list "+kind+" "+(offset/10+2)+(branchFilter.isEmpty()?"":" "+branchFilter));
});
}
private void roleMissionCommand(Player player,String kind,JsonObject data,JsonObject row,String verb,String[] args){
String field=verb.equals("dossier")?"dossier":"cargo";
if(!kind.equals("pol")||!text(row,"state","").equals("active")||yes(row,"canClaim")||
!row.has(field)||!row.get(field).isJsonObject()){
player.sendMessage("That NPC step is unavailable for this mission.");return;
}
var state=row.getAsJsonObject(field);
var role=PolQuestNpc.decisionContact(text(state,"role",""));
if(role==null){player.sendMessage("No current mission contact is available.");return;}
if(field.equals("dossier")){
if(yes(state,"complete")){player.sendMessage("This dossier is complete.");return;}
int stage=state.get("stage").getAsInt();
if(stage<2&&args.length==0){dossierStep(player,data,role,row,stage,null,false);return;}
if(stage>=2&&state.has("answers")){
var answers=state.getAsJsonArray("answers");
int answer=-1;
if(args.length==1)try{answer=Integer.parseInt(args[0])-1;}catch(NumberFormatException ignored){}
if(answer>=0&&answer<answers.size()){dossierStep(player,data,role,row,stage,answer,false);return;}
for(int index=0;index<answers.size();index++)player.sendMessage((index+1)+". "+answers.get(index).getAsString());
player.sendMessage("Use /missions dossier pol "+text(row,"id","")+" <answer-number>.");
}
return;
}
String phase=text(state,"stage","");
if(verb.equals("cargo")&&args.length==0&&
(Set.of("seal","pickup").contains(phase)||phase.equals("deliver")&&yes(state,"routeReady"))){
cargoMission(player,role,row,phase,false);return;
}
if(verb.equals("partner")&&phase.equals("partner")){
String status=text(state,"partnerState","");
if(status.equals("choose")&&state.has("candidates")){
for(var value:state.getAsJsonArray("candidates")){
var candidate=value.getAsJsonObject();String id=text(candidate,"id","");
if(args.length==2&&args[0].equalsIgnoreCase("offer")&&id.equalsIgnoreCase(args[1])){
cargoPartner(player,role,row,"offer",id,false);return;
}
if(args.length==0)player.sendMessage(text(candidate,"name","Candidate")+" · "+id);
}
if(args.length==0)player.sendMessage("Use /missions partner pol "+text(row,"id","")+" offer <partner-id>.");
else player.sendMessage("Choose a current eligible partner.");
return;
}
String pair=text(state,"pairId","");
if(!pair.isEmpty()&&args.length==1){
String action=args[0].toLowerCase(Locale.ROOT);
if(status.equals("accept")&&Set.of("accept","decline").contains(action)||
!Set.of("choose","accept").contains(status)&&action.equals("withdraw")){
cargoPartner(player,role,row,action,pair,false);return;
}
}
}
player.sendMessage("Current cargo step: "+phase+" · Contact: "+role.name()+".");
}
private void nativeMissionStep(Player player,String kind,JsonObject row,String operation){
String state=text(row,"state",""),branch=text(row,"branch","");
boolean active=state.equals("active"),available=active||yes(row,"canStart");
if(kind.equals("pol")){
switch(operation){
case "research"->{if(row.has("research")&&!state.equals("claimed")&&(available||state.equals("completed"))){research(player,kind,branch,0,row,false);return;}}
case "meat"->{if(Set.of("pol-jerboa-meat-25","pol-jerboa-meat-50").contains(text(row,"metric",""))&&!state.equals("claimed")&&!yes(row,"canClaim")&&available){meatTurnin(player,kind,branch,0,row,false);return;}}
case "supply"->{if(row.has("supply")&&!row.get("supply").isJsonNull()&&!state.equals("claimed")&&!yes(row,"canClaim")&&available){supplyTurnin(player,kind,branch,0,row,false);return;}}
case "refine"->{if(Set.of("POL-ELYTRA-REFINE","POL-ELYTRA-CONTAMINATE","POL-SPICE-UPGRADE-REFINE","POL-SPICE-UPGRADE-CONTAMINATE").contains(text(row,"id",""))&&(available||Set.of("completed","claimed").contains(state))){refine(player,kind,branch,0,row,false);return;}}
}
}
player.sendMessage("That NPC step is unavailable for this mission.");
}
void open(Player p){roleScope.remove(p.getUniqueId());var screen=journalPanel(p,"Mission journal");put(screen,20,"Personal Experience","Your personal mission branches",Material.BOOK,()->load(p,"personal",null,null,0));put(screen,24,"Reputation","Your Reputation mission branches",Material.ENCHANTED_BOOK,()->load(p,"pol",null,null,0));put(screen,31,"Political decisions","Decisions available to your current offices",Material.WRITABLE_BOOK,()->openDecisions(p,0));put(screen,45,"Website Mentat Report","Open your full online journal",Material.MAP,()->website(p));put(screen,49,"Back","Imperial Codex",Material.ARROW,()->back.accept(p));show(p,screen);}
void starterJournal(Player p){roleScope.remove(p.getUniqueId());load(p,"personal","h",null,0);}
void openRole(Player p,PolQuestNpc.Role role){roleScope.put(p.getUniqueId(),role);if(role.branches().contains("prologue")){housePrologue(p,role);return;}load(p,"pol",null,null,0);}
private void housePrologue(Player p,PolQuestNpc.Role role){var input=new JsonObject();input.addProperty("action","read");input.addProperty("kind","personal");input.addProperty("npcRole",role.key());request(p,input,data->{var screen=panel(p,"NPC turn-in · "+role.name());roleAvatar(screen,data,role);var state=data.has("housePrologue")&&data.get("housePrologue").isJsonObject()?data.getAsJsonObject("housePrologue"):new JsonObject();screen.description=text(state,"dialogue","");if(!yes(state,"required")){put(screen,13,"Welcome back","Your established preparation is retained. Use the existing Guild Navigator for passage.",Material.COMPASS,null);}else if(!role.key().equals(text(state,"mentor",""))){put(screen,13,"Choose your House","Meet the adviser of your current House. Visit the existing account and House selection flow.",Material.BOOK,null);put(screen,31,"Open account and House selection","Complete your account and select a House before returning.",Material.MAP,()->{p.closeInventory();p.sendMessage(Component.text("Open your account and House selection →",NamedTextColor.GOLD).clickEvent(ClickEvent.openUrl("https://cp.dunerealms.com/")));});}else{put(screen,13,"House Prologue","Account setup: "+(yes(state,"onboarding")?"Verified":"Pending")+"\nProfile: "+(yes(state,"profile")?"Verified":"Pending")+"\nMentat introduction: "+(yes(state,"introduced")?"Verified":"Pending")+"\nStarter equipment: "+(yes(state,"kit")?"Verified":"Pending"),Material.WRITABLE_BOOK,null);if(!yes(state,"introduced"))put(screen,31,"Acknowledge House introduction","Record this matching Mentat interaction. Rewards are issued automatically on verification.",Material.LIME_DYE,()->{try{bridge.houseMentorIntroduction(p,role.key());p.sendMessage("Introduction recorded. Reopen this contact to refresh your verified progress.");}catch(Exception error){p.sendMessage("Return to your matching House Mentat.");}});else if(!yes(state,"kit"))put(screen,31,"Your starter equipment","Open the existing starter objective; retain your original shovel and kit.",Material.WOODEN_SHOVEL,()->{p.closeInventory();p.performCommand("start");});else if(yes(state,"ready"))put(screen,31,"Your first passage is unlocked","Use the existing Guild Navigator to travel to your native world.",Material.COMPASS,null);else put(screen,31,"Finish account preparation","Complete the existing website profile and first sign-in requirements.",Material.MAP,()->{p.closeInventory();p.sendMessage(Component.text("Open your account →",NamedTextColor.GOLD).clickEvent(ClickEvent.openUrl("https://cp.dunerealms.com/")));});}put(screen,49,"Refresh","Check your actual progress and automatically recorded rewards",Material.ARROW,()->housePrologue(p,role));show(p,screen);});}
private boolean roleAllowed(JsonObject data,PolQuestNpc.Role role,JsonObject q){String branch=text(q,"branch","");boolean contact=q.has("dossier")&&!q.get("dossier").isJsonNull()&&role.key().equals(text(q.getAsJsonObject("dossier"),"role",""))||q.has("cargo")&&!q.get("cargo").isJsonNull()&&role.key().equals(text(q.getAsJsonObject("cargo"),"role",""));return data.has("npcContact")&&!data.get("npcContact").isJsonNull()&&(role.faction().equals("*")||role.faction().equals(text(data,"npcFaction",""))||branch.equals("company")&&role.key().equals("roma_atani"))&&(contact||role.branches().contains(branch)&&role.key().equals(text(q,"npcRole",text(q,"issuer",""))));}
private void roleAvatar(Panel screen,JsonObject data,PolQuestNpc.Role role){if(!data.has("npcContact")||data.get("npcContact").isJsonNull())return;var contact=data.getAsJsonObject("npcContact");var portrait=contact.has("avatar")&&contact.get("avatar").isJsonObject()?contact.getAsJsonObject("avatar"):new JsonObject();int cell=7;if(text(portrait,"atlas","").equals("https://cp.dunerealms.com/assets/mentat-portraits-atlas-v1.png")&&portrait.has("cell"))try{int candidate=portrait.get("cell").getAsInt();if(candidate>=0&&candidate<=7)cell=candidate;}catch(RuntimeException invalid){/* Existing account portrait fallback. */}put(screen,4,text(contact,"name",role.name()),text(contact,"role","Quest contact"),Material.PLAYER_HEAD,null);var item=screen.inventory.getItem(4);var meta=item.getItemMeta();meta.getPersistentDataContainer().set(new NamespacedKey("dunerealms","menu_art"),org.bukkit.persistence.PersistentDataType.STRING,"npc_avatar_"+cell);item.setItemMeta(meta);screen.inventory.setItem(4,item);var art=new ItemStack(Material.PAPER);var artMeta=art.getItemMeta();artMeta.displayName(Component.text("Realm artwork",NamedTextColor.GOLD));artMeta.getPersistentDataContainer().set(new NamespacedKey("dunerealms","menu_art"),org.bukkit.persistence.PersistentDataType.STRING,"npc_world_"+(role.key().equals("imperial_attendant")?"imperial":role.world()));art.setItemMeta(artMeta);screen.inventory.setItem(8,art); }
private void roleJournal(Player p,JsonObject data,PolQuestNpc.Role role,String selected){
var available=new ArrayList<JsonObject>();for(var e:data.getAsJsonArray("quests")){var q=e.getAsJsonObject();if(roleAllowed(data,role,q)&&!text(q,"state","").equals("claimed")&&(Set.of("active","completed").contains(text(q,"state",""))||yes(q,"canStart")))available.add(q);}
if(selected!=null){var row=available.stream().filter(q->selected.equals(text(q,"id",""))).findFirst().orElse(null);if(row!=null){roleSelected(p,data,role,row);return;}}
var screen=panel(p,"NPC dashboard · "+role.name());screen.description="";roleAvatar(screen,data,role);int active=0,ready=0,claimed=0;for(var e:data.getAsJsonArray("quests")){var q=e.getAsJsonObject();if(!roleAllowed(data,role,q))continue;if(text(q,"state","").equals("claimed"))claimed++;else if(yes(q,"canClaim"))ready++;else if(text(q,"state","").equals("active"))active++;}String stats=active+" active · "+ready+" ready · "+claimed+" claimed";if(data.has("npcSummary")&&data.get("npcSummary").isJsonObject()){var rep=data.getAsJsonObject("npcSummary");stats+="\nReputation "+text(rep,"xp","—")+" / "+text(rep,"nextXP","—");if(rep.has("percent")&&!rep.get("percent").isJsonNull())stats+="\nProgress: "+Math.max(0,Math.min(100,rep.get("percent").getAsInt()))+"%";}put(screen,5,"Mission overview",stats,Material.PAPER,null);var summary=screen.inventory.getItem(5);var meta=summary.getItemMeta();meta.getPersistentDataContainer().set(new NamespacedKey("dunerealms","menu_art"),org.bukkit.persistence.PersistentDataType.STRING,"npc_summary");summary.setItemMeta(meta);screen.inventory.setItem(5,summary);var ordered=new ArrayList<JsonObject>(available);ordered.sort(Comparator.comparingInt(q->Set.of("active","completed").contains(text(q,"state",""))?0:1));
int slot=9;for(var q:ordered){if(slot>=45)break;String status=Set.of("active","completed").contains(text(q,"state",""))?"Progress: "+text(q,"progress","0")+" / "+text(q,"target","1"):"Eligible to accept";put(screen,slot++,text(q,"title","Mission"),status+"\n"+text(q,"id","")+" · "+text(q,"objective",""),Material.WRITABLE_BOOK,()->roleSelected(p,data,role,q));}
if(ordered.isEmpty())put(screen,13,"No eligible missions","Read the website journal for the full record.",Material.MAP,null);
if(role.key().equals("esmar_tuek"))put(screen,47,role.world().equals("guild_lobby")?"Personal smuggler passage":"Smuggler return",role.world().equals("guild_lobby")?"Opt in with Esmar or board your paid one-hour personal route.":"Return to the Guild from your confirmed smuggler arrival.",Material.COMPASS,()->{if(role.world().equals("guild_lobby"))smugglerMenu(p,data,role);else try{bridge.returnSmuggler(p);}catch(Exception failure){p.sendMessage("Meet Esmar Tuek on Arrakis to return.");}});
if(Set.of("thufir_hawat","piter_de_vries","hasimir_fenring","roma_atani","imperial_attendant","stilgar","jessica_atreides","gaius_helen_mohiam","alia_atreides","edric","guild_navigator","duncan_idaho").contains(role.key()))put(screen,48,"POL decisions","See only current executable political decisions",Material.BOOK,()->openDecisions(p,0));put(screen,49,"Website journal","Full mission choices and history",Material.MAP,()->website(p));show(p,screen);
}
private void smugglerRequest(Player p,JsonObject input,Consumer<JsonObject> callback){try{bridge.questCharacterNpc(p,"esmar_tuek");}catch(Exception unavailable){p.sendMessage("Meet Esmar Tuek first.");return;}UUID id=p.getUniqueId(),world=p.getWorld().getUID(),operation=UUID.randomUUID();if(pending.putIfAbsent(id,operation)!=null)return;p.closeInventory();Bukkit.getScheduler().runTaskAsynchronously(plugin,()->{JsonObject result=null;String error=null;try{if(text(input,"action","").equals("smuggler_board")&&!bridge.worldOnline("arrakis"))throw new IllegalStateException("Arrakis is currently unavailable.");result=bridge.guild(id,input);}catch(Exception failure){error=failure.getMessage();}var response=result;String message=error;Bukkit.getScheduler().runTask(plugin,()->{if(!pending.remove(id,operation)||!p.isOnline()||!p.getWorld().getUID().equals(world))return;if(response==null){p.sendMessage(message==null?"The smuggler passage is unavailable.":message);return;}callback.accept(response);});});}
private void smugglerMenu(Player p,JsonObject data,PolQuestNpc.Role role){var input=new JsonObject();input.addProperty("action","smuggler_quote");smugglerRequest(p,input,quote->{var screen=panel(p,"NPC turn-in · "+role.name());screen.description="A personal smuggler passage is distinct from sanctioned Guild travel. Unsanctioned arrival may carry the existing in-game bounty.";roleAvatar(screen,data,role);if(!yes(quote,"eligible")){put(screen,13,"Ordinary Guild passage","Your current lawful route is available. Use the normal Guild Navigator.",Material.COMPASS,null);}else if(!yes(quote,"allowed")){put(screen,13,"Personal passage","Opt in with Esmar if ordinary Arrakis passage is unavailable. One hour from the verified introduction.",Material.COMPASS,null);put(screen,31,"Opt in to smuggling","Register the existing smuggler introduction and personal permission.",Material.LIME_DYE,()->{var introduction=data.getAsJsonArray("quests").asList().stream().map(JsonElement::getAsJsonObject).filter(q->text(q,"id","").equals("POL-SMUGGLERS-01")).findFirst().orElse(null);if(introduction==null){p.sendMessage("The current smuggler mission is unavailable.");return;}Runnable emit=()->{try{bridge.smugglerIntroduction(p);p.sendMessage("Introduction recorded. Reopen personal passage after J.A.R.V.I.S. verifies it.");}catch(Exception error){p.sendMessage("Meet Esmar Tuek in the Guild lobby.");}};if(yes(introduction,"canStart")&&!Set.of("active","completed","claimed").contains(text(introduction,"state",""))){var start=new JsonObject();start.addProperty("action","start");start.addProperty("kind","pol");start.addProperty("definitionId","POL-SMUGGLERS-01");start.addProperty("requestId",UUID.randomUUID().toString());start.addProperty("confirmed",true);request(p,start,ignored->emit.run());}else emit.run();});}else{long expiry=quote.get("permitExpiresAt").getAsLong();int price=quote.get("fareMinor").getAsInt();put(screen,13,"Personal passage to Arrakis","Fare: "+String.format(Locale.ROOT,"%.2f DM",price/100.0)+"\nPermission expires: "+java.time.Instant.ofEpochMilli(expiry)+"\nExisting unsanctioned-arrival rules apply.",Material.COMPASS,null);if(yes(quote,"affordable"))put(screen,31,"Book passage","Reserve this exact fare; payment settles only after arrival.",Material.LIME_DYE,()->{var board=new JsonObject();board.addProperty("action","smuggler_board");board.addProperty("requestId",UUID.randomUUID().toString());board.add("keyId",quote.get("keyId"));board.add("version",quote.get("version"));board.add("fareMinor",quote.get("fareMinor"));board.addProperty("destination","arrakis");smugglerRequest(p,board,ticket->{try{bridge.dispatchGuild(p,ticket);}catch(Exception error){p.sendMessage("The transfer was not dispatched; unused reservation expires.");}});});else put(screen,31,"Insufficient funds","Your personal central bank account must cover the fare.",Material.CLOCK,null);}put(screen,33,"Starter spice shovel","Open the existing starter objective for your original shovel; no duplicate issue.",Material.WOODEN_SHOVEL,()->{p.closeInventory();p.performCommand("start");});put(screen,49,"Back","Return to Esmar's missions",Material.ARROW,()->load(p,"pol",null,null,0));show(p,screen);});}
void decisionCommand(Player player,String[] args){
if(args.length==0){openDecisions(player,0);return;}
if(args[0].equalsIgnoreCase("enact")){enactDecisionCommand(player,args);return;}
if(args.length!=1||!args[0].matches("[A-Za-z0-9-]{1,32}")){player.sendMessage("Use /decisions [list|decision-id].");return;}
String requested=args[0].toUpperCase(Locale.ROOT);
var input=new JsonObject();input.addProperty("action","read");
request(player,input,data->{
var decisions=data.getAsJsonArray("decisions");
if(!requested.equals("LIST")){
for(var value:decisions){
var decision=value.getAsJsonObject();
if(!requested.equals(text(decision,"id","")))continue;
player.sendMessage(text(decision,"title","Decision")+" · "+requested);
String description=dialogue(decision,"introduction","");
if(!description.isBlank())player.sendMessage(description);
String fee=text(decision,"feeMinor","");
if(fee.matches("[0-9]+"))player.sendMessage("Base cost: "+new java.math.BigDecimal(fee).movePointLeft(2).toPlainString()+" DM");
var contact=PolQuestNpc.decisionContact(text(decision,"npcRole",""));
if(decision.has("accounts"))for(var entry:decision.getAsJsonArray("accounts")){
var account=entry.getAsJsonObject();
player.sendMessage("Account: "+text(account,"name","Funding account")+" · "+text(account,"id",""));
}
if(decision.has("parameters"))for(var entry:decision.getAsJsonArray("parameters")){
var option=entry.getAsJsonObject();
player.sendMessage("Parameter: "+text(option,"label","")+" · "+text(option,"value",""));
}
if(text(decision,"kind","").equals("website"))decisionWebsite(player,requested);
else if(contact!=null)player.sendMessage("Contact: "+contact.name());
return;
}
player.sendMessage("That decision is not currently available to you.");
return;
}
if(decisions.isEmpty()){player.sendMessage("No political decisions are currently available to you.");return;}
for(var value:decisions){
var decision=value.getAsJsonObject();
var contact=PolQuestNpc.decisionContact(text(decision,"npcRole",""));
player.sendMessage(text(decision,"title","Decision")+" · "+text(decision,"id","")+
(contact==null?"":" · "+contact.name()));
}
},true);
}
private void enactDecisionCommand(Player player,String[] args){
if(args.length<2||args.length>4||!args[1].matches("[A-Za-z0-9-]{1,32}")){
player.sendMessage("Use /decisions enact <id> [account-id] [parameter].");return;
}
var input=new JsonObject();input.addProperty("action","read");
request(player,input,data->{
for(var value:data.getAsJsonArray("decisions")){
var row=value.getAsJsonObject();
if(!args[1].equalsIgnoreCase(text(row,"id","")))continue;
if(text(row,"kind","").equals("website")){decisionWebsite(player,text(row,"id",""));return;}
var role=PolQuestNpc.decisionContact(text(row,"npcRole",""));
if(role==null){player.sendMessage("No current decision contact is available.");return;}
boolean funding=!row.has("fundingRequired")||yes(row,"fundingRequired");
boolean parameterRequired=row.has("parameters");
if(args.length!=2+(funding?1:0)+(parameterRequired?1:0)){
player.sendMessage("Review /decisions "+args[1]+" for the required account and options.");return;
}
String account=funding?args[2]:null;
String parameter=parameterRequired?args[funding?3:2]:null;
if(funding&&row.getAsJsonArray("accounts").asList().stream().map(JsonElement::getAsJsonObject)
.noneMatch(a->account.equals(text(a,"id",""))&&hasDecisionFunds(a,row))){
player.sendMessage("Choose an eligible account with enough available funds.");return;
}
if(parameterRequired&&row.getAsJsonArray("parameters").asList().stream().map(JsonElement::getAsJsonObject)
.noneMatch(option->parameter.equals(text(option,"value","")))){
player.sendMessage("Choose a current decision parameter.");return;
}
submitDecision(player,new JsonObject(),role,row,account,parameter,UUID.randomUUID(),false);
return;
}
player.sendMessage("That decision is not currently available to you.");
},true);
}
private static boolean hasDecisionFunds(JsonObject account,JsonObject row){
try{return new java.math.BigInteger(text(account,"availableMinor","0")).compareTo(new java.math.BigInteger(text(row,"feeMinor","0")))>=0;}
catch(NumberFormatException invalid){return false;}
}
void openDecisions(Player p,int page){
var input=new JsonObject();input.addProperty("action","read");
request(p,input,data->{
var screen=panel(p,"NPC dashboard decision · Political decisions");
screen.description="Decisions available to your current political offices and mandates.";
var decisions=data.getAsJsonArray("decisions");
int pageSize=27,last=Math.max(0,(decisions.size()-1)/pageSize),current=Math.min(page,last),slot=9;
for(int index=current*pageSize;index<Math.min(decisions.size(),(current+1)*pageSize);index++){
var row=decisions.get(index).getAsJsonObject();
var contact=PolQuestNpc.decisionContact(text(row,"npcRole",""));
if(contact==null)continue;
put(screen,slot++,text(row,"title","Decision"),"Required Reputation: "+text(row,"level","—")+"\n"+contact.name(),Material.BOOK,()->roleDecisionDetails(p,new JsonObject(),contact,row,null,null));
}
if(slot==9)put(screen,13,"No available decisions","Your current authority and cooldown determine what appears here.",Material.MAP,null);
if(current>0)put(screen,45,"Previous page","Earlier decisions",Material.ARROW,()->openDecisions(p,current-1));
if(current<last)put(screen,53,"Next page","More decisions",Material.ARROW,()->openDecisions(p,current+1));
put(screen,48,"Back","Mission journal",Material.ARROW,()->open(p));
put(screen,49,"Website","Decision definitions and history",Material.MAP,()->decisionWebsite(p));
show(p,screen);
},true);
}
private boolean showDevelopmentView(Player player,Panel screen){
boolean decisions=screen.title.startsWith("NPC dashboard decision · ");
boolean quests=screen.title.startsWith("NPC dashboard · ")||screen.title.startsWith("NPC turn-in · ")||
screen.title.startsWith("NPC next quest · ");
if(!decisions&&!quests&&!screen.journalView)return false;
String setting=decisions?"development.fullscreen-decisions-viewers":"development.fullscreen-quest-viewers";
String dialogue=screen.description;
for(int index=screen.descriptionNotes.size()-1;index>=0;index--){
String note=screen.descriptionNotes.get(index);
if(dialogue.endsWith(note))dialogue=dialogue.substring(0,dialogue.length()-note.length());
}
return NativeMenus.show(plugin,player,setting,screen.title,dialogue,screen.inventory,screen.actions,screen.gate,
screen.journalView?DecisionsViewTransport.Style.JOURNAL:DecisionsViewTransport.Style.AUTO,null);
}
private void decisionWebsite(Player p){decisionWebsite(p,null);}
private void decisionWebsite(Player p,String decision){p.closeInventory();String url="https://clans.dunerealms.com/#quests/quests?xp=pol&view=decisions";if(decision!=null&&decision.matches("[A-Z0-9-]{1,32}"))url+="&decision="+decision;p.sendMessage(Component.text("Review POL decisions on the website →",NamedTextColor.GOLD).clickEvent(ClickEvent.openUrl(url)));}
private void roleDecisionDetails(Player p,JsonObject contact,PolQuestNpc.Role role,JsonObject row,String account,String parameter){var screen=panel(p,"NPC turn-in decision · "+role.name());screen.description=dialogue(row,"introduction","");roleAvatar(screen,contact,role);String kind=text(row,"kind","");String fee=text(row,"feeMinor","0");String amount;try{amount=new java.math.BigDecimal(fee).movePointLeft(2).toPlainString()+" DM";}catch(NumberFormatException invalid){amount="—";}put(screen,13,text(row,"title","Decision"),"Required Reputation: "+text(row,"level","—")+"\nBase cost: "+amount+"\nAward: "+text(row,"reputation","—")+" Reputation",Material.BOOK,null);
if(kind.equals("website")){put(screen,31,"Open website workflow","This decision requires the existing website controls.",Material.MAP,()->decisionWebsite(p,text(row,"id","")));}
else if(account==null&&(!row.has("fundingRequired")||yes(row,"fundingRequired"))){int slot=18;for(var e:row.getAsJsonArray("accounts")){var a=e.getAsJsonObject();if(slot>=35)break;String id=text(a,"id","");try{if(new java.math.BigInteger(text(a,"availableMinor","0")).compareTo(new java.math.BigInteger(fee))<0)continue;}catch(NumberFormatException invalid){continue;}put(screen,slot++,text(a,"name","Funding account"),"Account "+text(a,"number","")+" · available "+new java.math.BigDecimal(text(a,"availableMinor","0")).movePointLeft(2).toPlainString()+" DM",Material.GOLD_INGOT,()->roleDecisionDetails(p,contact,role,row,id,parameter));}}
else if(row.has("parameters")&&parameter==null){int slot=18;for(var item:row.getAsJsonArray("parameters")){var value=item.getAsJsonObject();if(slot>=35)break;put(screen,slot++,text(value,"label","Parameter"),"Select this exact parameter",Material.PAPER,()->roleDecisionDetails(p,contact,role,row,account,text(value,"value","")));}}
else{String parameterLabel=parameter;if(parameter!=null&&row.has("parameters"))for(var entry:row.getAsJsonArray("parameters")){var option=entry.getAsJsonObject();if(parameter.equals(text(option,"value",""))){parameterLabel=text(option,"label",parameter);break;}}put(screen,22,"Decision terms",(account==null?"No separate funding required":"Funding account "+account)+(parameter==null?"":"\nParameter: "+parameterLabel),Material.GOLD_INGOT,null);UUID requestId=UUID.randomUUID();put(screen,31,"Enact decision","Record this decision through J.A.R.V.I.S. at "+role.name(),Material.LIME_DYE,()->submitDecision(p,contact,role,row,account,parameter,requestId,true));}
put(screen,49,"Back","Current executable decisions",Material.ARROW,()->openDecisions(p,0));show(p,screen);
}
private void submitDecision(Player player,JsonObject contact,PolQuestNpc.Role role,JsonObject row,String account,String parameter,UUID requestId,boolean reopen){
var input=new JsonObject();input.addProperty("action","execute");input.addProperty("npcRole",role.key());
input.addProperty("decisionId",text(row,"id",""));input.addProperty("requestId",requestId.toString());
if(account!=null)input.addProperty("sourceAccount",account);
if(parameter!=null)input.addProperty("parameter",parameter);
input.addProperty("confirmed",true);
decisionRequest(player,role,input,result->{
if(reopen)roleDecisionResult(player,contact,role,row,result);
else player.sendMessage("Decision recorded · "+text(result,"keyId","J.A.R.V.I.S."));
});
}
private void roleDecisionResult(Player p,JsonObject contact,PolQuestNpc.Role role,JsonObject row,JsonObject result){var screen=panel(p,"NPC next quest decision · "+role.name());screen.description=dialogue(row,"turnIn","");roleAvatar(screen,contact,role);put(screen,13,text(row,"title","Decision"),"Reference: "+text(result,"keyId","Recorded")+"\nReputation: "+text(result,"xp","—"),Material.LIME_DYE,null);put(screen,31,"Next decision","See the remaining current eligible decisions",Material.BOOK,()->openDecisions(p,0));put(screen,49,"Later","Return to the contact dashboard",Material.ARROW,()->load(p,"pol",null,null,0));show(p,screen);}
private void decisionRequest(Player p,PolQuestNpc.Role role,JsonObject input,Consumer<JsonObject> callback){try{bridge.questCharacterNpc(p,role.key());request(p,input,callback,true);}catch(Exception unavailable){p.sendMessage("Return to this political quest contact.");}}
private void roleSelected(Player p,JsonObject data,PolQuestNpc.Role role,JsonObject row){if(website(row)){details(p,"pol",data,text(row,"branch",""),0,row);return;}if(!Set.of("active","completed").contains(text(row,"state",""))){roleIntro(p,data,role,row);return;}details(p,"pol",data,text(row,"branch",""),0,row);}
private void roleIntro(Player p,JsonObject data,PolQuestNpc.Role role,JsonObject row){var screen=panel(p,"NPC next quest · "+role.name());screen.description=dialogue(row,"introduction","");roleAvatar(screen,data,role);put(screen,13,text(row,"title","Next mission"),text(row,"objective","")+"\nReputation: "+text(row,"xp","—"),Material.WRITABLE_BOOK,null);put(screen,30,"Accept","Accept exactly this mission",Material.LIME_DYE,()->act(p,"pol",text(row,"branch",""),0,row,"start"));put(screen,32,"Later","Return to the contact's mission dashboard",Material.ARROW,()->roleJournal(p,data,role,null));show(p,screen);}
private void roleThanks(Player p,JsonObject data,PolQuestNpc.Role role,JsonObject row){var screen=panel(p,"NPC turn-in · "+role.name());screen.description=dialogue(row,"turnIn","");roleAvatar(screen,data,role);put(screen,13,text(row,"title","Completed mission"),"Verified reward recorded through J.A.R.V.I.S.",Material.LIME_DYE,null);put(screen,31,"Next quest","Find the next eligible mission in this selected arc",Material.BOOK,()->roleNext(p,role,row));put(screen,49,"Later","Return to the mission dashboard",Material.ARROW,()->load(p,"pol",null,null,0));show(p,screen);}
private void roleNext(Player p,PolQuestNpc.Role role,JsonObject completed){var input=new JsonObject();input.addProperty("action","read");input.addProperty("kind","pol");input.addProperty("npcRole",role.key());request(p,input,data->{String id=text(completed,"id",""),branch=text(completed,"branch",""),metric=text(completed,"metric","");for(var e:data.getAsJsonArray("quests")){var q=e.getAsJsonObject();if(!branch.equals(text(q,"branch",""))||!yes(q,"canStart")||text(q,"state","").equals("claimed"))continue;boolean next=metric.equals(text(q,"metric",""));if(q.has("requires"))for(var req:q.getAsJsonArray("requires"))if(id.equals(req.getAsString()))next=true;if(!next)continue;if(roleAllowed(data,role,q)){roleSelected(p,data,role,q);return;}}roleJournal(p,data,role,null);});}
private void website(Player p){p.closeInventory();p.sendMessage(Component.text("Open your Mentat Report →",NamedTextColor.GOLD).clickEvent(ClickEvent.openUrl("https://clans.dunerealms.com/#quests/quests")));}
private void workshopCommand(Player player,String[] args){
UUID owner=player.getUniqueId();
if(args.length==2&&args[1].equalsIgnoreCase("apply")){
var quote=refitQuotes.remove(owner);
if(quote==null||!quote.world.equals(player.getWorld().getUID())||System.nanoTime()>=quote.expires){
player.sendMessage("Request a fresh workshop quote first.");return;
}
confirmRefit(player,quote.input);return;
}
if(!(args.length==2&&args[1].equalsIgnoreCase("list")||args.length==4&&args[1].equalsIgnoreCase("quote"))){
player.sendMessage("Use /missions workshop list, quote <kind> <organisation-id>, or apply.");return;
}
var input=new JsonObject();input.addProperty("action","read_refits");input.addProperty("kind","pol");
request(player,input,data->{
for(var value:data.getAsJsonArray("owners")){
var candidate=value.getAsJsonObject();
String kind=text(candidate,"kind",""),id=text(candidate,"id","");
if(args.length==2)player.sendMessage(text(candidate,"label","Workshop")+" · "+kind+" · "+id);
else if(kind.equalsIgnoreCase(args[2])&&id.equalsIgnoreCase(args[3])){
refitQuotes.remove(owner);
prepareRefit(player,candidate,false);return;
}
}
player.sendMessage(args.length==2?"Use /missions workshop quote <kind> <organisation-id>.":"Choose a workshop from your current authorised list.");
});
}
private void workshop(Player p,int page){var input=new JsonObject();input.addProperty("action","read_refits");input.addProperty("kind","pol");request(p,input,data->{var screen=panel(p,"Organisation workshop");var owners=data.getAsJsonArray("owners");int offset=page*36;for(int i=offset;i<Math.min(owners.size(),offset+36);i++){var owner=owners.get(i).getAsJsonObject();put(screen,i-offset,text(owner,"label","Organisation"),"Use your specialist’s researched MK and rarity for this organisation",Material.NETHERITE_UPGRADE_SMITHING_TEMPLATE,()->prepareRefit(p,owner));}if(owners.isEmpty())put(screen,22,"Specialist required","Your current organisation deed must grant equipment research authority.",Material.GRAY_DYE,null);if(page>0)put(screen,45,"Previous","Earlier organisations",Material.ARROW,()->workshop(p,page-1));if(offset+36<owners.size())put(screen,53,"Next","More organisations",Material.ARROW,()->workshop(p,page+1));put(screen,49,"Back","Mission journal",Material.ARROW,()->open(p));show(p,screen);});}
private void prepareRefit(Player p,JsonObject owner){prepareRefit(p,owner,true);}
private void prepareRefit(Player p,JsonObject owner,boolean reopen){try{var input=new JsonObject();input.addProperty("action","prepare_refit");input.addProperty("kind","pol");var selected=new JsonObject();selected.add("kind",owner.get("kind"));selected.add("id",owner.get("id"));input.add("owner",selected);input.add("snapshot",bridge.refitSnapshot(p));input.addProperty("requestId",UUID.randomUUID().toString());input.addProperty("npcUuid",bridge.starterNpc(p).toString());input.addProperty("confirmed",true);request(p,input,permit->{var plan=permit.getAsJsonObject("plan");var output=plan.getAsJsonObject("output");StringBuilder cost=new StringBuilder("Surrender the held original and:");for(var token:plan.getAsJsonObject("consume").getAsJsonArray("templates"))cost.append("\n1 ").append(token.getAsJsonObject().get("id").getAsString().replace("dr_","").replace('_',' '));if(!reopen){
refitQuotes.put(p.getUniqueId(),new RefitQuote(input.deepCopy(),p.getWorld().getUID(),System.nanoTime()+30_000_000_000L));
p.sendMessage("Refit to MK "+text(output,"equipmentMark","")+" · "+text(output,"quality","").replace('_',' ')+".");
p.sendMessage(cost.toString());p.sendMessage("Use /missions workshop apply within 30 seconds while holding the same original near Gurney.");
return;
}var screen=panel(p,"Review equipment refit");Material material=Material.matchMaterial(output.get("material").getAsString());put(screen,13,"MK "+output.get("equipmentMark").getAsString()+" · "+output.get("quality").getAsString().replace('_',' '),"Original identity, name, lore and wear retained.\nExisting enchantments scale with the next tier.\nReputation level "+plan.get("requiredReputationLevel").getAsString()+" required.\n"+cost,material==null?Material.NETHERITE_UPGRADE_SMITHING_TEMPLATE:material,null);put(screen,30,"Refit original",cost+"\nOne minute between refits. Review expires after 30 seconds.",Material.LIME_DYE,()->confirmRefit(p,input));put(screen,32,"Back","Return without consuming anything",Material.ARROW,()->workshop(p,0));show(p,screen);});}catch(Exception failure){p.sendMessage(Component.text(failure.getMessage()==null?"Hold your original near Gurney’s quartermaster.":failure.getMessage(),NamedTextColor.RED));}}
private void confirmRefit(Player p,JsonObject input){
try{
if(!input.get("snapshot").equals(bridge.refitSnapshot(p))||!input.get("npcUuid").getAsString().equals(bridge.starterNpc(p).toString())){
p.sendMessage("Hold the quoted original near the same quartermaster and request a new quote.");return;
}
}catch(Exception unavailable){p.sendMessage("Hold your original near Gurney’s quartermaster.");return;}
// Recheck the central deed/research after the player confirms the review.
// An appointment or organisation may have changed while that panel was open.
request(p,input,verified->{try{boolean done=bridge.refitEquipment(p,verified);p.sendMessage(Component.text(done?"Original equipment upgraded. Organisation name and MK are purple.":"This refit was already processed.",NamedTextColor.GREEN));}catch(Exception failure){p.sendMessage(Component.text(failure.getMessage()==null?"Refit not confirmed. Reopen the workshop.":failure.getMessage(),NamedTextColor.RED));}});
}
private void request(Player p,JsonObject input,Consumer<JsonObject> result){request(p,input,result,false);}
private void request(Player p,JsonObject input,Consumer<JsonObject> result,boolean decision){
UUID owner=p.getUniqueId();if(pending.containsKey(owner))return;UUID operation=UUID.randomUUID(),world=p.getWorld().getUID();pending.put(owner,operation);p.closeInventory();p.sendMessage(Component.text("Jarvis executing matrix",NamedTextColor.GOLD));
Bukkit.getScheduler().runTaskAsynchronously(plugin,()->{JsonObject data=null;String error=null;try{data=decision?bridge.decisions(owner,input):bridge.quests(owner,input);}catch(Exception failure){error=failure instanceof java.io.IOException?failure.getMessage():"The mission journal is unavailable. Reopen it before retrying.";}JsonObject received=data;String message=error;if(!plugin.isEnabled())return;
Bukkit.getScheduler().runTask(plugin,()->{if(!operation.equals(pending.get(owner)))return;pending.remove(owner);if(!p.isOnline()||!world.equals(p.getWorld().getUID()))return;if(message!=null){p.sendMessage(message);return;}if(p.getOpenInventory().getType()!=InventoryType.CRAFTING)return;result.accept(received);});
});
}
private void load(Player p,String kind,String branch,String selected,int page){var input=new JsonObject();input.addProperty("action","read");input.addProperty("kind",kind);var contact=roleScope.get(p.getUniqueId());if(contact!=null&&kind.equals("pol"))input.addProperty("npcRole",contact.key());request(p,input,data->{if(!"active".equals(text(data,"state",""))){p.sendMessage("No active quest season is available.");open(p);return;}var role=roleScope.get(p.getUniqueId());if(role!=null&&kind.equals("pol")){roleJournal(p,data,role,selected);return;}if(branch==null)branches(p,kind,data);else if(selected==null)quests(p,kind,data,branch,page);else{JsonObject row=null;for(var entry:data.getAsJsonArray("quests"))if(selected.equals(text(entry.getAsJsonObject(),"id","")))row=entry.getAsJsonObject();if(row==null)quests(p,kind,data,branch,page);else details(p,kind,data,branch,page,row);}});}
private void branches(Player p,String kind,JsonObject data){
var screen=journalPanel(p,kind.equals("pol")?"Reputation branches":"Personal mission branches");var branches=new LinkedHashMap<String,String>();for(var entry:data.getAsJsonArray("quests")){String id=text(entry.getAsJsonObject(),"branch","missions");branches.putIfAbsent(id,id);}
if(data.has("branches"))for(var entry:data.getAsJsonArray("branches")){var branch=entry.getAsJsonObject();String id=text(branch,"id","");if(branches.containsKey(id))branches.put(id,text(branch,"title",id));}
int slot=0;for(var branch:branches.entrySet()){if(slot>=45)break;String id=branch.getKey();put(screen,slot++,branch.getValue(),"Open this mission branch",Material.WRITABLE_BOOK,()->quests(p,kind,data,id,0));}put(screen,49,"Back","Mission journal",Material.ARROW,()->open(p));show(p,screen);
}
private void quests(Player p,String kind,JsonObject data,String branch,int page){
var rows=new ArrayList<JsonObject>();for(var entry:data.getAsJsonArray("quests")){var row=entry.getAsJsonObject();if(branch.equals(text(row,"branch","")))rows.add(row);}
int offset=page*36;var screen=journalPanel(p,"Missions · "+branch);for(int i=offset;i<Math.min(rows.size(),offset+36);i++){var row=rows.get(i);boolean web=website(row);put(screen,i-offset,text(row,"title","Quest"),text(row,"state","Pending")+"\n"+(web?"Website quest":"Minecraft / website quest")+"\n"+text(row,"progress","0")+" / "+text(row,"target","0"),web?Material.WRITABLE_BOOK:Material.LIGHT_BLUE_DYE,()->details(p,kind,data,branch,page,row));}
if(kind.equals("personal")&&branch.equals("e")){put(screen,36,"Official Spice Harvesting","Reputation careers · genuine harvested spice",Material.ORANGE_DYE,()->load(p,"pol","spice-harvesting",null,0));put(screen,38,"Smuggling Jobs","Native roaming smuggler contracts",Material.CHEST,()->load(p,"pol","smugglers",null,0));put(screen,40,"Bounty Jobs","Accept and complete an actual bounty",Material.MAP,()->load(p,"pol","bounty-jobs",null,0));}
if(kind.equals("pol")&&branch.equals("bounty-jobs"))put(screen,40,"View active bounties","Open /dune bounty on Arrakis",Material.PAPER,()->{p.closeInventory();p.performCommand("dune bounty");});
put(screen,45,"Branches","Choose another branch",Material.ARROW,()->branches(p,kind,data));if(page>0)put(screen,47,"Previous","Previous missions",Material.PAPER,()->quests(p,kind,data,branch,page-1));put(screen,49,"Refresh","Read current verified quest records",Material.CLOCK,()->load(p,kind,branch,null,page));if(offset+36<rows.size())put(screen,51,"Next","More missions",Material.PAPER,()->quests(p,kind,data,branch,page+1));show(p,screen);
}
private void details(Player p,String kind,JsonObject data,String branch,int page,JsonObject row){
var role=roleScope.get(p.getUniqueId());var screen=role!=null&&kind.equals("pol")?panel(p,"NPC turn-in · "+role.name()):journalPanel(p,"Quest dossier");if(role!=null&&kind.equals("pol")){screen.description=yes(row,"canClaim")?dialogue(row,"turnIn",""):dialogue(row,"context","");roleAvatar(screen,data,role);}String title=text(row,"title","Quest"),state=text(row,"state","Pending"),description=text(row,"objective","Complete the verified objective.")+"\nProgress: "+text(row,"progress","0")+" / "+text(row,"target","0")+"\nState: "+state+"\n"+(kind.equals("pol")?"Reputation: ":"XP: ")+text(row,"xp","Not configured");
if(row.has("personalXP")&&!row.get("personalXP").isJsonNull())description+="\nBase Personal XP: "+row.get("personalXP").getAsInt();if(row.has("baseDMMinor")&&!row.get("baseDMMinor").isJsonNull())description+="\nBase funded reward: "+String.format(Locale.ROOT,"%.2f DM",row.get("baseDMMinor").getAsLong()/100.0);
put(screen,13,title,description,website(row)?Material.WRITABLE_BOOK:Material.LIGHT_BLUE_DYE,null);
if(website(row))put(screen,31,"Open website journal","This objective belongs to the website",Material.MAP,()->website(p));
else if(yes(row,"canClaim"))put(screen,31,"Claim verified reward","Revalidate the objective and current reward",Material.LIME_DYE,()->act(p,kind,branch,page,row,"claim"));
else if(text(row,"metric","").equals("citizen-introduction")&&state.equals("active"))put(screen,31,"Read citizen briefing","Read and acknowledge your Imperial Citizen introduction",Material.BOOK,()->introduction(p,kind,data,branch,page,row));
else if(state.equals("completed")&&!yes(row,"rewardConfigured"))put(screen,31,"Reward policy unavailable","Your objective is verified. Its reward must be configured before claiming.",Material.GRAY_DYE,null);
else if(row.has("cooldownUntil")&&!row.get("cooldownUntil").isJsonNull()&&row.get("cooldownUntil").getAsLong()>System.currentTimeMillis())put(screen,31,"Mission cooling down","Available after "+java.time.Instant.ofEpochMilli(row.get("cooldownUntil").getAsLong()),Material.CLOCK,null);
else if(yes(row,"canStart")&&!state.equals("active")&&!state.equals("claimed")&&!state.equals("completed"))put(screen,31,"Start mission","Accept this objective through J.A.R.V.I.S.",Material.LIME_DYE,()->act(p,kind,branch,page,row,"start"));
else put(screen,31,state.equals("claimed")?"Reward claimed":"Awaiting verified progress","No reward can be issued from an unverified objective",Material.GRAY_DYE,null);
if(kind.equals("pol")&&Set.of("POL-ELYTRA-REFINE","POL-ELYTRA-CONTAMINATE","POL-SPICE-UPGRADE-REFINE","POL-SPICE-UPGRADE-CONTAMINATE").contains(text(row,"id",""))&&(yes(row,"canStart")||Set.of("active","completed","claimed").contains(state)))put(screen,33,"Refine at NPC","Stand near an Arrakis Smuggler.\nTurn in the ingredients shown in this quest.",Material.ORANGE_DYE,()->refine(p,kind,data,branch,page,row));
if(kind.equals("pol")&&text(row,"id","").equals("POL-SMUGGLERS-01")&&!state.equals("claimed")&&(yes(row,"canStart")||state.equals("active")))put(screen,33,"Meet the underground network","Stand near an Arrakis Smuggler.\nAccept Esmar Tuek’s introduction, then claim the quest.",Material.ORANGE_DYE,()->{try{bridge.smugglerIntroduction(p);p.sendMessage("Introduction recorded. Refresh this quest in a few seconds.");}catch(Exception failure){p.sendMessage(failure.getMessage()==null?"Visit an Arrakis Smuggler first.":failure.getMessage());}});
if(kind.equals("pol")&&Set.of("POL-BOUNTY-01","POL-BOUNTY-02").contains(text(row,"id",""))&&!state.equals("claimed"))put(screen,33,"View active bounty jobs","On Arrakis, use the native bounty list and accept a target.",Material.MAP,()->{p.closeInventory();p.performCommand("dune bounty");});
if(kind.equals("pol")&&text(row,"id","").equals("POL-ORDOS-03")&&state.equals("active")&&!yes(row,"canClaim"))put(screen,33,"Open Exchange","Buy one item from another seller. The actual settled central payment will verify this mission.",Material.GOLD_INGOT,()->{p.closeInventory();p.performCommand("exchange");});
if(kind.equals("pol")&&row.has("research")&&!state.equals("claimed")&&(yes(row,"canStart")||state.equals("active")||state.equals("completed")))put(screen,33,"Submit research samples","Stand near Gurney Halleck.\nSurrender the materials shown in this quest.",Material.SMITHING_TABLE,()->research(p,kind,branch,page,row));
if(kind.equals("pol")&&Set.of("pol-jerboa-meat-25","pol-jerboa-meat-50").contains(text(row,"metric",""))&&!state.equals("claimed")&&!yes(row,"canClaim")&&(yes(row,"canStart")||state.equals("active")))put(screen,33,"Surrender cooked Jerboa meat","Stand near Shadout Mapes on Arrakis.\nSurrender the required genuine cooked Jerboa meat; no reuse of previous turn-ins.",Material.COOKED_RABBIT,()->meatTurnin(p,kind,branch,page,row));
if(kind.equals("pol")&&row.has("supply")&&!row.get("supply").isJsonNull()&&!state.equals("claimed")&&!yes(row,"canClaim")&&(yes(row,"canStart")||state.equals("active"))){var supply=row.getAsJsonObject("supply");put(screen,33,"Surrender mission supplies","Stand near "+text(supply,"contact","the mission contact")+".\nSurrender "+supply.get("quantity").getAsInt()+" genuine "+text(supply,"label","supplies")+".",Material.CHEST,()->supplyTurnin(p,kind,branch,page,row));}
if(kind.equals("pol")&&role!=null&&row.has("dossier")&&!row.get("dossier").isJsonNull()&&!yes(row,"canClaim")&&state.equals("active")){var dossier=row.getAsJsonObject("dossier");String next=text(dossier,"role","");put(screen,22,"Mission contact",text(dossier,"dialogue","")+"\nNext: "+next.replace('_',' '),Material.WRITABLE_BOOK,null);if(role.key().equals(next)&&!yes(dossier,"complete")){int stage=dossier.get("stage").getAsInt();if(stage<2)put(screen,33,stage==0?"Record briefing":"Record witness clue","Confirm this actual NPC interaction",Material.BOOK,()->dossierStep(p,data,role,row,stage,null));else if(dossier.has("answers")){int n=0;for(var answer:dossier.getAsJsonArray("answers")){int i=n++;put(screen,34+i,answer.getAsString(),"Submit this conclusion",Material.PAPER,()->dossierStep(p,data,role,row,stage,i));}}}}
if(kind.equals("pol")&&role!=null&&row.has("cargo")&&!row.get("cargo").isJsonNull()&&state.equals("active")&&!yes(row,"canClaim")){var cargo=row.getAsJsonObject("cargo");String phase=text(cargo,"stage",""),target=text(cargo,"role","");put(screen,22,"Assigned manifest",text(cargo,"quantity","—")+" × "+text(cargo,"item","Cargo")+"\nNext contact: "+target.replace('_',' ')+" · "+text(cargo,"server","").replace('-',' '),Material.CHEST,null);if(role.key().equals(target)&&phase.equals("seal"))put(screen,33,"Seal original cargo","Surrender the required genuine supplies into your bound parcel",Material.CHEST,()->cargoMission(p,role,row,phase));if(role.key().equals(target)&&phase.equals("pickup"))put(screen,33,"Collect sealed cargo","Receive the original company-funded parcel assigned to you",Material.CHEST,()->cargoMission(p,role,row,phase));if(role.key().equals(target)&&phase.equals("deliver")){if(yes(cargo,"routeReady"))put(screen,33,"Deliver sealed parcel","Surrender the exact original cargo after the required confirmed passage",Material.PAPER,()->cargoMission(p,role,row,phase));else put(screen,33,"Confirmed passage required","Take the assigned Guild route after sealing or collecting your parcel",Material.CLOCK,null);}if(role.key().equals(target)&&phase.equals("partner")){String partner=text(cargo,"partnerState","");if(partner.equals("choose"))put(screen,33,"Choose a mission partner","Select a player with the matching active mission and current affiliation",Material.PLAYER_HEAD,()->cargoPartners(p,data,role,row,0));else if(partner.equals("accept")){put(screen,33,"Accept cooperative assignment","Confirm the exact incoming partner assignment",Material.LIME_DYE,()->cargoPartner(p,role,row,"accept",text(cargo,"pairId","")));put(screen,34,"Decline invitation","Close the unaccepted invitation without moving any cargo",Material.RED_DYE,()->cargoPartner(p,role,row,"decline",text(cargo,"pairId","")));}else{put(screen,33,"Waiting for your partner","Both players must expressly accept the exact cooperative assignment",Material.CLOCK,null);put(screen,34,"Withdraw invitation","Close the unaccepted invitation without moving any cargo",Material.RED_DYE,()->cargoPartner(p,role,row,"withdraw",text(cargo,"pairId","")));}}if(phase.equals("escort"))put(screen,33,"Escort the carrier","Complete your own confirmed Guild passage on the same assigned route within two minutes of your partner. The carrier delivers the parcel.",Material.COMPASS,null);if(phase.equals("wait"))put(screen,33,"Waiting for assigned carrier","The other accepted party must complete their assigned step.",Material.CLOCK,null);}
if(kind.equals("personal")&&(yes(row,"canStart")||Set.of("active","completed","claimed").contains(state))){
if(text(row,"id","").equals("S1-H-01"))put(screen,33,"Collect House T0 kit","Available directly from /start.\nFour Common MK 0 stillsuit pieces at half durability.\nOne Uncommon MK I wooden spice shovel.\nOne original kit per account and season.",Material.NETHERITE_CHESTPLATE,()->starter(p,kind,branch,page,row,"obtain"));
if(text(row,"id","").equals("S1-H-02")){put(screen,29,"Prepare four repair parts","Buy, craft with genuine spice or collect native 5% mob drops.\nRepair plate, Binding patch, Tool fitting, Calibration piece.\nOptional: prepare all four from the ordinary materials.",Material.IRON_INGOT,()->starter(p,kind,branch,page,row,"parts"));put(screen,33,"Surrender original kit & parts","Hand in the four original bound armour pieces\nand all four verified repair parts.\nThen claim this quest to receive the intact kit.",Material.ANVIL,()->starter(p,kind,branch,page,row,"repair"));}
}
if(row.has("recipe")&&!row.get("recipe").isJsonNull())put(screen,22,"Revealed recipe","Craft on Arrakis · Very Rare · MK XI\nNetherite | Membrane | Netherite\nIron | Diamond | Iron\nContaminated spice | Membrane | Contaminated spice",Material.ELYTRA,null);
put(screen,45,"Back","Mission selection",Material.ARROW,()->{var currentRole=roleScope.get(p.getUniqueId());if(currentRole!=null&&kind.equals("pol"))roleJournal(p,data,currentRole,null);else quests(p,kind,data,branch,page);});put(screen,49,"Refresh","Read current progress",Material.CLOCK,()->load(p,kind,branch,text(row,"id",""),page));show(p,screen);
}
private void refine(Player p,String kind,JsonObject data,String branch,int page,JsonObject row){refine(p,kind,branch,page,row,true);}
private void refine(Player p,String kind,String branch,int page,JsonObject row,boolean reopen){try{var input=new JsonObject();input.addProperty("action","prepare_refine");input.addProperty("kind","pol");input.addProperty("definitionId",text(row,"id",""));input.addProperty("requestId",UUID.randomUUID().toString());input.addProperty("npcUuid",bridge.refinerNpc(p).toString());input.addProperty("confirmed",true);request(p,input,permit->{try{bridge.refineSpice(p,permit);p.sendMessage(Component.text("Spice refined. Your quest receipt is queued for confirmation.",NamedTextColor.GREEN));if(reopen)load(p,kind,branch,text(row,"id",""),page);else p.sendMessage("NPC step submitted. Check /missions show pol "+text(row,"id","")+" for progress.");}catch(Exception failure){p.sendMessage(Component.text(failure.getMessage()==null?"Refinement unavailable. Reopen the quest.":failure.getMessage(),NamedTextColor.RED));}});}catch(Exception failure){p.sendMessage(Component.text(failure.getMessage()==null?"Visit an Arrakis Smuggler first.":failure.getMessage(),NamedTextColor.RED));}}
private void research(Player p,String kind,String branch,int page,JsonObject row){research(p,kind,branch,page,row,true);}
private void research(Player p,String kind,String branch,int page,JsonObject row,boolean reopen){try{var input=new JsonObject();input.addProperty("action","prepare_research");input.addProperty("kind","pol");input.addProperty("definitionId",text(row,"id",""));input.addProperty("requestId",UUID.randomUUID().toString());input.addProperty("npcUuid",bridge.starterNpc(p).toString());input.addProperty("confirmed",true);request(p,input,permit->{try{bridge.research(p,permit);if(reopen)load(p,kind,branch,text(row,"id",""),page);else p.sendMessage("NPC step submitted. Check /missions show pol "+text(row,"id","")+" for progress.");}catch(Exception failure){p.sendMessage(Component.text(failure.getMessage()==null?"Research receipt pending. Refresh your quest.":failure.getMessage(),NamedTextColor.RED));}});}catch(Exception failure){p.sendMessage(Component.text(failure.getMessage()==null?"Visit Gurney Halleck.":failure.getMessage(),NamedTextColor.RED));}}
private void meatTurnin(Player p,String kind,String branch,int page,JsonObject row){meatTurnin(p,kind,branch,page,row,true);}
private void meatTurnin(Player p,String kind,String branch,int page,JsonObject row,boolean reopen){try{var input=new JsonObject();input.addProperty("action","prepare_husbandry_turnin");input.addProperty("kind","pol");input.addProperty("definitionId",text(row,"id",""));input.addProperty("requestId",UUID.randomUUID().toString());input.addProperty("npcUuid",bridge.questCharacterNpc(p,"shadout_mapes").toString());input.addProperty("confirmed",true);request(p,input,permit->{try{bridge.husbandryTurnin(p,permit);if(reopen)load(p,kind,branch,text(row,"id",""),page);else p.sendMessage("NPC step submitted. Check /missions show pol "+text(row,"id","")+" for progress.");}catch(Exception failure){p.sendMessage(failure.getMessage()==null?"Meat turn-in not confirmed.":failure.getMessage());}});}catch(Exception failure){p.sendMessage(failure.getMessage()==null?"Visit Shadout Mapes on Arrakis.":failure.getMessage());}}
private void supplyTurnin(Player p,String kind,String branch,int page,JsonObject row){supplyTurnin(p,kind,branch,page,row,true);}
private void supplyTurnin(Player p,String kind,String branch,int page,JsonObject row,boolean reopen){try{var input=new JsonObject();input.addProperty("action","prepare_pol_supply");input.addProperty("kind","pol");input.addProperty("definitionId",text(row,"id",""));input.addProperty("requestId",UUID.randomUUID().toString());input.addProperty("npcUuid",bridge.questCharacterNpc(p,row.getAsJsonObject("supply").get("role").getAsString()).toString());input.addProperty("confirmed",true);request(p,input,permit->{try{bridge.polSupplyTurnin(p,permit);if(reopen)load(p,kind,branch,text(row,"id",""),page);else p.sendMessage("NPC step submitted. Check /missions show pol "+text(row,"id","")+" for progress.");}catch(Exception failure){p.sendMessage(failure.getMessage()==null?"Supply turn-in not confirmed.":failure.getMessage());}});}catch(Exception failure){p.sendMessage(failure.getMessage()==null?"Visit the named quest contact.":failure.getMessage());}}
private void dossierStep(Player p,JsonObject data,PolQuestNpc.Role role,JsonObject row,int stage,Integer answer){dossierStep(p,data,role,row,stage,answer,true);}
private void dossierStep(Player p,JsonObject data,PolQuestNpc.Role role,JsonObject row,int stage,Integer answer,boolean reopen){try{var input=new JsonObject();input.addProperty("action","dossier_step");input.addProperty("kind","pol");input.addProperty("definitionId",text(row,"id",""));input.addProperty("requestId",UUID.randomUUID().toString());input.addProperty("confirmed",true);input.addProperty("npcRole",role.key());input.addProperty("npcUuid",bridge.questCharacterNpc(p,role.key()).toString());input.addProperty("stage",stage);if(answer!=null)input.addProperty("answer",answer);request(p,input,result->{if(!reopen){p.sendMessage(text(result,"dialogue","Dossier step recorded."));p.sendMessage(yes(result,"complete")?"Dossier complete. Claim the verified reward.":"Next contact: "+text(result,"nextRole","").replace('_',' '));return;}var screen=panel(p,"NPC turn-in · "+role.name());screen.description=text(result,"dialogue","");roleAvatar(screen,data,role);put(screen,13,text(row,"title","Mission"),yes(result,"complete")?"Completed · return to claim the verified reward":"Next contact: "+text(result,"nextRole","").replace('_',' '),Material.WRITTEN_BOOK,null);put(screen,31,"Continue","Return to current mission",Material.LIME_DYE,()->load(p,"pol",text(row,"branch",""),text(row,"id",""),0));show(p,screen);});}catch(Exception failure){p.sendMessage("Visit the exact named mission contact.");}}
private void cargoMission(Player p,PolQuestNpc.Role role,JsonObject row,String phase){cargoMission(p,role,row,phase,true);}
private void cargoMission(Player p,PolQuestNpc.Role role,JsonObject row,String phase,boolean reopen){try{var input=new JsonObject();input.addProperty("action","prepare_pol_cargo");input.addProperty("kind","pol");input.addProperty("definitionId",text(row,"id",""));input.addProperty("requestId",UUID.randomUUID().toString());input.addProperty("confirmed",true);input.addProperty("npcRole",role.key());input.addProperty("npcUuid",bridge.questCharacterNpc(p,role.key()).toString());input.addProperty("phase",phase);request(p,input,permit->{try{bridge.polCargo(p,permit);if(reopen)load(p,"pol",text(row,"branch",""),text(row,"id",""),0);else p.sendMessage("Cargo step submitted. Use /missions show pol "+text(row,"id","")+" to review progress.");}catch(Exception failure){p.sendMessage(failure.getMessage()==null?"Cargo not confirmed.":failure.getMessage());}});}catch(Exception unavailable){p.sendMessage("Visit the exact assigned cargo contact.");}}
private void cargoPartners(Player p,JsonObject data,PolQuestNpc.Role role,JsonObject row,int page){var cargo=row.getAsJsonObject("cargo");var screen=panel(p,"NPC turn-in · "+role.name());screen.description="";roleAvatar(screen,data,role);var candidates=cargo.has("candidates")?cargo.getAsJsonArray("candidates"):new JsonArray();int offset=page*30,slot=9;for(int i=offset;i<Math.min(offset+30,candidates.size());i++){var candidate=candidates.get(i).getAsJsonObject();String id=text(candidate,"id","");put(screen,slot++,text(candidate,"name","Eligible partner"),"Offer this exact cooperative assignment",Material.PLAYER_HEAD,()->cargoPartner(p,role,row,"offer",id));}if(candidates.size()==0)put(screen,13,"No current eligible partners","A matching active mission and current affiliation are required.",Material.CLOCK,null);if(page>0)put(screen,45,"Previous","More eligible partners",Material.ARROW,()->cargoPartners(p,data,role,row,page-1));if(offset+30<candidates.size())put(screen,53,"Next","More eligible partners",Material.ARROW,()->cargoPartners(p,data,role,row,page+1));put(screen,49,"Back","Selected mission",Material.ARROW,()->details(p,"pol",data,text(row,"branch",""),0,row));show(p,screen);}
private void cargoPartner(Player p,PolQuestNpc.Role role,JsonObject row,String phase,String id){cargoPartner(p,role,row,phase,id,true);}
private void cargoPartner(Player p,PolQuestNpc.Role role,JsonObject row,String phase,String id,boolean reopen){try{var input=new JsonObject();input.addProperty("action","cargo_partner");input.addProperty("kind","pol");input.addProperty("definitionId",text(row,"id",""));input.addProperty("requestId",UUID.randomUUID().toString());input.addProperty("confirmed",true);input.addProperty("npcRole",role.key());input.addProperty("npcUuid",bridge.questCharacterNpc(p,role.key()).toString());input.addProperty("phase",phase);input.addProperty(phase.equals("offer")?"partnerId":"pairId",id);request(p,input,result->{if(reopen)load(p,"pol",text(row,"branch",""),text(row,"id",""),0);else p.sendMessage("Cooperative assignment updated.");});}catch(Exception unavailable){p.sendMessage("Meet Edric with your current cooperative mission.");}}
private void starter(Player p,String kind,String branch,int page,JsonObject row,String operation){starter(p,kind,branch,page,row,operation,true);}
private void starter(Player p,String kind,String branch,int page,JsonObject row,String operation,boolean reopen){try{var input=new JsonObject();input.addProperty("action","prepare_starter");input.addProperty("kind","personal");input.addProperty("definitionId",text(row,"id",""));input.addProperty("operation",operation);input.addProperty("requestId",UUID.randomUUID().toString());input.addProperty("access","journal");input.addProperty("confirmed",true);request(p,input,permit->{try{bridge.starterKit(p,permit);if(reopen)load(p,kind,branch,text(row,"id",""),page);else p.sendMessage("Starter equipment action submitted. Check /missions show personal "+text(row,"id","")+" for progress.");}catch(Exception failure){p.sendMessage(Component.text(failure.getMessage()==null?"Your equipment exchange remains available. Reopen the quest.":failure.getMessage(),NamedTextColor.RED));}});}catch(Exception failure){p.sendMessage(Component.text(failure.getMessage()==null?"Open /start in Survival or Adventure mode.":failure.getMessage(),NamedTextColor.RED));}}
private static final String CITIZEN_BRIEFING="Your House determines normal travel authority.\nGuild travel uses boarding windows and your central bank.\nClan and company actions follow current deeds.\nBlue missions require ingame actions or item turn-ins.\nWebsite missions use your linked website account.\nRead your Mentat Report for current news and duties.";
private void recordCitizenBriefing(Player player){
try{
bridge.citizenIntroduction(player);
player.closeInventory();
player.sendMessage(Component.text("Citizen briefing submitted. Check the mission in a few seconds to claim its verified reward.",NamedTextColor.GREEN));
}catch(Exception unavailable){player.sendMessage("The briefing could not be recorded. Try again while the mission is active.");}
}
private void introduction(Player p,String kind,JsonObject data,String branch,int page,JsonObject row){
var screen=panel(p,"Imperial Citizen briefing");
put(screen,13,"Welcome, Imperial Citizen",CITIZEN_BRIEFING,Material.WRITTEN_BOOK,null);
put(screen,30,"Record briefing","Record that you have read the Imperial Citizen briefing",Material.LIME_DYE,()->recordCitizenBriefing(p));
put(screen,32,"Back","Return to the mission",Material.ARROW,()->details(p,kind,data,branch,page,row));show(p,screen);
}
private void act(Player p,String kind,String branch,int page,JsonObject row,String action){act(p,kind,branch,page,row,action,true);}
private void act(Player p,String kind,String branch,int page,JsonObject row,String action,boolean reopen){var input=new JsonObject();input.addProperty("action",action);input.addProperty("kind",kind);input.addProperty("definitionId",text(row,"id",""));input.addProperty("requestId",UUID.randomUUID().toString());input.addProperty("confirmed",true);if(action.equals("claim"))input.add("revision",row.get("revision"));request(p,input,result->{p.sendMessage(Component.text(action.equals("claim")?"Verified quest reward recorded.":"Mission accepted.",NamedTextColor.GREEN));if(action.equals("claim")&&text(row,"id","").equals("S1-H-02"))try{bridge.refreshKits(p);}catch(Exception unavailable){p.sendMessage("Your intact replacement remains queued for delivery.");}if(!reopen)return;var role=roleScope.get(p.getUniqueId());if(action.equals("claim")&&role!=null&&kind.equals("pol")){var read=new JsonObject();read.addProperty("action","read");read.addProperty("kind","pol");read.addProperty("npcRole",role.key());request(p,read,data->roleThanks(p,data,role,row));return;}load(p,kind,branch,text(row,"id",""),page);});}
@EventHandler public void click(InventoryClickEvent e){if(!(e.getView().getTopInventory().getHolder() instanceof Panel panel))return;e.setCancelled(true);if(!(e.getWhoClicked() instanceof Player p)||!panel.owner.equals(p.getUniqueId())||e.getClickedInventory()!=panel.inventory||e.getClick()!=ClickType.LEFT)return;var action=panel.actions.get(e.getRawSlot());if(action!=null&&panel.gate.claim(p.getUniqueId()))Bukkit.getScheduler().runTask(plugin,()->{if(p.isOnline()&&p.getOpenInventory().getTopInventory()==panel.inventory)action.run();});}
@EventHandler public void drag(InventoryDragEvent e){if(e.getView().getTopInventory().getHolder() instanceof Panel)e.setCancelled(true);}
@EventHandler public void closed(InventoryCloseEvent e){if(e.getInventory().getHolder() instanceof Panel panel)panel.gate.expire();}
@EventHandler public void quit(PlayerQuitEvent e){pending.remove(e.getPlayer().getUniqueId());roleScope.remove(e.getPlayer().getUniqueId());refitQuotes.remove(e.getPlayer().getUniqueId());}
}