import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { trackInitiateCheckout, trackLead } from "@/lib/facebookPixel";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Checkbox } from "@/components/ui/checkbox";
import { toast } from "sonner";
import { ChevronRight, ChevronLeft, Music, Heart, MessageCircle, Loader2 } from "lucide-react";
import { CheckoutDialog } from "./CheckoutDialog";
import { TermsDialog } from "./TermsDialog";
import { PrivacyDialog } from "./PrivacyDialog";

type FormData = {
  genre: string;
  customGenre?: string;
  occasion: string;
  customOccasion?: string;
  bpm: string;
  voiceType: string;
  from: string;
  recipient: string;
  relationship: string;
  customRelationship?: string;
  story: string;
  whatsapp: string;
  email: string;
  additionalNotes: string;
};

interface OrderFormProps {
  onSuccess?: () => void;
}

export const OrderForm = ({ onSuccess }: OrderFormProps) => {
  const [currentStep, setCurrentStep] = useState(1);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [acceptedTerms, setAcceptedTerms] = useState(false);
  const [couponCode, setCouponCode] = useState("");
  const [appliedCoupon, setAppliedCoupon] = useState<any>(null);
  const [isValidatingCoupon, setIsValidatingCoupon] = useState(false);
  const [productPrice, setProductPrice] = useState<number | null>(null);
  const [discount, setDiscount] = useState<number>(0);
  const [originalPrice, setOriginalPrice] = useState<number | null>(null);
  const [isPricesLoaded, setIsPricesLoaded] = useState(false);
  const [showCheckout, setShowCheckout] = useState(false);
  const [checkoutData, setCheckoutData] = useState<any>(null);
  const [formData, setFormData] = useState<FormData>({
    genre: '',
    customGenre: '',
    occasion: '',
    customOccasion: '',
    bpm: '',
    voiceType: '',
    from: '',
    recipient: '',
    relationship: '',
    customRelationship: '',
    story: '',
    whatsapp: '',
    email: '',
    additionalNotes: '',
  });

  useEffect(() => {
    loadProductPrice();
  }, []);

  // Track Facebook Pixel event when reaching checkout step
  useEffect(() => {
    if (currentStep === 3 && productPrice !== null) {
      const finalAmount = appliedCoupon ? appliedCoupon.finalAmount : productPrice;
      trackInitiateCheckout(finalAmount);
    }
  }, [currentStep, productPrice, appliedCoupon]);

  const loadProductPrice = async () => {
    try {
      console.log('🔍 Carregando preços do banco de dados...');
      
      const { data, error } = await supabase
        .from('settings')
        .select('key, value')
        .in('key', ['product_price', 'original_price', 'promotional_discount']);

      if (error) throw error;

      if (data && data.length > 0) {
        const priceData = data.find(item => item.key === 'product_price');
        const originalData = data.find(item => item.key === 'original_price');
        const discountData = data.find(item => item.key === 'promotional_discount');

        const loadedPrice = priceData ? parseFloat(priceData.value) : null;
        const loadedOriginal = originalData ? parseFloat(originalData.value) : null;
        const loadedDiscount = discountData ? parseFloat(discountData.value) : 0;

        console.log('💰 Preços carregados:', { 
          product: loadedPrice, 
          original: loadedOriginal, 
          discount: loadedDiscount 
        });

        // ✅ VALIDAÇÃO: Garantir que o preço seja válido
        if (!loadedPrice || loadedPrice < 1) {
          console.error('⚠️ PREÇO INVÁLIDO DETECTADO:', loadedPrice);
          toast.error('Erro ao carregar preço. Por favor, atualize a página.');
          setIsPricesLoaded(true);
          return;
        }

        setProductPrice(loadedPrice);
        setOriginalPrice(loadedOriginal);
        setDiscount(loadedDiscount);
        setIsPricesLoaded(true);
      } else {
        console.error('⚠️ Nenhum preço encontrado no banco de dados');
        toast.error('Erro ao carregar preços. Por favor, atualize a página.');
        setIsPricesLoaded(true);
      }
    } catch (error) {
      console.error('Error loading product price:', error);
      toast.error('Erro ao carregar preços. Por favor, atualize a página.');
      setIsPricesLoaded(true);
    }
  };

  const updateFormData = (field: keyof FormData, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  const formatWhatsApp = (value: string) => {
    const numbers = value.replace(/\D/g, "");
    if (numbers.length <= 11) {
      return numbers.replace(/(\d{2})(\d{5})(\d{4})/, "($1) $2-$3").substring(0, 15);
    }
    return value;
  };

  const validateStep = (step: number): boolean => {
    if (step === 1) {
      if (!formData.genre || !formData.occasion || !formData.bpm || !formData.voiceType) {
        toast.error("Por favor, preencha todos os campos");
        return false;
      }
      if (formData.genre === "outro" && !formData.customGenre?.trim()) {
        toast.error("Por favor, especifique o estilo musical");
        return false;
      }
      if (formData.occasion === "outro" && !formData.customOccasion?.trim()) {
        toast.error("Por favor, especifique a ocasião");
        return false;
      }
    } else if (step === 2) {
      if (!formData.from || !formData.recipient || !formData.relationship || !formData.story) {
        toast.error("Por favor, preencha todos os campos");
        return false;
      }
      if (formData.relationship === "outro" && !formData.customRelationship?.trim()) {
        toast.error("Por favor, especifique o relacionamento");
        return false;
      }
      if (formData.story.length < 20) {
        toast.error("A história precisa ter pelo menos 20 caracteres");
        return false;
      }
    } else if (step === 3) {
      if (!formData.whatsapp || !formData.email || !acceptedTerms) {
        toast.error("Por favor, preencha WhatsApp, email e aceite os termos");
        return false;
      }
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailRegex.test(formData.email)) {
        toast.error("Por favor, insira um email válido");
        return false;
      }
    }
    return true;
  };

  const nextStep = () => {
    if (validateStep(currentStep)) {
      // Track Lead event when completing step 2 (recipient info)
      if (currentStep === 2) {
        trackLead('Order Form - Recipient Info Completed');
      }
      
      setCurrentStep(prev => Math.min(prev + 1, 3));
      if (currentStep === 1) {
        toast.success("Ótimo! Continue...", { duration: 1500 });
      }
    }
  };

  const prevStep = () => {
    setCurrentStep(prev => Math.max(prev - 1, 1));
  };

  const validateCoupon = async () => {
    if (!isPricesLoaded || productPrice === null) {
      toast.error("Aguarde o carregamento dos preços...");
      return;
    }
    
    if (!couponCode.trim()) {
      toast.error("Digite um código de cupom");
      return;
    }

    console.log('🎫 Validando cupom com preço:', productPrice);
    
    setIsValidatingCoupon(true);
    try {
      const { data, error } = await supabase.functions.invoke('validate-coupon', {
        body: {
          couponCode: couponCode.trim(),
          purchaseAmount: productPrice,
        },
      });

      if (error) throw error;

      if (data.valid) {
        setAppliedCoupon(data);
        toast.success(`Cupom aplicado! Desconto de R$ ${data.discountAmount.toFixed(2)}`);
      } else {
        setAppliedCoupon(null);
        toast.error(data.error || "Cupom inválido");
      }
    } catch (error: any) {
      console.error('Error validating coupon:', error);
      toast.error("Erro ao validar cupom");
      setAppliedCoupon(null);
    } finally {
      setIsValidatingCoupon(false);
    }
  };

  const removeCoupon = () => {
    setCouponCode("");
    setAppliedCoupon(null);
    toast.success("Cupom removido");
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!validateStep(3)) return;

    setIsSubmitting(true);

    try {
      // Criar pedido via edge function (service role) — evita problemas de RLS
      // no fluxo anônimo e valida preço/cupom no servidor.
      const { data, error } = await supabase.functions.invoke("create-order", {
        body: {
          genre: formData.genre,
          occasion: formData.occasion,
          bpm: formData.bpm,
          voice_type: formData.voiceType,
          sender_name: formData.from,
          recipient_name: formData.recipient,
          relationship: formData.relationship,
          story: formData.story,
          whatsapp: formData.whatsapp,
          email: formData.email,
          additional_notes: formData.additionalNotes,
          coupon_code: appliedCoupon ? appliedCoupon.coupon.code : null,
        },
      });

      if (error || !data?.orderId) {
        throw new Error(error?.message || data?.error || "Falha ao criar pedido");
      }

      console.log("Order created:", data);

      toast.success("Pedido criado! Abrindo checkout...");

      setCheckoutData({
        orderId: data.orderId,
        amount: Number(data.finalAmount),
        description: data.description ?? `Música Personalizada - ${formData.occasion}`,
        email: data.email ?? formData.email,
      });
      setShowCheckout(true);
    } catch (error: any) {
      console.error("Error:", error);
      toast.error(error.message || "Erro ao enviar pedido");
    } finally {
      setIsSubmitting(false);
    }
  };

  const steps = [
    { number: 1, label: "Sobre a música", icon: Music },
    { number: 2, label: "Conte a história", icon: Heart },
    { number: 3, label: "Finalizar", icon: MessageCircle },
  ];

  return (
    <>
      {checkoutData && (
        <CheckoutDialog
          open={showCheckout}
          onOpenChange={setShowCheckout}
          orderId={checkoutData.orderId}
          amount={checkoutData.amount}
          email={checkoutData.email}
          description={checkoutData.description}
          onSuccess={onSuccess}
        />
      )}
      
      <div className="bg-gradient-card backdrop-blur-sm rounded-2xl p-4 sm:p-6 lg:p-8 border border-primary/20 shadow-card pb-safe">
      {/* Progress Indicator */}
      <div className="relative mb-8 sm:mb-12">
        {/* Background line */}
        <div className="absolute top-5 left-0 right-0 h-0.5 bg-muted" />
        
        {/* Active progress line */}
        <div 
          className="absolute top-5 left-0 h-0.5 bg-gradient-hero transition-all duration-500"
          style={{ width: `${((currentStep - 1) / (steps.length - 1)) * 100}%` }}
        />

        {/* Steps */}
        <div className="relative flex justify-between">
          {steps.map((step) => {
            const Icon = step.icon;
            const isActive = currentStep === step.number;
            const isCompleted = currentStep > step.number;

            return (
              <div key={step.number} className="flex flex-col items-center max-w-[80px]">
                <div
                  className={`w-10 h-10 sm:w-12 sm:h-12 rounded-full flex items-center justify-center transition-all duration-300 ${
                    isActive || isCompleted
                      ? "bg-gradient-hero text-white shadow-glow scale-110"
                      : "bg-card text-muted-foreground border-2 border-muted"
                  }`}
                >
                  <Icon className="w-4 h-4 sm:w-5 sm:h-5" />
                </div>
                <span
                  className={`text-[10px] sm:text-xs mt-2 sm:mt-3 text-center font-medium transition-colors leading-tight ${
                    isActive || isCompleted
                      ? "text-primary"
                      : "text-muted-foreground"
                  }`}
                >
                  {step.label}
                </span>
              </div>
            );
          })}
        </div>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6">
        {/* Step 1: Sobre a música */}
        {currentStep === 1 && (
          <div className="space-y-4 animate-fade-in">
            <div>
              <h3 className="text-xl font-bold mb-1">Sobre a música</h3>
              <p className="text-sm text-muted-foreground">O que você quer criar?</p>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="genre" className="text-sm sm:text-base">Estilo musical *</Label>
                <Select value={formData.genre} onValueChange={(value) => updateFormData("genre", value)}>
                  <SelectTrigger id="genre" className="bg-muted border-border h-11 sm:h-12 text-base">
                    <SelectValue placeholder="Escolha o estilo" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="romantica">🎵 Romântica</SelectItem>
                    <SelectItem value="sertanejo">🤠 Sertanejo</SelectItem>
                    <SelectItem value="pop">🎤 Pop</SelectItem>
                    <SelectItem value="mpb">🎸 MPB</SelectItem>
                    <SelectItem value="rock">🎸 Rock</SelectItem>
                    <SelectItem value="samba">🥁 Samba</SelectItem>
                    <SelectItem value="pagode">🎺 Pagode</SelectItem>
                    <SelectItem value="outro">🎼 Outro</SelectItem>
                  </SelectContent>
                </Select>
                {formData.genre === "outro" && (
                  <Input
                    placeholder="Qual estilo? (máx. 25 caracteres)"
                    maxLength={25}
                    value={formData.customGenre || ""}
                    onChange={(e) => updateFormData("customGenre", e.target.value)}
                    className="animate-fade-in border-primary/40 h-11 sm:h-12 text-base"
                  />
                )}
                {formData.genre === "outro" && formData.customGenre && (
                  <div className="text-xs text-right text-muted-foreground">
                    {formData.customGenre.length}/25
                  </div>
                )}
              </div>

              <div className="space-y-2">
                <Label htmlFor="occasion" className="text-sm sm:text-base">Ocasião *</Label>
                <Select value={formData.occasion} onValueChange={(value) => updateFormData("occasion", value)}>
                  <SelectTrigger id="occasion" className="bg-muted border-border h-11 sm:h-12 text-base">
                    <SelectValue placeholder="Qual a ocasião?" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="aniversario">🎂 Aniversário</SelectItem>
                    <SelectItem value="namorados">💕 Dia dos Namorados</SelectItem>
                    <SelectItem value="casamento">💍 Casamento</SelectItem>
                    <SelectItem value="maes">🌸 Dia das Mães</SelectItem>
                    <SelectItem value="pais">👔 Dia dos Pais</SelectItem>
                    <SelectItem value="natal">🎄 Natal</SelectItem>
                    <SelectItem value="anorelac">💑 Aniversário de Relacionamento</SelectItem>
                    <SelectItem value="outro">🎁 Outro</SelectItem>
                  </SelectContent>
                </Select>
                {formData.occasion === "outro" && (
                  <Input
                    placeholder="Qual ocasião? (máx. 25 caracteres)"
                    maxLength={25}
                    value={formData.customOccasion || ""}
                    onChange={(e) => updateFormData("customOccasion", e.target.value)}
                    className="animate-fade-in border-primary/40 h-11 sm:h-12 text-base"
                  />
                )}
                {formData.occasion === "outro" && formData.customOccasion && (
                  <div className="text-xs text-right text-muted-foreground">
                    {formData.customOccasion.length}/25
                  </div>
                )}
              </div>

              <div className="space-y-2">
                <Label htmlFor="bpm" className="text-sm sm:text-base">Batida da música *</Label>
                <Select value={formData.bpm} onValueChange={(value) => updateFormData("bpm", value)}>
                  <SelectTrigger id="bpm" className="bg-muted border-border h-11 sm:h-12 text-base">
                    <SelectValue placeholder="Escolha o ritmo" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="40-60">🐢 Muito Lenta (40-60 BPM)</SelectItem>
                    <SelectItem value="60-80">🚶 Lenta (60-80 BPM)</SelectItem>
                    <SelectItem value="80-100">🎵 Moderada (80-100 BPM)</SelectItem>
                    <SelectItem value="100-120">🎶 Animada (100-120 BPM)</SelectItem>
                    <SelectItem value="120-140">⚡ Acelerada (120-140 BPM)</SelectItem>
                    <SelectItem value="140+">🚀 Muito Acelerada (140+ BPM)</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div className="space-y-2">
                <Label htmlFor="voiceType" className="text-sm sm:text-base">Voz *</Label>
                <Select value={formData.voiceType} onValueChange={(value) => updateFormData("voiceType", value)}>
                  <SelectTrigger id="voiceType" className="bg-muted border-border h-11 sm:h-12 text-base">
                    <SelectValue placeholder="Escolha o tipo de voz" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="masculina">🎤 Masculina</SelectItem>
                    <SelectItem value="feminina">🎤 Feminina</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <Button
              type="button"
              onClick={nextStep}
              className="w-full bg-gradient-hero hover:opacity-90 transition-opacity text-base font-semibold min-h-[44px] py-3 shadow-glow"
            >
              Próximo passo
              <ChevronRight className="w-5 h-5 ml-2" />
            </Button>
          </div>
        )}

        {/* Step 2: Conte a história */}
        {currentStep === 2 && (
          <div className="space-y-4 animate-fade-in">
            <div>
              <h3 className="text-xl font-bold mb-1">Conte a história</h3>
              <p className="text-sm text-muted-foreground">O coração da música</p>
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="from" className="text-sm sm:text-base">Presente de *</Label>
                <Input
                  id="from"
                  type="text"
                  placeholder="Seu nome"
                  value={formData.from}
                  onChange={(e) => updateFormData("from", e.target.value)}
                  className="bg-muted border-border h-11 sm:h-12 text-base"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="recipient" className="text-sm sm:text-base">Presenteado(a) *</Label>
                <Input
                  id="recipient"
                  type="text"
                  placeholder="Nome"
                  value={formData.recipient}
                  onChange={(e) => updateFormData("recipient", e.target.value)}
                  className="bg-muted border-border h-11 sm:h-12 text-base"
                />
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="relationship" className="text-sm sm:text-base">Presente para *</Label>
              <Select value={formData.relationship} onValueChange={(value) => updateFormData("relationship", value)}>
                <SelectTrigger id="relationship" className="bg-muted border-border h-11 sm:h-12 text-base">
                  <SelectValue placeholder="Selecione o destinatário" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="namorado">💑 Namorado(a)</SelectItem>
                  <SelectItem value="esposo">💍 Esposo(a)</SelectItem>
                  <SelectItem value="mae">👩 Mãe</SelectItem>
                  <SelectItem value="pai">👨 Pai</SelectItem>
                  <SelectItem value="filho">👶 Filho(a)</SelectItem>
                  <SelectItem value="amigo">🤝 Amigo(a)</SelectItem>
                  <SelectItem value="irmao">👫 Irmão(ã)</SelectItem>
                  <SelectItem value="outro">❤️ Outro</SelectItem>
                </SelectContent>
              </Select>
              {formData.relationship === "outro" && (
                <Input
                  placeholder="Especifique (máx. 25 caracteres)"
                  maxLength={25}
                  value={formData.customRelationship || ""}
                  onChange={(e) => updateFormData("customRelationship", e.target.value)}
                  className="animate-fade-in border-primary/40 h-11 sm:h-12 text-base"
                />
              )}
              {formData.relationship === "outro" && formData.customRelationship && (
                <div className="text-xs text-right text-muted-foreground">
                  {formData.customRelationship.length}/25
                </div>
              )}
            </div>

            <div className="space-y-2">
              <Label htmlFor="story" className="text-sm sm:text-base">História *</Label>
              <Textarea
                id="story"
                placeholder="Descreva a história que você quer transformar em música..."
                maxLength={250}
                rows={5}
                value={formData.story}
                onChange={(e) => updateFormData("story", e.target.value)}
                className="bg-muted border-border resize-none text-base min-h-[120px]"
              />
              <div className="flex justify-between items-center text-xs">
                <span className={formData.story.length < 20 ? "text-destructive" : "text-muted-foreground"}>
                  Mínimo 20 caracteres
                </span>
                <span className={formData.story.length > 200 ? "text-primary font-semibold" : "text-muted-foreground"}>
                  {formData.story.length}/250
                </span>
              </div>
            </div>

            <div className="flex gap-3">
              <Button
                type="button"
                onClick={prevStep}
                variant="outline"
                className="flex-1 min-h-[44px]"
              >
                <ChevronLeft className="w-5 h-5 mr-2" />
                Voltar
              </Button>
              <Button
                type="button"
                onClick={nextStep}
                className="flex-1 bg-gradient-hero hover:opacity-90 transition-opacity font-semibold shadow-glow min-h-[44px]"
              >
                Quase lá!
                <ChevronRight className="w-5 h-5 ml-2" />
              </Button>
            </div>
          </div>
        )}

        {/* Step 3: Finalizar */}
        {currentStep === 3 && (
          <div className="space-y-4 animate-fade-in pb-24 sm:pb-8">
            <div>
              <h3 className="text-xl font-bold mb-1">Finalizar pedido</h3>
              <p className="text-sm text-muted-foreground">Só mais um passo!</p>
            </div>

            <div className="space-y-2">
              <Label htmlFor="email" className="text-sm sm:text-base">Email *</Label>
              <Input
                id="email"
                type="email"
                placeholder="seu@email.com"
                value={formData.email}
                onChange={(e) => updateFormData("email", e.target.value)}
                className="bg-muted border-border h-11 sm:h-12 text-base"
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="whatsapp" className="text-sm sm:text-base">WhatsApp *</Label>
              <Input
                id="whatsapp"
                type="tel"
                inputMode="numeric"
                placeholder="(00) 00000-0000"
                value={formData.whatsapp}
                onChange={(e) => updateFormData("whatsapp", formatWhatsApp(e.target.value))}
                className="bg-muted border-border h-11 sm:h-12 text-base"
              />
              <p className="text-xs text-muted-foreground">Você receberá a música por aqui</p>
            </div>

            <div className="space-y-2">
              <Label htmlFor="additionalNotes" className="text-sm sm:text-base">Observações adicionais</Label>
              <Textarea
                id="additionalNotes"
                placeholder="Alguma informação adicional que queira compartilhar... (opcional)"
                maxLength={500}
                rows={4}
                value={formData.additionalNotes}
                onChange={(e) => updateFormData("additionalNotes", e.target.value)}
                className="bg-muted border-border resize-none text-base min-h-[100px]"
              />
              {formData.additionalNotes && (
                <div className="text-xs text-right text-muted-foreground">
                  {formData.additionalNotes.length}/500
                </div>
              )}
            </div>

            <div className="space-y-4">
              <div>
                <Label htmlFor="coupon" className="text-sm">Cupom de Desconto (Opcional)</Label>
                <div className="flex flex-col sm:flex-row gap-2 mt-1">
                  <Input
                    id="coupon"
                    value={couponCode}
                    onChange={(e) => setCouponCode(e.target.value.toUpperCase())}
                    placeholder="Digite o código"
                    disabled={!!appliedCoupon}
                    className="h-11"
                  />
                  {appliedCoupon ? (
                    <Button type="button" variant="outline" onClick={removeCoupon} className="h-11 sm:w-auto w-full">
                      Remover
                    </Button>
                  ) : (
                    <Button
                      type="button"
                      variant="outline"
                      onClick={validateCoupon}
                      disabled={isValidatingCoupon || !couponCode.trim()}
                      className="h-11 sm:w-auto w-full"
                    >
                      {isValidatingCoupon ? "Validando..." : "Aplicar"}
                    </Button>
                  )}
                </div>
                {appliedCoupon && (
                  <p className="text-xs sm:text-sm text-green-600 mt-2">
                    ✓ Cupom aplicado: {appliedCoupon.coupon.code}
                  </p>
                )}
              </div>
            </div>

            <div className="bg-muted/50 p-3 sm:p-4 rounded-lg space-y-2 border border-border">
              <div className="text-sm font-semibold">Resumo do pedido:</div>
              <div className="text-xs text-muted-foreground space-y-1">
                <p>🎵 {formData.genre === "outro" ? formData.customGenre : formData.genre}</p>
                <p>🎁 Ocasião: {formData.occasion === "outro" ? formData.customOccasion : formData.occasion}</p>
                <p>💝 {formData.from} → {formData.recipient} ({formData.relationship === "outro" ? formData.customRelationship : formData.relationship})</p>
                <p className="line-clamp-2 sm:line-clamp-3">"{formData.story}"</p>
              </div>
              <div className="border-t pt-2 space-y-1">
                {!isPricesLoaded || productPrice === null ? (
                  <div className="flex items-center justify-center gap-2 py-2 text-sm text-muted-foreground">
                    <Loader2 className="w-4 h-4 animate-spin" />
                    Carregando preços...
                  </div>
                ) : (
                  <>
                    <div className="flex justify-between text-xs items-center">
                      <span>Valor:</span>
                      {discount > 0 ? (
                        <div className="flex items-center gap-1.5 flex-wrap justify-end">
                          <span className="line-through text-muted-foreground text-[10px]">
                            R$ {(originalPrice || 0).toFixed(2)}
                          </span>
                          <span className="font-semibold text-primary">
                            R$ {productPrice.toFixed(2)}
                          </span>
                          <span className="text-[10px] px-1.5 py-0.5 bg-green-500 text-white font-bold rounded whitespace-nowrap">
                            -{discount.toFixed(0)}%
                          </span>
                        </div>
                      ) : (
                        <span>R$ {productPrice.toFixed(2)}</span>
                      )}
                    </div>
                    {appliedCoupon && (
                      <div className="flex justify-between text-xs text-green-600">
                        <span>Desconto:</span>
                        <span>- R$ {appliedCoupon.discountAmount.toFixed(2)}</span>
                      </div>
                    )}
                    <div className="flex justify-between font-semibold text-sm pt-1 border-t">
                      <span>Total:</span>
                      <span>R$ {(appliedCoupon ? appliedCoupon.finalAmount : productPrice).toFixed(2)}</span>
                    </div>
                  </>
                )}
              </div>
            </div>

            <div className="flex items-start gap-2 sm:gap-3 pt-2">
              <Checkbox
                id="terms"
                checked={acceptedTerms}
                onCheckedChange={(checked) => setAcceptedTerms(checked as boolean)}
                className="mt-0.5 sm:mt-1 min-w-[18px] min-h-[18px] sm:min-w-[20px] sm:min-h-[20px]"
              />
              <label
                htmlFor="terms"
                className="text-xs sm:text-sm text-muted-foreground leading-relaxed cursor-pointer flex-1"
              >
                Concordo com os{" "}
                <TermsDialog>
                  <button type="button" className="text-primary hover:underline">
                    Termos de Uso
                  </button>
                </TermsDialog>{" "}
                e{" "}
                <PrivacyDialog>
                  <button type="button" className="text-primary hover:underline">
                    Política de Privacidade
                  </button>
                </PrivacyDialog>
              </label>
            </div>

            {/* Card de desconto promocional */}
            {isPricesLoaded && productPrice !== null && discount > 0 && !appliedCoupon && (
              <div className="mb-4 p-2 sm:p-3 bg-card border border-primary/30 rounded-lg relative overflow-hidden">
                <div className="absolute inset-0 bg-gradient-to-r from-primary/10 to-secondary/10 opacity-50" />
                <div className="relative z-10">
                  <p className="text-xs sm:text-sm font-medium text-foreground text-center">
                    De <span className="line-through text-muted-foreground">R$ {(originalPrice || 0).toFixed(2)}</span> por{" "}
                    <span className="text-base sm:text-lg font-bold bg-gradient-to-r from-primary to-secondary bg-clip-text text-transparent">
                      R$ {productPrice.toFixed(2)}
                    </span>
                    {" "}✨
                  </p>
                  <p className="text-[10px] sm:text-xs text-secondary font-semibold text-center mt-0.5 sm:mt-1">
                    Economize {discount.toFixed(0)}% nesta promoção!
                  </p>
                </div>
              </div>
            )}

            {/* Card de cupom aplicado */}
            {appliedCoupon && (
              <div className="mb-4 p-2 sm:p-3 bg-card border border-accent/40 rounded-lg relative overflow-hidden">
                <div className="absolute inset-0 bg-gradient-to-r from-accent/15 to-primary/10 opacity-60" />
                <div className="relative z-10">
                  <p className="text-xs sm:text-sm font-medium text-foreground text-center">
                    🎟️ Cupom <span className="font-bold text-primary">{couponCode}</span> aplicado!
                  </p>
                  <p className="text-[10px] sm:text-xs text-accent-foreground text-center mt-0.5 sm:mt-1">
                    De <span className="text-muted-foreground">R$ {productPrice?.toFixed(2)}</span> por{" "}
                    <span className="font-bold text-base sm:text-lg bg-gradient-to-r from-primary to-secondary bg-clip-text text-transparent">
                      R$ {appliedCoupon.finalAmount.toFixed(2)}
                    </span>
                  </p>
                </div>
              </div>
            )}

            <div className="flex flex-col-reverse sm:flex-row gap-2 sm:gap-3">
              <Button
                type="button"
                onClick={prevStep}
                variant="outline"
                className="w-full sm:flex-1 min-h-[48px]"
              >
                <ChevronLeft className="w-5 h-5 mr-2" />
                Voltar
              </Button>
              <Button
                type="submit"
                disabled={isSubmitting || !isPricesLoaded || productPrice === null}
                className="w-full sm:flex-1 bg-gradient-hero hover:opacity-90 transition-opacity text-base font-semibold min-h-[48px] shadow-glow"
              >
                {isSubmitting ? "Processando..." : (!isPricesLoaded || productPrice === null) ? "Carregando..." : (
                  <>
                    Presentear por R$ {(appliedCoupon ? appliedCoupon.finalAmount : productPrice).toFixed(2)} 🎁
                  </>
                )}
              </Button>
            </div>

            <p className="text-[11px] sm:text-xs text-center text-muted-foreground mt-2">
              Pagamento seguro via Mercado Pago • Pix ou Cartão
            </p>
          </div>
        )}
      </form>
    </div>
    </>
  );
};
