<script setup lang="ts">
import { computed, ref } from 'vue';
import type { ClassId, Loadout, SkillNode, SkillTree } from '../types';

const props = defineProps<{
  loadout: Loadout;
  skillTrees: Record<ClassId, SkillTree | null>;
  allocations: Record<string, number>;
  classes: { id: ClassId; name: string }[];
}>();

const emit = defineEmits<{
  'update:loadout': [next: Loadout];
}>();

type SlotKind = 'ability' | 'technique';

interface SkillOption {
  tag: string;
  name: string;
  icon: string | null;
  kind: string;
  classId: ClassId;
  className: string;
}

// Index every allocated node across all 5 trees so we can both render the
// chosen slot icon AND show a picker of eligible options.
const allAllocatedByTag = computed(() => {
  const out = new Map<string, SkillOption>();
  for (const c of props.classes) {
    const tree = props.skillTrees[c.id];
    if (!tree) continue;
    for (const st of tree.subtrees) {
      for (const node of st.nodes) {
        if ((props.allocations[node.tag] || 0) > 0) {
          out.set(node.tag, {
            tag: node.tag,
            name: node.name,
            icon: node.icon,
            kind: node.kind,
            classId: c.id,
            className: c.name,
          });
        }
      }
    }
  }
  return out;
});

function eligibleFor(kind: SlotKind): SkillOption[] {
  const result: SkillOption[] = [];
  for (const opt of allAllocatedByTag.value.values()) {
    if (kind === 'ability') {
      if (opt.kind === 'Ability' || opt.kind === 'Spice') result.push(opt);
    } else {
      if (opt.kind === 'Perk') result.push(opt);
    }
  }
  result.sort(
    (a, b) =>
      a.className.localeCompare(b.className) || a.name.localeCompare(b.name),
  );
  return result;
}

const pickerOpenFor = ref<{ kind: SlotKind; index: number } | null>(null);

function openPicker(kind: SlotKind, index: number) {
  pickerOpenFor.value = { kind, index };
}
function closePicker() {
  pickerOpenFor.value = null;
}

function assign(tag: string | null) {
  const sel = pickerOpenFor.value;
  if (!sel) return;
  const next: Loadout = {
    abilities: [...props.loadout.abilities],
    techniques: [...props.loadout.techniques],
  };
  const arr = sel.kind === 'ability' ? next.abilities : next.techniques;
  // If the same tag is already in another slot of the same kind, clear it.
  if (tag) {
    for (let i = 0; i < arr.length; i++) {
      if (arr[i] === tag) arr[i] = null;
    }
  }
  arr[sel.index] = tag;
  emit('update:loadout', next);
  closePicker();
}

function clearSlot(kind: SlotKind, index: number) {
  const next: Loadout = {
    abilities: [...props.loadout.abilities],
    techniques: [...props.loadout.techniques],
  };
  (kind === 'ability' ? next.abilities : next.techniques)[index] = null;
  emit('update:loadout', next);
}

function lookup(tag: string | null): SkillOption | null {
  if (!tag) return null;
  return allAllocatedByTag.value.get(tag) || null;
}
</script>

<template>
  <div class="loadout">
    <div class="loadout-head">
      <h3>Loadout</h3>
      <div class="hint">
        3 Abilities + 3 Techniques · drawn from your allocated skills across
        all classes
      </div>
    </div>

    <div class="loadout-row">
      <div class="row-label">Abilities</div>
      <div class="slots">
        <div
          v-for="(tag, i) in loadout.abilities"
          :key="`ab-${i}`"
          class="slot slot-ability"
          :class="{ filled: !!tag }"
          @click="openPicker('ability', i)"
          @contextmenu.prevent="clearSlot('ability', i)"
          :title="lookup(tag)?.name || `Empty ability slot ${i + 1}`"
        >
          <img
            v-if="lookup(tag)?.icon"
            :src="`/icons/${lookup(tag)!.icon}`"
            :alt="lookup(tag)?.name"
            class="slot-icon"
            draggable="false"
          />
          <span v-else class="slot-placeholder">+</span>
          <span v-if="lookup(tag)" class="slot-label">
            {{ lookup(tag)!.name }}
          </span>
        </div>
      </div>
    </div>

    <div class="loadout-row">
      <div class="row-label">Techniques</div>
      <div class="slots">
        <div
          v-for="(tag, i) in loadout.techniques"
          :key="`te-${i}`"
          class="slot slot-technique"
          :class="{ filled: !!tag }"
          @click="openPicker('technique', i)"
          @contextmenu.prevent="clearSlot('technique', i)"
          :title="lookup(tag)?.name || `Empty technique slot ${i + 1}`"
        >
          <img
            v-if="lookup(tag)?.icon"
            :src="`/icons/${lookup(tag)!.icon}`"
            :alt="lookup(tag)?.name"
            class="slot-icon"
            draggable="false"
          />
          <span v-else class="slot-placeholder">+</span>
          <span v-if="lookup(tag)" class="slot-label">
            {{ lookup(tag)!.name }}
          </span>
        </div>
      </div>
    </div>

    <!-- Picker modal -->
    <div v-if="pickerOpenFor" class="picker-overlay" @click="closePicker">
      <div class="picker" @click.stop>
        <div class="picker-head">
          <h4>
            Pick {{ pickerOpenFor.kind === 'ability' ? 'Ability' : 'Technique' }}
            for Slot {{ pickerOpenFor.index + 1 }}
          </h4>
          <button @click="closePicker">Cancel</button>
        </div>
        <div class="picker-options" v-if="eligibleFor(pickerOpenFor.kind).length > 0">
          <button class="picker-clear" @click="assign(null)">
            Clear slot
          </button>
          <button
            v-for="opt in eligibleFor(pickerOpenFor.kind)"
            :key="opt.tag"
            class="picker-option"
            :class="{
              selected:
                (pickerOpenFor.kind === 'ability'
                  ? loadout.abilities
                  : loadout.techniques
                ).includes(opt.tag),
            }"
            @click="assign(opt.tag)"
          >
            <img
              v-if="opt.icon"
              :src="`/icons/${opt.icon}`"
              :alt="opt.name"
              class="picker-icon"
              draggable="false"
            />
            <span class="picker-cls">{{ opt.className }}</span>
            <span class="picker-name">{{ opt.name }}</span>
          </button>
        </div>
        <div v-else class="picker-empty">
          No allocated
          {{ pickerOpenFor.kind === 'ability' ? 'Abilities or Spice skills' : 'Perks' }}
          yet. Spend points in a skill tree first.
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.loadout {
  margin-top: 22px;
  padding-top: 18px;
  border-top: 1px dashed var(--line-soft);
}
.loadout-head {
  display: flex;
  align-items: baseline;
  gap: 14px;
  margin-bottom: 14px;
  flex-wrap: wrap;
}
.loadout-head h3 {
  font-family: 'Cormorant Garamond', serif;
  font-size: 22px;
  margin: 0;
  font-weight: 500;
  color: var(--sand);
}
.loadout-head .hint {
  font-family: 'JetBrains Mono', monospace;
  font-size: 10.5px;
  color: var(--ink-muted);
  letter-spacing: 0.14em;
}

.loadout-row {
  display: flex;
  align-items: center;
  gap: 18px;
  margin-bottom: 14px;
}
.row-label {
  font-family: 'JetBrains Mono', monospace;
  font-size: 11px;
  letter-spacing: 0.2em;
  text-transform: uppercase;
  color: var(--ink-muted);
  width: 100px;
  flex-shrink: 0;
}
.slots {
  display: flex;
  gap: 14px;
  flex-wrap: wrap;
}

.slot {
  width: 96px;
  height: 96px;
  border: 2px dashed var(--line);
  border-radius: 6px;
  background-color: var(--bg-2);
  background-size: cover;
  background-position: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: border-color 0.15s, transform 0.1s;
  position: relative;
}
.slot:hover { border-color: var(--sand-2); transform: translateY(-1px); }
.slot.filled {
  border-style: solid;
  border-color: var(--spice);
  background-color: rgba(224, 138, 60, 0.08);
}
.slot-ability { background-image: url('/icons/slot-ability.png'); }
.slot-technique { background-image: url('/icons/slot-technique.png'); }
.slot.filled.slot-ability,
.slot.filled.slot-technique {
  /* dim the background tile so the icon stands out */
  background-blend-mode: multiply;
  background-color: rgba(0, 0, 0, 0.55);
}
.slot-icon {
  width: 72px;
  height: 72px;
  object-fit: contain;
  filter: drop-shadow(0 0 6px rgba(0, 0, 0, 0.6));
  pointer-events: none;
  user-select: none;
}
.slot-placeholder {
  font-family: 'Cormorant Garamond', serif;
  font-size: 32px;
  color: var(--ink-muted);
}
.slot-label {
  position: absolute;
  bottom: -22px;
  left: 50%;
  transform: translateX(-50%);
  font-family: 'JetBrains Mono', monospace;
  font-size: 10px;
  color: var(--ink-dim);
  white-space: nowrap;
  text-shadow: 0 0 4px var(--bg);
  pointer-events: none;
}

/* Picker */
.picker-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 24px;
}
.picker {
  background: var(--panel);
  border: 1px solid var(--line);
  border-radius: 6px;
  padding: 22px;
  width: 100%;
  max-width: 640px;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
}
.picker-head {
  display: flex;
  justify-content: space-between;
  align-items: baseline;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px dashed var(--line-soft);
}
.picker-head h4 {
  font-family: 'Cormorant Garamond', serif;
  font-size: 20px;
  margin: 0;
  font-weight: 500;
  color: var(--sand);
}
.picker-options {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
  gap: 10px;
  overflow-y: auto;
  padding-right: 4px;
}
.picker-option,
.picker-clear {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  padding: 10px 6px;
  border: 1px solid var(--line-soft);
  border-radius: 4px;
  background: var(--bg-2);
  color: var(--ink-dim);
  font-family: 'Inter', sans-serif;
  font-size: 12px;
  cursor: pointer;
  text-transform: none;
  letter-spacing: 0;
}
.picker-option:hover,
.picker-clear:hover {
  border-color: var(--sand-2);
  color: var(--sand);
}
.picker-option.selected {
  border-color: var(--spice);
  background: rgba(224, 138, 60, 0.08);
}
.picker-icon {
  width: 48px;
  height: 48px;
  object-fit: contain;
}
.picker-cls {
  font-family: 'JetBrains Mono', monospace;
  font-size: 9.5px;
  letter-spacing: 0.16em;
  color: var(--ink-muted);
  text-transform: uppercase;
}
.picker-name {
  text-align: center;
  line-height: 1.2;
}
.picker-clear {
  font-style: italic;
  color: var(--ember);
}
.picker-empty {
  padding: 16px;
  font-family: 'JetBrains Mono', monospace;
  font-size: 12px;
  color: var(--ink-muted);
  text-align: center;
}
</style>
