
using System.Collections;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using DG.Tweening;
using TMPro;

namespace com.al_arcade.mcq
{
    using shared;

    [AddComponentMenu("Science Street/MCQ Demo Builder")]
    public class McqDemoBuilder : MonoBehaviour
    {
        [Header("Build Configuration")]
        [SerializeField] private string buildType = "scistreet";
        [SerializeField] private int gradeId = 0;
        [SerializeField] private int questionCount = 10;
        [SerializeField] private string classCode = "";

        [Header("Game Settings")]
        [SerializeField] private float runSpeed = 12f;
        [SerializeField] private int lives = 3;

        [Header("Arabic Font")]
        [Tooltip("Drag your Arabic TMP Font Asset here")]
        [SerializeField] private TMP_FontAsset arabicFont;

        [Header("Debug")]
        [SerializeField] private bool useOfflineTestData = false;

        private McqGameManager _gm;
        private McqPlayerRunner _player;
        private McqQuestionDisplay _questionDisplay;
        private McqUIManager _uiManager;

        private void Start()
        {
            DOTween.Init();
            if (arabicFont != null) SSFontManager.Font = arabicFont;
            StartCoroutine(BuildEverything());
        }

        private IEnumerator BuildEverything()
        {
            Debug.Log("══════ MCQ Runner Demo Builder ══════");


            if (FindObjectOfType<EventSystem>() == null)
            {
                var es = new GameObject("EventSystem");
                es.AddComponent<EventSystem>();
                es.AddComponent<StandaloneInputModule>();
            }


            SSApiManager.EnsureInstance();
            SSAudioManager.EnsureInstance();
            SSParticleManager.EnsureInstance();

            var session = SSGameSession.EnsureInstance();
            session.buildType = buildType;
            session.gradeId = gradeId;
            session.questionCount = questionCount;
            session.classCode = classCode;
            yield return null;


            BuildScene();
            yield return null;


            BuildPlayer();
            yield return null;


            BuildQuestionDisplay();
            yield return null;


            BuildUI();
            yield return null;


            BuildGameManager();
            yield return null;


            SetupCamera();
            yield return null;


            SetupLighting();
            yield return null;

            Debug.Log("══════ MCQ Ready — A/D or ←/→ to steer ══════");

            yield return new WaitForSeconds(0.3f);


            if (useOfflineTestData)
                _gm.StartWithQuestions(GetTestQuestions());
            else
                _gm.StartGame();
        }


        private void BuildScene()
        {
            Camera.main.clearFlags = CameraClearFlags.SolidColor;
            Camera.main.backgroundColor = new Color32(180, 200, 240, 255);

            var shader = GetLitShader();


            var road = GameObject.CreatePrimitive(PrimitiveType.Cube);
            road.name = "Road";
            road.transform.position = new Vector3(0, -0.05f, 200);
            road.transform.localScale = new Vector3(16, 0.1f, 500);
            road.GetComponent<Renderer>().material = new Material(shader)
                { color = new Color32(60, 60, 80, 255) };


            for (int i = -1; i <= 1; i += 2)
            {
                var line = GameObject.CreatePrimitive(PrimitiveType.Cube);
                line.name = $"LaneLine_{i}";
                line.transform.position = new Vector3(i * 2f, 0.01f, 200);
                line.transform.localScale = new Vector3(0.08f, 0.01f, 500);
                Destroy(line.GetComponent<Collider>());
                line.GetComponent<Renderer>().material = new Material(shader)
                    { color = SSColorPalette.WithAlpha(SSColorPalette.Accent, 0.4f) };
            }


            for (float z = 0; z < 400; z += 4)
            {
                var dash = GameObject.CreatePrimitive(PrimitiveType.Cube);
                dash.name = "Dash";
                dash.transform.position = new Vector3(0, 0.01f, z);
                dash.transform.localScale = new Vector3(0.05f, 0.01f, 2f);
                Destroy(dash.GetComponent<Collider>());
                dash.GetComponent<Renderer>().material = new Material(shader)
                    { color = SSColorPalette.WithAlpha(Color.white, 0.2f) };
            }


            for (int side = -1; side <= 1; side += 2)
            {
                for (float z = 0; z < 400; z += 20)
                {
                    var block = GameObject.CreatePrimitive(PrimitiveType.Cube);
                    block.name = "SideBlock";
                    float h = Random.Range(2f, 5f);
                    block.transform.position = new Vector3(side * 12f, h / 2f, z);
                    block.transform.localScale = new Vector3(
                        Random.Range(2f, 4f), h, Random.Range(3f, 8f));
                    Destroy(block.GetComponent<Collider>());
                    var c = Color.Lerp(SSColorPalette.Primary,
                        SSColorPalette.PrimaryLight, Random.value);
                    block.GetComponent<Renderer>().material = new Material(shader)
                        { color = SSColorPalette.WithAlpha(c, 0.4f) };
                }
            }


            var horizon = GameObject.CreatePrimitive(PrimitiveType.Cube);
            horizon.name = "Horizon";
            horizon.transform.position = new Vector3(0, 2f, 500);
            horizon.transform.localScale = new Vector3(200, 40, 1);
            Destroy(horizon.GetComponent<Collider>());
            horizon.GetComponent<Renderer>().material = new Material(shader)
                { color = new Color32(100, 120, 180, 255) };
        }

        private void BuildPlayer()
        {
            var obj = new GameObject("Player");
            obj.tag = "Player";
            obj.transform.position = Vector3.zero;

            _player = obj.AddComponent<McqPlayerRunner>();
            _player.BuildDefaultVisuals();

            var rb = obj.GetComponent<Rigidbody>();
            if (rb == null) rb = obj.AddComponent<Rigidbody>();
            rb.isKinematic = true;
            rb.useGravity = false;
        }

        private void BuildQuestionDisplay()
        {
            var obj = new GameObject("QuestionDisplay");
            obj.transform.position = new Vector3(0, 8, 10);

            _questionDisplay = obj.AddComponent<McqQuestionDisplay>();
            _questionDisplay.Build(_player.transform);
        }

        private void BuildUI()
        {
            var obj = new GameObject("McqUI");
            _uiManager = obj.AddComponent<McqUIManager>();
            _uiManager.BuildUI();


            if (_uiManager.onRestartClicked == null)
                _uiManager.onRestartClicked = new UnityEvent();
        }

        private void BuildGameManager()
        {
            var obj = new GameObject("McqGameManager");
            _gm = obj.AddComponent<McqGameManager>();
            _gm.player = _player;
            _gm.questionDisplay = _questionDisplay;
            _gm.uiManager = _uiManager;
            _gm.gateParent = new GameObject("Gates").transform;


            _uiManager.onRestartClicked.AddListener(OnRestartClicked);
        }

        private void OnRestartClicked()
        {
            if (_gm != null) _gm.ResetGame();
            if (_player != null) _player.ResetToStart();
            SetupCamera();
            if (_gm != null) _gm.StartGame();
        }

        private void SetupCamera()
        {
            var cam = Camera.main;
            if (cam == null) return;

            var follower = cam.GetComponent<McqCameraFollow>();
            if (follower == null)
                follower = cam.gameObject.AddComponent<McqCameraFollow>();

            follower.target = _player != null ? _player.transform : null;
            follower.offset = new Vector3(0, 5f, -8f);
            follower.lookOffset = new Vector3(0, 1.5f, 12f);
            follower.smoothSpeed = 6f;
        }

        private void SetupLighting()
        {
            var existing = FindObjectOfType<Light>();
            Light dirLight;
            if (existing != null)
            {
                dirLight = existing;
            }
            else
            {
                var lo = new GameObject("DirLight");
                dirLight = lo.AddComponent<Light>();
            }

            dirLight.type = LightType.Directional;
            dirLight.transform.rotation = Quaternion.Euler(45, -30, 0);
            dirLight.color = new Color32(255, 245, 230, 255);
            dirLight.intensity = 1.2f;
            dirLight.shadows = LightShadows.Soft;

            RenderSettings.ambientLight = new Color32(80, 85, 110, 255);
            RenderSettings.ambientMode = UnityEngine.Rendering.AmbientMode.Flat;
        }


        private McqQuestion[] GetTestQuestions()
        {
            return new McqQuestion[]
            {
                new() { id="1", question_text="ما هي عاصمة مصر؟",
                    answer1="القاهرة", answer2="الإسكندرية",
                    answer3="أسوان", answer4="المنصورة", source="جغرافيا" },
                new() { id="2", question_text="كم عدد كواكب المجموعة الشمسية؟",
                    answer1="8", answer2="9",
                    answer3="7", answer4="10", source="علوم" },
                new() { id="3", question_text="ما هو أكبر محيط في العالم؟",
                    answer1="المحيط الهادي", answer2="المحيط الأطلسي",
                    answer3="المحيط الهندي", answer4="المحيط المتجمد", source="جغرافيا" },
                new() { id="4", question_text="ما هو الغاز الأكثر وفرة في الغلاف الجوي؟",
                    answer1="النيتروجين", answer2="الأكسجين",
                    answer3="ثاني أكسيد الكربون", answer4="الهيليوم", source="كيمياء" },
                new() { id="5", question_text="من اخترع المصباح الكهربائي؟",
                    answer1="توماس إديسون", answer2="نيكولا تسلا",
                    answer3="ألبرت آينشتاين", answer4="إسحاق نيوتن", source="تاريخ العلوم" },
            };
        }

        private Shader GetLitShader()
        {
            return Shader.Find("Universal Render Pipeline/Lit")
                ?? Shader.Find("Standard")
                ?? Shader.Find("Unlit/Color");
        }
    }


    public class McqCameraFollow : MonoBehaviour
    {
        public Transform target;
        public Vector3 offset = new(0, 5, -8);
        public Vector3 lookOffset = new(0, 1.5f, 12);
        public float smoothSpeed = 6f;

        private void LateUpdate()
        {
            if (target == null) return;
            Vector3 desired = target.position + offset;
            transform.position = Vector3.Lerp(transform.position, desired,
                Time.deltaTime * smoothSpeed);
            Vector3 lookTarget = target.position + lookOffset;
            transform.rotation = Quaternion.Slerp(transform.rotation,
                Quaternion.LookRotation(lookTarget - transform.position),
                Time.deltaTime * smoothSpeed);
        }
    }
}
