using UnityEngine;

namespace eagle {
    /// <summary>
    /// Creates a beasts/wildlife particle effect with circling birds (vultures/crows).
    /// </summary>
    [RequireComponent(typeof(RectTransform))]
    public class BeastsEffect : MonoBehaviour {
        [Header("Bird Settings")]
        public Texture2D birdTexture;
        public Material birdMaterial;  // Assign in prefab to ensure shader is included in build
        public float birdCount = 5f;
        public float birdLifetime = 8f;
        public float birdSize = 12f;
        public float circleRadius = 35f;
        public float circleSpeed = 1f;
        public Color birdColor = Color.white;

        [Header("Flight Pattern")]
        public float verticalOscillation = 10f;
        public float radiusVariation = 10f;

        private ParticleSystem _birdSystem;
        private Material _materialInstance;
        private const string BeastSortingLayerName = "UI Base Overlay";
        private const int BeastBirdSortingOrder = 102;

        void Start() { SetupParticleSystems(); }

        private void SetupParticleSystems() {
            var birdObj = new GameObject("BirdEffect");
            birdObj.transform.SetParent(transform, false);
            _birdSystem = birdObj.AddComponent<ParticleSystem>();
            SetupBirdSystem();
        }

        private void SetupBirdSystem() {
            var main = _birdSystem.main;
            main.playOnAwake = true;
            main.loop = true;
            main.startLifetime = birdLifetime;
            main.startSpeed = 0f;
            main.startSize = birdSize;
            main.startColor = birdColor;
            main.startRotation3D = true;
            main.simulationSpace = ParticleSystemSimulationSpace.Local;
            main.scalingMode = ParticleSystemScalingMode.Hierarchy;
            main.maxParticles = 10;

            var emission = _birdSystem.emission;
            emission.enabled = true;
            // Emit in bursts to maintain constant population
            emission.rateOverTime = 0f;
            emission.SetBursts(
                    new ParticleSystem.Burst[] { new ParticleSystem.Burst(0f, (short)birdCount) });

            // Start on circle perimeter
            var shape = _birdSystem.shape;
            shape.enabled = true;
            shape.shapeType = ParticleSystemShapeType.Circle;
            shape.radius = circleRadius;
            shape.radiusThickness = 0f;  // Only emit on edge
            shape.rotation = new Vector3(-90f, 0f, 0f);
            shape.arc = 360f;
            shape.arcMode = ParticleSystemShapeMultiModeValue.Random;

            // Orbital velocity for circling motion
            var velocityOverLifetime = _birdSystem.velocityOverLifetime;
            velocityOverLifetime.enabled = true;
            velocityOverLifetime.space = ParticleSystemSimulationSpace.Local;
            // All axes must use same curve mode (MinMaxCurve)
            velocityOverLifetime.orbitalX = new ParticleSystem.MinMaxCurve(0f, 0f);
            velocityOverLifetime.orbitalY =
                    new ParticleSystem.MinMaxCurve(circleSpeed, circleSpeed);
            velocityOverLifetime.orbitalZ = new ParticleSystem.MinMaxCurve(0f, 0f);
            velocityOverLifetime.radial = new ParticleSystem.MinMaxCurve(0f, 0f);

            // Add vertical bobbing with noise
            var noise = _birdSystem.noise;
            noise.enabled = true;
            noise.separateAxes = true;
            noise.strengthX = radiusVariation;
            noise.strengthY = verticalOscillation;
            noise.strengthZ = 0f;
            noise.frequency = 0.3f;
            noise.scrollSpeed = 0.5f;
            noise.damping = false;
            noise.octaveCount = 1;

            // Rotate to face direction of travel
            var rotationOverLifetime = _birdSystem.rotationOverLifetime;
            rotationOverLifetime.enabled = true;
            rotationOverLifetime.separateAxes = true;
            // Slight banking as they turn
            rotationOverLifetime.z = new ParticleSystem.MinMaxCurve(-0.1f, 0.1f);

            // No fade - birds stay visible while circling
            var colorOverLifetime = _birdSystem.colorOverLifetime;
            colorOverLifetime.enabled = true;
            var gradient = new Gradient();
            gradient.SetKeys(
                    new GradientColorKey[] {
                        new GradientColorKey(Color.white, 0f),
                        new GradientColorKey(Color.white, 1f)
                    },
                    new GradientAlphaKey[] {
                        new GradientAlphaKey(0f, 0f),
                        new GradientAlphaKey(1f, 0.05f),
                        new GradientAlphaKey(1f, 0.95f),
                        new GradientAlphaKey(0f, 1f)
                    });
            colorOverLifetime.color = new ParticleSystem.MinMaxGradient(gradient);

            var renderer = _birdSystem.GetComponent<ParticleSystemRenderer>();
            if (renderer != null) {
                // Use billboard facing camera
                renderer.renderMode = ParticleSystemRenderMode.Billboard;
                renderer.alignment = ParticleSystemRenderSpace.View;

                // Use provided material if available (ensures shader is in build)
                if (birdMaterial != null) {
                    _materialInstance = BeastMaterialCompatibility.CreateParticleMaterial(
                            birdMaterial,
                            birdTexture);
                    renderer.material = _materialInstance;
                } else {
                    // Fallback for editor testing
                    _materialInstance =
                            BeastMaterialCompatibility.CreateParticleMaterial(null, birdTexture);
                    if (_materialInstance != null) { renderer.material = _materialInstance; }
                }
                renderer.sortingLayerName = BeastSortingLayerName;
                renderer.sortingOrder = BeastBirdSortingOrder;
            }
        }

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