'use client';

import React, { useState, useEffect } from 'react';
import { useRouter, useParams, useSearchParams } from 'next/navigation';
import Link from 'next/link';
import AppLayout from '@/components/layout/AppLayout';
import { apiUrl, appRoute } from '@/lib/utils/asset';
import { ProductPickerModal } from '../../components/ProductPickerModal';
import { CollectionPickerModal } from '../../components/CollectionPickerModal';
import { TagPickerModal } from '../../components/TagPickerModal';
import { CategorySearchInput } from '../../components/CategorySearchInput';
import { TemplateLibrarySelector } from '../../components/TemplateLibrarySelector';
import { ProductTemplate } from '@/lib/templates/template-service';
import { ShopifyProduct, ShopifyCollection } from '@/lib/shopify/product-service';
import { VariantExportMode, CatalogRecord, CatalogSelectionRecord, CatalogFormData } from '@/types/catalog';
import { scrollToFirstError, useFormErrorScroll } from '@/lib/utils/scroll-to-error';

const TIMEZONES = [
  'America/New_York',
  'America/Los_Angeles',
  'America/Chicago',
  'America/Denver',
  'Europe/London',
  'Europe/Paris',
  'Europe/Berlin',
  'Asia/Dubai',
  'Asia/Kolkata',
  'Asia/Singapore',
  'Asia/Tokyo',
  'Australia/Sydney',
  'UTC',
];

export default function EditCatalogPage() {
  const router = useRouter();
  const params = useParams();
  const searchParams = useSearchParams();
  const catalogId = params?.id as string;
  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 [loading, setLoading] = useState(true);
  const [catalog, setCatalog] = useState<CatalogRecord | null>(null);

  // General Settings
  const [name, setName] = useState('');
  const [fbBusinessId, setFbBusinessId] = useState('');
  const [fbCatalogId, setFbCatalogId] = useState('');
  const [fbPixelId, setFbPixelId] = useState('');
  const [fbCommerceManagerUrl, setFbCommerceManagerUrl] = useState('');
  const [businesses, setBusinesses] = useState<Array<{ id: string; name: string }>>([]);
  const [catalogs, setCatalogs] = useState<Array<{ id: string; name: string }>>([]);
  const [pixels, setPixels] = useState<Array<{ id: string; name: string }>>([]);

  // Sync Selections
  const [syncScopeType, setSyncScopeType] = useState<'all' | 'collections' | 'tags' | 'specific_products'>('all');
  const [selectedCollections, setSelectedCollections] = useState<ShopifyCollection[]>([]);
  const [selectedTags, setSelectedTags] = useState<string[]>([]);
  const [selectedProducts, setSelectedProducts] = useState<ShopifyProduct[]>([]);
  const [excludeOutOfStock, setExcludeOutOfStock] = useState(false);
  const [excludeTags, setExcludeTags] = useState('');
  const [excludedCollections, setExcludedCollections] = useState<ShopifyCollection[]>([]);
  const [excludedTags, setExcludedTags] = useState<string[]>([]);
  const [excludedProducts, setExcludedProducts] = useState<ShopifyProduct[]>([]);
  const [activeExcludeTab, setActiveExcludeTab] = useState<'collections' | 'tags' | 'specific_products' | null>(null);

  // Modals
  const [isProductModalOpen, setIsProductModalOpen] = useState(false);
  const [isCollectionModalOpen, setIsCollectionModalOpen] = useState(false);
  const [isTagModalOpen, setIsTagModalOpen] = useState(false);
  const [isExcludeProductModalOpen, setIsExcludeProductModalOpen] = useState(false);
  const [isExcludeCollectionModalOpen, setIsExcludeCollectionModalOpen] = useState(false);
  const [isExcludeTagModalOpen, setIsExcludeTagModalOpen] = useState(false);

  // Variant & Taxonomy
  const [selectedTemplateId, setSelectedTemplateId] = useState<string>('tpl_advantage_plus');
  const [priceMode, setPriceMode] = useState<'compare_at_and_price' | 'price_only' | 'compare_at_only'>('compare_at_and_price');
  const [variantExportMode, setVariantExportMode] = useState<VariantExportMode>('all_separate');
  const [googleCategory, setGoogleCategory] = useState('');
  const [imageOption, setImageOption] = useState<'all' | 'first'>('all');
  const [productLinkDomain, setProductLinkDomain] = useState<'myshopify' | 'primary' | 'custom'>('myshopify');
  const [customDomain, setCustomDomain] = useState('');

  const handleTemplateSelected = (tpl: ProductTemplate) => {
    setSelectedTemplateId(tpl.id);
    if (tpl.priceRule) {
      setPriceMode(tpl.priceRule);
    }
  };

  // Schedule & Auto Sync
  const [isAutoSync, setIsAutoSync] = useState(true);
  const [pixelTrackingEnabled, setPixelTrackingEnabled] = useState(true);
  const [scheduleType, setScheduleType] = useState<'daily' | 'weekly'>('daily');
  const [scheduleDay, setScheduleDay] = useState('Every Monday');
  const [scheduleHour, setScheduleHour] = useState(2);
  const [schedulePeriod, setSchedulePeriod] = useState<'AM' | 'PM'>('AM');
  const [scheduleTimezone, setScheduleTimezone] = useState('America/New_York');
  const [shopifyStoreTimezone, setShopifyStoreTimezone] = useState<string>('');

  // Form state
  const [submitting, setSubmitting] = useState(false);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});

  // Auto-scroll smoothly toward error whenever form validation fails or API returns error
  useFormErrorScroll(errorMessage);
  useFormErrorScroll(fieldErrors);

  useEffect(() => {
    if (catalogId) {
      loadCatalogData();
      fetchMetaAccounts();
      fetchShopTimezone();
    }
  }, [catalogId, currentShop]);

  const fetchShopTimezone = async () => {
    try {
      const res = await fetch(getEndpoint('/api/shops'));
      const data = await res.json();
      if (data.success && data.store?.timezone) {
        setShopifyStoreTimezone(data.store.timezone);
      }
    } catch (err) {
      console.warn('Failed to fetch Shopify store timezone', err);
    }
  };

  const loadCatalogData = async () => {
    try {
      const res = await fetch(getEndpoint(`/api/catalogs/${catalogId}`));
      const data = await res.json();
      if (data.success && data.catalog) {
        const c: CatalogRecord = data.catalog;
        setCatalog(c);
        setName(c.name);
        setFbBusinessId(c.fb_business_id || '');
        setFbCatalogId(c.fb_catalog_id || '');
        setFbPixelId(c.fb_pixel_id || '');
        setSyncScopeType(c.sync_scope === 'all' ? 'all' : 'collections');
        setVariantExportMode(c.variant_mode);
        setGoogleCategory(c.google_category_name || '');
        setImageOption(c.additional_images ? 'all' : 'first');
        setProductLinkDomain(c.link_domain);
        setCustomDomain(c.custom_domain || '');
        setExcludeOutOfStock(Boolean(c.exclude_out_of_stock));
        setPriceMode(c.price_mode || 'compare_at_and_price');
        setIsAutoSync(c.auto_sync);
        setPixelTrackingEnabled(c.pixel_tracking);
        setScheduleType(c.schedule_type);
        setScheduleDay(c.schedule_day || 'Every Monday');
        setScheduleHour(c.schedule_hour || 2);
        setSchedulePeriod(c.schedule_period || 'AM');
        setScheduleTimezone(c.schedule_tz || 'America/New_York');
        setFbCommerceManagerUrl(data.fbCommerceManagerUrl || c.fb_catalog_url || '');

        if (data.selections && Array.isArray(data.selections)) {
          const sels: CatalogSelectionRecord[] = data.selections;
          const cols = sels
            .filter(s => s.type === 'collection' && !s.is_exclude)
            .map(s => ({ id: s.shopify_gid.replace(/^gid:\/\/shopify\/Collection\//, ''), title: s.value }));
          const tgs = sels
            .filter(s => s.type === 'tag' && !s.is_exclude)
            .map(s => s.value);
          const prods = sels
            .filter(s => s.type === 'product' && !s.is_exclude)
            .map(s => {
              const cleanId = s.shopify_gid.replace(/^gid:\/\/shopify\/Product\//, '');
              const displayTitle = (s as any).title || s.value || `Product #${cleanId}`;
              return { id: cleanId, title: displayTitle, handle: '', image: (s as any).image || '' };
            });

          const exCols = sels
            .filter(s => s.type === 'collection' && s.is_exclude)
            .map(s => ({ id: s.shopify_gid.replace(/^gid:\/\/shopify\/Collection\//, ''), title: s.value }));
          const exTags = sels
            .filter(s => s.type === 'tag' && s.is_exclude)
            .map(s => s.value);
          const exProds = sels
            .filter(s => s.type === 'product' && s.is_exclude)
            .map(s => {
              const cleanId = s.shopify_gid.replace(/^gid:\/\/shopify\/Product\//, '');
              const displayTitle = (s as any).title || s.value || `Product #${cleanId}`;
              return { id: cleanId, title: displayTitle, handle: '', image: (s as any).image || '' };
            });

          setSelectedCollections(cols as any);
          setSelectedTags(tgs);
          setSelectedProducts(prods as any);
          setExcludedCollections(exCols as any);
          setExcludedTags(exTags);
          setExcludedProducts(exProds as any);
          setExcludeTags('');

          if (exCols.length > 0) setActiveExcludeTab('collections');
          else if (exTags.length > 0) setActiveExcludeTab('tags');
          else if (exProds.length > 0) setActiveExcludeTab('specific_products');

          if (c.sync_scope === 'all') {
            setSyncScopeType('all');
          } else if (cols.length > 0) {
            setSyncScopeType('collections');
          } else if (tgs.length > 0) {
            setSyncScopeType('tags');
          } else if (prods.length > 0) {
            setSyncScopeType('specific_products');
          }
        }
      } else {
        setErrorMessage(data.error || 'Failed to load catalog');
      }
    } catch (err: any) {
      setErrorMessage(err.message || 'Failed to load catalog');
    } finally {
      setLoading(false);
    }
  };

  const fetchMetaAccounts = async () => {
    try {
      const [res, pxRes] = await Promise.all([
        fetch(getEndpoint('/api/meta/accounts?connectedOnly=true')),
        fetch(getEndpoint('/api/pixels')),
      ]);
      const data = await res.json();
      const pxData = await pxRes.json();

      if (data.success) {
        setBusinesses(data.businesses || []);
        setCatalogs(data.catalogs || []);
      }

      // Strictly show only connected pixels for this store
      let connectedList: Array<{ id: string; name: string }> = [];
      if (pxData.success && Array.isArray(pxData.pixels)) {
        connectedList = pxData.pixels.map((p: any) => {
          const rawName = p.pixel_name || 'Pixel';
          const cleanName = rawName.includes(p.pixel_id) ? rawName : `${p.pixel_id} - ${rawName}`;
          return {
            id: p.pixel_id,
            name: cleanName,
          };
        });
      } else if (data.pixels && Array.isArray(data.pixels)) {
        connectedList = data.pixels.map((p: any) => ({
          id: p.id,
          name: p.name,
        }));
      }

      setPixels(connectedList);
    } catch (err) {
      console.error('Failed to load Meta accounts', err);
    }
  };

  const handleBusinessChange = async (bizId: string) => {
    setFbBusinessId(bizId);
    if (fieldErrors.fbBusinessId) {
      setFieldErrors(prev => {
        const copy = { ...prev };
        delete copy.fbBusinessId;
        return copy;
      });
    }
    try {
      const res = await fetch(getEndpoint(`/api/meta/accounts?connectedOnly=true&businessId=${bizId}`));
      const data = await res.json();
      if (data.success) {
        if (data.catalogs) {
          setCatalogs(data.catalogs);
        }
      }
    } catch (err) {
      console.error('Failed to refresh pixels for business', err);
    }
  };

  const validateForm = (): boolean => {
    const errors: Record<string, string> = {};

    if (!name.trim()) {
      errors.name = 'Catalog Name is required';
    } else if (name.trim().length > 150) {
      errors.name = 'Catalog Name cannot exceed 150 characters';
    }

    if (syncScopeType === 'collections' && selectedCollections.length === 0) {
      errors.syncScope = 'Please select at least one collection';
    }

    if (syncScopeType === 'tags' && selectedTags.length === 0) {
      errors.syncScope = 'Please select at least one tag';
    }

    if (syncScopeType === 'specific_products' && selectedProducts.length === 0) {
      errors.syncScope = 'Please select at least one product';
    }

    if (productLinkDomain === 'custom') {
      if (!customDomain.trim()) {
        errors.customDomain = 'Custom domain is required';
      } else if (!/^https?:\/\/.+/i.test(customDomain.trim()) && !/^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/.test(customDomain.trim())) {
        errors.customDomain = 'Please enter a valid domain (e.g. https://yourdomain.com)';
      }
    }

    setFieldErrors(errors);
    if (Object.keys(errors).length > 0) {
      const firstError = Object.values(errors)[0];
      setErrorMessage(firstError);
      scrollToFirstError();
      return false;
    }

    setErrorMessage(null);
    return true;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validateForm()) {
      scrollToFirstError();
      return;
    }

    setSubmitting(true);
    setErrorMessage(null);

    const isSelectedMode = syncScopeType !== 'all';
    const manualTags = excludeTags ? excludeTags.split(',').map(t => t.trim()).filter(Boolean) : [];
    const allExcludedTags = Array.from(new Set([...excludedTags, ...manualTags]));

    const payload: CatalogFormData = {
      name: name.trim(),
      business_id: fbBusinessId,
      fb_catalog_id: fbCatalogId || undefined,
      pixel_id: fbPixelId || undefined,
      sync_scope: isSelectedMode ? 'selected' : 'all',
      selected_collections: syncScopeType === 'collections' ? selectedCollections.map(c => ({ id: String(c.id), title: c.title })) : [],
      selected_tags: syncScopeType === 'tags' ? selectedTags : [],
      selected_products: syncScopeType === 'specific_products' ? selectedProducts.map(p => ({ id: String(p.id), title: p.title })) : [],
      exclude_products_active: allExcludedTags.length > 0 || excludeOutOfStock || excludedCollections.length > 0 || excludedProducts.length > 0,
      exclude_out_of_stock: excludeOutOfStock,
      excluded_collections: excludedCollections.map(c => ({ id: String(c.id), title: c.title })),
      excluded_tags: allExcludedTags,
      excluded_products: excludedProducts.map(p => ({ id: String(p.id), title: p.title })),
      variant_mode: variantExportMode,
      google_category_id: googleCategory ? 'tax_' + googleCategory.substring(0, 10) : '',
      google_category_name: googleCategory,
      additional_images: imageOption === 'all',
      link_domain: productLinkDomain,
      custom_domain: productLinkDomain === 'custom' ? customDomain.trim() : undefined,
      price_mode: priceMode,
      schedule_type: scheduleType,
      schedule_day: scheduleDay,
      schedule_hour: scheduleHour,
      schedule_period: schedulePeriod,
      schedule_tz: scheduleTimezone,
      auto_sync: isAutoSync,
      pixel_tracking: pixelTrackingEnabled,
    };

    try {
      const res = await fetch(getEndpoint(`/api/catalogs/${catalogId}`), {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });

      const data = await res.json();
      if (data.success) {
        if (data.syncResult && !data.syncResult.success) {
          setErrorMessage(`Saved changes, but Meta sync had an issue: ${data.syncResult.error || 'Check catalog status'}`);
          scrollToFirstError();
        } else {
          router.push(getHref('/catalog'));
        }
      } else {
        setErrorMessage(data.error || 'Failed to update catalog');
        scrollToFirstError();
      }
    } catch (err: any) {
      setErrorMessage(err.message || 'Failed to update catalog');
      scrollToFirstError();
    } finally {
      setSubmitting(false);
    }
  };

  if (loading) {
    return (
      <AppLayout currentRoute="/catalog">
        <div className="flex items-center justify-center min-h-[50vh] text-xs text-slate-400 gap-2">
          <i className="fa-solid fa-spinner fa-spin text-theme text-sm" />
          <span>Loading catalog details...</span>
        </div>
      </AppLayout>
    );
  }

  return (
    <AppLayout currentRoute="/catalog">
      <ui-title-bar title="Edit Meta Catalog" />
      <div className="max-w-4xl mx-auto space-y-6 pb-16">
        {/* Top Header */}
        <div className="flex items-center justify-between border-b border-slate-200/80 pb-4">
          <div className="flex items-center gap-3">
            <Link
              href={getHref('/catalog')}
              className="p-2 rounded-xl bg-white border border-slate-200 hover:bg-slate-50 text-slate-600 hover:text-slate-900 transition shadow-2xs"
            >
              <i className="fa-solid fa-arrow-left text-xs" />
            </Link>
            <div>
              <h1 className="text-xl font-bold text-slate-900 tracking-tight">Edit Facebook Catalog</h1>
              <p className="text-xs text-slate-500">
                Catalog ID: <span className="font-mono text-slate-800 font-semibold">{catalog?.fb_catalog_id}</span>
              </p>
            </div>
          </div>

          {fbCommerceManagerUrl && (
            <a
              href={fbCommerceManagerUrl}
              target="_blank"
              rel="noreferrer"
              className="px-3.5 py-2 rounded-xl text-xs font-semibold bg-white border border-slate-200 hover:bg-slate-50 text-theme hover:text-theme-hover flex items-center gap-1.5 transition shadow-2xs"
            >
              <span>View in Facebook</span>
              <i className="fa-solid fa-arrow-up-right-from-square text-[10px]" />
            </a>
          )}
        </div>

        {errorMessage && (
          <div
            id="form-error-banner"
            data-error-banner
            role="alert"
            tabIndex={-1}
            className="p-4 rounded-xl bg-rose-50 border border-rose-200 text-rose-900 text-xs flex items-center justify-between shadow-xs"
          >
            <div className="flex items-center gap-2">
              <i className="fa-solid fa-circle-exclamation text-rose-600 text-sm shrink-0" />
              <span className="font-medium">{errorMessage}</span>
            </div>
            <button onClick={() => setErrorMessage(null)} className="text-slate-400 hover:text-slate-600 font-bold p-1">
              ✕
            </button>
          </div>
        )}

        <form onSubmit={handleSubmit} className="space-y-5">
          {/* Section 1: General Settings */}
          <div className="bg-white border border-slate-200/80 rounded-2xl p-5 sm:p-6 shadow-xs space-y-4">
            <div className="flex items-center gap-2 text-xs font-bold text-theme uppercase tracking-wider">
              <i className="fa-solid fa-layer-group text-xs" />
              <span>General Settings</span>
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
              <div>
                <label className="block text-xs font-semibold text-slate-700 mb-1.5">Facebook Business Account</label>
                <select
                  value={fbBusinessId}
                  onChange={e => handleBusinessChange(e.target.value)}
                  className="w-full px-3.5 py-2.5 bg-white border border-slate-200 rounded-xl text-xs text-slate-900 focus:outline-none focus:ring-2 focus:ring-theme/20 focus:border-theme"
                >
                  <option value="">Select a business account</option>
                  {businesses.map(b => (
                    <option key={b.id} value={b.id}>
                      {b.name}
                    </option>
                  ))}
                </select>
              </div>

              <div>
                <label className="block text-xs font-semibold text-slate-700 mb-1.5">Facebook Catalog</label>
                <select
                  value={fbCatalogId}
                  onChange={e => setFbCatalogId(e.target.value)}
                  className="w-full px-3.5 py-2.5 bg-white border border-slate-200 rounded-xl text-xs text-slate-900 focus:outline-none focus:ring-2 focus:ring-theme/20 focus:border-theme"
                >
                  {catalogs.map(c => (
                    <option key={c.id} value={c.id}>
                      {c.id} - {c.name}
                    </option>
                  ))}
                  {fbCatalogId && !catalogs.some(c => c.id === fbCatalogId) && (
                    <option value={fbCatalogId}>{fbCatalogId}</option>
                  )}
                </select>
              </div>

              <div>
                <label className="block text-xs font-semibold text-slate-700 mb-1.5">Meta Pixel (External Event Source)</label>
                <select
                  value={fbPixelId}
                  onChange={e => setFbPixelId(e.target.value)}
                  className="w-full px-3.5 py-2.5 bg-white border border-slate-200 rounded-xl text-xs text-slate-900 focus:outline-none focus:ring-2 focus:ring-theme/20 focus:border-theme"
                >
                  <option value="">{pixels.length === 0 ? 'No connected pixels found' : 'Select a Pixel'}</option>
                  {pixels.map(p => (
                    <option key={p.id} value={p.id}>
                      {p.name}
                    </option>
                  ))}
                  {fbPixelId && !pixels.some(p => p.id === fbPixelId) && (
                    <option value={fbPixelId}>{fbPixelId} - (Previously Selected Pixel)</option>
                  )}
                </select>
                {pixels.length === 0 && (
                  <p className="text-[11px] text-amber-600 mt-1.5 flex items-center gap-1 font-medium">
                    <i className="fa-solid fa-triangle-exclamation text-[10px]" />
                    <span>No connected pixel found in this store. Please connect a pixel first in &quot;Facebook Pixel &amp; CAPI&quot;.</span>
                  </p>
                )}
              </div>
            </div>

            <div>
              <div className="flex items-center justify-between mb-1.5">
                <label className="text-xs font-semibold text-slate-700">
                  Catalog Name <span className="text-rose-500">*</span>
                </label>
                <span className="text-[11px] text-slate-400 font-medium">{name.length}/150</span>
              </div>
              <input
                type="text"
                maxLength={150}
                value={name}
                onChange={e => {
                  setName(e.target.value);
                  if (fieldErrors.name) {
                    setFieldErrors(prev => {
                      const copy = { ...prev };
                      delete copy.name;
                      return copy;
                    });
                  }
                }}
                className={`w-full px-3.5 py-2.5 bg-white border rounded-xl text-xs text-slate-900 placeholder-slate-400 focus:outline-none focus:ring-2 ${
                  fieldErrors.name
                    ? 'border-rose-400 focus:ring-rose-500/20 focus:border-rose-500 bg-rose-50/20'
                    : 'border-slate-200 focus:ring-theme/20 focus:border-theme'
                }`}
              />
              {fieldErrors.name && (
                <p className="text-[11px] text-rose-500 mt-1 font-medium">{fieldErrors.name}</p>
              )}
            </div>
          </div>

          {/* Section 2: What to Sync */}
          <div className={`bg-white border rounded-2xl p-5 sm:p-6 shadow-xs space-y-4 ${
            fieldErrors.syncScope ? 'border-rose-300 ring-1 ring-rose-300/30' : 'border-slate-200/80'
          }`}>
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2 text-xs font-bold text-theme uppercase tracking-wider">
                <i className="fa-solid fa-boxes-stacked text-xs" />
                <span>What to Sync</span>
              </div>
              {fieldErrors.syncScope && (
                <span className="text-xs text-rose-500 font-semibold">{fieldErrors.syncScope}</span>
              )}
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-3">
              <label
                onClick={() => {
                  setSyncScopeType('all');
                  if (fieldErrors.syncScope) {
                    setFieldErrors(prev => {
                      const copy = { ...prev };
                      delete copy.syncScope;
                      return copy;
                    });
                  }
                }}
                className={`flex items-center gap-2.5 p-3 rounded-xl border cursor-pointer transition-all ${
                  syncScopeType === 'all'
                    ? 'bg-theme/5 border-theme text-theme font-semibold shadow-2xs ring-1 ring-theme/20'
                    : 'bg-white border-slate-200 text-slate-700 hover:bg-slate-50'
                }`}
              >
                <input
                  type="radio"
                  name="syncType"
                  checked={syncScopeType === 'all'}
                  onChange={() => setSyncScopeType('all')}
                  className="w-4 h-4 text-theme focus:ring-theme"
                />
                <span className="text-xs">All products</span>
              </label>

              <label
                onClick={() => {
                  setSyncScopeType('collections');
                  if (fieldErrors.syncScope && selectedCollections.length > 0) {
                    setFieldErrors(prev => {
                      const copy = { ...prev };
                      delete copy.syncScope;
                      return copy;
                    });
                  }
                }}
                className={`flex items-center gap-2.5 p-3 rounded-xl border cursor-pointer transition-all ${
                  syncScopeType === 'collections'
                    ? 'bg-theme/5 border-theme text-theme font-semibold shadow-2xs ring-1 ring-theme/20'
                    : 'bg-white border-slate-200 text-slate-700 hover:bg-slate-50'
                }`}
              >
                <input
                  type="radio"
                  name="syncType"
                  checked={syncScopeType === 'collections'}
                  onChange={() => setSyncScopeType('collections')}
                  className="w-4 h-4 text-theme focus:ring-theme"
                />
                <span className="text-xs">Collections</span>
              </label>

              <label
                onClick={() => {
                  setSyncScopeType('tags');
                  if (fieldErrors.syncScope && selectedTags.length > 0) {
                    setFieldErrors(prev => {
                      const copy = { ...prev };
                      delete copy.syncScope;
                      return copy;
                    });
                  }
                }}
                className={`flex items-center gap-2.5 p-3 rounded-xl border cursor-pointer transition-all ${
                  syncScopeType === 'tags'
                    ? 'bg-theme/5 border-theme text-theme font-semibold shadow-2xs ring-1 ring-theme/20'
                    : 'bg-white border-slate-200 text-slate-700 hover:bg-slate-50'
                }`}
              >
                <input
                  type="radio"
                  name="syncType"
                  checked={syncScopeType === 'tags'}
                  onChange={() => setSyncScopeType('tags')}
                  className="w-4 h-4 text-theme focus:ring-theme"
                />
                <span className="text-xs">Tags</span>
              </label>

              <label
                onClick={() => {
                  setSyncScopeType('specific_products');
                  if (fieldErrors.syncScope && selectedProducts.length > 0) {
                    setFieldErrors(prev => {
                      const copy = { ...prev };
                      delete copy.syncScope;
                      return copy;
                    });
                  }
                }}
                className={`flex items-center gap-2.5 p-3 rounded-xl border cursor-pointer transition-all ${
                  syncScopeType === 'specific_products'
                    ? 'bg-theme/5 border-theme text-theme font-semibold shadow-2xs ring-1 ring-theme/20'
                    : 'bg-white border-slate-200 text-slate-700 hover:bg-slate-50'
                }`}
              >
                <input
                  type="radio"
                  name="syncType"
                  checked={syncScopeType === 'specific_products'}
                  onChange={() => setSyncScopeType('specific_products')}
                  className="w-4 h-4 text-theme focus:ring-theme"
                />
                <span className="text-xs">Specific products</span>
              </label>
            </div>

            {/* Collection Picker */}
            {syncScopeType === 'collections' && (
              <div className="p-4 rounded-xl bg-slate-50 border border-slate-200/80 space-y-3">
                <div className="flex items-center justify-between">
                  <span className="text-xs font-semibold text-slate-700">
                    Selected Collections ({selectedCollections.length})
                  </span>
                  <button
                    type="button"
                    onClick={() => setIsCollectionModalOpen(true)}
                    className="px-3 py-1.5 bg-theme hover:bg-theme-hover text-white text-xs font-bold rounded-lg flex items-center gap-1 shadow-sm transition"
                  >
                    <i className="fa-solid fa-plus text-xs" /> Select collections
                  </button>
                </div>
                {selectedCollections.length > 0 && (
                  <div className="flex flex-wrap gap-2">
                    {selectedCollections.map(c => (
                      <span
                        key={c.id}
                        className="inline-flex items-center gap-1.5 px-3 py-1 rounded-lg bg-white border border-slate-200 text-xs text-slate-800 shadow-2xs font-medium"
                      >
                        {c.title}
                        <button
                          type="button"
                          onClick={() => setSelectedCollections(prev => prev.filter(item => item.id !== c.id))}
                          className="text-slate-400 hover:text-rose-600 font-bold ml-1"
                        >
                          ✕
                        </button>
                      </span>
                    ))}
                  </div>
                )}
              </div>
            )}

            {/* Tag Picker */}
            {syncScopeType === 'tags' && (
              <div className="p-4 rounded-xl bg-slate-50 border border-slate-200/80 space-y-3">
                <div className="flex items-center justify-between">
                  <span className="text-xs font-semibold text-slate-700">
                    Selected Tags ({selectedTags.length})
                  </span>
                  <button
                    type="button"
                    onClick={() => setIsTagModalOpen(true)}
                    className="px-3 py-1.5 bg-theme hover:bg-theme-hover text-white text-xs font-bold rounded-lg flex items-center gap-1 shadow-sm transition"
                  >
                    <i className="fa-solid fa-plus text-xs" /> Select tags
                  </button>
                </div>
                {selectedTags.length > 0 && (
                  <div className="flex flex-wrap gap-2">
                    {selectedTags.map(t => (
                      <span
                        key={t}
                        className="inline-flex items-center gap-1.5 px-3 py-1 rounded-lg bg-white border border-slate-200 text-xs text-slate-800 shadow-2xs font-medium"
                      >
                        {t}
                        <button
                          type="button"
                          onClick={() => setSelectedTags(prev => prev.filter(item => item !== t))}
                          className="text-slate-400 hover:text-rose-600 font-bold ml-1"
                        >
                          ✕
                        </button>
                      </span>
                    ))}
                  </div>
                )}
              </div>
            )}

            {/* Product Picker */}
            {syncScopeType === 'specific_products' && (
              <div className="p-4 rounded-xl bg-slate-50 border border-slate-200/80 space-y-3">
                <div className="flex items-center justify-between">
                  <span className="text-xs font-semibold text-slate-700">
                    Selected Products ({selectedProducts.length})
                  </span>
                  <button
                    type="button"
                    onClick={() => setIsProductModalOpen(true)}
                    className="px-3 py-1.5 bg-theme hover:bg-theme-hover text-white text-xs font-bold rounded-lg flex items-center gap-1 shadow-sm transition"
                  >
                    <i className="fa-solid fa-plus text-xs" /> Select products
                  </button>
                </div>
                {selectedProducts.length > 0 && (
                  <div className="max-h-48 overflow-y-auto space-y-1.5 pr-1">
                    {selectedProducts.map(p => (
                      <div
                        key={p.id}
                        className="flex items-center justify-between p-2 rounded-lg bg-white border border-slate-200 text-xs text-slate-800 shadow-2xs"
                      >
                        <span className="font-medium truncate max-w-sm">{p.title}</span>
                        <button
                          type="button"
                          onClick={() => setSelectedProducts(prev => prev.filter(item => item.id !== p.id))}
                          className="text-slate-400 hover:text-rose-600 p-1"
                        >
                          <i className="fa-regular fa-trash-can text-xs" />
                        </button>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            )}

            {/* Exclusions */}
            <div className="pt-3 border-t border-slate-100 space-y-4">
              <div className="flex items-center justify-between">
                <div>
                  <h4 className="text-xs font-bold text-slate-900">
                    Exclude Products
                  </h4>
                  <p className="text-[11px] text-slate-500">
                    Filter out items by stock status, collections, tags, or specific products
                  </p>
                </div>
              </div>

              {/* Out-of-stock checkbox */}
              <label className="flex items-center gap-2.5 cursor-pointer select-none">
                <input
                  type="checkbox"
                  checked={excludeOutOfStock}
                  onChange={e => setExcludeOutOfStock(e.target.checked)}
                  className="w-4 h-4 rounded border-slate-300 text-theme focus:ring-theme"
                />
                <span className="text-xs text-slate-700 font-medium">Exclude out-of-stock products</span>
              </label>

              {/* Exclusion Type Choosers */}
              <div className="space-y-3">
                <span className="text-[11px] font-bold uppercase tracking-wider text-slate-400 block">
                  Exclude by Collections, Tags, or Specific Products:
                </span>

                <div className="grid grid-cols-1 sm:grid-cols-3 gap-2.5">
                  {/* Option 1: Collections */}
                  <button
                    type="button"
                    onClick={() => setActiveExcludeTab(activeExcludeTab === 'collections' ? null : 'collections')}
                    className={`p-3 rounded-xl border text-left transition-all cursor-pointer ${
                      activeExcludeTab === 'collections' || excludedCollections.length > 0
                        ? 'bg-rose-50/70 border-rose-300 ring-1 ring-rose-300/50 shadow-2xs'
                        : 'bg-white border-slate-200/90 hover:bg-slate-50'
                    }`}
                  >
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <i className="fa-solid fa-layer-group text-xs text-rose-600" />
                        <span className="text-xs font-bold text-slate-900">Collections</span>
                      </div>
                      {excludedCollections.length > 0 && (
                        <span className="px-1.5 py-0.2 rounded-full text-[10px] font-black bg-rose-200 text-rose-800">
                          {excludedCollections.length}
                        </span>
                      )}
                    </div>
                    <p className="text-[10px] text-slate-500 mt-1">
                      Exclude entire categories
                    </p>
                  </button>

                  {/* Option 2: Tags */}
                  <button
                    type="button"
                    onClick={() => setActiveExcludeTab(activeExcludeTab === 'tags' ? null : 'tags')}
                    className={`p-3 rounded-xl border text-left transition-all cursor-pointer ${
                      activeExcludeTab === 'tags' || excludedTags.length > 0 || (excludeTags && excludeTags.trim().length > 0)
                        ? 'bg-rose-50/70 border-rose-300 ring-1 ring-rose-300/50 shadow-2xs'
                        : 'bg-white border-slate-200/90 hover:bg-slate-50'
                    }`}
                  >
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <i className="fa-solid fa-tags text-xs text-rose-600" />
                        <span className="text-xs font-bold text-slate-900">Tags</span>
                      </div>
                      {(excludedTags.length > 0 || (excludeTags && excludeTags.trim().length > 0)) && (
                        <span className="px-1.5 py-0.2 rounded-full text-[10px] font-black bg-rose-200 text-rose-800">
                          {excludedTags.length + (excludeTags ? excludeTags.split(',').filter(t => t.trim() && !excludedTags.includes(t.trim())).length : 0)}
                        </span>
                      )}
                    </div>
                    <p className="text-[10px] text-slate-500 mt-1">
                      Exclude tags or labels
                    </p>
                  </button>

                  {/* Option 3: Specific Products */}
                  <button
                    type="button"
                    onClick={() => setActiveExcludeTab(activeExcludeTab === 'specific_products' ? null : 'specific_products')}
                    className={`p-3 rounded-xl border text-left transition-all cursor-pointer ${
                      activeExcludeTab === 'specific_products' || excludedProducts.length > 0
                        ? 'bg-rose-50/70 border-rose-300 ring-1 ring-rose-300/50 shadow-2xs'
                        : 'bg-white border-slate-200/90 hover:bg-slate-50'
                    }`}
                  >
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <i className="fa-solid fa-box text-xs text-rose-600" />
                        <span className="text-xs font-bold text-slate-900">Specific Products</span>
                      </div>
                      {excludedProducts.length > 0 && (
                        <span className="px-1.5 py-0.2 rounded-full text-[10px] font-black bg-rose-200 text-rose-800">
                          {excludedProducts.length}
                        </span>
                      )}
                    </div>
                    <p className="text-[10px] text-slate-500 mt-1">
                      Exclude individual items
                    </p>
                  </button>
                </div>

                {/* Collections Exclusion Panel */}
                {(activeExcludeTab === 'collections' || excludedCollections.length > 0) && (
                  <div className="p-4 rounded-xl bg-rose-50/40 border border-rose-200/80 space-y-3">
                    <div className="flex items-center justify-between">
                      <span className="text-xs font-bold text-slate-800 flex items-center gap-1.5">
                        <i className="fa-solid fa-ban text-rose-600 text-xs" />
                        <span>Excluded Collections ({excludedCollections.length})</span>
                      </span>
                      <button
                        type="button"
                        onClick={() => setIsExcludeCollectionModalOpen(true)}
                        className="px-3 py-1.5 bg-rose-700 hover:bg-rose-800 text-white text-xs font-semibold rounded-lg flex items-center gap-1.5 shadow-2xs cursor-pointer"
                      >
                        <i className="fa-solid fa-plus text-xs" /> Select collections to exclude
                      </button>
                    </div>

                    {excludedCollections.length > 0 ? (
                      <div className="flex flex-wrap gap-2">
                        {excludedCollections.map(c => (
                          <span
                            key={c.id}
                            className="inline-flex items-center gap-1.5 px-3 py-1 rounded-lg bg-white border border-rose-200 text-xs text-rose-900 shadow-2xs font-semibold"
                          >
                            <span>{c.title}</span>
                            <button
                              type="button"
                              onClick={() => setExcludedCollections(prev => prev.filter(item => item.id !== c.id))}
                              className="text-rose-400 hover:text-rose-700 font-bold ml-1 cursor-pointer"
                              title="Remove exclusion"
                            >
                              ✕
                            </button>
                          </span>
                        ))}
                      </div>
                    ) : (
                      <p className="text-xs text-slate-400">Click &quot;Select collections to exclude&quot; to pick collections.</p>
                    )}
                  </div>
                )}

                {/* Tags Exclusion Panel */}
                {(activeExcludeTab === 'tags' || excludedTags.length > 0 || (excludeTags && excludeTags.trim().length > 0)) && (
                  <div className="p-4 rounded-xl bg-rose-50/40 border border-rose-200/80 space-y-3">
                    <div className="flex items-center justify-between">
                      <span className="text-xs font-bold text-slate-800 flex items-center gap-1.5">
                        <i className="fa-solid fa-ban text-rose-600 text-xs" />
                        <span>Excluded Tags ({excludedTags.length})</span>
                      </span>
                      <button
                        type="button"
                        onClick={() => setIsExcludeTagModalOpen(true)}
                        className="px-3 py-1.5 bg-rose-700 hover:bg-rose-800 text-white text-xs font-semibold rounded-lg flex items-center gap-1.5 shadow-2xs cursor-pointer"
                      >
                        <i className="fa-solid fa-plus text-xs" /> Select tags to exclude
                      </button>
                    </div>

                    {excludedTags.length > 0 && (
                      <div className="flex flex-wrap gap-2">
                        {excludedTags.map(t => (
                          <span
                            key={t}
                            className="inline-flex items-center gap-1.5 px-3 py-1 rounded-lg bg-white border border-rose-200 text-xs text-rose-900 shadow-2xs font-semibold"
                          >
                            <span>{t}</span>
                            <button
                              type="button"
                              onClick={() => setExcludedTags(prev => prev.filter(item => item !== t))}
                              className="text-rose-400 hover:text-rose-700 font-bold ml-1 cursor-pointer"
                              title="Remove tag exclusion"
                            >
                              ✕
                            </button>
                          </span>
                        ))}
                      </div>
                    )}

                    <div>
                      <label className="block text-[11px] font-semibold text-slate-600 mb-1">
                        Or enter tags manually (comma separated):
                      </label>
                      <input
                        type="text"
                        value={excludeTags}
                        onChange={e => setExcludeTags(e.target.value)}
                        placeholder="e.g. draft, archived, secret, private"
                        className="w-full px-3.5 py-2 bg-white border border-slate-200 rounded-xl text-xs text-slate-900 placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-rose-500/20 focus:border-rose-500"
                      />
                    </div>
                  </div>
                )}

                {/* Specific Products Exclusion Panel */}
                {(activeExcludeTab === 'specific_products' || excludedProducts.length > 0) && (
                  <div className="p-4 rounded-xl bg-rose-50/40 border border-rose-200/80 space-y-3">
                    <div className="flex items-center justify-between">
                      <span className="text-xs font-bold text-slate-800 flex items-center gap-1.5">
                        <i className="fa-solid fa-ban text-rose-600 text-xs" />
                        <span>Excluded Products ({excludedProducts.length})</span>
                      </span>
                      <button
                        type="button"
                        onClick={() => setIsExcludeProductModalOpen(true)}
                        className="px-3 py-1.5 bg-rose-700 hover:bg-rose-800 text-white text-xs font-semibold rounded-lg flex items-center gap-1.5 shadow-2xs cursor-pointer"
                      >
                        <i className="fa-solid fa-plus text-xs" /> Select products to exclude
                      </button>
                    </div>

                    {excludedProducts.length > 0 ? (
                      <div className="max-h-48 overflow-y-auto space-y-1.5 pr-1">
                        {excludedProducts.map(p => (
                          <div
                            key={p.id}
                            className="flex items-center justify-between p-2 rounded-lg bg-white border border-rose-200 text-xs text-slate-800 shadow-2xs"
                          >
                            <span className="font-medium truncate max-w-sm text-rose-950">{p.title}</span>
                            <button
                              type="button"
                              onClick={() => setExcludedProducts(prev => prev.filter(item => item.id !== p.id))}
                              className="text-slate-400 hover:text-rose-600 p-1 cursor-pointer"
                              title="Remove product exclusion"
                            >
                              <i className="fa-regular fa-trash-can text-xs" />
                            </button>
                          </div>
                        ))}
                      </div>
                    ) : (
                      <p className="text-xs text-slate-400">Click &quot;Select products to exclude&quot; to pick specific items.</p>
                    )}
                  </div>
                )}
              </div>
            </div>
          </div>

          {/* Section: Template Library Selector */}
          <TemplateLibrarySelector
            selectedTemplateId={selectedTemplateId}
            onSelectTemplate={handleTemplateSelected}
            currentPriceMode={priceMode}
            onPriceModeChange={setPriceMode}
          />

          {/* Section 3: Variant Export Modes */}
          <div className="bg-white border border-slate-200/80 rounded-2xl p-5 sm:p-6 shadow-xs space-y-4">
            <div className="flex items-center gap-2 text-xs font-bold text-theme uppercase tracking-wider">
              <i className="fa-solid fa-tag text-xs" />
              <span>Variant Export Mode</span>
            </div>

            <div className="space-y-2.5">
              <label
                onClick={() => setVariantExportMode('all_separate')}
                className={`flex items-start gap-3 p-3.5 rounded-xl border cursor-pointer transition-all ${
                  variantExportMode === 'all_separate'
                    ? 'bg-theme/5 border-theme shadow-2xs ring-1 ring-theme/20'
                    : 'bg-white border-slate-200 hover:bg-slate-50'
                }`}
              >
                <input
                  type="radio"
                  name="variantMode"
                  checked={variantExportMode === 'all_separate'}
                  onChange={() => setVariantExportMode('all_separate')}
                  className="mt-0.5 w-4 h-4 text-theme focus:ring-theme"
                />
                <div>
                  <p className="text-xs font-bold text-slate-900">
                    All variants as separate items (default)
                  </p>
                  <p className="text-[11px] text-slate-500 mt-0.5">
                    Every product variant is pushed to Facebook Catalog as an independent item with variant ID.
                  </p>
                </div>
              </label>

              <label
                onClick={() => setVariantExportMode('grouped')}
                className={`flex items-start gap-3 p-3.5 rounded-xl border cursor-pointer transition-all ${
                  variantExportMode === 'grouped'
                    ? 'bg-theme/5 border-theme shadow-2xs ring-1 ring-theme/20'
                    : 'bg-white border-slate-200 hover:bg-slate-50'
                }`}
              >
                <input
                  type="radio"
                  name="variantMode"
                  checked={variantExportMode === 'grouped'}
                  onChange={() => setVariantExportMode('grouped')}
                  className="mt-0.5 w-4 h-4 text-theme focus:ring-theme"
                />
                <div>
                  <p className="text-xs font-bold text-slate-900">
                    Group variants under item_group_id
                  </p>
                  <p className="text-[11px] text-slate-500 mt-0.5">
                    All variants are linked together using Shopify Product ID as item_group_id.
                  </p>
                </div>
              </label>

              <label
                onClick={() => setVariantExportMode('first_variant_title')}
                className={`flex items-start gap-3 p-3.5 rounded-xl border cursor-pointer transition-all ${
                  variantExportMode === 'first_variant_title'
                    ? 'bg-theme/5 border-theme shadow-2xs ring-1 ring-theme/20'
                    : 'bg-white border-slate-200 hover:bg-slate-50'
                }`}
              >
                <input
                  type="radio"
                  name="variantMode"
                  checked={variantExportMode === 'first_variant_title'}
                  onChange={() => setVariantExportMode('first_variant_title')}
                  className="mt-0.5 w-4 h-4 text-theme focus:ring-theme"
                />
                <div>
                  <p className="text-xs font-bold text-slate-900">
                    First variant only with Variant Title &amp; Variant ID
                  </p>
                  <p className="text-[11px] text-slate-500 mt-0.5">
                    Only exports the first variant using the variant title and variant ID.
                  </p>
                </div>
              </label>

              <label
                onClick={() => setVariantExportMode('first_product_title')}
                className={`flex items-start gap-3 p-3.5 rounded-xl border cursor-pointer transition-all ${
                  variantExportMode === 'first_product_title'
                    ? 'bg-theme/5 border-theme shadow-2xs ring-1 ring-theme/20'
                    : 'bg-white border-slate-200 hover:bg-slate-50'
                }`}
              >
                <input
                  type="radio"
                  name="variantMode"
                  checked={variantExportMode === 'first_product_title'}
                  onChange={() => setVariantExportMode('first_product_title')}
                  className="mt-0.5 w-4 h-4 text-theme focus:ring-theme"
                />
                <div>
                  <p className="text-xs font-bold text-slate-900">
                    First variant only with Product Title &amp; Product ID
                  </p>
                  <p className="text-[11px] text-slate-500 mt-0.5">
                    Exports only the product level item using the main product title and product ID.
                  </p>
                </div>
              </label>
            </div>
          </div>

          {/* Section 4: Category & Taxonomy */}
          <div className="bg-white border border-slate-200/80 rounded-2xl p-5 sm:p-6 shadow-xs space-y-4">
            <div className="flex items-center gap-2 text-xs font-bold text-theme uppercase tracking-wider">
              <i className="fa-solid fa-globe text-xs" />
              <span>Category &amp; Taxonomy</span>
            </div>

            <div>
              <label className="block text-xs font-semibold text-slate-700 mb-1.5">
                Google / Facebook Product Category (Taxonomy)
              </label>
              <CategorySearchInput
                value={googleCategory}
                onChange={setGoogleCategory}
                placeholder="Search taxonomy e.g. Apparel & Accessories > Clothing"
              />
            </div>
          </div>

          {/* Section 5: Product Images & Links */}
          <div className="bg-white border border-slate-200/80 rounded-2xl p-5 sm:p-6 shadow-xs space-y-4">
            <div className="flex items-center gap-2 text-xs font-bold text-theme uppercase tracking-wider">
              <i className="fa-regular fa-image text-xs" />
              <span>Images &amp; Link Settings</span>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-xs font-semibold text-slate-700 mb-1.5">Product Images Mode</label>
                <div className="space-y-2">
                  <label className="flex items-center gap-2 cursor-pointer text-xs text-slate-700">
                    <input
                      type="radio"
                      name="imageOption"
                      checked={imageOption === 'all'}
                      onChange={() => setImageOption('all')}
                      className="w-4 h-4 text-theme focus:ring-theme"
                    />
                    <span>All product images (up to 20 images)</span>
                  </label>
                  <label className="flex items-center gap-2 cursor-pointer text-xs text-slate-700">
                    <input
                      type="radio"
                      name="imageOption"
                      checked={imageOption === 'first'}
                      onChange={() => setImageOption('first')}
                      className="w-4 h-4 text-theme focus:ring-theme"
                    />
                    <span>Main featured image only</span>
                  </label>
                </div>
              </div>

              <div>
                <label className="block text-xs font-semibold text-slate-700 mb-1.5">Product Link Domain</label>
                <div className="space-y-2">
                  <label className="flex items-center gap-2 cursor-pointer text-xs text-slate-700">
                    <input
                      type="radio"
                      name="productLinkDomain"
                      checked={productLinkDomain === 'myshopify'}
                      onChange={() => setProductLinkDomain('myshopify')}
                      className="w-4 h-4 text-theme focus:ring-theme"
                    />
                    <span>MyShopify Domain (Default)</span>
                  </label>
                  <label className="flex items-center gap-2 cursor-pointer text-xs text-slate-700">
                    <input
                      type="radio"
                      name="productLinkDomain"
                      checked={productLinkDomain === 'primary'}
                      onChange={() => setProductLinkDomain('primary')}
                      className="w-4 h-4 text-theme focus:ring-theme"
                    />
                    <span>Primary Store Domain</span>
                  </label>
                  <label className="flex items-center gap-2 cursor-pointer text-xs text-slate-700">
                    <input
                      type="radio"
                      name="productLinkDomain"
                      checked={productLinkDomain === 'custom'}
                      onChange={() => setProductLinkDomain('custom')}
                      className="w-4 h-4 text-theme focus:ring-theme"
                    />
                    <span>Custom Domain</span>
                  </label>
                </div>
                {productLinkDomain === 'custom' && (
                  <div>
                    <input
                      type="text"
                      value={customDomain}
                      onChange={e => {
                        setCustomDomain(e.target.value);
                        if (fieldErrors.customDomain) {
                          setFieldErrors(prev => {
                            const copy = { ...prev };
                            delete copy.customDomain;
                            return copy;
                          });
                        }
                      }}
                      placeholder="https://yourcustomdomain.com"
                      className={`w-full mt-2 px-3 py-2 bg-white border rounded-xl text-xs text-slate-900 placeholder-slate-400 focus:outline-none focus:ring-2 ${
                        fieldErrors.customDomain
                          ? 'border-rose-400 focus:ring-rose-500/20 focus:border-rose-500 bg-rose-50/20'
                          : 'border-slate-200 focus:ring-theme/20 focus:border-theme'
                      }`}
                    />
                    {fieldErrors.customDomain && (
                      <p className="text-[11px] text-rose-500 mt-1 font-medium">{fieldErrors.customDomain}</p>
                    )}
                  </div>
                )}
              </div>
            </div>
          </div>

          {/* Section 6: Schedule & Auto Sync */}
          <div className="bg-white border border-slate-200/80 rounded-2xl p-5 sm:p-6 shadow-xs space-y-4">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2 text-xs font-bold text-theme uppercase tracking-wider">
                <i className="fa-regular fa-clock text-xs" />
                <span>Schedule &amp; Auto Sync</span>
              </div>
              <button
                type="button"
                onClick={() => setIsAutoSync(!isAutoSync)}
                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 ${
                  isAutoSync ? '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 ${
                    isAutoSync ? 'translate-x-4' : 'translate-x-0'
                  }`}
                />
              </button>
            </div>

            {isAutoSync && (
              <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-3 pt-2">
                <div>
                  <label className="block text-xs font-semibold text-slate-700 mb-1">Frequency</label>
                  <select
                    value={scheduleType}
                    onChange={e => setScheduleType(e.target.value as any)}
                    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="daily">Daily</option>
                    <option value="weekly">Weekly</option>
                  </select>
                </div>

                {scheduleType === 'weekly' && (
                  <div>
                    <label className="block text-xs font-semibold text-slate-700 mb-1">Day of Week</label>
                    <select
                      value={scheduleDay}
                      onChange={e => setScheduleDay(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="Every Monday">Monday</option>
                      <option value="Every Tuesday">Tuesday</option>
                      <option value="Every Wednesday">Wednesday</option>
                      <option value="Every Thursday">Thursday</option>
                      <option value="Every Friday">Friday</option>
                      <option value="Every Saturday">Saturday</option>
                      <option value="Every Sunday">Sunday</option>
                    </select>
                  </div>
                )}

                <div>
                  <label className="block text-xs font-semibold text-slate-700 mb-1">Hour of Day</label>
                  <div className="flex gap-1.5">
                    <select
                      value={scheduleHour}
                      onChange={e => setScheduleHour(parseInt(e.target.value, 10))}
                      className="flex-1 px-2.5 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"
                    >
                      {Array.from({ length: 12 }, (_, i) => i + 1).map(h => (
                        <option key={h} value={h}>
                          {h}:00
                        </option>
                      ))}
                    </select>
                    <select
                      value={schedulePeriod}
                      onChange={e => setSchedulePeriod(e.target.value as 'AM' | 'PM')}
                      className="w-16 px-2 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="AM">AM</option>
                      <option value="PM">PM</option>
                    </select>
                  </div>
                </div>

                <div>
                  <label className="block text-xs font-semibold text-slate-700 mb-1">Shopify Store Timezone</label>
                  <select
                    value={scheduleTimezone}
                    onChange={e => setScheduleTimezone(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 font-medium"
                  >
                    {Array.from(new Set([scheduleTimezone, shopifyStoreTimezone, ...TIMEZONES].filter(Boolean))).map(tz => (
                      <option key={tz} value={tz}>
                        {tz} {tz === shopifyStoreTimezone ? '(Store Default)' : ''}
                      </option>
                    ))}
                  </select>
                </div>
              </div>
            )}
          </div>

          {/* Bottom Action Footer */}
          <div className="flex flex-col-reverse sm:flex-row items-stretch sm:items-center justify-end gap-3 pt-4">
            <Link
              href={getHref('/catalog')}
              className="px-5 py-2.5 bg-white border border-slate-200 hover:bg-slate-50 text-slate-700 text-xs font-semibold rounded-xl transition shadow-2xs text-center"
            >
              Cancel
            </Link>
            <button
              type="submit"
              disabled={submitting}
              className="px-6 py-2.5 bg-theme hover:bg-theme-hover disabled:opacity-50 text-white text-xs font-bold rounded-xl shadow-sm hover:shadow-md transition active:scale-[0.985] flex items-center justify-center gap-2"
            >
              {submitting ? 'Saving Changes...' : 'Save Catalog Changes'}
            </button>
          </div>
        </form>

        {/* Selection Modals */}
        <ProductPickerModal
          isOpen={isProductModalOpen}
          onClose={() => setIsProductModalOpen(false)}
          onSelect={setSelectedProducts}
          initiallySelectedIds={selectedProducts.map(p => String(p.id))}
          shop={currentShop}
        />

        <CollectionPickerModal
          isOpen={isCollectionModalOpen}
          onClose={() => setIsCollectionModalOpen(false)}
          onSelect={setSelectedCollections}
          initiallySelectedIds={selectedCollections.map(c => String(c.id))}
          shop={currentShop}
        />

        <TagPickerModal
          isOpen={isTagModalOpen}
          onClose={() => setIsTagModalOpen(false)}
          onSelect={setSelectedTags}
          initiallySelectedTags={selectedTags}
          shop={currentShop}
        />

        {/* Exclusion Modals */}
        <ProductPickerModal
          isOpen={isExcludeProductModalOpen}
          onClose={() => setIsExcludeProductModalOpen(false)}
          onSelect={setExcludedProducts}
          initiallySelectedIds={excludedProducts.map(p => String(p.id))}
          shop={currentShop}
        />

        <CollectionPickerModal
          isOpen={isExcludeCollectionModalOpen}
          onClose={() => setIsExcludeCollectionModalOpen(false)}
          onSelect={setExcludedCollections}
          initiallySelectedIds={excludedCollections.map(c => String(c.id))}
          shop={currentShop}
        />

        <TagPickerModal
          isOpen={isExcludeTagModalOpen}
          onClose={() => setIsExcludeTagModalOpen(false)}
          onSelect={setExcludedTags}
          initiallySelectedTags={excludedTags}
          shop={currentShop}
        />
      </div>
    </AppLayout>
  );
}
