'use client'

import { motion, AnimatePresence } from 'framer-motion'
import { useState } from 'react'
import { ShoppingBag, Check } from 'lucide-react'
import { useCatalogStore } from '@/lib/store'
import { formatPrice, getEffectivePrice } from '@/lib/catalog-utils'
import { buildWhatsAppUrl } from '@/lib/whatsapp-message'

/**
 * FloatingCheckoutButton — persistent "Finalizar Compra" CTA pinned to the
 * bottom-left corner of the screen, above the magazine viewer's bottom
 * control bar (page slider).
 *
 * Behavior:
 * - Visible only when the cart has at least one item.
 * - Hidden while the cart drawer is open (the drawer has its own checkout
 *   button — showing two would be redundant).
 * - Hidden while the product detail modal is open (avoids floating over the
 *   full-screen modal).
 * - On click: builds the same WhatsApp checkout message as the cart drawer
 *   and opens wa.me in a new tab. Shows a brief "✓ Pedido enviado!" flash.
 *
 * No hydration-mismatch guard needed: Zustand `persist` hydrates from
 * localStorage AFTER the first render, so both the server render and the
 * client's first render see an empty cart (button hidden) — they match.
 * The button then appears naturally once the persisted cart hydrates.
 *
 * z-index: 35 — sits above the magazine viewer content and below the cart
 * drawer (z-40) and product modal (z-50), so it never floats over overlays.
 */
export function FloatingCheckoutButton() {
  const cart = useCatalogStore(s => s.cart)
  const products = useCatalogStore(s => s.products)
  const cartOpen = useCatalogStore(s => s.cartOpen)
  const selectedProduct = useCatalogStore(s => s.selectedProduct)
  // Distribuidor vinculado (?d=slug). Quando presente, o checkout abre o
  // chat DIRETO com o WhatsApp dele.
  const distributor = useCatalogStore(s => s.currentDistributor)

  const [flash, setFlash] = useState(false)

  // Compute total + item count from the preloaded products cache.
  const { total, count } = (() => {
    if (products.length === 0 || cart.length === 0) return { total: 0, count: 0 }
    let t = 0, c = 0
    for (const item of cart) {
      const p = products.find(pp => pp.code === item.code)
      if (p) { t += getEffectivePrice(p) * item.qty; c += item.qty }
    }
    return { total: t, count: c }
  })()

  // Hide when: cart empty, cart drawer open, or product modal open
  const visible = count > 0 && !cartOpen && !selectedProduct

  const handleCheckout = () => {
    // Build the WhatsApp URL — same logic as the cart drawer. Se há
    // distribuidor vinculado, a mensagem vai direto para o número dele.
    const items = cart.map(item => {
      const p = products.find(pp => pp.code === item.code)
      if (!p) return null
      return { product: p, qty: item.qty, unitPrice: getEffectivePrice(p) }
    }).filter(Boolean) as Array<{ product: typeof products[number]; qty: number; unitPrice: number }>

    const url = buildWhatsAppUrl(items, distributor?.whatsapp, distributor?.name)
    window.open(url, '_blank')
    setFlash(true)
    setTimeout(() => setFlash(false), 2000)
  }

  return (
    <AnimatePresence>
      {visible && (
        <motion.button
          initial={{ opacity: 0, y: 40, scale: 0.85 }}
          animate={{ opacity: 1, y: 0, scale: 1 }}
          exit={{ opacity: 0, y: 40, scale: 0.85 }}
          transition={{ type: 'spring', damping: 24, stiffness: 280 }}
          onClick={handleCheckout}
          // Pinned to the BOTTOM of the viewport on mobile — sits right at
          // the bottom edge (4px gap so the rounded pill isn't clipped by
          // the screen). This places it below the catalog image area, over
          // the left end of the bottom control bar. The page slider stays
          // usable on the right (the button only covers the page-number +
          // left portion of the slider). Desktop keeps bottom-20 (floating
          // above the control bar).
          className="fixed left-3 sm:left-4 bottom-1 sm:bottom-20 z-[35] flex items-center gap-2 pl-3 pr-3 sm:pr-4 h-12 sm:h-14 rounded-full shadow-2xl ring-1 ring-black/5 active:scale-95 transition-transform"
          aria-label={`Finalizar compra — ${count} ${count === 1 ? 'item' : 'itens'}, total ${formatPrice(total)}`}
          title="Finalizar compra no WhatsApp"
        >
          {/* Pulsing glow ring — draws attention without being annoying */}
          {!flash && (
            <span
              className="absolute inset-0 rounded-full bg-green-400 fcb-pulse-ring"
              style={{ zIndex: -1 }}
              aria-hidden
            />
          )}

          {/* Background — green when idle, darker green on flash */}
          <span
            className={`absolute inset-0 rounded-full transition-colors ${flash ? 'bg-green-700' : 'bg-green-500'}`}
            aria-hidden
          />

          {/* Content */}
          <span className="relative flex items-center gap-2">
            <span className="w-7 h-7 rounded-full bg-white/25 flex items-center justify-center flex-shrink-0">
              {flash ? (
                <Check className="w-4 h-4 text-white" strokeWidth={3} />
              ) : (
                <ShoppingBag className="w-4 h-4 text-white" />
              )}
            </span>
            <span className="flex flex-col items-start leading-none">
              <span className="text-[9px] uppercase tracking-wider text-white/80 font-semibold">
                {flash ? 'Enviado!' : 'Finalizar'}
              </span>
              <span className="text-sm font-extrabold text-white tabular-nums whitespace-nowrap">
                {flash ? 'WhatsApp ✓' : formatPrice(total)}
              </span>
            </span>
            {/* Item count badge */}
            {!flash && (
              <span className="ml-0.5 min-w-[20px] h-5 px-1.5 bg-white text-green-600 text-[10px] font-bold rounded-full flex items-center justify-center flex-shrink-0">
                {count}
              </span>
            )}
          </span>

          <style jsx>{`
            .fcb-pulse-ring {
              animation: fcb-pulse 2s ease-out infinite;
            }
            @keyframes fcb-pulse {
              0%   { transform: scale(1);    opacity: 0.55; }
              70%  { transform: scale(1.35); opacity: 0;    }
              100% { transform: scale(1.35); opacity: 0;    }
            }
            @media (prefers-reduced-motion: reduce) {
              .fcb-pulse-ring { animation: none !important; opacity: 0 !important; }
            }
          `}</style>
        </motion.button>
      )}
    </AnimatePresence>
  )
}
