using System; using System.IO; using System.Linq; using KernelPanic.Combat; using KernelPanic.Core; using KernelPanic.Data; using KernelPanic.Meta; using KernelPanic.Run; using UnityEngine.UIElements; namespace KernelPanic.UI { internal sealed class TutorialFlow : IDisposable { private readonly VisualElement _overlay; private readonly RunManager _run; private readonly CombatManager _combat; private readonly CardDatabase _cards; private readonly LanguageDeckDatabase _languages; private readonly SaveService _save; private readonly Action _returnToMenu; private TutorialSpotlight _spotlight; private Action _refresh; private int _lesson, _shopStep; private bool _leaving, _resuming; private string _renderKey, _error; public TutorialGuide Guide { get; private set; } public bool Reading => Guide.Reading; public int Lesson => _lesson; public TutorialFlow(VisualElement overlay, RunManager run, CombatManager combat, CardDatabase cards, LanguageDeckDatabase languages, SaveService save, RunConfig config, Action returnToMenu) { _overlay = overlay; _run = run; _combat = combat; _cards = cards; _languages = languages; _save = save; _lesson = config.TutorialLesson; _returnToMenu = returnToMenu; _resuming = _lesson > 1; SetGuide(_lesson); } public void SetRefresh(Action refresh) => _refresh = refresh; private void Redraw() { if (_refresh != null) _refresh(); else Refresh(); } private void SetGuide(int lesson) { _spotlight?.Dispose(); _spotlight = null; Guide = new TutorialGuide(lesson); _combat.TutorialGuide = Guide; _combat.TutorialReading = true; _renderKey = null; } public void ObserveCard(ResolutionTrack track) => Guide.CardPlayed(track); public void ObserveResolved(ResolutionTrack track) => Guide.CardResolved(track); public void ObservePhase(TurnPhase phase) => Guide.PhaseChanged(phase); public void UpdateState() { if (!_resuming) Guide.Update(_combat); } public void Review() => Redraw(); public void AdvancePage() { if (_leaving || _resuming) return; Guide.Acknowledge(_combat); Redraw(); } public void ResumeSecondWave() { if (!_resuming) return; _resuming = false; if (!_combat.ContinueTutorialWave()) throw new InvalidDataException("Training checkpoint is not a completed lesson boundary."); } public void Refresh() { if (_leaving || _resuming) return; UpdateState(); if (Guide.Active && !_combat.RunFinished) { _overlay.RemoveFromClassList("tutorial-overlay"); _spotlight ??= new TutorialSpotlight(_overlay, AdvancePage); _spotlight.Show(Guide, _combat); return; } _spotlight?.Dispose(); _spotlight = null; bool cleared = _combat.AwaitingWaveContinue, lost = _combat.RunFinished; if (!cleared && !lost) { _overlay.RemoveFromClassList("tutorial-overlay"); _overlay.Clear(); _overlay.style.display = DisplayStyle.None; _renderKey = null; return; } if (cleared && _lesson < TutorialCampaign.LessonCount && !_run.RepositoryVisitActive) _run.GenerateRepositoryOffers(_cards, _languages); bool purchased = _run.RepositoryOffers.Any(offer => offer.Sold); string key = $"{_lesson}:{cleared}:{lost}:{_shopStep}:{purchased}:{_error}"; if (_renderKey == key) return; _renderKey = key; _overlay.Clear(); _overlay.AddToClassList("tutorial-overlay"); _overlay.style.display = DisplayStyle.Flex; var panel = TerminalLayout.Section(lost ? "Practice ended" : _lesson == 1 ? "Wave one cleared / repository" : _lesson < TutorialCampaign.LessonCount ? "Wave two cleared" : "Training complete", "TutorialDialog"); panel.AddToClassList("tutorial-dialog"); var scroll = new ScrollView(ScrollViewMode.Vertical) { name = "TutorialCopy" }; scroll.style.flexShrink = 1; scroll.style.minHeight = 0; scroll.horizontalScrollerVisibility = ScrollerVisibility.Hidden; panel.Add(scroll); Button action; if (lost) { scroll.Add(TerminalLayout.BodyText("Retry this wave from its start. Your purchased upgrade is saved; your collection is safe.")); action = new Button(RestartLesson) { text = "Retry training", name = "TutorialRetry" }; } else if (_lesson == 1) { var bits = TerminalLayout.Heading($"{_run.Bits} Bits available", "TutorialShopBits"); scroll.Add(bits); if (_shopStep == 0) { bits.AddToClassList("tutorial-shop-highlight"); scroll.Add(TerminalLayout.BodyText("Spend combat Bits here to improve this run. Your permanent currencies are separate.")); action = new Button(() => { _shopStep = 1; Redraw(); }) { text = "Show an upgrade", name = "TutorialShopNext" }; } else { // A real card patch keeps the five-card teaching hand intact for the scheduler lesson. var offer = _run.RepositoryOffers.FirstOrDefault(item => item.Kind == RepositoryOfferKind.CardUpgrade); if (offer == null) throw new InvalidOperationException("Training shop needs a card upgrade."); var item = new VisualElement(); item.AddToClassList("tutorial-shop-highlight"); scroll.Add(item); item.Add(TerminalLayout.Heading(offer.DisplayName)); item.Add(TerminalLayout.BodyText(offer.Description)); item.Add(TerminalLayout.BodyText($"Price: {offer.Price} Bits. This patch stays on the card for the rest of this run.")); var buy = new Button(() => { _run.BuyOffer(offer, _combat.PlayerState); _renderKey = null; Redraw(); }) { text = purchased ? "Purchased" : $"Buy / {offer.Price} Bits", name = "TutorialBuy" }; buy.SetEnabled(!purchased && _run.Bits >= offer.Price); item.Add(buy); scroll.Add(TerminalLayout.BodyText(purchased ? "Upgrade installed. Your Uptime, deck and patch carry into wave two." : "Buy this upgrade to practice spending Bits. Then start the next wave.")); action = new Button(Continue) { text = "Start wave two", name = "TutorialContinue" }; action.SetEnabled(purchased); } } else if (_lesson < TutorialCampaign.LessonCount) { scroll.Add(TerminalLayout.BodyText("Queue and stack mastered. One last practice: Cron Job's countdown and a Daemon miniboss.")); scroll.Add(TerminalLayout.BodyText("Continue to save your progress and restore full Uptime for the final practice.")); action = new Button(Continue) { text = "Start wave three", name = "TutorialContinue" }; } else { scroll.Add(TerminalLayout.BodyText("All three waves cleared. You're ready for a campaign.")); scroll.Add(TerminalLayout.Heading($"+{TutorialCampaign.BandwidthReward:N0} Bandwidth")); scroll.Add(TerminalLayout.Heading($"+{TutorialCampaign.EntropyReward:N0} Entropy")); scroll.Add(TerminalLayout.BodyText("Enough Entropy for one standard 10-pull. This training reward is granted once per profile.")); action = new Button(Continue) { text = "Claim rewards & finish", name = "TutorialContinue" }; } if (!string.IsNullOrEmpty(_error)) scroll.Add(TerminalLayout.BodyText("Could not save: " + _error + " Retry to continue.", "TutorialSaveError")); action.AddToClassList("primary-action"); panel.Add(action); panel.RegisterCallback(evt => evt.StopPropagation()); TerminalTheme.ConstrainModalFocus(panel); _overlay.Add(panel); (panel.Q