<template>
  <form class="dp-affiliate-form" @submit.prevent="submitLead">
    <input v-model="form.name" placeholder="Name" required>
    <input v-model="form.email" type="email" placeholder="Email" required>
    <input v-model="form.phone" placeholder="Phone" required>

    <select v-model="form.caseTypeId" required>
      <option value="">Select case type</option>
      <option v-for="item in caseTypes" :key="item.id" :value="item.id">{{ item.name }}</option>
    </select>

    <textarea v-model="form.message" placeholder="Message" required></textarea>
    <button type="submit">Submit Lead</button>
    <p>{{ status }}</p>
  </form>
</template>

<script setup>
import { onMounted, reactive, ref } from "vue";

const API_BASE_URL = "YOUR_API_BASE_URL";
const API_KEY = "YOUR_API_KEY";

const caseTypes = ref([]);
const status = ref("");
const form = reactive({
  name: "",
  email: "",
  phone: "",
  caseTypeId: "",
  message: ""
});

onMounted(async () => {
  const response = await fetch(`${API_BASE_URL}/api/leads/casetypes`);
  caseTypes.value = await response.json();
});

async function submitLead() {
  status.value = "Submitting...";

  const response = await fetch(`${API_BASE_URL}/api/leads`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-Api-Key": API_KEY
    },
    body: JSON.stringify({
      ...form,
      caseTypeId: Number(form.caseTypeId),
      sourceType: 2,
      sourceUrl: window.location.href
    })
  });

  const data = await response.json();
  status.value = response.ok ? `Lead submitted: ${data.leadId}` : data.error || "Please try again.";
}
</script>
