import { useState, useEffect } from 'react';
import { initUTMTracking, trackLeadWithPixel } from './lib/tracking/utmAndPixel';
import imgCapa from '../assets/pd.jpg';
import imgCinza from '../assets/CINZA_700x.webp';
import imgBranco from '../assets/BRANCO_45105607-1fef-4f96-a614-f4a6d869fe20_700x.webp';
import imgRosa from '../assets/ROSA_700x.webp';
import imgPreto from '../assets/preto_700x.webp';
import imgPd1 from '../assets/pd1_700x.webp';
import imgPd2 from '../assets/pd2_b88deed2-1778-469e-a622-a88589e97ccc_700x.webp';
import imgPd3 from '../assets/pd3_a3b8801b-756d-41c5-a614-ebd6e5809113_700x.webp';
import imgPd4 from '../assets/pd4_700x.webp';
import imgPd6 from '../assets/pd6_700x.webp';
import imgPd7 from '../assets/pd7_700x.webp';
import imgPd10 from '../assets/PD10_700x.webp';
import imgAtacadoBrasil from '../assets/atacados-brasil-logo-DTK1lMUd.jpg';
import imgHomem1 from '../assets/Homem1.jpg';
import imgHomem2 from '../assets/Homem2.jpg';
import imgHomem3 from '../assets/Homem3.jpg';
import imgMulher1 from '../assets/Mulher1.jpg';
import imgMulher2 from '../assets/Mulher2.jpg';

type Color = "Cinza" | "Azul" | "Prata" | "Rosa" | "Preto" | "Branco";
type ProductColor = 'cinza' | 'azul' | 'prata' | 'rosa' | 'preto' | 'branco';
type Storage = "64GB" | "512GB" | "1TB";
type ScreenSizeId = "14" | "16";

// Mapeamento de checkouts por combinação de produto
// Formato: "storage-tamanho": "url-do-checkout"
// As cores não importam para o checkout, apenas armazenamento e tamanho de tela
const checkoutUrls: Record<string, string> = {
  // 64GB - 14 POLEGADAS
  "64GB-14": "https://pay.lojascomprae.online/a9ArZMIVJev37xj",
  // 64GB - 16 POLEGADAS
  "64GB-16": "https://pay.lojascomprae.online/NDr8gmKXqWVZBmj",
  // 512GB - 14 POLEGADAS
  "512GB-14": "https://pay.lojascomprae.online/65XDZB8e21pgVJw",
  // 512GB - 16 POLEGADAS
  "512GB-16": "https://pay.lojascomprae.online/DYp0ZxV2LyQgmvX",
  // 1TB - 14 POLEGADAS
  "1TB-14": "https://pay.lojascomprae.online/QqyLgqoE0yWZvkE",
  // 1TB - 16 POLEGADAS
  "1TB-16": "https://pay.lojascomprae.online/PVYB34en2NvZKzk",
};

// Função para obter a URL do checkout baseada na seleção atual
// As cores não importam para o checkout, apenas armazenamento e tamanho de tela
const getCheckoutUrl = (storage: Storage, screenSize: ScreenSizeId): string => {
  const key = `${storage}-${screenSize}`;
  return checkoutUrls[key] || "https://pay.lojascomprae.online/default";
};

const productGallery: string[] = [
  imgCapa,
  imgPd1,
  imgPd2,
  imgPd3,
  imgPd4,
  imgPd6,
  imgPd7,
];


const productImagesByColor: Record<ProductColor, string> = {
  cinza: imgCinza,
  azul: imgPd1,
  prata: imgBranco,
  rosa: imgRosa,
  preto: imgPreto,
  branco: imgBranco,
};

// Preços por combinação de armazenamento e tamanho de tela
// Ordem conforme as URLs dos checkouts:
// 1. 64GB 14" = R$ 43,71
// 2. 64GB 16" = R$ 53,71
// 3. 512GB 14" = R$ 53,71
// 4. 512GB 16" = R$ 63,71
// 5. 1TB 14" = R$ 63,71
// 6. 1TB 16" = R$ 73,71
const pricesByCombination: Record<string, number> = {
  "64GB-14": 43.71,
  "64GB-16": 53.71,
  "512GB-14": 53.71,
  "512GB-16": 63.71,
  "1TB-14": 63.71,
  "1TB-16": 73.71,
};

const oldPrices: Record<Storage, number> = {
  "64GB": 2209.00,
  "512GB": 3109.00,
  "1TB": 3509.00,
};

const formatCurrency = (value: number): string => {
  return new Intl.NumberFormat('pt-BR', {
    style: 'currency',
    currency: 'BRL',
  }).format(value);
};

const ProductPage = () => {
  const [selectedColor, setSelectedColor] = useState<Color>("Cinza");
  const [selectedStorage, setSelectedStorage] = useState<Storage>("64GB");
  const [selectedScreenSize, setSelectedScreenSize] = useState<ScreenSizeId>("14");
  const [isOptionsModalOpen, setIsOptionsModalOpen] = useState(false);
  const [isStoreModalOpen, setIsStoreModalOpen] = useState(false);
  const [isChatModalOpen, setIsChatModalOpen] = useState(false);
  const [isDiscountPopupOpen, setIsDiscountPopupOpen] = useState(false);
  const [openFaqIndex, setOpenFaqIndex] = useState<number | null>(3);
  const [currentImageIndex, setCurrentImageIndex] = useState(0);
  const [timeRemaining, setTimeRemaining] = useState(300);
  const [chatMessages, setChatMessages] = useState<Array<{ type: 'user' | 'bot'; text: string }>>([
    { type: 'bot', text: 'Olá! Me chamo Paulo do time de atendimento da AtacadosBrasil. Como podemos ajudar você hoje com seu Blackview?' }
  ]);

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

  useEffect(() => {
    // Carrega o script do ConverteAI
    const scriptId = 'scr_689bec1b375bae07913639a9';
    if (!document.getElementById(scriptId)) {
      const s = document.createElement('script');
      s.id = scriptId;
      s.src = 'https://scripts.converteai.net/e511d669-65af-4d3e-93cd-13c3dc0a6182/players/689bec1b375bae07913639a9/player.js';
      s.async = true;
      document.head.appendChild(s);
    }
  }, []);

  useEffect(() => {
    if (timeRemaining > 0) {
      const timer = setInterval(() => {
        setTimeRemaining((prev) => prev - 1);
      }, 1000);
      return () => clearInterval(timer);
    }
  }, [timeRemaining]);

  const formatTime = (seconds: number): string => {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = seconds % 60;
    return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
  };

  const handlePrevImage = () => {
    setCurrentImageIndex((prev) =>
      prev === 0 ? productGallery.length - 1 : prev - 1
    );
  };

  const handleNextImage = () => {
    setCurrentImageIndex((prev) =>
      prev === productGallery.length - 1 ? 0 : prev + 1
    );
  };

  const getColorKey = (color: Color): ProductColor => {
    if (color === "Cinza") return "cinza";
    if (color === "Azul") return "azul";
    if (color === "Prata") return "prata";
    if (color === "Rosa") return "rosa";
    if (color === "Preto") return "preto";
    return "branco";
  };

  const getPriceKey = (storage: Storage, screenSize: ScreenSizeId): string => {
    return `${storage}-${screenSize}`;
  };

  const finalPrice = pricesByCombination[getPriceKey(selectedStorage, selectedScreenSize)] || 43.71;
  const oldPrice = oldPrices[selectedStorage];
  const discountPercent = Math.round(((oldPrice - finalPrice) / oldPrice) * 100);

  const handleBuy = () => {
    const checkoutUrl = getCheckoutUrl(selectedStorage, selectedScreenSize);

    trackLeadWithPixel({
      eventName: 'InitiateCheckout',
      value: finalPrice,
      currency: 'BRL',
      extra: {
        product_name: 'Blackview',
        product_color: selectedColor,
        product_storage: selectedStorage,
        product_screen_size: selectedScreenSize,
        checkout_url: checkoutUrl,
      },
    });
    window.location.href = checkoutUrl;
  };

  const faqResponses: Record<string, string> = {
    'Quanto tempo tenho de garantia?': 'O Blackview tem garantia de 5 anos contra defeitos de fabricação. A garantia é válida a partir da data de compra e cobre problemas de funcionamento normal.',
    'Na primeira compra tem frete grátis?': 'Sim! O frete é totalmente grátis para todo o Brasil. O prazo de entrega é de até 15 dias úteis com código de rastreamento completo.',
    'Como funciona a devolução do produto?': 'Você tem até 30 dias após o recebimento para solicitar a devolução. O produto deve estar em perfeitas condições, com embalagem original e todos os acessórios. O frete de devolução é grátis e o reembolso é processado em até 7 dias úteis.'
  };

  const handleFaqClick = (question: string) => {
    const response = faqResponses[question];
    if (response) {
      setChatMessages(prev => [
        ...prev,
        { type: 'user', text: question },
        { type: 'bot', text: response }
      ]);
    }
  };

  const handleCloseChat = () => {
    setIsChatModalOpen(false);
    setChatMessages([
      { type: 'bot', text: 'Olá! Me chamo Paulo do time de atendimento da AtacadosBrasil. Como podemos ajudar você hoje com seu Blackview?' }
    ]);
  };

  const handleConfirmOptions = () => {
    setIsOptionsModalOpen(false);
  };

  const faqItems = [
    {
      question: "O produto é original?",
      answer: "Sim, todos os nossos produtos são 100% originais e acompanham nota fiscal eletrônica. Trabalhamos apenas com distribuidores autorizados pela Samsung."
    },
    {
      question: "Quanto tempo demora a entrega?",
      answer: "O prazo de entrega varia conforme sua região. Em média, entregamos em 5 a 10 dias úteis. Para compras acima de R$ 200, o frete é grátis."
    },
    {
      question: "O tablet vem com nota fiscal?",
      answer: "Sim, todos os produtos são enviados com Nota Fiscal Eletrônica, que será enviada por e-mail após a confirmação do pagamento."
    },
    {
      question: "Qual a garantia do produto?",
      answer: "O Blackview possui 5 anos de garantia oficial contra defeitos de fabricação."
    },
    {
      question: "Posso trocar se não gostar?",
      answer: "Sim, você tem até 7 dias corridos após o recebimento do produto para solicitar a troca ou devolução, desde que o produto esteja em perfeito estado e na embalagem original."
    },
    {
      question: "Vem S Pen na caixa?",
      answer: "Sim, a S Pen original está incluída na embalagem do Blackview, junto com o cabo USB-C e todos os acessórios padrão."
    }
  ];

  const reviews = [
    {
      name: "Lucas M.",
      time: "3 dias atrás",
      text: "Gente, chegou hoje e já tô apaixonado! Olha só a caixa que capricho... Abri e tava tudo lacradinho, a caneta S Pen vem junto. A tela é LINDA, parece foto de catálogo de tão boa! Vou usar pra estudar mas já testei vendo série e tá perfeito. Valeu cada centavo 🤩",
      images: [imgPd2, imgPd7],
      helpful: 234,
      avatar: imgHomem1
    },
    {
      name: "Ana Paula S.",
      time: "1 semana atrás",
      text: "Pessoal, esse tablet é sério! Recebi e desembalei com o maior cuidado haha. Tava com medo de não valer a pena mas gente... é outro nível! A tela é gigante e super nítida, as cores são vibrantes demais. Tô usando pra trabalho e pra ver Netflix, não me arrependo nem um pouco. Recomendo de olhos fechados!",
      images: [imgPd3],
      helpful: 189,
      avatar: imgMulher1
    },
    {
      name: "Ricardo F.",
      time: "2 semanas atrás",
      text: "Melhor compra do ano! A S Pen funciona perfeitamente, super precisa. Uso pra desenhar e fazer anotações na faculdade. A bateria dura o dia todo tranquilo. Chegou super rápido e bem embalado. Muito satisfeito!",
      images: [imgPd6, imgPd10],
      helpful: 156,
      avatar: imgHomem2
    },
    {
      name: "Juliana L.",
      time: "3 semanas atrás",
      text: "Tablet incrível! A resistência à água IP68 é real, testei (com cuidado) e funcionou perfeitamente. A tela de 90Hz é muito fluida. Recomendo demais!",
      images: [imgPd1],
      helpful: 142,
      avatar: imgMulher2
    },
    {
      name: "Carlos E.",
      time: "1 mês atrás",
      text: "Produto excelente! Superou minhas expectativas. A qualidade de construção é premium, a tela é simplesmente espetacular. Uso diariamente e não tenho nenhuma reclamação. Atendimento e entrega também foram perfeitos!",
      helpful: 128,
      avatar: imgHomem3
    }
  ];

  const ratingDistribution = [
    { stars: 5, count: 1268, percentage: 82 },
    { stars: 4, count: 186, percentage: 12 },
    { stars: 3, count: 82, percentage: 5 },
    { stars: 2, count: 62, percentage: 4 },
    { stars: 1, count: 15, percentage: 1 }
  ];


  return (
    <div className="min-h-screen bg-white pb-28">
      <div className="max-w-md mx-auto">
        <div className="relative w-full bg-white">
          <div className="relative w-full" role="region" aria-roledescription="carousel">
            <div className="overflow-hidden">
              <div
                className="flex -ml-4 transition-transform duration-300 ease-in-out"
                style={{ transform: `translate3d(-${currentImageIndex * 100}%, 0px, 0px)` }}
              >
                {productGallery.map((image, index) => (
                  <div
                    key={index}
                    role="group"
                    aria-roledescription="slide"
                    className="min-w-0 shrink-0 grow-0 basis-full pl-4"
                  >
                    <div className="w-full aspect-square bg-white flex items-center justify-center overflow-hidden">
                      <img
                        src={image}
                        alt={`Blackview - Imagem ${index + 1}`}
                        className="w-full h-full max-w-full max-h-full object-contain"
                        loading={index === 0 ? "eager" : "lazy"}
                        decoding={index === 0 ? "sync" : "async"}
                      />
                    </div>
                  </div>
                ))}
              </div>
            </div>
            <button
              onClick={handlePrevImage}
              disabled={currentImageIndex === 0}
              className="inline-flex items-center justify-center gap-2 whitespace-nowrap text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-300 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 border border-gray-300 hover:text-gray-900 absolute h-8 w-8 rounded-full top-1/2 -translate-y-1/2 left-4 md:left-6 bg-white/80 hover:bg-white shadow-md"
            >
              <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="h-4 w-4">
                <path d="m12 19-7-7 7-7"></path>
                <path d="M19 12H5"></path>
              </svg>
              <span className="sr-only">Previous slide</span>
            </button>
            <button
              onClick={handleNextImage}
              disabled={currentImageIndex === productGallery.length - 1}
              className="inline-flex items-center justify-center gap-2 whitespace-nowrap text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-300 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 border border-gray-300 hover:text-gray-900 absolute h-8 w-8 rounded-full top-1/2 -translate-y-1/2 right-4 md:right-6 bg-white/80 hover:bg-white shadow-md"
            >
              <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="h-4 w-4">
                <path d="M5 12h14"></path>
                <path d="m12 5 7 7-7 7"></path>
              </svg>
              <span className="sr-only">Next slide</span>
            </button>
          </div>
        </div>

        <div className="w-full bg-[#fd2154] text-white px-2 sm:px-3 py-2 sm:py-3">
          <div className="max-w-md mx-auto">
            <div className="flex justify-between items-start gap-2">
              <div className="flex-1 pb-1 sm:pb-2">
                <div className="text-2xl sm:text-[30px] font-extrabold leading-none tracking-tight font-sans">
                  {formatCurrency(finalPrice)}
                </div>
                <div className="flex items-center gap-1.5 sm:gap-2 mt-0.5 sm:mt-1">
                  <span className="text-xs sm:text-sm opacity-90 line-through font-medium">
                    {formatCurrency(oldPrice)}
                  </span>
                  <span className="text-xs sm:text-[13.6px] font-bold tracking-wide">
                    Economize {discountPercent}%
                  </span>
                </div>
              </div>
              <div className="bg-white/20 px-1.5 sm:px-2 py-0.5 sm:py-1 rounded text-[10px] sm:text-[11.3px] font-bold whitespace-nowrap tracking-wide">
                TERMINA EM {formatTime(timeRemaining)}
              </div>
            </div>
            <div className="flex gap-1.5 sm:gap-2 mt-1.5 sm:mt-2 flex-wrap">
              <span className="bg-purple-600 text-white px-2 sm:px-2.5 py-0.5 rounded-full text-[10px] sm:text-[11.4px] font-bold tracking-wide">
                Economize {formatCurrency(oldPrice - finalPrice)}
              </span>
              <span className="bg-purple-600 text-white px-2 sm:px-2.5 py-0.5 rounded-full text-[10px] sm:text-[11.4px] font-bold tracking-wide">
                {discountPercent}% OFF COM CUPOM
              </span>
            </div>
          </div>
        </div>

        <div className="bg-white">
          <div className="px-2 sm:px-3 py-3 sm:py-4">
            <div className="inline-flex items-center bg-[#fd2154] text-white px-2 sm:px-2.5 py-0.5 rounded-full text-[10px] sm:text-xs font-semibold mb-2 uppercase">
              ⚡ OFERTA RELÂMPAGO
            </div>
            <h1 className="text-sm sm:text-base font-bold text-black mb-2 leading-tight">
              Blackview - Tablet com IA e S Pen - Tela de 14" ou 16" 90Hz com IP68
            </h1>
            <div className="flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm text-gray-600 mb-2 sm:mb-3 flex-wrap">
              <div className="flex items-center gap-1">
                <span className="text-yellow-400 text-sm sm:text-base">★</span>
                <span className="font-semibold text-gray-900">4.9</span>
                <span className="text-xs sm:text-sm">(1.547)</span>
              </div>
              <span>•</span>
              <span className="text-xs sm:text-sm">8.422 vendidos</span>
            </div>
            <div className="flex items-start gap-1.5 sm:gap-2 text-xs sm:text-sm mb-2">
              <span className="text-gray-600 mt-0.5 flex-shrink-0">🚚</span>
              <div>
                <div className="text-xs sm:text-sm text-gray-900 font-bold">Receba até 15 de novembro – 20 de novembro.</div>
                <div className="text-xs sm:text-sm text-green-600 font-medium">Taxa de envio: grátis</div>
              </div>
            </div>
          </div>
          <div className="border-t border-gray-200 px-3 py-4">
            <h3 className="text-sm font-bold text-gray-900 mb-3">Serviços oferecidos para você:</h3>
            <div className="space-y-2">
              <div className="flex items-center gap-2 text-sm">
                <span className="text-green-600 text-base flex-shrink-0">✓</span>
                <span className="text-gray-900">Devolução gratuita</span>
              </div>
              <div className="flex items-center gap-2 text-sm">
                <span className="text-green-600 text-base flex-shrink-0">✓</span>
                <span className="text-gray-900">Cupom por perda ou dano</span>
              </div>
              <div className="flex items-center gap-2 text-sm">
                <span className="text-green-600 text-base flex-shrink-0">✓</span>
                <span className="text-gray-900">Seguro</span>
              </div>
            </div>
          </div>
          <div className="border-t border-gray-200 px-3 py-4">
            <h3 className="text-base font-bold text-black mb-3">Vídeos do Produto</h3>
            <div className="relative w-full">
              <div
                id="vid_689bec1b375bae07913639a9"
                style={{ position: 'relative', width: '100%', padding: '56.25% 0 0' }}
              >
                <img
                  id="thumb_689bec1b375bae07913639a9"
                  src="https://images.converteai.net/e511d669-65af-4d3e-93cd-13c3dc0a6182/players/689bec1b375bae07913639a9/thumbnail.jpg"
                  style={{
                    position: 'absolute',
                    top: 0,
                    left: 0,
                    width: '100%',
                    height: '100%',
                    objectFit: 'cover',
                    display: 'block'
                  }}
                  alt="thumbnail"
                />
                <div
                  id="backdrop_689bec1b375bae07913639a9"
                  style={{
                    WebkitBackdropFilter: 'blur(5px)',
                    backdropFilter: 'blur(5px)',
                    position: 'absolute',
                    top: 0,
                    height: '100%',
                    width: '100%'
                  }}
                ></div>
              </div>
            </div>
          </div>
        </div>

        <div id="reviews-section" className="border-t border-gray-200 px-3 py-4">
          <div className="flex justify-between items-center mb-4">
            <h3 className="text-base font-bold text-black">Avaliações (1.547)</h3>
            <button className="text-sm text-[#fd2154] font-medium">Ver todas</button>
          </div>
          <div className="flex gap-6 mb-6">
            <div className="flex flex-col items-start">
              <div className="text-5xl font-bold text-black mb-1">4,8</div>
              <div className="flex gap-0.5 mb-1">
                {[...Array(5)].map((_, i) => (
                  <span key={i} className="text-yellow-400 text-base">★</span>
                ))}
              </div>
              <div className="text-xs text-gray-600">1.547 avaliações</div>
            </div>
            <div className="flex-1 space-y-1">
              {ratingDistribution.map((rating) => (
                <div key={rating.stars} className="flex items-center gap-2">
                  <span className="text-xs text-gray-600 w-4">{rating.stars}</span>
                  <span className="text-yellow-400 text-xs">★</span>
                  <div className="flex-1 h-2 bg-gray-200 rounded-full overflow-hidden">
                    <div className="h-full bg-yellow-400" style={{ width: `${rating.percentage}%` }}></div>
                  </div>
                  <span className="text-xs text-gray-600 w-10 text-right">{rating.count}</span>
                </div>
              ))}
            </div>
          </div>
          <div className="space-y-4">
            {reviews.map((review, index) => (
              <div key={index} className="border-t border-gray-200 pt-4 first:border-t-0 first:pt-0">
                <div className="flex items-start gap-2">
                  <img
                    src={review.avatar}
                    alt={review.name}
                    className="relative flex shrink-0 overflow-hidden rounded-full w-8 h-8 object-cover"
                    loading="lazy"
                  />
                  <div className="flex-1 min-w-0">
                    <div className="flex justify-between items-start mb-1">
                      <span className="text-xs font-medium text-gray-900">{review.name}</span>
                      <span className="text-[10px] text-gray-500">{review.time}</span>
                    </div>
                    <div className="flex gap-0.5 mb-2">
                      {[...Array(5)].map((_, i) => (
                        <span key={i} className="text-yellow-400 text-[10px]">★</span>
                      ))}
                    </div>
                    <p className="text-xs text-gray-600 mb-2 leading-relaxed">{review.text}</p>
                    {review.images && review.images.length > 0 && (
                      <div className="flex gap-1.5 mb-2">
                        {review.images.map((img, imgIndex) => (
                          <img key={imgIndex} src={img} alt={`Foto ${imgIndex + 1}`} className="w-20 h-20 rounded border border-gray-200 object-cover" loading="lazy" />
                        ))}
                      </div>
                    )}
                    <button className="text-[8px] text-gray-500">👍 Útil ({review.helpful})</button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="border-t border-gray-200 px-3 py-4">
          <h3 className="text-sm font-bold text-gray-900 mb-3">Informações da Loja</h3>
          <div className="flex items-center gap-2 mb-4">
            <img src={imgAtacadoBrasil} alt="AtacadosBrasil" className="relative shrink-0 rounded-full w-10 h-10 object-cover" loading="lazy" />
            <div className="flex-1">
              <div className="text-sm font-bold text-gray-900">AtacadosBrasil</div>
              <div className="text-xs text-gray-600">Online • Responde rápido</div>
            </div>
            <button className="inline-flex items-center justify-center gap-2 whitespace-nowrap font-medium transition-colors border border-gray-300 bg-white hover:bg-gray-50 rounded-md px-3 text-xs h-8">
              Seguir
            </button>
          </div>
          <div className="grid grid-cols-3 gap-2">
            <div className="text-center">
              <div className="text-sm font-bold text-gray-900">98%</div>
              <div className="text-xs text-gray-600">Avaliação</div>
            </div>
            <div className="text-center">
              <div className="text-sm font-bold text-gray-900">52K</div>
              <div className="text-xs text-gray-600">Produtos</div>
            </div>
            <div className="text-center">
              <div className="text-sm font-bold text-gray-900">2.4M</div>
              <div className="text-xs text-gray-600">Seguidores</div>
            </div>
          </div>
        </div>
        <div className="border-t border-gray-200 px-3 py-4">
          <h3 className="text-base font-bold text-gray-900 mb-3">Descrição</h3>
          <p className="text-sm text-gray-600 mb-4 leading-relaxed">
            Blackview com design ultrafino de apenas 6.0mm e bordas reduzidas. Tela de 14" ou 16" TFT LCD com taxa de atualização de 90Hz, processador Exynos 1580 e Assistente Matemático com IA. Resistência IP68 contra água e poeira, Vision Booster com brilho de 800 nits e S Pen incluída.
          </p>
          <div className="bg-gray-50 border border-gray-200 rounded-lg p-3 mb-4">
            <div className="flex items-center gap-2 mb-3">
              <span className="text-gray-900 text-base">📋</span>
              <h4 className="text-sm font-bold text-gray-900">Especificações Técnicas</h4>
            </div>
            <div className="space-y-2">
              <div className="flex justify-between items-center py-1 border-b border-gray-200 last:border-b-0">
                <span className="text-xs text-gray-600">Tela</span>
                <span className="text-xs text-gray-900 font-medium">14" ou 16" TFT LCD 90Hz</span>
              </div>
              <div className="flex justify-between items-center py-1 border-b border-gray-200 last:border-b-0">
                <span className="text-xs text-gray-600">Processador</span>
                <span className="text-xs text-gray-900 font-medium">Exynos 1580</span>
              </div>
              <div className="flex justify-between items-center py-1 border-b border-gray-200 last:border-b-0">
                <span className="text-xs text-gray-600">RAM</span>
                <span className="text-xs text-gray-900 font-medium">8GB</span>
              </div>
              <div className="flex justify-between items-center py-1 border-b border-gray-200 last:border-b-0">
                <span className="text-xs text-gray-600">Armazenamento</span>
                <span className="text-xs text-gray-900 font-medium">128GB</span>
              </div>
              <div className="flex justify-between items-center py-1 border-b border-gray-200 last:border-b-0">
                <span className="text-xs text-gray-600">Resistência</span>
                <span className="text-xs text-gray-900 font-medium">IP68 (água e poeira)</span>
              </div>
              <div className="flex justify-between items-center py-1 border-b border-gray-200 last:border-b-0">
                <span className="text-xs text-gray-600">S Pen</span>
                <span className="text-xs text-gray-900 font-medium">Incluída na caixa</span>
              </div>
              <div className="flex justify-between items-center py-1 border-b border-gray-200 last:border-b-0">
                <span className="text-xs text-gray-600">Bateria</span>
                <span className="text-xs text-gray-900 font-medium">8.000 mAh</span>
              </div>
              <div className="flex justify-between items-center py-1 border-b border-gray-200 last:border-b-0">
                <span className="text-xs text-gray-600">Peso</span>
                <span className="text-xs text-gray-900 font-medium">465g</span>
              </div>
            </div>
          </div>
          <div className="mb-4">
            <div className="flex items-center gap-2 mb-3">
              <span className="text-blue-600 text-base">✨</span>
              <h4 className="text-sm font-bold text-gray-900">Recursos e Diferenciais</h4>
            </div>
            <div className="space-y-2">
              <div className="flex gap-2">
                <span className="text-green-600 text-base flex-shrink-0 mt-0.5">✓</span>
                <p className="text-xs text-gray-600 leading-relaxed">
                  <span className="font-semibold text-gray-900">Inteligência Artificial Integrada:</span> Assistente matemático com IA para resolver equações complexas
                </p>
              </div>
              <div className="flex gap-2">
                <span className="text-green-600 text-base flex-shrink-0 mt-0.5">✓</span>
                <p className="text-xs text-gray-600 leading-relaxed">
                  <span className="font-semibold text-gray-900">Pesquisa Inteligente:</span> Tecnologia Circle to Search com IA do Google
                </p>
              </div>
              <div className="flex gap-2">
                <span className="text-green-600 text-base flex-shrink-0 mt-0.5">✓</span>
                <p className="text-xs text-gray-600 leading-relaxed">
                  <span className="font-semibold text-gray-900">Display Imersivo:</span> Tela de 14" ou 16" com bordas ultra-finas de 5.3mm e taxa de 90Hz
                </p>
              </div>
              <div className="flex gap-2">
                <span className="text-green-600 text-base flex-shrink-0 mt-0.5">✓</span>
                <p className="text-xs text-gray-600 leading-relaxed">
                  <span className="font-semibold text-gray-900">Resistência Certificada:</span> Proteção IP68 contra água e poeira + Vision Booster 800 nits
                </p>
              </div>
              <div className="flex gap-2">
                <span className="text-green-600 text-base flex-shrink-0 mt-0.5">✓</span>
                <p className="text-xs text-gray-600 leading-relaxed">
                  <span className="font-semibold text-gray-900">Acabamento Premium:</span> Design ultrafino com apenas 6.0mm de espessura
                </p>
              </div>
              <div className="flex gap-2">
                <span className="text-green-600 text-base flex-shrink-0 mt-0.5">✓</span>
                <p className="text-xs text-gray-600 leading-relaxed">
                  <span className="font-semibold text-gray-900">S Pen Inclusa:</span> Caneta stylus para desenho e anotações de alta precisão
                </p>
              </div>
            </div>
          </div>
          <div className="bg-red-50 border border-red-200 rounded-lg p-3 mb-4">
            <div className="flex items-center gap-2 mb-2">
              <span className="text-red-600 text-base">📦</span>
              <h4 className="text-sm font-bold text-red-600">Conteúdo da Embalagem</h4>
            </div>
            <div className="space-y-1">
              <p className="text-xs text-gray-900">• Blackview 64GB</p>
              <p className="text-xs text-gray-900">• S Pen (Caneta Stylus Original)</p>
              <p className="text-xs text-gray-900">• Cabo USB-C</p>
              <p className="text-xs text-gray-900">• Garantia Oficial (5 anos)</p>
              <p className="text-xs text-gray-900">• Nota Fiscal Eletrônica</p>
            </div>
          </div>
          <div className="bg-red-50 border border-red-200 rounded-lg p-3">
            <div className="flex items-center gap-2 mb-1">
              <span className="text-orange-600 text-base">⚠️</span>
              <h4 className="text-sm font-bold text-orange-600">Disponibilidade Limitada</h4>
            </div>
            <p className="text-[10px] text-gray-900 leading-tight">
              Restam apenas <span className="font-bold text-red-600">7 unidades</span> com este preço. Garanta o seu!
            </p>
          </div>
        </div>
        <div className="border-t border-gray-200 px-3 py-4">
          <h3 className="text-sm font-bold text-gray-900 mb-3">Perguntas Frequentes</h3>
          <div className="w-full">
            {faqItems.map((item, index) => {
              const isOpen = openFaqIndex === index;
              return (
                <div key={index} className="border border-gray-200 rounded-lg mb-2 px-3">
                  <button
                    onClick={() => setOpenFaqIndex(isOpen ? null : index)}
                    className="flex flex-1 items-center justify-between font-medium transition-all text-xs text-gray-900 hover:no-underline py-3 w-full text-left"
                  >
                    {item.question}
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={`h-4 w-4 shrink-0 transition-transform duration-200 ${isOpen ? 'rotate-180' : ''}`}>
                      <path d="m6 9 6 6 6-6"></path>
                    </svg>
                  </button>
                  {isOpen && (
                    <div className="overflow-hidden text-sm transition-all">
                      <div className="pt-0 text-xs text-gray-600 pb-3">{item.answer}</div>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>
      </div>

      <div className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 shadow-lg z-50">
        <div className="w-full flex items-center gap-1 md:gap-2 p-2 md:p-3 px-2 md:px-4 max-w-md mx-auto">
          <button
            onClick={() => setIsStoreModalOpen(true)}
            className="flex flex-col items-center justify-center gap-0.5 min-w-[44px] md:min-w-[50px] flex-shrink-0"
          >
            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="h-5 w-5 md:h-6 md:w-6 stroke-[2]">
              <path d="M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8"></path>
              <path d="M3 10a2 2 0 0 1 .709-1.528l7-5.999a2 2 0 0 1 2.582 0l7 5.999A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path>
            </svg>
            <span className="text-[10px] md:text-sm font-normal">Loja</span>
          </button>
          <button
            onClick={() => setIsChatModalOpen(true)}
            className="flex flex-col items-center justify-center gap-0.5 min-w-[44px] md:min-w-[50px] flex-shrink-0"
          >
            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="h-5 w-5 md:h-6 md:w-6 stroke-[2]">
              <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
            </svg>
            <span className="text-[10px] md:text-sm font-normal">Chat</span>
          </button>
          <button
            onClick={() => setIsOptionsModalOpen(true)}
            className="inline-flex items-center justify-center gap-2 whitespace-nowrap transition-colors border bg-white hover:bg-[#fd2154]/10 px-4 py-2 flex-1 h-11 md:h-12 text-xs md:text-sm font-bold border-[#fd2154] text-[#fd2154] rounded-lg min-w-0 uppercase"
          >
            Carrinho
          </button>
          <button
            onClick={handleBuy}
            className="inline-flex items-center justify-center gap-2 whitespace-nowrap transition-colors px-4 py-2 flex-1 h-11 md:h-12 bg-[#fd2154] hover:bg-[#e01d4a] text-white font-bold text-xs md:text-sm rounded-lg min-w-0 uppercase"
          >
            Comprar
          </button>
        </div>
      </div>

      {isOptionsModalOpen && (
        <div className="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
          <div className="bg-white w-full max-w-md rounded-2xl shadow-lg max-h-[80vh] overflow-y-auto">
            <div className="sticky top-0 bg-white border-b border-gray-200 px-4 py-3 flex items-center justify-between z-10">
              <h3 className="text-lg font-bold text-gray-900">Selecione as opções</h3>
              <button
                onClick={() => setIsOptionsModalOpen(false)}
                className="text-gray-500 text-2xl leading-none"
              >
                ×
              </button>
            </div>
            <div className="p-4">
              <div className="flex gap-3 items-center border rounded-2xl p-3 mb-4">
                <div className="w-20 h-20 bg-neutral-100 rounded-xl flex items-center justify-center flex-shrink-0 overflow-hidden">
                  <img
                    src={productImagesByColor[getColorKey(selectedColor)]}
                    alt="Blackview"
                    className="w-full h-full object-contain"
                  />
                </div>
                <div className="flex-1 min-w-0">
                  <h4 className="font-bold text-gray-900 mb-1">Blackview</h4>
                  <div className="flex items-baseline gap-2 mb-1">
                    <span className="text-xl font-bold text-pink-600">
                      {formatCurrency(finalPrice)}
                    </span>
                    <span className="text-sm text-gray-400 line-through">
                      {formatCurrency(oldPrice)}
                    </span>
                  </div>
                  <span className="inline-block bg-green-600 text-white text-xs font-semibold px-2 py-1 rounded">
                    Economize 70%
                  </span>
                </div>
              </div>

              <div className="mb-6">
                <h4 className="font-semibold text-gray-900 mb-3">
                  Cor: {selectedColor}
                </h4>
                <div className="flex gap-3 flex-wrap">
                  {(["Cinza", "Azul", "Prata", "Rosa", "Preto", "Branco"] as Color[]).map((color) => {
                    const colorKey = getColorKey(color);
                    return (
                      <button
                        key={color}
                        onClick={() => setSelectedColor(color)}
                        className={`flex flex-col items-center gap-1 relative ${
                          selectedColor === color
                            ? 'border-2 border-pink-600 rounded-xl p-2'
                            : 'border border-gray-200 rounded-xl p-2'
                        }`}
                      >
                        <div className="w-20 h-16 rounded-lg overflow-hidden">
                          <img
                            src={productImagesByColor[colorKey]}
                            alt={color}
                            className="w-full h-full object-contain"
                          />
                        </div>
                        {selectedColor === color && (
                          <div className="absolute top-1 right-1 w-5 h-5 bg-pink-600 rounded-full flex items-center justify-center">
                            <span className="text-white text-xs">✓</span>
                          </div>
                        )}
                        <span className="text-xs font-medium text-gray-900">{color}</span>
                      </button>
                    );
                  })}
                </div>
              </div>

              <div className="mb-6">
                <h4 className="font-semibold text-gray-900 mb-3">
                  Armazenamento: {selectedStorage}
                </h4>
                <div className="space-y-3">
                  {(["64GB", "512GB", "1TB"] as Storage[]).map((storage) => {
                    const storageFinalPrice = pricesByCombination[getPriceKey(storage, selectedScreenSize)] || 43.71;
                    const storageOldPrice = oldPrices[storage];
                    return (
                      <button
                        key={storage}
                        onClick={() => setSelectedStorage(storage)}
                        className={`w-full border rounded-2xl p-3 flex flex-col gap-1 relative ${
                          selectedStorage === storage
                            ? 'border-pink-600 bg-pink-50'
                            : 'border-gray-200 bg-white'
                        }`}
                      >
                        <div className="flex items-center justify-between">
                          <span className="font-semibold text-gray-900">{storage}</span>
                          {selectedStorage === storage && (
                            <div className="w-5 h-5 bg-pink-600 rounded-full flex items-center justify-center">
                              <span className="text-white text-xs">✓</span>
                            </div>
                          )}
                        </div>
                        <div className="flex items-baseline gap-2">
                          <span className="text-lg font-bold text-pink-600">
                            {formatCurrency(storageFinalPrice)}
                          </span>
                          <span className="text-sm text-gray-400 line-through">
                            {formatCurrency(storageOldPrice)}
                          </span>
                        </div>
                        <span className="inline-block bg-green-600 text-white text-xs font-semibold px-2 py-1 rounded w-fit">
                          Economize 70%
                        </span>
                      </button>
                    );
                  })}
                </div>
              </div>

              <div className="mb-6">
                <h4 className="font-semibold text-gray-900 mb-3">Tamanho de Tela</h4>
                <div className="flex gap-3">
                  <button
                    onClick={() => setSelectedScreenSize("14")}
                    className={`px-4 py-2 rounded-full border text-sm font-medium ${
                      selectedScreenSize === "14"
                        ? 'border-pink-600 bg-pink-50 text-pink-600'
                        : 'border-gray-200 bg-white text-gray-900'
                    }`}
                  >
                    14"
                  </button>
                  <button
                    onClick={() => setSelectedScreenSize("16")}
                    className={`px-4 py-2 rounded-full border text-sm font-medium ${
                      selectedScreenSize === "16"
                        ? 'border-pink-600 bg-pink-50 text-pink-600'
                        : 'border-gray-200 bg-white text-gray-900'
                    }`}
                  >
                    16"
                  </button>
                </div>
              </div>

              <button
                onClick={handleConfirmOptions}
                className="w-full rounded-full py-3 text-center font-semibold text-white bg-pink-600 mt-4 hover:bg-pink-700 transition-colors"
              >
                Confirmar – {formatCurrency(finalPrice)}
              </button>
            </div>
          </div>
        </div>
      )}

      {isStoreModalOpen && (
        <div className="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
          <div className="bg-white w-full max-w-md rounded-2xl overflow-hidden max-h-[90vh] overflow-y-auto relative">
            <button
              onClick={() => setIsStoreModalOpen(false)}
              className="absolute right-4 top-4 rounded-sm opacity-70 hover:opacity-100 transition-opacity focus:outline-none focus:ring-2 focus:ring-gray-300 focus:ring-offset-2"
            >
              <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="h-4 w-4 text-gray-500">
                <path d="M18 6 6 18"></path>
                <path d="m6 6 12 12"></path>
              </svg>
              <span className="sr-only">Close</span>
            </button>
            <div className="p-6">
              <div className="flex flex-col space-y-1.5 text-center sm:text-left mb-4">
                <h2 className="font-semibold tracking-tight text-center text-sm sm:text-base">Informações da Loja</h2>
              </div>
              <div className="space-y-4 pt-1">
                <div className="flex flex-col items-center text-center gap-1.5">
                  <img src={imgAtacadoBrasil} alt="AtacadosBrasil Logo" className="w-12 h-12 sm:w-14 sm:h-14 rounded-full object-cover" loading="lazy" />
                  <div>
                    <h3 className="font-bold text-base sm:text-lg text-black">AtacadosBrasil</h3>
                    <p className="text-xs sm:text-sm text-gray-600">Distribuidor Autorizado Samsung</p>
                    <div className="flex items-center justify-center gap-1 mt-1">
                      <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="h-3.5 w-3.5 sm:h-4 sm:w-4 fill-yellow-400 text-yellow-400">
                        <path d="M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z"></path>
                      </svg>
                      <span className="font-semibold text-xs sm:text-sm">4.9</span>
                      <span className="text-xs sm:text-sm text-gray-600">(15.234 avaliações)</span>
                    </div>
                  </div>
                </div>
                <div className="border-t border-gray-200 pt-3">
                  <div className="flex items-center gap-2 mb-2">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="h-4 w-4 sm:h-5 sm:w-5 text-gray-900">
                      <circle cx="12" cy="12" r="10"></circle>
                      <polyline points="12 6 12 12 16 14"></polyline>
                    </svg>
                    <h4 className="font-bold text-xs sm:text-sm text-black">Horário de Atendimento</h4>
                  </div>
                  <div className="space-y-1.5 pl-6">
                    <div className="flex justify-between text-xs sm:text-sm">
                      <span className="text-gray-600">Segunda - Sexta</span>
                      <span className="text-gray-900 font-medium">09:00 - 18:00</span>
                    </div>
                    <div className="flex justify-between text-xs sm:text-sm">
                      <span className="text-gray-600">Sábado</span>
                      <span className="text-gray-900 font-medium">10:00 - 16:00</span>
                    </div>
                    <div className="flex justify-between text-xs sm:text-sm">
                      <span className="text-gray-600">Domingo</span>
                      <span className="text-gray-900 font-medium">Fechado</span>
                    </div>
                  </div>
                </div>
                <div className="border-t border-gray-200 pt-3">
                  <div className="flex items-center gap-2 mb-2">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="h-4 w-4 sm:h-5 sm:w-5 text-gray-900">
                      <path d="M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0"></path>
                      <circle cx="12" cy="10" r="3"></circle>
                    </svg>
                    <h4 className="font-bold text-xs sm:text-sm text-black">Localização</h4>
                  </div>
                  <div className="pl-6 space-y-0.5">
                    <p className="text-xs sm:text-sm text-gray-600">Av. Paulista, 1000 - Bela Vista</p>
                    <p className="text-xs sm:text-sm text-gray-600">São Paulo - SP, 01310-100</p>
                  </div>
                </div>
                <div className="border-t border-gray-200 pt-3">
                  <div className="flex items-center gap-2 mb-2">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="h-4 w-4 sm:h-5 sm:w-5 text-gray-900">
                      <path d="M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"></path>
                      <path d="m9 12 2 2 4-4"></path>
                    </svg>
                    <h4 className="font-bold text-xs sm:text-sm text-black">Garantias e Benefícios</h4>
                  </div>
                  <div className="space-y-2.5 pl-6">
                    <div>
                      <div className="flex items-start gap-2">
                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="h-3.5 w-3.5 sm:h-4 sm:w-4 text-blue-600 mt-0.5 flex-shrink-0">
                          <path d="M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z"></path>
                          <path d="M12 22V12"></path>
                          <path d="m3.3 7 7.703 4.734a2 2 0 0 0 1.994 0L20.7 7"></path>
                          <path d="m7.5 4.27 9 5.15"></path>
                        </svg>
                        <div>
                          <p className="font-semibold text-xs sm:text-sm text-black">Política de Devolução</p>
                          <p className="text-[10px] sm:text-xs text-gray-600">Devolução gratuita em até 7 dias</p>
                        </div>
                      </div>
                    </div>
                    <div>
                      <div className="flex items-start gap-2">
                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="h-3.5 w-3.5 sm:h-4 sm:w-4 text-green-600 mt-0.5 flex-shrink-0">
                          <path d="M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"></path>
                          <path d="m9 12 2 2 4-4"></path>
                        </svg>
                        <div>
                          <p className="font-semibold text-xs sm:text-sm text-black">Garantia do Fabricante</p>
                          <p className="text-[10px] sm:text-xs text-gray-600">5 anos garantia oficial</p>
                        </div>
                      </div>
                    </div>
                    <div>
                      <div className="flex items-start gap-2">
                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="h-3.5 w-3.5 sm:h-4 sm:w-4 text-orange-600 mt-0.5 flex-shrink-0">
                          <path d="M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2"></path>
                          <path d="M15 18H9"></path>
                          <path d="M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14"></path>
                          <circle cx="17" cy="18" r="2"></circle>
                          <circle cx="7" cy="18" r="2"></circle>
                        </svg>
                        <div>
                          <p className="font-semibold text-xs sm:text-sm text-black">Entrega Expressa</p>
                          <p className="text-[10px] sm:text-xs text-gray-600">Frete grátis com rastreamento</p>
                        </div>
                      </div>
                    </div>
                    <div>
                      <div className="flex items-start gap-2">
                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="h-3.5 w-3.5 sm:h-4 sm:w-4 text-purple-600 mt-0.5 flex-shrink-0">
                          <rect width="18" height="11" x="3" y="11" rx="2" ry="2"></rect>
                          <path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
                        </svg>
                        <div>
                          <p className="font-semibold text-xs sm:text-sm text-black">Compra Protegida</p>
                          <p className="text-[10px] sm:text-xs text-gray-600">Pagamento 100% seguro SSL</p>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <div className="border-t border-gray-200 pt-3">
                  <div className="grid grid-cols-3 gap-2 text-center">
                    <div>
                      <p className="text-lg sm:text-2xl font-bold text-pink-500">2.4M</p>
                      <p className="text-[10px] sm:text-xs text-gray-600">Seguidores</p>
                    </div>
                    <div>
                      <p className="text-lg sm:text-2xl font-bold text-pink-500">52K</p>
                      <p className="text-[10px] sm:text-xs text-gray-600">Produtos</p>
                    </div>
                    <div>
                      <p className="text-lg sm:text-2xl font-bold text-pink-500">98%</p>
                      <p className="text-[10px] sm:text-xs text-gray-600">Satisfação</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      {isChatModalOpen && (
        <div className="fixed inset-0 bg-black/40 z-50 flex items-center justify-center p-4">
          <div className="bg-white max-w-sm w-full rounded-2xl shadow-lg overflow-hidden relative flex flex-col max-h-[90vh]">
            <button
              onClick={handleCloseChat}
              className="absolute right-4 top-4 rounded-sm opacity-70 hover:opacity-100 transition-opacity focus:outline-none focus:ring-2 focus:ring-gray-300 focus:ring-offset-2 z-10"
            >
              <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="h-4 w-4 text-gray-500">
                <path d="M18 6 6 18"></path>
                <path d="m6 6 12 12"></path>
              </svg>
              <span className="sr-only">Close</span>
            </button>
            <div className="flex flex-col space-y-1.5 text-center sm:text-left p-3 pb-2 border-b bg-gradient-to-r from-pink-500/5 to-pink-500/10">
              <h2 className="text-lg font-semibold leading-none tracking-tight flex items-center gap-2">
                <div className="relative">
                  <img src={imgAtacadoBrasil} alt="AtacadosBrasil Logo" className="h-8 w-8 rounded-full object-cover ring-2 ring-pink-500/20" loading="lazy" />
                  <div className="absolute -bottom-0.5 -right-0.5 h-2.5 w-2.5 bg-green-500 rounded-full border-2 border-white"></div>
                </div>
                <div className="flex flex-col">
                  <span className="text-sm font-semibold">Atendimento AtacadosBrasil</span>
                  <span className="text-[10px] text-gray-600 font-normal">Online agora</span>
                </div>
              </h2>
            </div>
            <div className="flex-1 overflow-y-auto space-y-2.5 p-3 min-h-[250px] max-h-[350px]">
              {chatMessages.map((message, index) => (
                <div
                  key={index}
                  className={`flex gap-1.5 ${message.type === 'user' ? 'justify-end' : 'justify-start'}`}
                >
                  {message.type === 'bot' && (
                    <img src={imgAtacadoBrasil} alt="AtacadosBrasil" className="h-6 w-6 rounded-full object-cover flex-shrink-0 mt-0.5" loading="lazy" />
                  )}
                  <div className={`max-w-[75%] rounded-2xl px-2.5 py-1.5 ${
                    message.type === 'user'
                      ? 'bg-pink-500 text-white rounded-tr-sm'
                      : 'bg-gray-100 text-gray-900 rounded-tl-sm'
                  }`}>
                    <p className="text-[11px] leading-relaxed">{message.text}</p>
                  </div>
                </div>
              ))}
            </div>
            <div className="border-t bg-gray-100/30 p-2.5 space-y-1.5">
              <p className="text-[9px] text-gray-600 font-medium px-0.5">Perguntas frequentes:</p>
              <button
                onClick={() => handleFaqClick('Quanto tempo tenho de garantia?')}
                className="inline-flex items-center gap-2 font-medium ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-300 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 border border-gray-300 bg-white hover:text-gray-900 rounded-md w-full text-left justify-start text-[9px] h-auto py-1.5 px-2 whitespace-normal leading-tight hover:bg-pink-500/10 hover:border-pink-500/30 transition-colors"
              >
                Quanto tempo tenho de garantia?
              </button>
              <button
                onClick={() => handleFaqClick('Na primeira compra tem frete grátis?')}
                className="inline-flex items-center gap-2 font-medium ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-300 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 border border-gray-300 bg-white hover:text-gray-900 rounded-md w-full text-left justify-start text-[9px] h-auto py-1.5 px-2 whitespace-normal leading-tight hover:bg-pink-500/10 hover:border-pink-500/30 transition-colors"
              >
                Na primeira compra tem frete grátis?
              </button>
              <button
                onClick={() => handleFaqClick('Como funciona a devolução do produto?')}
                className="inline-flex items-center gap-2 font-medium ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-300 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 border border-gray-300 bg-white hover:text-gray-900 rounded-md w-full text-left justify-start text-[9px] h-auto py-1.5 px-2 whitespace-normal leading-tight hover:bg-pink-500/10 hover:border-pink-500/30 transition-colors"
              >
                Como funciona a devolução do produto?
              </button>
            </div>
          </div>
        </div>
      )}

      {isDiscountPopupOpen && (
        <div className="fixed inset-0 bg-black/50 z-[60] flex items-center justify-center p-4">
          <div className="bg-white w-full max-w-md rounded-2xl shadow-2xl overflow-hidden relative">
            <button
              onClick={() => setIsDiscountPopupOpen(false)}
              className="absolute right-4 top-4 rounded-sm opacity-70 hover:opacity-100 transition-opacity focus:outline-none focus:ring-2 focus:ring-gray-300 focus:ring-offset-2 z-10"
            >
              <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="h-4 w-4 text-white">
                <path d="M18 6 6 18"></path>
                <path d="m6 6 12 12"></path>
              </svg>
              <span className="sr-only">Close</span>
            </button>
            <div className="bg-[#fd2154] text-white p-4 text-center">
              <div className="flex items-center justify-center gap-2 mb-1">
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="currentColor" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="h-5 w-5">
                  <path d="M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"></path>
                </svg>
                <h2 className="text-xl font-bold">ESPERE!</h2>
              </div>
              <p className="text-base font-semibold">Não vá embora sem seu desconto especial!</p>
            </div>
            <div className="p-3 sm:p-4 space-y-3 sm:space-y-4">
              <div className="text-center">
                <div className="mb-3 sm:mb-4">
                  <img
                    src={imgPd4}
                    alt="Blackview - Tablet com IA e S Pen"
                    className="w-full max-w-[240px] sm:max-w-[300px] mx-auto h-auto object-contain"
                    loading="lazy"
                  />
                  <h3 className="font-bold text-base sm:text-lg mt-2 px-2 leading-tight">
                    Blackview - Tablet com IA e S Pen
                  </h3>
                </div>
              </div>
              <div className="bg-gray-50 p-3 rounded-lg text-center space-y-1.5">
                <p className="text-xs text-gray-600">
                  De: <span className="line-through">R$ 2.299,00</span>
                </p>
                <div className="flex items-center justify-center gap-2 flex-wrap">
                  <span className="text-2xl sm:text-3xl font-bold text-[#fd2154]">
                    {formatCurrency(finalPrice)}
                  </span>
                  <span className="bg-[#fd2154] text-white px-2 py-1 rounded text-xs font-bold">
                    {discountPercent}% OFF
                  </span>
                </div>
                <p className="text-sm sm:text-base font-bold text-green-600">
                  Economize {formatCurrency(oldPrice - finalPrice)}!
                </p>
              </div>
              <div className="space-y-2.5">
                <button
                  onClick={handleBuy}
                  className="inline-flex items-center justify-center gap-2 whitespace-nowrap transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-300 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 rounded-md px-8 w-full bg-[#fd2154] hover:bg-[#e01d4a] text-white font-bold text-sm sm:text-base h-11 sm:h-12"
                >
                  SIM! QUERO MEU DESCONTO
                </button>
                <button
                  onClick={() => setIsDiscountPopupOpen(false)}
                  className="w-full text-xs text-gray-600 hover:text-gray-900 underline"
                >
                  Não, obrigado. Prefiro pagar {formatCurrency(oldPrice)}
                </button>
              </div>
              <div className="text-center text-[10px] sm:text-xs text-gray-600">
                ⚡ Oferta válida apenas nesta sessão
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default ProductPage;
