<script setup>
// 계좌 선택기: 종류(대분류) 클릭 → 해당 종류 계좌(소분류) 펼침. CategoryPicker 형태.
import { computed, ref, watch } from 'vue'
import BottomSheet from './BottomSheet.vue'

const props = defineProps({
  modelValue: { type: [String, Number], default: '' },
  wallets: { type: Array, default: () => [] }, // { id, name, type, issuer }
  title: { type: String, default: '계좌 선택' },
  placeholder: { type: String, default: '계좌를 선택하세요' },
  disabled: { type: Boolean, default: false },
  emptyText: { type: String, default: '선택할 계좌가 없습니다' },
  allLabel: { type: String, default: '' }, // 필터용 '전체' 옵션(설정 시 노출)
})
const emit = defineEmits(['update:modelValue'])

const KINDS = [
  { key: 'BANK', label: '은행계좌' },
  { key: 'CASH', label: '현금' },
  { key: 'CARD', label: '카드' },
  { key: 'LOAN', label: '대출' },
  { key: 'MINUS', label: '마이너스' },
  { key: 'INVEST', label: '투자' },
]
const groups = computed(() =>
  KINDS.map((k) => ({ ...k, items: props.wallets.filter((w) => w.type === k.key) })).filter(
    (g) => g.items.length,
  ),
)
const selected = computed(() => props.wallets.find((w) => w.id === props.modelValue) || null)
const triggerLabel = computed(() => {
  if (selected.value) return selected.value.name
  if (props.allLabel && !props.modelValue) return props.allLabel
  return props.placeholder
})
const isEmptyState = computed(() => !selected.value && !(props.allLabel && !props.modelValue))

const open = ref(false)
const expanded = ref('')
const expandedGroup = computed(() => groups.value.find((g) => g.key === expanded.value) || null)
watch(open, (o) => {
  if (o) expanded.value = selected.value?.type || (groups.value.length === 1 ? groups.value[0].key : '')
})
function toggle(k) {
  expanded.value = expanded.value === k ? '' : k
}
function pick(id) {
  emit('update:modelValue', id)
  open.value = false
}
</script>

<template>
  <button
    type="button" class="ap-trigger" :class="{ empty: isEmptyState }"
    :disabled="disabled" @click="open = true"
  >
    <span class="ap-label">{{ triggerLabel }}</span>
    <span class="ap-caret">▾</span>
  </button>

  <BottomSheet v-model="open" :title="title">
    <div v-if="groups.length" class="ap-picker">
      <div class="ap-grid">
        <button
          v-if="allLabel"
          type="button" class="ap-chip all" :class="{ active: !modelValue }"
          @click="pick('')"
        >{{ allLabel }}</button>
        <button
          v-for="g in groups" :key="g.key"
          type="button" class="ap-chip major" :class="{ active: expanded === g.key }"
          @click="toggle(g.key)"
        >{{ g.label }}</button>
      </div>
      <div v-if="expandedGroup" class="ap-sub-grid">
        <button
          v-for="w in expandedGroup.items" :key="w.id"
          type="button" class="ap-chip sub" :class="{ active: w.id === modelValue }"
          @click="pick(w.id)"
        >{{ w.name }}</button>
      </div>
    </div>
    <p v-else class="ap-empty">{{ emptyText }}</p>
  </BottomSheet>
</template>

<style scoped>
.ap-trigger {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 0.5rem;
  width: 100%;
  padding: 0.55rem 0.75rem;
  border: 1px solid var(--color-border);
  border-radius: 6px;
  background: var(--color-background-soft);
  color: var(--color-text);
  font-size: 0.9rem;
  cursor: pointer;
  text-align: left;
}
.ap-trigger:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
.ap-trigger.empty .ap-label {
  opacity: 0.5;
}
.ap-label {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.ap-caret {
  opacity: 0.5;
  font-size: 0.8rem;
  flex-shrink: 0;
}
.ap-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 0.35rem;
  padding: 0.2rem 0 0.4rem;
}
.ap-sub-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 0.35rem;
  padding: 0.5rem;
  margin-bottom: 0.4rem;
  border-radius: 0 6px 6px 6px;
  background: var(--color-background-mute);
  border-left: 3px solid hsla(160, 100%, 37%, 0.4);
}
.ap-chip {
  flex: 1 1 calc(25% - 0.35rem);
  min-width: 0;
  padding: 0.5rem 0.4rem;
  border: 1px solid var(--color-border);
  border-radius: 6px;
  background: transparent;
  color: var(--color-text);
  font-size: 0.82rem;
  cursor: pointer;
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.ap-chip.active {
  border-color: hsla(160, 100%, 37%, 1);
  background: hsla(160, 100%, 37%, 0.1);
  color: hsla(160, 100%, 37%, 1);
  font-weight: 600;
}
.ap-empty {
  padding: 1.2rem 0.4rem;
  opacity: 0.6;
  text-align: center;
}
</style>
