<script lang="ts">
import { density, composing, style, temperature, notesImage, notesTokens, audioBlob } from '$lib/stores';

const compose = async (): Promise<void> => {
  try {
    $composing = true;
    const composeResponse = await fetch('compose', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        music_style: $style,
        density: $density,
        temperature: $temperature,
      }),
    });

    if (!composeResponse.ok) {
      throw new Error(`Unable to create composition: [${composeResponse.status}] ${composeResponse.text()}`);
    }

    const { audio, image, tokens } = await composeResponse.json();

    $notesImage = image;
    $notesTokens = tokens;
    $audioBlob = audio;
  } catch (err) {
    console.error(err);
  } finally {
    $composing = false;
  }
};
</script>

<button disabled={$composing} on:click={compose}>
  {#if $composing}
    Composing...
  {:else}
    Compose <img src="wand.svg" alt="Magic wand" />
  {/if}
</button>

<style>
button {
  display: block;
  font-size: 1.2rem;
  font-family: 'Lato', sans-serif;
  font-weight: 700;
  color: hsl(0 0% 97%);
  background: transparent;
  border: 3px solid hsl(0 0% 97%);
  border-radius: 0.375rem;
  padding: 0.5rem 1rem;
  cursor: pointer;
  margin: 1rem auto 2rem;
}

button[disabled] {
  border-color: hsl(0 0% 50%);
  color: hsl(0 0% 50%);
  cursor: initial;
}

img {
  height: 1.2rem;
  aspect-ratio: 1 / 1;
  vertical-align: bottom;
}

@media (min-width: 900px) {
  button {
    margin-top: 0;
  }
}
</style>
