'use client'

import { useEffect } from 'react'

export default function SuccessClient() {
  useEffect(() => {
    const params = new URLSearchParams(window.location.search)
    const sessionId = params.get('session_id')
    const loading = document.getElementById('loading')

    if (!sessionId) {
      if (loading) loading.textContent = 'Commande enregistrée.'
      return
    }

    fetch(`/api/session/${sessionId}`)
      .then((r) => r.json())
      .then((data) => {
        const orderDetails = document.getElementById('order-details') as HTMLElement | null
        if (loading) loading.style.display = 'none'
        if (orderDetails) orderDetails.style.display = 'flex'

        const amount = data.amount ? `${(data.amount / 100).toLocaleString('fr-FR')} €` : '—'
        const amountEl = document.getElementById('amount-display')
        const emailEl = document.getElementById('email-display')
        const productEl = document.getElementById('product-display')
        if (amountEl) amountEl.textContent = amount
        if (emailEl) emailEl.textContent = data.customer_email ?? '—'
        if (productEl && data.product) productEl.textContent = String(data.product).replace(/-/g, '_').toUpperCase()

        if (data.receipt_url) {
          const btn = document.getElementById('receipt-btn') as HTMLAnchorElement | null
          if (btn) {
            btn.href = data.receipt_url
            btn.style.display = 'inline-block'
          }
        }
      })
      .catch(() => {
        if (loading) loading.textContent = 'Commande enregistrée.'
      })
  }, [])

  return null
}
