'use client';

import React, { useState } from 'react';
import { useApp, Product } from '@/context/AppContext';
import { FolderHeart, Sparkles, Filter, Plus, HelpCircle, Check, ShoppingBag, Eye, X, ChevronDown, ArrowUpDown } from 'lucide-react';
import { motion } from 'motion/react';
import { translations } from '@/lib/translations';

export default function StorefrontView() {
  const { products, addToCart, theme, formatPrice, searchQuery, currentUser, setAuthModalOpen, setAuthModalTab, language } = useApp();
  const t = translations[language];

  // Map products to their translated counterparts
  const localizedProducts = products.map(prod => {
    const override = t.products && t.products[prod.id];
    if (override) {
      return {
        ...prod,
        name: override.name,
        description: override.description,
        tags: override.tags
      };
    }
    return prod;
  });

  const [selectedCategory, setSelectedCategory] = useState<string>('all');
  const [sortBy, setSortBy] = useState<'latest' | 'popularity' | 'price_asc' | 'price_desc'>('latest');
  const [briefModalProduct, setBriefModalProduct] = useState<Product | null>(null);
  const [customInstructions, setCustomInstructions] = useState('');
  const [qty, setQty] = useState(1);
  const [activeQuickView, setActiveQuickView] = useState<Product | null>(null);

  const isDark = theme === 'dark';

  // Categories mapping
  const categories = [
    { id: 'all', label: t.allServicesAndProducts },
    { id: 'digital_products', label: t.digitalProducts },
    { id: 'graphic_design', label: t.graphicDesign },
    { id: 'video_editing', label: t.videoEditing },
  ];

  const filteredProducts = localizedProducts.filter((prod) => {
    const matchesCategory = selectedCategory === 'all' || prod.category === selectedCategory;
    const query = searchQuery.trim().toLowerCase();
    
    if (!query) return matchesCategory;

    const matchesSearch = 
      prod.name.toLowerCase().includes(query) ||
      prod.category.replace('_', ' ').toLowerCase().includes(query) ||
      prod.description.toLowerCase().includes(query) ||
      prod.tags.some(tag => tag.toLowerCase().includes(query));

    return matchesCategory && matchesSearch;
  });

  const getPopularityScore = (productId: string): number => {
    const scores: Record<string, number> = {
      'prod-1': 95,
      'prod-2': 85,
      'prod-3': 98,
      'prod-4': 80,
      'prod-5': 88,
      'prod-6': 92,
      'prod-7': 82,
      'prod-8': 75,
      'prod-9': 70,
      'prod-10': 91,
      'prod-11': 78,
      'prod-12': 86,
    };
    return scores[productId] ?? 50;
  };

  const getProductOrderValue = (productId: string): number => {
    const parts = productId.split('prod-');
    if (parts.length > 1) {
      const num = parseInt(parts[1], 10);
      if (!isNaN(num)) {
        if (num > 1000) {
          return num; // Dynamic timestamp ID e.g., prod-171758... (larger values are newer)
        }
        // Seed products prod-1 through prod-12 (lower indexes mapped to higher values so prod-1 is newer than prod-12 among seeds)
        return 1000 - num;
      }
    }
    return 0;
  };

  const sortedProducts = [...filteredProducts].sort((a, b) => {
    if (sortBy === 'latest') {
      return getProductOrderValue(b.id) - getProductOrderValue(a.id);
    }
    if (sortBy === 'price_asc') {
      return a.price - b.price;
    }
    if (sortBy === 'price_desc') {
      return b.price - a.price;
    }
    return getPopularityScore(b.id) - getPopularityScore(a.id);
  });

  const handleOpenBrief = (product: Product) => {
    if (!currentUser) {
      setAuthModalTab('register');
      setAuthModalOpen(true);
      return;
    }
    setBriefModalProduct(product);
    setQty(1);
    // Suggest helpful default briefs based on item
    if (product.category === 'graphic_design') {
      setCustomInstructions('Colors: Dark themed/glowing. Brand Name: [MyBrand]. Visual references: cybernetic, glass-morphism.');
    } else if (product.category === 'video_editing') {
      setCustomInstructions('Audio duration: 3:10. Mood/aesthetic: Synthwave, slow-paced motion, high sync lyrics.');
    } else {
      setCustomInstructions('Special notes or preferred delivery channels.');
    }
  };

  const handleConfirmAdd = () => {
    if (!briefModalProduct) return;
    addToCart(briefModalProduct, qty, customInstructions);
    setBriefModalProduct(null);
    setCustomInstructions('');
  };

  return (
    <div className="w-full max-w-7xl mx-auto px-4 sm:px-6 py-8" id="storefront-container">
      
      {/* Search and Category Filters */}
      <div className={`flex flex-col md:flex-row md:items-center justify-between gap-6 mb-12 border-b pb-8 transition-colors duration-300 ${
        isDark ? 'border-white/[0.05]' : 'border-slate-200'
      }`}>
        <div>
          <h2 className={`font-display font-black text-2xl sm:text-3xl flex items-center gap-2.5 transition-colors duration-300 ${
            isDark ? 'text-slate-100' : 'text-slate-900'
          }`}>
            <FolderHeart className="w-6 h-6 text-purple-500" />
            <span>{t.storeTitle}</span>
          </h2>
          <p className={`text-xs mt-1 transition-colors duration-300 ${
            isDark ? 'text-slate-400' : 'text-slate-500'
          }`}>
            {t.storeSubtitle}
          </p>
        </div>

        {/* Categories sliding pills & Sorting options */}
        <div className="flex flex-col lg:flex-row lg:items-center gap-4 w-full md:w-auto" id="storefront-filters-and-sort">
          <div className="flex items-center gap-2 overflow-x-auto pb-2 custom-scroll w-full lg:w-auto" id="category-pills">
            <Filter className="w-4 h-4 text-slate-500 mr-1 flex-shrink-0" />
            {categories.map((cat) => (
              <button
                key={cat.id}
                onClick={() => setSelectedCategory(cat.id)}
                className={`px-4 py-2 text-xs font-semibold rounded-xl whitespace-nowrap border cursor-pointer transition-all duration-300 ${
                  selectedCategory === cat.id
                    ? isDark
                      ? 'bg-purple-500/10 text-purple-300 border-purple-500/30 shadow-[0_0_15px_rgba(168,85,247,0.15)]'
                      : 'bg-purple-500/10 text-purple-600 border-purple-500/20 shadow-sm'
                    : isDark
                      ? 'bg-white/[0.02] text-slate-400 border-white/5 hover:text-white hover:bg-white/5'
                      : 'bg-white border-slate-200 text-slate-600 hover:text-slate-900 hover:bg-slate-50 shadow-sm'
                }`}
              >
                {cat.label}
              </button>
            ))}
          </div>

          {/* Quick Sorting Dropdown */}
          <div className="relative flex items-center min-w-[170px] w-full lg:w-48" id="product-sort-container">
            <span className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none text-slate-400/85">
              <ArrowUpDown className="w-3.5 h-3.5" />
            </span>
            <select
              value={sortBy}
              onChange={(e) => setSortBy(e.target.value as any)}
              className={`w-full text-xs font-semibold pl-8.5 pr-8 py-2 rounded-xl border outline-none cursor-pointer appearance-none transition-all duration-300 ${
                isDark
                  ? 'bg-white/[0.02] border-white/5 text-slate-200 hover:bg-white/5 hover:border-white/10 focus:border-cyan-500/40 focus:ring-1 focus:ring-cyan-500/10'
                  : 'bg-white border-slate-200 text-slate-700 hover:bg-slate-50 hover:border-slate-300 focus:border-purple-500/40 focus:ring-1 focus:ring-purple-500/10 shadow-sm'
              }`}
            >
              <option value="latest">{t.latestUploaded}</option>
              <option value="popularity">{t.popularity}</option>
              <option value="price_asc">{t.priceLowToHigh}</option>
              <option value="price_desc">{t.priceHighToLow}</option>
            </select>
            <span className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none text-slate-400">
              <ChevronDown className="w-3.5 h-3.5 animate-bounce-slow" />
            </span>
          </div>
        </div>
      </div>

      {/* Products & Services Grid */}
      {sortedProducts.length === 0 ? (
        <div className={`text-center py-20 border rounded-3xl transition-colors duration-300 ${
          isDark ? 'bg-slate-950/20 border-white/5' : 'bg-slate-50 border-slate-200'
        }`}>
          <HelpCircle className="w-12 h-12 text-slate-400/50 mx-auto mb-3" />
          <p className={`text-sm font-mono ${isDark ? 'text-slate-400' : 'text-slate-500'}`}>
            {searchQuery.trim() 
              ? `${t.noOfferingsFound} "${searchQuery}"` 
              : t.noOfferingsFoundSub}
          </p>
          <p className="text-[10px] text-slate-500 mt-1">
            {t.correctTypos}
          </p>
        </div>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6" id="products-grid">
          {sortedProducts.map((prod, index) => (
            <motion.div
              layout
              initial={{ opacity: 0, scale: 0.98 }}
              animate={{ opacity: 1, scale: 1 }}
              whileHover={{ y: -6 }}
              whileTap={{ scale: 0.985 }}
              transition={{ duration: 0.4, delay: index * 0.03, ease: 'easeOut' }}
              key={prod.id}
              className={`group relative rounded-3xl overflow-hidden border flex flex-col p-5 h-full justify-between transition-[border-color,background-color,box-shadow] duration-300 ${
                isDark 
                  ? 'border-white/10 bg-white/5 backdrop-blur-md hover:border-cyan-400/35 hover:shadow-[0_8px_32px_rgba(34,211,238,0.1)]' 
                  : 'border-slate-200 bg-white/80 backdrop-blur-md hover:border-cyan-400/35 shadow-sm hover:shadow-[0_8px_32px_rgba(34,211,238,0.06)]'
              }`}
            >
              {/* Top Accent line on hover */}
              <div className="absolute top-0 left-0 w-full h-[2px] bg-gradient-to-r from-cyan-400 to-purple-500 opacity-0 group-hover:opacity-100 transition-opacity" />

              <div>
                {/* Product Cover Asset */}
                <div className={`relative w-full aspect-[16/10] rounded-xl overflow-hidden border mb-4 transition-colors ${
                  isDark ? 'bg-slate-950 border-white/5' : 'bg-slate-100 border-slate-200/60'
                }`}>
                  <img
                    src={prod.mediaUrl}
                    alt={prod.name}
                    className="w-full h-full object-cover group-hover:scale-105 duration-700 pointer-events-none"
                    referrerPolicy="no-referrer"
                  />
                  
                  {/* Category mini badge */}
                  <span className={`absolute top-3 left-3 px-2 py-1 backdrop-blur-md rounded-lg font-mono text-[9px] uppercase tracking-wider border transition-colors duration-300 ${
                    isDark 
                      ? 'bg-slate-950/80 text-slate-300 border-white/10' 
                      : 'bg-white/90 text-slate-600 border-slate-200 shadow-sm'
                  }`}>
                    {prod.category.replace('_', ' ')}
                  </span>

                  {/* Stock status badge */}
                  <span className={`absolute top-3 right-3 px-2 py-1 backdrop-blur-md rounded-lg font-mono text-[9px] uppercase tracking-wider border font-bold transition-all duration-300 ${
                    prod.inStock !== false 
                      ? 'bg-emerald-500/20 text-emerald-300 border-emerald-500/30' 
                      : 'bg-rose-500/20 text-rose-300 border-rose-500/30'
                  }`}>
                    {prod.inStock !== false ? 'In Stock' : 'Out of Stock'}
                  </span>

                  {/* Operational specs badge */}
                  <span className={`absolute bottom-3 right-3 px-2 py-1 backdrop-blur-md rounded-lg font-mono text-[9px] border transition-colors duration-300 ${
                    isDark 
                      ? 'bg-slate-950/80 text-cyan-400 border-white/10' 
                      : 'bg-white/95 text-cyan-600 border-slate-200 shadow-sm font-semibold'
                  }`}>
                    SLA: {prod.deliveryTime}
                  </span>
                </div>

                {/* Sub-tags row */}
                <div className="flex flex-wrap gap-1.5 mb-3">
                  {prod.tags.map((tg, i) => (
                    <span key={i} className={`text-[9px] font-mono px-2 py-0.5 rounded border transition-colors duration-300 ${
                      isDark 
                        ? 'text-slate-500 bg-white/[0.01] border-white/5' 
                        : 'text-slate-500 bg-slate-50 border-slate-200'
                    }`}>
                      #{tg}
                    </span>
                  ))}
                </div>

                {/* Name */}
                <h3 className={`font-display font-bold text-base transition-colors mb-2 line-clamp-1 ${
                  isDark ? 'text-slate-200 group-hover:text-purple-300' : 'text-slate-900 group-hover:text-purple-600'
                }`}>
                  {prod.name}
                </h3>

                {/* Description */}
                <p className={`text-xs mb-6 leading-relaxed line-clamp-3 transition-colors duration-300 ${
                  isDark ? 'text-slate-400' : 'text-slate-600'
                }`}>
                  {prod.description}
                </p>
              </div>

              {/* Price and Add button section */}
              <div className={`flex items-center justify-between border-t pt-4 mt-auto transition-colors duration-300 ${
                isDark ? 'border-white/[0.04]' : 'border-slate-100'
              }`}>
                <div className="text-left">
                  <span className="text-[10px] font-mono text-slate-500 block tracking-widest uppercase leading-none mb-1">{t.priceRate}</span>
                  <span className={`text-xl font-display font-black duration-300 ${
                    isDark ? 'text-white group-hover:text-cyan-400' : 'text-slate-900 group-hover:text-cyan-650'
                  }`}>
                    {formatPrice(prod.price)}
                  </span>
                </div>

                <div className="flex items-center gap-2">
                  <button
                    onClick={() => setActiveQuickView(prod)}
                    className={`p-2 rounded-xl transition-all text-xs flex items-center justify-center cursor-pointer border ${
                      isDark 
                        ? 'bg-white/[0.02] hover:bg-white/[0.08] text-slate-400 hover:text-white border-white/5' 
                        : 'bg-slate-50 hover:bg-slate-100 text-slate-500 hover:text-slate-900 border-slate-200 shadow-sm'
                    }`}
                    title={t.quickView}
                  >
                    <Eye className="w-4 h-4" />
                  </button>
                  
                  {prod.inStock !== false ? (
                    <button
                      onClick={() => handleOpenBrief(prod)}
                      className="px-4 py-2.5 rounded-xl bg-gradient-to-r from-purple-600 to-indigo-600 hover:from-purple-500 hover:to-indigo-500 text-xs font-semibold text-white tracking-wide flex items-center gap-1.5 shadow-lg group-hover:shadow-purple-500/10 cursor-pointer transition-all duration-300 transform group-hover:-translate-y-0.5 animate-fade-in"
                    >
                      <Plus className="w-4.5 h-4.5" />
                      <span>{t.addToCart}</span>
                    </button>
                  ) : (
                    <button
                      disabled
                      className="px-4 py-2.5 rounded-xl bg-slate-100 dark:bg-white/5 border border-slate-200 dark:border-white/10 text-xs font-semibold text-slate-400 dark:text-slate-500 cursor-not-allowed transition-all duration-300"
                    >
                      <span>Out Of Stock</span>
                    </button>
                  )}
                </div>
              </div>
            </motion.div>
          ))}
        </div>
      )}

      {/* Brief / Configure SLA Modal */}
      {briefModalProduct && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          <div className="absolute inset-0 bg-black/70 backdrop-blur-sm" onClick={() => setBriefModalProduct(null)} />
          
          <div className={`border rounded-2xl w-full max-w-lg p-6 relative z-10 font-sans shadow-2xl transition-all duration-300 ${
            isDark 
              ? 'bg-[#060412] border-white/10 text-white shadow-[0_0_50px_rgba(168,85,247,0.15)]' 
              : 'bg-white border-slate-200 text-slate-900 shadow-[0_10px_40px_rgba(0,0,0,0.08)]'
          }`}>
            <button 
              onClick={() => setBriefModalProduct(null)}
              className={`absolute top-4 right-4 p-1 rounded-lg border transition-all cursor-pointer ${
                isDark 
                  ? 'border-white/5 text-slate-400 hover:text-white hover:bg-white/5' 
                  : 'border-slate-200 text-slate-400 hover:text-slate-900 hover:bg-slate-50'
              }`}
            >
              <X className="w-4 h-4" />
            </button>

            <div className="flex items-center gap-3 mb-4">
              <div className="w-10 h-10 rounded-lg bg-purple-500/10 border border-purple-500/20 flex items-center justify-center text-purple-500">
                <Sparkles className="w-5 h-5" />
              </div>
              <div>
                <h4 className={`font-display font-bold text-base transition-colors duration-300 ${
                  isDark ? 'text-slate-100' : 'text-slate-900'
                }`}>Bespoke Setup Instructions</h4>
                <p className="text-[10px] font-mono text-cyan-600 dark:text-cyan-400 uppercase tracking-widest mt-0.5 font-bold">
                  SLA Deliverable: {briefModalProduct.deliveryTime}
                </p>
              </div>
            </div>

            <p className={`text-xs leading-relaxed mb-4 border p-3 rounded-xl italic transition-all duration-300 ${
              isDark 
                ? 'text-slate-400 bg-white/[0.01] border-white/5' 
                : 'text-slate-600 bg-slate-50 border-slate-200 shadow-sm'
            }`}>
              Selected: <b>{briefModalProduct.name}</b> at <b>{formatPrice(briefModalProduct.price)}</b> rate.
            </p>

            {/* Visual Progress Bar / Estimated Completion Time */}
            <div className={`p-4 rounded-xl border mb-5 transition-all text-left ${
              isDark 
                ? 'bg-[#0b0821] border-cyan-500/10 text-slate-300' 
                : 'bg-cyan-50/20 border-cyan-100 text-slate-705 shadow-xs'
            }`}>
              <div className="flex justify-between items-center text-[10px] uppercase font-mono tracking-wider font-extrabold mb-2 text-cyan-600 dark:text-cyan-400">
                <span>Estimated Fulfillment Lead Time</span>
                <span className="bg-purple-500/10 dark:bg-purple-500/20 px-2 py-0.5 rounded-md text-[9px] text-purple-600 dark:text-purple-300 font-bold">
                  {briefModalProduct.deliveryTime}
                </span>
              </div>
              
              <div className="space-y-3">
                {/* Visual Progress Line */}
                <div className="relative pt-0.5" id="brief-modal-timeline">
                  {/* Background Track bar */}
                  <div className="w-full bg-slate-200 dark:bg-purple-950/40 h-2 rounded-full overflow-hidden relative border border-slate-300 dark:border-white/5">
                    {/* Active dynamic filled bar */}
                    <div className="h-full bg-gradient-to-r from-cyan-400 via-purple-500 to-indigo-500 rounded-full animate-pulse shadow-[0_0_8px_rgba(6,182,212,0.4)]" style={{ width: briefModalProduct.deliveryTime.toLowerCase().includes('instant') || briefModalProduct.deliveryTime.toLowerCase().includes('15 min') ? '100%' : '35%' }} />
                  </div>
                </div>

                {/* Milestones Flow Steps */}
                <div className="grid grid-cols-3 gap-2 text-[9px] font-mono leading-tight">
                  {(() => {
                    const isMm = language === 'MM';
                    const isInstant = briefModalProduct.deliveryTime.toLowerCase().includes('instant') || briefModalProduct.deliveryTime.toLowerCase().includes('15 min');
                    if (isInstant) {
                      return [
                        { step: isMm ? "ငွေပေးချေမှုအတည်ပြု" : "Verify Order", duration: "1 min", active: true },
                        { step: isMm ? "အလိုအလျောက်သတ်မှတ်" : "Auto Provision", duration: "2 min", active: true },
                        { step: isMm ? "ချက်ချင်းပေးပို့သည်" : "Instant Active", duration: "Released", active: true }
                      ].map((item, index) => (
                        <div key={index} className="flex flex-col">
                          <span className={`${isDark ? 'text-slate-200' : 'text-slate-800'} font-bold`}>{item.step}</span>
                          <span className="text-[8px] text-slate-500 mt-0.5">{item.duration}</span>
                        </div>
                      ));
                    } else {
                      return [
                        { step: isMm ? "ဒီဇိုင်းအတည်ပြု" : "Verify Brief", duration: "Pending", active: true },
                        { step: isMm ? "ပုံကြမ်းရေးဆွဲဖန်တီး" : "Creative Render", duration: "Active Work", active: false },
                        { step: isMm ? "အချောသတ်စစ်ဆေး" : "Secure Release", duration: "SLA Target", active: false }
                      ].map((item, index) => (
                        <div key={index} className="flex flex-col">
                          <span className={`font-bold ${item.active ? (isDark ? 'text-cyan-400' : 'text-cyan-650') : (isDark ? 'text-slate-500' : 'text-slate-400')}`}>{item.step}</span>
                          <span className="text-[8px] text-purple-500/80 mt-0.5 font-bold">{item.duration}</span>
                        </div>
                      ));
                    }
                  })()}
                </div>
              </div>
            </div>

            {/* Custom brief instructions block */}
            <div className="space-y-4">
              <div>
                <label className={`text-[10px] font-mono block mb-1 uppercase tracking-wider font-bold ${
                  isDark ? 'text-slate-400' : 'text-slate-500'
                }`}>
                  {briefModalProduct.isDigital 
                    ? "Custom Config Instructions (Optional)" 
                    : "Creative Project Brief & Notes (Highly Recommended)"}
                </label>
                <textarea
                  value={customInstructions}
                  onChange={(e) => setCustomInstructions(e.target.value)}
                  rows={4}
                  className={`w-full border focus:border-purple-500 focus:ring-1 focus:ring-purple-500/30 rounded-xl p-3 text-xs outline-none resize-none font-sans leading-relaxed transition-all duration-300 ${
                    isDark 
                      ? 'bg-slate-900/50 border-white/10 text-slate-200' 
                      : 'bg-slate-50 border-slate-200 text-slate-800'
                  }`}
                  placeholder="Insert preferred configuration notes, files links, usernames or soundscape visual parameters..."
                />
              </div>

              {/* Quantity selectors */}
              <div className={`flex items-center justify-between border px-4 py-3 rounded-xl transition-all duration-300 ${
                isDark 
                  ? 'bg-white/[0.02] border-white/5' 
                  : 'bg-slate-50 border-slate-200'
              }`}>
                <span className={`text-xs font-mono ${isDark ? 'text-slate-400' : 'text-slate-500'}`}>Task Commission Multiplier (Qty):</span>
                <div className="flex items-center gap-3">
                  <button 
                    onClick={() => setQty(Math.max(1, qty - 1))}
                    className={`w-7 h-7 rounded-lg border flex items-center justify-center text-sm font-bold cursor-pointer transition-all duration-300 ${
                      isDark 
                        ? 'bg-white/5 border-white/10 text-slate-300 hover:text-white hover:bg-white/10' 
                        : 'bg-white border-slate-200 text-slate-600 hover:text-slate-900 hover:bg-slate-100 shadow-sm'
                    }`}
                  >
                    -
                  </button>
                  <span className={`font-mono text-sm font-bold w-4 text-center ${isDark ? 'text-slate-100' : 'text-slate-800'}`}>{qty}</span>
                  <button 
                    onClick={() => setQty(qty + 1)}
                    className={`w-7 h-7 rounded-lg border flex items-center justify-center text-sm font-bold cursor-pointer transition-all duration-300 ${
                      isDark 
                        ? 'bg-white/5 border-white/10 text-slate-300 hover:text-white hover:bg-white/10' 
                        : 'bg-white border-slate-200 text-slate-600 hover:text-slate-900 hover:bg-slate-100 shadow-sm'
                    }`}
                  >
                    +
                  </button>
                </div>
              </div>

              {/* Checkout triggers */}
              <button
                onClick={handleConfirmAdd}
                className="w-full py-4.5 rounded-xl bg-gradient-to-r from-cyan-500 to-purple-600 hover:from-cyan-400 hover:to-purple-500 text-xs font-black tracking-widest text-white uppercase shadow-xl hover:shadow-[0_0_20px_rgba(139,92,246,0.2)] transition-all duration-300 flex items-center justify-center gap-2 cursor-pointer mt-2"
              >
                <ShoppingBag className="w-4 h-4" />
                <span>Add Selected to Cart &bull; {formatPrice(briefModalProduct.price * qty)}</span>
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Quick Info Look Modal */}
      {activeQuickView && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          <div className="absolute inset-0 bg-black/75 backdrop-blur-sm" onClick={() => setActiveQuickView(null)} />
          <div className={`border rounded-3xl w-full max-w-2xl max-h-[90vh] overflow-y-auto custom-scroll relative z-10 p-6 sm:p-8 shadow-2xl transition-all duration-300 ${
            isDark 
              ? 'bg-[#05030f] border-white/10 text-white shadow-[0_0_50px_rgba(6,182,212,0.15)]' 
              : 'bg-white border-slate-200 text-slate-950 shadow-[0_10px_40px_rgba(0,0,0,0.08)]'
          }`}>
            <button 
              onClick={() => setActiveQuickView(null)}
              className={`absolute top-4 right-4 p-1.5 rounded-lg border transition-all cursor-pointer ${
                isDark 
                  ? 'border-white/5 text-slate-400 hover:text-white hover:bg-white/5' 
                  : 'border-slate-200 text-slate-450 hover:text-slate-900 hover:bg-slate-55'
              }`}
            >
              <X className="w-4 h-4" />
            </button>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-6 sm:gap-8">
              {/* Product Cover image */}
              <div className={`relative aspect-[4/3] rounded-2xl overflow-hidden border transition-colors duration-300 ${
                isDark ? 'bg-slate-950 border-white/5' : 'bg-slate-100 border-slate-200'
              }`}>
                <img 
                  src={activeQuickView.mediaUrl} 
                  alt={activeQuickView.name} 
                  className="w-full h-full object-cover"
                />
              </div>

              {/* Details column */}
              <div className="flex flex-col justify-between">
                <div>
                  <span className={`px-2.5 py-1 font-mono text-[9px] uppercase tracking-widest rounded-lg border w-fit block mb-3 transition-colors duration-300 ${
                    isDark
                      ? 'bg-purple-500/10 text-purple-300 border-purple-500/20'
                      : 'bg-purple-50/80 text-purple-600 border-purple-200 shadow-sm font-semibold'
                  }`}>
                    {activeQuickView.category.replace('_', ' ')}
                  </span>
                  
                  <h3 className={`font-display font-black text-xl mb-2 leading-tight transition-colors duration-300 ${
                    isDark ? 'text-white' : 'text-slate-900'
                  }`}>
                    {activeQuickView.name}
                  </h3>

                  <p className={`text-xs leading-relaxed mb-4 transition-colors duration-300 ${
                    isDark ? 'text-slate-400' : 'text-slate-650'
                  }`}>
                    {activeQuickView.description}
                  </p>

                  <div className={`space-y-2 border-t pt-4 transition-colors duration-300 ${
                    isDark ? 'border-white/5' : 'border-slate-100'
                  }`}>
                    <div className="flex justify-between text-xs">
                      <span className="text-slate-500 font-mono">Provisioning Speed:</span>
                      <span className="text-cyan-600 dark:text-cyan-400 font-semibold">{activeQuickView.deliveryTime}</span>
                    </div>
                    <div className="flex justify-between text-xs">
                      <span className="text-slate-500 font-mono">Integration Model:</span>
                      <span className={`font-semibold ${isDark ? 'text-slate-300' : 'text-slate-705'}`}>{activeQuickView.isDigital ? "Digital Direct Secure" : "Specialized Creative Review"}</span>
                    </div>
                    <div className="flex justify-between text-xs">
                      <span className="text-slate-500 font-mono">Stock Availability:</span>
                      <span className={`font-semibold ${activeQuickView.inStock !== false ? 'text-emerald-505 dark:text-emerald-400' : 'text-rose-505 dark:text-rose-400'}`}>
                        {activeQuickView.inStock !== false ? "In Stock" : "Out of Stock"}
                      </span>
                    </div>
                  </div>
                </div>

                <div className={`flex items-center justify-between border-t pt-6 mt-6 md:mt-0 transition-colors duration-300 ${
                  isDark ? 'border-white/5' : 'border-slate-100'
                }`}>
                  <div>
                    <span className="text-[9px] font-mono text-slate-500 block uppercase tracking-widest mb-1">Total Fee Rate</span>
                    <span className={`text-2xl font-display font-black transition-colors duration-300 ${
                      isDark ? 'text-white' : 'text-slate-900'
                    }`}>{formatPrice(activeQuickView.price)}</span>
                  </div>

                  {activeQuickView.inStock !== false ? (
                    <button
                      onClick={() => {
                        const prod = activeQuickView;
                        setActiveQuickView(null);
                        handleOpenBrief(prod);
                      }}
                      className="px-5 py-3 rounded-2xl bg-gradient-to-r from-purple-600 to-indigo-600 hover:from-purple-500 hover:to-indigo-500 text-xs font-bold text-white tracking-widest uppercase shadow-lg transition-all duration-300 flex items-center gap-1.5 cursor-pointer"
                    >
                      <Plus className="w-4.5 h-4.5" />
                      <span>Enlist Setup</span>
                    </button>
                  ) : (
                    <button
                      disabled
                      className="px-5 py-3 rounded-2xl bg-slate-100 dark:bg-white/5 border border-slate-200 dark:border-white/10 text-xs font-bold text-slate-400 dark:text-slate-500 cursor-not-allowed transition-all duration-300"
                    >
                      <span>Out Of Stock</span>
                    </button>
                  )}
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

    </div>
  );
}
