'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { useSearchParams, useRouter } from 'next/navigation';
import AppLayout from '@/components/layout/AppLayout';
import { CatalogActionMenu } from './components/CatalogActionMenu';
import { CatalogRecord } from '@/types/catalog';
import { parseMetaErrorMessage, ParsedMetaError } from '@/lib/meta/error-parser';
import { apiUrl, appRoute } from '@/lib/utils/asset';

interface MetaBusinessAccount {
  id: string;
  name: string;
}

interface MetaAccountData {
  connected: boolean;
  user: {
    id: string;
    name: string;
    avatar?: string | null;
  } | null;
  businesses: MetaBusinessAccount[];
  selectedBusinessId: string;
}

interface CatalogStats {
  totalProducts: number;
  productLimit: number | null;
  totalCatalogs: number;
  catalogLimit: number | null;
  planId?: string;
  planName?: string;
  subscriptionStatus?: string;
  trialDaysRemaining?: number | null;
}

interface NotificationState {
  type: 'success' | 'error';
  title?: string;
  message: string;
  actionableStep?: string;
  rawError?: string;
  actionUrl?: string;
  actionLabel?: string;
}

export default function CatalogPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const currentShop = searchParams?.get('shop') || searchParams?.get('shopify_domain') || '';

  const getEndpoint = (path: string) => {
    const qs = currentShop ? `shop=${encodeURIComponent(currentShop)}` : '';
    const sep = path.includes('?') ? '&' : '?';
    return apiUrl(qs ? `${path}${sep}${qs}` : path);
  };

  const getHref = (path: string) => {
    return appRoute(path, currentShop);
  };

  const [activeTab, setActiveTab] = useState<'catalogs' | 'feeds'>('catalogs');
  const [catalogs, setCatalogs] = useState<CatalogRecord[]>([]);
  const [stats, setStats] = useState<CatalogStats>({
    totalProducts: 0,
    productLimit: 10000,
    totalCatalogs: 0,
    catalogLimit: 10,
    planId: 'growth',
    planName: 'Growth Plan',
    subscriptionStatus: 'active',
    trialDaysRemaining: null,
  });
  const [metaAccount, setMetaAccount] = useState<MetaAccountData | null>(null);
  const [metaStatus, setMetaStatus] = useState<'connected' | 'disconnected' | 'token_expired'>('disconnected');
  const [isConnectingFb, setIsConnectingFb] = useState(false);
  const [selectedBizId, setSelectedBizId] = useState<string>('');
  const [loading, setLoading] = useState(true);
  const [syncingMap, setSyncingMap] = useState<Record<string, boolean>>({});
  const [copiedFeed, setCopiedFeed] = useState<'xml' | 'csv' | null>(null);
  const [notification, setNotification] = useState<NotificationState | null>(null);

  const [feedUrls, setFeedUrls] = useState({
    xml: '',
    csv: '',
  });

  const fetchMetaAccount = async () => {
    try {
      const statusRes = await fetch(getEndpoint('/api/meta/status'));
      const statusData = await statusRes.json();
      const status = statusData?.status || (statusData?.connected ? 'connected' : 'disconnected');
      setMetaStatus(status);

      if (statusData?.connected) {
        const res = await fetch(getEndpoint('/api/meta/accounts'));
        const data = await res.json();
        if (data.success && data.connected) {
          setMetaAccount(data);
          setSelectedBizId(data.selectedBusinessId || data.businesses?.[0]?.id || '');
          return;
        }
      }

      setMetaAccount({
        connected: false,
        user: statusData?.user || null,
        businesses: [],
        selectedBusinessId: '',
      });
      setSelectedBizId('');
    } catch (err) {
      console.error('Failed to load meta account info', err);
      setMetaStatus('disconnected');
      setMetaAccount(null);
    }
  };

  const openMetaOAuthPopup = (autoContinueToCreate = false) => {
    const width = 650;
    const height = 750;
    const left = window.screenX + (window.outerWidth - width) / 2;
    const top = window.screenY + (window.outerHeight - height) / 2;
    const qs = currentShop ? `?shop=${encodeURIComponent(currentShop)}` : '';
    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`
    );

    let completed = false;
    const onAuthSuccess = async () => {
      if (completed) return;
      completed = true;
      setIsConnectingFb(false);
      setNotification({
        type: 'success',
        title: 'Facebook Account Connected',
        message: 'Your Facebook account has been connected and verified successfully.',
      });
      await fetchMetaAccount();
      await fetchCatalogs();
      if (autoContinueToCreate) {
        router.push(getHref('/catalog/create'));
      }
    };

    if (popup) {
      setIsConnectingFb(true);
      const pollTimer = setInterval(() => {
        if (popup.closed) {
          clearInterval(pollTimer);
          setTimeout(async () => {
            const statusRes = await fetch(getEndpoint('/api/meta/status'));
            const statusData = await statusRes.json();
            if (statusData?.connected) {
              await onAuthSuccess();
            } else if (!completed) {
              setIsConnectingFb(false);
              setNotification({
                type: 'error',
                title: 'Connection Cancelled',
                message: 'Facebook connection was cancelled or not completed. Please connect to manage catalogs.',
              });
            }
          }, 1000);
        }
      }, 1000);
    }
  };

  useEffect(() => {
    fetchCatalogs();
    fetchMetaAccount();
    if (typeof window !== 'undefined') {
      const origin = window.location.origin;
      setFeedUrls({
        xml: `${origin}/api/catalog/feed/meta.xml`,
        csv: `${origin}/api/catalog/feed/meta.csv`,
      });
    }

    const handleAuthMessage = (event: MessageEvent) => {
      if (event.data?.type === 'META_AUTH_SUCCESS') {
        fetchMetaAccount();
        fetchCatalogs();
      }
    };
    window.addEventListener('message', handleAuthMessage);

    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') {
            fetchMetaAccount();
            fetchCatalogs();
          }
        };
      }
    } catch {}

    const handleStorageEvent = (event: StorageEvent) => {
      if (event.key === 'meta_auth_success') {
        fetchMetaAccount();
        fetchCatalogs();
      }
    };
    window.addEventListener('storage', handleStorageEvent);

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

  const fetchCatalogs = async () => {
    try {
      const res = await fetch(getEndpoint('/api/catalogs'));
      const data = await res.json();
      if (data.success) {
        setCatalogs(data.catalogs || []);
        if (data.stats) {
          setStats(data.stats);
        }
      }
    } catch (err) {
      console.error('Failed to load catalogs', err);
    } finally {
      setLoading(false);
    }
  };

  const handleDisconnectFb = async () => {
    if (confirm('Are you sure you want to disconnect your Facebook account? Your catalog tracking will be paused until reconnected.')) {
      try {
        await fetch(getEndpoint('/api/meta/connect'), { method: 'DELETE' });
        setMetaAccount(null);
        setMetaStatus('disconnected');
        setSelectedBizId('');
        setCatalogs([]);
        await fetchMetaAccount();
        await fetchCatalogs();
        setNotification({ type: 'success', message: 'Facebook account disconnected successfully.' });
      } catch {
        setNotification({ type: 'error', message: 'Failed to disconnect account' });
      }
    }
  };

  const handleToggleAutoSync = async (catalogId: string, currentState: boolean) => {
    try {
      const res = await fetch(getEndpoint(`/api/catalogs/${catalogId}/auto-sync`), {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ auto_sync: !currentState }),
      });
      const data = await res.json();
      if (data.success) {
        setCatalogs(prev =>
          prev.map(c => (c.id === catalogId ? { ...c, auto_sync: !currentState } : c))
        );
      }
    } catch (err) {
      console.error('Failed to toggle auto sync', err);
    }
  };

  const handleTogglePixel = async (catalogId: string, currentState: boolean) => {
    try {
      const res = await fetch(getEndpoint(`/api/catalogs/${catalogId}/pixel`), {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ pixel_tracking: !currentState }),
      });
      const data = await res.json();
      if (data.success) {
        setCatalogs(prev =>
          prev.map(c => (c.id === catalogId ? { ...c, pixel_tracking: !currentState } : c))
        );
      }
    } catch (err) {
      console.error('Failed to toggle tracking pixel', err);
    }
  };

  const [isRefreshingProducts, setIsRefreshingProducts] = useState(false);

  const handleRefreshProductsFromShopify = async () => {
    setIsRefreshingProducts(true);
    setNotification(null);
    try {
      const res = await fetch(getEndpoint('/api/shopify/products/sync'), { method: 'POST' });
      const data = await res.json();
      if (data.success) {
        setNotification({
          type: 'success',
          title: 'Shopify Products Synchronized',
          message: data.message || 'Successfully pulled latest product data from Shopify store.',
        });
        await fetchCatalogs();
      } else {
        const isPerm = Boolean(data.isPermissionError || (data.error && (data.error.includes('403') || data.error.toLowerCase().includes('read_products'))));
        setNotification({
          type: 'error',
          title: isPerm ? 'Shopify Store Permission Required (HTTP 403)' : 'Shopify Product Sync Failed',
          message: data.error || 'Failed to sync products from Shopify',
          actionableStep: data.hint || 'Check your Shopify store connection or permissions in Settings.',
          actionUrl: data.reauthUrl || (isPerm && currentShop ? apiUrl(`/api/auth/shopify?shop=${encodeURIComponent(currentShop)}`) : undefined),
          actionLabel: 'Re-authorize Shopify Store Now',
        });
      }
    } catch (err: any) {
      setNotification({
        type: 'error',
        title: 'Sync Network Error',
        message: err.message || 'Could not connect to Shopify sync endpoint',
      });
    } finally {
      setIsRefreshingProducts(false);
    }
  };

  const handleNotificationAction = async () => {
    if (!notification?.actionUrl) return;

    // If it's a Shopify re-authorization action:
    if (
      notification.actionUrl.includes('auth/shopify') ||
      notification.actionUrl.includes('/admin/oauth/authorize') ||
      notification.actionLabel?.toLowerCase().includes('re-authorize')
    ) {
      const shop = currentShop || (typeof window !== 'undefined' ? sessionStorage.getItem('shopify_shop_domain') : null);
      if (notification.actionUrl.includes('/admin/oauth/authorize')) {
        if (window.top && window.top !== window) {
          window.top.location.href = notification.actionUrl;
        } else {
          window.location.href = notification.actionUrl;
        }
        return;
      }

      try {
        if (shop) {
          const res = await fetch(apiUrl(`/api/auth/shopify?shop=${encodeURIComponent(shop)}&format=json`));
          const data = await res.json();
          if (data.url) {
            if (window.top && window.top !== window) {
              window.top.location.href = data.url;
            } else {
              window.location.href = data.url;
            }
            return;
          }
        }
      } catch {}

      if (shop) {
        const apiKey = process.env.NEXT_PUBLIC_SHOPIFY_API_KEY || 'd6d73fa2d424638f91826f822d89c51f';
        const redirectUri = encodeURIComponent('https://portal.webiletechnologies.com/meta-connector/api/auth/shopify/callback');
        const scopes = encodeURIComponent('read_products,write_products,read_inventory,read_customer_events');
        const directUrl = `https://${shop}/admin/oauth/authorize?client_id=${apiKey}&scope=${scopes}&redirect_uri=${redirectUri}`;
        if (window.top && window.top !== window) {
          window.top.location.href = directUrl;
        } else {
          window.location.href = directUrl;
        }
        return;
      }
    }

    if (window.top && window.top !== window) {
      window.top.location.href = notification.actionUrl;
    } else {
      window.location.href = notification.actionUrl;
    }
  };

  const handleSyncNow = async (catalogId: string) => {
    setSyncingMap(prev => ({ ...prev, [catalogId]: true }));
    setNotification(null);
    try {
      const res = await fetch(getEndpoint(`/api/catalogs/${catalogId}/sync`), { method: 'POST' });
      const data = await res.json();
      if (data.success) {
        setNotification({
          type: 'success',
          title: 'Catalog Synced Successfully',
          message: `All ${data.result?.totalVariants || 0} product variants are synchronized with Meta Commerce Manager.`,
        });
        await fetchCatalogs();
      } else {
        const parsed = parseMetaErrorMessage(data.error);
        const resolvedActionUrl = parsed.actionUrl
          ? (parsed.actionUrl.includes('?') ? apiUrl(parsed.actionUrl) : apiUrl(`${parsed.actionUrl}?shop=${encodeURIComponent(currentShop)}`))
          : undefined;

        setNotification({
          type: 'error',
          title: parsed.title,
          message: parsed.message,
          actionableStep: parsed.actionableStep,
          rawError: parsed.rawError,
          actionUrl: resolvedActionUrl,
          actionLabel: parsed.actionLabel,
        });
        await fetchCatalogs();
      }
    } catch (err: any) {
      const parsed = parseMetaErrorMessage(err.message);
      const resolvedActionUrl = parsed.actionUrl
        ? (parsed.actionUrl.includes('?') ? apiUrl(parsed.actionUrl) : apiUrl(`${parsed.actionUrl}?shop=${encodeURIComponent(currentShop)}`))
        : undefined;

      setNotification({
        type: 'error',
        title: parsed.title,
        message: parsed.message,
        actionableStep: parsed.actionableStep,
        rawError: err.message,
        actionUrl: resolvedActionUrl,
        actionLabel: parsed.actionLabel,
      });
    } finally {
      setSyncingMap(prev => ({ ...prev, [catalogId]: false }));
    }
  };

  const handleDeleteCatalog = async (catalogId: string) => {
    try {
      const res = await fetch(getEndpoint(`/api/catalogs/${catalogId}`), { method: 'DELETE' });
      const data = await res.json();
      if (data.success) {
        setCatalogs(prev => prev.filter(c => c.id !== catalogId));
        setNotification({ type: 'success', message: 'Catalog deleted successfully' });
      } else {
        setNotification({ type: 'error', message: data.error || 'Failed to delete catalog' });
      }
    } catch (err: any) {
      setNotification({ type: 'error', message: err.message || 'Delete operation failed' });
    }
  };

  const copyToClipboard = (type: 'xml' | 'csv') => {
    navigator.clipboard.writeText(type === 'xml' ? feedUrls.xml : feedUrls.csv);
    setCopiedFeed(type);
    setTimeout(() => setCopiedFeed(null), 2000);
  };

  const formatLastSync = (lastSyncedAt?: Date | string | null, nextSyncAt?: Date | string | null) => {
    let lastText = 'Never';
    if (lastSyncedAt) {
      const d = new Date(lastSyncedAt);
      const diffSecs = Math.floor((Date.now() - d.getTime()) / 1000);
      if (diffSecs < 60) lastText = 'a few seconds ago';
      else if (diffSecs < 3600) lastText = `${Math.floor(diffSecs / 60)} minutes ago`;
      else if (diffSecs < 86400) lastText = `${Math.floor(diffSecs / 3600)} hours ago`;
      else lastText = d.toLocaleDateString();
    }

    let nextText = '';
    if (nextSyncAt) {
      const nd = new Date(nextSyncAt);
      nextText = `Next: ${nd.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}, ${nd.toLocaleDateString([], { month: 'short', day: 'numeric' })}`;
    }

    return { lastText, nextText };
  };

  return (
    <AppLayout currentRoute="/catalog">
      <ui-title-bar title="Meta Catalogs & Feeds">
        <button variant="primary" onClick={() => { router.push(getHref('/catalog/create')); }}>Create Catalog</button>
      </ui-title-bar>
      <div className="space-y-6 pb-12">
        {/* Header and Page Tabs */}
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-slate-200/80 pb-4">
          <div>
            <div className="flex items-center gap-2 text-xs font-semibold text-theme uppercase tracking-wider">
              <i className="fa-solid fa-layer-group text-xs" />
              <span>Catalog &amp; Feed Engine</span>
            </div>
            <h1 className="text-2xl font-bold text-slate-900 tracking-tight mt-1">Facebook Product Catalogs &amp; Feeds</h1>
            <p className="text-xs text-slate-500">
              Create, sync, and manage Facebook/Instagram product catalogs for Advantage+ dynamic catalog ads.
            </p>
          </div>

          {/* Tab Navigation */}
          <div className="flex items-center gap-1 bg-slate-100 p-1 rounded-xl border border-slate-200/70 overflow-x-auto max-w-full">
            <button
              onClick={() => setActiveTab('catalogs')}
              className={`px-3.5 sm:px-4 py-1.5 rounded-lg text-xs font-semibold transition-all flex items-center gap-1.5 whitespace-nowrap ${
                activeTab === 'catalogs'
                  ? 'bg-white text-slate-900 shadow-xs'
                  : 'text-slate-600 hover:text-slate-900'
              }`}
            >
              <i className="fa-solid fa-layer-group text-xs text-theme" />
              <span>Catalogs</span>
            </button>
            <button
              onClick={() => setActiveTab('feeds')}
              className={`px-3.5 sm:px-4 py-1.5 rounded-lg text-xs font-semibold transition-all flex items-center gap-1.5 whitespace-nowrap ${
                activeTab === 'feeds'
                  ? 'bg-white text-slate-900 shadow-xs'
                  : 'text-slate-600 hover:text-slate-900'
              }`}
            >
              <i className="fa-solid fa-rss text-xs text-emerald-600" />
              <span>Feeds</span>
            </button>
            <Link
              href={getHref('/templates')}
              className="px-3.5 sm:px-4 py-1.5 rounded-lg text-xs font-semibold transition-all flex items-center gap-1.5 text-slate-600 hover:text-slate-900 hover:bg-white/50 whitespace-nowrap"
              title="Open Dynamic Product Templates Studio"
            >
              <i className="fa-solid fa-wand-magic-sparkles text-xs text-theme" />
              <span>Template Library</span>
            </Link>
          </div>
        </div>

        {/* Notification Toast */}
        {notification && (
          <div
            className={`p-4 rounded-2xl border text-xs shadow-xs animate-in fade-in-50 duration-200 ${
              notification.type === 'success'
                ? 'bg-emerald-50/90 border-emerald-200 text-emerald-900'
                : 'bg-rose-50/95 border-rose-200 text-rose-900'
            }`}
          >
            <div className="flex items-start justify-between gap-3">
              <div className="flex items-start gap-3">
                {notification.type === 'success' ? (
                  <i className="fa-solid fa-circle-check text-emerald-600 text-base shrink-0 mt-0.5" />
                ) : (
                  <i className="fa-solid fa-circle-exclamation text-rose-600 text-base shrink-0 mt-0.5" />
                )}
                <div className="space-y-1">
                  {notification.title && (
                    <h4 className="font-bold text-slate-900 text-xs">{notification.title}</h4>
                  )}
                  <p className="font-medium text-slate-800 leading-relaxed">{notification.message}</p>
                  {notification.actionableStep && (
                    <div className="mt-2 p-2.5 bg-white/80 border border-slate-200/80 rounded-xl text-slate-700 font-normal leading-relaxed text-[11px]">
                      <span className="font-semibold text-slate-900">👉 Action: </span>
                      {notification.actionableStep}
                    </div>
                  )}
                  {notification.actionUrl && (
                    <div className="mt-3">
                      <button
                        type="button"
                        onClick={handleNotificationAction}
                        className="inline-flex items-center gap-1.5 px-3 py-1.5 bg-rose-600 hover:bg-rose-700 text-white rounded-lg text-xs font-bold transition-colors shadow-xs cursor-pointer"
                      >
                        <i className="fa-solid fa-shield-halved text-xs" />
                        <span>{notification.actionLabel || 'Re-authorize Shopify Store'}</span>
                        <i className="fa-solid fa-arrow-right text-[10px]" />
                      </button>
                    </div>
                  )}
                  {notification.rawError && (
                    <p className="text-[10px] text-slate-500 font-mono pt-1">
                      Details: {notification.rawError}
                    </p>
                  )}
                </div>
              </div>
              <button
                onClick={() => setNotification(null)}
                className="text-slate-400 hover:text-slate-600 font-bold p-1 text-xs shrink-0 cursor-pointer"
              >
                ✕
              </button>
            </div>
          </div>
        )}

        {/* Top Cards (Plan Limit & Connected FB Account) */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {/* Card 1: Product & Catalog Limits */}
          <div className="bg-white border border-slate-200/80 rounded-2xl p-4 sm:p-5 shadow-xs space-y-4">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <span className="text-[11px] font-bold text-slate-400 uppercase tracking-wider">Usage &amp; Limits</span>
                {stats.subscriptionStatus === 'trial' && (
                  <span className="inline-flex items-center gap-1 text-[10px] font-bold text-theme bg-theme/10 border border-theme/20 px-2 py-0.5 rounded-full">
                    <i className="fa-solid fa-wand-magic-sparkles text-[10px] text-theme" />
                    <span>Trial ({stats.trialDaysRemaining ?? 14}d left)</span>
                  </span>
                )}
              </div>
              <Link
                href={getHref('/pricing')}
                className="text-xs font-semibold text-theme hover:text-theme-hover flex items-center gap-1"
              >
                <span>Upgrade Plan</span>
                <i className="fa-solid fa-arrow-up-right-from-square text-[10px]" />
              </Link>
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div className="bg-slate-50 p-3 sm:p-3.5 rounded-xl border border-slate-200/60">
                <p className="text-[11px] font-medium text-slate-500">Your store products</p>
                <p className="text-lg sm:text-xl font-bold text-slate-900 mt-1">
                  {stats.totalProducts}{' '}
                  <span className="text-xs font-normal text-slate-400">
                    / {stats.productLimit !== null && stats.productLimit !== undefined ? stats.productLimit.toLocaleString() : 'Unlimited'}
                  </span>
                </p>
              </div>
              <div className="bg-slate-50 p-3 sm:p-3.5 rounded-xl border border-slate-200/60">
                <p className="text-[11px] font-medium text-slate-500">Catalogs &amp; feeds created</p>
                <p className="text-lg sm:text-xl font-bold text-slate-900 mt-1">
                  {catalogs.length}{' '}
                  <span className="text-xs font-normal text-slate-400">
                    / {stats.catalogLimit !== null && stats.catalogLimit !== undefined ? stats.catalogLimit : 'Unlimited'}
                  </span>
                </p>
              </div>
            </div>
          </div>

          {/* Card 2: Facebook Account Connection State (3 States) */}
          {metaStatus === 'connected' && metaAccount?.connected ? (
            /* State 2: Connected & Verified */
            <div className="bg-white border border-slate-200/80 rounded-2xl p-4 sm:p-5 shadow-xs space-y-3">
              <div className="flex flex-wrap sm:flex-nowrap items-center justify-between gap-2">
                <div className="flex items-center gap-2.5 min-w-0">
                  <div className="w-8 h-8 rounded-full bg-blue-600 text-white flex items-center justify-center font-bold text-sm shadow-2xs shrink-0">
                    <i className="fa-brands fa-facebook-f" />
                  </div>
                  <div className="min-w-0">
                    <h4 className="text-xs font-bold text-slate-900 truncate">
                      {metaAccount?.user?.name || 'Connected Facebook Account'}
                    </h4>
                    <p className="text-[11px] text-emerald-600 flex items-center gap-1 font-medium">
                      <span className="w-1.5 h-1.5 rounded-full bg-emerald-500 shrink-0"></span> Connected &amp; Verified
                    </p>
                  </div>
                </div>
                <button
                  type="button"
                  onClick={handleDisconnectFb}
                  className="px-3 py-1.5 text-xs font-semibold bg-white border border-slate-200 hover:bg-slate-50 text-slate-700 rounded-xl transition shadow-2xs cursor-pointer shrink-0"
                >
                  Disconnect
                </button>
              </div>

              <div className="pt-1">
                <label className="block text-[11px] font-semibold text-slate-600 mb-1">Choose business account</label>
                <select
                  value={selectedBizId}
                  onChange={e => setSelectedBizId(e.target.value)}
                  className="w-full px-3 py-2 bg-white border border-slate-200 rounded-xl text-xs text-slate-800 focus:outline-none focus:ring-2 focus:ring-theme/20 focus:border-theme"
                >
                  <option value="">All business accounts</option>
                  {metaAccount?.businesses?.map(b => (
                    <option key={b.id} value={b.id}>
                      {b.name}
                    </option>
                  ))}
                </select>
              </div>
            </div>
          ) : metaStatus === 'token_expired' ? (
            /* State 3: Session Expired / Reconnect */
            <div className="bg-white border border-amber-200 rounded-2xl p-4 sm:p-5 shadow-xs space-y-3 bg-amber-50/20">
              <div className="flex flex-wrap sm:flex-nowrap items-center justify-between gap-2">
                <div className="flex items-center gap-2.5 min-w-0">
                  <div className="w-8 h-8 rounded-full bg-amber-500 text-white flex items-center justify-center font-bold text-sm shadow-2xs shrink-0">
                    <i className="fa-solid fa-triangle-exclamation" />
                  </div>
                  <div className="min-w-0">
                    <h4 className="text-xs font-bold text-slate-900 truncate">
                      {metaAccount?.user?.name ? `${metaAccount.user.name} (Expired)` : 'Facebook Session Expired'}
                    </h4>
                    <p className="text-[11px] text-amber-600 flex items-center gap-1 font-medium">
                      <span className="w-1.5 h-1.5 rounded-full bg-amber-500 shrink-0"></span> Action Required &bull; Reconnect
                    </p>
                  </div>
                </div>
                <button
                  type="button"
                  onClick={() => openMetaOAuthPopup(false)}
                  disabled={isConnectingFb}
                  className="px-3.5 py-1.5 text-xs font-bold bg-amber-600 hover:bg-amber-700 text-white rounded-xl transition shadow-xs cursor-pointer inline-flex items-center gap-1.5 shrink-0 disabled:opacity-50"
                >
                  <i className={`fa-solid fa-rotate-right text-xs ${isConnectingFb ? 'fa-spin' : ''}`} />
                  <span>{isConnectingFb ? 'Connecting...' : 'Reconnect'}</span>
                </button>
              </div>
              <p className="text-[11px] text-amber-800 bg-amber-50 border border-amber-200/60 p-2 rounded-xl">
                Your Facebook access token has expired. Please reconnect to resume catalog syncing.
              </p>
            </div>
          ) : (
            /* State 1: Not Connected */
            <div className="bg-white border border-slate-200/80 rounded-2xl p-4 sm:p-5 shadow-xs space-y-3">
              <div className="flex flex-wrap sm:flex-nowrap items-center justify-between gap-2">
                <div className="flex items-center gap-2.5 min-w-0">
                  <div className="w-8 h-8 rounded-full bg-slate-100 text-slate-500 flex items-center justify-center font-bold text-sm shadow-2xs shrink-0">
                    <i className="fa-brands fa-facebook-f" />
                  </div>
                  <div className="min-w-0">
                    <h4 className="text-xs font-bold text-slate-900 truncate">
                      No Facebook Account Connected
                    </h4>
                    <p className="text-[11px] text-slate-500 flex items-center gap-1">
                      <span className="w-1.5 h-1.5 rounded-full bg-slate-400 shrink-0"></span> Not Connected
                    </p>
                  </div>
                </div>
                <button
                  type="button"
                  onClick={() => openMetaOAuthPopup(false)}
                  disabled={isConnectingFb}
                  className="px-3.5 py-1.5 text-xs font-bold bg-[#1877F2] hover:bg-[#166fe5] text-white rounded-xl transition shadow-xs cursor-pointer inline-flex items-center gap-1.5 shrink-0 disabled:opacity-50"
                >
                  <i className={`fa-brands fa-facebook text-xs ${isConnectingFb ? 'animate-pulse' : ''}`} />
                  <span>{isConnectingFb ? 'Opening Facebook...' : 'Connect Facebook'}</span>
                </button>
              </div>
              <p className="text-[11px] text-slate-500 bg-slate-50 border border-slate-100 p-2 rounded-xl">
                <i className="fa-solid fa-circle-info text-slate-400 mr-1" />
                Connect your Facebook account to create &amp; manage catalogs and synchronize product feeds with Meta Commerce Manager.
              </p>
            </div>
          )}
        </div>

        {/* Tab 1: Catalogs View */}
        {activeTab === 'catalogs' && (
          <div className="bg-white border border-slate-200/80 rounded-2xl shadow-xs overflow-hidden">
            {/* Header & Create Button */}
            <div className="p-4 sm:p-5 border-b border-slate-100 flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-3">
              <div className="flex items-center gap-2">
                <i className="fa-solid fa-layer-group text-theme text-sm" />
                <h3 className="text-sm font-bold text-slate-900">Catalogs ({catalogs.length})</h3>
              </div>
              <div className="flex flex-wrap items-center gap-2">
                <button
                  type="button"
                  onClick={() => {
                    if (metaStatus !== 'connected' || !metaAccount?.connected) {
                      setNotification({
                        type: 'error',
                        title: 'Facebook Login Required',
                        message: 'Facebook account connection is required to synchronize products.',
                      });
                      openMetaOAuthPopup(false);
                      return;
                    }
                    handleRefreshProductsFromShopify();
                  }}
                  disabled={isRefreshingProducts}
                  className="px-3 py-2 bg-white hover:bg-slate-50 border border-slate-200 text-slate-700 text-xs font-semibold rounded-xl flex items-center justify-center gap-1.5 shadow-xs transition active:scale-98 disabled:opacity-50 cursor-pointer"
                  title="Pull latest products and updates directly from Shopify"
                >
                  <i className={`fa-solid fa-arrows-rotate text-theme text-xs ${isRefreshingProducts ? 'fa-spin' : ''}`} />
                  <span>{isRefreshingProducts ? 'Syncing Products...' : 'Sync Products from Shopify'}</span>
                </button>
                {stats.catalogLimit !== null && catalogs.length >= stats.catalogLimit ? (
                  <Link
                    href={getHref('/pricing')}
                    className="px-4 py-2 bg-theme hover:bg-theme-hover text-white text-xs font-semibold rounded-xl flex items-center justify-center gap-1.5 shadow-sm transition active:scale-98"
                    title={`Catalog limit reached (${stats.catalogLimit}). Click to upgrade.`}
                  >
                    <i className="fa-solid fa-wand-magic-sparkles text-xs" />
                    <span>Upgrade Plan</span>
                  </Link>
                ) : (
                  <button
                    type="button"
                    onClick={() => {
                      if (metaStatus !== 'connected' || !metaAccount?.connected) {
                        openMetaOAuthPopup(true);
                      } else {
                        router.push(getHref('/catalog/create'));
                      }
                    }}
                    className="px-4 py-2 bg-theme hover:bg-theme-hover text-white text-xs font-bold rounded-xl flex items-center justify-center gap-1.5 shadow-sm hover:shadow-md transition active:scale-98 cursor-pointer"
                  >
                    <i className="fa-solid fa-plus text-xs" />
                    <span>Create catalog</span>
                  </button>
                )}
              </div>
            </div>

            {/* Catalogs Table */}
            {loading ? (
              <div className="p-16 text-center text-slate-400 flex items-center justify-center gap-2 text-xs">
                <i className="fa-solid fa-spinner fa-spin text-theme text-sm" />
                <span>Loading catalogs...</span>
              </div>
            ) : catalogs.length === 0 ? (
              <div className="p-12 sm:p-16 text-center space-y-4 max-w-md mx-auto">
                <div className="w-12 h-12 rounded-2xl bg-theme/10 text-theme flex items-center justify-center mx-auto">
                  <i className="fa-solid fa-boxes-stacked text-xl" />
                </div>
                <div className="space-y-1">
                  <h4 className="text-sm font-bold text-slate-900">No Catalogs Created Yet</h4>
                  <p className="text-xs text-slate-500">
                    Create your first Facebook product catalog to automatically sync your Shopify products and launch dynamic ads.
                  </p>
                </div>
                <div className="pt-2">
                  {stats.catalogLimit !== null && catalogs.length >= stats.catalogLimit ? (
                    <Link
                      href={getHref('/pricing')}
                      className="inline-flex items-center gap-1.5 px-4 py-2 bg-theme hover:bg-theme-hover text-white text-xs font-semibold rounded-xl shadow-sm transition"
                    >
                      <i className="fa-solid fa-wand-magic-sparkles text-xs" />
                      <span>Upgrade Plan to Create More</span>
                    </Link>
                  ) : (
                    <button
                      type="button"
                      onClick={() => {
                        if (metaStatus !== 'connected' || !metaAccount?.connected) {
                          openMetaOAuthPopup(true);
                        } else {
                          router.push(getHref('/catalog/create'));
                        }
                      }}
                      className="inline-flex items-center gap-1.5 px-4 py-2 bg-theme hover:bg-theme-hover text-white text-xs font-bold rounded-xl shadow-sm hover:shadow-md transition cursor-pointer"
                    >
                      <i className="fa-solid fa-plus text-xs" />
                      <span>Create catalog</span>
                    </button>
                  )}
                </div>
              </div>
            ) : (
              <div className="overflow-x-auto">
                <table className="w-full text-left text-xs border-collapse min-w-[700px]">
                  <thead>
                    <tr className="bg-slate-50 text-slate-400 uppercase tracking-wider text-[10px] font-bold border-b border-slate-100">
                      <th className="py-3 px-4 w-28">Auto sync</th>
                      <th className="py-3 px-4 sm:px-5">Catalog name</th>
                      <th className="py-3 px-4">Status</th>
                      <th className="py-3 px-4">Tracking pixel</th>
                      <th className="py-3 px-4 sm:px-5">Last synced</th>
                      <th className="py-3 px-4 text-right w-16">Action</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-100">
                    {catalogs.map(cat => {
                      const { lastText, nextText } = formatLastSync(cat.last_synced_at, cat.next_sync_at);
                      const isRecentlyUpdated = cat.updated_at ? (Date.now() - new Date(cat.updated_at).getTime() < 120000) : false;
                      const isSyncing = Boolean(syncingMap[cat.id] || (cat.status === 'syncing' && isRecentlyUpdated));
                      const variantCount = cat.variant_count || 0;

                      return (
                        <tr key={cat.id} className="hover:bg-slate-50/70 transition-colors">
                          {/* Auto Sync Toggle */}
                          <td className="py-3.5 px-4">
                            <button
                              type="button"
                              onClick={() => handleToggleAutoSync(cat.id, cat.auto_sync)}
                              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 ${
                                cat.auto_sync ? 'bg-theme' : 'bg-slate-200'
                              }`}
                            >
                              <span
                                className={`pointer-events-none inline-block h-4 w-4 transform rounded-full bg-white shadow-sm ring-0 transition duration-200 ease-in-out ${
                                  cat.auto_sync ? 'translate-x-4' : 'translate-x-0'
                                }`}
                              />
                            </button>
                          </td>

                          {/* Catalog Name + Meta Catalog ID + Variant Count */}
                          <td className="py-3.5 px-4 sm:px-5">
                            <div>
                              <div className="flex flex-wrap items-center gap-2">
                                <p className="font-bold text-slate-900 text-xs hover:text-theme transition">
                                  <Link href={getHref(`/catalog/edit/${cat.id}`)}>{cat.name}</Link>
                                </p>
                                {cat.fb_catalog_id && (
                                  <a
                                    href={cat.fb_catalog_url || (cat.fb_business_id ? `https://business.facebook.com/commerce/catalogs/${cat.fb_catalog_id}/home/?business_id=${cat.fb_business_id}` : `https://business.facebook.com/commerce/catalogs/${cat.fb_catalog_id}/home/`)}
                                    target="_blank"
                                    rel="noreferrer"
                                    className="inline-flex items-center gap-1 text-[11px] text-theme hover:text-theme-hover hover:underline font-medium"
                                    title="Open in Facebook Commerce Manager"
                                  >
                                    <span>Commerce Manager</span>
                                    <i className="fa-solid fa-arrow-up-right-from-square text-[10px] text-theme" />
                                  </a>
                                )}
                              </div>
                              <div className="text-[11px] text-slate-400 flex items-center gap-2 mt-0.5">
                                <span>Catalog ID: <span className="font-mono text-slate-700 font-semibold">{cat.fb_catalog_id || 'Pending'}</span></span>
                                <span>•</span>
                                <span className="text-slate-600 font-medium">
                                  {variantCount} {variantCount === 1 ? 'variant' : 'variants'}
                                </span>
                              </div>
                            </div>
                          </td>

                          {/* Status Badge */}
                          <td className="py-3.5 px-4 whitespace-nowrap">
                            {isSyncing ? (
                              <span className="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-[10px] font-semibold bg-theme/10 text-theme border border-theme/20">
                                <i className="fa-solid fa-arrows-rotate fa-spin text-theme text-[10px]" /> Syncing
                              </span>
                            ) : cat.status === 'synced' ? (
                              <span className="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-[10px] font-semibold bg-emerald-50 text-emerald-700 border border-emerald-200/60">
                                <span className="w-1.5 h-1.5 rounded-full bg-emerald-500"></span> Synced
                              </span>
                            ) : cat.status === 'failed' ? (
                              <span className="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-[10px] font-semibold bg-rose-50 text-rose-700 border border-rose-200/60">
                                <span className="w-1.5 h-1.5 rounded-full bg-rose-500"></span> Failed
                              </span>
                            ) : (
                              <span className="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-[10px] font-semibold bg-slate-100 text-slate-700 border border-slate-200">
                                <span className="w-1.5 h-1.5 rounded-full bg-slate-400"></span> Pending
                              </span>
                            )}
                          </td>

                          {/* Tracking Pixel Toggle */}
                          <td className="py-3.5 px-4 whitespace-nowrap">
                            <div className="flex items-center gap-2">
                              <button
                                type="button"
                                onClick={() => handleTogglePixel(cat.id, cat.pixel_tracking)}
                                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 ${
                                  cat.pixel_tracking ? 'bg-theme' : 'bg-slate-200'
                                }`}
                              >
                                <span
                                  className={`pointer-events-none inline-block h-4 w-4 transform rounded-full bg-white shadow-sm ring-0 transition duration-200 ease-in-out ${
                                    cat.pixel_tracking ? 'translate-x-4' : 'translate-x-0'
                                  }`}
                                />
                              </button>
                              {cat.fb_pixel_id && (
                                <span className="text-[11px] text-slate-500 truncate max-w-[110px]" title={cat.fb_pixel_id}>
                                  {cat.fb_pixel_id}
                                </span>
                              )}
                            </div>
                          </td>

                          {/* Last Synced / Next Synced */}
                          <td className="py-3.5 px-4 sm:px-5 whitespace-nowrap">
                            <div>
                              <p className="text-slate-800 font-medium text-xs">{lastText}</p>
                              {nextText && <p className="text-[10px] text-slate-400 mt-0.5">{nextText}</p>}
                            </div>
                          </td>

                          {/* Actions Menu */}
                          <td className="py-3.5 px-4 text-right">
                            <CatalogActionMenu
                              catalog={cat}
                              onSyncNow={handleSyncNow}
                              onDelete={handleDeleteCatalog}
                              shop={currentShop}
                            />
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        )}

        {/* Tab 2: Feeds View */}
        {activeTab === 'feeds' && (
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
            {/* XML RSS Feed Card */}
            <div className="bg-white p-4 sm:p-5 rounded-2xl border border-slate-200/80 shadow-xs space-y-3">
              <div className="flex flex-wrap sm:flex-nowrap items-center justify-between gap-2">
                <div className="flex items-center gap-2.5">
                  <div className="w-8 h-8 rounded-xl bg-theme/10 text-theme flex items-center justify-center font-bold shrink-0">
                    <i className="fa-solid fa-code text-sm" />
                  </div>
                  <div>
                    <h3 className="font-bold text-xs text-slate-900">Primary Meta XML Feed (RSS 2.0)</h3>
                    <p className="text-[10px] text-slate-400">Facebook &amp; Instagram Dynamic Ads</p>
                  </div>
                </div>
                <a
                  href={feedUrls.xml}
                  target="_blank"
                  rel="noreferrer"
                  className="text-[11px] text-theme hover:underline flex items-center gap-1 font-semibold shrink-0"
                >
                  <span>View Raw XML</span>
                  <i className="fa-solid fa-arrow-up-right-from-square text-[10px]" />
                </a>
              </div>

              <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-2 p-2 rounded-xl bg-slate-50 border border-slate-200/80 text-xs font-mono text-slate-700">
                <span className="truncate flex-1 min-w-0 text-[11px]">{feedUrls.xml || '/api/catalog/feed/meta.xml'}</span>
                <button
                  onClick={() => copyToClipboard('xml')}
                  className="px-2.5 py-1 rounded-lg bg-white border border-slate-200/80 hover:bg-slate-50 text-slate-700 font-sans font-semibold shrink-0 flex items-center justify-center gap-1 shadow-2xs cursor-pointer"
                >
                  {copiedFeed === 'xml' ? <i className="fa-solid fa-check text-emerald-600 text-xs" /> : <i className="fa-regular fa-copy text-xs" />}
                  <span>{copiedFeed === 'xml' ? 'Copied' : 'Copy'}</span>
                </button>
              </div>

              <p className="text-[11px] text-slate-500">
                Paste in <strong>Meta Commerce Manager &gt; Data Sources &gt; Data Feed &gt; Set a Schedule</strong>.
              </p>
            </div>

            {/* CSV Feed Card */}
            <div className="bg-white p-4 sm:p-5 rounded-2xl border border-slate-200/80 shadow-xs space-y-3">
              <div className="flex flex-wrap sm:flex-nowrap items-center justify-between gap-2">
                <div className="flex items-center gap-2.5">
                  <div className="w-8 h-8 rounded-xl bg-emerald-50 text-emerald-600 flex items-center justify-center font-bold shrink-0">
                    <i className="fa-solid fa-file-csv text-sm" />
                  </div>
                  <div>
                    <h3 className="font-bold text-xs text-slate-900">Standard Meta CSV Bulk Feed</h3>
                    <p className="text-[10px] text-slate-400">Manual upload or offline backup</p>
                  </div>
                </div>
                <a
                  href={feedUrls.csv}
                  target="_blank"
                  rel="noreferrer"
                  className="text-[11px] text-emerald-600 hover:underline flex items-center gap-1 font-semibold shrink-0"
                >
                  <span>Download CSV</span>
                  <i className="fa-solid fa-arrow-up-right-from-square text-[10px]" />
                </a>
              </div>

              <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-2 p-2 rounded-xl bg-slate-50 border border-slate-200/80 text-xs font-mono text-slate-700">
                <span className="truncate flex-1 min-w-0 text-[11px]">{feedUrls.csv || '/api/catalog/feed/meta.csv'}</span>
                <button
                  onClick={() => copyToClipboard('csv')}
                  className="px-2.5 py-1 rounded-lg bg-white border border-slate-200/80 hover:bg-slate-50 text-slate-700 font-sans font-semibold shrink-0 flex items-center justify-center gap-1 shadow-2xs cursor-pointer"
                >
                  {copiedFeed === 'csv' ? <i className="fa-solid fa-check text-emerald-600 text-xs" /> : <i className="fa-regular fa-copy text-xs" />}
                  <span>{copiedFeed === 'csv' ? 'Copied' : 'Copy'}</span>
                </button>
              </div>

              <p className="text-[11px] text-slate-500">
                Fully compliant with Facebook Catalog bulk upload requirements.
              </p>
            </div>
          </div>
        )}
      </div>
    </AppLayout>
  );
}
