<script setup lang="ts">
// 카테고리 생성/수정 모달 — 이름 + 색상(hue 슬라이더)
import { computed, ref } from 'vue'
import BaseModal from '@/components/common/BaseModal.vue'
import type {
  ApiScheduleCategory,
  ScheduleCategoryPayload,
} from '@/types/schedule'

const props = defineProps<{ init: ApiScheduleCategory | null }>()
const emit = defineEmits<{
  (e: 'save', payload: ScheduleCategoryPayload): void
  (e: 'close'): void
}>()

const CAT_SAT = 62
const CAT_LIG = 46

function hslToHex(h: number, s: number, l: number): string {
  s /= 100
  l /= 100
  const k = (n: number) => (n + h / 30) % 12
  const a = s * Math.min(l, 1 - l)
  const f = (n: number) =>
    l - a * Math.max(-1, Math.min(k(n) - 3, Math.min(9 - k(n), 1)))
  const to = (x: number) =>
    Math.round(255 * x)
      .toString(16)
      .padStart(2, '0')
  return `#${to(f(0))}${to(f(8))}${to(f(4))}`
}
function hexToHue(hex: string): number {
  const m = hex.replace('#', '')
  const r = parseInt(m.slice(0, 2), 16) / 255
  const g = parseInt(m.slice(2, 4), 16) / 255
  const b = parseInt(m.slice(4, 6), 16) / 255
  const max = Math.max(r, g, b)
  const min = Math.min(r, g, b)
  const d = max - min
  let h = 0
  if (d) {
    if (max === r) h = ((g - b) / d) % 6
    else if (max === g) h = (b - r) / d + 2
    else h = (r - g) / d + 4
    h *= 60
    if (h < 0) h += 360
  }
  return Math.round(h)
}

const isEdit = computed(() => !!props.init)
const name = ref(props.init?.label ?? '')
const hue = ref(props.init?.color ? hexToHue(props.init.color) : 210)
const color = computed(() => hslToHex(hue.value, CAT_SAT, CAT_LIG))
const valid = computed(() => !!name.value.trim())

function submit(): void {
  if (!valid.value) return
  emit('save', { label: name.value.trim(), color: color.value })
}
</script>

<template>
  <BaseModal
    :title="isEdit ? '카테고리 편집' : '새 카테고리'"
    size="sm"
    @close="emit('close')"
  >
    <label class="form-field"><span class="form-label">이름</span>
      <input
        v-model="name"
        class="form-input"
        placeholder="카테고리 이름"
        autofocus
        @keydown.enter="submit"
      >
    </label>
    <div class="form-field">
      <span class="form-label">색상</span>
      <div class="cat-color">
        <span
          class="cat-dot"
          :style="{ background: color }"
        />
        <input
          v-model.number="hue"
          type="range"
          min="0"
          max="359"
          class="hue-slider"
          :style="{ '--cur': color }"
        >
      </div>
    </div>

    <template #foot>
      <button
        class="mbtn"
        @click="emit('close')"
      >
        취소
      </button>
      <button
        class="mbtn primary"
        :disabled="!valid"
        @click="submit"
      >
        {{ isEdit ? '저장' : '추가' }}
      </button>
    </template>
  </BaseModal>
</template>

<style scoped>
.cat-color {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}
.cat-dot {
  width: 1.5rem;
  height: 1.5rem;
  border-radius: var(--radius);
  flex-shrink: 0;
  box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.08);
}
.hue-slider {
  -webkit-appearance: none;
  appearance: none;
  flex: 1;
  height: 1rem;
  margin: 0.375rem 0;
  border-radius: 0.5rem;
  cursor: pointer;
  outline: none;
  background: linear-gradient(
    to right,
    #f00 0%,
    #ff0 17%,
    #0f0 33%,
    #0ff 50%,
    #00f 67%,
    #f0f 83%,
    #f00 100%
  );
}
.hue-slider::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 1.5rem;
  height: 1.5rem;
  border-radius: 50%;
  background: var(--cur);
  border: 3px solid #fff;
  box-shadow: 0 1px 4px rgba(20, 24, 33, 0.4);
  cursor: grab;
}
.hue-slider::-moz-range-thumb {
  width: 1.5rem;
  height: 1.5rem;
  border-radius: 50%;
  background: var(--cur);
  border: 3px solid #fff;
  box-shadow: 0 1px 4px rgba(20, 24, 33, 0.4);
  cursor: grab;
}
</style>
