<template>
  <NuxtLayout name="ui">
    <header :class="errorClasses">
      Connection failed. <button @click="update">Click here to retry</button>.
    </header>
    <main class="grid">
      <Card v-for="item in items" :title="item.title" :description="item.description" :type="item.type"/>
    </main>
        <div class="bg-slate-600 rounded-md text-md text-white px-2">
        </div>
  </NuxtLayout>
</template>

<script setup lang="ts">
import Card from '../components/Card.vue'
import { ref, onMounted } from 'vue'

onMounted(_ => update())

const items = ref([...new Array(9)].map((_, i) => ({
    title: `Item ${i}`,
    description: "",
    type: "?"
  }))
)
const errorClasses = ref("error hidden")


function updateItem(item) {
  items.value.forEach(n => {
    if (n.title == item.title) {
      if (item.description)
        n.description = item.description;
      if (item.type)
        n.type = item.type;
    }
  })
}

function failure() {
  errorClasses.value = "error"
  console.log("aaaaaa")
}

async function update() {
  errorClasses.value = "error hidden"
  await streamRequest("/hello_world/json", updateItem, failure, update);
}
</script>

<style>
  .grid {
    align-items: center;
    display: grid;
    grid-template-columns: auto auto auto;
    grid-template-rows: auto auto auto;
    margin: 1em;
    gap: 1em;
  }

  .error {
    background-color: red;
  }

  .hidden {
    display: none;
  }
</style>