using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CursorSwitcher : MonoBehaviour
{
    [SerializeField] private Texture2D defaultCursor;
    [SerializeField] private Texture2D targetCursor;
    [SerializeField] private Texture2D knobCursor;
    [SerializeField] private Texture2D liquidCursor;
    [SerializeField] private float interactDistance = 3f;
    public float InteractDistance => interactDistance;
    [SerializeField] private LayerMask interactMask = ~0;
    [SerializeField] private HandController handController;

    private Camera _camera;
    private bool _isTargeting;

    void Start()
    {
        _camera = GetComponent<Camera>();
        Cursor.visible = true;
        Cursor.lockState = CursorLockMode.None;
        SetDefaultCursor();
    }

    void Update()
    {
        Ray ray = _camera.ScreenPointToRay(Input.mousePosition);
        RaycastHit[] hits = Physics.RaycastAll(ray, interactDistance, interactMask);
        bool holding = handController != null && handController.IsHoldingAny();

        bool hasTarget = false;
        bool hasLiquid = false;
        bool hasBreakable = false;
        bool hasScale = false;
        bool hasKnob = false;

        foreach (var hit in hits)
        {
            Transform current = hit.collider.transform;
            while (current != null)
            {
                if (current.CompareTag("Target")) hasTarget = true;
                if (current.CompareTag("Liquid")) hasLiquid = true;
                if (current.CompareTag("Breakable")) hasBreakable = true;
                if (holding && current.CompareTag("Scale")) hasScale = true;
                if (current.CompareTag("Knob") || current.CompareTag("Drawer") || current.CompareTag("Door")) hasKnob = true;
                current = current.parent;
            }
        }

        if (hasTarget || hasBreakable || hasScale)
        {
            SetTargetCursor(); _isTargeting = true;
        }
        else if (hasLiquid)
        {
            SetLiquidCursor(); _isTargeting = true;
        }
        else if (hasKnob)
        {
            SetKnobCursor(); _isTargeting = true;
        }
        else if (_isTargeting)
        {
            SetDefaultCursor();
            _isTargeting = false;
        }
    }


    void SetDefaultCursor()
    {
        if (defaultCursor != null)
            Cursor.SetCursor(defaultCursor, new Vector2(16, 16), CursorMode.Auto);
    }

    void SetTargetCursor()
    {
        if (targetCursor != null)
            Cursor.SetCursor(targetCursor, new Vector2(16, 16), CursorMode.Auto);
    }

    void SetKnobCursor()
    {
        if (knobCursor != null)
            Cursor.SetCursor(knobCursor, new Vector2(16, 16), CursorMode.Auto);
    }

    void SetLiquidCursor()
    {
        if (liquidCursor != null)
            Cursor.SetCursor(liquidCursor, new Vector2(16, 16), CursorMode.Auto);
        else
            SetTargetCursor();
    }
}
