<script setup lang="ts">
import { storeToRefs } from 'pinia'
import { useMosaicStore } from '@/stores/mosaic'
import { canvasToBlob, createPaletteCsv, downloadBlob, renderExportCanvas } from '@/utils/projectExport'

const store = useMosaicStore()
const { imageCanvas, imageName, imageWidth, imageHeight, regions, groups, settings } = storeToRefs(store)
const baseName = () => (imageName.value.replace(/\.[^.]+$/, '').replace(/[^\p{L}\p{N}_-]+/gu, '-') || 'mozaika')

async function exportPng(): Promise<void> {
  if (!imageCanvas.value) return store.notify('Najprv načítajte obrázok.', 'warning')
  try {
    const canvas = renderExportCanvas(
      imageCanvas.value,
      { width: imageWidth.value, height: imageHeight.value },
      regions.value,
      groups.value,
      settings.value.exportOverlay,
      settings.value.useUserClickPositionForLabels,
    )
    downloadBlob(await canvasToBlob(canvas), `${baseName()}-ocislovane.png`)
  } catch (error) { store.notify(error instanceof Error ? error.message : 'Export PNG zlyhal.', 'error') }
}

function exportCsv(): void {
  if (!groups.value.length) return store.notify('Paleta je zatiaľ prázdna.', 'warning')
  downloadBlob(new Blob([createPaletteCsv(groups.value, regions.value)], { type: 'text/csv;charset=utf-8' }), `${baseName()}-paleta.csv`)
}

async function exportJson(): Promise<void> {
  if (!imageWidth.value) return store.notify('Nie je čo exportovať.', 'warning')
  try {
    const project = await store.serializeProject(true)
    downloadBlob(new Blob([JSON.stringify(project)], { type: 'application/json' }), `${baseName()}-projekt.json`)
    if (!project.imageDataUrl) store.notify('Obrázok je väčší než 5 MB. Pri importe JSON ho bude potrebné znova vybrať.', 'info')
  } catch (error) {
    store.notify(error instanceof Error ? error.message : 'Export projektu JSON zlyhal.', 'error')
  }
}
</script>

<template>
  <section class="panel-section export-section">
    <h2>Export</h2>
    <label class="check"><input v-model="settings.exportOverlay" type="checkbox" /> Zahrnúť farebné prekrytie do PNG</label>
    <div class="export-grid">
      <button class="button" type="button" :disabled="!imageCanvas" @click="exportPng">Očíslované PNG</button>
      <button class="button" type="button" :disabled="!groups.length" @click="exportCsv">Paleta CSV</button>
      <button class="button" type="button" :disabled="!imageWidth" @click="exportJson">Projekt JSON</button>
    </div>
  </section>
</template>

<style scoped>
.export-section { border-bottom: 0; }
.check { display: flex; align-items: center; gap: 7px; margin-top: 10px; color: #475569; font-size: .72rem; }
.export-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 7px; margin-top: 11px; }
.export-grid .button:last-child { grid-column: 1 / -1; }
</style>
