/*
  Arpegiador Musical con Encoder, Sensores, Botones de Transposición y Matriz 8x8
  ------------------------------------------------------------------------------------------------
  Hardware:
  - Sensor Ultrasónico (Nota Base / Posición): TRIG = Pin 5, ECHO = Pin 6
      * Cerca (5 cm) = Tono Grave (Nota baja) + Menos LEDs (Fila 7)
      * Lejos (40 cm) = Tono Agudo (Nota alta) + Más LEDs (Fila 7)
  - Encoder Rotativo:
      * S1 -> Pin 9  (Ajusta Velocidad del Arpegio: Sentido Horario = Más Rápido)
      * S2 -> Pin 10
      * KEY -> Pin 4 (Pulsador para cambiar Escala: Menor -> Mayor -> Armónica)
  - Botones Transposición:
      * Subir (+) -> Pin 2 (INPUT_PULLUP - Dibuja nota C, C', D, D', E, F, F', G, G', A, A', B)
      * Bajar (-) -> Pin 3 (INPUT_PULLUP)
  - Salida Audio (BD243A): Pin 8
  - Matriz LED 8x8 (MAX7219): DIN = Pin 11, CS = Pin 12, CLK = Pin 13
*/

#include <LedControl.h>

// --- PINES DE HARDWARE ---
const int TRIG_DERECHO = 5;
const int ECHO_DERECHO = 6;

const int ENCODER_S1  = 9;
const int ENCODER_S2  = 10;
const int ENCODER_KEY = 4; // Cambiar Escala (Pulsador del encoder)

const int BOTON_SUBIR = 2; // Transposición +
const int BOTON_BAJAR = 3; // Transposición -

const int AUDIO_PIN  = 8;

const int MATRIZ_DIN = 11;
const int MATRIZ_CS  = 12;
const int MATRIZ_CLK = 13;

LedControl lc = LedControl(MATRIZ_DIN, MATRIZ_CLK, MATRIZ_CS, 1);

// --- RANGOS Y GEOMETRÍA DEL SENSOR ULTRASÓNICO ---
const int DIST_MIN = 5;
const int ANCHO_POSICION = 4; 
const int TOTAL_POSICIONES = 8; 
const int LIMITE_ULTIMA_POS = DIST_MIN + ((TOTAL_POSICIONES - 1) * ANCHO_POSICION); 
const int DIST_MAX = LIMITE_ULTIMA_POS + 8; 

// --- BANCOS DE 3 OCTAVAS (21 NOTAS CADA UNO EN RE / D) ---
// 0. Escala Menor Natural
const int BANCO_MENOR[21] = {
  294, 330, 349, 392, 440, 466, 523,
  587, 659, 698, 784, 880, 932, 1047,
  1175, 1318, 1397, 1568, 1760, 1865, 2093
};

// 1. Escala Mayor
const int BANCO_MAYOR[21] = {
  294, 330, 370, 392, 440, 494, 554,
  587, 659, 740, 784, 880, 988, 1109,
  1175, 1318, 1480, 1568, 1760, 1976, 2217
};

// 2. Escala Menor Armónica
const int BANCO_ARMONICA[21] = {
  294, 330, 349, 392, 440, 466, 554,
  587, 659, 698, 784, 880, 932, 1109,
  1175, 1318, 1397, 1568, 1760, 1865, 2217
};

int tipoEscala = 0; // 0 = Menor, 1 = Mayor, 2 = Armónica
int notaBaseOffset = 0; // Semitonos de transposición (-12 a +12)

// --- BITMAPS DE LAS ESCALAS (DIBUJO DE TONOS Y SEMITONOS 8x8) ---
const uint8_t BITMAP_MENOR[8] = {
  0x00, 0x80, 0x60, 0x10, 0x0C, 0x02, 0x01, 0x00
};

const uint8_t BITMAP_MAYOR[8] = {
  0x00, 0x80, 0x40, 0x30, 0x08, 0x04, 0x03, 0x00
};

const uint8_t BITMAP_ARMONICA[8] = {
  0x00, 0x80, 0x60, 0x10, 0x0C, 0x00, 0x03, 0x00
};

// --- BITMAPS DE NOTAS CROMÁTICAS 8x8 (C, C', D, D', E, F, F', G, G', A, A', B) ---
const uint8_t BITMAPS_NOTAS[12][8] = {
  // 0: C
  {0x00, 0x3C, 0x42, 0x40, 0x40, 0x40, 0x42, 0x3C},
  // 1: C'
  {0x00, 0x3C, 0x42, 0x40, 0x40, 0x40, 0x43, 0x3F},
  // 2: D
  {0x00, 0x78, 0x44, 0x42, 0x42, 0x42, 0x44, 0x78},
  // 3: D'
  {0x00, 0x78, 0x44, 0x42, 0x42, 0x42, 0x47, 0x7B},
  // 4: E
  {0x00, 0x7E, 0x40, 0x40, 0x7C, 0x40, 0x40, 0x7E},
  // 5: F
  {0x00, 0x40, 0x40, 0x40, 0x7C, 0x40, 0x40, 0x7E},
  // 6: F'
  {0x00, 0x40, 0x40, 0x40, 0x7C, 0x40, 0x43, 0x7F},
  // 7: G
  {0x00, 0x3C, 0x42, 0x42, 0x4E, 0x40, 0x42, 0x3C},
  // 8: G'
  {0x00, 0x3C, 0x42, 0x42, 0x4E, 0x40, 0x43, 0x3F},
  // 9: A
  {0x00, 0x42, 0x42, 0x42, 0x7E, 0x42, 0x42, 0x3C},
  // 10: A'
  {0x00, 0x42, 0x42, 0x42, 0x7E, 0x42, 0x43, 0x3C},
  // 11: B
  {0x00, 0x7C, 0x42, 0x42, 0x7C, 0x42, 0x42, 0x7C}
};

// --- FUNCIÓN PARA DIBUJAR BITMAPS EN ORIENTACIÓN Y DIRECCIÓN CORRECTA ---
void mostrarBitmapAjustado(const uint8_t bitmap[8]) {
  uint8_t rotado[8] = {0};
  for (int r = 0; r < 8; r++) {
    for (int c = 0; c < 8; c++) {
      if ((bitmap[r] >> (7 - c)) & 1) {
        int new_r = c;
        int new_c = r;
        rotado[new_r] |= (1 << (7 - new_c));
      }
    }
  }
  for (int r = 0; r < 8; r++) {
    lc.setRow(0, r, rotado[r]);
  }
}

// --- CONTROL DE PANTALLA TEMPORAL (OVERLAY VISUAL) ---
enum ModoAviso { AVISO_NINGUNO, AVISO_ESCALA, AVISO_NOTA };
ModoAviso modoAvisoActual = AVISO_NINGUNO;
unsigned long tiempoInicioAviso = 0;
const unsigned long DURACION_AVISO_MS = 1500; // 1.5 segundos en pantalla

// --- PATRÓN Y FORMA VISUAL DEL ARPEGIO ---
const int PATRON_PASOS[8] = {0, 2, 4, 2, 7, 2, 4, 2};
const int TOTAL_PASOS_ARPEGIO = 8;
int pasoActual = 0;

const int FORMA_ARPEGIADOR[8] = {1, 2, 3, 2, 4, 2, 3, 2};

// --- TEMPO Y VELOCIDAD ---
unsigned long tiempoAnterior = 0;
int velocidadArpegio = 120; // Milisegundos por paso
int nivelVelocidadLed = 4;

// --- ESTADOS DE CONTROL Y DEBOUNCE ---
int estadoAnteriorS1;
bool ultimoEstadoKey = HIGH;
bool ultEstadoSubir = HIGH;
bool ultEstadoBajar = HIGH;

long medirDistancia(int trigPin, int echoPin) {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  long duracion = pulseIn(echoPin, HIGH, 15000); 
  if (duracion == 0) return -1;
  return duracion * 0.034 / 2;
}

void setup() {
  pinMode(TRIG_DERECHO, OUTPUT);
  pinMode(ECHO_DERECHO, INPUT);

  pinMode(ENCODER_S1, INPUT);
  pinMode(ENCODER_S2, INPUT);
  pinMode(ENCODER_KEY, INPUT_PULLUP);

  pinMode(BOTON_SUBIR, INPUT_PULLUP);
  pinMode(BOTON_BAJAR, INPUT_PULLUP);

  pinMode(AUDIO_PIN, OUTPUT);

  estadoAnteriorS1 = digitalRead(ENCODER_S1);

  lc.shutdown(0, false);
  lc.setIntensity(0, 4);
  lc.clearDisplay(0);

  Serial.begin(9600);
}

void loop() {
  // --- 1. BOTÓN KEY DEL ENCODER / POTENCIÓMETRO (CAMBIAR DE ESCALA CON DIBUJO) ---
  bool lecturaKey = digitalRead(ENCODER_KEY);
  if (lecturaKey == LOW && ultimoEstadoKey == HIGH) {
    tipoEscala = (tipoEscala + 1) % 3; // Menor (0) -> Mayor (1) -> Armónica (2)
    modoAvisoActual = AVISO_ESCALA;
    tiempoInicioAviso = millis();
    delay(150); // Antirrebote estable
  }
  ultimoEstadoKey = lecturaKey;

  // --- 2. BOTONES DE TRANSPOSICIÓN CON DIBUJO DE NOTA (+ / -) ---
  bool estadoSubir = digitalRead(BOTON_SUBIR);
  if (estadoSubir == LOW && ultEstadoSubir == HIGH) {
    notaBaseOffset++;
    if (notaBaseOffset > 12) notaBaseOffset = 12;
    modoAvisoActual = AVISO_NOTA;
    tiempoInicioAviso = millis();
    delay(100);
  }
  ultEstadoSubir = estadoSubir;

  bool estadoBajar = digitalRead(BOTON_BAJAR);
  if (estadoBajar == LOW && ultEstadoBajar == HIGH) {
    notaBaseOffset--;
    if (notaBaseOffset < -12) notaBaseOffset = -12;
    modoAvisoActual = AVISO_NOTA;
    tiempoInicioAviso = millis();
    delay(100);
  }
  ultEstadoBajar = estadoBajar;

  // --- 3. GIRO DEL ENCODER ---
  int estadoActualS1 = digitalRead(ENCODER_S1);
  if (estadoActualS1 != estadoAnteriorS1 && estadoActualS1 == HIGH) {
    if (digitalRead(ENCODER_S2) == estadoActualS1) {
      // Sentido Horario: Más Rápido
      velocidadArpegio -= 10;
      if (velocidadArpegio < 40) velocidadArpegio = 40;
      if (nivelVelocidadLed < 8) nivelVelocidadLed++;
    } else {
      // Sentido Antihorario: Más Lento
      velocidadArpegio += 10;
      if (velocidadArpegio > 200) velocidadArpegio = 200;
      if (nivelVelocidadLed > 1) nivelVelocidadLed--;
    }
  }
  estadoAnteriorS1 = estadoActualS1;

  // --- 4. SENSOR ULTRASÓNICO (SELECCIONAR NOTA BASE: CERCA = GRAVE, LEJOS = AGUDO) ---
  long distDerecha = medirDistancia(TRIG_DERECHO, ECHO_DERECHO);
  int indiceNotaBase = -1;
  int nivelFrecuenciaLed = 0;

  if (distDerecha >= DIST_MIN && distDerecha <= DIST_MAX) {
    int posicionCalculada = 0;
    if (distDerecha >= LIMITE_ULTIMA_POS) {
      posicionCalculada = TOTAL_POSICIONES - 1;
    } else {
      posicionCalculada = (distDerecha - DIST_MIN) / ANCHO_POSICION;
    }
    posicionCalculada = constrain(posicionCalculada, 0, TOTAL_POSICIONES - 1);

    // Cerca (posicionCalculada = 0) -> Nota Grave (0) + 1 LED encendido
    // Lejos (posicionCalculada = 7) -> Nota Aguda (14) + 8 LEDs encendidos
    indiceNotaBase = posicionCalculada * 2; 

    nivelFrecuenciaLed = posicionCalculada + 1;
    nivelFrecuenciaLed = constrain(nivelFrecuenciaLed, 0, 8);
  }

  // --- 5. MOTOR DEL ARPEGIADOR POR INTERVALOS ---
  unsigned long tiempoActual = millis();

  if (indiceNotaBase >= 0) {
    if (tiempoActual - tiempoAnterior >= (unsigned long)velocidadArpegio) {
      tiempoAnterior = tiempoActual;

      // Calcular la nota arpegiada sumando el intervalo del patrón
      int indiceArpegio = indiceNotaBase + PATRON_PASOS[pasoActual];
      indiceArpegio = constrain(indiceArpegio, 0, 20);

      // Obtener frecuencia según el banco de escala activo
      int freqBase = 0;
      if (tipoEscala == 0) freqBase = BANCO_MENOR[indiceArpegio];
      else if (tipoEscala == 1) freqBase = BANCO_MAYOR[indiceArpegio];
      else freqBase = BANCO_ARMONICA[indiceArpegio];

      // Aplicar transposición si se pulsaron los botones + / -
      float freqFinal = freqBase * pow(2.0, notaBaseOffset / 12.0);

      tone(AUDIO_PIN, (int)freqFinal);

      pasoActual = (pasoActual + 1) % TOTAL_PASOS_ARPEGIO;
    }
  } else {
    noTone(AUDIO_PIN);
    digitalWrite(AUDIO_PIN, LOW);
  }

  // --- 6. RENDERIZAR EN MATRIZ LED 8x8 ---
  lc.clearDisplay(0);

  // Verificamos si hay un aviso activo (cambio de nota o cambio de escala)
  if (modoAvisoActual != AVISO_NINGUNO && (millis() - tiempoInicioAviso < DURACION_AVISO_MS)) {
    if (modoAvisoActual == AVISO_ESCALA) {
      // Dibuja el patrón de Tonos y Semitonos en la matriz LED con orientación corregida
      if (tipoEscala == 0) {
        mostrarBitmapAjustado(BITMAP_MENOR);
      } else if (tipoEscala == 1) {
        mostrarBitmapAjustado(BITMAP_MAYOR);
      } else {
        mostrarBitmapAjustado(BITMAP_ARMONICA);
      }
    } else if (modoAvisoActual == AVISO_NOTA) {
      // Dibuja la letra de la nota cromática elegida con orientación corregida
      int idxNota = (2 + notaBaseOffset) % 12;
      if (idxNota < 0) idxNota += 12;
      mostrarBitmapAjustado(BITMAPS_NOTAS[idxNota]);
    }
  } else {
    modoAvisoActual = AVISO_NINGUNO; // Termina la vista temporal

    // --- INTERFAZ DINÁMICA NORMAL ---
    // Fila 0: Nivel de Velocidad (Encoder: más a la derecha / más leds = más rápido)
    for (int j = 0; j < nivelVelocidadLed; j++) {
      lc.setLed(0, 0, j, true);
    }

    // Fila 7: Nota Base / Distancia (Sensor Ultrasónico: cerca = 1 led, lejos = 8 leds)
    for (int j = 0; j < nivelFrecuenciaLed; j++) {
      lc.setLed(0, 7, j, true);
    }

    // Filas centrales (2 a 5): Forma ondulante del arpegio
    if (indiceNotaBase >= 0) {
      int pasoActivo = (pasoActual - 1 + TOTAL_PASOS_ARPEGIO) % TOTAL_PASOS_ARPEGIO;
      int filaLed = map(FORMA_ARPEGIADOR[pasoActivo], 1, 4, 5, 2);
      lc.setLed(0, filaLed, pasoActivo, true);
    }
  }
}
