<template>
  <section class="py-8 space-y-6">
    <div class="flex items-center justify-between">
      <h2 class="text-2xl font-semibold">Welcome</h2>
      <div class="flex gap-2">
        <UButton
          icon="i-heroicons-arrow-down-tray"
          color="gray"
          @click="onExport"
          >Export JSON</UButton
        >
        <UButton icon="i-heroicons-arrow-up-tray" color="gray" @click="onImport"
          >Import JSON</UButton
        >
      </div>
    </div>

    <UCard>
      <div class="flex items-center gap-3">
        <UButton icon="i-heroicons-plus" @click="store.increment"
          >Increment</UButton
        >
        <div class="text-sm text-gray-500">
          Count: {{ store.count }} (x2: {{ store.doubleCount }})
        </div>
      </div>
    </UCard>
  </section>
</template>

<script setup lang="ts">
import { useCounterStore } from "~/stores/counter";
const store = useCounterStore();

const onExport = () => {
  const data = exportAll();
  const blob = new Blob([JSON.stringify(data, null, 2)], {
    type: "application/json",
  });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = "urgent-tools.json";
  a.click();
  URL.revokeObjectURL(url);
};

const onImport = async () => {
  const input = document.createElement("input");
  input.type = "file";
  input.accept = "application/json";
  input.onchange = async () => {
    const file = input.files?.[0];
    if (!file) return;
    const text = await file.text();
    importAll(JSON.parse(text));
  };
  input.click();
};

const { exportAll, importAll } = useFixtureIO();
</script>
