/* global React, Icons, Field, Select, NumPair, RatingRange, Toggle, ProductImage, Sparkline, Stars, Checkbox, MASTER_COLUMNS, COLUMN_BY_KEY, renderCellValue, ManageColumnsDrawer */
const { useState, useMemo, useEffect } = React;

function FilterSection({ title, open, onToggle, children }) {
  return (
    <div style={{ borderTop: '1px solid var(--line)' }}>
      <div onClick={onToggle} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '11px 20px', cursor: 'pointer', userSelect: 'none' }}>
        <span style={{ display: 'inline-flex', width: 18, height: 18, alignItems: 'center', justifyContent: 'center', transform: open ? 'rotate(0deg)' : 'rotate(-90deg)', transition: 'transform 0.18s', color: 'var(--text-2)' }}>
          <Icons.chevDown size={13}/>
        </span>
        <div style={{ fontSize: 13, fontWeight: 600 }}>{title}</div>
      </div>
      {open && (
        <div style={{ padding: '4px 20px 16px', display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16 }}>
          {children}
        </div>
      )}
    </div>
  );
}

const FILTER_DEFAULTS = {
  category: 'All categories',
  price: ['', ''], monthlySales: ['', ''], revenue30d: ['', ''],
  bsr: ['', ''], reviewCount: ['', ''], rating: [1, 5],
  variations: ['', ''], videos: ['', ''], listingAge: ['', ''],
  cc: ['', ''], ccCommission: ['', ''],
  totalBudget: ['', ''], budget: ['', ''], budgetPct: ['', ''],
  availableSlots: ['', ''], slotsPct: ['', ''],
  campaignStart: ['', ''], campaignEnd: ['', ''],
  hasMainVideo: false,
};

const LEADS_COLS_KEY = 'aip_leads_cols';
const PAGE_SIZE = 100;

function loadStoredCols(customCols) {
  const customKeys = new Set((customCols || []).map(c => c.key));
  const validKeys  = new Set([...MASTER_COLUMNS.map(c => c.key), ...customKeys]);
  try {
    const stored = localStorage.getItem(LEADS_COLS_KEY);
    if (stored) {
      const { order, hidden } = JSON.parse(stored);
      // Strip any keys removed from MASTER_COLUMNS (e.g. old cost/profit/roi)
      const filteredOrder = order.filter(k => validKeys.has(k) || k.startsWith('cust_'));
      return { order: filteredOrder, hidden: new Set(hidden) };
    }
  } catch (_) {}
  return {
    order:  [...LEADS_DEFAULT_ORDER, ...(customCols || []).map(c => c.key)],
    hidden: new Set(),
  };
}

const LEADS_DEFAULT_ORDER = [
  'product','asin','brand','hasMainVideo','cc','ccCommission','videos','budget','remainingBudget','campaignDate',
  'availableSlots','totalSlots','slotsTrend','category','price','revenue30d','monthlySales','bsr',
  'reviews','rating','variations','listingAge','onSite','onSiteCommission','trend',
];

const LIST_COLORS = [
  '#4cc9f0','#a855f7','#f59e0b','#22d3ee','#10b981','#84cc16',
  '#f43f5e','#3b82f6','#f97316','#6366f1','#ec4899','#eab308',
  '#14b8a6','#8b5cf6','#ef4444','#7c5cff','#22c55e','#fb7185',
  '#60a5fa','#fbbf24','#34d399','#c084fc','#38bdf8','#f87171',
  '#a3e635','#e879f9','#2dd4bf','#facc15','#4ade80','#06b6d4',
];

// All available stat options — stored as list.statKeys (array of 4)
const LEADS_STAT_OPTIONS = [
  { key: 'count',           label: 'Leads in List',      sub: 'total products' },
  { key: 'avgMonthlySales', label: 'Avg Monthly Sales',  sub: 'units / month' },
  { key: 'avgCcCommission', label: 'Avg CC Commission',  sub: 'per qualifying sale' },
  { key: 'avgRev',          label: 'Avg 30d Revenue',    sub: 'per listing · 30 days' },
  { key: 'totalCost',       label: 'Total Cost',         sub: 'if buying 1 of each lead' },
  { key: 'breakEven',       label: 'Avg Break Even',     sub: 'CC sales to recoup cost' },
  { key: 'avgCcRate',       label: 'Avg CC Rate',        sub: 'across CC products' },
  { key: 'ccCount',         label: 'CC Products',        sub: 'with active CC campaign' },
];
const DEFAULT_STAT_KEYS = ['count', 'avgMonthlySales', 'avgCcCommission', 'avgRev'];

const FLOW_DEFAULT_STATUSES = [
  { id: 'leads',       label: 'Leads',       color: '#4cc9f0', iconId: 'bookmark' },
  { id: 'requested',   label: 'Requested',   color: '#a855f7', iconId: 'mail' },
  { id: 'followed_up', label: 'Followed Up', color: '#f59e0b', iconId: 'arrow' },
  { id: 'to_buy',      label: 'To Buy',      color: '#22d3ee', iconId: 'tag' },
  { id: 'in_transit',  label: 'In Transit',  color: '#10b981', iconId: 'package' },
  { id: 'done',        label: 'Done',        color: '#84cc16', iconId: 'check' },
];

const STATUS_ICON_MAP = {
  bookmark: Icons.bookmark, mail: Icons.mail,     arrow: Icons.arrow,
  tag: Icons.tag,           package: Icons.package, check: Icons.check,
  bolt: Icons.bolt,         trend: Icons.trend,   cart: Icons.cart,
  calendar: Icons.calendar, video: Icons.video,   dollar: Icons.dollar,
  star: Icons.star,         folder: Icons.folder, link: Icons.link,
  users: Icons.users,       edit: Icons.edit,     eye: Icons.eye,
  list: Icons.list,         chart: Icons.chart,   diamond: Icons.diamond,
  zap: Icons.zap,           download: Icons.download, upload: Icons.upload,
  filter: Icons.filter,     copy: Icons.copy,     reset: Icons.reset,
  trash: Icons.trash,       kanban: Icons.kanban, sort: Icons.sort,
};
const getStatusIcon = (iconId) => STATUS_ICON_MAP[iconId] || Icons.tag;

const LeadsPage = ({ leads, setLeads }) => {
  const { fmtUSD, fmtInt, fmtBSR } = window.AIP_DATA;

  const { CATEGORIES } = window.AIP_DATA;

  const [activeListId, setActiveListId] = useState(() => localStorage.getItem('aip_active_list') || 'inbox');
  const [search, setSearch] = useState('');
  const [filters, setFilters] = useState(FILTER_DEFAULTS);
  const [filtersOpen, setFiltersOpen] = useState(false);
  const [secOpen, setSecOpen] = useState({ cc: true, performance: true, listing: false });
  const [showColumnsDrawer, setShowColumnsDrawer] = useState(false);
  const [selected, setSelected] = useState(new Set());

  const toNum = s => s === '' ? null : parseFloat(s);
  const setF = (k, v) => setFilters(prev => ({ ...prev, [k]: v }));

  const activeFilterCount = useMemo(() => {
    let n = 0;
    if (filters.category !== 'All categories') n++;
    ['price','monthlySales','revenue30d','bsr','reviewCount','variations','videos','listingAge',
     'cc','ccCommission','totalBudget','budget','budgetPct','availableSlots','slotsPct'].forEach(k => {
      if (toNum(filters[k][0]) !== null || toNum(filters[k][1]) !== null) n++;
    });
    if (filters.rating[0] > 1 || filters.rating[1] < 5) n++;
    if (filters.campaignStart[0] || filters.campaignStart[1]) n++;
    if (filters.campaignEnd[0] || filters.campaignEnd[1]) n++;
    if (filters.hasMainVideo) n++;
    return n;
  }, [filters]);

  const resetFilters = () => { setFilters(FILTER_DEFAULTS); setSearch(''); };
  const [creatingList, setCreatingList] = useState(false);
  const [newListName, setNewListName] = useState('');
  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
  const [editingListId, setEditingListId] = useState(null);
  const [menuOpenId, setMenuOpenId] = useState(null);
  const [dragListIdx, setDragListIdx] = useState(null);
  const [undoData, setUndoData] = useState(null);
  const [defaultListId, setDefaultListId] = useState(() => localStorage.getItem('aip_default_list') || null);
  const [showDefaultPicker, setShowDefaultPicker] = useState(false);
  const [movedId, setMovedId] = useState(null);
  const [copiedId, setCopiedId] = useState(null);
  const [confirmDeleteId, setConfirmDeleteId] = useState(null);
  const [showQuickCopyPicker, setShowQuickCopyPicker] = useState(false);
  const [qcProfiles, setQcProfiles] = useState(() => {
    try {
      const stored = localStorage.getItem('aip_qc_profiles');
      if (stored) return JSON.parse(stored);
    } catch (_) {}
    // Migrate from old per-key storage if present
    const oldKeys  = localStorage.getItem('aip_quick_copy_cols');
    const oldOrder = localStorage.getItem('aip_quick_copy_order');
    const oldLinks = localStorage.getItem('aip_qc_links');
    return [{ id: 'default', name: 'Default',
      keys:         oldKeys  ? JSON.parse(oldKeys)  : null,
      order:        oldOrder ? JSON.parse(oldOrder) : null,
      includeLinks: oldLinks === 'true',
    }];
  });
  const [activeQcProfileId, setActiveQcProfileId] = useState(() =>
    localStorage.getItem('aip_qc_active_profile') || 'default'
  );
  const [renamingQcProfileId, setRenamingQcProfileId] = useState(null);
  const [qcCopiedHeaders, setQcCopiedHeaders] = useState(false);
  const [qcDragIdx, setQcDragIdx] = useState(null);
  const [showQcAddCol, setShowQcAddCol] = useState(false);
  const [qcNewColName, setQcNewColName] = useState('');
  const [showStatusDropdown, setShowStatusDropdown] = useState(false);
  const [showStatPicker, setShowStatPicker] = useState(false);

  useEffect(() => {
    if (!menuOpenId) return;
    const close = () => setMenuOpenId(null);
    document.addEventListener('click', close);
    return () => document.removeEventListener('click', close);
  }, [menuOpenId]);

  useEffect(() => {
    if (!confirmDeleteId) return;
    const close = () => setConfirmDeleteId(null);
    document.addEventListener('click', close);
    return () => document.removeEventListener('click', close);
  }, [confirmDeleteId]);

  useEffect(() => {
    if (!showQuickCopyPicker) return;
    const close = () => setShowQuickCopyPicker(false);
    document.addEventListener('click', close);
    return () => document.removeEventListener('click', close);
  }, [showQuickCopyPicker]);

  useEffect(() => {
    if (!showQuickCopyPicker) { setShowQcAddCol(false); setQcNewColName(''); }
  }, [showQuickCopyPicker]);

  useEffect(() => {
    localStorage.setItem('aip_qc_profiles', JSON.stringify(qcProfiles));
  }, [qcProfiles]);

  useEffect(() => {
    localStorage.setItem('aip_qc_active_profile', activeQcProfileId);
  }, [activeQcProfileId]);

  useEffect(() => {
    if (!showDefaultPicker) return;
    const close = () => setShowDefaultPicker(false);
    document.addEventListener('click', close);
    return () => document.removeEventListener('click', close);
  }, [showDefaultPicker]);

  useEffect(() => {
    if (!showStatusDropdown) return;
    const close = () => setShowStatusDropdown(false);
    document.addEventListener('click', close);
    return () => document.removeEventListener('click', close);
  }, [showStatusDropdown]);


  useEffect(() => {
    if (defaultListId) localStorage.setItem('aip_default_list', defaultListId);
    else localStorage.removeItem('aip_default_list');
  }, [defaultListId]);

  useEffect(() => {
    localStorage.setItem('aip_active_list', activeListId);
  }, [activeListId]);

  const reorderLists = (fromIdx, toIdx) => {
    setLeads(prev => {
      const lists = prev.lists.filter(l => l.id !== 'inbox');
      const [moved] = lists.splice(fromIdx, 1);
      lists.splice(toIdx, 0, moved);
      return { ...prev, lists };
    });
  };

  const defaultList = defaultListId === 'inbox'
    ? { id: 'inbox', name: 'Inbox', color: 'var(--accent)' }
    : (defaultListId ? leads.lists.find(l => l.id === defaultListId) : null);

  // Derive active profile settings as plain consts (re-computed each render)
  const activeQcProfile = qcProfiles.find(p => p.id === activeQcProfileId) ?? qcProfiles[0] ?? { id: 'default', name: 'Default', keys: null, order: null, includeLinks: false };
  const quickCopyKeys         = activeQcProfile.keys != null ? new Set(activeQcProfile.keys) : null;
  const quickCopyOrder        = activeQcProfile.order ?? null;
  const quickCopyIncludeLinks = activeQcProfile.includeLinks ?? false;

  const updateActiveQcProfile = (changes) =>
    setQcProfiles(prev => prev.map(p => p.id === activeQcProfileId ? { ...p, ...changes } : p));

  const addQcProfile = () => {
    const id = 'qcp_' + Date.now();
    setQcProfiles(prev => [...prev, {
      id, name: `Profile ${prev.length + 1}`,
      keys: activeQcProfile.keys, order: activeQcProfile.order, includeLinks: activeQcProfile.includeLinks,
    }]);
    setActiveQcProfileId(id);
    setRenamingQcProfileId(id);
  };

  const deleteQcProfile = (id) => {
    setQcProfiles(prev => {
      const next = prev.filter(p => p.id !== id);
      const safe = next.length > 0 ? next : [{ id: 'default', name: 'Default', keys: null, order: null, includeLinks: false }];
      if (activeQcProfileId === id) setActiveQcProfileId(safe[0].id);
      return safe;
    });
  };

  const renameQcProfile = (id, name) =>
    setQcProfiles(prev => prev.map(p => p.id === id ? { ...p, name } : p));

  const addCustomColFromQc = (label) => {
    if (!label.trim()) return;
    const key = 'qcol_' + Date.now();
    updateActiveQcProfile({ qcCols: [...(activeQcProfile.qcCols || []), { key, label: label.trim() }] });
    setShowQcAddCol(false);
    setQcNewColName('');
  };

  const deleteQcOnlyCol = (key) => {
    updateActiveQcProfile({
      qcCols: (activeQcProfile.qcCols || []).filter(c => c.key !== key),
      order: activeQcProfile.order ? activeQcProfile.order.filter(k => k !== key) : null,
      keys:  activeQcProfile.keys  ? activeQcProfile.keys.filter(k => k !== key)  : null,
    });
  };

  const copyRow = (p) => {
    const keysToUse = (() => {
      const ordered = effectiveQcOrder;
      return quickCopyKeys !== null ? ordered.filter(k => quickCopyKeys.has(k)) : ordered;
    })();

    const getHeader = (key) => {
      const std = COLUMN_BY_KEY[key];
      const cust = !std && customCols.find(c => c.key === key);
      const qcOnly = !std && !cust && qcOnlyCols.find(c => c.key === key);
      return std?.label || cust?.label || qcOnly?.label || key;
    };

    const getValue = (key) => {
      if (key.startsWith('qcol_')) return '';
      if (isCustomKey(key)) return notes[p.id]?.[key] || '';
      if (!quickCopyIncludeLinks) return getPlainValue(key, p, fmtUSD, fmtInt, fmtBSR);
      // Link-aware formatting (mirrors CSV export)
      const creatorId = localStorage.getItem('aip_creator_id');
      const hl = (url, label) => `=HYPERLINK("${url}","${String(label).replace(/"/g, "'")}") `;
      const ccSearchUrl = (kw) => {
        const params = new URLSearchParams({
          status: 'opportunity', type: 'affiliate-plus', sortBy: 'recommended_for_you',
          keyword: kw, filterExpanderStatus: 'false', categories: '',
          nonFullyClaimedOnly: 'false', campaignStatuses: 'active,pending',
          earlyAccessOnly: 'false', topBrandsOnly: 'false',
          creatorFavoritesOnly: 'false', brands: '', contentType: '', budgetAvailability: '',
        });
        if (creatorId) params.set('creatorId', creatorId);
        return `https://affiliate-program.amazon.com/p/connect/requests?${params}`;
      };
      switch (key) {
        case 'product': {
          const url = p.asin ? `https://www.amazon.com/dp/${p.asin}` : null;
          return url ? hl(url, p.name || p.asin) : (p.name || '');
        }
        case 'brand': return p.brand ? hl(ccSearchUrl(p.brand), p.brand) : '';
        case 'cc': return p.cc != null ? hl(ccSearchUrl(p.asin), `${p.cc}%`) : '';
        case 'campaignDate': {
          const dateRange = [p.campaignStart, p.campaignEnd].filter(Boolean).join(' → ');
          if (p.campaignId) {
            const fullId = p.campaignId.startsWith('amzn1.campaign.') ? p.campaignId : `amzn1.campaign.${p.campaignId}`;
            const parts = [
              creatorId ? `creatorId=${creatorId}` : null,
              `adId=${fullId}`, `campaignId=${fullId}`,
              'recc=0', 'early-acc=0', 'type=spcc', 'status=opportunity',
            ].filter(Boolean).join('&');
            return hl(`https://affiliate-program.amazon.com/p/connect/request?${parts}`, dateRange);
          }
          return dateRange;
        }
        default: return getPlainValue(key, p, fmtUSD, fmtInt, fmtBSR);
      }
    };

    const rows = [keysToUse.map(getValue).join('\t')];

    navigator.clipboard.writeText(rows.join('\n')).then(() => {
      setCopiedId(p.id);
      setTimeout(() => setCopiedId(null), 1500);
    });
  };

  const moveToDefault = (productId) => {
    if (!defaultListId) return;
    setLeads(prev => ({
      ...prev,
      products: prev.products.map(p =>
        p.id === productId
          ? { ...p, lists: [...new Set([...(p.lists || []), defaultListId])] }
          : p
      ),
    }));
    setMovedId(productId);
    setTimeout(() => setMovedId(null), 1200);
  };

  // Move: adds to default list AND removes from current list.
  // When viewing All Leads, falls back to save-only (nothing to remove from).
  const moveAndRemove = (productId) => {
    if (!defaultListId) return;
    const isAllLeads = activeListId === 'all';
    const isSameList = activeListId === defaultListId;
    setLeads(prev => ({
      ...prev,
      products: prev.products.map(p => {
        if (p.id !== productId) return p;
        let lists = [...new Set([...(p.lists || []), defaultListId])];
        if (!isAllLeads && !isSameList) lists = lists.filter(lid => lid !== activeListId);
        return { ...p, lists };
      }),
    }));
    setMovedId(productId);
    setTimeout(() => setMovedId(null), 1200);
  };

  const initialCustom = leads.customCols || [];
  const [customCols, setCustomCols] = useState(initialCustom);
  const storedCols = loadStoredCols(initialCustom);
  const [order, setOrder] = useState(storedCols.order);
  const [hidden, setHidden] = useState(storedCols.hidden);
  const [notes, setNotes] = useState(leads.notes || {});
  const [sortKey, setSortKey] = useState(() => localStorage.getItem('aip_sort_key') || null);
  const [sortDir, setSortDir] = useState(() => localStorage.getItem('aip_sort_dir') || 'asc');
  const [page, setPage] = useState(1);

  useEffect(() => {
    setLeads(prev => ({ ...prev, customCols, notes }));
  }, [customCols, notes]);

  useEffect(() => {
    try { localStorage.setItem(LEADS_COLS_KEY, JSON.stringify({ order, hidden: [...hidden] })); } catch (_) {}
  }, [order, hidden]);

  // Reset to page 1 whenever the result set changes
  useEffect(() => { setPage(1); }, [activeListId, search, filters, sortKey, sortDir]);

  const visibleProducts = useMemo(() => {
    let out = leads.products;
    if (activeListId !== 'all') out = out.filter(p => (p.lists || []).includes(activeListId));
    if (search) {
      const q = search.toLowerCase();
      out = out.filter(p => p.name.toLowerCase().includes(q) || p.asin.toLowerCase().includes(q) || (p.brand || '').toLowerCase().includes(q));
    }
    if (filters.category !== 'All categories') out = out.filter(p => p.category === filters.category);

    const rangeFilter = (field, [lo, hi]) => {
      if (toNum(lo) !== null) out = out.filter(p => (p[field] ?? 0) >= toNum(lo));
      if (toNum(hi) !== null) out = out.filter(p => (p[field] ?? 0) <= toNum(hi));
    };
    rangeFilter('price',        filters.price);
    rangeFilter('monthlySales', filters.monthlySales);
    rangeFilter('revenue30d',   filters.revenue30d);
    rangeFilter('bsr',          filters.bsr);
    rangeFilter('reviews',      filters.reviewCount);
    rangeFilter('variations',   filters.variations);
    rangeFilter('videos',       filters.videos);
    rangeFilter('cc',           filters.cc);
    rangeFilter('budget',          filters.totalBudget);
    rangeFilter('remainingBudget', filters.budget);
    rangeFilter('ccCommission',    filters.ccCommission);
    rangeFilter('availableSlots',  filters.availableSlots);
    rangeFilter('listingAge',      filters.listingAge);
    const budgetPctLo = toNum(filters.budgetPct[0]), budgetPctHi = toNum(filters.budgetPct[1]);
    if (budgetPctLo !== null) out = out.filter(p => p.budget > 0 && (p.remainingBudget / p.budget * 100) >= budgetPctLo);
    if (budgetPctHi !== null) out = out.filter(p => p.budget > 0 && (p.remainingBudget / p.budget * 100) <= budgetPctHi);
    const slotsPctLo = toNum(filters.slotsPct[0]), slotsPctHi = toNum(filters.slotsPct[1]);
    if (slotsPctLo !== null) out = out.filter(p => p.totalSlots > 0 && (p.availableSlots / p.totalSlots * 100) >= slotsPctLo);
    if (slotsPctHi !== null) out = out.filter(p => p.totalSlots > 0 && (p.availableSlots / p.totalSlots * 100) <= slotsPctHi);
    if (filters.rating[0] > 1) out = out.filter(p => (p.rating || 0) >= filters.rating[0]);
    if (filters.rating[1] < 5) out = out.filter(p => (p.rating || 0) <= filters.rating[1]);
    if (filters.campaignStart[0]) out = out.filter(p => p.campaignStart && p.campaignStart >= filters.campaignStart[0]);
    if (filters.campaignStart[1]) out = out.filter(p => p.campaignStart && p.campaignStart <= filters.campaignStart[1]);
    if (filters.campaignEnd[0]) out = out.filter(p => p.campaignEnd && p.campaignEnd >= filters.campaignEnd[0]);
    if (filters.campaignEnd[1]) out = out.filter(p => p.campaignEnd && p.campaignEnd <= filters.campaignEnd[1]);
    if (filters.hasMainVideo) out = out.filter(p => p.hasMainVideo);

    if (sortKey) {
      const SORT_FIELD = { product: 'name', campaignDate: 'campaignStart' };
      const getVal = (p, key) => {
        if (key === 'trend') return p.budget > 0 ? (p.remainingBudget / p.budget) * 100 : null;
        if (key === 'slotsTrend') return p.totalSlots > 0 ? (p.availableSlots / p.totalSlots) * 100 : null;
        const field = SORT_FIELD[key] || key;
        return p[field] ?? null;
      };
      out = [...out].sort((a, b) => {
        let av = getVal(a, sortKey), bv = getVal(b, sortKey);
        if (av == null && bv == null) return 0;
        if (av == null) return 1;
        if (bv == null) return -1;
        const cmp = typeof av === 'string' ? av.localeCompare(bv) : av - bv;
        return sortDir === 'asc' ? cmp : -cmp;
      });
    }

    return out;
  }, [leads.products, activeListId, search, filters, sortKey, sortDir]);

  const totalPages = Math.max(1, Math.ceil(visibleProducts.length / PAGE_SIZE));
  const safePage   = Math.min(page, totalPages);
  const pagedProducts = visibleProducts.slice((safePage - 1) * PAGE_SIZE, safePage * PAGE_SIZE);

  const activeList = leads.lists.find(l => l.id === activeListId);

  const updateNote = (productId, colKey, text) => {
    setNotes(prev => ({ ...prev, [productId]: { ...(prev[productId] || {}), [colKey]: text } }));
  };

  const createList = () => {
    if (!newListName.trim()) return;
    const id = newListName.toLowerCase().replace(/[^a-z0-9]+/g, '-') + '-' + Date.now().toString(36).slice(-4);
    const color = LIST_COLORS[leads.lists.length % LIST_COLORS.length];
    setLeads(prev => ({ ...prev, lists: [...prev.lists, { id, name: newListName, color }] }));
    setNewListName(''); setCreatingList(false); setActiveListId(id);
  };

  const deleteList = (id) => {
    if (!confirm(`Delete this list? Products will stay in All Leads.`)) return;
    setLeads(prev => ({
      ...prev,
      lists: prev.lists.filter(l => l.id !== id),
      products: prev.products.map(p => ({ ...p, lists: (p.lists || []).filter(lid => lid !== id) })),
    }));
    if (activeListId === id) setActiveListId('all');
  };

  const renameList = (id, name) => {
    setLeads(prev => ({ ...prev, lists: prev.lists.map(l => l.id === id ? { ...l, name } : l) }));
  };

  const setListColor = (id, color) => {
    setLeads(prev => ({ ...prev, lists: prev.lists.map(l => l.id === id ? { ...l, color } : l) }));
    setMenuOpenId(null);
  };

  const setListStatus = (id, status) => {
    setLeads(prev => ({ ...prev, lists: prev.lists.map(l => l.id === id ? { ...l, status } : l) }));
  };

  const setListStatKeys = (id, statKeys) => {
    setLeads(prev => ({ ...prev, lists: prev.lists.map(l => l.id === id ? { ...l, statKeys } : l) }));
  };

  const removeFromLeads = (id, fromListId) => {
    if (fromListId === 'all') {
      if (!confirm('Permanently delete this lead from All Leads and all lists?')) return;
      setUndoData(leads.products);
      setLeads(prev => ({ ...prev, products: prev.products.filter(p => p.id !== id) }));
    } else {
      // Remove from this list only — product stays in All Leads and any other lists
      setLeads(prev => ({
        ...prev,
        products: prev.products.map(p =>
          p.id === id ? { ...p, lists: (p.lists || []).filter(lid => lid !== fromListId) } : p
        ),
      }));
    }
  };

  const undoDelete = () => {
    setLeads(prev => ({ ...prev, products: undoData }));
    setUndoData(null);
  };

  // ── Bulk selection ────────────────────────────────────────────────────────
  // Checkbox operates on the current page only; a secondary action selects the full list.
  const allPageSelected  = pagedProducts.length > 0 && pagedProducts.every(p => selected.has(p.id));
  const somePageSelected = pagedProducts.some(p => selected.has(p.id));
  const allVisibleSelected = visibleProducts.length > 0 && visibleProducts.every(p => selected.has(p.id));
  // Show "select all in list" banner when whole page is ticked but there's more
  const showSelectAllBanner = allPageSelected && !allVisibleSelected && visibleProducts.length > pagedProducts.length;

  const toggleSelect = (id) => setSelected(prev => {
    const next = new Set(prev);
    if (next.has(id)) next.delete(id); else next.add(id);
    return next;
  });

  const toggleSelectPage = () => {
    if (allPageSelected) {
      setSelected(prev => { const next = new Set(prev); pagedProducts.forEach(p => next.delete(p.id)); return next; });
    } else {
      setSelected(prev => { const next = new Set(prev); pagedProducts.forEach(p => next.add(p.id)); return next; });
    }
  };

  const selectAllVisible = () => {
    setSelected(prev => { const next = new Set(prev); visibleProducts.forEach(p => next.add(p.id)); return next; });
  };

  const bulkDelete = () => {
    const n = selected.size;
    const plural = n > 1 ? 's' : '';
    if (activeListId === 'all') {
      if (!confirm(`Permanently delete ${n} product${plural} from All Leads? This cannot be undone.`)) return;
      setUndoData(leads.products);
      setLeads(prev => ({ ...prev, products: prev.products.filter(p => !selected.has(p.id)) }));
    } else {
      const listLabel = activeListId === 'inbox' ? 'Inbox' : 'this list';
      if (!confirm(`Remove ${n} product${plural} from ${listLabel}? They will stay in All Leads.`)) return;
      setLeads(prev => ({
        ...prev,
        products: prev.products.map(p =>
          selected.has(p.id) ? { ...p, lists: (p.lists || []).filter(lid => lid !== activeListId) } : p
        ),
      }));
    }
    setSelected(new Set());
  };

  const bulkMove = (listId) => {
    setLeads(prev => ({
      ...prev,
      products: prev.products.map(p =>
        selected.has(p.id) ? { ...p, lists: [...new Set([...(p.lists || []), listId])] } : p
      ),
    }));
    setSelected(new Set());
  };

  const isCustomKey = (k) => k.startsWith('cust_');

  const handleSort = (key) => {
    if (isCustomKey(key)) return;
    if (sortKey === key) {
      const next = sortDir === 'asc' ? 'desc' : 'asc';
      setSortDir(next);
      localStorage.setItem('aip_sort_dir', next);
    } else {
      setSortKey(key);
      setSortDir('asc');
      localStorage.setItem('aip_sort_key', key);
      localStorage.setItem('aip_sort_dir', 'asc');
    }
  };

  const visibleCols = order.filter(k => !hidden.has(k));

  const qcOnlyCols = activeQcProfile.qcCols || [];

  // Quick-copy effective column order: all configured columns (including hidden ones)
  // plus any QC-only columns stored in the active profile.
  const effectiveQcOrder = useMemo(() => {
    const qcOnlyKeys = qcOnlyCols.map(c => c.key);
    const allKeys = [...order, ...qcOnlyKeys];
    if (quickCopyOrder === null) return allKeys;
    const stored = quickCopyOrder.filter(k => allKeys.includes(k));
    const storedSet = new Set(stored);
    const newCols = allKeys.filter(k => !storedSet.has(k));
    return [...stored, ...newCols];
  }, [quickCopyOrder, order, qcOnlyCols]);

  const exportCSV = () => {
    const colDefs = visibleCols.map(key => {
      const std = COLUMN_BY_KEY[key];
      const cust = !std && customCols.find(c => c.key === key);
      return { key, label: std?.label || cust?.label || key, isCustom: !!cust };
    }).filter(c => c.label);

    const getCellText = (key, p) => {
      if (isCustomKey(key)) return notes[p.id]?.[key] || '';
      switch (key) {
        case 'product':        return p.name || '';
        case 'campaignDate':   return [p.campaignStart, p.campaignEnd].filter(Boolean).join(' → ');
        case 'cc':             return p.cc ? `${p.cc}%` : '';
        case 'onSite':         return p.onSite != null ? `${p.onSite}%` : '';
        case 'trend':          return p.budget > 0 ? `${Math.round((p.remainingBudget / p.budget) * 100)}%` : '—';
        default:               return p[key] != null ? String(p[key]) : '';
      }
    };

    const esc = (v) => {
      const s = String(v ?? '');
      return /[,"\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
    };

    // Helpers for linked columns
    const creatorId = localStorage.getItem('aip_creator_id');
    // =HYPERLINK("url","label") — internal quotes swapped to ' so the formula stays valid
    const hyperlink = (url, label) =>
      `=HYPERLINK("${url}","${String(label).replace(/"/g, "'")}")`;
    const buildCCSearchUrl = (asin) => {
      const params = new URLSearchParams({
        status: 'opportunity', type: 'affiliate-plus',
        sortBy: 'recommended_for_you', keyword: asin,
        filterExpanderStatus: 'false', categories: '',
        nonFullyClaimedOnly: 'false', campaignStatuses: 'active,pending',
        earlyAccessOnly: 'false', topBrandsOnly: 'false',
        creatorFavoritesOnly: 'false', brands: '', contentType: '', budgetAvailability: '',
      });
      if (creatorId) params.set('creatorId', creatorId);
      return `https://affiliate-program.amazon.com/p/connect/requests?${params}`;
    };
    const buildCampaignUrl = (p) => {
      if (!p.campaignId) return null;
      const fullId = p.campaignId.startsWith('amzn1.campaign.') ? p.campaignId : `amzn1.campaign.${p.campaignId}`;
      const parts = [
        creatorId ? `creatorId=${creatorId}` : null,
        `adId=${fullId}`, `campaignId=${fullId}`,
        'recc=0', 'early-acc=0', 'type=spcc', 'status=opportunity',
      ].filter(Boolean).join('&');
      return `https://affiliate-program.amazon.com/p/connect/request?${parts}`;
    };

    const exportCols = colDefs;
    const getExportText = (key, p) => {
      switch (key) {
        case 'product': {
          const url = p.asin ? `https://www.amazon.com/dp/${p.asin}` : null;
          return url ? hyperlink(url, p.name || p.asin) : (p.name || '');
        }
        case 'brand': {
          if (!p.brand) return '';
          return hyperlink(buildCCSearchUrl(p.brand), p.brand);
        }
        case 'cc': {
          if (!p.cc) return '';
          return hyperlink(buildCCSearchUrl(p.asin), `${p.cc}%`);
        }
        case 'campaignDate': {
          const dateRange = [p.campaignStart, p.campaignEnd].filter(Boolean).join(' → ');
          const url = buildCampaignUrl(p);
          return (url && dateRange) ? hyperlink(url, dateRange) : dateRange;
        }
        default:
          return getCellText(key, p);
      }
    };

    const header = exportCols.map(c => esc(c.label)).join(',');
    const rows   = visibleProducts.map(p => exportCols.map(c => esc(getExportText(c.key, p))).join(','));
    const csv    = [header, ...rows].join('\n');

    const listName = activeListId === 'all' ? 'All Leads' : (activeList?.name || 'Leads');
    const date     = new Date().toISOString().slice(0, 10);
    const filename = `${listName} ${date}.csv`;

    const url = URL.createObjectURL(new Blob([csv], { type: 'text/csv' }));
    Object.assign(document.createElement('a'), { href: url, download: filename }).click();
    URL.revokeObjectURL(url);
  };

  // stats: fixed cards + all configurable stat values
  const stats = useMemo(() => {
    const items = visibleProducts;
    if (items.length === 0) return null;
    const avgMonthlySales = Math.round(items.reduce((a, p) => a + p.monthlySales, 0) / items.length);
    const avgCcCommission = items.reduce((a, p) => a + p.ccCommission, 0) / items.length;
    const avgRev = items.reduce((a, p) => a + p.revenue30d, 0) / items.length;
    const totalCost = items.reduce((a, p) => a + (p.price || 0), 0);
    const ccItems = items.filter(p => p.cc > 0);
    const breakEven = ccItems.length
      ? Math.round(ccItems.reduce((a, p) => a + 100 / p.cc, 0) / ccItems.length)
      : 0;
    const avgCcRate = ccItems.length
      ? Math.round(ccItems.reduce((a, p) => a + p.cc, 0) / ccItems.length)
      : 0;
    const ccCount = ccItems.length;
    return { count: items.length, avgMonthlySales, avgCcCommission, avgRev, totalCost, breakEven, avgCcRate, ccCount };
  }, [visibleProducts]);

  return (
    <div className="page" style={{
      padding: 0,
      display: 'grid',
      gridTemplateColumns: sidebarCollapsed ? '52px 1fr' : '260px 1fr',
      transition: 'grid-template-columns 0.2s',
      gap: 0,
    }}>
      {/* LEFT PANEL */}
      <div style={{
        borderRight: '1px solid var(--line)',
        background: 'rgba(10,14,26,0.4)',
        padding: sidebarCollapsed ? '24px 6px' : '24px 14px',
        height: '100%', overflowY: 'auto', overflowX: 'hidden',
        display: 'flex', flexDirection: 'column',
        position: 'relative',
      }}>
        <button
          className="icon-btn"
          style={{ position: 'absolute', top: 14, right: sidebarCollapsed ? 6 : 10, width: 28, height: 28, zIndex: 2 }}
          onClick={() => setSidebarCollapsed(c => !c)}
          title={sidebarCollapsed ? 'Expand' : 'Collapse'}
        >
          {sidebarCollapsed ? <Icons.chevRight size={13}/> : <Icons.chevLeft size={13}/>}
        </button>

        {!sidebarCollapsed && (
          <div style={{ padding: '0 8px 12px' }}>
            <div className="card-eyebrow">Lead lists</div>
            <div style={{ fontSize: 18, fontWeight: 700, marginTop: 4, letterSpacing: '-0.3px' }}>Your pipeline</div>
          </div>
        )}

        <div
          className={`list-pill ${activeListId === 'all' ? 'active' : ''}`}
          onClick={() => setActiveListId('all')}
          style={sidebarCollapsed ? { justifyContent: 'center', padding: '9px 6px' } : null}
          title="All leads"
        >
          <Icons.layout size={14} style={{ color: 'var(--accent)' }}/>
          {!sidebarCollapsed && <>
            <span className="name">All leads</span>
            <span className="count">{leads.products.length}</span>
          </>}
        </div>

        {/* Inbox — fixed, non-deletable, always shows latest import */}
        {(() => {
          const inboxCount = leads.products.filter(p => (p.lists || []).includes('inbox')).length;
          return (
            <div
              className={`list-pill ${activeListId === 'inbox' ? 'active' : ''}`}
              onClick={() => setActiveListId('inbox')}
              style={sidebarCollapsed ? { justifyContent: 'center', padding: '9px 6px' } : null}
              title="Inbox — latest import"
            >
              <Icons.mail size={14} style={{ color: 'var(--accent)', flexShrink: 0 }}/>
              {!sidebarCollapsed && <>
                <span className="name">Inbox</span>
                <span className="count">{inboxCount}</span>
              </>}
            </div>
          );
        })()}

        {!sidebarCollapsed && <div className="nav-section-label" style={{ padding: '14px 10px 6px' }}>My lists</div>}

        {leads.lists.filter(l => l.id !== 'inbox').map((l, idx) => {
          const count = leads.products.filter(p => (p.lists || []).includes(l.id)).length;
          const isEditing = editingListId === l.id;
          return (
            <div
              key={l.id}
              style={{ position: 'relative', opacity: dragListIdx === idx ? 0.4 : 1 }}
              draggable={!sidebarCollapsed}
              onDragStart={() => setDragListIdx(idx)}
              onDragOver={(e) => e.preventDefault()}
              onDrop={() => { if (dragListIdx !== null && dragListIdx !== idx) reorderLists(dragListIdx, idx); setDragListIdx(null); }}
              onDragEnd={() => setDragListIdx(null)}
            >
              <div
                className={`list-pill ${activeListId === l.id ? 'active' : ''}`}
                onClick={() => !isEditing && setActiveListId(l.id)}
                style={sidebarCollapsed ? { justifyContent: 'center', padding: '9px 6px' } : null}
                title={l.name}
              >
                {!sidebarCollapsed && <Icons.drag size={12} style={{ color: 'var(--text-3)', flexShrink: 0, cursor: 'grab' }}/>}
                <span
                  className="dot-sq"
                  style={{ background: l.color, boxShadow: `0 0 6px ${l.color}`, cursor: 'pointer' }}
                  onClick={(e) => { e.stopPropagation(); setMenuOpenId(menuOpenId === l.id ? null : l.id); }}
                  title="Change color"
                />
                {!sidebarCollapsed && (isEditing ? (
                  <input
                    autoFocus
                    value={l.name}
                    onChange={(e) => renameList(l.id, e.target.value)}
                    onBlur={() => setEditingListId(null)}
                    onKeyDown={(e) => e.key === 'Enter' && setEditingListId(null)}
                    onClick={(e) => e.stopPropagation()}
                    style={{ flex: 1, minWidth: 0, background: 'transparent', border: '1px dashed var(--line-strong)', borderRadius: 4, padding: '2px 6px', color: 'var(--text-0)', font: 'inherit', outline: 'none' }}
                  />
                ) : (
                  <span className="name" style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{l.name}</span>
                ))}
                {!sidebarCollapsed && (
                  <>
                    <span className="count">{count}</span>
                    <button
                      className="icon-btn"
                      style={{ width: 24, height: 24, flexShrink: 0, opacity: 0.6 }}
                      onClick={(e) => { e.stopPropagation(); setMenuOpenId(menuOpenId === l.id ? null : l.id); }}
                      title="More options"
                    >
                      <Icons.more size={13}/>
                    </button>
                  </>
                )}
              </div>
              {menuOpenId === l.id && !sidebarCollapsed && (
                <div
                  style={{
                    position: 'absolute', top: '100%', right: 0, zIndex: 10,
                    background: 'var(--bg-elev)', border: '1px solid var(--line-strong)',
                    borderRadius: 10, padding: 6, marginTop: 4,
                    boxShadow: '0 12px 30px -8px rgba(0,0,0,0.7)',
                    minWidth: 170,
                  }}
                  onClick={(e) => e.stopPropagation()}
                >
                  <button
                    className="btn btn-ghost btn-sm"
                    style={{ width: '100%', justifyContent: 'flex-start', gap: 8, fontSize: 12 }}
                    onClick={() => { setEditingListId(l.id); setMenuOpenId(null); }}
                  >
                    <Icons.edit size={11}/> Rename
                  </button>
                  <div style={{ padding: '8px 10px 4px' }}>
                    <div style={{ fontSize: 11, color: 'var(--text-3)', marginBottom: 6, fontWeight: 600, letterSpacing: '0.04em' }}>COLOR</div>
                    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 5 }}>
                      {LIST_COLORS.map(c => (
                        <span key={c}
                          onClick={() => setListColor(l.id, c)}
                          style={{
                            width: 19, height: 19, borderRadius: 5,
                            background: c, cursor: 'pointer',
                            boxShadow: l.color === c ? `0 0 0 2px var(--bg-elev), 0 0 0 3.5px ${c}` : `0 0 4px ${c}50`,
                          }}
                        />
                      ))}
                    </div>
                  </div>
                  <div style={{ height: 1, background: 'var(--line)', margin: '6px 0' }}/>
                  <button
                    className="btn btn-ghost btn-sm"
                    style={{ width: '100%', justifyContent: 'flex-start', gap: 8, fontSize: 12, color: 'var(--danger)' }}
                    onClick={() => { deleteList(l.id); setMenuOpenId(null); }}
                  >
                    <Icons.trash size={11}/> Delete list
                  </button>
                </div>
              )}
            </div>
          );
        })}

        {!sidebarCollapsed && (
          <div style={{ marginTop: 8 }}>
            {creatingList ? (
              <div style={{ padding: 10, borderRadius: 9, border: '1px dashed var(--line-strong)', background: 'var(--bg-2)' }}>
                <input className="field-input" style={{ padding: '7px 10px', fontSize: 12 }}
                  placeholder="List name" value={newListName} autoFocus
                  onChange={(e) => setNewListName(e.target.value)}
                  onKeyDown={(e) => e.key === 'Enter' && createList()} />
                <div style={{ display: 'flex', gap: 6, marginTop: 8 }}>
                  <button className="btn btn-primary btn-sm" style={{ flex: 1 }} onClick={createList}>Create</button>
                  <button className="btn btn-sm btn-ghost" onClick={() => { setCreatingList(false); setNewListName(''); }}>Cancel</button>
                </div>
              </div>
            ) : (
              <div className="list-pill" onClick={() => setCreatingList(true)} style={{
                border: '1px dashed var(--line-strong)', color: 'var(--text-2)', justifyContent: 'center',
              }}>
                <Icons.plus size={13}/> <span style={{ flex: 'none' }}>Create new list</span>
              </div>
            )}
          </div>
        )}

        {!sidebarCollapsed && (
          <div style={{ marginTop: 'auto', padding: '14px 4px 0', borderTop: '1px solid var(--line)' }}>
            <div className="card-eyebrow">Quick actions</div>
            <div style={{ display: 'grid', gap: 4, marginTop: 8 }}>
              <button className="btn btn-ghost btn-sm" style={{ justifyContent: 'flex-start' }}><Icons.upload size={13}/> Import CSV</button>
              <button className="btn btn-ghost btn-sm" style={{ justifyContent: 'flex-start' }} onClick={exportCSV}><Icons.download size={13}/> Export list</button>
            </div>
          </div>
        )}
      </div>

      {/* MAIN CONTENT */}
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
        {/* Non-scrolling: header + stats + filters */}
        <div style={{ padding: '24px 28px 0', flexShrink: 0 }}>
        <div className="page-header">
          <div className="page-title-block">
            <h1 style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
              {activeList && <span className="dot-sq" style={{ width: 14, height: 14, borderRadius: 4, background: activeList.color, boxShadow: `0 0 12px ${activeList.color}` }}/>}
              {activeListId === 'all' ? 'All leads' : activeListId === 'inbox' ? 'Inbox' : activeList?.name}
              {/* Status stage badge — only for named lists */}
              {activeList && activeListId !== 'inbox' && (() => {
                const activeStatuses = leads.flowStatuses || FLOW_DEFAULT_STATUSES;
                const defaultId = activeStatuses[0]?.id;
                const currentStatus = activeStatuses.find(s => s.id === (activeList.status || defaultId)) || activeStatuses[0];
                if (!currentStatus) return null;
                const StatusIcon = getStatusIcon(currentStatus.iconId);
                return (
                  <div style={{ position: 'relative' }} onClick={e => e.stopPropagation()}>
                    <button
                      onClick={() => setShowStatusDropdown(p => !p)}
                      style={{
                        display: 'flex', alignItems: 'center', gap: 5,
                        padding: '4px 9px', borderRadius: 6,
                        background: 'var(--bg-2)', border: '1px solid var(--line-strong)',
                        cursor: 'pointer', color: 'var(--text-2)',
                        fontSize: 12, fontWeight: 500, letterSpacing: '0.01em',
                      }}
                    >
                      <StatusIcon size={12}/>
                      {currentStatus.label}
                      <Icons.chevDown size={10} style={{ color: 'var(--text-3)', marginLeft: 1 }}/>
                    </button>
                    {showStatusDropdown && (
                      <div style={{
                        position: 'absolute', top: 'calc(100% + 6px)', left: 0, zIndex: 20,
                        background: 'var(--bg-elev)', border: '1px solid var(--line-strong)',
                        borderRadius: 10, padding: 6, minWidth: 176,
                        boxShadow: '0 12px 30px -8px rgba(0,0,0,0.7)',
                      }}>
                        {activeStatuses.map((s, i) => {
                          const SIcon = getStatusIcon(s.iconId);
                          const isCurrent = s.id === (activeList.status || defaultId);
                          return (
                            <button
                              key={s.id}
                              onClick={() => { setListStatus(activeListId, s.id); setShowStatusDropdown(false); }}
                              style={{
                                display: 'flex', alignItems: 'center', gap: 8,
                                width: '100%', padding: '7px 10px', borderRadius: 6,
                                background: isCurrent ? 'var(--accent-soft)' : 'transparent',
                                border: 'none', cursor: 'pointer',
                                color: isCurrent ? 'var(--accent)' : 'var(--text-1)',
                                fontSize: 13, fontWeight: isCurrent ? 600 : 400,
                                textAlign: 'left',
                              }}
                            >
                              <span style={{
                                display: 'flex', alignItems: 'center', justifyContent: 'center',
                                width: 22, height: 22, borderRadius: 5, flexShrink: 0,
                                background: s.color + '20', color: s.color,
                              }}>
                                <SIcon size={12}/>
                              </span>
                              {s.label}
                            </button>
                          );
                        })}
                      </div>
                    )}
                  </div>
                );
              })()}
            </h1>
            <div className="subtitle">
              {visibleProducts.length} products
              {activeListId !== 'all' && ` · ${activeListId === 'inbox' ? 'Inbox' : activeList?.name}`}
              {' · last updated Apr 26, 2026'}
            </div>
          </div>
          <div className="page-actions">
            {undoData && (
              <button className="btn" onClick={undoDelete} style={{ color: 'var(--danger)', borderColor: 'var(--danger)' }}>
                <Icons.reset size={13}/> Undo delete
              </button>
            )}
            <button className="btn" onClick={exportCSV}><Icons.download size={13}/> Export</button>
            <button className="btn" onClick={() => setShowColumnsDrawer(true)}>
              <Icons.columns size={13}/> Manage columns
            </button>
            {/* Quick copy field picker */}
            <div style={{ position: 'relative', display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 3 }} onClick={e => e.stopPropagation()}>
              <button
                className="btn"
                onClick={() => setShowQuickCopyPicker(p => !p)}
                title="Choose which fields are included when you click the copy row icon"
              >
                <Icons.copy size={13}/>
                Quick copy
                {quickCopyKeys !== null && (
                  <span className="badge badge-neutral" style={{ marginLeft: 4, fontSize: 10 }}>
                    {effectiveQcOrder.filter(k => quickCopyKeys.has(k)).length}
                  </span>
                )}
              </button>
              <div style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 11, fontWeight: 600, color: 'var(--accent)', paddingRight: 2 }}>
                <span style={{ width: 6, height: 6, borderRadius: 2, background: 'var(--accent)', boxShadow: '0 0 5px var(--accent)' }}/>
                {activeQcProfile.name}
              </div>
              {showQuickCopyPicker && (
                <div
                  onClick={e => e.stopPropagation()}
                  style={{
                    position: 'absolute', top: 'calc(100% + 6px)', right: 0, zIndex: 20,
                    background: 'var(--bg-elev)', border: '1px solid var(--line-strong)',
                    borderRadius: 10, padding: 6, minWidth: 230,
                    boxShadow: '0 12px 30px -8px rgba(0,0,0,0.7)',
                    maxHeight: 440, overflowY: 'auto',
                  }}
                >
                  {/* Profile selector */}
                  <div style={{ fontSize: 11, color: 'var(--text-3)', fontWeight: 600, padding: '4px 8px 6px', letterSpacing: '0.05em' }}>PROFILE</div>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4, padding: '0 6px 8px' }}>
                    {qcProfiles.map(profile => (
                      <div
                        key={profile.id}
                        onClick={() => { setActiveQcProfileId(profile.id); setRenamingQcProfileId(null); }}
                        style={{
                          display: 'flex', alignItems: 'center', gap: 3,
                          padding: '3px 6px 3px 10px', borderRadius: 20, cursor: 'pointer',
                          border: `1px solid ${activeQcProfileId === profile.id ? 'var(--accent)' : 'var(--line-strong)'}`,
                          background: activeQcProfileId === profile.id ? 'var(--accent-soft)' : 'transparent',
                        }}
                      >
                        {renamingQcProfileId === profile.id ? (
                          <input
                            autoFocus
                            value={profile.name}
                            style={{ width: 80, background: 'transparent', border: 'none', outline: 'none', color: 'var(--text-0)', font: 'inherit', fontSize: 12 }}
                            onChange={e => renameQcProfile(profile.id, e.target.value)}
                            onBlur={() => setRenamingQcProfileId(null)}
                            onKeyDown={e => { if (e.key === 'Enter') setRenamingQcProfileId(null); }}
                            onClick={e => e.stopPropagation()}
                          />
                        ) : (
                          <span
                            style={{ fontSize: 12, color: activeQcProfileId === profile.id ? 'var(--accent)' : 'var(--text-1)' }}
                            onDoubleClick={e => { e.stopPropagation(); setRenamingQcProfileId(profile.id); }}
                            title="Double-click to rename"
                          >
                            {profile.name}
                          </span>
                        )}
                        {qcProfiles.length > 1 && (
                          <button
                            title="Delete profile"
                            onClick={e => { e.stopPropagation(); deleteQcProfile(profile.id); }}
                            style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', width: 14, height: 14, background: 'transparent', border: 'none', cursor: 'pointer', color: 'var(--text-3)', padding: 0, flexShrink: 0 }}
                          >
                            <Icons.close size={9}/>
                          </button>
                        )}
                      </div>
                    ))}
                    <button
                      className="btn btn-sm btn-ghost"
                      style={{ fontSize: 11, padding: '3px 8px', borderRadius: 20 }}
                      onClick={addQcProfile}
                      title="New profile (copies current settings)"
                    >
                      <Icons.plus size={10}/> New
                    </button>
                  </div>

                  <div style={{ height: 1, background: 'var(--line)', margin: '0 0 4px' }}/>

                  {/* Copy headings button */}
                  <button
                    className="btn btn-ghost btn-sm"
                    style={{ width: '100%', justifyContent: 'flex-start', gap: 8, fontSize: 12, padding: '6px 10px' }}
                    onClick={() => {
                      const keysToUse = quickCopyKeys !== null
                        ? effectiveQcOrder.filter(k => quickCopyKeys.has(k))
                        : effectiveQcOrder;
                      const headers = keysToUse.map(key => {
                        const std = COLUMN_BY_KEY[key];
                        const cust = !std && customCols.find(c => c.key === key);
                        const qcOnly = !std && !cust && qcOnlyCols.find(c => c.key === key);
                        return std?.label || cust?.label || qcOnly?.label || key;
                      });
                      navigator.clipboard.writeText(headers.join('\t')).then(() => {
                        setQcCopiedHeaders(true);
                        setTimeout(() => setQcCopiedHeaders(false), 1500);
                      });
                    }}
                  >
                    {qcCopiedHeaders ? <Icons.check size={12} style={{ color: 'var(--success)' }}/> : <Icons.copy size={12}/>}
                    <span style={{ color: qcCopiedHeaders ? 'var(--success)' : 'var(--text-1)' }}>
                      {qcCopiedHeaders ? 'Headings copied!' : 'Copy headings'}
                    </span>
                  </button>

                  {/* Include links toggle */}
                  <button
                    className="btn btn-ghost btn-sm"
                    style={{ width: '100%', justifyContent: 'space-between', fontSize: 12, padding: '6px 10px' }}
                    onClick={() => updateActiveQcProfile({ includeLinks: !quickCopyIncludeLinks })}
                  >
                    <span style={{ color: 'var(--text-1)' }}>Include links</span>
                    <span style={{
                      display: 'inline-flex', width: 30, height: 16, borderRadius: 8, padding: 2,
                      background: quickCopyIncludeLinks ? 'var(--accent)' : 'rgba(255,255,255,0.12)',
                      alignItems: 'center', flexShrink: 0, transition: 'background 0.2s',
                    }}>
                      <span style={{
                        width: 12, height: 12, borderRadius: '50%', background: '#fff',
                        marginLeft: quickCopyIncludeLinks ? 14 : 0, transition: 'margin-left 0.2s',
                        boxShadow: '0 1px 3px rgba(0,0,0,0.35)',
                      }}/>
                    </span>
                  </button>

                  <div style={{ height: 1, background: 'var(--line)', margin: '6px 0' }}/>

                  {/* All / None */}
                  <div style={{ display: 'flex', gap: 6, padding: '2px 4px 8px' }}>
                    <button
                      className="btn btn-sm btn-ghost"
                      style={{ fontSize: 11, padding: '3px 10px' }}
                      onClick={() => updateActiveQcProfile({ keys: null })}
                    >
                      All {quickCopyKeys === null && <span style={{ color: 'var(--accent)' }}>✓</span>}
                    </button>
                    <button
                      className="btn btn-sm btn-ghost"
                      style={{ fontSize: 11, padding: '3px 10px' }}
                      onClick={() => updateActiveQcProfile({ keys: [] })}
                    >
                      None
                    </button>
                  </div>

                  <div style={{ height: 1, background: 'var(--line)', margin: '0 0 4px' }}/>

                  {/* Column rows — draggable to reorder */}
                  {effectiveQcOrder.map((key, idx) => {
                    const std = COLUMN_BY_KEY[key];
                    const cust = !std && customCols.find(c => c.key === key);
                    const qcOnly = !std && !cust && qcOnlyCols.find(c => c.key === key);
                    const label = std?.label || cust?.label || qcOnly?.label || key;
                    const checked = quickCopyKeys === null || quickCopyKeys.has(key);
                    return (
                      <div
                        key={key}
                        draggable
                        onDragStart={() => setQcDragIdx(idx)}
                        onDragOver={e => e.preventDefault()}
                        onDrop={() => {
                          if (qcDragIdx !== null && qcDragIdx !== idx) {
                            const next = [...effectiveQcOrder];
                            const [moved] = next.splice(qcDragIdx, 1);
                            next.splice(idx, 0, moved);
                            updateActiveQcProfile({ order: next });
                          }
                          setQcDragIdx(null);
                        }}
                        onDragEnd={() => setQcDragIdx(null)}
                        style={{
                          display: 'flex', alignItems: 'center', gap: 7,
                          padding: '5px 8px', borderRadius: 6,
                          opacity: qcDragIdx === idx ? 0.4 : 1,
                          background: 'transparent',
                        }}
                      >
                        <span style={{ color: 'var(--text-3)', cursor: 'grab', flexShrink: 0, lineHeight: 0 }}>
                          <Icons.drag size={12}/>
                        </span>
                        <button
                          style={{
                            width: 14, height: 14, borderRadius: 3, flexShrink: 0,
                            border: `1.5px solid ${checked ? 'var(--accent)' : 'var(--line-strong)'}`,
                            background: checked ? 'var(--accent)' : 'transparent',
                            display: 'flex', alignItems: 'center', justifyContent: 'center',
                            cursor: 'pointer', padding: 0,
                            transition: 'background 0.15s, border-color 0.15s',
                          }}
                          onClick={() => {
                            setQcProfiles(prev => prev.map(p => {
                              if (p.id !== activeQcProfileId) return p;
                              const base = p.keys == null ? new Set(effectiveQcOrder) : new Set(p.keys);
                              if (base.has(key)) base.delete(key); else base.add(key);
                              return { ...p, keys: [...base] };
                            }));
                          }}
                        >
                          {checked && <Icons.check size={9} style={{ color: '#fff' }}/>}
                        </button>
                        <span style={{ flex: 1, fontSize: 12, color: 'var(--text-1)' }}>{label}</span>
                        {cust && <span className="badge badge-accent" style={{ fontSize: 9 }}>note</span>}
                        {qcOnly && (
                          <>
                            <span className="badge badge-neutral" style={{ fontSize: 9, opacity: 0.7 }}>qc only</span>
                            <button
                              onClick={e => { e.stopPropagation(); deleteQcOnlyCol(key); }}
                              style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', width: 14, height: 14, background: 'transparent', border: 'none', cursor: 'pointer', color: 'var(--text-3)', padding: 0, flexShrink: 0 }}
                              title="Remove QC-only column"
                            >
                              <Icons.close size={9}/>
                            </button>
                          </>
                        )}
                      </div>
                    );
                  })}

                  {/* Add custom column */}
                  <div style={{ height: 1, background: 'var(--line)', margin: '4px 0 0' }}/>
                  {showQcAddCol ? (
                    <div style={{ display: 'flex', gap: 4, padding: '4px 6px 6px' }}>
                      <input
                        autoFocus
                        className="field-input"
                        placeholder="Column name…"
                        value={qcNewColName}
                        onChange={e => setQcNewColName(e.target.value)}
                        onKeyDown={e => {
                          if (e.key === 'Enter') addCustomColFromQc(qcNewColName);
                          if (e.key === 'Escape') { setShowQcAddCol(false); setQcNewColName(''); }
                        }}
                        style={{ flex: 1, padding: '4px 8px', fontSize: 12 }}
                      />
                      <button
                        className="btn btn-sm btn-primary"
                        style={{ padding: '4px 8px', fontSize: 11 }}
                        onClick={() => addCustomColFromQc(qcNewColName)}
                      >Add</button>
                      <button
                        className="btn btn-sm btn-ghost"
                        style={{ padding: '4px 8px', fontSize: 11 }}
                        onClick={() => { setShowQcAddCol(false); setQcNewColName(''); }}
                      >✕</button>
                    </div>
                  ) : (
                    <button
                      className="btn btn-ghost btn-sm"
                      style={{ width: '100%', justifyContent: 'flex-start', gap: 8, fontSize: 12, padding: '6px 10px', color: 'var(--text-2)' }}
                      onClick={() => setShowQcAddCol(true)}
                    >
                      <Icons.plus size={12}/> Add custom column
                    </button>
                  )}
                </div>
              )}
            </div>
            <div style={{ position: 'relative', display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 3 }} onClick={e => e.stopPropagation()}>
              <button
                className="btn"
                onClick={() => setShowDefaultPicker(p => !p)}
                title="Set the list the folder button moves leads into"
              >
                <Icons.folder size={13}/>
                Default list
              </button>
              {defaultList && (
                <div style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 11, fontWeight: 600, color: defaultList.color, paddingRight: 2 }}>
                  <span style={{ width: 6, height: 6, borderRadius: 2, background: defaultList.color, boxShadow: `0 0 5px ${defaultList.color}` }}/>
                  {defaultList.name}
                </div>
              )}
              {showDefaultPicker && (
                <div
                  onClick={e => e.stopPropagation()}
                  style={{
                    position: 'absolute', top: 'calc(100% + 6px)', right: 0, zIndex: 20,
                    background: 'var(--bg-elev)', border: '1px solid var(--line-strong)',
                    borderRadius: 10, padding: 6, minWidth: 180,
                    boxShadow: '0 12px 30px -8px rgba(0,0,0,0.7)',
                  }}>
                  <div style={{ fontSize: 11, color: 'var(--text-3)', fontWeight: 600, padding: '4px 8px 6px', letterSpacing: '0.05em' }}>QUICK-MOVE TARGET</div>
                  <button
                    className="btn btn-ghost btn-sm"
                    style={{ width: '100%', justifyContent: 'flex-start', gap: 8, fontWeight: defaultListId === 'inbox' ? 700 : 400 }}
                    onClick={() => { setDefaultListId('inbox'); setShowDefaultPicker(false); }}
                  >
                    <Icons.mail size={11} style={{ color: 'var(--accent)', flexShrink: 0 }}/>
                    Inbox
                    {defaultListId === 'inbox' && <span style={{ marginLeft: 'auto', color: 'var(--accent)', fontSize: 11 }}>✓</span>}
                  </button>
                  {leads.lists.filter(l => l.id !== 'inbox').map(l => (
                    <button
                      key={l.id}
                      className="btn btn-ghost btn-sm"
                      style={{ width: '100%', justifyContent: 'flex-start', gap: 8, fontWeight: l.id === defaultListId ? 700 : 400 }}
                      onClick={() => { setDefaultListId(l.id); setShowDefaultPicker(false); }}
                    >
                      <span style={{ width: 8, height: 8, borderRadius: 2, background: l.color, flexShrink: 0, boxShadow: `0 0 5px ${l.color}` }}/>
                      {l.name}
                      {l.id === defaultListId && <span style={{ marginLeft: 'auto', color: 'var(--accent)', fontSize: 11 }}>✓</span>}
                    </button>
                  ))}
                  {defaultListId && (
                    <>
                      <div style={{ height: 1, background: 'var(--line)', margin: '4px 0' }}/>
                      <button
                        className="btn btn-ghost btn-sm"
                        style={{ width: '100%', justifyContent: 'flex-start', color: 'var(--text-3)' }}
                        onClick={() => { setDefaultListId(null); setShowDefaultPicker(false); }}
                      >
                        Clear default
                      </button>
                    </>
                  )}
                </div>
              )}
            </div>
          </div>
        </div>

        {/* Filter bar */}
        <div className="card" style={{ marginBottom: 14, overflow: 'hidden' }}>
          {/* Top row */}
          <div style={{ padding: 14, display: 'flex', gap: 10, alignItems: 'center' }}>
            <div style={{ position: 'relative', flex: 1 }}>
              <Icons.search size={14} style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--text-3)' }}/>
              <input className="field-input" style={{ paddingLeft: 36 }}
                placeholder="Search by title, ASIN, or brand…"
                value={search} onChange={(e) => setSearch(e.target.value)} />
            </div>
            <button
              className={`btn ${activeFilterCount > 0 ? 'btn-primary' : ''}`}
              onClick={() => setFiltersOpen(o => !o)}
            >
              <Icons.filter size={13}/>
              {filtersOpen ? 'Hide filters' : 'Filters'}
              {activeFilterCount > 0 && (
                <span className="badge badge-accent" style={{ marginLeft: 4, fontSize: 10 }}>{activeFilterCount}</span>
              )}
            </button>
            {(activeFilterCount > 0 || search) && (
              <button className="btn btn-ghost btn-sm" onClick={resetFilters}>
                <Icons.reset size={12}/> Reset
              </button>
            )}
          </div>

          {/* Expandable filter sections */}
          {filtersOpen && (
            <>
              <FilterSection title="Creator Connections" open={secOpen.cc} onToggle={() => setSecOpen(o => ({ ...o, cc: !o.cc }))}>
                <Field label="CC %"><NumPair values={filters.cc} onChange={v => setF('cc', v)} placeholderA="Min %" placeholderB="Max %"/></Field>
                <Field label="CC Commission ($)"><NumPair values={filters.ccCommission} onChange={v => setF('ccCommission', v)} placeholderA="Min $" placeholderB="Max $"/></Field>
                <Field label="Budget ($)"><NumPair values={filters.totalBudget} onChange={v => setF('totalBudget', v)}/></Field>
                <Field label="Remaining Budget ($)"><NumPair values={filters.budget} onChange={v => setF('budget', v)}/></Field>
                <Field label="% Budget Remaining"><NumPair values={filters.budgetPct} onChange={v => setF('budgetPct', v)} placeholderA="Min %" placeholderB="Max %"/></Field>
                <Field label="Available Slots"><NumPair values={filters.availableSlots} onChange={v => setF('availableSlots', v)} placeholderA="Min" placeholderB="Max"/></Field>
                <Field label="% Slots Remaining"><NumPair values={filters.slotsPct} onChange={v => setF('slotsPct', v)} placeholderA="Min %" placeholderB="Max %"/></Field>
                <div className="field">
                  <label className="field-label">Brand video</label>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10, paddingTop: 6 }}>
                    <button
                      onClick={() => setF('hasMainVideo', !filters.hasMainVideo)}
                      style={{
                        width: 36, height: 20, borderRadius: 10, border: 'none', cursor: 'pointer',
                        background: filters.hasMainVideo ? 'var(--accent)' : 'rgba(255,255,255,0.12)',
                        boxShadow: filters.hasMainVideo ? '0 0 8px var(--accent)' : 'none',
                        position: 'relative', flexShrink: 0,
                        transition: 'background 0.2s, box-shadow 0.2s',
                      }}
                    >
                      <span style={{
                        position: 'absolute', top: 3, left: filters.hasMainVideo ? 19 : 3,
                        width: 14, height: 14, borderRadius: '50%', background: '#fff',
                        transition: 'left 0.2s',
                        boxShadow: '0 1px 3px rgba(0,0,0,0.35)',
                      }}/>
                    </button>
                    <span style={{ fontSize: 12, color: filters.hasMainVideo ? 'var(--accent)' : 'var(--text-2)', fontWeight: filters.hasMainVideo ? 600 : 400, transition: 'color 0.2s' }}>
                      Has brand video
                    </span>
                  </div>
                </div>
                <div className="field" style={{ gridColumn: 'span 2' }}>
                  <label className="field-label">Campaign start date</label>
                  <div style={{ display: 'flex', gap: 6 }}>
                    <input type="date" className="field-input" style={{ flex: 1 }}
                      value={filters.campaignStart[0]}
                      onChange={e => setF('campaignStart', [e.target.value, filters.campaignStart[1]])} />
                    <input type="date" className="field-input" style={{ flex: 1 }}
                      value={filters.campaignStart[1]}
                      onChange={e => setF('campaignStart', [filters.campaignStart[0], e.target.value])} />
                  </div>
                </div>
                <div className="field" style={{ gridColumn: 'span 2' }}>
                  <label className="field-label">Campaign end date</label>
                  <div style={{ display: 'flex', gap: 6 }}>
                    <input type="date" className="field-input" style={{ flex: 1 }}
                      value={filters.campaignEnd[0]}
                      onChange={e => setF('campaignEnd', [e.target.value, filters.campaignEnd[1]])} />
                    <input type="date" className="field-input" style={{ flex: 1 }}
                      value={filters.campaignEnd[1]}
                      onChange={e => setF('campaignEnd', [filters.campaignEnd[0], e.target.value])} />
                  </div>
                </div>
              </FilterSection>

              <FilterSection title="Performance" open={secOpen.performance} onToggle={() => setSecOpen(o => ({ ...o, performance: !o.performance }))}>
                <Field label="Price ($)"><NumPair values={filters.price} onChange={v => setF('price', v)}/></Field>
                <Field label="Monthly sales"><NumPair values={filters.monthlySales} onChange={v => setF('monthlySales', v)}/></Field>
                <Field label="30‑day revenue ($)"><NumPair values={filters.revenue30d} onChange={v => setF('revenue30d', v)}/></Field>
                <Field label="90d BSR"><NumPair values={filters.bsr} onChange={v => setF('bsr', v)}/></Field>
                <Field label="Review count"><NumPair values={filters.reviewCount} onChange={v => setF('reviewCount', v)}/></Field>
                <div className="field" style={{ gridColumn: 'span 3' }}>
                  <label className="field-label">Rating ({filters.rating[0].toFixed(1)} – {filters.rating[1].toFixed(1)} ★)</label>
                  <RatingRange value={filters.rating} onChange={v => setF('rating', v)}/>
                </div>
              </FilterSection>

              <FilterSection title="Listing details" open={secOpen.listing} onToggle={() => setSecOpen(o => ({ ...o, listing: !o.listing }))}>
                <Field label="Category">
                  <Select value={filters.category} onChange={v => setF('category', v)}
                    options={['All categories', ...(CATEGORIES || [])]}/>
                </Field>
                <Field label="# Variations"><NumPair values={filters.variations} onChange={v => setF('variations', v)}/></Field>
                <Field label="Video count"><NumPair values={filters.videos} onChange={v => setF('videos', v)}/></Field>
                <Field label="Listing age (days)"><NumPair values={filters.listingAge} onChange={v => setF('listingAge', v)} placeholderA="Min" placeholderB="Max"/></Field>
              </FilterSection>
            </>
          )}
        </div>
        </div>{/* end non-scrolling */}

        {/* Bulk action bar — pinned above the scroll area */}
        {selected.size > 0 && (
          <div style={{ padding: '0 28px', flexShrink: 0 }}>
            <div style={{
              display: 'flex', alignItems: 'center', gap: 10,
              padding: '10px 16px', marginBottom: 10,
              background: 'var(--accent-soft)', borderRadius: 10,
              border: '1px solid var(--accent)',
            }}>
              <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--accent)' }}>
                {selected.size} selected
              </span>
              {showSelectAllBanner && (
                <button
                  className="btn btn-sm btn-primary"
                  onClick={selectAllVisible}
                  style={{ padding: '4px 12px' }}
                >
                  Select all {visibleProducts.length.toLocaleString()} in list
                </button>
              )}
              <div style={{ flex: 1 }}/>
              <span style={{ fontSize: 12, color: 'var(--text-2)' }}>Move to:</span>
              <select
                className="field-input"
                style={{ width: 'auto', padding: '5px 10px', fontSize: 12 }}
                defaultValue=""
                onChange={e => { if (e.target.value) { bulkMove(e.target.value); e.target.value = ''; } }}
              >
                <option value="" disabled>Choose list…</option>
                <option value="inbox">📥 Inbox</option>
                {leads.lists.map(l => <option key={l.id} value={l.id}>{l.name}</option>)}
              </select>
              <button className="btn btn-sm" style={{ color: 'var(--danger)' }} onClick={bulkDelete}>
                <Icons.trash size={12}/> Delete
              </button>
              <button className="btn btn-sm btn-ghost" onClick={() => setSelected(new Set())}>
                Cancel
              </button>
            </div>
          </div>
        )}

        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden', padding: '0 28px 24px' }}>

        {/* Pagination bar */}
        {visibleProducts.length > 0 && (
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
            <span style={{ fontSize: 12, color: 'var(--accent)', fontWeight: 600 }}>
              {visibleProducts.length <= PAGE_SIZE
                ? `Showing all ${visibleProducts.length.toLocaleString()} products`
                : `Showing ${((safePage - 1) * PAGE_SIZE + 1).toLocaleString()}–${Math.min(safePage * PAGE_SIZE, visibleProducts.length).toLocaleString()} of ${visibleProducts.length.toLocaleString()} products`
              }
            </span>
            {totalPages > 1 && (
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <button className="btn btn-sm btn-ghost"
                  disabled={safePage <= 1}
                  onClick={() => setPage(p => Math.max(1, p - 1))}
                >← Prev</button>
                <span style={{ fontSize: 12, color: 'var(--text-2)', fontWeight: 500 }}>
                  Page {safePage} of {totalPages}
                </span>
                <button className="btn btn-sm btn-ghost"
                  disabled={safePage >= totalPages}
                  onClick={() => setPage(p => Math.min(totalPages, p + 1))}
                >Next →</button>
              </div>
            )}
          </div>
        )}

        {/* TABLE */}
        <div className="card" style={{ flex: 1, minHeight: 0, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
          {visibleProducts.length === 0 ? (
            <div style={{ padding: '60px 20px', textAlign: 'center' }}>
              <div style={{ width: 56, height: 56, margin: '0 auto', borderRadius: 14, background: 'var(--accent-soft)', display: 'grid', placeItems: 'center', color: 'var(--accent)' }}>
                <Icons.bookmark size={24}/>
              </div>
              <div style={{ marginTop: 16, fontWeight: 600, fontSize: 15 }}>No leads here yet</div>
              <div style={{ color: 'var(--text-2)', fontSize: 13, marginTop: 4 }}>
                Use the Search page or the Chrome extension to add products.
              </div>
            </div>
          ) : (
          <div style={{ flex: 1, overflow: 'auto', minHeight: 0 }}>
          {/* Stat strip — scrolls away, above the sticky headers */}
          {stats && (() => {
            const canConfigure = !!(activeList && activeListId !== 'all' && activeListId !== 'inbox');
            const activeStatKeys = activeList?.statKeys || DEFAULT_STAT_KEYS;

            const getStatDisplay = (key) => {
              switch (key) {
                case 'count':           return { label: 'Leads in list',      value: String(stats.count),                                   sub: '+' + Math.min(stats.count, 4) + ' this week', subColor: 'var(--success)', glow: true };
                case 'avgMonthlySales': return { label: 'Avg Monthly Sales',  value: fmtInt(stats.avgMonthlySales),                         sub: 'units / month',              subColor: 'var(--text-2)' };
                case 'avgCcCommission': return { label: 'Avg CC Commission',  value: fmtUSD(stats.avgCcCommission),                         sub: 'per qualifying sale',        subColor: 'var(--accent)' };
                case 'avgRev':          return { label: 'Avg 30d Revenue',    value: fmtUSD(stats.avgRev),                                  sub: 'per listing · 30 days',      subColor: 'var(--success)' };
                case 'totalCost':       return { label: 'Total Cost',         value: fmtUSD(stats.totalCost),                               sub: 'if buying 1 of each lead',   subColor: 'var(--text-2)' };
                case 'breakEven':       return { label: 'Avg Break Even',     value: stats.breakEven ? stats.breakEven + ' sales' : '—',    sub: 'CC sales to recoup cost',    subColor: 'var(--text-2)' };
                case 'avgCcRate':       return { label: 'Avg CC Rate',        value: stats.avgCcRate ? stats.avgCcRate + '%' : '—',         sub: 'across CC products',         subColor: 'var(--text-2)' };
                case 'ccCount':         return { label: 'CC Products',        value: String(stats.ccCount),                                  sub: 'with active CC campaign',    subColor: 'var(--text-2)' };
                default: return null;
              }
            };

            const toggleStatKey = (key) => {
              if (!canConfigure) return;
              if (activeStatKeys.includes(key)) {
                if (activeStatKeys.length <= 1) return;
                setListStatKeys(activeListId, activeStatKeys.filter(k => k !== key));
              } else {
                const next = activeStatKeys.length >= 4
                  ? [...activeStatKeys.slice(1), key]
                  : [...activeStatKeys, key];
                setListStatKeys(activeListId, next);
              }
            };

            return (
              <div style={{ borderBottom: '1px solid var(--line)' }}>
                {/* Cards + customize button */}
                <div style={{ display: 'flex', alignItems: 'center', padding: '16px 18px 12px', gap: 10 }}>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, flex: 1 }}>
                    {activeStatKeys.map(key => {
                      const card = getStatDisplay(key);
                      if (!card) return null;
                      return (
                        <div key={key} className={card.glow ? 'stat-card glow' : 'stat-card'}>
                          <div className="stat-label">{card.label}</div>
                          <div className="stat-value">{card.value}</div>
                          <div className="stat-delta" style={{ color: card.subColor }}>{card.sub}</div>
                        </div>
                      );
                    })}
                  </div>
                  {canConfigure && (
                    <button
                      onClick={() => setShowStatPicker(v => !v)}
                      title="Customize stats"
                      style={{
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                        width: 28, height: 28, flexShrink: 0,
                        border: '1px solid var(--line)', borderRadius: 6, cursor: 'pointer',
                        background: showStatPicker ? 'rgba(99,102,241,0.12)' : 'transparent',
                        color: showStatPicker ? 'var(--accent)' : 'var(--text-3)',
                        transition: 'all 0.12s',
                      }}
                      onMouseEnter={e => { e.currentTarget.style.color = 'var(--accent)'; e.currentTarget.style.borderColor = 'var(--accent)40'; }}
                      onMouseLeave={e => { e.currentTarget.style.color = showStatPicker ? 'var(--accent)' : 'var(--text-3)'; e.currentTarget.style.borderColor = 'var(--line)'; }}
                    >
                      <Icons.edit size={11}/>
                    </button>
                  )}
                </div>

                {/* Picker panel — sits between stat strip and table, no absolute positioning */}
                {showStatPicker && canConfigure && (
                  <div style={{ padding: '10px 18px 14px', borderTop: '1px solid var(--line)', background: 'var(--bg-2)' }}>
                    <div style={{ fontSize: 10, fontWeight: 600, color: 'var(--text-3)', letterSpacing: '0.06em', marginBottom: 8 }}>
                      CUSTOMIZE STATS — select up to 4 ({activeStatKeys.length}/4)
                    </div>
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                      {LEADS_STAT_OPTIONS.map(o => {
                        const isSelected = activeStatKeys.includes(o.key);
                        const pos = activeStatKeys.indexOf(o.key) + 1;
                        return (
                          <button
                            key={o.key}
                            onClick={() => toggleStatKey(o.key)}
                            style={{
                              display: 'flex', alignItems: 'center', gap: 7,
                              padding: '5px 11px 5px 7px', borderRadius: 6, cursor: 'pointer',
                              border: isSelected ? '1px solid var(--accent)' : '1px solid var(--line)',
                              background: isSelected ? 'rgba(99,102,241,0.12)' : 'transparent',
                              color: isSelected ? 'var(--accent)' : 'var(--text-2)',
                              fontSize: 12, fontWeight: isSelected ? 600 : 400,
                              transition: 'all 0.12s',
                            }}
                          >
                            {isSelected
                              ? <span style={{ width: 16, height: 16, borderRadius: 4, background: 'var(--accent)', color: '#fff', fontSize: 9, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{pos}</span>
                              : <span style={{ width: 16, height: 16, borderRadius: 4, border: '1px solid var(--line-strong)', flexShrink: 0 }}/>
                            }
                            {o.label}
                          </button>
                        );
                      })}
                    </div>
                    <div style={{ fontSize: 11, color: 'var(--text-3)', marginTop: 8 }}>
                      Numbers show display order · click to add or remove · max 4
                    </div>
                  </div>
                )}
              </div>
            );
          })()}
          <table className="data-table">
            <thead>
              <tr>
                <th style={{ width: 58 }}><Checkbox checked={allPageSelected} indeterminate={somePageSelected && !allPageSelected} onChange={toggleSelectPage}/></th>
                {visibleCols.map(key => {
                  const std = COLUMN_BY_KEY[key];
                  const cust = !std && customCols.find(c => c.key === key);
                  if (!std && !cust) return null;
                  const num    = std?.num;
                  const center = std?.center;
                  const isSorted = sortKey === key;
                  const sortable = !cust;
                  return (
                    <th key={key}
                      style={{ textAlign: num ? 'right' : center ? 'center' : 'left', cursor: sortable ? 'pointer' : 'default', userSelect: 'none', whiteSpace: 'nowrap' }}
                      onClick={sortable ? () => handleSort(key) : undefined}
                    >
                      {cust && <Icons.edit size={10} style={{ marginRight: 5, color: 'var(--accent)', verticalAlign: 'middle' }}/>}
                      {std?.label || cust?.label}
                      {isSorted && (
                        <span style={{ marginLeft: 4, color: 'var(--accent)', fontSize: 10 }}>
                          {sortDir === 'asc' ? '↑' : '↓'}
                        </span>
                      )}
                    </th>
                  );
                })}
                <th style={{ width: 50, textAlign: 'right' }}>Link</th>
              </tr>
            </thead>
            <tbody>
              {pagedProducts.map((p, i) => (
                <tr key={p.id}>
                  <td>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
                      <Checkbox checked={selected.has(p.id)} onChange={() => toggleSelect(p.id)}/>
                      {/* Vertical icon stack */}
                      <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
                        {/* Trash — two-step confirm */}
                        {(() => {
                          const confirming = confirmDeleteId === p.id;
                          return (
                            <button
                              title={confirming ? 'Click to confirm delete' : 'Remove'}
                              onClick={e => {
                                e.stopPropagation();
                                if (confirming) {
                                  removeFromLeads(p.id, activeListId);
                                  setConfirmDeleteId(null);
                                } else {
                                  setConfirmDeleteId(p.id);
                                }
                              }}
                              style={{
                                display: 'flex', alignItems: 'center', justifyContent: 'center',
                                width: 16, height: 16, flexShrink: 0,
                                border: 'none', background: 'transparent', padding: 0,
                                color: confirming ? 'var(--danger)' : 'rgba(255,255,255,0.2)',
                                cursor: 'pointer', transition: 'color 0.15s',
                              }}
                              onMouseEnter={e => { if (!confirming) e.currentTarget.style.color = 'var(--danger)'; }}
                              onMouseLeave={e => { if (!confirming) e.currentTarget.style.color = 'rgba(255,255,255,0.2)'; }}
                            >
                              {confirming ? <Icons.close size={11}/> : <Icons.trash size={11}/>}
                            </button>
                          );
                        })()}
                        {/* Folder — move to default list */}
                        {(() => {
                          const justMoved = movedId === p.id;
                          const active = !!defaultListId;
                          return (
                            <button
                              title={active ? `Move to ${defaultList?.name}` : 'Set a default list first'}
                              onClick={() => active && moveToDefault(p.id)}
                              style={{
                                display: 'flex', alignItems: 'center', justifyContent: 'center',
                                width: 16, height: 16, flexShrink: 0,
                                border: 'none', background: 'transparent', padding: 0,
                                color: justMoved
                                  ? defaultList.color
                                  : active ? defaultList.color : 'rgba(255,255,255,0.2)',
                                cursor: active ? 'pointer' : 'default',
                                transition: 'color 0.2s',
                                filter: justMoved ? `drop-shadow(0 0 4px ${defaultList.color})` : 'none',
                              }}
                            >
                              {justMoved ? <Icons.check size={12}/> : <Icons.folder size={12}/>}
                            </button>
                          );
                        })()}
                        {/* Move — add to default list and remove from current */}
                        {(() => {
                          const justMoved = movedId === p.id;
                          const active = !!defaultListId;
                          const isAllLeads = activeListId === 'all';
                          const isSameList = activeListId === defaultListId;
                          const title = !active
                            ? 'Set a default list first'
                            : isAllLeads || isSameList
                              ? `Save to ${defaultList?.name}`
                              : `Move to ${defaultList?.name} (removes from this list)`;
                          return (
                            <button
                              title={title}
                              onClick={() => active && moveAndRemove(p.id)}
                              style={{
                                display: 'flex', alignItems: 'center', justifyContent: 'center',
                                width: 16, height: 16, flexShrink: 0,
                                border: 'none', background: 'transparent', padding: 0,
                                color: justMoved
                                  ? defaultList?.color
                                  : active ? defaultList?.color : 'rgba(255,255,255,0.2)',
                                cursor: active ? 'pointer' : 'default',
                                transition: 'color 0.2s',
                                filter: justMoved ? `drop-shadow(0 0 4px ${defaultList?.color})` : 'none',
                              }}
                            >
                              {justMoved ? <Icons.check size={12}/> : <Icons.arrow size={12}/>}
                            </button>
                          );
                        })()}
                        {/* Copy row to clipboard */}
                        {(() => {
                          const justCopied = copiedId === p.id;
                          return (
                            <button
                              title="Copy row to clipboard"
                              onClick={() => copyRow(p)}
                              style={{
                                display: 'flex', alignItems: 'center', justifyContent: 'center',
                                width: 16, height: 16, flexShrink: 0,
                                border: 'none', background: 'transparent', padding: 0,
                                color: justCopied ? 'var(--success)' : 'rgba(255,255,255,0.2)',
                                cursor: 'pointer', transition: 'color 0.2s',
                              }}
                              onMouseEnter={e => { if (copiedId !== p.id) e.currentTarget.style.color = 'var(--accent)'; }}
                              onMouseLeave={e => { if (copiedId !== p.id) e.currentTarget.style.color = 'rgba(255,255,255,0.2)'; }}
                            >
                              {justCopied ? <Icons.check size={11}/> : <Icons.copy size={11}/>}
                            </button>
                          );
                        })()}
                      </div>
                    </div>
                  </td>
                  {visibleCols.map(key => {
                    if (isCustomKey(key)) {
                      const val = notes[p.id]?.[key] || '';
                      return (
                        <td key={key} style={{ whiteSpace: 'normal' }}>
                          <textarea
                            placeholder="Add note…"
                            value={val}
                            rows={1}
                            title={val || undefined}
                            ref={(el) => {
                              if (el) { el.style.height = 'auto'; el.style.height = Math.min(el.scrollHeight, 68) + 'px'; if (document.activeElement !== el) el.scrollTop = 0; }
                            }}
                            onChange={(e) => {
                              updateNote(p.id, key, e.target.value);
                              e.target.style.height = 'auto';
                              e.target.style.height = Math.min(e.target.scrollHeight, 68) + 'px';
                            }}
                            onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); e.target.blur(); } }}
                            style={{
                              width: 140, padding: '5px 8px',
                              background: 'transparent',
                              border: '1px dashed transparent',
                              borderRadius: 6, color: 'var(--text-0)',
                              font: 'inherit', outline: 'none',
                              resize: 'none', overflow: 'hidden',
                              lineHeight: '1.5', display: 'block',
                              transition: 'border-color 0.15s',
                            }}
                            onFocus={(e) => e.target.style.borderColor = 'var(--accent-soft)'}
                            onBlur={(e) => { e.target.style.borderColor = 'transparent'; e.target.scrollTop = 0; }}
                            onMouseEnter={(e) => { if (!val) e.target.style.borderColor = 'var(--line)'; }}
                            onMouseLeave={(e) => { if (document.activeElement !== e.target) e.target.style.borderColor = 'transparent'; }}
                          />
                        </td>
                      );
                    }
                    const c = COLUMN_BY_KEY[key]; if (!c) return null;
                    return (
                      <td key={key} style={{ textAlign: c.num ? 'right' : c.center ? 'center' : 'left' }}>
                        {renderCellValue(key, p, i, fmtUSD, fmtInt, fmtBSR)}
                      </td>
                    );
                  })}
                  <td>
                    <div style={{ display: 'flex', gap: 4, justifyContent: 'flex-end' }}>
                      <button className="icon-btn" style={{ width: 28, height: 28 }} title="View on Amazon" onClick={() => window.open(`https://www.amazon.com/dp/${p.asin}`, '_blank', 'noopener,noreferrer')}><Icons.ext size={12}/></button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          </div>
          )}
        </div>
        </div>{/* end scrolling */}
      </div>{/* end MAIN CONTENT */}

      {showColumnsDrawer && (
        <ManageColumnsDrawer
          order={order} setOrder={setOrder}
          hidden={hidden} setHidden={setHidden}
          customCols={customCols} setCustomCols={setCustomCols}
          defaultOrder={LEADS_DEFAULT_ORDER}
          onClose={() => setShowColumnsDrawer(false)}
        />
      )}
    </div>
  );
};

window.LeadsPage = LeadsPage;
