<template>
  <div class="captcha-wrapper">
    <div class="captcha-container">
      <input v-model="captchaInput" placeholder="Enter code" class="form-control"/>
      
      <img
        v-show="captchaLoaded"
        :src="captchaUrl"
        alt="CAPTCHA"
        @load="onCaptchaLoad"
      />
      
      <FontAwesomeIcon icon="fa-solid fa-sync-alt" class="refresh-icon" @click="refreshCaptcha" />
    </div>
  </div>
</template>



<script setup>
import { ref, watch, onMounted } from 'vue'

// 👇 Use apiUrl from runtime config
const captchaUrl = ref('');  // initially empty
const captchaLoaded = ref(false);
const captchaInput = ref('');

onMounted(() => {
  loadCaptcha();
});

const loadCaptcha = () => {
  captchaLoaded.value = false;
  captchaUrl.value = `${window.location.origin}/api/captcha?${Date.now()}`;
};

const refreshCaptcha = () => {
  loadCaptcha();
};

const onCaptchaLoad = () => {
  captchaLoaded.value = true;
};

// Emit to parent whenever input changes
const emit = defineEmits(['update:captcha']);

watch(captchaInput, (newVal) => {
  emit('update:captcha', newVal)
});
</script>

<style scoped>
.captcha-wrapper {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 15px;
}

.captcha-container {
  position: relative;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-items: center;
  flex-direction: row;
  gap:10px;
}

.captcha-container img {
  max-height: 40px;
  border-radius: 4px;
}

.refresh-icon {
  font-size: 1.2rem;
  cursor: pointer;
  color: #3b82f6;
}

.refresh-icon:hover {
  color: #2563eb;
}
.form-control {
  display: inline-block;
  width: 50%;
  flex:1;
  padding: 0.375rem 0.75rem;
  font-size: 1rem;
  font-weight: 400;
  line-height: 1.5;
  color: #212529;
  background-color: #fff;
  background-clip: padding-box;
  border: 1px solid #ced4da;
  border-radius: 0.375rem;
  transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
}

.form-control:focus {
  color: #212529;
  background-color: #fff;
  border-color: #86b7fe;
  outline: 0;
  box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
}

.btn {
  width: 100%;
  padding: 0.8rem;
  font-weight: 600;
  font-size: 1.1rem;
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn:hover:not(:disabled) {
  background-color: #2563eb;
}

.btn:disabled {
  background-color: #93c5fd;
  cursor: not-allowed;
}
</style>
