/**
 * WhatsApp checkout message builder.
 *
 * Shared by the cart drawer and the floating checkout button so both produce
 * the exact same, well-organized order message.
 *
 * Layout (plain text with WhatsApp markdown-style formatting):
 *
 *   🌸 *ABELHA RAINHA* 🌸
 *   ━━━━━━━━━━━━━━━━━━━
 *
 *   🛍️ *MEU PEDIDO*
 *
 *   1️⃣ 2x Produto A
 *      Código: 3504
 *      R$ 50,00
 *
 *   2️⃣ 1x Produto B
 *      Código: 3505
 *      R$ 25,00
 *
 *   ━━━━━━━━━━━━━━━━━━━
 *   💰 *TOTAL: R$ 75,00*
 *   📦 3 itens
 *
 *   Gostaria de finalizar meu pedido! 
 */

import type { Product } from '@/lib/types'
import { formatPrice, getEffectivePrice } from '@/lib/catalog-utils'

const DIVIDER = '━━━━━━━━━━━━━━━━━━━'

// Number emojis 1️⃣ … 9️⃣, then 🔟+ falls back to a plain "#10" prefix.
const NUM_EMOJIS = ['1️⃣', '2️⃣', '3️⃣', '4️⃣', '5️⃣', '6️⃣', '7️⃣', '8️⃣', '9️⃣']

export interface OrderItem {
  product: Product
  qty: number
  unitPrice: number
}

/**
 * Build the full WhatsApp checkout message for a list of cart items.
 *
 * Se `distributorName` for informado, personaliza o cabeçalho/rodapé para
 * indicar que o pedido está sendo enviado para aquele distribuidor.
 */
export function buildWhatsAppMessage(
  items: OrderItem[],
  distributorName?: string | null
): string {
  if (items.length === 0) return ''

  const subtotal = items.reduce((s, i) => s + i.unitPrice * i.qty, 0)
  const totalItems = items.reduce((s, i) => s + i.qty, 0)
  const totalSavings = items.reduce((s, i) => {
    if (i.product.promotionalPrice && i.product.promotionalPrice < i.product.price) {
      return s + (i.product.price - i.product.promotionalPrice) * i.qty
    }
    return s
  }, 0)

  const lines: string[] = []

  // Header
  lines.push('🌸 *ABELHA RAINHA* 🌸')
  if (distributorName) {
    lines.push(` Atendimento: *${distributorName}*`)
  }
  lines.push(DIVIDER)
  lines.push('')
  lines.push('🛍️ *MEU PEDIDO*')
  lines.push('')

  // Items
  items.forEach((item, idx) => {
    const num = idx < 9 ? NUM_EMOJIS[idx] : `*${idx + 1}.*`
    const { product, qty, unitPrice } = item
    const lineTotal = unitPrice * qty

    lines.push(`${num} *${qty}x ${product.name}*`)

    // Code + volume on the same sub-line for compactness
    const metaParts: string[] = [`Código: ${product.code}`]
    if (product.volume) metaParts.push(product.volume)
    lines.push(`   └ ${metaParts.join(' • ')}`)

    // Price line — show original (struck-through) + promo if applicable
    if (product.promotionalPrice && product.promotionalPrice < product.price) {
      const originalLine = formatPrice(product.price * qty)
      lines.push(`   💵 ~${originalLine}~ → *${formatPrice(lineTotal)}*`)
    } else {
      lines.push(`   💵 ${formatPrice(lineTotal)}`)
    }

    lines.push('')
  })

  // Footer
  lines.push(DIVIDER)
  lines.push(`💰 *TOTAL: ${formatPrice(subtotal)}*`)
  lines.push(`📦 ${totalItems} ${totalItems === 1 ? 'item' : 'itens'}`)

  if (totalSavings > 0) {
    lines.push(`🎉 Economia: ${formatPrice(totalSavings)}`)
  }

  lines.push('')
  lines.push(
    distributorName
      ? `Gostaria de finalizar meu pedido com ${distributorName}! `
      : 'Gostaria de finalizar meu pedido! '
  )

  return lines.join('\n')
}

/**
 * Build a compact share-text (used by navigator.share / clipboard).
 * Shorter than the full checkout message since it's meant for quick sharing.
 */
export function buildShareText(items: OrderItem[]): string {
  if (items.length === 0) return ''

  const subtotal = items.reduce((s, i) => s + i.unitPrice * i.qty, 0)
  const totalItems = items.reduce((s, i) => s + i.qty, 0)

  const itemLines = items
    .map(i => `▪️ ${i.qty}x *${i.product.name}*`)
    .join('\n')

  return (
    `🌸 *Meu carrinho Abelha Rainha*\n` +
    `📦 ${totalItems} ${totalItems === 1 ? 'item' : 'itens'} • 💰 ${formatPrice(subtotal)}\n\n` +
    `${itemLines}`
  )
}

/**
 * Constrói a URL completa do WhatsApp (wa.me) para um checkout.
 *
 * - Se `whatsapp` for informado (número do distribuidor vinculado), abre o
 *   chat DIRETAMENTE com ele: https://wa.me/{whatsapp}?text={msg} e
 *   personaliza a mensagem com o nome do distribuidor.
 * - Se não houver distribuidor vinculado, cai no fluxo antigo: abre o
 *   WhatsApp sem destinatário definido (https://wa.me/?text={msg}), deixando
 *   o cliente escolher para quem enviar.
 *
 * `whatsapp` deve conter apenas dígitos, já com o código do país (ex: 5511...).
 */
export function buildWhatsAppUrl(
  items: OrderItem[],
  whatsapp?: string | null,
  distributorName?: string | null
): string {
  const msg = buildWhatsAppMessage(items, distributorName)
  const text = encodeURIComponent(msg)
  const phone = whatsapp ? whatsapp.replace(/\D/g, '') : ''
  return phone
    ? `https://wa.me/${phone}?text=${text}`
    : `https://wa.me/?text=${text}`
}
