<template>
  <div class="color-swatch-picker">
    <div class="swatches">
      <button
        v-for="c in palette"
        :key="c"
        type="button"
        class="swatch"
        :class="{ active: modelValue === c }"
        :style="{ backgroundColor: c }"
        :title="c"
        @click="$emit('update:modelValue', c)"
      ></button>
    </div>
    <div class="custom">
      <input
        type="color"
        :value="isHex(modelValue) ? modelValue : '#000000'"
        @input="$emit('update:modelValue', $event.target.value)"
      />
      <input
        type="text"
        :value="modelValue"
        placeholder="#RRGGBB"
        maxlength="20"
        @input="$emit('update:modelValue', $event.target.value)"
      />
      <span class="preview" :style="colorStyle(modelValue)">Aa</span>
    </div>
  </div>
</template>

<script setup>
import { PALETTE, colorStyle } from '@/utils/colorStyle'

defineProps({ modelValue: { type: String, default: '' } })
defineEmits(['update:modelValue'])

const palette = PALETTE
function isHex(c) {
  return typeof c === 'string' && /^#[0-9a-fA-F]{3,8}$/.test(c)
}
</script>

<style scoped>
.color-swatch-picker {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.swatches {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}
.swatch {
  width: 26px;
  height: 26px;
  border-radius: 6px;
  border: 2px solid transparent;
  cursor: pointer;
  padding: 0;
}
.swatch.active {
  border-color: var(--bg);
  box-shadow: 0 0 0 2px var(--text);
}
.custom {
  display: flex;
  align-items: center;
  gap: 8px;
}
.custom input[type="text"] {
  width: 120px;
  padding: 6px 8px;
  border: 1px solid var(--border);
  border-radius: 6px;
  background: var(--bg);
  color: var(--text);
  font-family: monospace;
}
.custom input[type="color"] {
  width: 34px;
  height: 34px;
  padding: 0;
  border: 1px solid var(--border);
  border-radius: 6px;
  background: none;
  cursor: pointer;
}
.preview {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 34px;
  height: 34px;
  border-radius: 6px;
  font-weight: 700;
  border: 1px solid var(--border);
}
</style>
