<template>
  <Transition name="overlay">
    <div v-if="visible" class="wash-overlay">
      <!-- Header -->
      <div class="wash-header">
        <div class="header-left">
          <div class="header-icon">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
              <path d="M12 1v22M17 5H9.5a3.5 3.5 0 000 7h5a3.5 3.5 0 010 7H6"/>
            </svg>
          </div>
          <h2>{{ stationLabel }}</h2>
        </div>
        <button class="close-btn" @click="close">
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M1 1l12 12M13 1L1 13" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>
        </button>
      </div>

      <!-- Body -->
      <div class="wash-body">
        <WashMenu
          :dirtyAmount="dirtyAmount"
          :washRate="washRate"
          :dirtyLabel="dirtyLabel"
          @wash="onWash"
        />
      </div>
    </div>
  </Transition>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import WashMenu from './components/WashMenu.vue'

const visible = ref(false)
const stationLabel = ref('')
const dirtyAmount = ref(0)
const washRate = ref(0.8)
const dirtyLabel = ref('Marked Bills')

function onWash(amount) {
  fetch(`https://${GetParentResourceName()}/wash`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ amount }),
  })
}

function close() {
  visible.value = false
  fetch(`https://${GetParentResourceName()}/close`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({}),
  })
}

function GetParentResourceName() {
  return window.GetParentResourceName ? window.GetParentResourceName() : 'mercyv-moneywash'
}

function handleMessage(event) {
  const data = event.data
  switch (data.type) {
    case 'open':
      visible.value = true
      stationLabel.value = data.stationLabel || 'Geldwaesche'
      dirtyAmount.value = data.dirtyAmount || 0
      washRate.value = data.washRate || 0.8
      dirtyLabel.value = data.dirtyLabel || 'Marked Bills'
      break
    case 'close':
      visible.value = false
      break
    case 'washSuccess':
      // UI stays open, amount will be updated
      break
    case 'updateAmount':
      dirtyAmount.value = data.dirtyAmount || 0
      break
  }
}

onMounted(() => {
  window.addEventListener('message', handleMessage)
  window.addEventListener('keydown', (e) => {
    if (e.key === 'Escape' && visible.value) close()
  })
})

onUnmounted(() => {
  window.removeEventListener('message', handleMessage)
})
</script>
