<script lang="ts">
  /// <reference types="../../types/turnstile" />
  import { onMount } from 'svelte'
  import IconSend from '~icons/lucide/send'
  import IconCheck from '~icons/lucide/check-circle'
  import IconAlertCircle from '~icons/lucide/alert-circle'

  interface Props {
    sitekey: string
  }

  let { sitekey }: Props = $props()

  let formState = $state<'idle' | 'submitting' | 'success' | 'error'>('idle')
  let errorMessage = $state('')
  let turnstileWidgetId: string | null = $state(null)
  let turnstileContainer: HTMLElement
  let turnstileInitialized = false

  const TURNSTILE_SITEKEY = sitekey

  function initTurnstile() {
    if (turnstileInitialized) return
    turnstileInitialized = true

    // Wait for Turnstile script to load
    const interval = setInterval(() => {
      if (typeof window.turnstile !== 'undefined') {
        clearInterval(interval)
        // Render Turnstile widget
        turnstileWidgetId = window.turnstile.render(turnstileContainer, {
          sitekey: TURNSTILE_SITEKEY,
          theme: 'auto',
          size: 'normal',
          appearance: 'execute',
        })
      }
    }, 100)
  }

  onMount(() => {
    return () => {
      if (turnstileWidgetId !== null && typeof window.turnstile !== 'undefined') {
        window.turnstile.remove(turnstileWidgetId)
      }
    }
  })

  async function handleSubmit(event: Event) {
    event.preventDefault()
    formState = 'submitting'
    errorMessage = ''

    // Get Turnstile token
    let turnstileToken = ''
    if (turnstileWidgetId !== null && typeof window.turnstile !== 'undefined') {
      turnstileToken = window.turnstile.getResponse(turnstileWidgetId)

      if (!turnstileToken) {
        formState = 'error'
        errorMessage = 'Please complete the verification challenge.'
        return
      }
    }

    const form = event.target as HTMLFormElement
    const formData = new FormData(form)

    // Add Turnstile token to form data
    const data = {
      ...Object.fromEntries(formData),
      'cf-turnstile-response': turnstileToken,
    }

    try {
      const response = await fetch('https://submit-form.com/JXY5zUICN', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Accept: 'application/json',
        },
        body: JSON.stringify(data),
      })

      if (response.ok) {
        formState = 'success'
        form.reset()

        // Reset Turnstile widget
        if (turnstileWidgetId !== null && typeof window.turnstile !== 'undefined') {
          window.turnstile.reset(turnstileWidgetId)
        }

        // Reset to idle after 5 seconds
        setTimeout(() => {
          formState = 'idle'
        }, 5000)
      } else {
        formState = 'error'
        errorMessage = 'Failed to send message. Please try again.'

        // Reset Turnstile on error
        if (turnstileWidgetId !== null && typeof window.turnstile !== 'undefined') {
          window.turnstile.reset(turnstileWidgetId)
        }
      }
    } catch (error) {
      formState = 'error'
      errorMessage = 'Network error. Please check your connection and try again.'

      // Reset Turnstile on error
      if (turnstileWidgetId !== null && typeof window.turnstile !== 'undefined') {
        window.turnstile.reset(turnstileWidgetId)
      }
    }
  }
</script>

<form onsubmit={handleSubmit} onfocusin={initTurnstile} class="flex flex-col gap-4">
  <div class="flex flex-col gap-2">
    <label for="name" class="text-sm font-medium text-foreground">
      Name <span class="text-destructive">*</span>
    </label>
    <input
      type="text"
      id="name"
      name="name"
      placeholder="Your name"
      required
      disabled={formState === 'submitting'}
      class="w-full rounded-md border border-border bg-background px-4 py-2.5 text-foreground placeholder:text-muted-foreground focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20 disabled:cursor-not-allowed disabled:opacity-50 transition-all duration-200"
    />
  </div>

  <div class="flex flex-col gap-2">
    <label for="email" class="text-sm font-medium text-foreground">
      Email <span class="text-destructive">*</span>
    </label>
    <input
      type="email"
      id="email"
      name="email"
      placeholder="your.email@example.com"
      autocomplete="email"
      required
      disabled={formState === 'submitting'}
      class="w-full rounded-md border border-border bg-background px-4 py-2.5 text-foreground placeholder:text-muted-foreground focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20 disabled:cursor-not-allowed disabled:opacity-50 transition-all duration-200"
    />
  </div>

  <div class="flex flex-col gap-2">
    <label for="message" class="text-sm font-medium text-foreground">
      Message <span class="text-destructive">*</span>
    </label>
    <textarea
      id="message"
      name="message"
      placeholder="Tell me about the opportunity..."
      required
      rows="5"
      disabled={formState === 'submitting'}
      class="w-full resize-y rounded-md border border-border bg-background px-4 py-2.5 text-foreground placeholder:text-muted-foreground focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20 disabled:cursor-not-allowed disabled:opacity-50 transition-all duration-200 min-h-[120px]"
    ></textarea>
  </div>

  

  {#if formState === 'success'}
    <div class="flex items-center gap-2 rounded-md bg-primary/10 border border-primary/20 px-4 py-3 text-sm text-primary">
      <IconCheck class="size-5 shrink-0" />
      <p>Message sent successfully! I'll get back to you soon.</p>
    </div>
  {/if}

  {#if formState === 'error'}
    <div class="flex items-center gap-2 rounded-md bg-destructive/10 border border-destructive/20 px-4 py-3 text-sm text-destructive">
      <IconAlertCircle class="size-5 shrink-0" />
      <p>{errorMessage}</p>
    </div>
  {/if}

  <div class="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4 min-h-[65px]">
    <!-- Turnstile Widget (300x65 for normal size) -->
    <div bind:this={turnstileContainer} class="min-w-[300px]"></div>

    <button
      type="submit"
      disabled={formState === 'submitting'}
      class="w-full sm:w-auto inline-flex items-center justify-center gap-2 rounded-md bg-primary px-6 py-2.5 text-sm font-medium text-primary-foreground hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 transition-all duration-200"
    >
      {#if formState === 'submitting'}
        <span class="inline-block size-4 animate-spin rounded-full border-2 border-current border-t-transparent"></span>
        Sending...
      {:else}
        <IconSend class="size-4" />
        Send Message
      {/if}
    </button>
  </div>
</form>
