/* === Shared components === */
const { useState, useEffect, useMemo, useRef, useCallback } = React;

const analyticsSessionId = () => {
  try {
    let id = sessionStorage.getItem('aisubs_analytics_session');
    if (!id) {
      id = crypto.randomUUID ? crypto.randomUUID() : `${Date.now()}-${Math.random().toString(16).slice(2)}`;
      sessionStorage.setItem('aisubs_analytics_session', id);
    }
    return id;
  } catch (e) {
    return 'session-unavailable';
  }
};

const analyticsDevice = () => {
  const ua = navigator.userAgent || '';
  if (/Mobi|Android|iPhone/i.test(ua) || window.innerWidth < 700) return 'mobile';
  if (/iPad|Tablet/i.test(ua) || window.innerWidth < 1024) return 'tablet';
  return 'desktop';
};

const analyticsBrowser = () => {
  const ua = navigator.userAgent || '';
  if (/Edg\//.test(ua)) return 'Edge';
  if (/Chrome\//.test(ua)) return 'Chrome';
  if (/Safari\//.test(ua) && !/Chrome\//.test(ua)) return 'Safari';
  if (/Firefox\//.test(ua)) return 'Firefox';
  return 'Other';
};

const analyticsReferrer = () => {
  try {
    if (!document.referrer) return '';
    return new URL(document.referrer).hostname;
  } catch (e) {
    return '';
  }
};

const analyticsRoute = () => {
  if (window.AISUBS_CURRENT_ROUTE) return window.AISUBS_CURRENT_ROUTE;
  try {
    const hash = window.location.hash || '';
    if (hash && hash !== '#') {
      let route = hash.slice(1);
      try { route = decodeURIComponent(route); } catch (e) {}
      route = route.replace(/^\/+/, '').replace(/\/+$/, '');
      if (route.startsWith('category/')) return `cat:${route.slice(9)}`;
      if (route.startsWith('cat/')) return `cat:${route.slice(4)}`;
      if (route.startsWith('brand/')) return `brand:${route.slice(6)}`;
      return route || 'home';
    }
    let path = window.location.pathname || '/';
    try { path = decodeURIComponent(path); } catch (e) {}
    path = path.replace(/^\/+/, '').replace(/\/+$/, '');
    if (!path || path === 'home') return 'home';
    const [head, ...rest] = path.split('/');
    const segment = rest.join('/');
    if ((head === 'category' || head === 'cat') && segment) return `cat:${segment}`;
    if (head === 'brand' && segment) return `brand:${segment}`;
    return path;
  } catch (e) {
    return 'home';
  }
};

const trackAnalytics = (type, props = {}) => {
  try {
    const route = analyticsRoute();
    if (route.startsWith('admin-ahmed')) return;
    const payload = {
      type,
      route,
      path: window.location.pathname,
      sessionId: analyticsSessionId(),
      lang: document.documentElement.lang || 'ar',
      referrer: analyticsReferrer(),
      device: analyticsDevice(),
      browser: analyticsBrowser(),
      props
    };
    const body = JSON.stringify(payload);
    if (navigator.sendBeacon) {
      navigator.sendBeacon('/api/track', new Blob([body], { type: 'application/json' }));
      return;
    }
    fetch('/api/track', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body,
      keepalive: true
    }).catch(() => {});
  } catch (e) {}
};

// === Icons (inline SVG, no deps) ===
const Icon = ({ name, size = 20, ...rest }) => {
  const s = size;
  const paths = {
    cart:    <><circle cx="9" cy="20" r="1.5"/><circle cx="18" cy="20" r="1.5"/><path d="M3 4h2l2.5 11h12l2-7H7" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></>,
    user:    <><circle cx="12" cy="8" r="4" fill="none" stroke="currentColor" strokeWidth="1.6"/><path d="M4 21c1-4.5 4.5-7 8-7s7 2.5 8 7" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></>,
    search:  <><circle cx="11" cy="11" r="6" fill="none" stroke="currentColor" strokeWidth="1.6"/><path d="M16 16l4 4" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></>,
    arrow:   <path d="M16 12H6m4-4l-4 4 4 4" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"/>,
    arrowR:  <path d="M8 12h10m-4-4l4 4-4 4" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"/>,
    chevR:   <path d="M9 6l6 6-6 6" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"/>,
    chevL:   <path d="M15 6l-6 6 6 6" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"/>,
    menu:    <path d="M4 7h16M4 12h16M4 17h16" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/>,
    close:   <path d="M6 6l12 12M18 6L6 18" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round"/>,
    check:   <path d="M5 12l5 5L20 7" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>,
    bolt:    <path d="M13 2L4 14h7l-2 8 9-12h-7l2-8z" fill="currentColor"/>,
    shield:  <path d="M12 2l8 4v6c0 5-3.5 9-8 10-4.5-1-8-5-8-10V6l8-4z" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"/>,
    clock:   <><circle cx="12" cy="12" r="9" fill="none" stroke="currentColor" strokeWidth="1.6"/><path d="M12 7v5l3 2" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></>,
    star:    <path d="M12 2l3 7h7l-5.5 4.5L18 21l-6-4-6 4 1.5-7.5L2 9h7z" fill="currentColor"/>,
    plus:    <path d="M12 5v14M5 12h14" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/>,
    minus:   <path d="M5 12h14" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/>,
    trash:   <><path d="M4 7h16M9 7V4h6v3M6 7l1 13h10l1-13" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></>,
    fb:      <path d="M14 6h3V2h-3a4 4 0 00-4 4v3H7v4h3v9h4v-9h3l1-4h-4V6.5c0-.3.2-.5.5-.5h.5z" fill="currentColor"/>,
    wa:      <path d="M12 2a10 10 0 00-8.6 15L2 22l5.2-1.4A10 10 0 1012 2zm5.2 14c-.2.6-1.2 1.2-1.7 1.3-.4.1-1 .1-1.6-.1a14 14 0 01-3.8-1.7 11 11 0 01-3-3.7c-.6-1-.7-1.9-.6-2.5.1-.5.6-1 .9-1.2.3-.2.6-.3.8-.3h.6c.2 0 .4-.1.7.5l1 2.4c.1.2 0 .4-.1.6l-.4.5c-.1.1-.3.3-.1.6.4.7 1.1 1.6 1.7 2.1.7.6 1.4 1 2.1 1.3.3.1.5.1.7-.1l.7-.9c.2-.3.4-.2.7-.1l1.9 1c.3.1.5.2.5.4.1.2.1.7-.1 1z" fill="currentColor"/>,
    home:    <path d="M4 12L12 4l8 8M6 10v10h4v-6h4v6h4V10" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"/>,
    box:     <><path d="M3 7l9-4 9 4-9 4-9-4z" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"/><path d="M3 7v10l9 4 9-4V7" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"/></>,
    out:     <path d="M15 3h6v6m0-6L10 14M14 14v6H4V10h6" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>,
    grid:    <><rect x="3" y="3" width="7" height="7" fill="none" stroke="currentColor" strokeWidth="1.6"/><rect x="14" y="3" width="7" height="7" fill="none" stroke="currentColor" strokeWidth="1.6"/><rect x="3" y="14" width="7" height="7" fill="none" stroke="currentColor" strokeWidth="1.6"/><rect x="14" y="14" width="7" height="7" fill="none" stroke="currentColor" strokeWidth="1.6"/></>,
    heart:   <path d="M12 21s-7-4.5-9.5-9C.5 7.5 4 4 7.5 5.5 9 6 11 7 12 9c1-2 3-3 4.5-3.5C20 4 23.5 7.5 21.5 12c-2.5 4.5-9.5 9-9.5 9z" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"/>,
    sparkle: <path d="M12 3l1.5 4.5L18 9l-4.5 1.5L12 15l-1.5-4.5L6 9l4.5-1.5L12 3zm7 8l.7 2 2 .7-2 .7-.7 2-.7-2-2-.7 2-.7.7-2zM5 14l.7 2 2 .7-2 .7L5 19l-.7-1.6-2-.7 2-.7L5 14z" fill="currentColor"/>,
    logout:  <path d="M9 21H5a2 2 0 01-2-2V5a2 2 0 012-2h4M16 17l5-5-5-5M21 12H9" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>,
    instapay:<path d="M3 7l9 5 9-5M3 7v10h18V7M3 7l9-4 9 4" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"/>,
    wallet:  <path d="M3 7v12a1 1 0 001 1h16a1 1 0 001-1v-9a1 1 0 00-1-1H4a1 1 0 01-1-1V5a1 1 0 011-1h13M17 14h2" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round" strokeLinecap="round"/>,
  };
  return (
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none" {...rest}>
      {paths[name] || null}
    </svg>
  );
};

// === Brand visual (the thumbnail) ===
const BrandVisual = ({ brand, color, glyph, size = 'md' }) => {
  // Stylized brand badge — colored bg + initial mark
  const bgStyle = {
    background: `linear-gradient(135deg, ${color}22, ${color}11)`,
    width: '100%', height: '100%',
    position: 'relative', overflow: 'hidden',
  };
  // Pattern: subtle scattered glyphs
  return (
    <div style={bgStyle}>
      <div style={{
        position: 'absolute', inset: 0,
        background: `radial-gradient(80% 60% at 50% 50%, ${color}33, transparent 70%)`
      }} />
      <div style={{
        position: 'absolute', top: '50%', left: '50%',
        transform: 'translate(-50%, -50%)',
        zIndex: 2,
      }}>
        <div className="brand-badge" style={{
          width: size === 'lg' ? 120 : 64,
          height: size === 'lg' ? 120 : 64,
          borderRadius: size === 'lg' ? 28 : 16,
          background: color,
          display: 'grid', placeItems: 'center',
          boxShadow: `0 12px 40px ${color}66, inset 0 2px 0 rgba(255,255,255,0.15)`,
          color: 'white', fontWeight: 800,
          fontFamily: 'Inter, sans-serif',
          fontSize: size === 'lg' ? 42 : 22,
          letterSpacing: '-0.02em',
          textAlign: 'center', lineHeight: 1,
          padding: 8,
        }}>
          {window.BRAND_LOGOS && window.BRAND_LOGOS[brand]
            ? <div style={{ width: size === 'lg' ? '55%' : '55%', height: size === 'lg' ? '55%' : '55%', display:'flex', alignItems:'center', justifyContent:'center' }}>
                {React.cloneElement(window.BRAND_LOGOS[brand], { style: { width:'100%', height:'100%' } })}
              </div>
            : glyph}
        </div>
      </div>
      {/* Brand name watermark at bottom */}
      <div className="brand-watermark" style={{
        position: 'absolute', bottom: size === 'lg' ? 12 : 6, right: 0, left: 0,
        textAlign: 'center', zIndex: 2,
        fontSize: size === 'lg' ? 18 : 10,
        fontWeight: 700, color: 'white',
        fontFamily: 'Inter, sans-serif',
        letterSpacing: '0.02em',
        opacity: 0.85,
        textShadow: '0 2px 8px rgba(0,0,0,0.6)',
        overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
        padding: '0 6px',
      }}>
        {brand}
      </div>
    </div>
  );
};

// === Compact thumb (for cart/summary) ===
const ThumbSm = ({ brand, color, glyph, size = 56 }) => (
  <div className="thumb-sm" style={{
    width: size, height: size,
    borderRadius: size > 40 ? 12 : 10,
    background: `linear-gradient(135deg, ${color}, ${color}aa)`,
    fontSize: size > 50 ? 20 : 14,
    display: 'grid', placeItems: 'center', flexShrink: 0,
    fontFamily: 'var(--font-en)', fontWeight: 800, color: 'white',
  }}>
    {window.BRAND_LOGOS && window.BRAND_LOGOS[brand]
      ? <div style={{ width: '55%', height: '55%', color:'white', display:'flex', alignItems:'center', justifyContent:'center' }}>
          {React.cloneElement(window.BRAND_LOGOS[brand], { style: { width:'100%', height:'100%' } })}
        </div>
      : glyph}
  </div>
);

// === Format EGP price ===
const fmtPrice = (n) => {
  if (n == null || isNaN(n)) return null;
  return new Intl.NumberFormat('en-US').format(n);
};

// === Localize billing label ===
const billingAr = {
  'Monthly': 'شهري',
  'Annual': 'سنوي',
  'Annual equivalent': 'سنوي (مكافئ شهري)',
  'Annual equivalent monthly': 'سنوي (شهري)',
  'Annual subscription': 'اشتراك سنوي',
  'Top-up': 'شحن',
  'Gift card': 'بطاقة هدية',
  'بطاقة هدية': 'Gift Card',
  'Monthly/Annual': 'شهري / سنوي',
  'Custom': 'مخصص',
};
const billingEn = Object.fromEntries(Object.entries(billingAr).map(([k, v]) => [v, k]));
const tBilling = (b, lang) => {
  if (lang === 'en') return billingEn[b] || b || '';
  return billingAr[b] || b || '';
};

// === WhatsApp buy helper — opens WA with prefilled order message ===
const WA_NUMBER = '201551724428';
const WA_LINK = `https://wa.me/${WA_NUMBER}`;
const CART_ITEM_LIMIT = 2;

const cartItemCount = (items = []) => {
  return (Array.isArray(items) ? items : []).reduce((sum, item) => {
    const qty = Math.max(0, Number(item?.qty) || 0);
    return sum + qty;
  }, 0);
};

const clampCartItems = (items = [], limit = CART_ITEM_LIMIT) => {
  const out = [];
  let remaining = limit;
  (Array.isArray(items) ? items : []).forEach((item) => {
    if (!item || remaining <= 0) return;
    const qty = Math.max(1, Number(item.qty) || 1);
    const nextQty = Math.min(qty, remaining);
    out.push({ ...item, qty: nextQty });
    remaining -= nextQty;
  });
  return out;
};

const cartLimitMessage = (lang = 'ar') => {
  return lang === 'en'
    ? `Cart limit is ${CART_ITEM_LIMIT} plans only.`
    : '\u0627\u0644\u0643\u0627\u0631\u062a \u064a\u0627\u062e\u062f \u0628\u0627\u0642\u062a\u064a\u0646 \u0628\u0633.';
};

// Translate plan names to clear Arabic for the WA message
const planArabic = (plan) => {
  const map = {
    'Go': 'ChatGPT Go',
    'Plus (Lower Limit)': 'مشترك - حد استخدام أقل',
    'Plus (Higher Limit)': 'مشترك - حد استخدام أعلى',
    'Plus Private': 'خاص',
    'Pro 5x': 'برو 5x (5 أضعاف الاستخدام)',
    'Pro 20x': 'برو 20x (20 ضعف الاستخدام)',
  };
  return map[plan] || plan;
};

const displayPlanName = (productOrPlan, lang = 'ar', brand = '') => {
  const product = productOrPlan && typeof productOrPlan === 'object' ? productOrPlan : null;
  const plan = String(product ? product.plan : productOrPlan || '');
  const productBrand = product ? product.brand : brand;
  const t = (ar, en) => lang === 'en' ? en : ar;
  if (productBrand === 'ChatGPT') {
    if (/Plus Shared/i.test(plan)) return t('بلس مشترك', 'Plus Shared');
    if (/Plus Private|Private/i.test(plan)) return t('بلس خاص', 'Plus Private');
  }
  return plan;
};

const waDurationLine = (lang = 'ar', isCart = false) => {
  if (lang === 'en') {
    return isCart ? '• Subscription duration: 1 month each' : '• Subscription duration: 1 month';
  }
  return isCart ? '• مدة كل اشتراك: شهر' : '• مدة الاشتراك: شهر';
};

const buildWaUrl = (product, lang = 'ar') => {
  const planLabel = displayPlanName(product, lang);
  const durationLine = waDurationLine(lang);
  const msg = lang === 'en'
    ? `Hello, I'd like to start this 1-month subscription:\n\n• Brand: ${product.brand}\n• Plan: ${planLabel}\n${durationLine}\n\nPlease send me the price and payment steps so I can start activation. Thanks!`
    : `السلام عليكم، حابب أبدأ الاشتراك ده لمدة شهر:\n\n• البراند: ${product.brand}\n• الباقة: ${planLabel}\n${durationLine}\n\nابعتلي السعر وخطوات الدفع عشان أبدأ التفعيل. شكراً.`;
  return `https://wa.me/${WA_NUMBER}?text=${encodeURIComponent(msg)}`;
};

const buildCartWaUrl = (cart, lang = 'ar') => {
  const itemsList = cart.map(it => {
    const planLabel = displayPlanName(it, lang);
    return `• ${it.qty}x ${it.brand} — ${planLabel}`;
  }).join('\n');

  const durationLine = waDurationLine(lang, true);
  const msg = lang === 'en'
    ? `Hello, I'd like to start these 1-month subscriptions:\n\n${itemsList}\n${durationLine}\n\nPlease send me the total price and payment steps so I can start activation. Thanks!`
    : `السلام عليكم، حابب أبدأ الاشتراكات دي لمدة شهر:\n\n${itemsList}\n${durationLine}\n\nابعتلي الإجمالي وخطوات الدفع عشان أبدأ التفعيل. شكراً.`;
  
  return `https://wa.me/${WA_NUMBER}?text=${encodeURIComponent(msg)}`;
};

const formatDurationParts = (ms) => {
  const totalMinutes = Math.max(1, Math.ceil(Number(ms || 0) / 60000));
  return {
    hours: Math.floor(totalMinutes / 60),
    minutes: totalMinutes % 60
  };
};

const whatsappCooldownMessage = (retryAfterMs, lang = 'ar') => {
  const { hours, minutes } = formatDurationParts(retryAfterMs);
  const timeText = lang === 'en'
    ? [hours ? `${hours}h` : '', minutes ? `${minutes}m` : ''].filter(Boolean).join(' ')
    : [hours ? `${hours} ساعة` : '', minutes ? `${minutes} دقيقة` : ''].filter(Boolean).join(' و ');
  return lang === 'en'
    ? `WhatsApp is limited for this visitor. Try again in ${timeText || 'a few minutes'}, or leave your details and we will contact you.`
    : `فتح واتساب محدود للزائر ده. حاول تاني بعد ${timeText || 'دقائق قليلة'}، أو سيب بياناتك وهنكلمك.`;
};

const whatsappIntentBody = (props = {}) => {
  const route = analyticsRoute();
  return {
    sessionId: analyticsSessionId(),
    route,
    path: window.location.pathname || '/',
    lang: document.documentElement.lang || 'ar',
    referrer: analyticsReferrer(),
    device: analyticsDevice(),
    browser: analyticsBrowser(),
    props,
    userAgent: navigator.userAgent || ''
  };
};

const openWhatsAppUrl = (url, targetWindow = null) => {
  if (targetWindow && !targetWindow.closed) {
    try { targetWindow.opener = null; } catch (e) {}
    targetWindow.location.href = url;
    return;
  }
  const a = document.createElement('a');
  a.href = url;
  a.target = '_blank';
  a.rel = 'noopener noreferrer';
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
};

const notifyWhatsAppBlocked = (message, retryAfterMs) => {
  const event = new CustomEvent('aisubs:whatsapp-blocked', {
    detail: { message, retryAfterMs }
  });
  window.dispatchEvent(event);
};

const guardWhatsAppOpen = async (event, url, lang = 'ar', props = {}) => {
  if (event) {
    event.preventDefault();
  }
  let targetWindow = null;
  try {
    targetWindow = window.open('', '_blank');
  } catch (e) {}

  try {
    const res = await fetch('/api/whatsapp-intent', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(whatsappIntentBody(props))
    });
    const data = await res.json().catch(() => ({}));
    if (res.status === 429 || data.allowed === false) {
      if (targetWindow && !targetWindow.closed) targetWindow.close();
      const retryAfterMs = data.retryAfterMs || 0;
      notifyWhatsAppBlocked(whatsappCooldownMessage(retryAfterMs, lang), retryAfterMs);
      return false;
    }
    if (!res.ok) throw new Error(data.error || 'WhatsApp intent check failed');
    openWhatsAppUrl(url, targetWindow);
    return true;
  } catch (err) {
    // Fail open so a temporary analytics outage does not block a real buyer.
    trackAnalytics('whatsapp_click', props);
    openWhatsAppUrl(url, targetWindow);
    return true;
  }
};

const buyOnWhatsApp = (product, lang = 'ar') => {
  const url = buildWaUrl(product, lang);
  guardWhatsAppOpen(null, url, lang, {
    brand: product.brand,
    plan: product.plan,
    category: product.category,
    source: 'buy_helper'
  });
};

const buyOnWhatsAppDirect = (product, lang = 'ar') => {
  const a = document.createElement('a');
  a.href = buildWaUrl(product, lang);
  a.target = '_blank';
  a.rel = 'noopener noreferrer';
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
};

// Arabic search aliases — brands stay English in UI, but searchable in Arabic
const BRAND_AR_ALIASES = {
  'ChatGPT': 'شات جي بي تي شات جبت',
  'Claude': 'كلود',
  'Gemini': 'جيميني جمناي',
  'Perplexity': 'بربلكستي',
  'Midjourney': 'ميدجورني',
  'GitHub Copilot': 'جيت هاب كوبايلوت',
  'Cursor': 'كيرسور',
  'Windsurf': 'ويندسيرف',
  'ElevenLabs': 'ايلفن لابز',
  'Manus AI': 'مانوس',
  'Netflix': 'نتفلكس نتفليكس',
  'Spotify': 'سبوتيفاي سبوتفاي',
  'Disney+': 'ديزني بلس',
  'YouTube Premium': 'يوتيوب بريميوم',
  'Shahid VIP': 'شاهد فيب',
  'Crunchyroll': 'كرانشي رول',
  'Apple Music': 'ابل ميوزك',
  'Apple TV+': 'ابل تي في',
  'Canva': 'كانفا',
  'Adobe Creative Cloud': 'ادوبي كريتيف',
  'Figma': 'فيجما',
  'Freepik': 'فريبيك',
  'Envato Elements': 'انفاتو',
  'PlayStation Plus': 'بلايستيشن بلس',
  'Xbox Game Pass': 'اكس بوكس جيم باس',
  'EA Play': 'اي ايه بلاي',
  'Nintendo Online': 'ننتندو',
  'JetBrains': 'جيت براينز',
  'Replit': 'ربلت',
  'JetBrains AI': 'جيت براينز',
  'Gemini Code Assist': 'جيميني كود',
  'iTunes': 'ايتونز اي تيونز',
  'Google Play': 'جوجل بلاي',
  'NordVPN': 'نورد في بي ان',
  'ExpressVPN': 'اكسبريس في بي ان',
  'Grammarly': 'جرامرلي',
  'Z AI': 'زي ايه اي glm جي ال ام',
  'Notion': 'نوشن',
  'Zoom': 'زووم',
  'Duolingo': 'ديولينجو',
  'LinkedIn Premium': 'لينكد ان بريميوم',
  'iCloud+': 'اي كلاود بلس',
  'CapCut': 'كاب كات',
  'Leonardo.AI': 'ليوناردو',
  'Kling AI': 'كلينج',
  'Runway': 'رن واي',
  'Higgsfield': 'هيجزفيلد',
  'Microsoft Copilot': 'مايكروسوفت كوبايلوت',
  'Grok': 'جروك سوبر جروك',
  'Character.AI': 'كاراكتر',
  'Poe': 'بو',
  'OSN+': 'او اس ان',
  'WATCH IT': 'واتش ات',
  'Amazon Prime Egypt': 'امازون برايم',
  'TOD': 'تود',
  'beIN': 'بي ان',
  'StarzPlay': 'ستارز بلاي',
  'Anghami': 'انغامي',
  'HiTV': 'هاي تي في',
  'PUBG MOBILE': 'ببجي',
  'Free Fire': 'فري فاير',
  'Mobile Legends': 'موبايل ليجندز',
  'Valorant': 'فالورانت',
  'PlayStation': 'بلايستيشن',
  'Steam': 'ستيم',
  'Roblox': 'روبلوكس',
  'Xbox': 'اكس بوكس',
  'EA SPORTS FC Mobile': 'اي ايه سبورتس',
  'Tabnine': 'تاب ناين',
};

const BEST_SELLERS = ['ChatGPT','Netflix','Claude','Spotify','Canva'];
const NEW_BRANDS = ['Cursor','Windsurf','ElevenLabs','Manus AI','Z AI'];
const POPULAR_BRANDS = ['Gemini','Perplexity','Midjourney','GitHub Copilot'];

const getProductTag = (product, lang) => {
  const t = (ar, en) => lang === 'en' ? en : ar;
  if (BEST_SELLERS.includes(product.brand)) return { cls: 'best-seller', label: t('الأكثر طلباً', 'Best Seller') };
  if (NEW_BRANDS.includes(product.brand)) return { cls: 'new-tag', label: t('جديد', 'New') };
  if (POPULAR_BRANDS.includes(product.brand)) return { cls: 'popular', label: t('رائج', 'Popular') };
  return null;
};

const ProductCard = ({ product, lang, onClick, onAdd }) => {
  const buyLabel = lang === 'en' ? 'Order (WhatsApp)' : 'طلب (واتساب)';
  const addLabel = lang === 'en' ? 'Add' : 'أضف';
  const tag = getProductTag(product, lang);
  const planLabel = displayPlanName(product, lang);

  return (
    <div className="product-card" onClick={onClick}>
      <div className="thumb">
        {tag && <span className={`product-tag ${tag.cls}`}>{tag.label}</span>}
        <BrandVisual brand={product.brand} color={product.color} glyph={product.glyph} />
      </div>
      <div className="body">
        <div className="brand-name">{product.brand}</div>
        <div className="plan-name">{planLabel}</div>
        <div className="billing">{tBilling(product.billing, lang)}</div>
        <div className="card-foot" style={{display:'flex', gap:8, marginTop:'auto', paddingTop:12}}>
          <button className="btn btn-ghost" 
            style={{flex:1, padding:'10px 0', justifyContent:'center', border:'1px solid var(--line-2)'}}
            onClick={(e) => {
              e.stopPropagation();
              if (onAdd) {
                const added = onAdd(product);
                if (added !== false) flyToCart(e, product);
              } else if (onClick) {
                onClick();
              }
            }}>
            <Icon name="plus" size={14}/>
            {addLabel}
          </button>
          <a className="btn-buy" href={buildWaUrl(product, lang)} target="_blank" rel="noopener noreferrer"
            style={{flex:2, justifyContent:'center', padding:'10px 0', background:'#25D366', color:'white', textDecoration:'none', display:'inline-flex', alignItems:'center', gap:6, borderRadius:8, fontWeight:700}}
            onClick={(e) => {
              e.stopPropagation();
              guardWhatsAppOpen(e, buildWaUrl(product, lang), lang, { brand: product.brand, plan: product.plan, category: product.category, source: 'product_card' });
            }}>
            <Icon name="wa" size={14}/>
            {buyLabel}
          </a>
        </div>
      </div>
    </div>
  );
};

// === Fly-to-cart animation ===
const flyToCart = (e, product) => {
  const btn = e.currentTarget;
  const srcRect = btn.getBoundingClientRect();
  const cartBtn = document.querySelector('.header-actions .icon-btn:last-child');
  if (!cartBtn) return;
  const destRect = cartBtn.getBoundingClientRect();

  const flyer = document.createElement('div');
  flyer.className = 'fly-item';
  flyer.textContent = product.glyph || product.brand[0];
  Object.assign(flyer.style, {
    position: 'fixed',
    zIndex: 9999,
    width: '48px',
    height: '48px',
    borderRadius: '14px',
    background: product.color || 'var(--gold)',
    color: 'white',
    fontWeight: '800',
    fontFamily: 'Inter, sans-serif',
    fontSize: '18px',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    boxShadow: `0 8px 24px ${product.color}88`,
    pointerEvents: 'none',
    left: srcRect.left + srcRect.width / 2 - 24 + 'px',
    top: srcRect.top + srcRect.height / 2 - 24 + 'px',
    transition: 'all 0.65s cubic-bezier(0.2, 0.8, 0.2, 1)',
    opacity: '1',
    transform: 'scale(1)',
  });
  document.body.appendChild(flyer);

  requestAnimationFrame(() => {
    requestAnimationFrame(() => {
      Object.assign(flyer.style, {
        left: destRect.left + destRect.width / 2 - 12 + 'px',
        top: destRect.top + destRect.height / 2 - 12 + 'px',
        width: '24px',
        height: '24px',
        borderRadius: '50%',
        fontSize: '10px',
        opacity: '0.3',
        transform: 'scale(0.4)',
      });
    });
  });

  flyer.addEventListener('transitionend', () => {
    flyer.remove();
    cartBtn.classList.add('cart-bounce');
    const badge = cartBtn.querySelector('.badge');
    if (badge) badge.classList.add('badge-pop');
    setTimeout(() => {
      cartBtn.classList.remove('cart-bounce');
      if (badge) badge.classList.remove('badge-pop');
    }, 400);
  }, { once: true });
};

// Expose to other Babel scripts
Object.assign(window, {
  Icon, BrandVisual, ThumbSm, fmtPrice, tBilling, billingAr, displayPlanName, ProductCard, buyOnWhatsApp, buyOnWhatsAppDirect, buildWaUrl, buildCartWaUrl, guardWhatsAppOpen, WA_NUMBER, WA_LINK, CART_ITEM_LIMIT, cartItemCount, clampCartItems, cartLimitMessage, flyToCart, BRAND_AR_ALIASES, analyticsSessionId, analyticsDevice, analyticsBrowser, analyticsReferrer, analyticsRoute, trackAnalytics,
});
