<script>
  import { onMount } from "svelte";

  const apiBaseUrl = "YOUR_API_BASE_URL";
  const apiKey = "YOUR_API_KEY";

  let caseTypes = [];
  let status = "";
  let form = {
    name: "",
    email: "",
    phone: "",
    caseTypeId: "",
    message: ""
  };

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

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

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

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

<form class="dp-affiliate-form" on:submit|preventDefault={submitLead}>
  <input bind:value={form.name} placeholder="Name" required>
  <input bind:value={form.email} type="email" placeholder="Email" required>
  <input bind:value={form.phone} placeholder="Phone" required>

  <select bind:value={form.caseTypeId} required>
    <option value="">Select case type</option>
    {#each caseTypes as item}
      <option value={item.id}>{item.name}</option>
    {/each}
  </select>

  <textarea bind:value={form.message} placeholder="Message" required></textarea>
  <button type="submit">Submit Lead</button>
  <p>{status}</p>
</form>
