package com.helldivers.app;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class ActivityGame extends AppCompatActivity {

    private static final String[] ARROWS = new String[]{"\u2191", "\u2193", "\u2190", "\u2192"};
    private static final int UP = 0, DOWN = 1, LEFT = 2, RIGHT = 3;

    private static final int[][] STRATAGEMS = new int[][]{
        new int[]{UP, DOWN, RIGHT, LEFT, UP},
        new int[]{DOWN, DOWN, UP, RIGHT},
        new int[]{UP, DOWN, RIGHT, UP},
        new int[]{RIGHT, UP, UP, DOWN},
        new int[]{DOWN, UP, LEFT, DOWN, UP, RIGHT, DOWN, UP},
        new int[]{DOWN, UP, DOWN, UP},
        new int[]{DOWN, LEFT, DOWN, UP, RIGHT},
        new int[]{DOWN, LEFT, RIGHT, UP, DOWN},
        new int[]{DOWN, LEFT, DOWN, UP, UP, LEFT},
        new int[]{DOWN, DOWN, LEFT, UP, RIGHT},
        new int[]{DOWN, LEFT, RIGHT, RIGHT, LEFT},
        new int[]{DOWN, LEFT, UP, DOWN, UP},
        new int[]{DOWN, LEFT, DOWN, UP, UP, RIGHT},
        new int[]{DOWN, RIGHT, DOWN, UP, LEFT, RIGHT},
        new int[]{DOWN, DOWN, UP, DOWN, DOWN},
        new int[]{RIGHT, DOWN, LEFT, UP, UP},
        new int[]{RIGHT, RIGHT, RIGHT},
        new int[]{RIGHT, RIGHT, DOWN, LEFT, RIGHT, DOWN},
        new int[]{RIGHT, DOWN, UP, UP, LEFT, DOWN, DOWN},
        new int[]{RIGHT, DOWN, RIGHT, DOWN, RIGHT, DOWN},
        new int[]{RIGHT, DOWN, UP, RIGHT, DOWN},
        new int[]{RIGHT, UP, DOWN, DOWN, RIGHT},
        new int[]{UP, RIGHT, RIGHT},
        new int[]{UP, RIGHT, DOWN, RIGHT},
        new int[]{UP, RIGHT, DOWN, DOWN, RIGHT},
        new int[]{UP, RIGHT, DOWN, UP},
        new int[]{DOWN, UP, UP, DOWN, UP},
        new int[]{UP, RIGHT, DOWN, UP},
        new int[]{UP, RIGHT, UP, LEFT},
        new int[]{UP, RIGHT, DOWN, DOWN, DOWN},
        new int[]{UP, UP, LEFT, UP, RIGHT},
        new int[]{RIGHT, RIGHT, UP},
        new int[]{RIGHT, RIGHT, DOWN, RIGHT},
        new int[]{RIGHT, RIGHT, LEFT, DOWN},
        new int[]{RIGHT, RIGHT, DOWN, UP},
        new int[]{DOWN, UP, LEFT, RIGHT, RIGHT, LEFT},
        new int[]{DOWN, DOWN, LEFT, RIGHT, LEFT, RIGHT},
        new int[]{DOWN, UP, RIGHT, UP, LEFT, RIGHT},
        new int[]{DOWN, LEFT, UP, RIGHT},
        new int[]{DOWN, LEFT, DOWN, UP, UP, DOWN},
        new int[]{DOWN, LEFT, UP, LEFT, DOWN},
        new int[]{DOWN, LEFT, DOWN, UP, LEFT},
        new int[]{DOWN, LEFT, LEFT, DOWN},
        new int[]{UP, DOWN, LEFT, UP, RIGHT, RIGHT},
        new int[]{DOWN, LEFT, DOWN, DOWN, UP, LEFT},
        new int[]{DOWN, RIGHT, DOWN, UP, LEFT, LEFT},
        new int[]{DOWN, UP, LEFT, RIGHT, LEFT, RIGHT},
        new int[]{DOWN, UP, RIGHT, RIGHT, UP},
        new int[]{DOWN, UP, RIGHT, LEFT},
        new int[]{DOWN, UP, RIGHT, RIGHT, DOWN},
        new int[]{DOWN, UP, LEFT, UP, RIGHT, DOWN},
        new int[]{DOWN, UP, RIGHT, UP, LEFT, UP},
        new int[]{DOWN, UP, RIGHT, RIGHT, LEFT},
        new int[]{DOWN, UP, RIGHT, DOWN, RIGHT}
    };

    private static final String[] NAMES = new String[]{
        "Reforzamiento", "Reabastecimiento", "Baliza SOS", "Artilleria", "Bomba Infernal",
        "Bandera", "Ametralladora", "Rifle material", "Leal", "Antitanque",
        "Rifle retroceso", "Echador llama", "Canon auto", "Canon riel", "Lanza",
        "Bombardeo", "Ataque aereo", "HE 120mm", "HE 380mm", "Aluvion",
        "Laser orbital", "Riel orbital", "Carrera", "Ataque", "Racimo",
        "Napalm", "Salto", "Humo", "Cohetes", "Bomba 500kg",
        "Rearme", "Precision", "Gas", "EMS", "Humo2",
        "HMG", "Escudo", "Tesla", "Minas", "Suministros",
        "Granadas", "Laser", "Incendiarias", "Rover", "Balistico",
        "Arco", "Escudo2", "Centinela1", "Centinela2", "Centinela3",
        "Guardian", "Centinela4", "Centinela5", "Centinela6", "Centinela7"
    };

    private SoundManager soundManager;
    private Handler handler = new Handler();

    private TextView tvSequence;
    private TextView tvCounter;
    private Button btnUp, btnDown, btnLeft, btnRight;
    private Button btnVolver;

    private int[] sequence;
    private int playerIndex = 0;
    private int completadas = 0;
    private boolean esperando = false;
    private boolean juegoActivo = true;
    private String[] ultimosArrows;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game);

        try { soundManager = new SoundManager(this); }
        catch (Exception e) { soundManager = null; }

        tvSequence = findViewById(R.id.tv_sequence);
        tvCounter = findViewById(R.id.tv_counter);
        btnUp = findViewById(R.id.btn_up);
        btnDown = findViewById(R.id.btn_down);
        btnLeft = findViewById(R.id.btn_left);
        btnRight = findViewById(R.id.btn_right);
        btnVolver = findViewById(R.id.btn_volver);

        btnVolver.setOnClickListener(v -> finish());

        if (btnUp != null) btnUp.setOnClickListener(v -> onInputWithSound(UP));
        if (btnDown != null) btnDown.setOnClickListener(v -> onInputWithSound(DOWN));
        if (btnLeft != null) btnLeft.setOnClickListener(v -> onInputWithSound(LEFT));
        if (btnRight != null) btnRight.setOnClickListener(v -> onInputWithSound(RIGHT));

        nuevaRonda();
    }

    private void nuevaRonda() {
        int idx = (int)(Math.random() * STRATAGEMS.length);
        sequence = STRATAGEMS[idx];
        playerIndex = 0;
        juegoActivo = true;
        ultimosArrows = new String[sequence.length];
        
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < sequence.length; i++) {
            int dir = sequence[i];
            ultimosArrows[i] = ARROWS[dir];
            sb.append(ultimosArrows[i]).append(" ");
        }
        if (tvSequence != null) {
            tvSequence.setText(sb.toString().trim());
            tvSequence.setTextColor(Color.parseColor("#FFD700"));
        }
        
        handler.removeCallbacksAndMessages(null);
        handler.postDelayed(() -> { esperando = true; }, 1200);
    }

    private void onInputWithSound(int dir) {
        if (soundManager != null) {
            try { soundManager.playTone(dir); } catch (Exception e) {}
        }
        onInput(dir);
    }

    private void onInput(int dir) {
        if (!juegoActivo || !esperando) return;
        
        if (dir == sequence[playerIndex]) {
            playerIndex++;
            
            if (tvSequence != null) {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < sequence.length; i++) {
                    if (i < playerIndex) {
                        sb.append("<font color='#00FF00'>").append(ultimosArrows[i]).append("</font> ");
                    } else {
                        sb.append(ultimosArrows[i]).append(" ");
                    }
                }
                try {
                    tvSequence.setText(android.text.Html.fromHtml(sb.toString()));
                } catch (Exception e) {
                    tvSequence.setText(sb.toString().replaceAll("<[^>]*>", ""));
                }
            }
            
            if (playerIndex >= sequence.length) {
                if (soundManager != null) {
                    try { soundManager.playSuccess(); } catch (Exception e) {}
                }
                completadas++;
                if (tvCounter != null) tvCounter.setText(String.valueOf(completadas));
                if (tvSequence != null) {
                    tvSequence.setText("OK!");
                    tvSequence.setTextColor(Color.parseColor("#00FF00"));
                }
                esperando = false;
                handler.postDelayed(this::nuevaRonda, 1200);
            }
        } else {
            if (soundManager != null) {
                try { soundManager.playFailure(); } catch (Exception e) {}
            }
            if (tvSequence != null) {
                tvSequence.setText("X");
                tvSequence.setTextColor(Color.parseColor("#FF0000"));
            }
            juegoActivo = false;
            handler.postDelayed(this::nuevaRonda, 1500);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
        if (soundManager != null) soundManager.release();
    }
}