using System;
namespace DevilLink2.Gameplay
{
/// Quarter-second active-time accumulator. ElapsedTime excludes penalties and bonuses.
/// Pause preserves the fractional step; Stop freezes the timer permanently.
public sealed class SessionTimer
{
public const double StepSeconds = .25;
private double accumulator;
private bool stopped;
public double InitialTime { get; }
public double RemainingTime { get; private set; }
public double ElapsedTime { get; private set; }
public bool HasTimer { get; }
public bool IsRunning => !stopped && !IsPaused && !IsExpired;
public bool IsPaused { get; private set; }
public bool IsExpired { get; private set; }
public double TimeBarMax { get; private set; }
public bool IsLowTime => HasTimer && RemainingTime <= 15;
public event Action Expired;
public event Action LowTimeChanged;
public event Action RemainingTimeChanged;
public SessionTimer(LevelDefinition level)
{
if (level == null) throw new ArgumentNullException(nameof(level));
HasTimer = level.HasTimer;
InitialTime = RemainingTime = TimeBarMax = level.TimeLimitSeconds;
}
public void Advance(double seconds)
{
GameplayTime.Validate(seconds, nameof(seconds));
if (!IsRunning) return;
double total = accumulator + seconds;
GameplayTime.Validate(total, nameof(seconds));
// Tolerate floating-point accumulation, without tying ticks to render frames.
double ticks = Math.Floor(total / StepSeconds + 1e-9);
double elapsed = ticks * StepSeconds;
GameplayTime.Validate(elapsed, nameof(seconds));
accumulator = Math.Max(0, total - elapsed);
if (elapsed == 0) return;
ElapsedTime += HasTimer ? Math.Min(RemainingTime, elapsed) : elapsed;
if (HasTimer) SetRemaining(Math.Max(0, RemainingTime - elapsed));
}
public void Pause() { if (!stopped && !IsExpired) IsPaused = true; }
public void Resume() { if (!stopped && !IsExpired) IsPaused = false; }
public void Stop() { stopped = true; IsPaused = false; }
public bool ApplyInvalidMatchPenalty()
{
if (!HasTimer || stopped || IsExpired) return false;
SetRemaining(Math.Max(0, RemainingTime - 3));
return true;
}
public bool AddTime(double seconds)
{
GameplayTime.Validate(seconds, nameof(seconds));
if (!HasTimer || stopped || IsExpired || seconds == 0) return false;
double next = RemainingTime + seconds;
GameplayTime.Validate(next, nameof(seconds));
TimeBarMax = Math.Max(TimeBarMax, next);
SetRemaining(next);
return true;
}
private void SetRemaining(double value)
{
bool wasLow = IsLowTime;
RemainingTime = value;
bool expiresNow = value == 0 && !IsExpired;
// Commit expiration before callbacks, so subscribers cannot revive this timer.
if (expiresNow) { IsExpired = true; stopped = true; IsPaused = false; }
RemainingTimeChanged?.Invoke(value);
if (wasLow != IsLowTime) LowTimeChanged?.Invoke(IsLowTime);
if (expiresNow) Expired?.Invoke();
}
}
}