package com.gilman.truguitartuner;

import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowCompat;
import androidx.core.view.WindowInsetsCompat;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import com.google.android.ump.ConsentInformation;
import com.google.android.ump.ConsentRequestParameters;
import com.google.android.ump.UserMessagingPlatform;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.firebase.FirebaseApp;
import com.google.firebase.vertexai.FirebaseVertexAI;
import com.google.firebase.vertexai.GenerativeModel;
import com.google.firebase.vertexai.java.GenerativeModelFutures;
import com.google.firebase.vertexai.type.Content;
import com.google.firebase.vertexai.type.GenerateContentResponse;
import com.google.firebase.vertexai.type.TextPart;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.Executors;

public class SelectorActivity extends AppCompatActivity implements TuningAdapter.OnInfoClickListener {
    private GenerativeModel vertexAiModel;
    private ConsentInformation consentInformation;
    private Map<String, ChordInfo> chordInfoMap;
    private ImageView chordChartImageView; // For the dialog

    public static final TuningType[] tuningTypes = new TuningType[]{
            // --- Most Common Guitar Tunings ---
            new TuningType("Guitar Standard",
                    new double[]{82.41, 110.00, 146.83, 196.00, 246.94, 329.63},
                    new String[]{"E", "A", "D", "G", "B", "e"}, R.drawable.guitar_acoustic, R.color.color_acoustic_guitar),
            new TuningType("Guitar Drop D",
                    new double[]{73.42, 110.00, 146.83, 196.00, 246.94, 329.63},
                    new String[]{"D", "A", "D", "G", "B", "e"}, R.drawable.ic_guitar_electric, R.color.color_electric_guitar),

            // --- Common Drop/Down Tunings ---
            new TuningType("Guitar D Standard",
                    new double[]{73.42, 98.00, 130.80, 174.60, 220.00, 293.66},
                    new String[]{"D","G","C","F","A","d"}, R.drawable.ic_guitar_electric, R.color.color_electric_guitar),
            new TuningType("Guitar Drop C",
                    new double[]{65.41, 98.00, 130.80, 174.60, 220.00, 293.66},
                    new String[]{"C","G","C","F","A","d"}, R.drawable.ic_guitar_electric, R.color.color_electric_guitar),
            new TuningType("Guitar C Standard",
                    new double[]{65.41, 87.31, 116.5, 155.6, 196.0, 261.6},
                    new String[]{"C","F","A#","D#","G","c"}, R.drawable.ic_guitar_electric, R.color.color_electric_guitar),
            new TuningType("Guitar B Standard",
                    new double[]{61.74, 82.41, 110.0, 146.83, 185.0, 246.94},
                    new String[]{"B","E","A","D","F#","b"}, R.drawable.ic_guitar_electric, R.color.color_electric_guitar),

            // --- Common Open Guitar Tunings ---
            new TuningType("Guitar Open D",
                    new double[]{73.42, 110.00, 146.83, 185.00, 220.00, 293.66},
                    new String[]{"D","A","D","F#","A","d"}, R.drawable.guitar_acoustic, R.color.color_acoustic_guitar),
            new TuningType("Guitar Open G",
                    new double[]{73.42, 98.0, 146.83, 196.00, 246.94, 293.66},
                    new String[]{"D","G","D","G","B","d"}, R.drawable.guitar_acoustic, R.color.color_acoustic_guitar),
            new TuningType("Guitar Open E",
                    new double[]{82.41, 123.47, 164.81, 207.65, 246.94, 329.63},
                    new String[]{"E","B","E","G#","B","e"}, R.drawable.guitar_acoustic, R.color.color_acoustic_guitar),
            new TuningType("Guitar Open A",
                    new double[]{82.41, 110.00, 164.81, 220.00, 277.18, 329.63},
                    new String[]{"E","A","E","A","C#","e"}, R.drawable.guitar_acoustic, R.color.color_acoustic_guitar),
            new TuningType("Guitar Open C",
                    new double[]{65.41, 98.00, 130.81, 196.00, 261.63, 329.63},
                    new String[]{"C","G","C","G","C","e"}, R.drawable.guitar_acoustic, R.color.color_acoustic_guitar),
            new TuningType("Guitar Open Em",
                    new double[]{82.41, 123.47, 164.81, 196.00, 246.94, 329.63},
                    new String[]{"E","B","E","G","B","e"}, R.drawable.guitar_acoustic, R.color.color_acoustic_guitar),
            new TuningType("Guitar Open F",
                    new double[]{65.3, 87.3, 130.7, 174.5, 219.99, 261.5},
                    new String[]{"C","F","C","F","A","c"}, R.drawable.guitar_acoustic, R.color.color_acoustic_guitar),

            // --- Bass Guitar Tunings ---
            new TuningType("Bass Standard",
                    new double[]{41.20, 55.00, 73.42, 98.00},
                    new String[]{"E", "A", "D", "G"}, R.drawable.ic_bass_icon, R.color.color_bass_guitar),
            new TuningType("Bass 6 String",
                    new double[]{30.8, 41.2, 55.0, 73.2, 98.0, 130.8},
                    new String[]{"B","E","A","D","G","c"}, R.drawable.ic_bass_icon, R.color.color_bass_guitar),

            // --- Other Instruments ---
            new TuningType("Ukulele Standard",
                    new double[]{392.0, 261.63, 329.63,440.0},
                    new String[]{"g","C","E","a"}, R.drawable.ic_ukulele_icon, R.color.color_ukulele),
            new TuningType("Banjo Open G Standard",
                    new double[]{392.00,146.83, 196.00, 246.94, 293.66},
                    new String[]{"g","D","G","B","d"}, R.drawable.ic_banjo_icon, R.color.color_banjo),
            new TuningType("Banjo Double C",
                    new double[]{392.00, 130.81, 196.00, 261.63, 293.66},
                    new String[]{"g","C","G","C","d"}, R.drawable.ic_banjo_icon, R.color.color_banjo),
            new TuningType("Violin: Standard",
                    new double[]{659.25, 440.00, 293.66, 196.00},
                    new String[]{"E", "A", "D", "G"}, R.drawable.ic_violin_icon, R.color.color_violin),
            new TuningType("Mandolin: Standard",
                    new double[]{659.25, 392.00, 261.63, 196.00},
                    new String[]{"E", "A", "D", "G"}, R.drawable.ic_mandolin_icon, R.color.color_mandolin)
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        WindowCompat.setDecorFitsSystemWindows(getWindow(), false);
        FirebaseApp.initializeApp(this);
        setContentView(R.layout.activity_selector);

        SharedPreferences prefs = getSharedPreferences("app_prefs", MODE_PRIVATE);
        boolean isFirstRun = prefs.getBoolean("isFirstRun", true);

        vertexAiModel = FirebaseVertexAI.getInstance().generativeModel("gemini-2.5-flash");

        ConsentRequestParameters params = new ConsentRequestParameters.Builder().build();
        consentInformation = UserMessagingPlatform.getConsentInformation(this);
        consentInformation.requestConsentInfoUpdate(
                this,
                params,
                () -> {
                    if (consentInformation.isConsentFormAvailable()) {
                        loadForm();
                    }
                },
                formError -> Log.e("SelectorActivity", "Consent form error: " + formError.getMessage())
        );

        MobileAds.initialize(this, initializationStatus -> {});
        AdView mAdView = findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);

        ListView tuningListView = findViewById(R.id.tuning_list_view);
        androidx.appcompat.widget.Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        View chordFinderFooter = getLayoutInflater().inflate(R.layout.chord_finder_footer, tuningListView, false);
        tuningListView.addFooterView(chordFinderFooter);

        Button btnShowChordList = chordFinderFooter.findViewById(R.id.btn_show_chord_list);
        btnShowChordList.setOnClickListener(v -> showChordSelectionDialog());

        TuningAdapter adapter = new TuningAdapter(this, tuningTypes, this);
        tuningListView.setAdapter(adapter);

        // ** ADDED: Initialize the chord map **
        initializeChordMap();

        if (isFirstRun) {
            showFirstRunAiWelcome();
            prefs.edit().putBoolean("isFirstRun", false).apply();
        }

        tuningListView.setOnItemClickListener((parent, view, position, id) -> {
            Intent intent = new Intent(SelectorActivity.this, MainActivity.class);
            intent.putExtra("selectedTuning", position);
            startActivity(intent);
        });

        final View rootView = findViewById(R.id.main_layout);
        ViewCompat.setOnApplyWindowInsetsListener(rootView, (v, windowInsets) -> {
            int topInset = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars()).top;
            int bottomInset = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars()).bottom;
            v.setPadding(v.getPaddingLeft(), topInset, v.getPaddingRight(), bottomInset);
            return windowInsets;
        });
    }

    @Override
    public boolean onCreateOptionsMenu(android.view.Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            Intent intent = new Intent(this, SettingsActivity.class);
            startActivity(intent);
            return true;
        } else if (id == R.id.action_privacy_policy) {
            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://gilmanlabs.com/true-guitar-tuner-privacy/"));
            startActivity(browserIntent);
            return true;
        } else if (id == R.id.action_terms_of_service) {
            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://gilmanlabs.com/true-guitar-tuner-terms-of-service/"));
            startActivity(browserIntent);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void loadForm() {
        UserMessagingPlatform.loadConsentForm(
                this,
                consentForm -> {
                    if (consentInformation.getConsentStatus() == ConsentInformation.ConsentStatus.REQUIRED) {
                        consentForm.show(
                                SelectorActivity.this,
                                formError -> {
                                    if (formError != null) {
                                        Log.e("SelectorActivity", "Error showing consent form: " + formError.getMessage());
                                    }
                                }
                        );
                    }
                },
                formError -> Log.e("SelectorActivity", "Error loading consent form: " + formError.getMessage())
        );
    }

    private void showChordSelectionDialog() {
        final String[] commonChords = {
                "A Major", "A Minor", "B Major", "B Minor", "C Major", "C Minor",
                "D Major", "D Minor", "E Major", "E Minor", "F Major", "F Minor",
                "G Major", "G Minor", "A7", "B7", "C7", "D7", "E7", "F7", "G7",
                "Amaj7", "Cmaj7", "Dmaj7", "Emaj7", "Fmaj7", "Gmaj7", "Am7", "Bm7",
                "Cm7", "Dm7", "Em7", "Fm7", "Gm7", "Asus4","Dsus4", "Esus4","Fsus4", "Gsus4",
                "Gsus2", "Cdim7", "Gdim", "Eaug", "Cadd9", "Gadd9", "Dadd9",
                "E7#9 (The Hendrix Chord)", "D/F# (D over F-sharp)", "G/B (G over B)"
        };
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Select a Chord");
        builder.setItems(commonChords, (dialog, which) -> {
            String selectedChord = commonChords[which];
            onFindChordClicked(selectedChord);
        });
        builder.create().show();
    }

    private void showFirstRunAiWelcome() {
        // This prompt has been updated to accurately reflect that skins change
        // both the appearance and the information displayed.
        String prompt = "You are the friendly AI assistant for the 'True Guitar Tuner' app.\n" +
                "Write a short and sweet welcoming message for a first-time user. Use simple HTML for formatting.\n" +
                "**CRITICAL:** Do NOT use any automatic list formatting. Present the points exactly as provided below.\n" +
                "**CRITICAL FORMATTING RULE:** End every point with two HTML line break tags: `<br><br>` to create paragraph spacing.\n" +
                "\n" +
                "Here are the key points:\n" +
                "<b>1. Select a Tuning:</b> Tap a tuning from the main list to get started. By default, the tuner is in chromatic mode, so it will detect any note you play. Don't be surprised if the needle moves a little—it's just picking up background noise!<br><br>\n" +
                "<b>2. Change Skins:</b> On the tuner screen, tap the skin thumbnail near the bottom. Each skin changes the tuner's look and the information it displays, like target frequency.<br><br>\n" +
                "<b>3. Isolate a Note:</b> On the tuner screen, tap a note button to have the tuner listen only for that specific note. This is great for noisy places.<br><br>\n" +
                "<b>4. Hear the Note:</b> Tap the smaller play button (▶) next to it to hear the perfect pitch for ear training.<br><br>\n" +
                "<b>5. Discover More:</b> Look for the info icon (✪) for fun facts, and check out the 'AI Chord Finder' at the bottom of the list.<br><br>\n" +
                "<b>6. Pro Settings:</b> Tap the three dots (⋮) at the top-right to open Settings. There you can adjust the 'Concert Pitch' or set the play note length.<br><br>\n" +
                "\n" +
                "Keep the tone enthusiastic and encouraging. Start with 'Welcome to True Guitar Tuner!' and end with 'Happy Tuning!'.";

        callVertexAI("Welcome!", prompt, "Please wait for your welcome message...");
    }
    @Override
    public void onInfoClick(TuningType tuning) {
        String[] varietyInstructions = {
                "Share a fun fact about this tuning's history.",
                "Mention a famous musician known for using this tuning and name one of their songs that uses it.",
                "Describe the mood or genre of music this tuning is perfect for, and why.",
                "Suggest a simple two-chord progression that sounds great in this tuning.",
                "Explain a technical reason why a musician might choose this tuning over standard.",
                "Give a tip for a beginner trying this tuning for the first time.",
                "Compare this tuning to Standard EADGBe tuning and explain the key difference.",
                "Describe what makes this tuning unique from a music theory perspective."
        };
        int randomIndex1 = new Random().nextInt(varietyInstructions.length);
        int randomIndex2;
        do {
            randomIndex2 = new Random().nextInt(varietyInstructions.length);
        } while (randomIndex1 == randomIndex2);
        String randomInstruction1 = varietyInstructions[randomIndex1];
        String randomInstruction2 = varietyInstructions[randomIndex2];
        String finalPrompt = String.format(
                "You are a friendly music expert in a tuner app. The user is looking at the '%s' tuning. " +
                        "First, briefly explain what this tuning is. " +
                        "Then, add two interesting points: " +
                        "1. %s " +
                        "2. %s " +
                        "Keep the tone enthusiastic and encouraging. " +
                        "IMPORTANT: The entire response must be concise and no more than 3-4 short paragraphs in total.",
                tuning.humanReadableName,
                randomInstruction1,
                randomInstruction2
        );
        callVertexAI("About: " + tuning.humanReadableName, finalPrompt, "Getting tuning info...");
    }

    // ** CORRECTED onFindChordClicked METHOD **
// In SelectorActivity.java
// REPLACE your onFindChordClicked method with this one.

    // In SelectorActivity.java
// REPLACE your onFindChordClicked method with this one.

    private void onFindChordClicked(String chordName) {
        ChordInfo info = chordInfoMap.get(chordName);

        // This block for generic chords (no chart) also gets the updated instruction.
        if (info == null) {
            String genericPrompt = String.format(
                    "You are a helpful guitar teacher. A user wants to know how to play the '%s' chord. " +
                            "Provide the finger positions for one common voicing. " +
                            "Format the fingering as a list using <br> for each new line. " +
                            "IMPORTANT: Make only the string name bold, for example: '<b>Low E (6th):</b> X'. " +
                            "After the list, add a single, encouraging sentence with a helpful tip.",
                    chordName
            );
            callVertexAI("How to Play: " + chordName, genericPrompt, "Finding that chord for you...", null);
            return;
        }

        // --- THIS IS THE UPDATED PROMPT WITH THE NEW, MORE SPECIFIC INSTRUCTIONS ---
        // In onFindChordClicked(), replace the finalPrompt string with this one.

        String finalPrompt = String.format(
                "You are an expert and friendly guitar teacher explaining the '%s' chord. " +
                        "Your goal is to give a clear, encouraging explanation. " +
                        "Here is the data you need: " +
                        "1. The FRET numbers are: %s. " +
                        "2. The FINGER numbers to use are: %s (where 1=index, 2=middle, 3=ring, 4=pinky). " +
                        "Combine this information into a natural-sounding list. For example, you could say 'Place your 3rd finger on the 3rd fret of the A string'. " +
                        "Use simple HTML with <br> for new lines and <b> for bolding the string name. " +
                        "After the fingering list, add one dynamic, interesting fact about this chord. " +
                        "Finish with a single, encouraging sentence.",
                chordName,
                info.fretPattern,
                info.fingerPattern
        );

        callVertexAI("How to Play: " + chordName, finalPrompt, "Finding that chord for you...", info.drawableId);
    }
    // ** NEW: initializeChordMap METHOD **
    // In SelectorActivity.java
// REPLACE your existing initializeChordMap method with this complete one.
    // In SelectorActivity.java
// REPLACE your existing initializeChordMap method with this complete one.
    private void initializeChordMap() {
        chordInfoMap = new HashMap<>();

        // --- A ---
        chordInfoMap.put("A Major", new ChordInfo(
                R.drawable.open_a_major,
                "Low E (6th): X, A (5th): 0, D (4th): 2, G (3rd): 2, B (2nd): 2, high e (1st): 0",
                "Low E (6th): X, A (5th): 0, D (4th): 1, G (3rd): 2, B (2nd): 3, high e (1st): 0"
        ));
        chordInfoMap.put("A Minor", new ChordInfo(
                R.drawable.a_minor,
                "Low E (6th): X, A (5th): 0, D (4th): 2, G (3rd): 2, B (2nd): 1, high e (1st): 0",
                "Low E (6th): X, A (5th): 0, D (4th): 2, G (3rd): 3, B (2nd): 1, high e (1st): 0"
        ));
        chordInfoMap.put("A7", new ChordInfo(
                R.drawable.a7,
                "Low E (6th): X, A (5th): 0, D (4th): 2, G (3rd): 0, B (2nd): 2, high e (1st): 0",
                "Low E (6th): X, A (5th): 0, D (4th): 2, G (3rd): 0, B (2nd): 3, high e (1st): 0"
        ));
        chordInfoMap.put("Am7", new ChordInfo(
                R.drawable.am7,
                "Low E (6th): X, A (5th): 0, D (4th): 2, G (3rd): 0, B (2nd): 1, high e (1st): 0",
                "Low E (6th): X, A (5th): 0, D (4th): 2, G (3rd): 0, B (2nd): 1, high e (1st): 0"
        ));
        chordInfoMap.put("Amaj7", new ChordInfo(
                R.drawable.amaj7,
                "Low E (6th): X, A (5th): 0, D (4th): 2, G (3rd): 1, B (2nd): 2, high e (1st): 0",
                "Low E (6th): X, A (5th): 0, D (4th): 2, G (3rd): 1, B (2nd): 3, high e (1st): 0"
        ));
        chordInfoMap.put("Asus4", new ChordInfo(
                R.drawable.a_sus4,
                "Low E (6th): X, A (5th): 0, D (4th): 2, G (3rd): 2, B (2nd): 3, high e (1st): 0",
                "Low E (6th): X, A (5th): 0, D (4th): 1, G (3rd): 2, B (2nd): 3, high e (1st): 0"
        ));

        // --- B ---
        chordInfoMap.put("B Major", new ChordInfo(
                R.drawable.b_major,
                "Low E (6th): X, A (5th): 2, D (4th): 4, G (3rd): 4, B (2nd): 4, high e (1st): 2",
                "Low E (6th): X, A (5th): 1, D (4th): 3, G (3rd): 3, B (2nd): 3, high e (1st): 1"
        ));
        chordInfoMap.put("B Minor", new ChordInfo(
                R.drawable.b_minor,
                "Low E (6th): X, A (5th): 2, D (4th): 4, G (3rd): 4, B (2nd): 3, high e (1st): 2",
                "Low E (6th): X, A (5th): 1, D (4th): 3, G (4th): 4, B (2nd): 2, high e (1st): 1"
        ));
        chordInfoMap.put("B7", new ChordInfo(
                R.drawable.b7,
                "Low E (6th): X, A (5th): 2, D (4th): 1, G (3rd): 2, B (2nd): 0, high e (1st): 2",
                "Low E (6th): X, A (5th): 2, D (4th): 1, G (3rd): 3, B (2nd): 0, high e (1st): 4"
        ));
        chordInfoMap.put("Bm7", new ChordInfo(
                R.drawable.bm7,
                "Low E (6th): 7, A (5th): X, D (4th): 7, G (3rd): 7, B (2nd): 7, high e (1st): X",
                "Low E (6th): 2, A (5th): X, D (4th): 3, G (3rd): 3, B (2nd): 3, high e (1st): X"
        ));

        // --- C ---
        chordInfoMap.put("C Major", new ChordInfo(
                R.drawable.open_c_major,
                "Low E (6th): X, A (5th): 3, D (4th): 2, G (3rd): 0, B (2nd): 1, high e (1st): 0",
                "Low E (6th): X, A (5th): 3, D (4th): 2, G (3rd): 0, B (2nd): 1, high e (1st): 0"
        ));
        chordInfoMap.put("C Minor", new ChordInfo(
                R.drawable.c_minor,
                "Low E (6th): X, A (5th): 3, D (4th): 5, G (3rd): 5, B (2nd): 4, high e (1st): 3",
                "Low E (6th): X, A (5th): 1, D (4th): 3, G (3rd): 4, B (2nd): 2, high e (1st): 1"
        ));
        chordInfoMap.put("C7", new ChordInfo(
                R.drawable.open_c7,
                "Low E (6th): X, A (5th): 3, D (4th): 2, G (3rd): 3, B (2nd): 1, high e (1st): 0",
                "Low E (6th): X, A (5th): 3, D (4th): 2, G (3rd): 4, B (2nd): 1, high e (1st): 0"
        ));
        chordInfoMap.put("Cm7", new ChordInfo(
                R.drawable.c_minor7,
                "Low E (6th): X, A (5th): 3, D (4th): 5, G (3rd): 3, B (2nd): 4, high e (1st): 3",
                "Low E (6th): X, A (5th): 1, D (4th): 3, G (3rd): 1, B (2nd): 2, high e (1st): 1"
        ));
        chordInfoMap.put("Cmaj7", new ChordInfo(
                R.drawable.open_c_maj7,
                "Low E (6th): X, A (5th): 3, D (4th): 2, G (3rd): 0, B (2nd): 0, high e (1st): 0",
                "Low E (6th): X, A (5th): 3, D (4th): 2, G (3rd): 0, B (2nd): 0, high e (1st): 0"
        ));
        chordInfoMap.put("Cadd9", new ChordInfo(
                R.drawable.c_add9,
                "Low E (6th): X, A (5th): 3, D (4th): 2, G (3rd): 0, B (2nd): 3, high e (1st): 0",
                "Low E (6th): X, A (5th): 2, D (4th): 1, G (3rd): 0, B (2nd): 3, high e (1st): 0"
        ));
        chordInfoMap.put("Cdim7", new ChordInfo(
                R.drawable.c_dim7,
                "Low E (6th): X, A (5th): X, D (4th): 1, G (3rd): 2, B (2nd): 1, high e (1st): 2",
                "Low E (6th): X, A (5th): X, D (4th): 1, G (3rd): 3, B (2nd): 2, high e (1st): 4"
        ));

        // --- D ---
        chordInfoMap.put("D Major", new ChordInfo(
                R.drawable.open_d_major,
                "Low E (6th): X, A (5th): X, D (4th): 0, G (3rd): 2, B (2nd): 3, high e (1st): 2",
                "Low E (6th): X, A (5th): X, D (4th): 0, G (3rd): 1, B (2nd): 3, high e (1st): 2"
        ));
        chordInfoMap.put("D Minor", new ChordInfo(
                R.drawable.d_minor,
                "Low E (6th): X, A (5th): X, D (4th): 0, G (3rd): 2, B (2nd): 3, high e (1st): 1",
                "Low E (6th): X, A (5th): X, D (4th): 0, G (3rd): 2, B (2nd): 3, high e (1st): 1"
        ));
        chordInfoMap.put("D7", new ChordInfo(
                R.drawable.d7,
                "Low E (6th): X, A (5th): X, D (4th): 0, G (3rd): 2, B (2nd): 1, high e (1st): 2",
                "Low E (6th): X, A (5th): X, D (4th): 0, G (3rd): 2, B (2nd): 1, high e (1st): 3"
        ));
        chordInfoMap.put("Dm7", new ChordInfo(
                R.drawable.d_minor7,
                "Low E (6th): X, A (5th): X, D (4th): 0, G (3rd): 2, B (2nd): 1, high e (1st): 1",
                "Low E (6th): X, A (5th): X, D (4th): 0, G (3rd): 2, B (2nd): 1, high e (1st): 1"
        ));
        chordInfoMap.put("Dadd9", new ChordInfo(
                R.drawable.d_add9,
                "Low E (6th): X, A (5th): 5, D (4th): 4, G (3rd): 2, B (2nd): 5, high e (1st): 2",
                "Low E (6th): X, A (5th): 3, D (4th): 2, G (3rd): 1, B (2nd): 4, high e (1st): 1"
        ));
        chordInfoMap.put("Dmaj7", new ChordInfo(
                R.drawable.dmaj7,
                "Low E (6th): X, A (5th): X, D (4th): 0, G (3rd): 2, B (2nd): 2, high e (1st): 2",
                "Low E (6th): X, A (5th): X, D (4th): 0, G (3rd): 1, B (2nd): 1, high e (1st): 1"
        ));
        chordInfoMap.put("Dsus4", new ChordInfo(
                R.drawable.d_sus4,
                "Low E (6th): X, A (5th): X, D (4th): 0, G (3rd): 2, B (2nd): 3, high e (1st): 3",
                "Low E (6th): X, A (5th): X, D (4th): 0, G (3rd): 1, B (2nd): 2, high e (1st): 3"
        ));
        chordInfoMap.put("D/F# (D over F-sharp)", new ChordInfo(
                R.drawable.d_over_f_sharp,
                "Low E (6th): 2, A (5th): 5, D (4th): 4, G (3rd): 2, B (2nd): 3, high e (1st): 2",
                "Low E (6th): 1, A (5th): 4, D (4th): 3, G (3rd): 1, B (2nd): 2, high e (1st): 1"
        ));

        // --- E ---
        chordInfoMap.put("E Major", new ChordInfo(
                R.drawable.open_e_major,
                "Low E (6th): 0, A (5th): 2, D (4th): 2, G (3rd): 1, B (2nd): 0, high e (1st): 0",
                "Low E (6th): 0, A (5th): 2, D (4th): 3, G (3rd): 1, B (2nd): 0, high e (1st): 0"
        ));
        chordInfoMap.put("E Minor", new ChordInfo(
                R.drawable.e_minor,
                "Low E (6th): 0, A (5th): 2, D (4th): 2, G (3rd): 0, B (2nd): 0, high e (1st): 0",
                "Low E (6th): 0, A (5th): 2, D (4th): 3, G (3rd): 0, B (2nd): 0, high e (1st): 0"
        ));
        chordInfoMap.put("Eaug", new ChordInfo(
                R.drawable.e_aug,
                "Low E (6th): 0, A (5th): 3, D (4th): 2, G (3rd): 1, B (2nd): 1, high e (1st): 0",
                "Low E (6th): 0, A (5th): 4, D (4th): 3, G (3rd): 1, B (2nd): 2, high e (1st): 0"
        ));
        chordInfoMap.put("E7", new ChordInfo(
                R.drawable.e7,
                "Low E (6th): 0, A (5th): 2, D (4th): 0, G (3rd): 1, B (2nd): 0, high e (1st): 0",
                "Low E (6th): 0, A (5th): 2, D (4th): 0, G (3rd): 1, B (2nd): 0, high e (1st): 0"
        ));
        chordInfoMap.put("E7#9 (The Hendrix Chord)", new ChordInfo(
                R.drawable.e7_9,
                "Low E (6th): X, A (5th): 7, D (4th): 6, G (3rd): 7, B (2nd): 8, high e (1st): X",
                "Low E (6th): X, A (5th): 2, D (4th): 1, G (3rd): 3, B (2nd): 4, high e (1st): X"
        ));
        chordInfoMap.put("Em7", new ChordInfo(
                R.drawable.e_minor7,
                "Low E (6th): 0, A (5th): 2, D (4th): 0, G (3rd): 0, B (2nd): 0, high e (1st): 0",
                "Low E (6th): 0, A (5th): 2, D (4th): 0, G (3rd): 0, B (2nd): 0, high e (1st): 0"
        ));
        chordInfoMap.put("Emaj7", new ChordInfo(
                R.drawable.emaj7,
                "Low E (6th): 0, A (5th): 2, D (4th): 1, G (3rd): 1, B (2nd): 0, high e (1st): 0",
                "Low E (6th): 0, A (5th): 3, D (4th): 1, G (3rd): 2, B (2nd): 0, high e (1st): 0"
        ));
        chordInfoMap.put("Esus4", new ChordInfo(
                R.drawable.e_sus4,
                "Low E (6th): 0, A (5th): 2, D (4th): 2, G (3rd): 2, B (2nd): 0, high e (1st): 0",
                "Low E (6th): 0, A (5th): 2, D (4th): 3, G (3rd): 4, B (2nd): 0, high e (1st): 0"
        ));

        // --- F ---
        chordInfoMap.put("F Major", new ChordInfo(
                R.drawable.f_major,
                "Low E (6th): 1, A (5th): 3, D (4th): 3, G (3rd): 2, B (2nd): 1, high e (1st): 1",
                "Low E (6th): 1, A (5th): 3, D (4th): 4, G (3rd): 2, B (2nd): 1, high e (1st): 1"
        ));

        chordInfoMap.put("F Minor", new ChordInfo(
                R.drawable.f_minor,
                "Low E (6th): 1, A (5th): 3, D (4th): 3, G (3rd): 1, B (2nd): 1, high e (1st): 1",
                "Low E (6th): 1, A (5th): 3, D (4th): 4, G (3rd): 1, B (2nd): 1, high e (1st): 1"
        ));
        chordInfoMap.put("Fm7", new ChordInfo(
                R.drawable.f_minor7,
                "Low E (6th): 1, A (5th): 3, D (4th): 1, G (3rd): 1, B (2nd): 1, high e (1st): 1",
                "Low E (6th): 1, A (5th): 3, D (4th): 1, G (3rd): 1, B (2nd): 1, high e (1st): 1"
        ));
        chordInfoMap.put("F7", new ChordInfo(
                R.drawable.f7,
                "Low E (6th): 1, A (5th): 3, D (4th): 1, G (3rd): 2, B (2nd): 1, high e (1st): 1",
                "Low E (6th): 1, A (5th): 3, D (4th): 1, G (3rd): 2, B (2nd): 1, high e (1st): 1"
        ));
        chordInfoMap.put("Fmaj7", new ChordInfo(
                R.drawable.f_maj7,
                "Low E (6th): X, A (5th): X, D (4th): 3, G (3rd): 2, B (2nd): 1, high e (1st): 0",
                "Low E (6th): X, A (5th): X, D (4th): 3, G (3rd): 2, B (2nd): 1, high e (1st): 0"
        ));
        chordInfoMap.put("Fsus4", new ChordInfo(
                R.drawable.f_sus4,
                "Low E (6th): 1, A (5th): 3, D (4th): 3, G (3rd): 3, B (2nd): 1, high e (1st): 1",
                "Low E (6th): 1, A (5th): 2, D (4th): 3, G (3rd): 4, B (2nd): 1, high e (1st): 1"
        ));

        // --- G ---
        chordInfoMap.put("G Major", new ChordInfo(
                R.drawable.open_g_major,
                "Low E (6th): 3, A (5th): 2, D (4th): 0, G (3rd): 0, B (2nd): 0, high e (1st): 3",
                "Low E (6th): 2, A (5th): 1, D (4th): 0, G (3rd): 0, B (2nd): 0, high e (1st): 3"
        ));
        chordInfoMap.put("Gmaj7", new ChordInfo(
                R.drawable.g_maj7,
                "Low E (6th): 3, A (5th): 2, D (4th): 0, G (3rd): 0, B (2nd): 0, high e (1st): 2",
                "Low E (6th): 3, A (5th): 2, D (4th): 0, G (3rd): 0, B (2nd): 0, high e (1st): 1"
        ));
        chordInfoMap.put("G Minor", new ChordInfo(
                R.drawable.g_minor,
                "Low E (6th): 3, A (5th): 5, D (4th): 5, G (3rd): 3, B (2nd): 3, high e (1st): 3",
                "Low E (6th): 1, A (5th): 3, D (4th): 4, G (3rd): 1, B (2nd): 1, high e (1st): 1"
        ));
        chordInfoMap.put("Gm7", new ChordInfo(
                R.drawable.g_minor7,
                "Low E (6th): 3, A (5th): 5, D (4th): 3, G (3rd): 3, B (2nd): 3, high e (1st): 3",
                "Low E (6th): 1, A (5th): 3, D (4th): 1, G (3rd): 1, B (2nd): 1, high e (1st): 1"
        ));
        chordInfoMap.put("G7", new ChordInfo(
                R.drawable.g7,
                "Low E (6th): 3, A (5th): 2, D (4th): 0, G (3rd): 0, B (2nd): 0, high e (1st): 1",
                "Low E (6th): 3, A (5th): 2, D (4th): 0, G (3rd): 0, B (2nd): 0, high e (1st): 1"
        ));
        chordInfoMap.put("Gadd9", new ChordInfo(
                R.drawable.g_add9,
                "Low E (6th): 3, A (5th): 0, D (4th): 0, G (3rd): 2, B (2nd): 0, high e (1st): 3",
                "Low E (6th): 2, A (5th): 0, D (4th): 0, G (3rd): 1, B (2nd): 0, high e (1st): 3"
        ));
        chordInfoMap.put("Gsus4", new ChordInfo(
                R.drawable.g_sus4,
                "Low E (6th): 3, A (5th): 3, D (4th): 0, G (3rd): 0, B (2nd): 1, high e (1st): 3",
                "Low E (6th): 2, A (5th): 3, D (4th): 0, G (3rd): 0, B (2nd): 1, high e (1st): 4"
        ));

        chordInfoMap.put("Gdim", new ChordInfo(
                R.drawable.g_dim,
                "Low E (6th): 3, A (5th): 1, D (4th): X, G (3rd): 3, B (2nd): 2, high e (1st): X",
                "Low E (6th): 3, A (5th): 1, D (4th): X, G (3rd): 4, B (2nd): 2, high e (1st): X"
        ));
        chordInfoMap.put("G/B (G over B)", new ChordInfo(
                R.drawable.g_over_b,
                "Low E (6th): X, A (5th): 2, D (4th): 0, G (3rd): 0, B (2nd): 0, high e (1st): 3",
                "Low E (6th): X, A (5th): 1, D (4th): 0, G (3rd): 0, B (2nd): 0, high e (1st): 2"
        ));
    }

    // ** NEW: callVertexAI HELPER METHOD **
    private void callVertexAI(String title, String prompt, String loadingMessage) {
        callVertexAI(title, prompt, loadingMessage, null);
    }

    // ** NEW: MAIN callVertexAI METHOD THAT HANDLES IMAGES **
    private void callVertexAI(String title, String prompt, String loadingMessage, @Nullable Integer drawableId) {
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_chord_explanation, null);
        final TextView aiTextView = dialogView.findViewById(R.id.aiExplanationTextView);
        chordChartImageView = dialogView.findViewById(R.id.chordChartImageView);

        aiTextView.setText(loadingMessage);

        if (drawableId != null) {
            chordChartImageView.setImageResource(drawableId);
            chordChartImageView.setVisibility(View.VISIBLE);
        } else {
            chordChartImageView.setVisibility(View.GONE);
        }

        AlertDialog aiDialog = new AlertDialog.Builder(this)
                .setTitle(title)
                .setView(dialogView)
                .setPositiveButton("OK", null)
                .create();
        aiDialog.show();

        Content content = new Content.Builder().addPart(new TextPart(prompt)).build();
        GenerativeModelFutures modelFutures = GenerativeModelFutures.from(vertexAiModel);

        Futures.addCallback(modelFutures.generateContent(content),
                new FutureCallback<GenerateContentResponse>() {
                    // In your main callVertexAI method...

                    @Override
                    public void onSuccess(GenerateContentResponse result) {
                        String aiResponse = result.getText();

                        // --- THIS IS THE FIX ---
                        // Instead of setting plain text, we now parse it as HTML.
                        runOnUiThread(() -> {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                // For Android N (API 24) and above
                                aiTextView.setText(Html.fromHtml(aiResponse, Html.FROM_HTML_MODE_LEGACY));
                            } else {
                                // For older versions
                                aiTextView.setText(Html.fromHtml(aiResponse));
                            }
                        });
                        // --- END OF FIX ---
                    }
                    @Override
                    public void onFailure(@NonNull Throwable t) {
                        runOnUiThread(() -> {
                            aiTextView.setText("Sorry, something went wrong while contacting the AI. Please check your connection and try again.");
                            Log.e("SelectorActivity", "Vertex AI error", t);
                        });
                    }
                },
                Executors.newSingleThreadExecutor());
    }
}