using UnityEngine;
using UnityEngine.Events;
/// <summary>
/// GAME 1303 Tier 6 — A pool of light that keeps the dark at bay. Detective Liz's lamps,
/// windows, and lit rooms; also a checkpoint-feeling safe spot.
///
/// SETUP
/// - Empty GameObject + Collider2D (Is Trigger) covering the lit area + this script.
/// - Put it on a layer called "SafeLight" and set that layer in DarknessMeter's
/// Safe Light Layers.
/// - Optional: a URP Light 2D child so it actually looks lit, and a Flicker for a
/// failing bulb.
/// - Can be switched off by a story event: wire a PuzzleSwitch or a ghost's OnDeath to
/// SetActive(false), and the room goes dark.
/// </summary>
[RequireComponent(typeof(Collider2D))]
public class SafeLightZone : MonoBehaviour
{
public GameObject lightVisual;
public bool startOn = true;
[Header("Flicker (a failing bulb)")]
public bool flicker = false;
public float flickerChance = 0.05f;
public float flickerDuration = 0.08f;
[Header("Events")]
public UnityEvent OnPlayerEntered;
public UnityEvent OnPlayerExited;
public UnityEvent OnSwitchedOff;
public bool IsOn { get; private set; }
private Collider2D zone;
private float flickerTimer;
void Reset() { GetComponent<Collider2D>().isTrigger = true; }
void Awake()
{
zone = GetComponent<Collider2D>();
SetOn(startOn);
}
void Update()
{
if (!IsOn || !flicker || lightVisual == null) return;
if (flickerTimer > 0f)
{
flickerTimer -= Time.deltaTime;
if (flickerTimer <= 0f) lightVisual.SetActive(true);
}
else if (Random.value < flickerChance * Time.deltaTime * 60f)
{
lightVisual.SetActive(false);
flickerTimer = flickerDuration;
}
}
public void SetOn(bool on)
{
IsOn = on;
if (zone != null) zone.enabled = on;
if (lightVisual != null) lightVisual.SetActive(on);
if (!on) OnSwitchedOff?.Invoke();
}
public void Toggle() => SetOn(!IsOn);
void OnTriggerEnter2D(Collider2D other) { if (other.CompareTag("Player")) OnPlayerEntered?.Invoke(); }
void OnTriggerExit2D(Collider2D other) { if (other.CompareTag("Player")) OnPlayerExited?.Invoke(); }
}