package com.helldivers.app;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class ActivityGame extends AppCompatActivity {

    private static final int UP = 0, DOWN = 1, LEFT = 2, RIGHT = 3;
    
private static final int[][] STRATAGEMS = {
        // SUPPORT WEAPONS (12 items) - from wiki
        new int[]{DOWN, LEFT, DOWN, UP, RIGHT},        // MG-43 Machine Gun
        new int[]{DOWN, DOWN, LEFT, UP, RIGHT},       // EAT-17 Expendable Anti-Tank
        new int[]{DOWN, LEFT, DOWN, UP, UP, LEFT},    // M-105 Stalwart
        new int[]{DOWN, LEFT, DOWN, UP, LEFT},        // LAS-98 Laser Cannon
        new int[]{DOWN, LEFT, RIGHT, UP, DOWN},       // APW-1 Anti-Materiel Rifle
        new int[]{DOWN, LEFT, RIGHT, RIGHT, LEFT},    // GR-8 Recoilless Rifle
        new int[]{DOWN, LEFT, UP, LEFT, DOWN},        // GL-21 Grenade Launcher
        new int[]{DOWN, LEFT, UP, DOWN, UP},          // FLAM-40 Flamethrower
        new int[]{DOWN, LEFT, DOWN, UP, UP, RIGHT},   // AC-8 Autocannon
        new int[]{DOWN, RIGHT, DOWN, UP, LEFT, LEFT}, // ARC-3 Arc Thrower
        new int[]{DOWN, RIGHT, DOWN, UP, LEFT, RIGHT},// RS-422 Railgun
        new int[]{DOWN, DOWN, UP, DOWN, DOWN}, // FAF-14 Spear

        // ORBITAL (11 items)
        new int[]{RIGHT, RIGHT, UP},                  // Orbital Precision Strike
        new int[]{RIGHT, DOWN, LEFT, UP, UP},         // Orbital Gatling Barrage
        new int[]{RIGHT, RIGHT, RIGHT},               // Orbital Airburst Strike
        new int[]{RIGHT, RIGHT, DOWN, LEFT, RIGHT, DOWN}, // Orbital 120MM HE Barrage
        new int[]{RIGHT, RIGHT, DOWN, UP},             // Orbital Smoke Strike
        new int[]{RIGHT, RIGHT, LEFT, DOWN},           // Orbital EMS Strike
        new int[]{RIGHT, DOWN, UP, UP, LEFT, DOWN, DOWN}, // Orbital 380MM HE Barrage
        new int[]{RIGHT, DOWN, RIGHT, DOWN, RIGHT, DOWN}, // Orbital Walking Barrage
        new int[]{RIGHT, DOWN, UP, RIGHT, DOWN},      // Orbital Laser
        new int[]{RIGHT, UP, DOWN, DOWN, RIGHT},      // Orbital Railcannon Strike
        new int[]{RIGHT, RIGHT, DOWN, RIGHT},          // Orbital Gas Strike

        // EAGLE (7 items)
        new int[]{UP, RIGHT, RIGHT},                  // Eagle Strafing Run
        new int[]{UP, RIGHT, DOWN, RIGHT},            // Eagle Airstrike
        new int[]{UP, RIGHT, DOWN, DOWN, RIGHT},      // Eagle Cluster Bomb
        new int[]{UP, RIGHT, UP, DOWN},               // Eagle Smoke Strike
        new int[]{UP, RIGHT, DOWN, UP},               // Eagle Napalm Airstrike
        new int[]{UP, RIGHT, UP, LEFT},               // Eagle 110MM Rocket Pods
        new int[]{UP, RIGHT, DOWN, DOWN, DOWN},       // Eagle 500kg Bomb

        // BACKPACKS (4 items)
        new int[]{DOWN, LEFT, DOWN, UP, UP, DOWN},    // B-1 Supply Pack
        new int[]{DOWN, UP, UP, DOWN, UP},            // LIFT-850 Jump Pack
        new int[]{DOWN, LEFT, DOWN, DOWN, UP, LEFT},  // SH-20 Ballistic Shield Backpack
        new int[]{DOWN, UP, LEFT, RIGHT, LEFT, RIGHT},// SH-32 Shield Generator Pack

        // MINES (2 items)
        new int[]{DOWN, LEFT, UP, RIGHT},       // MD-6 Anti-Personnel Minefield
        new int[]{DOWN, LEFT, LEFT, DOWN},           // MD-I4 Incendiary Mines

        // EMPLACEMENTS (3 items)
        new int[]{DOWN, DOWN, LEFT, RIGHT,LEFT, RIGHT},                // FX-12 Shield Generator Relay
        new int[]{DOWN, UP, LEFT, RIGHT, RIGHT, LEFT}, // EMG-101 HMG Emplacement
        new int[]{DOWN, UP, RIGHT, UP, LEFT, RIGHT}, // AARC-3 Tesla Tower

        // SENTRIES (6 items)
        new int[]{DOWN, UP, RIGHT, LEFT},            // AG-16 Gatling Sentry
        new int[]{DOWN, UP, RIGHT, RIGHT, UP},                  // AMG-43 Machine Gun Sentry
        new int[]{DOWN, UP, RIGHT, UP, LEFT, UP},        // AAC-8 Autocannon Sentry
        new int[]{DOWN, UP, RIGHT, DOWN, UP, UP},           // AMLS-4X Rocket Sentry
        new int[]{DOWN, UP, RIGHT, RIGHT, DOWN},   // AM-12 Mortar Sentry
        new int[]{DOWN, UP, RIGHT, DOWN, RIGHT},      // AM-23 EMS Mortar Sentry

        // MISSION (12 items)
        new int[]{UP, DOWN, RIGHT, LEFT, UP},         // Reinforce
        new int[]{DOWN, DOWN, UP, RIGHT},            // Resupply
        new int[]{UP, DOWN, RIGHT, UP},              // SOS Beacon
        new int[]{DOWN, UP, LEFT, DOWN, UP, RIGHT, DOWN}, // NUX-223 Hellbomb
        new int[]{DOWN, DOWN, DOWN, UP, UP}, // SSSD Delivery
        new int[]{UP, UP, LEFT, RIGHT, DOWN, DOWN}, // Seismic Probe
        new int[]{UP, UP, LEFT, UP, RIGHT},         // Eagle Rearm
        new int[]{DOWN, UP, DOWN, UP},   // Super Earth Flag
        new int[]{LEFT, RIGHT, UP, UP, UP},        // Upload Data
        new int[]{RIGHT, UP, UP, DOWN},// SEAF Artillery
        new int[]{LEFT, UP, DOWN, RIGHT, DOWN, DOWN}              // Hive Breaker Drill
    };

private static final String[] NAMES = {
        // SUPPORT WEAPONS (0-11)
        "MG-43 Machine Gun", "EAT-17", "M-105 Stalwart", "LAS-98 Laser Cannon", "APW-1 Anti-Materiel Rifle",
        "GR-8 Recoilless Rifle", "GL-21 Grenade Launcher", "FLAM-40 Flamethrower", "AC-8 Autocannon",
        "ARC-3 Arc Thrower", "RS-422 Railgun", "FAF-14 Spear",
        // ORBITAL (12-22)
        "Orbital Precision", "Orbital Gatling", "Orbital Airburst", "Orbital 120mm", "Orbital Smoke",
        "Orbital EMS", "Orbital 380mm", "Orbital Walking", "Orbital Laser", "Orbital Railcannon", "Orbital Gas",
        // EAGLE (23-29)
        "Eagle Strafing", "Eagle Airstrike", "Eagle Cluster", "Eagle Smoke", "Eagle Napalm",
        "Eagle Rocket Pods", "Eagle 500kg",
        // BACKPACKS (30-33)
        "Supply Pack", "Jump Pack", "Ballistic Shield", "Shield Generator",
        // MINES (34-35)
        "Anti-Personnel Mines", "Incendiary Mines",
        // EMPLACEMENTS (36-38)
        "Shield Relay", "HMG Emplacement", "Tesla Tower",
        // SENTRIES (39-44)
        "Gatling Sentry", "MG Sentry", "Autocannon Sentry", "Rocket Sentry", "Mortar Sentry", "EMS Mortar Sentry",
        // MISSION (45-56)
        "Reinforce", "Resupply", "SOS Beacon", "Hellbomb", "SSSD", "Seismic Probe", "Eagle Rearm", 
        "Super Earth Flag", "Upload Data", "SEAF Artillery", "Hive Breaker"
    };

    private static final int[] ICONS = new int[]{
        // SUPPORT WEAPONS (0-11)
        R.drawable.mg_43_machine_gun,
        R.drawable.eat_17_expendable_anti_tank,
        R.drawable.m_105_stalwart,
        R.drawable.las_98_laser_cannon,
        R.drawable.apw_1_anti_materiel_rifle,
        R.drawable.gr_8_recoilless_rifle,
        R.drawable.gl_21_grenade_launcher,
        R.drawable.flam_40_flamethrower,
        R.drawable.ac_8_autocannon,
        R.drawable.arc_3_arc_thrower,
        R.drawable.rs_422_railgun,
        R.drawable.faf_14_spear_launcher,
        // ORBITAL (12-22)
        R.drawable.orbital_precision_strike,
        R.drawable.orbital_gatling_barrage,
        R.drawable.orbital_airburst_strike,
        R.drawable.orbital_120mm_he_barrage,
        R.drawable.orbital_smoke_strike,
        R.drawable.orbital_ems_strike,
        R.drawable.orbital_380mm_he_barrage,
        R.drawable.orbital_walking_barrage,
        R.drawable.orbital_laser,
        R.drawable.orbital_railcannon_strike,
        R.drawable.orbital_gas_strike,
        // EAGLE (23-29)
        R.drawable.eagle_strafing_run,
        R.drawable.eagle_airstrike,
        R.drawable.eagle_cluster_bomb,
        R.drawable.eagle_smoke_strike,
        R.drawable.eagle_napalm_airstrike,
        R.drawable.eagle_110mm_rocket_pods,
        R.drawable.eagle_500kg_bomb,
        // BACKPACKS (30-33)
        R.drawable.b_1_supply_pack,
        R.drawable.lift_850_jump_pack,
        R.drawable.sh_20_ballistic_shield_backpack,
        R.drawable.sh_32_shield_generator_pack,
        // MINES (34-35)
        R.drawable.md_6_anti_personnel,
        R.drawable.md_i4_incendiary_mines,
        // EMPLACEMENTS (36-38)
        R.drawable.fx_12_shield_generator_relay,
        R.drawable.emg_101_hmg_emplacem_nt,
        R.drawable.aarc_3_tesla_tower,
        // SENTRIES (39-44)
        R.drawable.ag_16_gatling_sentry,
        R.drawable.amg_43_machine_gun_sentry,
        R.drawable.aac_8_autocannon_sentry,
        R.drawable.amls_4x_rocket_sentry,
        R.drawable.am_12_mortar_sentry,
        R.drawable.am_23_ems_mortar_sentry,
        // MISSION (45-56)
        R.drawable.reinforce,
        R.drawable.resupply,
        R.drawable.sos_beacon,
        R.drawable.nux_223_hellbomb,
        R.drawable.sssd_delivery,
        R.drawable.seismic_probe,
        R.drawable.eagle_rearm,
        R.drawable.super_earth_flag,
        R.drawable.nux_223_hellbomb,
        R.drawable.sssd_delivery,
        R.drawable.hive_breaker_drill
    };

    private static final int[] ARROW_ICONS = new int[]{
        R.drawable.stepforward, R.drawable.stepforward, R.drawable.stepforward, R.drawable.stepforward
    };

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

    private TextView tvCounter, tvFailuresCounter;
    private ImageView ivStratagemIcon;
    private LinearLayout sequenceContainer;
    private ImageButton btnUp, btnDown, btnLeft, btnRight, btnVolver;
    private ProgressBar progressBar;
    private ImageView ivFailure;

    private int[] sequence;
    private int playerIndex = 0;
    private int completadas = 0;
    private int fallos = 0;
    private boolean esperando = false;
    private boolean juegoActivo = true;
    private int currentStratagemIndex = 0;
    private boolean bloqueado = false;

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

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

        tvCounter = findViewById(R.id.tv_counter);
        tvFailuresCounter = findViewById(R.id.tv_failures_counter);
        ivStratagemIcon = findViewById(R.id.iv_stratagem_icon);
        sequenceContainer = findViewById(R.id.sequence_container);
        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);
        progressBar = findViewById(R.id.progress_bar);
        ivFailure = findViewById(R.id.iv_failure);

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

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

        nuevaRonda();
    }

    private void animateButtonClick(View v) {
        // Feedback háptico (vibración corta)
        v.performHapticFeedback(android.view.HapticFeedbackConstants.VIRTUAL_KEY);

        // Animación de escala más agresiva y rápida
        v.animate()
                .scaleX(0.7f)
                .scaleY(0.7f)
                .setDuration(40)
                .withEndAction(() -> v.animate()
                        .scaleX(1.0f)
                        .scaleY(1.0f)
                        .setDuration(150)
                        .setInterpolator(new android.view.animation.OvershootInterpolator(4.0f)) // Rebote más fuerte
                        .start())
                .start();
    }

    private int getArrowRotation(int dir) {
        switch(dir) {
            case UP: return 0;
            case DOWN: return 180;
            case LEFT: return -90;
            case RIGHT: return 90;
            default: return 0;
        }
    }

    private void nuevaRonda() {
        int idx = (int)(Math.random() * STRATAGEMS.length);
        sequence = STRATAGEMS[idx];
        currentStratagemIndex = idx;
        playerIndex = 0;
        juegoActivo = true;
        bloqueado = false;

        if (progressBar != null) progressBar.setVisibility(View.GONE);
        if (ivFailure != null) ivFailure.setVisibility(View.GONE);

        if (ivStratagemIcon != null) {
            try {
                int iconIndex = idx % ICONS.length;
                ivStratagemIcon.setImageResource(ICONS[iconIndex]);
            } catch (Exception e) {
                ivStratagemIcon.setImageResource(R.drawable.stratagemas_icon);
            }
        }

        secuenciaMostrar();
        
        handler.removeCallbacksAndMessages(null);
        esperando = true;
    }

    private static final String ARROW_CHARS = "\u2191\u2193\u2190\u2192";
    
    private void secuenciaMostrar() {
        if (sequenceContainer == null) return;
        sequenceContainer.removeAllViews();

        for (int i = 0; i < sequence.length; i++) {
            ImageView arrowView = new ImageView(this);
            int size = (int) (45 * getResources().getDisplayMetrics().density);
            int margin = (int) (2 * getResources().getDisplayMetrics().density);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(size, size);
            params.setMargins(margin, margin, margin, margin);
            arrowView.setLayoutParams(params);

            arrowView.setImageResource(R.drawable.ic_dpad_button);
            arrowView.setBackgroundResource(R.drawable.btn_direction);
            arrowView.setRotation(getArrowRotation(sequence[i]));
            arrowView.setColorFilter(Color.WHITE);
            int padding = (int) (8 * getResources().getDisplayMetrics().density);
            arrowView.setPadding(padding, padding, padding, padding);

            sequenceContainer.addView(arrowView);
        }
    }

    private void onInputWithSound(int dir) {
        onInput(dir);
    }

    private void onInput(int dir) {
        if (!juegoActivo || !esperando || bloqueado) return;
        bloqueado = true;
        
        if (dir == sequence[playerIndex]) {
            if (soundManager != null) {
                try { soundManager.playTone(dir); } catch (Exception e) {}
            }
            playerIndex++;
            
            if (sequenceContainer != null && playerIndex <= sequence.length) {
                View child = sequenceContainer.getChildAt(playerIndex - 1);
                if (child instanceof ImageView) {
                    ImageView arrowView = (ImageView) child;
                    arrowView.setColorFilter(Color.parseColor("#fde902"));
                }
            }
            
            if (playerIndex >= sequence.length) {
                if (soundManager != null) {
                    try { soundManager.playSuccess(); } catch (Exception e) {}
                }
                completadas++;
                if (tvCounter != null) tvCounter.setText(String.valueOf(completadas));
                esperando = false;
                if (progressBar != null) {
                    progressBar.setVisibility(View.VISIBLE);
                    handler.postDelayed(() -> {
                        if (progressBar != null) progressBar.setVisibility(View.GONE);
                    }, 300);
                }
                handler.postDelayed(this::nuevaRonda, 300);
            } else {
                bloqueado = false;
            }
        } else {
            if (soundManager != null) {
                try { soundManager.playFailure(); } catch (Exception e) {}
            }
            juegoActivo = false;
            fallos++;
            if (tvFailuresCounter != null) tvFailuresCounter.setText(String.valueOf(fallos));
            
            // Delay de medio segundo antes de reiniciar
            handler.postDelayed(this::nuevaRonda, 500);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (soundManager != null) soundManager.pause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (soundManager != null) soundManager.resume();
    }

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