using UnityEngine;

public class GridCell : MonoBehaviour
{
    private GameObject canon;
    public GameObject canonPrefab;
    private bool isOccupied = false;
    [SerializeField] private Material originalMat, occupiedMat;
    int price = 10;

    public void Highlight()
    {
        GetComponent<Renderer>().material = occupiedMat;
    }

    public void Occupy()
    {
        GetComponent<Renderer>().material = occupiedMat;
        isOccupied = true;
    }

    public GameObject GetCanonOnCell()
    {
        return canon;
    }
    public void UnOccupy()
    {
        UnHighlight();
        isOccupied = false;
        Debug.Log(gameObject.name);
        Debug.Log(isOccupied);
    }

    public void UnHighlight()
    {
        GetComponent<Renderer>().material = originalMat;
    }

    public void SpawnMachineGun()
    {
        if (isOccupied || canonPrefab == null || CoinSystem.instance.availableCoins < price)
            return;

        // Force correct z position for rendering
        Vector3 spawnPos = transform.position + new Vector3(0, 0f, 0f);
        spawnPos.z = 1f; // Match your intended prefab depth

        // Create the canon only once
        GameObject newCanon = Instantiate(canonPrefab, spawnPos, Quaternion.identity);
        canon = newCanon;
        canon.GetComponent<CanonController>().SetCurrentCell(gameObject);
        canon.GetComponent<CanonController>().SetCurrentCellPosition();

        // Tell the placement manager
        CanonPlacementManager.instance.CanonPlaced(newCanon);

        isOccupied = true;

        Highlight();

        Debug.Log("Canons: " + CanonPlacementManager.instance.GetCanonCount());

        SFXController.instance?.PlaySFX(5);

        CoinSystem.instance.SpendCoins(price);
    }

    public void RelocateMachineGun(GameObject newCanon)
    {
        if (isOccupied || canonPrefab == null || CoinSystem.instance.availableCoins < price)
            return;

        // Force correct z position for rendering
        Vector3 spawnPos = transform.position + new Vector3(0, 0f, 0f);
        spawnPos.z = 1f; // Match your intended prefab depth

        newCanon.GetComponent<Transform>().position = spawnPos;
        newCanon.GetComponent<CanonController>().SetCurrentCell(gameObject);
        newCanon.GetComponent<CanonController>().SetCurrentCellPosition();
        canon = newCanon;

        isOccupied = true;

        Highlight();

        Debug.Log("Canons: " + CanonPlacementManager.instance.GetCanonCount());

        SFXController.instance?.PlaySFX(5);
    }

    public bool IsOccupied()
    {
        return isOccupied;
    }
}