using UnityEngine;

namespace eagle {
    /// <summary>
    /// Manages the 256x1 color lookup texture for province rendering.
    /// Each pixel index corresponds to a province ID (0-255).
    /// Colors are batched and applied in LateUpdate for efficiency.
    /// </summary>
    public class ProvinceColorManager : MonoBehaviour {
        [Header("Material")]
        public Material provinceMapMaterial;

        private Texture2D _colorLookup;
        private Color[] _colors;
        private bool _dirty;

        public Texture2D ColorLookupTexture => _colorLookup;

        void Awake() { InitializeColorLookup(); }

        private void InitializeColorLookup() {
            _colorLookup = new Texture2D(256, 1, TextureFormat.RGBA32, false);
            _colorLookup.filterMode = FilterMode.Point;
            _colorLookup.wrapMode = TextureWrapMode.Clamp;

            _colors = new Color[256];
            for (int i = 0; i < 256; i++) { _colors[i] = Color.clear; }

            _colorLookup.SetPixels(_colors);
            _colorLookup.Apply();

            if (provinceMapMaterial != null) {
                provinceMapMaterial.SetTexture("_ColorLookup", _colorLookup);
            }
        }

        /// <summary>
        /// Sets the color for a specific province. Changes are batched
        /// and applied during LateUpdate.
        /// </summary>
        /// <param name="provinceId">Province ID (1-43 typically, max 255)</param>
        /// <param name="color">The color to display for this province</param>
        public void SetProvinceColor(int provinceId, Color color) {
            if (provinceId < 0 || provinceId > 255) { return; }
            if (_colors[provinceId] != color) {
                _colors[provinceId] = color;
                _dirty = true;
            }
        }

        /// <summary>
        /// Clears all province colors to transparent.
        /// </summary>
        public void ClearAllColors() {
            for (int i = 0; i < 256; i++) { _colors[i] = Color.clear; }
            _dirty = true;
        }

        void LateUpdate() {
            if (_dirty) {
                _colorLookup.SetPixels(_colors);
                _colorLookup.Apply();
                _dirty = false;
            }
        }

        void OnDestroy() {
            if (_colorLookup != null) { Destroy(_colorLookup); }
        }
    }
}
