'use client';

import React, { useState, useEffect, useMemo, useRef } from 'react';
import Link from 'next/link';
import { usePathname, useSearchParams, useRouter } from 'next/navigation';
import AppLayout from '@/components/layout/AppLayout';
import { MetaPixelRecord } from '@/types';
import { APP_CONFIG } from '@/config/app';
import { META_CONFIG } from '@/config/meta';
import { useBranding } from '@/context/BrandingContext';
import { normalizeAssetUrl, apiUrl } from '@/lib/utils/asset';
import AppLogo from '@/components/common/AppLogo';
import { getHelpArticle } from '@/config/helpArticles';
import { showToast } from '@/lib/shopify/appBridge';
import { scrollToFirstError, useFormErrorScroll } from '@/lib/utils/scroll-to-error';

function getCleanPixelName(rawName?: string | null, pixelId?: string): string {
  if (!rawName) return pixelId ? `Pixel ${pixelId}` : '';
  const trimmed = rawName.trim();
  if (trimmed.includes(' - ')) {
    const parts = trimmed.split(' - ');
    // If the first part is numeric pixel ID (e.g. "1273838518231551 - Dhaval's Market Data"), return descriptive name
    if (/^\d+$/.test(parts[0].trim())) {
      return parts.slice(1).join(' - ').trim();
    }
    return parts[1].trim();
  }
  return trimmed;
}

export default function MetaCommercePixelApp(props?: any) {
  const initialMode = props?.initialMode as ('onboarding' | 'manager' | undefined);
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const { branding } = useBranding();

  const isPixelRoute = initialMode === 'manager' || (pathname ? (pathname.endsWith('/pixel') || pathname.includes('/pixel')) : false);
  const isForceOnboarding = pathname?.startsWith('/onboarding') || searchParams?.get('onboarding') === 'true';
  const isRootRoute = initialMode === 'onboarding' || (!isPixelRoute && (pathname === '/' || pathname === '/meta-connector' || pathname === '/meta-connector/' || !pathname));

  const [currentShop, setCurrentShop] = useState<string>(() => {
    if (typeof window !== 'undefined') {
      const sp = new URLSearchParams(window.location.search);
      const urlShop = sp.get('shop') || sp.get('shopify_domain');
      if (urlShop) {
        try { localStorage.setItem('meta_connector_shop', urlShop); } catch {}
        return urlShop;
      }
      try {
        const cached = localStorage.getItem('meta_connector_shop');
        if (cached) return cached;
      } catch {}
      try {
        const refMatch = document.referrer?.match(/admin\.shopify\.com\/store\/([^/?#]+)/i);
        if (refMatch && refMatch[1]) {
          const derived = `${refMatch[1].toLowerCase()}.myshopify.com`;
          localStorage.setItem('meta_connector_shop', derived);
          return derived;
        }
      } catch {}
    }
    return '';
  });

  useEffect(() => {
    let urlShop = searchParams?.get('shop') || searchParams?.get('shopify_domain');
    if (!urlShop && typeof window !== 'undefined') {
      const refMatch = document.referrer?.match(/admin\.shopify\.com\/store\/([^/?#]+)/i);
      if (refMatch && refMatch[1]) {
        urlShop = `${refMatch[1].toLowerCase()}.myshopify.com`;
      }
    }
    if (urlShop) {
      setCurrentShop(urlShop);
      if (typeof window !== 'undefined') {
        try { localStorage.setItem('meta_connector_shop', urlShop); } catch {}
      }
    }
  }, [searchParams]);

  const [viewMode, setViewMode] = useState<'onboarding' | 'manager'>(() => {
    if (initialMode) return initialMode;
    if (isPixelRoute) return 'manager';
    return 'onboarding';
  });

  useEffect(() => {
    if (initialMode) {
      setViewMode(initialMode);
      return;
    }
    if (pathname?.includes('/pixel')) {
      setViewMode('manager');
    } else if (pathname === '/' || pathname === '/meta-connector' || pathname === '/meta-connector/') {
      setViewMode('onboarding');
    }
  }, [pathname, initialMode]);

  const navigateToPixelManager = () => {
    const currentSearch = typeof window !== 'undefined' && window.location.search ? window.location.search : '';
    router.push(`/pixel${currentSearch}`);
    setViewMode('manager');
  };

  const [pixels, setPixels] = useState<MetaPixelRecord[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  // Search & Pagination in Manager view
  const [searchQuery, setSearchQuery] = useState('');
  const [rowsPerPage, setRowsPerPage] = useState<number>(5);
  const [currentPage, setCurrentPage] = useState<number>(1);

  // Onboarding Stepper State (Step 1, 2, 3, 4=Congratulations)
  const [currentStep, setCurrentStep] = useState<1 | 2 | 3 | 4>(1);
  const [inputTab, setInputTab] = useState<'auto' | 'manual'>('auto');

  // Facebook OAuth State
  const [fbConnected, setFbConnected] = useState(false);
  const [showFbAuthModal, setShowFbAuthModal] = useState(false);
  const [fbUser, setFbUser] = useState<{ id?: string; name: string; avatar?: string | null } | null>(null);
  const [avatarLoadError, setAvatarLoadError] = useState(false);

  // Business & Pixel Options for Auto Mode (Strictly Dynamic)
  const [businessAccounts, setBusinessAccounts] = useState<Array<{ id: string; name: string }>>([]);
  const [availablePixels, setAvailablePixels] = useState<Array<{ id: string; name: string }>>([]);

  const [selectedBusiness, setSelectedBusiness] = useState('');
  const [selectedPixelOption, setSelectedPixelOption] = useState('');

  // Form Fields & Dual Input Source Management (Auto vs Manual)
  const [autoPixelName, setAutoPixelName] = useState('');
  const [manualPixelName, setManualPixelName] = useState('');
  const [manualPixelId, setManualPixelId] = useState('');
  const [activeSource, setActiveSource] = useState<'auto' | 'manual'>('auto');
  const [manualNameError, setManualNameError] = useState<string | null>(null);
  const [manualIdError, setManualIdError] = useState<string | null>(null);

  // Confirmation Dialog for Destructive / Overwrite Changes
  const [confirmDialog, setConfirmDialog] = useState<{
    title: string;
    description: string;
    confirmText?: string;
    cancelText?: string;
    isDanger?: boolean;
    onConfirm: () => void;
    onCancel: () => void;
  } | null>(null);

  // Success / Status Toast Notification
  const [toastMessage, setToastMessage] = useState<{
    text: string;
    type?: 'success' | 'info' | 'warning';
  } | null>(null);

  const [accessToken, setAccessToken] = useState('');
  const [autoToken, setAutoToken] = useState('');
  const [autoTokenMasked, setAutoTokenMasked] = useState('');
  const [tokenSource, setTokenSource] = useState<'auto' | 'manual'>('auto');
  const [capiEnabled, setCapiEnabled] = useState(true);
  const [showToken, setShowToken] = useState(false);
  const [testEventCode, setTestEventCode] = useState('');
  const [appEmbedChecked, setAppEmbedChecked] = useState(false);

  // Computed effective token (auto from connected Facebook account or manual entry)
  const effectiveAccessToken = tokenSource === 'auto' ? autoToken : accessToken;

  // App Embed Verification State
  const [isVerifyingEmbed, setIsVerifyingEmbed] = useState(false);
  const [embedVerificationError, setEmbedVerificationError] = useState<string | null>(null);
  const [embedStatus, setEmbedStatus] = useState<'idle' | 'checking' | 'verified' | 'unverified'>('idle');

  // Facebook Access Token Verification State
  const [isVerifyingToken, setIsVerifyingToken] = useState(false);
  const [tokenVerificationError, setTokenVerificationError] = useState<string | null>(null);
  const [tokenVerified, setTokenVerified] = useState(false);
  const [tokenInfo, setTokenInfo] = useState<{ name?: string; id?: string } | null>(null);

  // Edit Modal State
  const [editingPixel, setEditingPixel] = useState<MetaPixelRecord | null>(null);
  const [editName, setEditName] = useState('');
  const [editTarget, setEditTarget] = useState('all');
  const [editCapiToken, setEditCapiToken] = useState('');
  const [editTestCode, setEditTestCode] = useState('');
  const [showEditCapiToken, setShowEditCapiToken] = useState(false);
  const [editCapiVerified, setEditCapiVerified] = useState(false);
  const [editCapiVerifying, setEditCapiVerifying] = useState(false);
  const [editCapiError, setEditCapiError] = useState<string | null>(null);

  // Unified Pixel Modal State (Add & Edit matching media_1793011790523.png & media_1793011824820.png)
  const [showPixelModal, setShowPixelModal] = useState(false);
  const [pixelModalMode, setPixelModalMode] = useState<'add' | 'edit'>('add');
  const [pixelModalTab, setPixelModalTab] = useState<'auto' | 'manual'>('auto');
  const [modalPixelName, setModalPixelName] = useState('');
  const [modalPixelId, setModalPixelId] = useState('');
  const [modalSelectedBusiness, setModalSelectedBusiness] = useState('');
  const [modalSelectedPixel, setModalSelectedPixel] = useState('');
  const [modalTrackingPages, setModalTrackingPages] = useState<'all' | 'selected' | 'excluded'>('all');
  const [modalMarketTargeting, setModalMarketTargeting] = useState<'all' | 'specific'>('all');
  const [modalCapiEnabled, setModalCapiEnabled] = useState(true);
  const [modalAccessToken, setModalAccessToken] = useState('');
  const [modalTestEventCode, setModalTestEventCode] = useState('');
  const [modalError, setModalError] = useState<string | null>(null);
  const [isSavingModalPixel, setIsSavingModalPixel] = useState(false);
  const [appEmbedNoticeDismissed, setAppEmbedNoticeDismissed] = useState(false);

  // Auto-scroll inside modal or page when pixel errors occur
  useFormErrorScroll(modalError);

  // Auto-populate Pixel Name from selected pixel whenever modal is open in Auto input mode
  useEffect(() => {
    if (showPixelModal && pixelModalTab === 'auto' && availablePixels.length > 0) {
      if (!modalSelectedPixel || !availablePixels.some((p) => p.id === modalSelectedPixel)) {
        const first = availablePixels[0];
        setModalSelectedPixel(first.id);
        const clean = getCleanPixelName(first.name, first.id);
        setModalPixelName(clean);
      } else if (!modalPixelName.trim()) {
        const current = availablePixels.find((p) => p.id === modalSelectedPixel);
        if (current) {
          setModalPixelName(getCleanPixelName(current.name, current.id));
        }
      }
    }
  }, [showPixelModal, pixelModalTab, availablePixels, modalSelectedPixel, modalPixelName]);

  // Meta Pixel Verification & Workflow Tracking State
  const [verifyingPixelId, setVerifyingPixelId] = useState<string | null>(null);
  const [pixelVerificationError, setPixelVerificationError] = useState<{ id: string; message: string } | null>(null);

  // Delete Confirmation Modal State
  const [deletingPixel, setDeletingPixel] = useState<MetaPixelRecord | null>(null);

  // Help Modal State
  const [helpModal, setHelpModal] = useState<'pixel_id' | 'access_token' | 'test_code' | null>(null);

  // In-app Knowledge Base Guide Popup Modal State
  const [guideModalSlug, setGuideModalSlug] = useState<string | null>(null);
  const activeGuideArticle = guideModalSlug ? getHelpArticle(guideModalSlug) : null;

  // Verification Diagnostic Modal State
  const [showVerifyModal, setShowVerifyModal] = useState(false);
  const [verifyStep, setVerifyStep] = useState<number>(0);
  const [isVerifying, setIsVerifying] = useState(false);

  // Test Dispatcher State
  const [testEventName, setTestEventName] = useState('Purchase');
  const [testValue, setTestValue] = useState('49.99');
  const [isSendingTest, setIsSendingTest] = useState(false);
  const [testResult, setTestResult] = useState<Record<string, unknown> | null>(null);
  const [copiedId, setCopiedId] = useState<string | null>(null);

  const fetchPixels = async (allowAutoSwitch = true) => {
    try {
      const shopToUse = currentShop || searchParams?.get('shop') || searchParams?.get('shopify_domain') || (typeof window !== 'undefined' ? localStorage.getItem('meta_connector_shop') : '') || '';
      const endpoint = shopToUse ? `/api/pixels?shop=${encodeURIComponent(shopToUse)}` : '/api/pixels';
      const res = await fetch(apiUrl(endpoint));
      const data = await res.json();
      if (data.success && Array.isArray(data.pixels)) {
        setPixels(data.pixels);
        if (allowAutoSwitch) {
          if (isPixelRoute) {
            setViewMode('manager');
          } else if (isRootRoute || isForceOnboarding) {
            setViewMode('onboarding');
          }
        }
      } else if (allowAutoSwitch) {
        if (isPixelRoute) {
          setViewMode('manager');
        } else if (isRootRoute || isForceOnboarding) {
          setViewMode('onboarding');
        }
      }
    } catch (err) {
      console.error('Failed to load pixels:', err);
      if (allowAutoSwitch) {
        if (isPixelRoute) {
          setViewMode('manager');
        } else {
          setViewMode('onboarding');
        }
      }
    } finally {
      setIsLoading(false);
    }
  };

  const fetchMetaAccounts = async (bizId?: string) => {
    try {
      const currentShop = searchParams?.get('shop') || searchParams?.get('shopify_domain');
      const base = bizId
        ? `/api/meta/accounts?businessId=${encodeURIComponent(bizId)}`
        : '/api/meta/accounts';
      const url = currentShop ? `${base}${base.includes('?') ? '&' : '?'}shop=${encodeURIComponent(currentShop)}` : base;
      const res = await fetch(apiUrl(url));
      const data = await res.json();
      if (data.success) {
        if (data.connected) {
          setFbConnected(true);
          setFbUser(data.user || null);
          setAvatarLoadError(false);
          setBusinessAccounts(data.businesses || []);
          setAvailablePixels(data.pixels || []);
          if (!bizId && data.businesses?.[0]?.id) {
            setSelectedBusiness(data.businesses[0].id);
          }
          if (data.pixels && data.pixels.length > 0) {
            setSelectedPixelOption((prev) => {
              const exists = prev && data.pixels.some((x: any) => x.id === prev);
              const targetId = exists ? prev : data.pixels[0].id;
              const chosen = data.pixels.find((x: any) => x.id === targetId) || data.pixels[0];
              const pName = chosen.name.includes(' - ') ? chosen.name.split(' - ')[1] : chosen.name;
              setAutoPixelName((curr) => curr || pName);
              return targetId;
            });
          }
          // Only accept as autoToken if it is NOT an app login token (EAGR) and is a valid CAPI format (starts with EAA)
          if (data.rawToken && data.rawToken.startsWith('EAA') && !data.rawToken.startsWith('EAGR')) {
            setAutoToken(data.rawToken);
            const masked = data.accessTokenMasked || `••••••••••••${data.rawToken.slice(-4)}`;
            setAutoTokenMasked(masked);
            setTokenSource('auto');
            setTokenVerified(false);
            setTokenVerificationError(null);
          } else {
            setAutoToken('');
            setAutoTokenMasked('');
            setTokenSource('manual');
            setTokenVerified(false);
            setTokenVerificationError(null);
            setTokenInfo(null);
          }
        } else {
          // Explicitly clear all Meta account data when disconnected
          setFbConnected(false);
          setFbUser(null);
          setAvatarLoadError(false);
          setBusinessAccounts([]);
          setAvailablePixels([]);
          setSelectedBusiness('');
          setSelectedPixelOption('');
          setAutoPixelName('');
          setAutoToken('');
          setAutoTokenMasked('');
          setTokenSource('manual');
          setTokenVerified(false);
          setTokenVerificationError(null);
          setTokenInfo(null);
          setModalSelectedBusiness('');
          setModalSelectedPixel('');
        }
        return data;
      }
    } catch (err) {
      console.error('Failed to load Meta accounts:', err);
    }
    return null;
  };

  const isHandlingAuthRef = useRef(false);

  const handleMetaAuthSuccess = async () => {
    if (isHandlingAuthRef.current) return;
    isHandlingAuthRef.current = true;
    setTimeout(() => {
      isHandlingAuthRef.current = false;
    }, 4000);

    setShowFbAuthModal(false);
    setFbConnected(true);
    const data = await fetchMetaAccounts();
    await fetchPixels(false);
    if (data?.businesses?.length) {
      setModalSelectedBusiness(data.businesses[0].id);
    }
    if (data?.pixels?.length) {
      setModalSelectedPixel(data.pixels[0].id);
      const chosen = data.pixels[0];
      const pName = chosen.name.includes(' - ') ? chosen.name.split(' - ')[1] : chosen.name;
      setModalPixelName(pName);
    }
    setCurrentStep(2);
  };

  useEffect(() => {
    fetchPixels(true);
    fetchMetaAccounts();
    verifyThemeEmbed(true);

    // 1. Message listener (from window.opener postMessage)
    const handleAuthMessage = (event: MessageEvent) => {
      if (event.data?.type === 'META_AUTH_SUCCESS') {
        handleMetaAuthSuccess();
      }
    };
    window.addEventListener('message', handleAuthMessage);

    // 2. BroadcastChannel listener (works across tabs/windows of same origin even if window.opener is severed)
    let bc: BroadcastChannel | null = null;
    try {
      if (typeof BroadcastChannel !== 'undefined') {
        bc = new BroadcastChannel('meta_auth_channel');
        bc.onmessage = (event) => {
          if (event.data?.type === 'META_AUTH_SUCCESS') {
            handleMetaAuthSuccess();
          }
        };
      }
    } catch {}

    // 3. Storage event listener (cross-window fallback)
    const handleStorageEvent = (event: StorageEvent) => {
      if (event.key === 'meta_auth_success') {
        handleMetaAuthSuccess();
      }
    };
    window.addEventListener('storage', handleStorageEvent);

    return () => {
      window.removeEventListener('message', handleAuthMessage);
      window.removeEventListener('storage', handleStorageEvent);
      if (bc) bc.close();
    };
  }, [searchParams]);

  const openMetaOAuthPopup = () => {
    const width = 650;
    const height = 750;
    const left = window.screenX + (window.outerWidth - width) / 2;
    const top = window.screenY + (window.outerHeight - height) / 2;
    const shopDomain = currentShop || searchParams?.get('shop') || searchParams?.get('shopify_domain') || (typeof window !== 'undefined' ? localStorage.getItem('meta_connector_shop') || '' : '') || '';
    const qs = shopDomain ? `?shop=${encodeURIComponent(shopDomain)}` : '';
    const metaAuthUrl = apiUrl(`/api/auth/meta${qs}`);
    const popup = window.open(
      metaAuthUrl,
      'MetaAuthPopup',
      `width=${width},height=${height},left=${left},top=${top},menubar=no,toolbar=no,location=no,status=no`
    );

    // Polling fallback: if user closes popup manually after completing OAuth, sync accounts and advance to Step 2
    if (popup) {
      const pollTimer = setInterval(() => {
        if (popup.closed) {
          clearInterval(pollTimer);
          fetchMetaAccounts().then((data) => {
            if (data?.connected) {
              handleMetaAuthSuccess();
            }
          });
        }
      }, 1000);
    }
  };

  const handleFbConnect = () => {
    openMetaOAuthPopup();
  };

  // Auto-dismiss toast notifications after 4 seconds and trigger native Shopify App Bridge toast
  useEffect(() => {
    if (toastMessage) {
      showToast(toastMessage.text, toastMessage.type !== 'success');
      const timer = setTimeout(() => setToastMessage(null), 4000);
      return () => clearTimeout(timer);
    }
  }, [toastMessage]);

  // Current values from both sources
  const currentAutoName = autoPixelName.trim();
  const currentAutoId = selectedPixelOption.trim();
  const currentManualName = manualPixelName.trim();
  const currentManualId = manualPixelId.trim();

  // Source Availability
  const hasAuto = fbConnected && Boolean(currentAutoId);
  const hasManual = Boolean(currentManualId || currentManualName);

  // Effective values according to active source
  const effectivePixelName =
    inputTab === 'manual'
      ? currentManualName
      : (currentAutoName || (currentAutoId ? `Pixel ${currentAutoId}` : ''));

  const effectivePixelId =
    inputTab === 'manual'
      ? currentManualId
      : currentAutoId;

  const pixelName = effectivePixelName;

  // Direct Tab Switching
  const switchInputTab = (targetSource: 'auto' | 'manual') => {
    setInputTab(targetSource);
    setActiveSource(targetSource);
    setManualNameError(null);
    setManualIdError(null);
  };

  const handleConfirmFbAuth = async () => {
    if (!accessToken) {
      alert('Please enter a Meta Access Token');
      return;
    }
    try {
      const res = await fetch(apiUrl('/api/meta/connect'), {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          businessId: selectedBusiness,
          pixelId: selectedPixelOption,
          pixelName: effectivePixelName,
          accessToken: accessToken,
        }),
      });
      const data = await res.json();
      if (data.success) {
        setShowFbAuthModal(false);
        setFbConnected(true);
        if (data.user) {
          setFbUser(data.user);
          setAvatarLoadError(false);
        }
        await fetchMetaAccounts();
      } else {
        alert(data.error || 'Failed to connect Meta account');
      }
    } catch (err) {
      console.error(err);
      alert('Network error connecting Meta account');
    }
  };

  const resetMetaState = () => {
    setFbConnected(false);
    setFbUser(null);
    setAvatarLoadError(false);
    setBusinessAccounts([]);
    setAvailablePixels([]);
    setSelectedBusiness('');
    setSelectedPixelOption('');
    setAutoPixelName('');
    setAutoToken('');
    setAutoTokenMasked('');
    setTokenSource('manual');
    setTokenVerified(false);
    setTokenVerificationError(null);
    setTokenInfo(null);
    setModalSelectedBusiness('');
    setModalSelectedPixel('');
    setModalPixelName('');
    setModalAccessToken('');
  };

  const handleFbDisconnect = async () => {
    const doDisconnect = async () => {
      try {
        const shopToUse = currentShop || (typeof window !== 'undefined' ? localStorage.getItem('meta_connector_shop') || '' : '');
        await fetch(apiUrl('/api/meta/connect'), {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ disconnect: true, shopDomain: shopToUse }),
        });
      } catch (err) {
        console.error('Failed to disconnect Facebook:', err);
      }
      resetMetaState();
      setActiveSource('manual');
      setInputTab('manual');
      setToastMessage({
        text: 'Facebook disconnected.',
        type: 'info',
      });
    };

    if (currentAutoId || currentAutoName) {
      setConfirmDialog({
        title: 'Disconnect Facebook Account?',
        description: hasManual
          ? 'Your Facebook account will be disconnected. Your manual pixel data will be retained as the active source.'
          : 'Your Facebook account will be disconnected. Your pixel data from Facebook will be preserved in Manual Input so tracking continues without interruption.',
        confirmText: 'Yes, Disconnect',
        cancelText: 'Keep Connected',
        onConfirm: async () => {
          // Preserve into manual if manual is empty
          if (!manualPixelName.trim() && autoPixelName.trim()) {
            setManualPixelName(autoPixelName.trim());
          }
          if (!manualPixelId.trim() && selectedPixelOption.trim()) {
            setManualPixelId(selectedPixelOption.trim());
          }
          await doDisconnect();
        },
        onCancel: () => {
          // Cancelled: keep connected
        },
      });
      return;
    }

    await doDisconnect();
  };

  const handleSelectBusiness = async (bizId: string) => {
    setSelectedBusiness(bizId);
    await fetchMetaAccounts(bizId);
  };

  const handleNextStep1 = async () => {
    if (inputTab === 'manual') {
      let hasError = false;
      const cleanName = manualPixelName.trim();
      const cleanId = manualPixelId.trim();

      if (!cleanName) {
        setManualNameError('Pixel name is required');
        hasError = true;
      } else if (cleanName.length > 255) {
        setManualNameError('Pixel name cannot exceed 255 characters');
        hasError = true;
      } else {
        setManualNameError(null);
      }

      if (!cleanId) {
        setManualIdError('Pixel ID is required');
        hasError = true;
      } else if (!/^\d+$/.test(cleanId)) {
        setManualIdError('Pixel ID must contain numbers only');
        hasError = true;
      } else if (cleanId.length < 15 || cleanId.length > 16) {
        setManualIdError(`Pixel ID must be 15 or 16 digits (currently ${cleanId.length} digits)`);
        hasError = true;
      } else {
        setManualIdError(null);
      }

      if (hasError) {
        return;
      }

      // Prevent duplicate pixel ID
      const duplicate = pixels.find((p) => p.pixel_id === cleanId);
      if (duplicate) {
        setManualIdError('This pixel is already added to this store.');
        return;
      }

      // Proactively save pixel to database immediately at Step 1 so it is never lost!
      try {
        const ok = await handleSavePixelDirectly(false, {
          id: cleanId,
          name: cleanName,
        });
        if (!ok) {
          return;
        }
      } catch (e) {
        console.error('Auto-save step 1 error:', e);
      }
    } else {
      if (!selectedPixelOption.trim()) {
        alert('Please connect your Facebook account and select a Pixel');
        return;
      }
      try {
        await handleSavePixelDirectly(false);
      } catch (e) {
        console.error('Auto-save step 1 error:', e);
      }
    }

    setCurrentStep(2);
    if (accessToken.trim() && !accessToken.trim().startsWith('EAGR')) {
      verifyMetaToken(accessToken.trim(), true);
    }
  };

  const eventsManagerSettingsUrl = effectivePixelId
    ? `https://eventsmanager.facebook.com/events_manager2/list/dataset/${encodeURIComponent(effectivePixelId)}/settings${
        selectedBusiness ? `?business_id=${encodeURIComponent(selectedBusiness)}` : ''
      }`
    : 'https://business.facebook.com/events_manager2/';

  const cleanStore = currentShop
    ? currentShop.replace('.myshopify.com', '').replace(/^https?:\/\//, '').replace(/\/.*$/, '').trim()
    : '';

  const themeEditorUrl = cleanStore
    ? `https://admin.shopify.com/store/${cleanStore}/themes/current/editor?context=apps&activateAppId=d6d73fa2d424638f91826f822d89c51f/pixel_embed`
    : 'https://admin.shopify.com/themes/current/editor?context=apps&activateAppId=d6d73fa2d424638f91826f822d89c51f/pixel_embed';

  const handleOpenThemeEditor = (e?: React.MouseEvent) => {
    if (e) e.preventDefault();
    if (typeof window !== 'undefined') {
      const shopifyObj = (window as any).shopify;
      if (shopifyObj && typeof shopifyObj.open === 'function') {
        shopifyObj.open(themeEditorUrl, '_blank');
        return;
      }
      window.open(themeEditorUrl, '_blank', 'noopener,noreferrer');
    }
  };

  // Verify theme app embed using Shopify App Bridge v4 and Server-Side probe
  const verifyThemeEmbed = async (silent = false): Promise<boolean> => {
    setIsVerifyingEmbed(true);
    setEmbedStatus('checking');
    if (!silent) setEmbedVerificationError(null);

    try {
      // 1. Try Shopify App Bridge direct extension check in Shopify Admin iframe
      if (typeof window !== 'undefined') {
        const shopifyObj = (window as any).shopify;
        if (shopifyObj) {
          try {
            let extensions: any = null;
            if (typeof shopifyObj.app?.extensions === 'function') {
              extensions = await shopifyObj.app.extensions();
            } else if (typeof shopifyObj.extensions === 'function') {
              extensions = await shopifyObj.extensions();
            }

            if (Array.isArray(extensions) && extensions.length > 0) {
              for (const ext of extensions) {
                const isOurExtension =
                  ext.type === 'theme_app_extension' ||
                  ext.handle === 'meta-commerce-pixel-con' ||
                  ext.handle === 'meta-sync-pixel-connector-1' ||
                  ext.id === '35913d5a-5d1f-1f3f-513a-29faaf412c6711065daf';

                if (isOurExtension && Array.isArray(ext.activations)) {
                  const pixelBlock =
                    ext.activations.find(
                      (a: any) =>
                        a.name === 'pixel_embed' ||
                        String(a.name || '').toLowerCase().includes('pixel') ||
                        a.target === 'body'
                    ) || ext.activations[0];

                  if (pixelBlock) {
                    if (pixelBlock.status === 'active') {
                      setAppEmbedChecked(true);
                      setEmbedStatus('verified');
                      setEmbedVerificationError(null);
                      setIsVerifyingEmbed(false);
                      return true;
                    } else {
                      setAppEmbedChecked(false);
                      setEmbedStatus('unverified');
                      if (!silent) {
                        setEmbedVerificationError(
                          "The 'Meta Pixel & CAPI Tracker' App Embed is currently turned OFF in your theme. Please open Theme Editor, toggle it ON in App Embeds, click Save, and verify again."
                        );
                      }
                      setIsVerifyingEmbed(false);
                      return false;
                    }
                  }
                }
              }
            }
          } catch (bridgeErr) {
            console.warn('[AppBridge] Extension check warning:', bridgeErr);
          }
        }
      }

      // 2. Call backend verification endpoint (/api/shopify/verify-app-embed)
      const res = await fetch(
        apiUrl(`/api/shopify/verify-app-embed?shop=${encodeURIComponent(currentShop)}`),
        {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ shop: currentShop }),
        }
      );

      const data = await res.json();
      if (data.verified) {
        setAppEmbedChecked(true);
        setEmbedStatus('verified');
        setEmbedVerificationError(null);
        setIsVerifyingEmbed(false);
        return true;
      } else {
        setAppEmbedChecked(false);
        setEmbedStatus('unverified');
        if (!silent) {
          setEmbedVerificationError(
            data.message ||
              "Theme App Embed was not detected on your live theme. Please open Theme Editor, turn ON 'Meta Pixel & CAPI Tracker' in the left App Embeds sidebar, click Save, and verify again."
          );
        }
        setIsVerifyingEmbed(false);
        return false;
      }
    } catch (err) {
      console.error('Embed verification failed:', err);
      setAppEmbedChecked(false);
      setEmbedStatus('unverified');
      if (!silent) {
        setEmbedVerificationError(
          'Could not verify theme app embed status. Please verify your internet connection and try again.'
        );
      }
      setIsVerifyingEmbed(false);
      return false;
    }
  };

  const handleCheckboxToggle = async (checked: boolean) => {
    if (!checked) {
      setAppEmbedChecked(false);
      setEmbedStatus('unverified');
      return;
    }
    const isVerified = await verifyThemeEmbed(false);
    if (!isVerified) {
      setAppEmbedChecked(false);
    }
  };

  const handleAutoFillConnectedToken = () => {
    if (autoToken) {
      setTokenSource('auto');
      setAccessToken('');
      setTokenVerified(true);
      setTokenVerificationError(null);
      setToastMessage({
        text: 'Conversions API access token automatically filled from connected Facebook account.',
        type: 'success',
      });
    }
  };

  // Verify Facebook Access Token with Meta Graph API
  const verifyMetaToken = async (tokenToVerify?: string, silent = false): Promise<boolean> => {
    const isAuto = tokenToVerify === undefined ? (tokenSource === 'auto') : (tokenToVerify === autoToken);
    const token = (tokenToVerify !== undefined ? tokenToVerify : (tokenSource === 'auto' ? autoToken : accessToken)).trim();
    if (!token) {
      if (!silent) {
        setTokenVerificationError('Please enter or paste your Conversions API access token.');
      }
      setTokenVerified(false);
      return false;
    }

    if (token.startsWith('EAGR')) {
      if (!silent) {
        setTokenVerificationError(
          'This looks like a Facebook login token, not a Conversions API token. Please go to Meta Events Manager → Settings → Conversions API and generate a new access token from there.'
        );
      }
      setTokenVerified(false);
      return false;
    }

    setIsVerifyingToken(true);
    if (!silent) setTokenVerificationError(null);

    try {
      const finalPixelId = effectivePixelId;
      const res = await fetch(apiUrl('/api/meta/verify-token'), {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          accessToken: token,
          pixelId: finalPixelId,
          isAutoConnected: isAuto,
          source: isAuto ? 'auto' : 'manual',
          shop: currentShop,
        }),
      });

      const data = await res.json();
      if (data.valid) {
        setTokenVerified(true);
        setTokenVerificationError(null);
        setTokenInfo(data.dataset || data.pixel || data.user || null);
        setIsVerifyingToken(false);
        return true;
      } else {
        setTokenVerified(false);
        setTokenInfo(null);
        if (!silent) {
          setTokenVerificationError(
            data.message || data.error || 'Invalid token — this token doesn\'t have access to your Pixel. Please check it in Meta Events Manager and try again.'
          );
        }
        setIsVerifyingToken(false);
        return false;
      }
    } catch (err) {
      console.error('Failed to verify Meta token:', err);
      setTokenVerified(false);
      if (!silent) {
        setTokenVerificationError('Network error connecting to Meta Graph API. Please try again.');
      }
      setIsVerifyingToken(false);
      return false;
    }
  };

  const handleNextStep2 = async () => {
    if (!capiEnabled) {
      // Save state with CAPI disabled
      try {
        await handleSavePixelDirectly(false);
      } catch (e) {
        console.error('Auto-save step 2 error:', e);
      }
      setCurrentStep(3);
      verifyThemeEmbed(true);
      return;
    }

    const tokenToUse = (tokenSource === 'auto' ? autoToken : accessToken).trim();
    if (tokenToUse) {
      if (tokenToUse.startsWith('EAGR')) {
        setTokenVerificationError(
          'This looks like a Facebook login token, not a Conversions API token. Please go to Meta Events Manager → Settings → Conversions API and generate a new access token from there.'
        );
        return;
      }

      if (!tokenVerified) {
        // Attempt token verification silently
        await verifyMetaToken(tokenToUse, true);
      }
    }
    // If token is empty, just proceed — CAPI is optional

    // Proactively save pixel updates immediately to database at Step 2!
    try {
      await handleSavePixelDirectly(false);
    } catch (e) {
      console.error('Auto-save step 2 error:', e);
    }

    // Proceed to Step 3
    setCurrentStep(3);
    verifyThemeEmbed(true);
  };

  const handleSavePixelDirectly = async (
    autoSwitch = false,
    override?: { id?: string; name?: string; token?: string; appEmbed?: boolean }
  ): Promise<boolean> => {
    const finalId =
      override?.id ||
      effectivePixelId ||
      (inputTab === 'manual' ? manualPixelId.trim() : selectedPixelOption.trim());
    const finalName =
      override?.name ||
      effectivePixelName ||
      (inputTab === 'manual' ? manualPixelName.trim() : autoPixelName.trim());
    const finalToken =
      override?.token !== undefined
        ? override.token
        : capiEnabled
        ? (tokenSource === 'auto' ? autoToken : accessToken.trim())
        : '';
    const finalAppEmbed = override?.appEmbed !== undefined ? override.appEmbed : appEmbedChecked;

    if (!finalId) {
      return false;
    }

    try {
      setIsLoading(true);
      const shopToUse =
        currentShop ||
        (typeof window !== 'undefined'
          ? new URLSearchParams(window.location.search).get('shop') ||
            new URLSearchParams(window.location.search).get('shopify_domain') ||
            localStorage.getItem('meta_connector_shop') ||
            document.referrer?.match(/admin\.shopify\.com\/store\/([^/?#]+)/i)?.[1]?.concat('.myshopify.com') ||
            ''
          : '');

      if (shopToUse && typeof window !== 'undefined') {
        try { localStorage.setItem('meta_connector_shop', shopToUse); } catch {}
      }

      const endpoint = shopToUse ? `/api/pixels?shop=${encodeURIComponent(shopToUse)}` : '/api/pixels';
      const isManual = inputTab === 'manual' || !fbConnected;
      const res = await fetch(apiUrl(endpoint), {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          shop: shopToUse,
          id: `pix_${finalId}`,
          pixelName: finalName || `Pixel ${finalId}`,
          pixelId: finalId,
          pixelType: 'master',
          source: isManual ? 'manual' : 'auto',
          facebookAccountId: isManual ? null : (fbUser?.id || selectedBusiness || null),
          targetCollection: 'all',
          pages_config: 'all',
          accessToken: finalToken,
          testEventCode: testEventCode,
          capiEnabled: capiEnabled,
          capi_status: capiEnabled && finalToken ? 'active' : 'not_configured',
          appEmbedActive: finalAppEmbed,
          isActive: true,
          status: 'active',
          verification_status: 'unverified',
        }),
      });

      const data = await res.json().catch(() => null);
      if (!res.ok || (data && !data.success)) {
        console.error('Failed to save pixel:', data);
        if (data?.error) {
          if (isManual) {
            setManualIdError(data.error);
          }
          setToastMessage({ text: data.error, type: 'warning' });
        }
        return false;
      }

      await fetchPixels(false);
      if (autoSwitch) {
        setViewMode('manager');
      }
      return true;
    } catch (err) {
      console.error('Save failed:', err);
      return false;
    } finally {
      setIsLoading(false);
    }
  };

  const handleNextStep3 = async () => {
    // Attempt theme verification silently
    let isVerified = false;
    try {
      isVerified = await verifyThemeEmbed(true);
    } catch {}

    // Save final status without blocking the user
    await handleSavePixelDirectly(false, {
      appEmbed: isVerified || appEmbedChecked,
    });
    setCurrentStep(4);
  };

  const handleFinishOnboarding = async () => {
    await handleSavePixelDirectly(true);
    navigateToPixelManager();
  };

  const handleOpenEdit = (pixel: MetaPixelRecord) => {
    setEditingPixel(pixel);
    setEditName(pixel.pixel_name);
    setEditTarget(pixel.target_collection || 'all');
    setEditCapiToken('');
    setEditTestCode(pixel.test_event_code || '');
    setShowEditCapiToken(false);
    setEditCapiVerified(false);
    setEditCapiVerifying(false);
    setEditCapiError(null);
  };

  const verifyEditCapiToken = async () => {
    const token = editCapiToken.trim();
    if (!token) {
      setEditCapiError('Please enter a Conversions API access token to verify.');
      return;
    }
    if (token.startsWith('EAGR')) {
      setEditCapiError('This looks like a Facebook login token, not a Conversions API token. Please generate one from Meta Events Manager → Settings → Conversions API.');
      return;
    }
    setEditCapiVerifying(true);
    setEditCapiError(null);
    try {
      const res = await fetch(apiUrl('/api/meta/verify-token'), {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          accessToken: token,
          pixelId: editingPixel?.pixel_id,
          shop: currentShop,
        }),
      });
      const data = await res.json();
      if (data.valid) {
        setEditCapiVerified(true);
        setEditCapiError(null);
        setToastMessage({ text: 'Conversions API token verified successfully.', type: 'success' });
      } else {
        setEditCapiVerified(false);
        setEditCapiError(data.message || data.error || "Invalid token — this token doesn't have access to your Pixel. Please check it in Meta Events Manager.");
      }
    } catch {
      setEditCapiError('Network error verifying token. Please try again.');
      setEditCapiVerified(false);
    } finally {
      setEditCapiVerifying(false);
    }
  };

  const handleOpenAddPixel = () => {
    setPixelModalMode('add');
    setEditingPixel(null);
    setPixelModalTab(fbConnected ? 'auto' : 'manual');
    const defaultBiz = fbConnected ? (selectedBusiness || businessAccounts[0]?.id || '') : '';
    setModalSelectedBusiness(defaultBiz);
    const firstPixel = availablePixels.length > 0 ? availablePixels[0] : null;
    const defaultPixelId = selectedPixelOption || firstPixel?.id || '';
    setModalSelectedPixel(defaultPixelId);
    const chosen = availablePixels.find((x) => x.id === defaultPixelId) || firstPixel;
    const defaultName = chosen ? getCleanPixelName(chosen.name, chosen.id) : '';
    setModalPixelName(defaultName);
    setModalPixelId('');
    setModalTrackingPages('all');
    setModalMarketTargeting('all');
    setModalCapiEnabled(true);
    setModalAccessToken(fbConnected ? (autoToken || '') : '');
    setModalTestEventCode('');
    setModalError(null);
    setShowPixelModal(true);
  };

  const handleOpenEditPixel = (pixel: MetaPixelRecord) => {
    setPixelModalMode('edit');
    setEditingPixel(pixel);
    const isAuto = pixel.source === 'auto' && fbConnected;
    setPixelModalTab(isAuto ? 'auto' : 'manual');
    setModalSelectedBusiness(pixel.facebook_account_id || selectedBusiness || businessAccounts[0]?.id || '');
    setModalSelectedPixel(pixel.pixel_id);
    setModalPixelName(pixel.pixel_name);
    setModalPixelId(pixel.pixel_id);
    const pagesCfg = pixel.pages_config === 'selected' || pixel.pages_config === 'excluded' ? pixel.pages_config : 'all';
    setModalTrackingPages(pagesCfg);
    setModalMarketTargeting('all');
    setModalCapiEnabled(Boolean(pixel.capi_enabled));
    setModalAccessToken('');
    setModalTestEventCode(pixel.test_event_code || '');
    setModalError(null);
    setShowPixelModal(true);
  };

  const handleModalSelectBusiness = async (bizId: string) => {
    setModalSelectedBusiness(bizId);
    setSelectedBusiness(bizId);
    const data = await fetchMetaAccounts(bizId);
    if (data?.pixels?.length) {
      const first = data.pixels[0];
      setModalSelectedPixel(first.id);
      setModalPixelName(getCleanPixelName(first.name, first.id));
    }
  };

  const handleModalSelectPixel = (pixelId: string) => {
    setModalSelectedPixel(pixelId);
    const chosen = availablePixels.find((x) => x.id === pixelId);
    if (chosen) {
      setModalPixelName(getCleanPixelName(chosen.name, chosen.id));
    }
  };

  const handleModalDisconnect = async () => {
    try {
      const shopToUse = currentShop || (typeof window !== 'undefined' ? localStorage.getItem('meta_connector_shop') || '' : '');
      await fetch(apiUrl('/api/meta/connect'), {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ disconnect: true, shopDomain: shopToUse }),
      });
    } catch (err) {
      console.error('Failed to disconnect Facebook:', err);
    }
    resetMetaState();
    setToastMessage({
      text: 'Facebook account disconnected.',
      type: 'info',
    });
  };

  const handleSaveModalPixel = async () => {
    setModalError(null);
    const cleanName = modalPixelName.trim();
    if (!cleanName) {
      setModalError('Pixel name is required');
      return;
    }

    let finalId = '';
    const finalSource: 'auto' | 'manual' = pixelModalTab;
    let finalFbAccountId: string | null = null;

    if (pixelModalTab === 'auto') {
      if (!fbConnected) {
        setModalError('Please connect your Facebook account or switch to Manual input');
        return;
      }
      if (!modalSelectedPixel) {
        setModalError('Please select a pixel from your connected Facebook account');
        return;
      }
      finalId = modalSelectedPixel;
      finalFbAccountId = modalSelectedBusiness || fbUser?.id || null;
    } else {
      finalId = modalPixelId.trim().replace(/\D/g, '');
      if (!finalId) {
        setModalError('Pixel ID is required');
        return;
      }
      if (finalId.length < 15 || finalId.length > 16) {
        setModalError('Pixel ID must be 15 or 16 numeric digits');
        return;
      }
      finalFbAccountId = null;
    }

    setIsSavingModalPixel(true);
    try {
      const shopToUse = currentShop || (typeof window !== 'undefined' ? localStorage.getItem('meta_connector_shop') || '' : '');

      if (pixelModalMode === 'add') {
        if (pixels.some((p) => p.pixel_id === finalId)) {
          setModalError('This pixel is already added to this store.');
          setIsSavingModalPixel(false);
          return;
        }

        const endpoint = shopToUse ? `/api/pixels?shop=${encodeURIComponent(shopToUse)}` : '/api/pixels';
        const res = await fetch(apiUrl(endpoint), {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            shop: shopToUse,
            id: `pix_${finalId}`,
            pixelName: cleanName,
            pixelId: finalId,
            pixelType: 'master',
            source: finalSource,
            facebookAccountId: finalFbAccountId,
            pages_config: modalTrackingPages,
            targetCollection: modalTrackingPages,
            capiEnabled: modalCapiEnabled,
            capi_status: modalCapiEnabled ? 'active' : 'not_configured',
            accessToken: modalCapiEnabled ? (modalAccessToken.trim() || (pixelModalTab === 'auto' ? autoToken : '')) : '',
            testEventCode: modalTestEventCode.trim(),
            appEmbedActive: true,
            isActive: true,
            status: 'active',
            verification_status: 'unverified',
          }),
        });
        const data = await res.json().catch(() => null);
        if (!res.ok || (data && !data.success)) {
          const errMsg = data?.error || 'Failed to save pixel. Please try again.';
          setModalError(errMsg);
          setIsSavingModalPixel(false);
          return;
        }
        setShowPixelModal(false);
        setToastMessage({ text: `Pixel "${cleanName}" added successfully!`, type: 'success' });
        await fetchPixels(false);
      } else {
        if (!editingPixel) return;
        if (finalId !== editingPixel.pixel_id && pixels.some((p) => p.pixel_id === finalId && p.id !== editingPixel.id)) {
          setModalError('This pixel ID is already in use by another pixel in this store.');
          setIsSavingModalPixel(false);
          return;
        }

        const endpoint = shopToUse ? `/api/pixels?shop=${encodeURIComponent(shopToUse)}` : '/api/pixels';
        const res = await fetch(apiUrl(endpoint), {
          method: 'PATCH',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            shop: shopToUse,
            id: editingPixel.id,
            pixelId: finalId,
            pixelName: cleanName,
            pages_config: modalTrackingPages,
            targetCollection: modalTrackingPages,
            capiEnabled: modalCapiEnabled,
            capi_status: modalCapiEnabled ? 'active' : 'not_configured',
            accessToken: modalAccessToken.trim() ? modalAccessToken.trim() : undefined,
            testEventCode: modalTestEventCode.trim(),
            source: finalSource,
            facebookAccountId: finalFbAccountId,
            appEmbedActive: true,
          }),
        });
        const data = await res.json().catch(() => null);
        if (!res.ok || (data && !data.success)) {
          const errMsg = data?.error || 'Failed to update pixel. Please try again.';
          setModalError(errMsg);
          setIsSavingModalPixel(false);
          return;
        }
        setShowPixelModal(false);
        setEditingPixel(null);
        setToastMessage({ text: `Pixel "${cleanName}" updated successfully!`, type: 'success' });
        await fetchPixels(false);
      }
    } catch (err) {
      console.error(err);
      setModalError('Network error saving pixel. Please try again.');
    } finally {
      setIsSavingModalPixel(false);
    }
  };

  const handleVerifyPixelWithMeta = async (pixel: MetaPixelRecord | { id: string; pixel_id: string; pixel_name: string }) => {
    setVerifyingPixelId(pixel.id);
    setPixelVerificationError(null);
    try {
      const shopToUse = currentShop || (typeof window !== 'undefined' ? localStorage.getItem('meta_connector_shop') || '' : '');
      const res = await fetch(apiUrl('/api/meta/verify-pixel'), {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          pixelId: pixel.pixel_id,
          shop: shopToUse,
        }),
      });
      const data = await res.json();
      if (data.valid) {
        setToastMessage({ text: `Meta verified Pixel "${pixel.pixel_name}" successfully!`, type: 'success' });
        setPixels((prev) =>
          prev.map((p) =>
            p.id === pixel.id || p.pixel_id === pixel.pixel_id
              ? { ...p, verification_status: 'verified', status: 'active', is_active: true }
              : p
          )
        );
        await fetchPixels(false);
      } else {
        const errorMsg = data.error || 'Meta verification failed. Please confirm this Pixel ID exists in Meta Events Manager.';
        setPixelVerificationError({ id: pixel.id, message: errorMsg });
        setToastMessage({ text: errorMsg, type: 'warning' });
        setPixels((prev) =>
          prev.map((p) =>
            p.id === pixel.id || p.pixel_id === pixel.pixel_id
              ? { ...p, verification_status: 'failed' }
              : p
          )
        );
      }
    } catch {
      const netMsg = 'Network error during Meta verification. Please retry.';
      setPixelVerificationError({ id: pixel.id, message: netMsg });
      setToastMessage({ text: netMsg, type: 'warning' });
      setPixels((prev) =>
        prev.map((p) =>
          p.id === pixel.id || p.pixel_id === pixel.pixel_id
            ? { ...p, verification_status: 'failed' }
            : p
        )
      );
    } finally {
      setVerifyingPixelId(null);
    }
  };

  const handleDeletePixel = async () => {
    if (!deletingPixel) return;
    try {
      const endpoint = `/api/pixels?id=${encodeURIComponent(deletingPixel.id)}${currentShop ? `&shop=${encodeURIComponent(currentShop)}` : ''}`;
      const res = await fetch(apiUrl(endpoint), { method: 'DELETE' });
      const data = await res.json().catch(() => null);
      if (!res.ok || (data && !data.success)) {
        setToastMessage({ text: 'Failed to delete pixel. Please try again.', type: 'warning' });
        setDeletingPixel(null);
        return;
      }
      const remaining = pixels.filter((p) => p.id !== deletingPixel.id && p.pixel_id !== deletingPixel.pixel_id);
      setPixels(remaining);
      setDeletingPixel(null);
      setToastMessage({ text: `Pixel "${deletingPixel.pixel_name}" deleted successfully.`, type: 'success' });
      setViewMode('manager');
    } catch (err) {
      console.error(err);
      setToastMessage({ text: 'Network error while deleting pixel. Please try again.', type: 'warning' });
      setDeletingPixel(null);
    }
  };

  const handleToggleActive = async (pixel: MetaPixelRecord) => {
    try {
      const currentActive = pixel.is_active !== false;
      const newStatus: 'active' | 'paused' = !currentActive ? 'active' : 'paused';
      const updated: MetaPixelRecord = { ...pixel, is_active: !currentActive, status: newStatus };
      setPixels(pixels.map((p) => (p.id === pixel.id ? updated : p)));
      const endpoint = currentShop ? `/api/pixels?shop=${encodeURIComponent(currentShop)}` : '/api/pixels';
      await fetch(apiUrl(endpoint), {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          shop: currentShop,
          id: updated.id,
          pixelName: updated.pixel_name,
          pixelId: updated.pixel_id,
          pixelType: updated.pixel_type,
          targetCollection: updated.target_collection,
          capiEnabled: updated.capi_enabled,
          isActive: updated.is_active,
          status: updated.status,
        }),
      });
    } catch (err) {
      console.error(err);
    }
  };

  const handleToggleCapi = async (pixel: MetaPixelRecord) => {
    try {
      const updated = { ...pixel, capi_enabled: !pixel.capi_enabled };
      setPixels(pixels.map((p) => (p.id === pixel.id ? updated : p)));
      const endpoint = currentShop ? `/api/pixels?shop=${encodeURIComponent(currentShop)}` : '/api/pixels';
      await fetch(apiUrl(endpoint), {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          shop: currentShop,
          id: updated.id,
          pixelName: updated.pixel_name,
          pixelId: updated.pixel_id,
          pixelType: updated.pixel_type,
          targetCollection: updated.target_collection,
          capiEnabled: updated.capi_enabled,
          isActive: updated.is_active,
        }),
      });
    } catch (err) {
      console.error(err);
    }
  };

  const handleSendTestEvent = async () => {
    setIsSendingTest(true);
    setTestResult(null);
    try {
      const res = await fetch(apiUrl('/api/capi/test'), {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          eventName: testEventName,
          testEventCode: testEventCode,
          value: parseFloat(testValue) || 49.99,
        }),
      });
      const data = await res.json();
      setTestResult(data);
    } catch {
      setTestResult({ error: 'Network error connecting to Meta Graph API' });
    } finally {
      setIsSendingTest(false);
    }
  };

  const handleRunVerification = async () => {
    setShowVerifyModal(true);
    setIsVerifying(true);
    setVerifyStep(1);

    const finalId = effectivePixelId;

    try {
      setTimeout(() => setVerifyStep(2), 500);

      await fetch(apiUrl('/api/diagnostics/verify'), {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          pixelId: finalId,
          accessToken: accessToken,
          appEmbedActive: appEmbedChecked,
          shop: currentShop,
        }),
      });

      setTimeout(() => {
        setVerifyStep(3);
        setIsVerifying(false);
      }, 1000);
    } catch {
      setTimeout(() => {
        setVerifyStep(3);
        setIsVerifying(false);
      }, 1000);
    }
  };

  const copyToClipboard = (text: string, id: string) => {
    navigator.clipboard.writeText(text);
    setCopiedId(id);
    setTimeout(() => setCopiedId(null), 2000);
  };

  // Filtered & Paginated Pixels for Table
  const filteredPixels = useMemo(() => {
    return pixels.filter((p) => {
      const q = (searchQuery || '').toLowerCase().trim();
      if (!q) return true;
      const name = String(p.pixel_name || '').toLowerCase();
      const id = String(p.pixel_id || '').toLowerCase();
      return name.includes(q) || id.includes(q);
    });
  }, [pixels, searchQuery]);

  const totalPages = Math.max(1, Math.ceil(filteredPixels.length / rowsPerPage));
  const safePage = Math.min(currentPage, totalPages);
  const paginatedPixels = useMemo(() => {
    const start = (safePage - 1) * rowsPerPage;
    return filteredPixels.slice(start, start + rowsPerPage);
  }, [filteredPixels, safePage, rowsPerPage]);

  if (isLoading) {
    return (
      <div className="min-h-screen bg-slate-50 text-slate-900 font-sans antialiased flex flex-col">
        <header className="sticky top-0 z-40 bg-white border-b border-slate-200/90 shadow-sm px-4 sm:px-6 h-14 flex items-center justify-between">
          <div className="flex items-center gap-2.5">
            <div className="w-6 h-6 rounded-full bg-slate-200 animate-pulse" />
            <div className="w-24 h-4 bg-slate-200 rounded animate-pulse" />
          </div>
          <div className="w-28 h-8 bg-slate-200 rounded-lg animate-pulse" />
        </header>
        <main className="flex-1 max-w-5xl w-full mx-auto p-4 sm:p-6 lg:p-8 space-y-6">
          <div className="bg-white rounded-2xl border border-slate-200/90 p-6 shadow-sm space-y-4">
            <div className="h-6 w-48 bg-slate-200 rounded animate-pulse" />
            <div className="h-4 w-96 bg-slate-100 rounded animate-pulse" />
            <div className="pt-4 grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="h-24 bg-slate-100 rounded-xl animate-pulse" />
              <div className="h-24 bg-slate-100 rounded-xl animate-pulse" />
              <div className="h-24 bg-slate-100 rounded-xl animate-pulse" />
            </div>
          </div>
        </main>
      </div>
    );
  }

  // =========================================================================
  // RENDER ONBOARDING VIEW (SCREENSHOTS 1, 2, 4, 5, 6, 8, 9)
  // =========================================================================
  if (viewMode === 'onboarding') {
    const finalSelectedPixelId = effectivePixelId;

    return (
      <div className="min-h-screen bg-slate-50/70 text-slate-900 font-sans antialiased flex flex-col selection:bg-theme/20 selection:text-black">
        {/* Top Header Bar */}
        <header className="sticky top-0 z-40 bg-white/95 backdrop-blur-md border-b border-slate-200/90 shadow-2xs px-4 sm:px-6 h-16 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <AppLogo size="md" />
            <div className="flex items-center gap-2 text-xs sm:text-sm">
              <span className="font-semibold text-slate-600 hidden sm:inline">{branding.appName}</span>
              <span className="text-slate-300 font-normal select-none hidden sm:inline">&rsaquo;</span>
              <span className="font-bold text-slate-900 tracking-tight">
                Setup Wizard
              </span>
            </div>
          </div>

          <div className="flex items-center gap-2.5">
            {pixels.length > 0 && (
              <button
                type="button"
                onClick={navigateToPixelManager}
                className="px-3.5 py-1.5 rounded-xl text-xs font-semibold text-slate-600 hover:text-black hover:bg-slate-100 transition-colors cursor-pointer"
                title="Return to Pixel Manager"
              >
                Exit Wizard
              </button>
            )}
          </div>
        </header>

        {/* Horizontal Top Progress Bar in Theme Color */}
        <div className="w-full bg-slate-200/80 h-1 relative overflow-hidden">
          <div
            className="h-full bg-theme transition-all duration-500 ease-out"
            style={{
              width:
                currentStep === 1
                  ? '33.33%'
                  : currentStep === 2
                  ? '66.66%'
                  : '100%',
            }}
          />
        </div>

        {/* Main Content Area */}
        <main className="flex-1 max-w-4xl w-full mx-auto p-4 sm:p-6 lg:p-8 space-y-6">
          {/* Centered Heading */}
          {currentStep !== 4 && (
            <div className="text-center space-y-2 pt-2 pb-1">
              <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-theme/10 border border-theme/20 text-theme text-xs font-bold shadow-2xs">
                {currentStep === 1 && (
                  <>
                    <i className="fa-solid fa-wand-magic-sparkles text-[11px]" />
                    <span>Step 1 of 3 &middot; Pixel Setup &amp; Pairing</span>
                  </>
                )}
                {currentStep === 2 && (
                  <>
                    <i className="fa-solid fa-server text-[11px]" />
                    <span>Step 2 of 3 &middot; Conversions API (CAPI) Integration</span>
                  </>
                )}
                {currentStep === 3 && (
                  <>
                    <i className="fa-solid fa-store text-[11px]" />
                    <span>Step 3 of 3 &middot; Theme App Embed Activation</span>
                  </>
                )}
              </div>

              <h1 className="text-2xl sm:text-3xl font-black text-black tracking-tight">
                {currentStep === 1
                  ? 'Get your Pixels ready'
                  : currentStep === 2
                  ? 'Level up your data with CAPI'
                  : 'Activate Storefront App Embed'}
              </h1>
              <p className="text-xs sm:text-sm text-slate-600 max-w-xl mx-auto leading-relaxed">
                {currentStep === 1
                  ? 'Install the right pixels, and install the pixels right to track storefront visitors and sales.'
                  : currentStep === 2
                  ? 'CAPI comes in when the pixel is blocked by browser ad-blockers and iOS 14.5+. This ensures zero signal loss for high-ROAS ads.'
                  : 'Make sure your app embed is enabled in your Shopify Theme Editor to begin capturing events in real-time.'}
              </p>
            </div>
          )}

          {/* ---------------------------------------------------------------- */}
          {/* SETUP PROGRESS STEPPER BAR (SHOWN RIGHT AFTER THE SUBTITLE) */}
          {/* ---------------------------------------------------------------- */}
          {currentStep !== 4 && (
            <div className="bg-white rounded-2xl border border-slate-200/90 shadow-sm p-4 sm:p-5">
              <div className="flex items-center justify-between mb-3 px-1">
                <span className="text-[11px] font-black uppercase tracking-wider text-black">
                  Setup Progress
                </span>
                <span className="text-xs font-semibold text-slate-500">
                  Step {currentStep} of 3
                </span>
              </div>

              {/* 3 Horizontal Steps */}
              <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                {/* Step 1 */}
                <div
                  onClick={() => currentStep > 1 && setCurrentStep(1)}
                  className={`p-3 rounded-xl border transition-all flex items-center gap-3 ${
                    currentStep === 1
                      ? 'bg-theme/5 border-theme shadow-2xs ring-2 ring-theme/15'
                      : currentStep > 1
                      ? 'bg-slate-50/60 border-slate-200 hover:bg-slate-100/70 cursor-pointer'
                      : 'bg-slate-50/30 border-slate-200/60 opacity-60'
                  }`}
                >
                  <div
                    className={`w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold shrink-0 transition-all ${
                      currentStep > 1
                        ? 'bg-black text-white'
                        : currentStep === 1
                        ? 'bg-theme text-white ring-4 ring-theme/20'
                        : 'border-2 border-slate-200 bg-white text-slate-400'
                    }`}
                  >
                    {currentStep > 1 ? <i className="fa-solid fa-check text-[11px]" /> : '01'}
                  </div>
                  <div className="min-w-0 flex-1">
                    <div className="flex items-center justify-between gap-1">
                      <h4
                        className={`text-xs font-bold truncate ${
                          currentStep === 1 ? 'text-black' : currentStep > 1 ? 'text-slate-800' : 'text-slate-400'
                        }`}
                      >
                        Add Facebook pixel
                      </h4>
                      {currentStep === 1 && (
                        <span className="text-[9px] font-bold text-white bg-theme px-1.5 py-0.2 rounded">
                          Active
                        </span>
                      )}
                      {currentStep > 1 && (
                        <span className="text-[9px] font-bold text-black bg-slate-200 px-1.5 py-0.2 rounded">
                          Done
                        </span>
                      )}
                    </div>
                    <p className="text-[11px] text-slate-500 truncate mt-0.5">
                      Install &amp; pair pixel
                    </p>
                  </div>
                </div>

                {/* Step 2 */}
                <div
                  onClick={() => currentStep > 2 && setCurrentStep(2)}
                  className={`p-3 rounded-xl border transition-all flex items-center gap-3 ${
                    currentStep === 2
                      ? 'bg-theme/5 border-theme shadow-2xs ring-2 ring-theme/15'
                      : currentStep > 2
                      ? 'bg-slate-50/60 border-slate-200 hover:bg-slate-100/70 cursor-pointer'
                      : 'bg-slate-50/30 border-slate-200/60 opacity-60'
                  }`}
                >
                  <div
                    className={`w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold shrink-0 transition-all ${
                      currentStep > 2
                        ? 'bg-black text-white'
                        : currentStep === 2
                        ? 'bg-theme text-white ring-4 ring-theme/20'
                        : 'border-2 border-slate-200 bg-white text-slate-400'
                    }`}
                  >
                    {currentStep > 2 ? <i className="fa-solid fa-check text-[11px]" /> : '02'}
                  </div>
                  <div className="min-w-0 flex-1">
                    <div className="flex items-center justify-between gap-1">
                      <h4
                        className={`text-xs font-bold truncate ${
                          currentStep === 2 ? 'text-black' : currentStep > 2 ? 'text-slate-800' : 'text-slate-400'
                        }`}
                      >
                        Conversion API
                      </h4>
                      {currentStep === 2 && (
                        <span className="text-[9px] font-bold text-white bg-theme px-1.5 py-0.2 rounded">
                          Active
                        </span>
                      )}
                      {currentStep > 2 && (
                        <span className="text-[9px] font-bold text-black bg-slate-200 px-1.5 py-0.2 rounded">
                          Done
                        </span>
                      )}
                    </div>
                    <p className="text-[11px] text-slate-500 truncate mt-0.5">
                      Bypass browser blocks
                    </p>
                  </div>
                </div>

                {/* Step 3 */}
                <div
                  className={`p-3 rounded-xl border transition-all flex items-center gap-3 ${
                    currentStep === 3
                      ? 'bg-theme/5 border-theme shadow-2xs ring-2 ring-theme/15'
                      : 'bg-slate-50/30 border-slate-200/60 opacity-60'
                  }`}
                >
                  <div
                    className={`w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold shrink-0 transition-all ${
                      currentStep === 3
                        ? 'bg-theme text-white ring-4 ring-theme/20'
                        : 'border-2 border-slate-200 bg-white text-slate-400'
                    }`}
                  >
                    03
                  </div>
                  <div className="min-w-0 flex-1">
                    <div className="flex items-center justify-between gap-1">
                      <h4
                        className={`text-xs font-bold truncate ${
                          currentStep === 3 ? 'text-black' : 'text-slate-400'
                        }`}
                      >
                        Activate app
                      </h4>
                      {currentStep === 3 && (
                        <span className="text-[9px] font-bold text-white bg-theme px-1.5 py-0.2 rounded">
                          Active
                        </span>
                      )}
                    </div>
                    <p className="text-[11px] text-slate-500 truncate mt-0.5">
                      Storefront theme embed
                    </p>
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* ---------------------------------------------------------------- */}
          {/* MAIN STEP CONTENT CARD */}
          {/* ---------------------------------------------------------------- */}
          {currentStep !== 4 && (
            <div className="space-y-4">
              <div className="bg-white rounded-2xl border border-slate-200/90 shadow-sm p-6 sm:p-8 space-y-6">
                {/* STEP 1 CONTENT */}
                {currentStep === 1 && (
                  <div className="space-y-6">
                    <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 border-b border-slate-100 pb-4">
                      <div>
                        <div className="flex items-center gap-2">
                          <h3 className="text-base font-extrabold text-black">
                            Add Facebook pixel
                          </h3>
                          <button
                            type="button"
                            onClick={() => setGuideModalSlug('setup-pixel-and-capi')}
                            className="inline-flex items-center gap-1 px-2 py-0.5 rounded-md bg-slate-100 text-slate-700 hover:bg-slate-200 text-[11px] font-medium border border-slate-200/80 transition-colors cursor-pointer"
                            title="Open Step 1 Guide Popup"
                          >
                            <i className="fa fa-book-open text-[10px] text-slate-500" />
                            <span>Guide</span>
                          </button>
                        </div>
                        <p className="text-xs text-slate-500 mt-0.5">
                          Select how you want to configure your tracking pixel.
                        </p>
                      </div>

                      {/* Auto input / Manual input Tabs */}
                      <div className="inline-flex rounded-xl bg-slate-100/90 p-1 border border-slate-200/70 shrink-0">
                        <button
                          type="button"
                          onClick={() => switchInputTab('auto')}
                          className={`px-3.5 py-1.5 text-xs font-bold rounded-lg transition-all flex items-center gap-1.5 cursor-pointer ${
                            inputTab === 'auto'
                              ? 'bg-theme text-white shadow-sm'
                              : 'text-slate-600 hover:text-black'
                          }`}
                        >
                          <i className="fa-solid fa-wand-magic-sparkles text-[10px]" />
                          <span>Auto input</span>
                          <span
                            className={`text-[9px] font-extrabold px-1.5 py-0.2 rounded ${
                              inputTab === 'auto' ? 'bg-white/20 text-white' : 'bg-slate-200 text-slate-700'
                            }`}
                          >
                            Recommended
                          </span>
                        </button>
                        <button
                          type="button"
                          onClick={() => switchInputTab('manual')}
                          className={`px-3.5 py-1.5 text-xs font-bold rounded-lg transition-all flex items-center gap-1.5 cursor-pointer ${
                            inputTab === 'manual'
                              ? 'bg-theme text-white shadow-sm'
                              : 'text-slate-600 hover:text-black'
                          }`}
                        >
                          <i className="fa-solid fa-keyboard text-[10px]" />
                          <span>Manual input</span>
                        </button>
                      </div>
                    </div>

                    {/* AUTO TAB */}
                    {inputTab === 'auto' && (
                      <div className="space-y-5">
                        {!fbConnected ? (
                          /* Disconnected state */
                          <div className="p-5 rounded-2xl border border-slate-200 bg-gradient-to-r from-slate-50 via-white to-slate-50 flex flex-col sm:flex-row sm:items-center justify-between gap-4 shadow-2xs">
                            <div className="flex items-start gap-3.5">
                              <div className="w-10 h-10 rounded-xl bg-[#1877F2] text-white flex items-center justify-center text-lg shadow-sm shrink-0">
                                <i className="fa-brands fa-facebook-f" />
                              </div>
                              <div className="space-y-1">
                                <h4 className="text-xs sm:text-sm font-bold text-black">
                                  Connect your Facebook account
                                </h4>
                                <p className="text-xs text-slate-500 leading-relaxed">
                                  Log in to automatically fetch your Business Portfolios, Pixels, and System User tokens.
                                </p>
                              </div>
                            </div>
                            <button
                              type="button"
                              onClick={handleFbConnect}
                              className="px-5 py-2.5 rounded-xl text-xs font-bold bg-[#1877F2] hover:bg-[#166fe5] text-white shadow-sm hover:shadow-md transition-all flex items-center justify-center gap-2 cursor-pointer shrink-0"
                            >
                              <i className="fa-brands fa-facebook-f text-xs" />
                              <span>Connect Facebook</span>
                              <i className="fa-solid fa-arrow-right text-[10px]" />
                            </button>
                          </div>
                        ) : (
                          /* Connected state */
                          <div className="space-y-5">
                            {/* Connected Account Card */}
                            <div className="p-4 rounded-xl border border-slate-200/90 bg-white shadow-2xs flex items-center justify-between">
                              <div className="flex items-center gap-3">
                                {(() => {
                                  const avatarSrc =
                                    fbUser?.avatar ||
                                    (fbUser?.id ? `https://graph.facebook.com/${fbUser.id}/picture?type=large` : '');
                                  return (
                                    <div className="relative shrink-0">
                                      {avatarSrc && !avatarLoadError ? (
                                        <img
                                          src={avatarSrc}
                                          alt={fbUser?.name || 'Facebook Profile'}
                                          onError={() => setAvatarLoadError(true)}
                                          className="w-10 h-10 rounded-full object-cover border border-slate-200 shadow-xs"
                                        />
                                      ) : (
                                        <div className="w-10 h-10 rounded-full bg-[#1877F2] text-white flex items-center justify-center text-lg font-bold shadow-xs">
                                          <i className="fa-brands fa-facebook-f" />
                                        </div>
                                      )}
                                      <span
                                        className="absolute -bottom-0.5 -right-0.5 w-4 h-4 rounded-full bg-[#1877F2] border-2 border-white flex items-center justify-center shadow-xs"
                                        title="Connected via Meta"
                                      >
                                        <i className="fa-solid fa-check text-[7px] text-white" />
                                      </span>
                                    </div>
                                  );
                                })()}
                                <div>
                                  <div className="flex items-center gap-2">
                                    <h4 className="text-xs font-bold text-black flex items-center gap-1.5">
                                      <span>{fbUser?.name || 'Meta Account'}</span>
                                      <i className="fa-brands fa-facebook text-[#1877F2] text-xs" title="Meta Verified" />
                                    </h4>
                                    <span className="text-[10px] font-bold text-[#1877F2] bg-[#1877F2]/10 border border-[#1877F2]/20 px-1.5 py-0.2 rounded">
                                      Verified
                                    </span>
                                  </div>
                                  <p className="text-[11px] text-emerald-600 font-semibold flex items-center gap-1 mt-0.5">
                                    <span className="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse" />
                                    Account connected to Graph API
                                  </p>
                                </div>
                              </div>
                              <button
                                type="button"
                                onClick={handleFbDisconnect}
                                className="px-3.5 py-1.5 rounded-lg text-xs font-semibold border border-slate-200 text-slate-700 hover:bg-rose-50 hover:text-rose-600 hover:border-rose-200 transition-colors cursor-pointer"
                              >
                                Disconnect
                              </button>
                            </div>

                            {/* Business Account Dropdown */}
                            <div className="space-y-1.5">
                              <label className="text-xs font-bold text-slate-800 flex items-center gap-1.5">
                                <i className="fa-solid fa-building text-slate-400 text-xs" />
                                <span>Select business account</span>
                              </label>
                              <div className="relative">
                                <select
                                  value={selectedBusiness}
                                  onChange={(e) => handleSelectBusiness(e.target.value)}
                                  className="w-full p-2.5 pr-9 rounded-xl border border-slate-200 text-xs bg-white text-slate-800 font-medium appearance-none shadow-2xs focus:outline-none focus:ring-2 focus:ring-theme/20 focus:border-theme transition-all cursor-pointer"
                                >
                                  {businessAccounts.map((b) => (
                                    <option key={b.id} value={b.id}>
                                      {b.name}
                                    </option>
                                  ))}
                                </select>
                                <i className="fa-solid fa-chevron-down text-[10px] text-slate-400 absolute right-3.5 top-1/2 -translate-y-1/2 pointer-events-none" />
                              </div>
                            </div>

                            {/* Pixel Dropdown */}
                            <div className="space-y-1.5">
                              <label className="text-xs font-bold text-slate-800 flex items-center gap-1.5">
                                <i className="fa-solid fa-bullseye text-slate-400 text-xs" />
                                <span>Select pixel</span>
                              </label>
                              <div className="relative">
                                <select
                                  value={selectedPixelOption}
                                  onChange={(e) => {
                                    const newId = e.target.value;
                                    setSelectedPixelOption(newId);
                                    const p = availablePixels.find((x) => x.id === newId);
                                    if (p) {
                                      const pName = p.name.split(' - ')[1] || p.name;
                                      setAutoPixelName(pName);
                                    }
                                  }}
                                  className="w-full p-2.5 pr-9 rounded-xl border border-slate-200 text-xs bg-white text-slate-800 font-medium appearance-none shadow-2xs focus:outline-none focus:ring-2 focus:ring-theme/20 focus:border-theme transition-all cursor-pointer"
                                >
                                  {availablePixels.map((p) => (
                                    <option key={p.id} value={p.id}>
                                      {p.name}
                                    </option>
                                  ))}
                                </select>
                                <i className="fa-solid fa-chevron-down text-[10px] text-slate-400 absolute right-3.5 top-1/2 -translate-y-1/2 pointer-events-none" />
                              </div>
                            </div>

                            {/* Pixel Name Input */}
                            <div className="space-y-1.5">
                              <div className="flex items-center justify-between">
                                <label className="text-xs font-bold text-slate-800 flex items-center gap-1.5">
                                  <i className="fa-solid fa-tag text-slate-400 text-xs" />
                                  <span>Pixel name</span>
                                  <span className="text-theme">*</span>
                                </label>
                                <span className={`text-[10px] font-mono ${autoPixelName.length >= 255 ? 'text-amber-600 font-bold' : 'text-slate-400'}`}>
                                  {autoPixelName.length}/255
                                </span>
                              </div>
                              <input
                                type="text"
                                maxLength={255}
                                value={autoPixelName}
                                onChange={(e) => setAutoPixelName(e.target.value.slice(0, 255))}
                                placeholder="e.g. Master Store Pixel"
                                className="w-full p-2.5 rounded-xl border border-slate-200 text-xs bg-white text-slate-800 shadow-2xs focus:outline-none focus:ring-2 focus:ring-theme/20 focus:border-theme transition-all"
                              />
                            </div>

                            {/* Information Callout */}
                            <div className="flex items-start gap-2.5 p-3.5 rounded-xl bg-theme/5 border border-theme/20 text-[11px] text-slate-800 leading-relaxed">
                              <i className="fa-solid fa-circle-info text-theme mt-0.5 shrink-0 text-xs" />
                              <p>
                                Your pixel will track all storefront pages by default (Page Views, View Content, Add To Cart, Checkout, Purchase). Advanced collection-specific routing can be customized later in Pixel Manager.
                              </p>
                            </div>
                          </div>
                        )}
                      </div>
                    )}

                    {/* MANUAL TAB */}
                    {inputTab === 'manual' && (
                      <div className="space-y-5">
                        {/* Pixel Name */}
                        <div className="space-y-1.5">
                          <div className="flex items-center justify-between">
                            <label className="text-xs font-bold text-slate-800 flex items-center gap-1.5">
                              <i className="fa-solid fa-tag text-slate-400 text-xs" />
                              <span>Pixel name</span>
                              <span className="text-theme">*</span>
                            </label>
                            <span
                              className={`text-[10px] font-mono transition-colors ${
                                manualPixelName.length >= 255 ? 'text-amber-600 font-bold' : 'text-slate-400'
                              }`}
                            >
                              {manualPixelName.length}/255
                            </span>
                          </div>
                          <input
                            type="text"
                            maxLength={255}
                            value={manualPixelName}
                            onChange={(e) => {
                              const val = e.target.value.slice(0, 255);
                              setManualPixelName(val);
                              if (manualNameError && val.trim().length > 0) {
                                setManualNameError(null);
                              }
                            }}
                            onBlur={() => {
                              if (!manualPixelName.trim()) {
                                setManualNameError('Pixel name is required');
                              } else {
                                setManualNameError(null);
                              }
                            }}
                            placeholder="e.g. Master Store Pixel or Facebook Pixel"
                            className={`w-full p-2.5 rounded-xl border text-xs bg-white text-slate-800 shadow-2xs focus:outline-none focus:ring-2 transition-all ${
                              manualNameError
                                ? 'border-red-400 focus:ring-red-100 focus:border-red-500'
                                : 'border-slate-200 focus:ring-theme/20 focus:border-theme'
                            }`}
                          />
                          {manualNameError && (
                            <p className="text-[11px] text-red-600 font-medium flex items-center gap-1.5 mt-1">
                              <i className="fa-solid fa-circle-exclamation text-[10px]" />
                              <span>{manualNameError}</span>
                            </p>
                          )}
                        </div>

                        {/* Pixel ID */}
                        <div className="space-y-1.5">
                          <div className="flex items-center justify-between">
                            <div className="flex items-center gap-2">
                              <label className="text-xs font-bold text-slate-800 flex items-center gap-1.5">
                                <i className="fa-solid fa-fingerprint text-slate-400 text-xs" />
                                <span>Pixel ID</span>
                                <span className="text-theme">*</span>
                              </label>
                              <button
                                type="button"
                                onClick={() => setHelpModal('pixel_id')}
                                className="text-[11px] text-theme hover:underline font-semibold flex items-center gap-1 cursor-pointer"
                              >
                                <i className="fa-regular fa-circle-question text-[10px]" />
                                <span>Where do I get it?</span>
                              </button>
                            </div>
                            <span
                              className={`text-[10px] font-mono transition-colors ${
                                manualPixelId.length >= 15 && manualPixelId.length <= 16
                                  ? 'text-emerald-600 font-semibold'
                                  : manualPixelId.length > 0
                                  ? 'text-amber-600 font-semibold'
                                  : 'text-slate-400'
                              }`}
                            >
                              {manualPixelId.length}/16 digits
                            </span>
                          </div>
                          <input
                            type="text"
                            inputMode="numeric"
                            pattern="[0-9]*"
                            maxLength={16}
                            value={manualPixelId}
                            onChange={(e) => {
                              const val = e.target.value.replace(/\D/g, '').slice(0, 16);
                              setManualPixelId(val);
                              if (manualIdError) {
                                if (val.length >= 15 && val.length <= 16) {
                                  setManualIdError(null);
                                }
                              }
                            }}
                            onBlur={() => {
                              const clean = manualPixelId.trim();
                              if (!clean) {
                                setManualIdError('Pixel ID is required');
                              } else if (clean.length < 15 || clean.length > 16) {
                                setManualIdError(`Pixel ID must be 15 or 16 digits (currently ${clean.length} digits)`);
                              } else {
                                setManualIdError(null);
                              }
                            }}
                            placeholder="Copy 15-16 digit Pixel ID from Meta Events Manager"
                            className={`w-full p-2.5 rounded-xl border text-xs bg-white font-mono text-slate-800 shadow-2xs focus:outline-none focus:ring-2 transition-all ${
                              manualIdError
                                ? 'border-red-400 focus:ring-red-100 focus:border-red-500'
                                : manualPixelId.length >= 15 && manualPixelId.length <= 16
                                ? 'border-emerald-300 focus:ring-emerald-100 focus:border-emerald-500'
                                : 'border-slate-200 focus:ring-theme/20 focus:border-theme'
                            }`}
                          />
                          {manualIdError ? (
                            <p className="text-[11px] text-red-600 font-medium flex items-center gap-1.5 mt-1">
                              <i className="fa-solid fa-circle-exclamation text-[10px]" />
                              <span>{manualIdError}</span>
                            </p>
                          ) : manualPixelId.length >= 15 && manualPixelId.length <= 16 ? (
                            <p className="text-[11px] text-emerald-600 font-medium flex items-center gap-1.5 mt-1">
                              <i className="fa-solid fa-circle-check text-[10px]" />
                              <span>Valid Meta Pixel ID format ({manualPixelId.length} digits)</span>
                            </p>
                          ) : manualPixelId.length > 0 ? (
                            <p className="text-[11px] text-amber-600 font-medium flex items-center gap-1.5 mt-1">
                              <i className="fa-solid fa-circle-info text-[10px]" />
                              <span>Meta Pixel IDs are 15-16 digits ({15 - manualPixelId.length > 0 ? `${15 - manualPixelId.length} more digits needed` : ''})</span>
                            </p>
                          ) : null}
                        </div>

                        {/* Information Callout */}
                        <div className="flex items-start gap-2.5 p-3.5 rounded-xl bg-theme/5 border border-theme/20 text-[11px] text-slate-800 leading-relaxed">
                          <i className="fa-solid fa-circle-info text-theme mt-0.5 shrink-0 text-xs" />
                          <p>
                            Your pixel will track all storefront pages by default. Advanced page tracking and collection routing can be customized later in your Pixel Manager.
                          </p>
                        </div>
                      </div>
                    )}
                  </div>
                )}

                {/* STEP 2 CONTENT (Matching Omega Facebook Pixel & CAPI layout) */}
                {currentStep === 2 && (
                  <div className="space-y-6">
                    <div className="border-b border-slate-100 pb-4">
                      <div className="flex items-start justify-between gap-4">
                        <div className="space-y-1">
                          <div className="flex items-center gap-2">
                            <h3 className="text-base font-extrabold text-black">
                              Conversions API (solution for iOS 14.5)
                            </h3>
                            <span className="bg-sky-50 text-sky-700 border border-sky-200 text-[10px] font-extrabold px-2 py-0.5 rounded-full">
                              Recommended
                            </span>
                            <button
                              type="button"
                              onClick={() => setGuideModalSlug('how-to-generate-capi-access-token')}
                              className="inline-flex items-center gap-1 px-2 py-0.5 rounded-md bg-slate-100 text-slate-700 hover:bg-slate-200 text-[11px] font-medium border border-slate-200/80 transition-colors ml-1 cursor-pointer"
                              title="How to Generate CAPI Access Token Guide Popup"
                            >
                              <i className="fa fa-book-open text-[10px] text-slate-500" />
                              <span>Token Guide</span>
                            </button>
                          </div>
                          <p className="text-xs text-slate-600 leading-relaxed">
                            Enable server-side API to track all customer behavior events bypassing the browser's limitation, or ad-blockers.
                          </p>
                        </div>

                        {/* Conversions API Toggle Switch (Like Omega) */}
                        <button
                          type="button"
                          onClick={() => setCapiEnabled(!capiEnabled)}
                          className={`relative inline-flex h-6 w-11 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none shrink-0 mt-0.5 ${
                            capiEnabled ? 'bg-slate-900' : 'bg-slate-200'
                          }`}
                          title={capiEnabled ? 'Disable Conversions API' : 'Enable Conversions API'}
                        >
                          <span
                            className={`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${
                              capiEnabled ? 'translate-x-5' : 'translate-x-0'
                            }`}
                          />
                        </button>
                      </div>

                      {/* Value-Proposition Chips */}
                      {capiEnabled && (
                        <div className="grid grid-cols-1 sm:grid-cols-3 gap-2.5 pt-3">
                          <div className="flex items-center gap-2 p-2.5 rounded-xl bg-slate-50 border border-slate-200/80">
                            <i className="fa-solid fa-shield-halved text-theme text-xs" />
                            <span className="text-[11px] font-bold text-slate-800">iOS 14.5+ Protected</span>
                          </div>
                          <div className="flex items-center gap-2 p-2.5 rounded-xl bg-slate-50 border border-slate-200/80">
                            <i className="fa-solid fa-bolt text-theme text-xs" />
                            <span className="text-[11px] font-bold text-slate-800">100% Server Delivery</span>
                          </div>
                          <div className="flex items-center gap-2 p-2.5 rounded-xl bg-slate-50 border border-slate-200/80">
                            <i className="fa-solid fa-chart-line text-theme text-xs" />
                            <span className="text-[11px] font-bold text-slate-800">8.5+ Event Match</span>
                          </div>
                        </div>
                      )}
                    </div>

                    {capiEnabled ? (
                      <div className="space-y-5">
                        {/* Conversions API Access Token Input Box */}
                        <div className="space-y-1.5">
                          <div className="flex items-center justify-between">
                            <div className="flex items-center gap-2">
                              <label className="text-xs font-bold text-slate-800 flex items-center gap-1.5">
                                <i className="fa-solid fa-key text-slate-400 text-xs" />
                                <span>Conversions API Access Token</span>
                                <span className="text-theme">*</span>
                              </label>
                              <button
                                type="button"
                                onClick={() => setHelpModal('access_token')}
                                className="text-[11px] text-theme hover:underline font-semibold flex items-center gap-1 cursor-pointer"
                              >
                                <i className="fa-regular fa-circle-question text-[10px]" />
                                <span>Where do I get it?</span>
                              </button>
                            </div>
                            <div className="flex items-center gap-2.5">
                              {accessToken.trim() && (
                                <button
                                  type="button"
                                  onClick={() => {
                                    setAccessToken('');
                                    setTokenVerified(false);
                                    setTokenVerificationError(null);
                                    setTokenInfo(null);
                                  }}
                                  className="text-[11px] font-semibold text-slate-400 hover:text-rose-600 cursor-pointer transition-colors"
                                  title="Clear token"
                                >
                                  Clear
                                </button>
                              )}
                              {accessToken.trim() && (
                                <button
                                  type="button"
                                  onClick={() => verifyMetaToken(accessToken, false)}
                                  disabled={isVerifyingToken}
                                  className="text-[11px] font-bold text-theme hover:underline flex items-center gap-1 cursor-pointer disabled:opacity-50"
                                >
                                  <i className={`fa-solid ${isVerifyingToken ? 'fa-spinner fa-spin' : 'fa-shield-check'} text-[10px]`} />
                                  <span>{isVerifyingToken ? 'Verifying...' : 'Verify Token'}</span>
                                </button>
                              )}
                            </div>
                          </div>

                          <div className="relative">
                            <input
                              type={showToken ? 'text' : 'password'}
                              value={accessToken}
                              onChange={(e) => {
                                const val = e.target.value;
                                setAccessToken(val);
                                setTokenVerified(false);
                                setTokenInfo(null);
                                if (val.trim().startsWith('EAGR')) {
                                  setTokenVerificationError(
                                    'Facebook App Login Token Detected (starts with EAGR). This is the login token from connecting your account, NOT a Conversions API token. Please generate a Conversions API token from Meta Events Manager > Settings > Set up direct integration (Set up with Dataset Quality API).'
                                  );
                                } else {
                                  setTokenVerificationError(null);
                                }
                              }}
                              placeholder="Paste Dataset Quality API token from Events Manager (starts with EAAdAd... or EAA...)"
                              className={`w-full p-2.5 pr-10 rounded-xl border text-xs bg-white font-mono text-slate-800 shadow-2xs focus:outline-none focus:ring-2 transition-all ${
                                tokenVerificationError
                                  ? 'border-rose-400 focus:ring-rose-200 focus:border-rose-500 bg-rose-50/20'
                                  : tokenVerified
                                  ? 'border-emerald-400 focus:ring-emerald-200 focus:border-emerald-500 bg-emerald-50/10'
                                  : 'border-slate-200 focus:ring-theme/20 focus:border-theme'
                              }`}
                            />
                            <button
                              type="button"
                              onClick={() => setShowToken(!showToken)}
                              className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-black cursor-pointer p-1"
                              title={showToken ? 'Hide token' : 'Show token'}
                            >
                              <i className={`fa-solid ${showToken ? 'fa-eye-slash' : 'fa-eye'} text-xs`} />
                            </button>
                          </div>

                          {/* Helper Info Note */}
                          {!accessToken.trim() && !tokenVerificationError && (
                            <p className="text-[11px] text-slate-500 mt-1 flex items-center justify-between">
                              <span>Enter the token from Events Manager &gt; Set up direct integration. Tokens start with <code className="bg-slate-100 px-1 py-0.5 rounded font-mono">EAA...</code>.</span>
                            </p>
                          )}

                          {/* Loading State */}
                          {isVerifyingToken && (
                            <div className="flex items-center gap-2 p-2.5 rounded-xl bg-blue-50 border border-blue-200 text-blue-900 text-xs mt-2">
                              <div className="w-3.5 h-3.5 border-2 border-blue-600 border-t-transparent rounded-full animate-spin shrink-0" />
                              <span>Verifying token with Meta Dataset Quality API for Dataset {effectivePixelId || '...'}</span>
                            </div>
                          )}

                          {/* Verified Success Banner */}
                          {!isVerifyingToken && tokenVerified && (
                            <div className="p-3.5 rounded-xl bg-emerald-50 border border-emerald-200 text-emerald-950 text-xs space-y-1 shadow-2xs mt-2">
                              <div className="flex items-center justify-between">
                                <div className="flex items-center gap-2">
                                  <i className="fa-solid fa-circle-check text-emerald-600 text-sm" />
                                  <span className="font-bold text-emerald-950">
                                    Conversions API Token Verified &amp; Connected
                                  </span>
                                </div>
                                <span className="text-[10px] font-extrabold bg-emerald-200 text-emerald-900 px-2 py-0.5 rounded-full">
                                  Dataset Quality API Active
                                </span>
                              </div>
                              <p className="text-[11px] text-emerald-800 pl-5 leading-relaxed">
                                Direct permission confirmed for Meta Dataset <strong>{tokenInfo?.name || effectivePixelName}</strong> (ID: {tokenInfo?.id || effectivePixelId}). Server-side tracking is ready.
                              </p>
                            </div>
                          )}

                          {/* Error Alert Banner */}
                          {!isVerifyingToken && tokenVerificationError && (
                            <div className="p-3.5 rounded-xl bg-rose-50 border border-rose-200 text-rose-950 text-xs space-y-1.5 shadow-2xs mt-2">
                              <div className="flex items-start gap-2">
                                <i className="fa-solid fa-circle-exclamation text-rose-600 mt-0.5 text-xs shrink-0" />
                                <div className="flex-1">
                                  <div className="flex items-center justify-between">
                                    <span className="font-bold text-rose-950">Invalid Conversions API Access Token</span>
                                    <span className="text-[10px] font-extrabold bg-rose-200 text-rose-900 px-1.5 py-0.5 rounded">
                                      Rejected by Meta
                                    </span>
                                  </div>
                                  <p className="text-[11px] text-rose-800 mt-1 leading-relaxed">
                                    {tokenVerificationError}
                                  </p>
                                </div>
                              </div>
                              <div className="pl-5 pt-0.5 flex items-center justify-end">
                                <a
                                  href={eventsManagerSettingsUrl}
                                  target="_blank"
                                  rel="noopener noreferrer"
                                  className="text-[11px] text-[#1877F2] font-bold hover:underline inline-flex items-center gap-1"
                                >
                                  <span>Open Meta Events Manager</span>
                                  <i className="fa-solid fa-arrow-up-right-from-square text-[9px]" />
                                </a>
                              </div>
                            </div>
                          )}
                        </div>

                        {/* Test Event Code Field (Matching Omega screenshot) */}
                        <div className="space-y-1.5">
                          <div className="flex items-center justify-between">
                            <div className="flex items-center gap-2">
                              <label className="text-xs font-bold text-slate-800 flex items-center gap-1.5">
                                <i className="fa-solid fa-vial text-slate-400 text-xs" />
                                <span>Test event code</span>
                              </label>
                              <button
                                type="button"
                                onClick={() => setHelpModal('test_code')}
                                className="text-[11px] text-theme hover:underline font-semibold flex items-center gap-1 cursor-pointer"
                              >
                                <i className="fa-regular fa-circle-question text-[10px]" />
                                <span>Where do I get it?</span>
                              </button>
                            </div>
                            <span className="text-[10px] text-slate-400 font-mono">
                              {testEventCode.length}/20
                            </span>
                          </div>

                          <div className="relative">
                            <input
                              type="text"
                              maxLength={20}
                              value={testEventCode}
                              onChange={(e) => setTestEventCode(e.target.value)}
                              placeholder=""
                              className="w-full p-2.5 rounded-xl border border-slate-200 text-xs bg-white font-mono text-slate-800 shadow-2xs focus:outline-none focus:ring-2 focus:ring-theme/20 focus:border-theme transition-all"
                            />
                          </div>
                          <p className="text-[11px] text-slate-500 leading-normal">
                            Use this if you need to test the server-side event. Remove it after testing.
                          </p>
                        </div>
                      </div>
                    ) : (
                      <div className="p-4 rounded-2xl bg-slate-50 border border-slate-200/80 text-xs text-slate-600 space-y-1">
                        <p className="font-semibold text-slate-800">Conversions API is currently paused</p>
                        <p className="text-[11px] text-slate-500">
                          Toggle the switch above to enable server-side tracking and bypass browser ad-blockers.
                        </p>
                      </div>
                    )}
                  </div>
                )}

                {/* STEP 3 CONTENT */}
                {currentStep === 3 && (
                  <div className="space-y-6">
                    <div className="border-b border-slate-100 pb-4">
                      <div className="flex items-center gap-2">
                        <h3 className="text-base font-extrabold text-black">
                          Activate Storefront App Embed
                        </h3>
                        <button
                          type="button"
                          onClick={() => setGuideModalSlug('app-checklist')}
                          className="inline-flex items-center gap-1 px-2 py-0.5 rounded-md bg-slate-100 text-slate-700 hover:bg-slate-200 text-[11px] font-medium border border-slate-200/80 transition-colors cursor-pointer"
                          title="Open App Embed Checklist Guide Popup"
                        >
                          <i className="fa fa-book-open text-[10px] text-slate-500" />
                          <span>Checklist Guide</span>
                        </button>
                        <span className="bg-theme/10 text-theme border border-theme/20 text-[10px] font-bold px-2 py-0.5 rounded-full">
                          Required for Tracking
                        </span>
                      </div>
                      <p className="text-xs text-slate-600 mt-1 leading-relaxed">
                        Enable the lightweight storefront script in your Shopify Theme Editor to activate client-side tracking and server deduplication.
                      </p>
                    </div>

                    {/* Step-by-Step Instruction Guide */}
                    <div className="p-5 rounded-2xl bg-gradient-to-br from-slate-50 to-white border border-slate-200/90 space-y-4 shadow-2xs">
                      <div className="flex items-center justify-between border-b border-slate-200/60 pb-3">
                        <span className="text-xs font-bold text-slate-800 flex items-center gap-1.5">
                          <i className="fa-solid fa-list-check text-theme text-xs" />
                          <span>Quick 2-Step Theme Setup</span>
                        </span>
                        <a
                          href={themeEditorUrl}
                          onClick={handleOpenThemeEditor}
                          target="_blank"
                          rel="noreferrer"
                          className="px-4 py-2 rounded-xl text-xs font-bold bg-black hover:bg-theme text-white shadow-2xs transition-colors inline-flex items-center gap-1.5 cursor-pointer"
                        >
                          <span>Open Theme Editor</span>
                          <i className="fa-solid fa-arrow-up-right-from-square text-[10px]" />
                        </a>
                      </div>

                      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 text-xs">
                        <div className="p-3.5 rounded-xl bg-white border border-slate-200/80 space-y-1">
                          <div className="flex items-center gap-2">
                            <span className="w-5 h-5 rounded-full bg-black text-white flex items-center justify-center text-[10px] font-bold">
                              1
                            </span>
                            <span className="font-bold text-slate-900">Turn On App Embed</span>
                          </div>
                          <p className="text-[11px] text-slate-500 leading-relaxed pl-7">
                            In Theme Editor, expand <strong>App embeds</strong> in the left sidebar and toggle ON <strong>Meta Pixel &amp; CAPI Tracker</strong>.
                          </p>
                        </div>

                        <div className="p-3.5 rounded-xl bg-white border border-slate-200/80 space-y-1">
                          <div className="flex items-center gap-2">
                            <span className="w-5 h-5 rounded-full bg-black text-white flex items-center justify-center text-[10px] font-bold">
                              2
                            </span>
                            <span className="font-bold text-slate-900">Save Changes</span>
                          </div>
                          <p className="text-[11px] text-slate-500 leading-relaxed pl-7">
                            Click the green <strong>Save</strong> button in the top right corner of the Theme Editor window.
                          </p>
                        </div>
                      </div>
                    </div>

                    {/* Real-time Verification Status Banner */}
                    {isVerifyingEmbed && (
                      <div className="p-4 rounded-xl bg-blue-50 border border-blue-200 text-blue-900 flex items-center gap-3 shadow-2xs">
                        <div className="w-5 h-5 border-2 border-blue-600 border-t-transparent rounded-full animate-spin shrink-0" />
                        <div className="text-xs">
                          <span className="font-bold">Verifying Theme App Embed with Shopify...</span>
                          <p className="text-blue-700 text-[11px] mt-0.5">
                            Checking your published theme to confirm the Meta Pixel tracking snippet is active.
                          </p>
                        </div>
                      </div>
                    )}

                    {!isVerifyingEmbed && embedVerificationError && (
                      <div className="p-4 rounded-xl bg-amber-50 border border-amber-300 text-amber-950 flex items-start gap-3 shadow-2xs">
                        <i className="fa-solid fa-triangle-exclamation text-amber-600 mt-0.5 text-base shrink-0" />
                        <div className="flex-1 space-y-1.5">
                          <div className="flex items-center justify-between gap-2">
                            <h4 className="text-xs font-bold text-amber-950">App Embed Not Detected Yet</h4>
                            <span className="text-[10px] font-bold bg-amber-200 text-amber-900 px-2 py-0.5 rounded-full">
                              Required Before Launch
                            </span>
                          </div>
                          <p className="text-xs text-amber-800 leading-relaxed">
                            {embedVerificationError}
                          </p>
                          <div className="pt-2 flex flex-wrap items-center gap-2.5">
                            <button
                              type="button"
                              onClick={() => verifyThemeEmbed(false)}
                              disabled={isVerifyingEmbed}
                              className="px-3.5 py-1.5 rounded-lg text-xs font-bold bg-amber-700 hover:bg-amber-800 text-white shadow-xs inline-flex items-center gap-1.5 cursor-pointer disabled:opacity-50"
                            >
                              <i className="fa-solid fa-rotate-right text-[11px]" />
                              <span>Re-verify App Embed</span>
                            </button>
                            <button
                              type="button"
                              onClick={handleOpenThemeEditor}
                              className="px-3.5 py-1.5 rounded-lg text-xs font-bold bg-white border border-amber-300 hover:bg-amber-100 text-amber-950 shadow-2xs inline-flex items-center gap-1.5 cursor-pointer"
                            >
                              <span>Open Theme Editor</span>
                              <i className="fa-solid fa-arrow-up-right-from-square text-[10px]" />
                            </button>
                          </div>
                        </div>
                      </div>
                    )}

                    {!isVerifyingEmbed && !embedVerificationError && appEmbedChecked && (
                      <div className="p-4 rounded-xl bg-emerald-50 border border-emerald-200 text-emerald-900 flex items-center justify-between gap-3 shadow-2xs">
                        <div className="flex items-center gap-2.5">
                          <div className="w-8 h-8 rounded-full bg-emerald-600 text-white flex items-center justify-center text-xs shrink-0">
                            <i className="fa-solid fa-check" />
                          </div>
                          <div>
                            <h4 className="text-xs font-bold text-emerald-950 flex items-center gap-1.5">
                              <span>App Embed Verified Active</span>
                              <span className="text-[9px] font-extrabold uppercase px-1.5 py-0.2 rounded bg-emerald-200/80 text-emerald-800">
                                Verified
                              </span>
                            </h4>
                            <p className="text-[11px] text-emerald-700 mt-0.5">
                              Theme app embed is confirmed active on your live theme. You can now launch tracking.
                            </p>
                          </div>
                        </div>
                        <button
                          type="button"
                          onClick={() => verifyThemeEmbed(false)}
                          disabled={isVerifyingEmbed}
                          title="Re-check Theme Embed status"
                          className="p-2 text-emerald-700 hover:text-emerald-900 hover:bg-emerald-100 rounded-lg transition-colors cursor-pointer"
                        >
                          <i className="fa-solid fa-rotate-right text-xs" />
                        </button>
                      </div>
                    )}

                    {!isVerifyingEmbed && !embedVerificationError && !appEmbedChecked && (
                      <div className="p-4 rounded-xl bg-slate-50 border border-slate-200/90 text-slate-700 flex items-center justify-between gap-3 shadow-2xs">
                        <div className="flex items-center gap-2.5">
                          <div className="w-8 h-8 rounded-full bg-slate-200 text-slate-600 flex items-center justify-center text-xs shrink-0">
                            <i className="fa-solid fa-shield-halved" />
                          </div>
                          <div>
                            <h4 className="text-xs font-bold text-slate-900">Verification Required</h4>
                            <p className="text-[11px] text-slate-500 mt-0.5">
                              Turn ON &apos;Meta Pixel &amp; CAPI Tracker&apos; in Theme Editor, click Save, then click verify.
                            </p>
                          </div>
                        </div>
                        <button
                          type="button"
                          onClick={() => verifyThemeEmbed(false)}
                          disabled={isVerifyingEmbed}
                          className="px-3.5 py-1.5 rounded-lg text-xs font-bold bg-theme hover:bg-theme-hover text-white shadow-2xs inline-flex items-center gap-1.5 cursor-pointer disabled:opacity-50"
                        >
                          <i className="fa-solid fa-magnifying-glass text-[11px]" />
                          <span>Verify Status</span>
                        </button>
                      </div>
                    )}

                    {/* Interactive Confirmation Toggle Card */}
                    <label
                      className={`flex items-start sm:items-center gap-3.5 p-4 rounded-2xl border transition-all cursor-pointer ${
                        appEmbedChecked
                          ? 'bg-theme/5 border-theme shadow-2xs ring-2 ring-theme/15'
                          : 'bg-white border-slate-200/90 hover:bg-slate-50'
                      }`}
                    >
                      <input
                        type="checkbox"
                        checked={appEmbedChecked}
                        onChange={(e) => handleCheckboxToggle(e.target.checked)}
                        disabled={isVerifyingEmbed}
                        className="mt-0.5 sm:mt-0 w-5 h-5 rounded-md text-theme focus:ring-theme transition-all cursor-pointer accent-theme"
                      />
                      <div className="flex-1">
                        <div className="flex items-center justify-between">
                          <span className="text-xs font-bold text-slate-900">
                            I&apos;ve turned on and saved the embedded app
                          </span>
                          {appEmbedChecked ? (
                            <span className="text-[10px] font-extrabold text-white bg-theme px-2 py-0.5 rounded-full flex items-center gap-1">
                              <i className="fa-solid fa-check text-[9px]" />
                              Verified Active
                            </span>
                          ) : (
                            <span className="text-[10px] font-bold text-slate-400 bg-slate-100 px-2 py-0.5 rounded-full">
                              Verification Required
                            </span>
                          )}
                        </div>
                        <p className="text-[11px] text-slate-500 mt-0.5">
                          Confirms storefront tracking snippet is published and active for all buyers.
                        </p>
                      </div>
                    </label>
                  </div>
                )}
              </div>

              {/* Step Navigation Bottom Bar */}
              <div className="bg-white rounded-2xl border border-slate-200/90 shadow-sm px-6 py-4 flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-3">
                <div>
                  {currentStep > 1 ? (
                    <button
                      type="button"
                      onClick={() => setCurrentStep((prev) => (prev - 1) as any)}
                      className="w-full sm:w-auto px-4 py-2 rounded-xl text-xs font-bold border border-slate-200 text-black hover:bg-slate-50 flex items-center justify-center gap-1.5 transition-colors cursor-pointer"
                    >
                      <i className="fa-solid fa-arrow-left text-[10px]" />
                      <span>Back</span>
                    </button>
                  ) : pixels.length > 0 ? (
                    <button
                      type="button"
                      onClick={navigateToPixelManager}
                      className="w-full sm:w-auto px-4 py-2 rounded-xl text-xs font-semibold text-slate-500 hover:text-black transition-colors cursor-pointer"
                    >
                      Cancel
                    </button>
                  ) : (
                    <div />
                  )}
                </div>

                <div className="flex items-center justify-center gap-2">
                  <span className="text-xs font-bold text-slate-700">
                    Step {currentStep} of 3
                  </span>
                  <div className="flex items-center gap-1.5">
                    {[1, 2, 3].map((s) => (
                      <div
                        key={s}
                        className={`w-2 h-2 rounded-full transition-all ${
                          currentStep === s
                            ? 'w-5 bg-theme'
                            : currentStep > s
                            ? 'bg-black'
                            : 'bg-slate-200'
                        }`}
                      />
                    ))}
                  </div>
                </div>

                <div className="flex items-center justify-end gap-2.5">

                  {currentStep === 1 && (
                    <div className="flex items-center gap-2">
                      {inputTab === 'manual' && (
                        <button
                          type="button"
                          onClick={async () => {
                            const cleanName = manualPixelName.trim();
                            const cleanId = manualPixelId.trim();
                            let hasErr = false;
                            if (!cleanName) {
                              setManualNameError('Pixel name is required');
                              hasErr = true;
                            } else if (cleanName.length > 255) {
                              setManualNameError('Pixel name cannot exceed 255 characters');
                              hasErr = true;
                            }
                            if (!cleanId) {
                              setManualIdError('Pixel ID is required');
                              hasErr = true;
                            } else if (!/^\d+$/.test(cleanId)) {
                              setManualIdError('Pixel ID must contain numbers only');
                              hasErr = true;
                            } else if (cleanId.length < 15 || cleanId.length > 16) {
                              setManualIdError(`Pixel ID must be 15 or 16 digits (currently ${cleanId.length} digits)`);
                              hasErr = true;
                            }
                            if (hasErr) return;
                            const duplicate = pixels.find((p) => p.pixel_id === cleanId);
                            if (duplicate) {
                              setManualIdError('This pixel is already added to this store.');
                              return;
                            }
                            const ok = await handleSavePixelDirectly(true, { id: cleanId, name: cleanName });
                            if (ok) {
                              navigateToPixelManager();
                              setToastMessage({ text: `Manual pixel "${cleanName}" saved successfully.`, type: 'success' });
                            }
                          }}
                          className="w-full sm:w-auto px-4 py-2.5 rounded-xl text-xs font-bold border border-slate-200 text-slate-700 hover:bg-slate-50 transition-colors cursor-pointer flex items-center justify-center gap-1.5"
                        >
                          <i className="fa-solid fa-floppy-disk text-[11px] text-slate-500" />
                          <span>Save Pixel</span>
                        </button>
                      )}
                      <button
                        type="button"
                        disabled={inputTab === 'auto' && !fbConnected}
                        onClick={handleNextStep1}
                        className="w-full sm:w-auto px-6 py-2.5 rounded-xl text-xs font-bold bg-theme hover:bg-theme-hover disabled:opacity-40 text-white shadow-sm hover:shadow-md transition-all flex items-center justify-center gap-1.5 cursor-pointer disabled:cursor-not-allowed"
                      >
                        <span>Next: Conversions API</span>
                        <i className="fa-solid fa-arrow-right text-[10px]" />
                      </button>
                    </div>
                  )}

                  {currentStep === 2 && (
                    <button
                      type="button"
                      disabled={isVerifyingToken}
                      onClick={handleNextStep2}
                      className="w-full sm:w-auto px-6 py-2.5 rounded-xl text-xs font-bold bg-theme hover:bg-theme-hover disabled:opacity-50 text-white shadow-sm hover:shadow-md transition-all flex items-center justify-center gap-1.5 cursor-pointer disabled:cursor-not-allowed"
                    >
                      {isVerifyingToken ? (
                        <>
                          <i className="fa-solid fa-spinner fa-spin text-[10px]" />
                          <span>Verifying with Facebook...</span>
                        </>
                      ) : (
                        <>
                          <span>Next: Activate App</span>
                          <i className="fa-solid fa-arrow-right text-[10px]" />
                        </>
                      )}
                    </button>
                  )}

                  {currentStep === 3 && (
                    <div className="flex items-center gap-2">
                      <button
                        type="button"
                        onClick={async () => {
                          await handleSavePixelDirectly(false);
                          navigateToPixelManager();
                        }}
                        className="px-4 py-2 rounded-xl text-xs font-semibold text-slate-500 hover:text-black hover:bg-slate-50 transition-colors cursor-pointer"
                      >
                        Skip &amp; View Pixels
                      </button>
                      <button
                        type="button"
                        disabled={isVerifyingEmbed}
                        onClick={handleNextStep3}
                        className="w-full sm:w-auto px-6 py-2.5 rounded-xl text-xs font-bold bg-theme hover:bg-theme-hover disabled:opacity-50 text-white shadow-sm hover:shadow-md transition-all flex items-center justify-center gap-1.5 cursor-pointer disabled:cursor-not-allowed"
                      >
                        {isVerifyingEmbed ? (
                          <>
                            <i className="fa-solid fa-spinner fa-spin text-[10px]" />
                            <span>Verifying Theme Embed...</span>
                          </>
                        ) : (
                          <>
                            <span>Complete Setup &amp; Launch</span>
                            <i className="fa-solid fa-rocket text-[10px]" />
                          </>
                        )}
                      </button>
                    </div>
                  )}
                </div>
              </div>
            </div>
          )}

          {/* ---------------------------------------------------------------- */}
          {/* STEP 4: CONGRATULATIONS COMPLETION VIEW */}
          {/* ---------------------------------------------------------------- */}
          {currentStep === 4 && (
            <div className="bg-white rounded-3xl border border-slate-200/90 shadow-lg p-8 sm:p-12 text-center space-y-8 max-w-2xl mx-auto my-6">
              {/* Celebration Icon */}
              <div className="relative mx-auto w-24 h-24">
                <img
                  src={normalizeAssetUrl(branding.logoUrl || '/images/logo.png')}
                  alt="Logo"
                  width={96}
                  height={96}
                  className="w-24 h-24 rounded-3xl object-contain shadow-xl shadow-theme/20 border border-slate-100 p-1 bg-white"
                />
                <div className="absolute -top-2 -right-2 w-8 h-8 rounded-full bg-black text-white flex items-center justify-center text-sm shadow-md animate-bounce">
                  ✨
                </div>
              </div>

              <div className="space-y-2">
                <div className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-theme/10 border border-theme/20 text-theme text-xs font-bold">
                  <i className="fa-solid fa-circle-check text-theme text-xs" />
                  <span>Setup Successfully Completed</span>
                </div>
                <h1 className="text-2xl sm:text-3xl font-black text-black tracking-tight">
                  Congratulations!
                </h1>
                <p className="text-xs sm:text-sm text-slate-600 max-w-md mx-auto leading-relaxed">
                  Your Meta Commerce &amp; Conversions API integration is live. Event data is now tracking with server-side redundancy.
                </p>
              </div>

              {/* Summary of Configured Setup */}
              <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 text-left">
                <div className="p-3.5 rounded-xl bg-slate-50 border border-slate-200/80 space-y-1">
                  <span className="text-[10px] font-black uppercase tracking-wider text-slate-400">
                    Configured Pixel
                  </span>
                  <p className="text-xs font-bold text-black truncate">
                    {pixelName || 'Master Pixel'}
                  </p>
                  <p className="text-[10px] font-mono text-slate-500 truncate">
                    {finalSelectedPixelId || 'Active'}
                  </p>
                </div>

                <div className="p-3.5 rounded-xl bg-slate-50 border border-slate-200/80 space-y-1">
                  <span className="text-[10px] font-black uppercase tracking-wider text-slate-400">
                    Conversions API
                  </span>
                  <div className="flex items-center gap-1 text-xs font-bold text-theme">
                    <span className="w-1.5 h-1.5 rounded-full bg-theme animate-pulse" />
                    <span>Server Active</span>
                  </div>
                  <p className="text-[10px] text-slate-500">Deduplication Ready</p>
                </div>

                <div className="p-3.5 rounded-xl bg-slate-50 border border-slate-200/80 space-y-1">
                  <span className="text-[10px] font-black uppercase tracking-wider text-slate-400">
                    App Embed
                  </span>
                  <div className={`flex items-center gap-1 text-xs font-bold ${appEmbedChecked ? 'text-theme' : 'text-amber-600'}`}>
                    <i className={`fa-solid ${appEmbedChecked ? 'fa-check' : 'fa-triangle-exclamation'} text-[10px]`} />
                    <span>{appEmbedChecked ? 'Theme Enabled' : 'Not Turned On'}</span>
                  </div>
                  <p className="text-[10px] text-slate-500">Shopify Storefront</p>
                </div>
              </div>

              <div className="flex flex-wrap items-center justify-center gap-3 pt-2">
                <button
                  type="button"
                  onClick={() => setCurrentStep(3)}
                  className="px-4 py-2.5 rounded-xl text-xs font-bold border border-slate-200 text-black hover:bg-slate-50 flex items-center gap-1.5 transition-colors cursor-pointer"
                >
                  <i className="fa-solid fa-arrow-left text-[10px]" />
                  <span>Back</span>
                </button>

                <button
                  type="button"
                  onClick={handleFinishOnboarding}
                  className="px-5 py-2.5 rounded-xl text-xs font-bold border border-slate-200 text-black hover:bg-slate-50 transition-colors cursor-pointer"
                >
                  Go to Pixel Manager
                </button>

                <Link
                  href={`/catalog/create?pixelId=${encodeURIComponent(finalSelectedPixelId || '')}${currentShop ? `&shop=${encodeURIComponent(currentShop)}` : ''}`}
                  onClick={() => handleSavePixelDirectly(true)}
                  className="px-5 py-2.5 rounded-xl text-xs font-bold bg-theme hover:bg-theme-hover text-white shadow-md hover:shadow-lg transition-all flex items-center gap-2 cursor-pointer"
                >
                  <i className="fa-solid fa-layer-group text-xs" />
                  <span>Configure Catalogs &amp; Feeds</span>
                  <i className="fa-solid fa-arrow-right text-[10px]" />
                </Link>

                <button
                  type="button"
                  onClick={handleRunVerification}
                  className="px-5 py-2.5 rounded-xl text-xs font-bold border border-slate-200 text-slate-700 hover:bg-slate-50 transition-colors flex items-center gap-1.5 cursor-pointer"
                >
                  <i className="fa-solid fa-shield-halved text-xs text-slate-400" />
                  <span>Verify setup health</span>
                </button>
              </div>
            </div>
          )}
        </main>

        {/* Render Help & Facebook Auth Modals */}
        {renderModals()}
      </div>
    );
  }

  // =========================================================================
  // RENDER MAIN DASHBOARD VIEW (SCREENSHOT 10: media_1790753256063.png)
  // =========================================================================
  return (
    <AppLayout
      currentRoute="/pixel"
      showAddPixelButton={true}
      onAddPixel={handleOpenAddPixel}
    >
      <ui-title-bar title="Facebook Pixel & CAPI">
        <button variant="primary" onClick={handleOpenAddPixel}>Add pixel</button>
      </ui-title-bar>
      <div className="space-y-6">
        {/* Top Action Row: Search bar & Add Pixel button */}
        <div className="flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-3">
          <div className="relative flex-1 max-w-md">
            <i className="fa-solid fa-magnifying-glass text-slate-400 text-xs absolute left-3.5 top-1/2 -translate-y-1/2" />
            <input
              type="text"
              value={searchQuery}
              onChange={(e) => {
                setSearchQuery(e.target.value);
                setCurrentPage(1);
              }}
              placeholder="Search by pixel name, pixel ID"
              className="w-full pl-9 pr-4 py-2 text-xs rounded-xl border border-slate-200 bg-white shadow-sm focus:outline-none focus:ring-1 focus:ring-slate-900"
            />
          </div>

          <button
            onClick={handleOpenAddPixel}
            className="px-4 py-2 rounded-xl text-xs font-bold bg-slate-900 hover:bg-slate-800 text-white flex items-center justify-center gap-1.5 shadow-sm transition-colors cursor-pointer shrink-0"
          >
            <i className="fa-solid fa-plus text-xs" />
            <span>Add pixel</span>
          </button>
        </div>

        {/* App Embed Status Notice (Omega style) */}
        {pixels.length > 0 &&
          !appEmbedChecked &&
          embedStatus !== 'verified' &&
          !pixels.some((p) => Boolean(p.app_embed_active)) &&
          !appEmbedNoticeDismissed && (
          <div className="p-3.5 rounded-xl bg-amber-50 border border-amber-200/90 text-amber-900 flex flex-col sm:flex-row sm:items-center justify-between gap-3 text-xs shadow-2xs">
            <div className="flex items-center gap-2.5">
              <i className="fa-solid fa-triangle-exclamation text-amber-600 text-sm shrink-0" />
              <span>
                <strong>Storefront App Embed is off:</strong> Turn on &quot;Meta Pixel &amp; CAPI Tracker&quot; in Theme Editor to activate client-side tracking.
              </span>
            </div>
            <div className="flex items-center gap-2 shrink-0">
              <button
                type="button"
                onClick={async () => {
                  const verified = await verifyThemeEmbed(false);
                  if (verified) {
                    setAppEmbedNoticeDismissed(true);
                  }
                }}
                disabled={isVerifyingEmbed}
                className="px-2.5 py-1.5 rounded-lg text-xs font-semibold border border-amber-300 bg-white hover:bg-amber-100/50 text-amber-900 transition-colors cursor-pointer"
              >
                {isVerifyingEmbed ? 'Checking...' : 'Check Status'}
              </button>
              <a
                href={themeEditorUrl}
                onClick={handleOpenThemeEditor}
                target="_blank"
                rel="noreferrer"
                className="px-3 py-1.5 rounded-lg text-xs font-bold bg-amber-700 hover:bg-amber-800 text-white shadow-xs inline-flex items-center justify-center gap-1.5 shrink-0 transition-colors"
              >
                <span>Open Theme Editor</span>
                <i className="fa-solid fa-arrow-up-right-from-square text-[10px]" />
              </a>
              <button
                type="button"
                onClick={() => setAppEmbedNoticeDismissed(true)}
                className="p-1.5 text-amber-600 hover:text-amber-900 transition-colors cursor-pointer"
                title="Dismiss warning"
              >
                <i className="fa-solid fa-xmark text-xs" />
              </button>
            </div>
          </div>
        )}

        {/* Pixels Table (Matching Screenshot 10 with polished responsive UI) */}
        <div className="bg-white rounded-2xl border border-slate-200/90 shadow-xs overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full text-left text-xs min-w-[640px]">
              <thead className="bg-slate-50/80 border-b border-slate-200/80 text-slate-400 font-bold uppercase text-[10px] tracking-wider">
                <tr>
                  <th className="py-3 px-4 sm:px-5 w-24">Active</th>
                  <th className="py-3 px-4 sm:px-5">Pixel ID</th>
                  <th className="py-3 px-4 sm:px-5">Pixel Name</th>
                  <th className="py-3 px-4 sm:px-5">Pages</th>
                  <th className="py-3 px-4 sm:px-5">Conversion API</th>
                  <th className="py-3 px-4 sm:px-5 text-right">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {paginatedPixels.length === 0 ? (
                  <tr>
                    <td colSpan={6} className="py-12 text-center text-slate-500 text-xs">
                      {searchQuery.trim() ? (
                        <div className="space-y-1">
                          <i className="fa-solid fa-magnifying-glass text-slate-300 text-base mb-1 block" />
                          <p className="font-semibold text-slate-600">No pixels found matching &quot;{searchQuery}&quot;</p>
                          <p className="text-[11px] text-slate-400">Try searching with a different name or pixel ID.</p>
                        </div>
                      ) : (
                        <div className="py-6 text-center space-y-3">
                          <div className="w-10 h-10 rounded-full bg-slate-100 text-slate-400 flex items-center justify-center mx-auto text-sm">
                            <i className="fa-brands fa-facebook" />
                          </div>
                          <div>
                            <p className="text-xs font-bold text-slate-800">No Meta Pixels added yet</p>
                            <p className="text-[11px] text-slate-400 mt-0.5">Add your first pixel to start tracking visitors and purchases.</p>
                          </div>
                          <button
                            type="button"
                            onClick={handleOpenAddPixel}
                            className="px-4 py-2 rounded-xl text-xs font-bold bg-theme hover:bg-theme-hover text-white shadow-2xs transition-colors cursor-pointer inline-flex items-center gap-1.5"
                          >
                            <i className="fa-solid fa-plus text-[10px]" />
                            <span>Add Pixel</span>
                          </button>
                        </div>
                      )}
                    </td>
                  </tr>
                ) : (
                  paginatedPixels.map((pixel) => (
                    <tr key={pixel.id} className="hover:bg-slate-50/70 transition-colors">
                      {/* Active Toggle Switch */}
                      <td className="py-4 px-4 sm:px-5">
                        <button
                          type="button"
                          onClick={() => handleToggleActive(pixel)}
                          className={`w-9 h-5 flex items-center rounded-full p-0.5 transition-colors cursor-pointer ${
                            pixel.is_active !== false ? 'bg-theme' : 'bg-slate-200'
                          }`}
                        >
                          <div
                            className={`bg-white w-4 h-4 rounded-full shadow-md transform transition-transform ${
                              pixel.is_active !== false ? 'translate-x-4' : 'translate-x-0'
                            }`}
                          />
                        </button>
                      </td>

                      {/* Pixel ID with Copy */}
                      <td className="py-4 px-4 sm:px-5 font-mono text-slate-700">
                        <div className="flex items-center gap-1.5">
                          <span className="font-semibold text-slate-800">{pixel.pixel_id}</span>
                          <button
                            onClick={() => copyToClipboard(pixel.pixel_id, pixel.id)}
                            className="text-slate-400 hover:text-slate-700 p-1 rounded-md hover:bg-slate-100 transition-colors cursor-pointer"
                            title="Copy ID"
                          >
                            {copiedId === pixel.id ? (
                              <i className="fa-solid fa-check text-emerald-600 text-xs" />
                            ) : (
                              <i className="fa-regular fa-copy text-xs" />
                            )}
                          </button>
                        </div>
                      </td>

                      {/* Pixel Name */}
                      <td className="py-4 px-4 sm:px-5 font-bold text-slate-900">
                        <span className="text-slate-900 font-bold">{pixel.pixel_name || '—'}</span>
                      </td>

                      {/* Pages Badge */}
                      <td className="py-4 px-4 sm:px-5">
                        <span className="px-2.5 py-1 rounded-full text-[11px] font-semibold bg-slate-100/80 text-slate-700 border border-slate-200/60 shadow-2xs whitespace-nowrap">
                          {pixel.target_collection === 'all'
                            ? 'All pages'
                            : `Collection: ${pixel.target_collection}`}
                        </span>
                      </td>

                      {/* Conversion API Toggle Switch */}
                      <td className="py-4 px-4 sm:px-5">
                        <div className="flex items-center gap-2">
                          <button
                            type="button"
                            onClick={() => handleToggleCapi(pixel)}
                            className={`w-9 h-5 flex items-center rounded-full p-0.5 transition-colors cursor-pointer shrink-0 ${
                              pixel.capi_enabled ? 'bg-theme' : 'bg-slate-200'
                            }`}
                          >
                            <div
                              className={`bg-white w-4 h-4 rounded-full shadow-md transform transition-transform ${
                                pixel.capi_enabled ? 'translate-x-4' : 'translate-x-0'
                              }`}
                            />
                          </button>
                          {pixel.capi_enabled && (
                            <span className="inline-flex items-center gap-1 text-[10px] font-bold text-emerald-700 bg-emerald-50 border border-emerald-200/60 px-2 py-0.5 rounded-full whitespace-nowrap">
                              <span className="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse" />
                              CAPI Active
                            </span>
                          )}
                        </div>
                      </td>

                      {/* Actions: Edit & Delete */}
                      <td className="py-4 px-4 sm:px-5 text-right">
                        <div className="flex items-center justify-end gap-1.5">
                          <button
                            onClick={() => handleOpenEditPixel(pixel)}
                            className="p-1.5 text-slate-400 hover:text-slate-700 hover:bg-slate-100 rounded-lg transition-colors cursor-pointer"
                            title="Edit Pixel"
                          >
                            <i className="fa-solid fa-pen-to-square text-xs" />
                          </button>
                          <button
                            onClick={() => setDeletingPixel(pixel)}
                            className="p-1.5 text-slate-400 hover:text-rose-600 hover:bg-rose-50 rounded-lg transition-colors cursor-pointer"
                            title="Delete Pixel"
                          >
                            <i className="fa-regular fa-trash-can text-xs" />
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>

          {/* Table Footer: Pagination & Rows Per Page */}
          <div className="px-4 sm:px-5 py-3 border-t border-slate-100 bg-white flex flex-col sm:flex-row items-center justify-between gap-3 text-xs text-slate-500">
            <div className="flex items-center gap-2">
              <span className="text-slate-400">Rows per page:</span>
              <select
                value={rowsPerPage}
                onChange={(e) => {
                  setRowsPerPage(Number(e.target.value));
                  setCurrentPage(1);
                }}
                className="px-2 py-1 rounded-lg border border-slate-200 text-xs bg-white text-slate-700 focus:outline-none"
              >
                <option value={5}>5</option>
                <option value={10}>10</option>
                <option value={20}>20</option>
              </select>
            </div>

            <div className="flex items-center gap-3">
              <span className="font-mono">
                {currentPage} of {totalPages}
              </span>
              <div className="flex items-center gap-1">
                <button
                  onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
                  disabled={currentPage === 1}
                  className="p-1 px-2 rounded border border-slate-200 disabled:opacity-30 hover:bg-slate-50 text-xs cursor-pointer"
                >
                  <i className="fa-solid fa-chevron-left text-[10px]" />
                </button>
                <button
                  onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
                  disabled={currentPage === totalPages}
                  className="p-1 px-2 rounded border border-slate-200 disabled:opacity-30 hover:bg-slate-50 text-xs cursor-pointer"
                >
                  <i className="fa-solid fa-chevron-right text-[10px]" />
                </button>
              </div>
            </div>
          </div>
        </div>

        {/* Live CAPI Test Dispatcher */}
        <div style={{ display: 'none' }} className="bg-white rounded-2xl border border-slate-200/90 shadow-xs p-5 sm:p-6 space-y-4">
          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 border-b border-slate-100 pb-3">
            <div className="flex items-center gap-2">
              <div className="w-7 h-7 rounded-lg bg-amber-50 text-amber-600 flex items-center justify-center shrink-0">
                <i className="fa-solid fa-bolt text-xs" />
              </div>
              <div>
                <h3 className="font-bold text-xs text-slate-900 uppercase tracking-wider">
                  Live CAPI Server Test Dispatcher
                </h3>
                <p className="text-[11px] text-slate-400">Meta Graph API {META_CONFIG.graphVersion} Edge verification</p>
              </div>
            </div>
            <span className="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-[10px] font-bold bg-emerald-50 text-emerald-700 border border-emerald-200/60 self-start sm:self-auto">
              <span className="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse" />
              Connected
            </span>
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-3 text-xs">
            <div>
              <label className="font-semibold text-slate-700 block mb-1">Standard Event</label>
              <select
                value={testEventName}
                onChange={(e) => setTestEventName(e.target.value)}
                className="w-full p-2.5 rounded-xl border border-slate-200 bg-white font-medium text-slate-800 focus:outline-none focus:ring-2 focus:ring-blue-500/20"
              >
                <option value="Purchase">Purchase ($49.99)</option>
                <option value="AddToCart">AddToCart</option>
                <option value="InitiateCheckout">InitiateCheckout</option>
                <option value="ViewContent">ViewContent</option>
              </select>
            </div>

            <div>
              <label className="font-semibold text-slate-700 block mb-1">Test Event Code (Optional)</label>
              <input
                type="text"
                value={testEventCode}
                onChange={(e) => setTestEventCode(e.target.value)}
                placeholder="e.g. TEST12345"
                className="w-full p-2.5 rounded-xl border border-slate-200 font-mono text-xs focus:outline-none focus:ring-2 focus:ring-blue-500/20"
              />
            </div>

            <div className="flex items-end sm:col-span-2 md:col-span-1">
              <button
                onClick={handleSendTestEvent}
                disabled={isSendingTest}
                className="w-full py-2.5 rounded-xl text-xs font-bold bg-slate-900 hover:bg-slate-800 disabled:opacity-50 text-white flex items-center justify-center gap-1.5 shadow-xs transition-colors cursor-pointer"
              >
                <i className={`fa-solid ${isSendingTest ? 'fa-spinner fa-spin' : 'fa-paper-plane'} text-xs`} />
                <span>{isSendingTest ? 'Sending Signal...' : 'Dispatch Test Event'}</span>
              </button>
            </div>
          </div>

          {testResult && (
            <pre className="p-3.5 rounded-xl bg-slate-900 text-emerald-400 font-mono text-[11px] overflow-x-auto max-h-48">
              {JSON.stringify(testResult, null, 2)}
            </pre>
          )}
        </div>
      </div>

      {renderModals()}
    </AppLayout>
  );

  // =========================================================================
  // HELPER MODAL RENDER FUNCTION
  // =========================================================================
  function renderModals() {
    return (
      <>
        {/* 1. Facebook OAuth Popup Modal (Screenshot 3) */}
        {showFbAuthModal && (
          <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-50 flex items-center justify-center p-4">
            <div className="bg-white rounded-2xl max-w-md w-full p-6 shadow-2xl border border-slate-200 space-y-5 text-center">
              <div className="w-14 h-14 rounded-2xl bg-gradient-to-tr from-blue-600 to-indigo-600 flex items-center justify-center text-white mx-auto shadow-lg shadow-blue-500/20 text-2xl font-black">
                M
              </div>

              <div className="space-y-2">
                <h3 className="font-extrabold text-base text-slate-900">
                  Connect Meta Commerce &amp; Facebook Accounts
                </h3>
                <p className="text-xs text-slate-600">
                  Authenticate with Facebook to automatically load your Meta Business Portfolios and Pixels.
                </p>
              </div>

              <div className="space-y-3 text-left">
                <div>
                  <label className="text-xs font-bold text-slate-700">Meta Access Token (System User or User Token)</label>
                  <input
                    type="password"
                    value={accessToken}
                    onChange={(e) => setAccessToken(e.target.value)}
                    placeholder="Paste Meta Access Token (EAA...)"
                    className="mt-1 w-full p-2.5 rounded-xl border border-slate-200 text-xs font-mono bg-slate-50 focus:bg-white focus:outline-none focus:ring-1 focus:ring-slate-900"
                  />
                </div>
              </div>

              <div className="space-y-2 pt-1">
                <button
                  type="button"
                  onClick={handleConfirmFbAuth}
                  className="w-full py-2.5 rounded-xl text-xs font-bold bg-theme hover:bg-theme-hover text-white shadow-md shadow-theme/20 transition-colors"
                >
                  Verify &amp; Connect Meta Account
                </button>

                <div className="flex items-center gap-2">
                  <div className="h-px bg-slate-200 flex-1" />
                  <span className="text-[10px] text-slate-400 uppercase font-semibold">or</span>
                  <div className="h-px bg-slate-200 flex-1" />
                </div>

                <button
                  type="button"
                  onClick={openMetaOAuthPopup}
                  className="w-full py-2.5 rounded-xl text-xs font-bold border border-slate-200 text-slate-800 hover:bg-slate-50 flex items-center justify-center gap-2 transition-colors"
                >
                  <span>Login via Facebook OAuth Dialog</span>
                  <i className="fa-solid fa-arrow-up-right-from-square text-[11px] text-slate-400" />
                </button>

                <button
                  type="button"
                  onClick={() => setShowFbAuthModal(false)}
                  className="w-full py-2 text-xs font-medium text-slate-500 hover:text-slate-700"
                >
                  Cancel
                </button>
              </div>

              <p className="text-[10px] text-slate-400 leading-normal pt-2 border-t border-slate-100 text-center">
                By connecting, {APP_CONFIG.name} will securely encrypt and store credentials to dispatch conversions and catalog updates to Meta Graph API {META_CONFIG.graphVersion}.
              </p>
            </div>
          </div>
        )}

        {/* 2. "How I get it?" Help Modal */}
        {helpModal && (
          <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-50 flex items-center justify-center p-4">
            <div className="bg-white rounded-2xl max-w-md w-full p-6 shadow-2xl border border-slate-200 space-y-4">
              <div className="flex items-center justify-between border-b border-slate-100 pb-3">
                <h4 className="font-bold text-sm text-slate-900">
                  {helpModal === 'pixel_id'
                    ? 'How to find your Meta Pixel ID'
                    : helpModal === 'access_token'
                    ? 'How to find your Access Token'
                    : 'How to find your Test Event Code'}
                </h4>
                <button onClick={() => setHelpModal(null)} className="text-slate-400 hover:text-slate-600">
                  <i className="fa-solid fa-xmark text-base" />
                </button>
              </div>

              <div className="text-xs text-slate-600 space-y-3 leading-relaxed">
                {helpModal === 'pixel_id' && (
                  <>
                    <p className="text-slate-700">
                      A <strong>Meta Pixel ID / Dataset ID</strong> is the 15–16 digit numerical identifier for your Meta tracking asset.
                    </p>
                    <div className="p-3 bg-slate-50 rounded-xl border border-slate-200/80 space-y-1.5">
                      <p className="font-bold text-slate-900">Step-by-Step Instructions:</p>
                      <ol className="list-decimal list-inside space-y-1 text-slate-600 pl-1">
                        <li>Log in to <a href="https://business.facebook.com/events_manager2/" target="_blank" rel="noopener noreferrer" className="text-[#1877F2] font-semibold hover:underline">Meta Events Manager</a>.</li>
                        <li>Select your Business Account and choose your <strong>Pixel or Dataset</strong> on the left.</li>
                        <li>Click the <strong>Settings</strong> tab.</li>
                        <li>Find and copy your numeric <strong>Dataset ID</strong> (or Pixel ID).</li>
                      </ol>
                    </div>
                    <div className="pt-1">
                      <a
                        href="https://business.facebook.com/events_manager2/"
                        target="_blank"
                        rel="noopener noreferrer"
                        className="inline-flex items-center gap-1.5 px-3 py-1.5 bg-[#1877F2] hover:bg-[#166fe5] text-white rounded-lg text-xs font-bold transition-colors cursor-pointer"
                      >
                        <span>Open Meta Events Manager</span>
                        <i className="fa-solid fa-arrow-up-right-from-square text-[10px]" />
                      </a>
                    </div>
                  </>
                )}
                {helpModal === 'access_token' && (
                  <>
                    <p className="text-slate-700">
                      The <strong>Conversions API Access Token</strong> authorizes server-side event delivery directly to Meta Graph API for your specific dataset.
                    </p>
                    <div className="p-3 bg-slate-50 rounded-xl border border-slate-200/80 space-y-1.5">
                      <p className="font-bold text-slate-900">Recommended: Dataset Quality API Direct Token</p>
                      <ol className="list-decimal list-inside space-y-1 text-slate-600 pl-1">
                        <li>Click <strong>Open Dataset Settings</strong> below to go to your dataset in Meta Events Manager.</li>
                        <li>Scroll down to the <strong>Conversions API</strong> subsection.</li>
                        <li>Under <strong>&quot;Set up direct integration&quot;</strong>, select <strong>&quot;Set up with Dataset Quality API&quot; [Recommended]</strong>.</li>
                        <li>Click <strong>Generate access token</strong>.</li>
                        <li>Copy the token (starts with <code className="bg-slate-100 px-1 py-0.5 rounded font-mono">EAAdAd...</code> or <code className="bg-slate-100 px-1 py-0.5 rounded font-mono">EAA...</code>) and paste it into Step 2.</li>
                      </ol>
                    </div>
                    <p className="text-[11px] text-amber-700 bg-amber-50 p-2.5 rounded-lg border border-amber-200/70">
                      <strong>Important:</strong> Facebook App login tokens (starts with <code className="font-mono">EAGR...</code>) are not valid for Conversions API and will be rejected. Always use the token generated from direct integration.
                    </p>
                    <div className="pt-1 flex flex-wrap gap-2">
                      <a
                        href={eventsManagerSettingsUrl}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="inline-flex items-center gap-1.5 px-3 py-1.5 bg-[#1877F2] hover:bg-[#166fe5] text-white rounded-lg text-xs font-bold transition-colors cursor-pointer"
                      >
                        <span>Open Dataset Settings in Events Manager</span>
                        <i className="fa-solid fa-arrow-up-right-from-square text-[10px]" />
                      </a>
                    </div>
                  </>
                )}
                {helpModal === 'test_code' && (
                  <>
                    <p className="text-slate-700">
                      A <strong>Test Event Code</strong> lets you verify server events in real-time in Events Manager without impacting your production reporting.
                    </p>
                    <div className="p-3 bg-slate-50 rounded-xl border border-slate-200/80 space-y-1.5">
                      <p className="font-bold text-slate-900">Step-by-Step Instructions:</p>
                      <ol className="list-decimal list-inside space-y-1 text-slate-600 pl-1">
                        <li>Go to <a href="https://business.facebook.com/events_manager2/" target="_blank" rel="noopener noreferrer" className="text-[#1877F2] font-semibold hover:underline">Meta Events Manager</a> &gt; select your Pixel/Dataset.</li>
                        <li>Click on the <strong>Test Events</strong> tab at the top.</li>
                        <li>Look under <strong>&quot;Confirm your server events are set up correctly&quot;</strong>.</li>
                        <li>Copy the 5–10 character code (e.g. <code className="bg-slate-100 px-1 py-0.5 rounded font-mono">TEST12345</code>).</li>
                      </ol>
                    </div>
                    <div className="pt-1">
                      <a
                        href="https://business.facebook.com/events_manager2/"
                        target="_blank"
                        rel="noopener noreferrer"
                        className="inline-flex items-center gap-1.5 px-3 py-1.5 bg-[#1877F2] hover:bg-[#166fe5] text-white rounded-lg text-xs font-bold transition-colors cursor-pointer"
                      >
                        <span>Open Test Events Tool</span>
                        <i className="fa-solid fa-arrow-up-right-from-square text-[10px]" />
                      </a>
                    </div>
                  </>
                )}
              </div>

              <div className="pt-2 border-t border-slate-100 flex justify-end">
                <button
                  onClick={() => setHelpModal(null)}
                  className="px-5 py-2.5 rounded-xl text-xs font-bold bg-theme text-white hover:bg-theme-hover transition-colors cursor-pointer"
                >
                  Got it
                </button>
              </div>
            </div>
          </div>
        )}

        {/* 2.5 In-App Knowledge Base Guide Popup Modal */}
        {activeGuideArticle && (
          <div
            className="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-50 flex items-center justify-center p-3 sm:p-5 animate-in fade-in duration-200"
            onClick={(e) => {
              if (e.target === e.currentTarget) setGuideModalSlug(null);
            }}
          >
            <div className="bg-white rounded-2xl max-w-2xl w-full max-h-[88vh] flex flex-col shadow-2xl border border-slate-200/90 overflow-hidden">
              {/* Modal Header */}
              <div className="p-4 sm:p-5 border-b border-slate-100 flex items-start justify-between gap-3 bg-white shrink-0">
                <div className="space-y-1 min-w-0">
                  <div className="flex flex-wrap items-center gap-2">
                    <span className="text-[10px] font-semibold text-slate-700 bg-slate-100 border border-slate-200/60 px-2 py-0.5 rounded-md">
                      {activeGuideArticle.category}
                    </span>
                    {activeGuideArticle.badge && (
                      <span className="text-[10px] font-semibold text-slate-700 bg-slate-50 border border-slate-200/70 px-2 py-0.5 rounded-md">
                        {activeGuideArticle.badge}
                      </span>
                    )}
                    <span className="text-[11px] text-slate-400 flex items-center gap-1 font-normal">
                      <i className="fa fa-clock text-[9px]" />
                      <span>{activeGuideArticle.readingTime}</span>
                    </span>
                  </div>
                  <h3 className="text-base sm:text-lg font-bold text-slate-900 leading-snug">
                    {activeGuideArticle.title}
                  </h3>
                  <p className="text-xs text-slate-500 line-clamp-2">
                    {activeGuideArticle.subtitle}
                  </p>
                </div>

                <button
                  type="button"
                  onClick={() => setGuideModalSlug(null)}
                  className="text-slate-400 hover:text-slate-700 p-1.5 rounded-lg hover:bg-slate-100 transition-colors shrink-0 cursor-pointer"
                  aria-label="Close Guide"
                >
                  <i className="fa fa-times text-base" />
                </button>
              </div>

              {/* Modal Scrollable Body */}
              <div className="p-4 sm:p-6 overflow-y-auto space-y-6 text-xs text-slate-600 leading-relaxed">
                {activeGuideArticle.sections.map((section) => (
                  <section key={section.id} className="space-y-3">
                    <h4 className="text-xs sm:text-sm font-bold text-slate-900 flex items-center gap-2 border-b border-slate-100 pb-1.5">
                      <span className="w-1 h-3.5 bg-slate-900 rounded-full inline-block" />
                      <span>{section.title}</span>
                    </h4>

                    {/* Section Content */}
                    <div className="space-y-2 leading-relaxed">
                      {section.content.split('\n').map((line, lIdx) => {
                        const trimmed = line.trim();
                        if (!trimmed) return null;

                        const parts = line.split(/(\*\*.*?\*\*|`.*?`)/g);
                        const rendered = parts.map((part, pIdx) => {
                          if (part.startsWith('**') && part.endsWith('**')) {
                            return (
                              <strong key={pIdx} className="font-bold text-slate-900">
                                {part.slice(2, -2)}
                              </strong>
                            );
                          }
                          if (part.startsWith('`') && part.endsWith('`')) {
                            return (
                              <code
                                key={pIdx}
                                className="px-1.5 py-0.5 rounded bg-slate-100 text-slate-800 font-mono text-[11px] border border-slate-200/60"
                              >
                                {part.slice(1, -1)}
                              </code>
                            );
                          }
                          return <span key={pIdx}>{part}</span>;
                        });

                        const isBullet = trimmed.startsWith('-');
                        const isNumbered = /^\d+\./.test(trimmed);

                        return (
                          <p
                            key={lIdx}
                            className={`text-xs ${
                              isBullet || isNumbered ? 'pl-3 text-slate-700' : 'text-slate-600'
                            }`}
                          >
                            {rendered}
                          </p>
                        );
                      })}
                    </div>

                    {/* Callout Alert */}
                    {section.callout && (
                      <div className="p-3.5 rounded-xl border border-slate-200/90 bg-slate-50 text-xs leading-relaxed flex items-start gap-2.5">
                        <i
                          className={`text-xs shrink-0 mt-0.5 text-slate-700 ${
                            section.callout.type === 'tip'
                              ? 'fa fa-lightbulb'
                              : section.callout.type === 'warning'
                              ? 'fa fa-triangle-exclamation'
                              : section.callout.type === 'important'
                              ? 'fa fa-circle-exclamation'
                              : 'fa fa-circle-info'
                          }`}
                        />
                        <div className="space-y-0.5">
                          <span className="font-bold uppercase text-[9px] tracking-wider text-slate-600 block">
                            {section.callout.type}
                          </span>
                          <p className="text-slate-700 leading-relaxed">{section.callout.text}</p>
                        </div>
                      </div>
                    )}

                    {/* Table (if any) */}
                    {section.table && (
                      <div className="overflow-x-auto rounded-xl border border-slate-200/90 shadow-2xs">
                        <table className="w-full text-left text-xs">
                          <thead className="bg-slate-50 border-b border-slate-200/80 text-slate-700 font-bold">
                            <tr>
                              {section.table.headers.map((h, i) => (
                                <th key={i} className="px-3 py-2 whitespace-nowrap">
                                  {h}
                                </th>
                              ))}
                            </tr>
                          </thead>
                          <tbody className="divide-y divide-slate-100">
                            {section.table.rows.map((row, rIdx) => (
                              <tr key={rIdx} className="hover:bg-slate-50/60 transition-colors">
                                {row.map((cell, cIdx) => (
                                  <td key={cIdx} className="px-3 py-2 text-slate-600">
                                    {cell}
                                  </td>
                                ))}
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                    )}

                    {/* Numbered Steps (if any) */}
                    {section.steps && (
                      <div className="space-y-2 pt-1">
                        {section.steps.map((st) => (
                          <div
                            key={st.stepNumber}
                            className="flex items-start gap-2.5 p-2.5 rounded-xl bg-slate-50/60 border border-slate-200/60"
                          >
                            <span className="w-5 h-5 rounded-full bg-slate-900 text-white font-bold text-[10px] flex items-center justify-center shrink-0">
                              {st.stepNumber}
                            </span>
                            <div className="space-y-0.5 min-w-0">
                              <h5 className="font-bold text-xs text-slate-900">{st.title}</h5>
                              <p className="text-xs text-slate-600 leading-relaxed">{st.description}</p>
                            </div>
                          </div>
                        ))}
                      </div>
                    )}
                  </section>
                ))}

                {/* FAQs */}
                {activeGuideArticle.faqs && activeGuideArticle.faqs.length > 0 && (
                  <div className="border-t border-slate-100 pt-4 space-y-2.5">
                    <h4 className="text-xs sm:text-sm font-bold text-slate-900 flex items-center gap-1.5">
                      <i className="fa fa-question-circle text-slate-500 text-xs" />
                      <span>Frequently Asked Questions</span>
                    </h4>
                    <div className="space-y-2">
                      {activeGuideArticle.faqs.map((faq, idx) => (
                        <div key={idx} className="p-3 rounded-xl bg-slate-50 border border-slate-200/60 space-y-1">
                          <h5 className="font-bold text-xs text-slate-900">{faq.question}</h5>
                          <p className="text-xs text-slate-600 leading-relaxed">{faq.answer}</p>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
              </div>

              {/* Modal Sticky Footer */}
              <div className="p-3.5 sm:p-4 border-t border-slate-100 bg-slate-50/70 flex items-center justify-end gap-3 shrink-0">
                <button
                  type="button"
                  onClick={() => setGuideModalSlug(null)}
                  className="px-5 py-2.5 rounded-xl text-xs font-bold bg-slate-900 text-white hover:bg-slate-800 transition-colors cursor-pointer shadow-xs"
                >
                  Got it, Close
                </button>
              </div>
            </div>
          </div>
        )}

        {/* 3. Verification Diagnostic Modal */}
        {showVerifyModal && (
          <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-50 flex items-center justify-center p-4">
            <div className="bg-white rounded-3xl max-w-lg w-full p-6 sm:p-8 shadow-2xl border border-slate-200 space-y-6">
              <div className="flex items-center justify-between border-b border-slate-100 pb-3">
                <div className="flex items-center gap-2">
                  <i className="fa-solid fa-shield-halved text-lg text-theme" />
                  <h3 className="font-bold text-base text-black">Verifying Your Setup</h3>
                </div>
                {!isVerifying && (
                  <button onClick={() => setShowVerifyModal(false)} className="text-slate-400 hover:text-black cursor-pointer">
                    <i className="fa-solid fa-xmark text-base" />
                  </button>
                )}
              </div>

              <div className="space-y-4">
                {/* Step 1 Check */}
                <div className="flex items-center justify-between p-3.5 rounded-xl border border-slate-200">
                  <span className="text-xs font-medium text-slate-700">1. Meta Pixel Script Reachability</span>
                  {verifyStep >= 1 ? (
                    <i className="fa-solid fa-circle-check text-theme text-sm" />
                  ) : (
                    <i className="fa-solid fa-spinner fa-spin text-slate-400 text-sm" />
                  )}
                </div>

                {/* Step 2 Check */}
                <div className="flex items-center justify-between p-3.5 rounded-xl border border-slate-200">
                  <span className="text-xs font-medium text-slate-700">2. Conversions API (Graph API {META_CONFIG.graphVersion})</span>
                  {verifyStep >= 2 ? (
                    <i className="fa-solid fa-circle-check text-theme text-sm" />
                  ) : verifyStep === 1 ? (
                    <i className="fa-solid fa-spinner fa-spin text-theme text-sm" />
                  ) : (
                    <div className="w-4 h-4 rounded-full bg-slate-200" />
                  )}
                </div>

                {/* Step 3 Check */}
                <div className="flex items-center justify-between p-3.5 rounded-xl border border-slate-200">
                  <span className="text-xs font-medium text-slate-700">3. Shopify Theme App Embed Active</span>
                  {verifyStep >= 3 ? (
                    appEmbedChecked ? (
                      <span className="flex items-center gap-1.5 text-xs font-bold text-theme">
                        <i className="fa-solid fa-circle-check text-theme text-sm" />
                        <span>Active</span>
                      </span>
                    ) : (
                      <span className="text-[11px] font-bold text-amber-700 bg-amber-50 border border-amber-200 px-2 py-0.5 rounded-full flex items-center gap-1">
                        <i className="fa-solid fa-triangle-exclamation text-amber-600" />
                        <span>Not Turned On</span>
                      </span>
                    )
                  ) : verifyStep === 2 ? (
                    <i className="fa-solid fa-spinner fa-spin text-theme text-sm" />
                  ) : (
                    <div className="w-4 h-4 rounded-full bg-slate-200" />
                  )}
                </div>
              </div>

              {verifyStep >= 3 && appEmbedChecked && (
                <div className="p-4 rounded-2xl bg-theme/10 border border-theme/20 text-center space-y-1">
                  <p className="text-xs font-bold text-black">All checks passed successfully!</p>
                  <p className="text-[11px] text-slate-600">
                    Your store is ready to capture 100% of signals with zero deduplication conflicts.
                  </p>
                </div>
              )}

              {verifyStep >= 3 && !appEmbedChecked && (
                <div className="p-4 rounded-2xl bg-amber-50 border border-amber-200 text-left space-y-2.5">
                  <div className="flex items-center gap-2 text-amber-900">
                    <i className="fa-solid fa-triangle-exclamation text-amber-600 text-sm" />
                    <p className="text-xs font-bold">Theme App Embed Not Turned On</p>
                  </div>
                  <p className="text-[11px] text-amber-700 leading-relaxed">
                    Your Shopify Theme App Embed is currently not enabled. Please open your Theme Editor, turn ON <strong>Meta Pixel &amp; CAPI Tracker</strong> in App Embeds, and click Save.
                  </p>
                  <div className="flex items-center justify-between pt-1">
                    <a
                      href={themeEditorUrl}
                      onClick={handleOpenThemeEditor}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="inline-flex items-center gap-1.5 px-3 py-1.5 bg-amber-600 hover:bg-amber-700 text-white rounded-lg text-[11px] font-bold transition-colors cursor-pointer"
                    >
                      <span>Open Theme Editor</span>
                      <i className="fa-solid fa-arrow-up-right-from-square text-[9px]" />
                    </a>
                    <label className="flex items-center gap-1.5 text-[11px] text-slate-700 cursor-pointer font-medium">
                      <input
                        type="checkbox"
                        checked={appEmbedChecked}
                        onChange={(e) => handleCheckboxToggle(e.target.checked)}
                        className="rounded text-theme focus:ring-theme"
                      />
                      <span>I turned it on</span>
                    </label>
                  </div>
                </div>
              )}

              <div className="pt-2 flex justify-end">
                <button
                  type="button"
                  disabled={isVerifying}
                  onClick={() => {
                    setShowVerifyModal(false);
                    handleFinishOnboarding();
                  }}
                  className="w-full py-2.5 rounded-xl text-xs font-bold bg-theme text-white hover:bg-theme-hover disabled:opacity-40 shadow-md transition-colors cursor-pointer"
                >
                  {isVerifying ? 'Testing...' : 'Go to Pixel Manager'}
                </button>
              </div>
            </div>
          </div>
        )}

        {/* 4. Unified Add & Edit Pixel Modal (media_1793011790523.png & media_1793011824820.png) */}
        {showPixelModal && (
          <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-50 flex items-center justify-center p-3 sm:p-4 overflow-y-auto animate-fadeIn">
            <div className="bg-white rounded-2xl max-w-2xl w-full my-6 shadow-2xl border border-slate-200 overflow-hidden flex flex-col max-h-[92vh]">
              {/* Header */}
              <div className="px-6 py-4 border-b border-slate-100 flex items-center justify-between shrink-0">
                <button
                  type="button"
                  onClick={() => setShowPixelModal(false)}
                  className="flex items-center gap-2 text-sm font-bold text-slate-800 hover:text-slate-600 transition-colors cursor-pointer"
                >
                  <i className="fa-solid fa-arrow-left text-xs" />
                  <span>{pixelModalMode === 'add' ? 'Add Facebook pixel' : 'Update Facebook pixel'}</span>
                </button>
                <button
                  type="button"
                  onClick={() => setShowPixelModal(false)}
                  className="text-slate-400 hover:text-slate-700 transition-colors cursor-pointer p-1"
                >
                  <i className="fa-solid fa-xmark text-sm" />
                </button>
              </div>

              {/* Scrollable Content Body */}
              <div className="p-6 overflow-y-auto space-y-5 text-xs text-slate-700">
                {/* Segmented Switch: Auto input vs Manual input */}
                <div className="p-1 bg-slate-100/90 rounded-xl inline-flex border border-slate-200/80">
                  <button
                    type="button"
                    onClick={() => {
                      setPixelModalTab('auto');
                      setModalError(null);
                      if (availablePixels.length > 0) {
                        const targetId = modalSelectedPixel || availablePixels[0].id;
                        setModalSelectedPixel(targetId);
                        const chosen = availablePixels.find((x) => x.id === targetId) || availablePixels[0];
                        setModalPixelName(getCleanPixelName(chosen.name, chosen.id));
                      }
                    }}
                    className={`px-4 py-1.5 rounded-lg text-xs font-bold transition-all cursor-pointer ${
                      pixelModalTab === 'auto'
                        ? 'bg-slate-900 text-white shadow-2xs'
                        : 'text-slate-600 hover:text-slate-900'
                    }`}
                  >
                    Auto input
                  </button>
                  <button
                    type="button"
                    onClick={() => {
                      setPixelModalTab('manual');
                      setModalError(null);
                    }}
                    className={`px-4 py-1.5 rounded-lg text-xs font-bold transition-all cursor-pointer ${
                      pixelModalTab === 'manual'
                        ? 'bg-slate-900 text-white shadow-2xs'
                        : 'text-slate-600 hover:text-slate-900'
                    }`}
                  >
                    Manual input
                  </button>
                </div>

                {/* Auto Input Fields */}
                {pixelModalTab === 'auto' && (
                  <div className="space-y-4">
                    {/* Meta Account Card */}
                    {fbConnected && fbUser ? (
                      <div className="p-3.5 bg-slate-50/80 border border-slate-200 rounded-xl flex items-center justify-between gap-3">
                        <div className="flex items-center gap-3">
                          {fbUser.avatar && !avatarLoadError ? (
                            <img
                              src={fbUser.avatar}
                              alt={fbUser.name}
                              className="w-9 h-9 rounded-full object-cover border border-slate-200 shadow-2xs"
                              onError={() => setAvatarLoadError(true)}
                            />
                          ) : (
                            <div className="w-9 h-9 rounded-full bg-blue-600 text-white flex items-center justify-center font-bold text-xs shadow-2xs">
                              {fbUser.name ? fbUser.name.charAt(0).toUpperCase() : <i className="fa-brands fa-facebook-f text-sm" />}
                            </div>
                          )}
                          <div>
                            <div className="font-bold text-slate-900 text-xs">{fbUser.name}</div>
                            <div className="flex items-center gap-1.5 text-[11px] text-emerald-600 font-medium">
                              <span className="w-1.5 h-1.5 rounded-full bg-emerald-500" />
                              <span>Account connected</span>
                            </div>
                          </div>
                        </div>
                        <button
                          type="button"
                          onClick={handleModalDisconnect}
                          className="text-xs font-semibold text-rose-600 hover:text-rose-700 hover:underline px-2.5 py-1 rounded-lg transition-colors cursor-pointer"
                        >
                          Disconnect
                        </button>
                      </div>
                    ) : (
                      <div className="p-3.5 bg-blue-50/60 border border-blue-200/80 rounded-xl flex flex-col sm:flex-row sm:items-center justify-between gap-3">
                        <div className="flex items-center gap-2.5">
                          <div className="w-8 h-8 rounded-full bg-[#1877F2] text-white flex items-center justify-center shrink-0">
                            <i className="fa-brands fa-facebook-f text-xs" />
                          </div>
                          <div>
                            <div className="font-bold text-slate-900 text-xs">Connect your Meta Account</div>
                            <div className="text-[11px] text-slate-500">Automatically sync Business Accounts and Pixels</div>
                          </div>
                        </div>
                        <button
                          type="button"
                          onClick={openMetaOAuthPopup}
                          className="px-3.5 py-1.5 rounded-lg text-xs font-bold bg-[#1877F2] hover:bg-blue-600 text-white flex items-center justify-center gap-1.5 shadow-2xs transition-colors cursor-pointer shrink-0"
                        >
                          <i className="fa-brands fa-facebook text-xs" />
                          <span>Connect Facebook</span>
                        </button>
                      </div>
                    )}

                    {/* Select business account */}
                    <div>
                      <label className="font-bold text-slate-700 block mb-1">
                        Select business account
                      </label>
                      <div className="relative">
                        <select
                          value={modalSelectedBusiness}
                          onChange={(e) => handleModalSelectBusiness(e.target.value)}
                          disabled={!fbConnected || businessAccounts.length === 0}
                          className="w-full p-2.5 pr-8 rounded-xl border border-slate-200 text-xs bg-white text-slate-800 font-medium appearance-none shadow-2xs focus:outline-none focus:ring-1 focus:ring-slate-900 cursor-pointer disabled:bg-slate-50 disabled:text-slate-400 disabled:cursor-not-allowed"
                        >
                          {!fbConnected ? (
                            <option value="">No business account connected</option>
                          ) : businessAccounts.length > 0 ? (
                            businessAccounts.map((b) => (
                              <option key={b.id} value={b.id}>
                                {b.name}
                              </option>
                            ))
                          ) : (
                            <option value="">No business accounts found</option>
                          )}
                        </select>
                        <i className="fa-solid fa-chevron-down text-[10px] text-slate-400 absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none" />
                      </div>
                    </div>

                    {/* Select pixel */}
                    <div>
                      <label className="font-bold text-slate-700 block mb-1">
                        Select pixel
                      </label>
                      <div className="relative">
                        <select
                          value={modalSelectedPixel}
                          onChange={(e) => handleModalSelectPixel(e.target.value)}
                          disabled={!fbConnected || availablePixels.length === 0}
                          className="w-full p-2.5 pr-8 rounded-xl border border-slate-200 text-xs bg-white text-slate-800 font-medium appearance-none shadow-2xs focus:outline-none focus:ring-1 focus:ring-slate-900 cursor-pointer disabled:bg-slate-50 disabled:text-slate-400 disabled:cursor-not-allowed"
                        >
                          {!fbConnected ? (
                            <option value="">No pixel connected</option>
                          ) : availablePixels.length > 0 ? (
                            availablePixels.map((p) => (
                              <option key={p.id} value={p.id}>
                                {p.name}
                              </option>
                            ))
                          ) : (
                            <option value="">No pixels found in this business</option>
                          )}
                        </select>
                        <i className="fa-solid fa-chevron-down text-[10px] text-slate-400 absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none" />
                      </div>
                    </div>

                    {/* Pixel Name */}
                    <div>
                      <div className="flex items-center justify-between mb-1">
                        <label className="font-bold text-slate-700">
                          Pixel name <span className="text-rose-500">*</span>
                        </label>
                        <span className="text-[10px] text-slate-400 font-mono">
                          {modalPixelName.length}/255
                        </span>
                      </div>
                      <input
                        type="text"
                        maxLength={255}
                        value={modalPixelName}
                        onChange={(e) => {
                          setModalPixelName(e.target.value);
                          if (modalError) setModalError(null);
                        }}
                        disabled={!fbConnected && availablePixels.length === 0}
                        placeholder={availablePixels.length > 0 || fbConnected ? "e.g. Primary Store Pixel" : "Connect Facebook to auto-fill pixel name"}
                        className="w-full p-2.5 rounded-xl border border-slate-200 text-xs bg-white text-slate-800 shadow-2xs focus:outline-none focus:ring-1 focus:ring-slate-900 disabled:bg-slate-50 disabled:text-slate-400 disabled:cursor-not-allowed"
                      />
                    </div>
                  </div>
                )}

                {/* Manual Input Fields */}
                {pixelModalTab === 'manual' && (
                  <div className="space-y-4">
                    {/* Pixel Name */}
                    <div>
                      <div className="flex items-center justify-between mb-1">
                        <label className="font-bold text-slate-700">
                          Pixel name <span className="text-rose-500">*</span>
                        </label>
                        <span className="text-[10px] text-slate-400 font-mono">
                          {modalPixelName.length}/255
                        </span>
                      </div>
                      <input
                        type="text"
                        maxLength={255}
                        value={modalPixelName}
                        onChange={(e) => {
                          setModalPixelName(e.target.value);
                          if (modalError) setModalError(null);
                        }}
                        placeholder="Any name will do. This is just so you can manage different pixels easily."
                        className="w-full p-2.5 rounded-xl border border-slate-200 text-xs bg-white text-slate-800 shadow-2xs focus:outline-none focus:ring-1 focus:ring-slate-900"
                      />
                    </div>

                    {/* Pixel ID */}
                    <div>
                      <div className="flex items-center justify-between mb-1">
                        <label className="font-bold text-slate-700">
                          Pixel ID <span className="text-rose-500">*</span>
                        </label>
                        <div className="flex items-center gap-2">
                          <a
                            href="https://www.facebook.com/events_manager"
                            target="_blank"
                            rel="noopener noreferrer"
                            className="text-blue-600 hover:underline text-[11px] font-medium inline-flex items-center gap-1"
                          >
                            <span>How I get it?</span>
                            <i className="fa-solid fa-arrow-up-right-from-square text-[9px]" />
                          </a>
                          <span className="text-[10px] text-slate-400 font-mono">
                            {modalPixelId.length}/20
                          </span>
                        </div>
                      </div>
                      <input
                        type="text"
                        maxLength={20}
                        value={modalPixelId}
                        onChange={(e) => {
                          const val = e.target.value.replace(/\D/g, '');
                          setModalPixelId(val);
                          if (modalError) setModalError(null);
                        }}
                        placeholder="Copy pixel ID from Facebook and paste here."
                        className="w-full p-2.5 rounded-xl border font-mono text-xs bg-white text-slate-800 shadow-2xs focus:outline-none focus:ring-1 focus:ring-slate-900"
                      />
                    </div>
                  </div>
                )}

                {/* Tracking on pages */}
                <div className="space-y-2 pt-1">
                  <label className="font-bold text-slate-700 block">Tracking on pages</label>
                  <div className="space-y-2">
                    <label className="flex items-center gap-2.5 cursor-pointer">
                      <input
                        type="radio"
                        name="modalTrackingPages"
                        value="all"
                        checked={modalTrackingPages === 'all'}
                        onChange={() => setModalTrackingPages('all')}
                        className="text-slate-900 focus:ring-slate-900"
                      />
                      <span className="text-xs text-slate-700 font-medium">All pages</span>
                    </label>
                    <label className="flex items-center gap-2.5 cursor-pointer">
                      <input
                        type="radio"
                        name="modalTrackingPages"
                        value="selected"
                        checked={modalTrackingPages === 'selected'}
                        onChange={() => setModalTrackingPages('selected')}
                        className="text-slate-900 focus:ring-slate-900"
                      />
                      <span className="text-xs text-slate-700 font-medium">Selected page</span>
                    </label>
                    <label className="flex items-center gap-2.5 cursor-pointer">
                      <input
                        type="radio"
                        name="modalTrackingPages"
                        value="excluded"
                        checked={modalTrackingPages === 'excluded'}
                        onChange={() => setModalTrackingPages('excluded')}
                        className="text-slate-900 focus:ring-slate-900"
                      />
                      <span className="text-xs text-slate-700 font-medium">Excluded page</span>
                    </label>
                  </div>
                </div>

                <hr className="border-slate-100" />

                {/* Market targeting */}
                <div className="space-y-2">
                  <label className="font-bold text-slate-700 block">Market targeting</label>
                  <div className="space-y-2">
                    <label className="flex items-center gap-2.5 cursor-pointer">
                      <input
                        type="radio"
                        name="modalMarketTargeting"
                        value="all"
                        checked={modalMarketTargeting === 'all'}
                        onChange={() => setModalMarketTargeting('all')}
                        className="text-slate-900 focus:ring-slate-900"
                      />
                      <span className="text-xs text-slate-700 font-medium">All markets</span>
                    </label>
                    <label className="flex items-center gap-2.5 cursor-pointer">
                      <input
                        type="radio"
                        name="modalMarketTargeting"
                        value="specific"
                        checked={modalMarketTargeting === 'specific'}
                        onChange={() => setModalMarketTargeting('specific')}
                        className="text-slate-900 focus:ring-slate-900"
                      />
                      <span className="text-xs text-slate-700 font-medium inline-flex items-center gap-1.5">
                        <span>Specific markets</span>
                        <span className="bg-slate-900 text-white text-[9px] font-bold px-1.5 py-0.5 rounded uppercase tracking-wider">
                          Scale
                        </span>
                      </span>
                    </label>
                  </div>
                </div>

                {/* Conversions API card */}
                <div className="p-4 rounded-xl border border-slate-200 bg-slate-50/60 space-y-3.5">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <span className="font-bold text-xs text-slate-900">Conversions API</span>
                      <span className="text-[10px] font-bold text-emerald-700 bg-emerald-100/90 px-2 py-0.5 rounded-full">
                        Recommended
                      </span>
                    </div>
                    {/* Toggle Switch */}
                    <button
                      type="button"
                      onClick={() => setModalCapiEnabled((v) => !v)}
                      className={`relative inline-flex h-5 w-9 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${
                        modalCapiEnabled ? 'bg-slate-900' : 'bg-slate-300'
                      }`}
                    >
                      <span
                        className={`pointer-events-none inline-block h-4 w-4 transform rounded-full bg-white shadow-md ring-0 transition duration-200 ease-in-out ${
                          modalCapiEnabled ? 'translate-x-4' : 'translate-x-0'
                        }`}
                      />
                    </button>
                  </div>

                  <p className="text-[11px] text-slate-500 leading-relaxed">
                    Conversions API (CAPI) sends web events directly from server to Facebook. Server events are linked to a pixel and are processed like browser events.
                  </p>

                  {modalCapiEnabled && (
                    <div className="space-y-3 pt-1 border-t border-slate-200/60">
                      {/* Access Token */}
                      <div>
                        <div className="flex items-center justify-between mb-1">
                          <label className="font-bold text-slate-700 flex items-center gap-1">
                            <span>Facebook access token</span>
                            <span
                              title="Generated in Meta Events Manager > Settings > Conversions API > Set up manually"
                              className="cursor-help text-slate-400 hover:text-slate-600"
                            >
                              <i className="fa-regular fa-circle-question text-[10px]" />
                            </span>
                          </label>
                          {autoToken && !modalAccessToken && (
                            <button
                              type="button"
                              onClick={() => setModalAccessToken(autoToken)}
                              className="text-[11px] font-bold text-theme hover:underline flex items-center gap-1 cursor-pointer"
                            >
                              <i className="fa-solid fa-rotate-left text-[9px]" />
                              <span>Auto-fill from account</span>
                            </button>
                          )}
                        </div>
                        <input
                          type="text"
                          value={modalAccessToken}
                          onChange={(e) => setModalAccessToken(e.target.value)}
                          placeholder="Paste Conversions API access token"
                          className="w-full p-2.5 rounded-xl border border-slate-200 font-mono text-xs bg-white text-slate-800 shadow-2xs focus:outline-none focus:ring-1 focus:ring-slate-900"
                        />
                      </div>

                      {/* Test event code */}
                      <div>
                        <div className="flex items-center justify-between mb-1">
                          <label className="font-bold text-slate-700 flex items-center gap-1">
                            <span>Test event code</span>
                            <span
                              title="Found in Meta Events Manager > Test Events tab"
                              className="cursor-help text-slate-400 hover:text-slate-600"
                            >
                              <i className="fa-regular fa-circle-question text-[10px]" />
                            </span>
                          </label>
                          <span className="text-[10px] text-slate-400 font-mono">
                            {modalTestEventCode.length}/20
                          </span>
                        </div>
                        <input
                          type="text"
                          maxLength={20}
                          value={modalTestEventCode}
                          onChange={(e) => setModalTestEventCode(e.target.value)}
                          placeholder="e.g. TEST12345"
                          className="w-full p-2.5 rounded-xl border border-slate-200 font-mono text-xs bg-white text-slate-800 shadow-2xs focus:outline-none focus:ring-1 focus:ring-slate-900"
                        />
                        <p className="text-[10px] text-slate-400 mt-1">
                          Use this if you need to test the server-side event. Remove it after testing.
                        </p>
                      </div>
                    </div>
                  )}
                </div>

                {/* Error Banner */}
                {modalError && (
                  <div
                    data-error-banner
                    role="alert"
                    className="p-3 bg-rose-50 border border-rose-200 rounded-xl text-rose-700 text-xs flex items-center gap-2 font-medium"
                  >
                    <i className="fa-solid fa-circle-exclamation shrink-0 text-rose-500" />
                    <span>{modalError}</span>
                  </div>
                )}
              </div>

              {/* Modal Footer */}
              <div className="px-6 py-3.5 border-t border-slate-100 bg-slate-50/60 flex items-center justify-end gap-2.5 shrink-0">
                <div className="flex items-center gap-2.5 w-full sm:w-auto justify-end">
                  <button
                    type="button"
                    onClick={() => setShowPixelModal(false)}
                    className="px-4 py-2 rounded-xl text-xs font-semibold border border-slate-200 text-slate-700 hover:bg-white transition-colors cursor-pointer"
                  >
                    Cancel
                  </button>
                  <button
                    type="button"
                    onClick={handleSaveModalPixel}
                    disabled={isSavingModalPixel}
                    className="px-5 py-2 rounded-xl text-xs font-bold bg-slate-900 hover:bg-slate-800 text-white shadow-sm transition-all cursor-pointer flex items-center gap-1.5 disabled:opacity-50"
                  >
                    {isSavingModalPixel && <i className="fa-solid fa-circle-notch fa-spin text-xs" />}
                    <span>{pixelModalMode === 'add' ? 'Save Pixel' : 'Update Pixel'}</span>
                  </button>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* 5. Delete Confirmation Modal */}
        {deletingPixel && (
          <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-50 flex items-center justify-center p-4">
            <div className="bg-white rounded-2xl max-w-sm w-full p-6 shadow-2xl border border-slate-200 space-y-4 text-center">
              <div className="w-12 h-12 rounded-full bg-rose-50 text-rose-600 flex items-center justify-center mx-auto">
                <i className="fa-regular fa-trash-can text-2xl" />
              </div>

              <div className="space-y-1">
                <h3 className="font-bold text-base text-slate-900">Delete Pixel?</h3>
                <p className="text-xs text-slate-500">
                  Are you sure you want to delete{' '}
                  <strong className="text-slate-800">{deletingPixel.pixel_name}</strong> (
                  <span className="font-mono">{deletingPixel.pixel_id}</span>)? Tracking will stop immediately.
                </p>
              </div>

              <div className="grid grid-cols-2 gap-3 pt-2">
                <button
                  type="button"
                  onClick={() => setDeletingPixel(null)}
                  className="py-2.5 rounded-xl text-xs font-semibold border border-slate-200 text-slate-700 hover:bg-slate-50"
                >
                  Cancel
                </button>
                <button
                  type="button"
                  onClick={handleDeletePixel}
                  className="py-2.5 rounded-xl text-xs font-bold bg-rose-600 hover:bg-rose-700 text-white shadow-sm"
                >
                  Delete
                </button>
              </div>
            </div>
          </div>
        )}

        {/* 6. Confirmation Modal */}
        {confirmDialog && (
          <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-50 flex items-center justify-center p-4 animate-fadeIn">
            <div className="bg-white rounded-2xl max-w-sm w-full p-6 shadow-2xl border border-slate-200 space-y-5">
              {/* Icon + Title */}
              <div className="flex flex-col items-center text-center gap-3">
                <div
                  className={`w-12 h-12 rounded-full flex items-center justify-center text-xl ${
                    confirmDialog.isDanger
                      ? 'bg-rose-50 text-rose-600'
                      : 'bg-amber-50 text-amber-600'
                  }`}
                >
                  <i
                    className={`fa-solid ${
                      confirmDialog.isDanger ? 'fa-triangle-exclamation' : 'fa-circle-exclamation'
                    }`}
                  />
                </div>
                <div className="space-y-1">
                  <h3 className="font-extrabold text-sm text-slate-900 leading-snug">
                    {confirmDialog.title}
                  </h3>
                  <p className="text-xs text-slate-500 leading-relaxed">
                    {confirmDialog.description}
                  </p>
                </div>
              </div>

              {/* Action Buttons */}
              <div className="flex items-center gap-2.5">
                <button
                  type="button"
                  onClick={() => {
                    confirmDialog.onCancel();
                    setConfirmDialog(null);
                  }}
                  className="flex-1 py-2.5 rounded-xl border border-slate-200 text-xs font-bold text-slate-700 hover:bg-slate-50 transition-colors cursor-pointer"
                >
                  {confirmDialog.cancelText || 'Cancel'}
                </button>
                <button
                  type="button"
                  onClick={() => {
                    const action = confirmDialog.onConfirm;
                    setConfirmDialog(null);
                    action();
                  }}
                  className={`flex-1 py-2.5 rounded-xl text-xs font-bold text-white shadow-sm transition-all cursor-pointer ${
                    confirmDialog.isDanger
                      ? 'bg-rose-600 hover:bg-rose-700'
                      : 'bg-theme hover:bg-theme-hover'
                  }`}
                >
                  {confirmDialog.confirmText || 'Confirm'}
                </button>
              </div>
            </div>
          </div>
        )}



        {/* 7. Success / Feedback Toast Notification */}
        {toastMessage && (
          <div className="fixed bottom-6 right-6 z-50 flex items-center gap-3 px-4 py-3 rounded-2xl bg-slate-900/95 text-white shadow-2xl border border-slate-800 backdrop-blur-md animate-slideUp text-xs font-medium">
            <div
              className={`w-6 h-6 rounded-full flex items-center justify-center shrink-0 text-xs ${
                toastMessage.type === 'warning'
                  ? 'bg-amber-500/20 text-amber-400'
                  : 'bg-emerald-500/20 text-emerald-400'
              }`}
            >
              <i
                className={`fa-solid ${
                  toastMessage.type === 'warning'
                    ? 'fa-triangle-exclamation'
                    : 'fa-circle-check'
                }`}
              />
            </div>
            <span className="leading-snug">{toastMessage.text}</span>
            <button
              type="button"
              onClick={() => setToastMessage(null)}
              className="ml-2 text-slate-400 hover:text-white transition-colors cursor-pointer"
            >
              <i className="fa-solid fa-xmark text-xs" />
            </button>
          </div>
        )}
      </>
    );
  }
}
