<script setup lang="ts">
import { computed } from 'vue'
import { storeToRefs } from 'pinia'
import { useMosaicStore } from '@/stores/mosaic'
import { rgbToHex } from '@/utils/colors'

const store = useMosaicStore()
const { regions, groups, selectedGroupId, selectedRegionId } = storeToRefs(store)
const visibleRegions = computed(() => selectedGroupId.value
  ? regions.value.filter((region) => region.groupId === selectedGroupId.value)
  : regions.value)
</script>

<template>
  <section class="panel-section">
    <div class="section-heading">
      <h2>{{ selectedGroupId ? 'Plochy vo vybranej skupine' : 'Rozpoznané plochy' }}</h2>
      <span>{{ visibleRegions.length }}</span>
    </div>
    <p v-if="!visibleRegions.length" class="empty-copy">Zatiaľ nie je označená žiadna plocha.</p>
    <article
      v-for="(region, index) in visibleRegions"
      :key="region.id"
      class="region-row"
      :class="{ selected: region.id === selectedRegionId }"
      @click="store.selectedRegionId = region.id; store.selectedGroupId = region.groupId"
    >
      <span class="region-index">{{ index + 1 }}</span>
      <span class="region-info"><b>{{ rgbToHex(region.color) }}</b><small>{{ region.pixelCount.toLocaleString('sk-SK') }} px</small></span>
      <select :value="region.groupId" aria-label="Farebná skupina" @click.stop @change="store.moveRegion(region.id, ($event.target as HTMLSelectElement).value)">
        <option v-for="group in groups" :key="group.id" :value="group.id">Sk. {{ group.number }}</option>
      </select>
      <button class="row-action" type="button" title="Oddeliť do novej skupiny" :disabled="(groups.find((g) => g.id === region.groupId)?.regionIds.length ?? 0) < 2" @click.stop="store.splitRegion(region.id)">Rozdeliť</button>
      <button class="delete-button" type="button" title="Odstrániť plochu" @click.stop="store.removeRegion(region.id)">×</button>
    </article>
  </section>
</template>

<style scoped>
.region-row { display: grid; grid-template-columns: 22px minmax(64px,1fr) 62px auto 25px; align-items: center; gap: 6px; margin-top: 6px; padding: 7px; border: 1px solid #e2e7ed; border-radius: 8px; cursor: pointer; }
.region-row.selected { border-color: #7aa7ee; background: #eff6ff; }
.region-index { color: #94a3b8; font-size: .67rem; }
.region-info { min-width: 0; }
.region-info b, .region-info small { display: block; font-size: .68rem; }
.region-info small { margin-top: 2px; color: #64748b; }
.region-row select { min-width: 0; padding: 5px 3px; font-size: .67rem; }
.row-action { border: 0; background: transparent; color: #2563eb; font-size: .64rem; cursor: pointer; }
.row-action:disabled { color: #aab4c1; cursor: default; }
.delete-button { width: 25px; height: 25px; padding: 0; border: 0; border-radius: 5px; background: transparent; color: #64748b; font-size: 18px; cursor: pointer; }
.delete-button:hover { background: #fee2e2; color: #b91c1c; }
</style>
