// Chord generation logic to insert into components

// Chord progression patterns for each key
const getChordProgression = (key) => {
  const progressions = {
    C: ["C", "Am", "F", "G", "Dm", "Em"],
    "C#": ["C#", "A#m", "F#", "G#", "D#m", "Fm"],
    D: ["D", "Bm", "G", "A", "Em", "F#m"],
    "D#": ["D#", "Cm", "G#", "A#", "Fm", "Gm"],
    E: ["E", "C#m", "A", "B", "F#m", "G#m"],
    F: ["F", "Dm", "Bb", "C", "Gm", "Am"],
    "F#": ["F#", "D#m", "B", "C#", "G#m", "A#m"],
    G: ["G", "Em", "C", "D", "Am", "Bm"],
    "G#": ["G#", "Fm", "C#", "D#", "A#m", "Cm"],
    A: ["A", "F#m", "D", "E", "Bm", "C#m"],
    "A#": ["A#", "Gm", "D#", "F", "Cm", "Dm"],
    B: ["B", "G#m", "E", "F#", "C#m", "D#m"],
  };
  return progressions[key] || progressions["C"];
};

// Generate chords above lyrics
const handleKeyGenerate = async () => {
  setIsGenerating(true);
  try {
    const chords = getChordProgression(currentKey);
    const lyrics = song.lyrics || "";
    const lines = lyrics.split("\n");

    let lyricsWithChords = "";
    let chordIndex = 0;

    for (let i = 0; i < lines.length; i++) {
      const line = lines[i].trim();

      // Skip empty lines
      if (!line) {
        lyricsWithChords += "\n";
        continue;
      }

      // Skip metadata lines (verse, chorus, etc.)
      if (
        /^\[(verse|chorus|bridge|intro|outro|pre-chorus|prechorus|interlude|refrain)/i.test(
          line
        )
      ) {
        lyricsWithChords += line + "\n";
        continue;
      }

      // Add chord above the line (every 2-3 lines)
      if (i % 2 === 0) {
        const chord = chords[chordIndex % chords.length];
        lyricsWithChords += chord + "\n";
        chordIndex++;
      }

      lyricsWithChords += line + "\n";
    }

    // Update the song with generated chords
    const updatedSong = {
      ...song,
      key: currentKey,
      lyrics: lyricsWithChords.trim(),
      chords: chords.join(" - "),
    };

    // Save to database
    const response = await fetch(`http://localhost:5100/api/songs/${song.id}`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(updatedSong),
    });

    if (response.ok) {
      setSong(updatedSong);
      alert("Chords generated and saved successfully!");
    } else {
      alert("Failed to save chords");
    }
  } catch (error) {
    console.error("Error generating chords:", error);
    alert("Error generating chords");
  } finally {
    setIsGenerating(false);
  }
};

const handleTranspose = (steps) => {
  const notes = [
    "C",
    "C#",
    "D",
    "D#",
    "E",
    "F",
    "F#",
    "G",
    "G#",
    "A",
    "A#",
    "B",
  ];
  const currentIndex = notes.indexOf(currentKey);
  const newIndex = (currentIndex + steps + 12) % 12;
  setCurrentKey(notes[newIndex]);
};
