/**
 * Acme Grocer — Delectable AI Data Insights Dashboard
 *
 * Interactive visualization of the Delectable AI grocery agent platform,
 * showing data pipeline, shopper intelligence, agent analytics,
 * vector search, food intelligence, and agent context.
 */

const { useState, useEffect, useMemo } = React;

// ─── Inline SVG Icons ──────────────────────────────────────────────────────────

const DatabaseIcon = () => (
  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <ellipse cx="12" cy="5" rx="9" ry="3" strokeWidth={2}/>
    <path d="M21 12c0 1.66-4 3-9 3s-9-1.34-9-3" strokeWidth={2}/>
    <path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5" strokeWidth={2}/>
  </svg>
);

const UsersIcon = () => (
  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z" />
  </svg>
);

const CartIcon = () => (
  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z" />
  </svg>
);

const ActivityIcon = () => (
  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <polyline points="22 12 18 12 15 21 9 3 6 12 2 12" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round"/>
  </svg>
);

const SearchIcon = () => (
  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <circle cx="11" cy="11" r="8" strokeWidth={2}/>
    <line x1="21" y1="21" x2="16.65" y2="16.65" strokeWidth={2}/>
  </svg>
);

const NetworkIcon = () => (
  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <circle cx="12" cy="12" r="3" strokeWidth={2}/>
    <circle cx="4" cy="6" r="2" strokeWidth={2}/>
    <circle cx="20" cy="6" r="2" strokeWidth={2}/>
    <circle cx="4" cy="18" r="2" strokeWidth={2}/>
    <circle cx="20" cy="18" r="2" strokeWidth={2}/>
    <line x1="9.5" y1="10" x2="6" y2="7.5" strokeWidth={2}/>
    <line x1="14.5" y1="10" x2="18" y2="7.5" strokeWidth={2}/>
    <line x1="9.5" y1="14" x2="6" y2="16.5" strokeWidth={2}/>
    <line x1="14.5" y1="14" x2="18" y2="16.5" strokeWidth={2}/>
  </svg>
);

const BotIcon = () => (
  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <rect x="3" y="11" width="18" height="10" rx="2" strokeWidth={2}/>
    <circle cx="12" cy="5" r="2" strokeWidth={2}/>
    <path d="M12 7v4" strokeWidth={2}/>
    <circle cx="8" cy="16" r="1" fill="currentColor"/>
    <circle cx="16" cy="16" r="1" fill="currentColor"/>
  </svg>
);

const SparklesIcon = () => (
  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 3v4M3 5h4M6 17v4m-2-2h4m5-16l2.286 6.857L21 12l-5.714 2.143L13 21l-2.286-6.857L5 12l5.714-2.143L13 3z" />
  </svg>
);

const BrainIcon = () => (
  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
  </svg>
);

const ChartBarIcon = () => (
  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
  </svg>
);

const CodeIcon = () => (
  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4" />
  </svg>
);

const ArrowRightIcon = () => (
  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M14 5l7 7m0 0l-7 7m7-7H3" />
  </svg>
);

const CheckIcon = () => (
  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
  </svg>
);

const AlertIcon = () => (
  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
  </svg>
);

const CubeIcon = () => (
  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
  </svg>
);

const LayersIcon = () => (
  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 2L2 7l10 5 10-5-10-5z" />
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2 17l10 5 10-5" />
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2 12l10 5 10-5" />
  </svg>
);

const UserCircleIcon = () => (
  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5.121 17.804A13.937 13.937 0 0112 16c2.5 0 4.847.655 6.879 1.804M15 10a3 3 0 11-6 0 3 3 0 016 0zm6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
  </svg>
);

const GraphIcon = () => (
  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <circle cx="6" cy="6" r="2.5" strokeWidth={2}/>
    <circle cx="18" cy="6" r="2.5" strokeWidth={2}/>
    <circle cx="12" cy="18" r="2.5" strokeWidth={2}/>
    <circle cx="18" cy="18" r="2.5" strokeWidth={2}/>
    <circle cx="6" cy="18" r="2.5" strokeWidth={2}/>
    <line x1="8" y1="7" x2="16" y2="7" strokeWidth={1.5}/>
    <line x1="7" y1="8" x2="11" y2="16" strokeWidth={1.5}/>
    <line x1="17" y1="8" x2="13" y2="16" strokeWidth={1.5}/>
    <line x1="14.5" y1="18" x2="16" y2="18" strokeWidth={1.5}/>
    <line x1="8.5" y1="18" x2="10" y2="18" strokeWidth={1.5}/>
  </svg>
);

// ─── Shared Helper Components ───────────────────────────────────────────────────

const AnimatedCounter = ({ value, suffix = '', prefix = '' }) => {
  const [displayed, setDisplayed] = useState(0);

  useEffect(() => {
    const duration = 1500;
    const steps = 60;
    const increment = value / steps;
    let current = 0;

    const timer = setInterval(() => {
      current += increment;
      if (current >= value) {
        setDisplayed(value);
        clearInterval(timer);
      } else {
        setDisplayed(Math.floor(current));
      }
    }, duration / steps);

    return () => clearInterval(timer);
  }, [value]);

  return <span>{prefix}{displayed.toLocaleString()}{suffix}</span>;
};

const ProgressBar = ({ value, max, color = '#3b82f6', height = 'h-2.5' }) => (
  <div className={`w-full bg-gray-700 rounded-full ${height} overflow-hidden`}>
    <div
      className="h-full rounded-full transition-all duration-1000 ease-out"
      style={{
        width: `${Math.min((value / max) * 100, 100)}%`,
        backgroundColor: color,
      }}
    />
  </div>
);

// ─── Data ───────────────────────────────────────────────────────────────────────

const EAGLE_DATA = {
  overview: {
    productsInCatalog: 70000,
    propensityProfiles: 135000,
    virtualPantryEstimates: 89000,
    agentConversations30d: 12400,
    shoppingListsOptimized: 3200,
    personalizationRate: 94,
  },
  missionClusters: [
    { name: 'Weekly Stock-Up', count: 38200, pct: 28.3, color: '#3b82f6', desc: 'Routine weekly grocery trips' },
    { name: 'Quick Meal', count: 29700, pct: 22.0, color: '#10b981', desc: 'Fast dinner/lunch solutions' },
    { name: 'Health Focus', count: 24300, pct: 18.0, color: '#8b5cf6', desc: 'Organic, clean-label priorities' },
    { name: 'Budget Batch', count: 20250, pct: 15.0, color: '#f59e0b', desc: 'Value-driven bulk buying' },
    { name: 'Special Occasion', count: 13500, pct: 10.0, color: '#ef4444', desc: 'Holiday, party, celebration' },
    { name: 'Exploration', count: 9050, pct: 6.7, color: '#ec4899', desc: 'New brands, cuisines, trends' },
  ],
  pipeline: {
    tables: [
      { name: 'shopper_profiles', rows: '135K', desc: 'Demographics, loyalty, segments', icon: 'users' },
      { name: 'product_catalog', rows: '70K', desc: 'Products, nutrition, pricing', icon: 'db' },
      { name: 'purchase_history', rows: '48M', desc: '2 years of transactions', icon: 'cart' },
      { name: 'product_embeddings', rows: '70K', desc: '768-dim multi-aspect vectors', icon: 'cube' },
    ],
    connections: [
      { source: 'Shoppers', target: 'Purchase History', joinKey: 'loyal_card_no', strength: 95 },
      { source: 'Purchase History', target: 'Products', joinKey: 'UPC', strength: 98 },
      { source: 'Products', target: 'Embeddings', joinKey: 'product_id', strength: 100 },
      { source: 'Embeddings', target: 'Agent', joinKey: 'VECTOR_SEARCH', strength: 92 },
      { source: 'Shoppers', target: 'Agent', joinKey: 'shopper_id', strength: 88 },
    ],
  },
  shopper: {
    id: '40001000512',
    missionCluster: 'Health Focus',
    clusterNumber: 3,
    loyaltyTier: 'MyPerks Gold',
    dietaryScores: [
      { label: 'organic', score: 0.91 },
      { label: 'high_protein', score: 0.89 },
      { label: 'low_sodium', score: 0.82 },
      { label: 'gluten_free', score: 0.78 },
      { label: 'high_fiber', score: 0.76 },
      { label: 'low_sugar', score: 0.71 },
      { label: 'dairy_free', score: 0.65 },
      { label: 'vegetarian', score: 0.34 },
      { label: 'nut_free', score: 0.15 },
      { label: 'vegan', score: 0.12 },
      { label: 'keto', score: 0.08 },
    ],
    pantry: [
      { name: 'Almond Milk', stock: 0.72 },
      { name: 'Olive Oil', stock: 0.65 },
      { name: 'Brown Rice', stock: 0.45 },
      { name: 'Chicken Breast', stock: 0.12 },
      { name: 'Greek Yogurt', stock: 0.08 },
    ],
  },
  agentAnalytics: {
    searches: 48200,
    selections: 31400,
    addToCartRate: 67,
    conversations: 12400,
    avgTurns: 4.2,
    avgToolCalls: 6.8,
    personalizationRate: 94,
    toolBreakdown: [
      { tool: 'search_products', pct: 42, calls: 20244, color: '#3b82f6' },
      { tool: 'get_shopper_profile', pct: 18, calls: 8676, color: '#10b981' },
      { tool: 'get_dietary_propensities', pct: 15, calls: 7230, color: '#8b5cf6' },
      { tool: 'get_virtual_pantry', pct: 12, calls: 5784, color: '#f59e0b' },
      { tool: 'optimize_shopping_list', pct: 8, calls: 3856, color: '#ef4444' },
      { tool: 'get_promos', pct: 5, calls: 2410, color: '#ec4899' },
    ],
  },
  vectorSearch: {
    embeddingTypes: [
      {
        name: 'Identity Embedding',
        dim: 768,
        fields: 'Product name, brand, category',
        purpose: 'Identity matching — find the exact product or close equivalents',
        color: 'from-blue-600 to-blue-500',
        borderColor: 'border-blue-500/40',
      },
      {
        name: 'Nutrition Embedding',
        dim: 768,
        fields: 'Macros, vitamins, health scores',
        purpose: 'Nutritional similarity — find products with similar health profiles',
        color: 'from-emerald-600 to-emerald-500',
        borderColor: 'border-emerald-500/40',
      },
      {
        name: 'Description Embedding',
        dim: 768,
        fields: 'Description, ingredients, use cases',
        purpose: 'Semantic understanding — natural language intent matching',
        color: 'from-purple-600 to-purple-500',
        borderColor: 'border-purple-500/40',
      },
    ],
    exampleQueries: [
      {
        query: 'healthy high-protein snack',
        primary: 'Nutrition',
        results: [
          { name: 'Chobani Greek Yogurt', identity: 0.72, nutrition: 0.94, description: 0.81 },
          { name: 'KIND Protein Bar', identity: 0.68, nutrition: 0.91, description: 0.85 },
          { name: 'Roasted Almonds', identity: 0.61, nutrition: 0.88, description: 0.76 },
        ],
      },
      {
        query: 'something like Greek yogurt but dairy-free',
        primary: 'Description',
        results: [
          { name: 'Kite Hill Almond Yogurt', identity: 0.58, nutrition: 0.82, description: 0.95 },
          { name: 'So Delicious Coconut Yogurt', identity: 0.54, nutrition: 0.79, description: 0.92 },
          { name: 'Silk Soy Yogurt', identity: 0.51, nutrition: 0.81, description: 0.89 },
        ],
      },
      {
        query: 'organic chicken breast',
        primary: 'Identity',
        results: [
          { name: 'Harvest Organic Chicken Breast', identity: 0.97, nutrition: 0.85, description: 0.78 },
          { name: 'Bell & Evans Organic Breast', identity: 0.94, nutrition: 0.83, description: 0.75 },
          { name: 'Perdue Harvestland Organic', identity: 0.91, nutrition: 0.82, description: 0.73 },
        ],
      },
    ],
  },
  semanticSearchDemo: [
    { query: 'healthy high-protein snack', keywords: ['protein', 'snack', 'healthy', 'high-protein'], results: ['Chobani Greek Yogurt', 'KIND Protein Bar', 'Roasted Almonds', 'Cottage Cheese Cups'] },
    { query: 'something like Greek yogurt but dairy-free', keywords: ['yogurt', 'dairy-free', 'dairy free', 'greek'], results: ['Kite Hill Almond Yogurt', 'So Delicious Coconut Yogurt', 'Silk Soy Yogurt'] },
    { query: 'organic chicken breast', keywords: ['chicken', 'breast', 'poultry', 'marinated'], results: ['Harvest Organic Chicken Breast', 'Bell & Evans Organic Breast', 'Perdue Harvestland Organic Chicken'] },
    { query: 'pasta dinner ingredients', keywords: ['pasta', 'spaghetti', 'penne', 'noodle', 'marinara'], results: ['Barilla GF Penne', "Rao's Marinara Sauce", 'Fresh Basil Bundle', 'Parmigiano Reggiano'] },
    { query: 'fresh vegetables for salad', keywords: ['salad', 'vegetable', 'lettuce', 'greens', 'fresh'], results: ['Organic Spring Mix', 'Cherry Tomatoes', 'English Cucumber', 'Avocado'] },
    { query: 'gluten free bread', keywords: ['gluten', 'bread', 'gf', 'celiac'], results: ['Canyon Bakehouse GF Bread', "Schar Multigrain Bread", "Udi's Whole Grain Bread"] },
    { query: 'baby food organic', keywords: ['baby', 'infant', 'toddler', 'puree'], results: ['Happy Baby Organics Puffs', "Earth's Best Puree Pouch", 'Gerber Organic Banana'] },
    { query: 'cleaning supplies', keywords: ['cleaning', 'cleaner', 'disinfect', 'wipes', 'spray'], results: ['Clorox Disinfecting Wipes', 'Method All-Purpose Cleaner', 'Seventh Generation Spray'] },
  ],

  // ─── Catalog Enrichment Data ──────────────────────────────────────────────────
  catalogEnrichment: {
    enrichmentLayers: [
      { layer: 1, name: 'Raw Catalog Data', count: 70000, color: '#64748b', desc: "Acme Grocer's original product catalog" },
      { layer: 2, name: 'Nutritional Intelligence', count: 63700, color: '#3b82f6', desc: 'USDA & Open Food Facts matching' },
      { layer: 3, name: 'Health Scoring', count: 42000, color: '#10b981', desc: 'Food Compass, Nutri-Score, NOVA' },
      { layer: 4, name: 'Ingredient Analysis', count: 58100, color: '#8b5cf6', desc: 'Allergens, dietary flags, materials' },
      { layer: 5, name: 'Semantic Embeddings', count: 70000, color: '#f59e0b', desc: 'Identity, nutrition, description vectors' },
      { layer: 6, name: 'Propensity Features', count: 63700, color: '#ef4444', desc: 'Features extracted for propensity models' },
    ],
    catalogBreakdown: [
      {
        tier: 'Food & Grocery',
        pct: 55,
        count: 38500,
        color: '#10b981',
        enrichments: ['Full Nutrition Facts', 'Health Scores', 'Dietary Flags', 'Allergens', 'Ingredient Parsing', 'Flavor Profile'],
        examples: [
          { name: 'Organic Chicken Breast', brand: 'Harvest Nature', dataPoints: 42, note: 'Full nutrition + health score + allergen flags' },
          { name: 'Chobani Greek Yogurt', brand: 'Chobani', dataPoints: 38, note: 'Probiotics, protein profile, Nutri-Score A' },
          { name: 'Barilla GF Penne', brand: 'Barilla', dataPoints: 35, note: 'Gluten-free flag, NOVA Group 3, ingredient parse' },
        ],
      },
      {
        tier: 'Health & Wellness',
        pct: 25,
        count: 17500,
        color: '#8b5cf6',
        enrichments: ['Supplement Facts', 'Active Ingredients', 'Dosage Info', 'Material Composition', 'Nutritional Content'],
        examples: [
          { name: 'Nature Made Vitamin D3', brand: 'Nature Made', dataPoints: 28, note: 'Active ingredient, dosage, supplement facts panel' },
          { name: 'Optimum Nutrition Whey', brand: 'ON', dataPoints: 31, note: 'Protein per serving, amino acid profile, allergens' },
          { name: 'Garden of Life Probiotics', brand: 'Garden of Life', dataPoints: 26, note: 'CFU count, strain info, storage requirements' },
        ],
      },
      {
        tier: 'Non-Food & Household',
        pct: 20,
        count: 14000,
        color: '#f59e0b',
        enrichments: ['Material Composition', 'Use-Case Categories', 'Chemical Ingredients', 'Safety Data', 'Beauty Ingredients'],
        examples: [
          { name: 'OPI Nail Lacquer', brand: 'OPI', dataPoints: 15, note: 'Chemical ingredients, material safety, color profile' },
          { name: 'Clorox Disinfecting Wipes', brand: 'Clorox', dataPoints: 20, note: 'Active chemicals, surface compatibility, safety warnings' },
          { name: 'KitchenAid Spatula Set', brand: 'KitchenAid', dataPoints: 12, note: 'Material (silicone/nylon), heat rating, use-case tags' },
        ],
      },
    ],
    coverageImpact: {
      enrichedPct: 91,
      enrichedCount: 63700,
      avgNewDataPoints: 34,
      untouchedCount: 6300,
      untouchedPct: 9,
      untouchedReasons: [
        { reason: 'Discontinued / seasonal items', count: 2100 },
        { reason: 'Insufficient source data', count: 1400 },
        { reason: 'No GTIN / UPC match', count: 1640 },
        { reason: 'Already fully enriched', count: 820 },
      ],
      beforeAfter: {
        before: { avgFields: 8, totalDataPoints: 560000 },
        after: { avgFields: 42, totalDataPoints: 2940000 },
      },
    },
    valueDrivers: [
      { name: 'Personalization', desc: 'Honor dietary restrictions & match preferences across 11 dimensions. Shoppers get recommendations that respect their health needs — something impossible without enriched ingredient and allergen data.', color: '#3b82f6', metric: '94% personalization rate' },
      { name: 'Propensity Features', desc: 'Enriched nutrition, ingredient, and health attributes become input features for granular propensity scoring. Each enrichment layer adds signal that improves model accuracy by 12-18%.', color: '#10b981', metric: '+15% model lift' },
      { name: 'Targeted Advertising', desc: 'Deep product understanding enables precise audience-product matching. Advertisers can target "high-protein seekers" or "organic families" — segments only possible with enriched data.', color: '#8b5cf6', metric: '3.2x ROAS improvement' },
      { name: 'UGC & Content Matching', desc: 'Rich metadata enables automatic recipe-to-product linking, review sentiment alignment, and user-generated content matching to relevant products.', color: '#f59e0b', metric: '67% content match rate' },
      { name: 'Recommender Systems', desc: 'Nutrition embeddings power "similar but healthier" recommendations. Material data enables "compatible accessories" for non-food. Multi-aspect vectors outperform keyword matching.', color: '#ef4444', metric: '+28% click-through' },
      { name: 'LLM Cost Efficiency', desc: 'Pre-computed enrichments reduce per-query LLM token usage by ~40%. The agent retrieves structured data instead of reasoning about raw product descriptions every time.', color: '#ec4899', metric: '~40% token reduction' },
    ],
    unenrichedProducts: {
      reasons: [
        { code: 'no_gtin', label: 'No GTIN / UPC Match', count: 1640, color: '#ef4444', desc: 'Product has no valid GTIN-14 / UPC barcode or the code doesn\'t match any external database (USDA, Open Food Facts, Nutritionix). Common for store-prepared items and local brands.' },
        { code: 'discontinued', label: 'Discontinued / Seasonal', count: 2100, color: '#f59e0b', desc: 'Product has been delisted or is a seasonal SKU no longer in active inventory. Enrichment is deprioritized since the item won\'t appear in search results.' },
        { code: 'already_complete', label: 'Already Fully Enriched', count: 820, color: '#10b981', desc: 'Product already had complete data from Acme Grocer\'s own feed — all nutrition, ingredients, allergens, and health fields were populated. No additional enrichment needed.' },
        { code: 'no_source_data', label: 'Insufficient Source Data', count: 1400, color: '#3b82f6', desc: 'GTIN exists and was matched, but external sources (USDA, Open Food Facts, Nutritionix) returned incomplete or conflicting data that didn\'t meet our confidence threshold. Often newer brands, niche imports, or recently reformulated products.' },
        { code: 'not_applicable', label: 'Not Applicable to Enrich', count: 340, color: '#8b5cf6', desc: 'Gift cards, store services, lottery tickets, bag fees, and other non-physical items that have no meaningful attributes to enrich.' },
      ],
      items: [
        // No GTIN match
        { name: 'Harvest Deli Fresh Rotisserie Chicken', brand: 'Acme Grocer', category: 'Deli / Prepared', reason: 'no_gtin', gtin: 'N/A (store-prepared)', existingFields: 3 },
        { name: 'Gourmet Market Artisan Sourdough', brand: 'Gourmet Market', category: 'Bakery', reason: 'no_gtin', gtin: 'N/A (in-store bakery)', existingFields: 4 },
        { name: 'Harvest Fresh Sushi Combo Platter', brand: 'Acme Grocer', category: 'Deli / Prepared', reason: 'no_gtin', gtin: 'N/A (store-prepared)', existingFields: 2 },
        { name: 'Levin Farms Local Honey 16oz', brand: 'Levin Farms', category: 'Pantry / Condiments', reason: 'no_gtin', gtin: '00000000000000', existingFields: 5 },
        { name: 'Gourmet Market Smoked Salmon', brand: 'Gourmet Market', category: 'Seafood', reason: 'no_gtin', gtin: 'N/A (store-prepared)', existingFields: 3 },
        { name: 'Harvest Custom Cake (Full Sheet)', brand: 'Acme Grocer', category: 'Bakery', reason: 'no_gtin', gtin: 'N/A (made to order)', existingFields: 2 },
        { name: 'Bistro to Go Chicken Caesar Wrap', brand: 'Acme Grocer', category: 'Deli / Prepared', reason: 'no_gtin', gtin: 'N/A (store-prepared)', existingFields: 3 },
        { name: 'Hometown Pickle Co. Dills', brand: 'Hometown Pickle Co.', category: 'Pantry / Condiments', reason: 'no_gtin', gtin: '85234100102', existingFields: 4 },
        // Discontinued
        { name: 'Haagen-Dazs Rum Raisin Pint', brand: 'Haagen-Dazs', category: 'Frozen / Ice Cream', reason: 'discontinued', gtin: '07456702104', existingFields: 12 },
        { name: 'Chobani Flip S\'mores Limited', brand: 'Chobani', category: 'Dairy / Yogurt', reason: 'discontinued', gtin: '81877602284', existingFields: 14 },
        { name: 'Blue Bell Bride\'s Cake Ice Cream', brand: 'Blue Bell', category: 'Frozen / Ice Cream', reason: 'discontinued', gtin: '07130001027', existingFields: 10 },
        { name: 'Kraft Velveeta Jalapeno Loaf 2lb', brand: 'Kraft', category: 'Dairy / Cheese', reason: 'discontinued', gtin: '02100006143', existingFields: 11 },
        { name: 'Nature Valley Protein Coconut Almond', brand: 'Nature Valley', category: 'Snacks / Bars', reason: 'discontinued', gtin: '01600047693', existingFields: 15 },
        { name: 'Pumpkin Spice Cheerios (Seasonal)', brand: 'General Mills', category: 'Breakfast / Cereal', reason: 'discontinued', gtin: '01600051545', existingFields: 14 },
        { name: 'Harvest Holiday Cookie Kit 2023', brand: 'Acme Grocer', category: 'Bakery / Seasonal', reason: 'discontinued', gtin: 'N/A (seasonal)', existingFields: 4 },
        // Already complete
        { name: 'Coca-Cola Classic 12pk Cans', brand: 'Coca-Cola', category: 'Beverages / Soda', reason: 'already_complete', gtin: '04900000252', existingFields: 42 },
        { name: 'Cheerios Original 18oz', brand: 'General Mills', category: 'Breakfast / Cereal', reason: 'already_complete', gtin: '01600012681', existingFields: 40 },
        { name: 'Tide PODS Original 42ct', brand: 'Tide', category: 'Household / Laundry', reason: 'already_complete', gtin: '03700091781', existingFields: 38 },
        { name: 'Lay\'s Classic Potato Chips 10oz', brand: 'Frito-Lay', category: 'Snacks / Chips', reason: 'already_complete', gtin: '02840032433', existingFields: 41 },
        { name: 'Oreo Original Cookies 14.3oz', brand: 'Nabisco', category: 'Snacks / Cookies', reason: 'already_complete', gtin: '04400000744', existingFields: 39 },
        // Insufficient source data
        { name: 'Prime Energy Drink Lemon Lime', brand: 'Prime', category: 'Beverages / Energy', reason: 'no_source_data', gtin: '85002646400', existingFields: 6 },
        { name: 'Mr. Beast Feastables Milk Choc Bar', brand: 'Feastables', category: 'Snacks / Candy', reason: 'no_source_data', gtin: '85967200612', existingFields: 7 },
        { name: 'Poppi Prebiotic Soda Strawberry', brand: 'Poppi', category: 'Beverages / Functional', reason: 'no_source_data', gtin: '85903800710', existingFields: 5 },
        { name: 'OLIPOP Vintage Cola 12oz', brand: 'OLIPOP', category: 'Beverages / Functional', reason: 'no_source_data', gtin: '86015400503', existingFields: 5 },
        { name: 'Siete Grain Free Tortilla Chips', brand: 'Siete', category: 'Snacks / Chips', reason: 'no_source_data', gtin: '85191400644', existingFields: 8 },
        { name: 'Banza Chickpea Rotini 8oz', brand: 'Banza', category: 'Pasta / Alt-Grain', reason: 'no_source_data', gtin: '85745500102', existingFields: 9 },
        { name: 'Koia Protein Shake Cacao', brand: 'Koia', category: 'Beverages / Protein', reason: 'no_source_data', gtin: '85834900301', existingFields: 6 },
        // Not applicable
        { name: '$25 Visa Gift Card', brand: 'Visa', category: 'Gift Cards', reason: 'not_applicable', gtin: 'N/A', existingFields: 2 },
        { name: '$50 iTunes Gift Card', brand: 'Apple', category: 'Gift Cards', reason: 'not_applicable', gtin: 'N/A', existingFields: 2 },
        { name: 'Harvest Reusable Bag $0.10', brand: 'Acme Grocer', category: 'Store Services', reason: 'not_applicable', gtin: 'N/A', existingFields: 1 },
        { name: 'PA Lottery Powerball Ticket', brand: 'PA Lottery', category: 'Lottery', reason: 'not_applicable', gtin: 'N/A', existingFields: 1 },
        { name: 'Coinstar Fee', brand: 'Coinstar', category: 'Store Services', reason: 'not_applicable', gtin: 'N/A', existingFields: 0 },
      ],
    },

    // ─── Enriched Products — Before & After ────────────────────────────────────
    enrichedProducts: [
      // ── Food & Grocery ──────────────────────────────────────────────────────
      {
        name: 'Organic Chicken Breast Boneless Skinless',
        brand: 'Harvest Nature',
        category: 'Meat / Poultry',
        tier: 'food',
        gtin: '00234961001',
        before: { productName: 'Organic Chicken Breast Boneless Skinless', brand: 'Harvest Nature', category: 'Meat / Poultry', upc: '00234961001', price: '$8.99/lb', packageSize: 'Variable weight', shelfLocation: 'Meat Counter' },
        after: { productName: 'Organic Chicken Breast Boneless Skinless', brand: 'Harvest Nature', category: 'Meat / Poultry', upc: '00234961001', price: '$8.99/lb', packageSize: 'Variable weight', shelfLocation: 'Meat Counter', calories: 165, totalFat: '3.6g', saturatedFat: '1g', cholesterol: '85mg', sodium: '74mg', totalCarbs: '0g', dietaryFiber: '0g', protein: '31g', iron: '6% DV', potassium: '8% DV', servingSize: '4 oz (112g)', ingredientsParsed: ['Organic Chicken Breast'], allergens: [], dietaryFlags: ['Organic', 'Gluten-Free', 'Dairy-Free', 'High-Protein', 'Keto-Friendly', 'Paleo', 'Whole30'], certifications: ['USDA Organic', 'No Antibiotics Ever', 'Free-Range'], foodCompassScore: 91, nutriScore: 'A', novaGroup: 1, novaLabel: 'Unprocessed / Minimally Processed', flavorProfile: ['Savory', 'Mild', 'Lean'], cuisineTags: ['American', 'Italian', 'Asian', 'Mexican'], mealSuggestions: ['Lunch', 'Dinner'], cookingMethods: ['Grill', 'Bake', 'Sauté', 'Air Fry'], identityEmbedding: 'vec_768d_org_chicken', nutritionEmbedding: 'vec_768d_nutr_meat_highprot', descriptionEmbedding: 'vec_768d_desc_org_chicken', propensityFeatures: { organicAffinity: 0.95, highProtein: 0.97, mealPrep: 0.80 } },
        fieldsAdded: 28,
      },
      {
        name: 'Chobani Greek Yogurt Plain 5.3oz',
        brand: 'Chobani',
        category: 'Dairy / Yogurt',
        tier: 'food',
        gtin: '08187960218',
        before: { productName: 'Chobani Greek Yogurt Plain 5.3oz', brand: 'Chobani', category: 'Dairy / Yogurt', upc: '08187960218', price: '$1.49', packageSize: '5.3 oz', shelfLocation: 'Aisle 4 — Dairy', stockStatus: 'In Stock' },
        after: { productName: 'Chobani Greek Yogurt Plain 5.3oz', brand: 'Chobani', category: 'Dairy / Yogurt', upc: '08187960218', price: '$1.49', packageSize: '5.3 oz', shelfLocation: 'Aisle 4 — Dairy', stockStatus: 'In Stock', calories: 80, totalFat: '0g', saturatedFat: '0g', cholesterol: '5mg', sodium: '50mg', totalCarbs: '6g', dietaryFiber: '0g', totalSugars: '4g', addedSugars: '0g', protein: '15g', calcium: '15% DV', servingSize: '1 container (150g)', servingsPerContainer: 1, ingredientsParsed: ['Nonfat Milk', 'Live Active Cultures (S. Thermophilus, L. Bulgaricus, L. Acidophilus, Bifidus, L. Casei)'], allergens: ['Milk'], dietaryFlags: ['Gluten-Free', 'Vegetarian', 'High-Protein', 'Low-Fat', 'No Added Sugar'], foodCompassScore: 82, nutriScore: 'A', novaGroup: 1, novaLabel: 'Unprocessed / Minimally Processed', flavorProfile: ['Tangy', 'Creamy', 'Mild'], cuisineTags: ['Mediterranean', 'American'], mealSuggestions: ['Breakfast', 'Snack'], identityEmbedding: 'vec_768d_chobani_plain', nutritionEmbedding: 'vec_768d_nutr_dairy_highprot', descriptionEmbedding: 'vec_768d_desc_greek_yogurt', propensityFeatures: { organicAffinity: 0.4, highProtein: 0.95, lowSodium: 0.85 } },
        fieldsAdded: 26,
      },
      {
        name: 'Wild-Caught Alaskan Salmon 8oz',
        brand: 'Trident Seafoods',
        category: 'Seafood / Fresh Fish',
        tier: 'food',
        gtin: '07170300125',
        before: { productName: 'Wild-Caught Alaskan Salmon 8oz', brand: 'Trident Seafoods', category: 'Seafood / Fresh Fish', upc: '07170300125', price: '$12.99' },
        after: { productName: 'Wild-Caught Alaskan Salmon 8oz', brand: 'Trident Seafoods', category: 'Seafood / Fresh Fish', upc: '07170300125', price: '$12.99', calories: 208, totalFat: '9.2g', saturatedFat: '1.4g', cholesterol: '63mg', sodium: '59mg', totalCarbs: '0g', protein: '28g', omega3: '2.2g', vitaminD: '142% DV', vitaminB12: '127% DV', selenium: '67% DV', servingSize: '4 oz (113g)', ingredientsParsed: ['Wild Sockeye Salmon'], allergens: ['Fish'], dietaryFlags: ['Gluten-Free', 'Dairy-Free', 'High-Protein', 'Keto-Friendly', 'Paleo', 'Heart-Healthy', 'Omega-3 Rich'], certifications: ['MSC Certified Sustainable', 'Wild-Caught'], foodCompassScore: 95, nutriScore: 'A', novaGroup: 1, novaLabel: 'Unprocessed / Minimally Processed', flavorProfile: ['Rich', 'Buttery', 'Ocean-Fresh'], cuisineTags: ['Japanese', 'American', 'Scandinavian'], mealSuggestions: ['Lunch', 'Dinner'], cookingMethods: ['Bake', 'Grill', 'Pan-Sear', 'Poach'], identityEmbedding: 'vec_768d_wild_salmon', nutritionEmbedding: 'vec_768d_nutr_fish_omega3', descriptionEmbedding: 'vec_768d_desc_wild_salmon', propensityFeatures: { healthFocus: 0.94, highProtein: 0.96, sustainableChoice: 0.88 } },
        fieldsAdded: 33,
      },
      {
        name: 'Barilla Gluten Free Penne 12oz',
        brand: 'Barilla',
        category: 'Pasta / Gluten-Free',
        tier: 'food',
        gtin: '07680885023',
        before: { productName: 'Barilla Gluten Free Penne 12oz', brand: 'Barilla', category: 'Pasta / Gluten-Free', upc: '07680885023', price: '$3.29', packageSize: '12 oz' },
        after: { productName: 'Barilla Gluten Free Penne 12oz', brand: 'Barilla', category: 'Pasta / Gluten-Free', upc: '07680885023', price: '$3.29', packageSize: '12 oz', calories: 200, totalFat: '1g', sodium: '0mg', totalCarbs: '43g', dietaryFiber: '1g', protein: '4g', servingSize: '56g dry', servingsPerContainer: 6, ingredientsParsed: ['Corn Flour', 'Rice Flour', 'Mono and Diglycerides'], allergens: [], dietaryFlags: ['Gluten-Free', 'Vegan', 'Dairy-Free', 'Nut-Free'], certifications: ['Certified Gluten-Free (GFCO)'], foodCompassScore: 48, nutriScore: 'B', novaGroup: 3, novaLabel: 'Processed Food', flavorProfile: ['Mild', 'Neutral', 'Starchy'], cuisineTags: ['Italian', 'American'], mealSuggestions: ['Lunch', 'Dinner'], cookingMethods: ['Boil'], identityEmbedding: 'vec_768d_barilla_gf_penne', nutritionEmbedding: 'vec_768d_nutr_pasta_gf', descriptionEmbedding: 'vec_768d_desc_gf_penne', propensityFeatures: { glutenFree: 0.97, plantBased: 0.6, convenienceMeal: 0.72 } },
        fieldsAdded: 26,
      },
      {
        name: "Lay's Classic Potato Chips 10oz",
        brand: "Lay's",
        category: 'Snacks / Chips',
        tier: 'food',
        gtin: '02840032433',
        before: { productName: "Lay's Classic Potato Chips 10oz", brand: "Lay's", category: 'Snacks / Chips', upc: '02840032433', price: '$4.99', packageSize: '10 oz', shelfLocation: 'Aisle 7 — Snacks' },
        after: { productName: "Lay's Classic Potato Chips 10oz", brand: "Lay's", category: 'Snacks / Chips', upc: '02840032433', price: '$4.99', packageSize: '10 oz', shelfLocation: 'Aisle 7 — Snacks', calories: 160, totalFat: '10g', saturatedFat: '1.5g', sodium: '170mg', totalCarbs: '15g', dietaryFiber: '1g', totalSugars: '1g', protein: '2g', servingSize: '1 oz (about 15 chips)', servingsPerContainer: 10, ingredientsParsed: ['Potatoes', 'Vegetable Oil (Sunflower, Corn, and/or Canola)', 'Salt'], allergens: [], dietaryFlags: ['Gluten-Free', 'Vegetarian', 'Vegan'], foodCompassScore: 22, nutriScore: 'D', novaGroup: 4, novaLabel: 'Ultra-Processed', flavorProfile: ['Salty', 'Crispy', 'Savory'], cuisineTags: ['American'], mealSuggestions: ['Snack'], identityEmbedding: 'vec_768d_lays_classic', nutritionEmbedding: 'vec_768d_nutr_snack_salty', descriptionEmbedding: 'vec_768d_desc_potato_chips', propensityFeatures: { impulsePurchase: 0.78, snacker: 0.92, brandLoyal: 0.65 } },
        fieldsAdded: 24,
      },
      {
        name: 'Organic Valley Whole Milk 64oz',
        brand: 'Organic Valley',
        category: 'Dairy / Milk',
        tier: 'food',
        gtin: '09365832001',
        before: { productName: 'Organic Valley Whole Milk 64oz', brand: 'Organic Valley', category: 'Dairy / Milk', upc: '09365832001', price: '$6.49', packageSize: '64 oz (half gallon)', shelfLocation: 'Aisle 4 — Dairy' },
        after: { productName: 'Organic Valley Whole Milk 64oz', brand: 'Organic Valley', category: 'Dairy / Milk', upc: '09365832001', price: '$6.49', packageSize: '64 oz (half gallon)', shelfLocation: 'Aisle 4 — Dairy', calories: 150, totalFat: '8g', saturatedFat: '5g', cholesterol: '35mg', sodium: '120mg', totalCarbs: '12g', totalSugars: '12g', addedSugars: '0g', protein: '8g', calcium: '30% DV', vitaminD: '15% DV', servingSize: '1 cup (240ml)', servingsPerContainer: 8, ingredientsParsed: ['Organic Whole Milk', 'Vitamin D3'], allergens: ['Milk'], dietaryFlags: ['Organic', 'Gluten-Free', 'Vegetarian'], certifications: ['USDA Organic', 'Pasture-Raised'], foodCompassScore: 62, nutriScore: 'B', novaGroup: 1, novaLabel: 'Unprocessed / Minimally Processed', flavorProfile: ['Creamy', 'Rich', 'Smooth'], cuisineTags: ['American'], mealSuggestions: ['Breakfast', 'Anytime'], identityEmbedding: 'vec_768d_ov_whole_milk', nutritionEmbedding: 'vec_768d_nutr_dairy_whole', descriptionEmbedding: 'vec_768d_desc_organic_milk', propensityFeatures: { organicAffinity: 0.93, dairyConsumer: 0.95, familySize: 0.82 } },
        fieldsAdded: 25,
      },
      {
        name: "Nature's Own Whole Wheat Bread 20oz",
        brand: "Nature's Own",
        category: 'Bakery / Bread',
        tier: 'food',
        gtin: '07225001220',
        before: { productName: "Nature's Own Whole Wheat Bread 20oz", brand: "Nature's Own", category: 'Bakery / Bread', upc: '07225001220', price: '$3.99', packageSize: '20 oz' },
        after: { productName: "Nature's Own Whole Wheat Bread 20oz", brand: "Nature's Own", category: 'Bakery / Bread', upc: '07225001220', price: '$3.99', packageSize: '20 oz', calories: 60, totalFat: '1g', sodium: '110mg', totalCarbs: '12g', dietaryFiber: '2g', totalSugars: '2g', addedSugars: '2g', protein: '3g', servingSize: '1 slice (26g)', servingsPerContainer: 22, ingredientsParsed: ['Whole Wheat Flour', 'Water', 'Sugar', 'Yeast', 'Wheat Gluten', 'Soybean Oil', 'Salt'], allergens: ['Wheat', 'Soy'], dietaryFlags: ['Vegetarian', 'Low-Fat', 'Whole-Grain'], foodCompassScore: 55, nutriScore: 'B', novaGroup: 4, novaLabel: 'Ultra-Processed', flavorProfile: ['Mild', 'Wheaty', 'Soft'], cuisineTags: ['American'], mealSuggestions: ['Breakfast', 'Lunch'], identityEmbedding: 'vec_768d_naturesown_wheat', nutritionEmbedding: 'vec_768d_nutr_bread_ww', descriptionEmbedding: 'vec_768d_desc_wheat_bread', propensityFeatures: { wholeGrain: 0.78, stapleItem: 0.94, familySize: 0.80 } },
        fieldsAdded: 25,
      },
      {
        name: 'Dole Baby Spinach 5oz',
        brand: 'Dole',
        category: 'Produce / Salad',
        tier: 'food',
        gtin: '07143000662',
        before: { productName: 'Dole Baby Spinach 5oz', brand: 'Dole', category: 'Produce / Salad', upc: '07143000662', price: '$3.49', packageSize: '5 oz' },
        after: { productName: 'Dole Baby Spinach 5oz', brand: 'Dole', category: 'Produce / Salad', upc: '07143000662', price: '$3.49', packageSize: '5 oz', calories: 20, totalFat: '0g', sodium: '65mg', totalCarbs: '3g', dietaryFiber: '2g', protein: '2g', vitaminA: '160% DV', vitaminC: '35% DV', iron: '15% DV', calcium: '8% DV', servingSize: '3 cups (85g)', ingredientsParsed: ['Baby Spinach'], allergens: [], dietaryFlags: ['Organic-Available', 'Gluten-Free', 'Vegan', 'Keto-Friendly', 'Paleo', 'Low-Calorie'], foodCompassScore: 100, nutriScore: 'A', novaGroup: 1, novaLabel: 'Unprocessed / Minimally Processed', flavorProfile: ['Earthy', 'Mild', 'Green'], cuisineTags: ['American', 'Mediterranean', 'Italian'], mealSuggestions: ['Lunch', 'Dinner', 'Smoothie'], identityEmbedding: 'vec_768d_dole_spinach', nutritionEmbedding: 'vec_768d_nutr_leafy_green', descriptionEmbedding: 'vec_768d_desc_baby_spinach', propensityFeatures: { healthFocus: 0.97, plantBased: 0.92, freshProduce: 0.95 } },
        fieldsAdded: 25,
      },
      {
        name: 'KIND Dark Chocolate Nuts & Sea Salt Bar',
        brand: 'KIND',
        category: 'Snacks / Bars',
        tier: 'food',
        gtin: '60264921100',
        before: { productName: 'KIND Dark Chocolate Nuts & Sea Salt Bar', brand: 'KIND', category: 'Snacks / Bars', upc: '60264921100', price: '$1.79', packageSize: '1.4 oz' },
        after: { productName: 'KIND Dark Chocolate Nuts & Sea Salt Bar', brand: 'KIND', category: 'Snacks / Bars', upc: '60264921100', price: '$1.79', packageSize: '1.4 oz', calories: 180, totalFat: '13g', saturatedFat: '3.5g', sodium: '25mg', totalCarbs: '16g', dietaryFiber: '3g', totalSugars: '8g', addedSugars: '5g', protein: '6g', servingSize: '1 bar (40g)', servingsPerContainer: 1, ingredientsParsed: ['Almonds', 'Dark Chocolate', 'Peanuts', 'Sugar', 'Honey', 'Sea Salt', 'Soy Lecithin'], allergens: ['Peanuts', 'Tree Nuts', 'Soy'], dietaryFlags: ['Gluten-Free', 'Non-GMO'], foodCompassScore: 44, nutriScore: 'C', novaGroup: 4, novaLabel: 'Ultra-Processed', flavorProfile: ['Sweet', 'Nutty', 'Chocolatey', 'Salty'], cuisineTags: ['American'], mealSuggestions: ['Snack'], identityEmbedding: 'vec_768d_kind_dk_choc', nutritionEmbedding: 'vec_768d_nutr_bar_nutty', descriptionEmbedding: 'vec_768d_desc_nut_bar', propensityFeatures: { snacker: 0.88, healthySwap: 0.62, impulsePurchase: 0.71 } },
        fieldsAdded: 24,
      },
      {
        name: "Eggland's Best Large Eggs 12ct",
        brand: "Eggland's Best",
        category: 'Dairy / Eggs',
        tier: 'food',
        gtin: '07102000010',
        before: { productName: "Eggland's Best Large Eggs 12ct", brand: "Eggland's Best", category: 'Dairy / Eggs', upc: '07102000010', price: '$4.29', packageSize: '12 count' },
        after: { productName: "Eggland's Best Large Eggs 12ct", brand: "Eggland's Best", category: 'Dairy / Eggs', upc: '07102000010', price: '$4.29', packageSize: '12 count', calories: 60, totalFat: '3.5g', saturatedFat: '1g', cholesterol: '170mg', sodium: '65mg', totalCarbs: '0g', protein: '6g', vitaminD: '25% DV', vitaminB12: '35% DV', omega3: '115mg', lutein: '225mcg', servingSize: '1 egg (50g)', servingsPerContainer: 12, ingredientsParsed: ['Egg'], allergens: ['Egg'], dietaryFlags: ['Gluten-Free', 'Dairy-Free', 'Keto-Friendly', 'Vegetarian'], certifications: ['Cage-Free Available', 'Vegetarian-Fed Hens'], foodCompassScore: 73, nutriScore: 'A', novaGroup: 1, novaLabel: 'Unprocessed / Minimally Processed', flavorProfile: ['Mild', 'Rich'], cuisineTags: ['Universal'], mealSuggestions: ['Breakfast', 'Lunch', 'Dinner', 'Baking'], cookingMethods: ['Scramble', 'Fry', 'Boil', 'Bake', 'Poach'], identityEmbedding: 'vec_768d_eb_eggs', nutritionEmbedding: 'vec_768d_nutr_eggs_enriched', descriptionEmbedding: 'vec_768d_desc_large_eggs', propensityFeatures: { stapleItem: 0.97, healthFocus: 0.72, familySize: 0.85 } },
        fieldsAdded: 27,
      },
      {
        name: 'Bertolli Extra Virgin Olive Oil 17oz',
        brand: 'Bertolli',
        category: 'Oils & Vinegars',
        tier: 'food',
        gtin: '00568100020',
        before: { productName: 'Bertolli Extra Virgin Olive Oil 17oz', brand: 'Bertolli', category: 'Oils & Vinegars', upc: '00568100020', price: '$7.99', packageSize: '17 oz' },
        after: { productName: 'Bertolli Extra Virgin Olive Oil 17oz', brand: 'Bertolli', category: 'Oils & Vinegars', upc: '00568100020', price: '$7.99', packageSize: '17 oz', calories: 120, totalFat: '14g', saturatedFat: '2g', monounsaturatedFat: '10g', polyunsaturatedFat: '1.5g', sodium: '0mg', totalCarbs: '0g', protein: '0g', servingSize: '1 tbsp (15ml)', servingsPerContainer: 33, ingredientsParsed: ['Extra Virgin Olive Oil'], allergens: [], dietaryFlags: ['Gluten-Free', 'Vegan', 'Keto-Friendly', 'Paleo', 'Heart-Healthy', 'Mediterranean Diet'], certifications: ['First Cold Press', 'Product of Italy'], foodCompassScore: 78, nutriScore: 'C', novaGroup: 1, novaLabel: 'Unprocessed / Minimally Processed', flavorProfile: ['Fruity', 'Peppery', 'Grassy'], cuisineTags: ['Italian', 'Mediterranean', 'Greek'], mealSuggestions: ['Cooking', 'Dressing', 'Finishing'], identityEmbedding: 'vec_768d_bertolli_evoo', nutritionEmbedding: 'vec_768d_nutr_oil_evoo', descriptionEmbedding: 'vec_768d_desc_olive_oil', propensityFeatures: { mediterraneanDiet: 0.91, premiumBuyer: 0.74, healthFocus: 0.83 } },
        fieldsAdded: 25,
      },
      {
        name: 'Cheerios Original 18oz',
        brand: 'General Mills',
        category: 'Cereal / Breakfast',
        tier: 'food',
        gtin: '01600012700',
        before: { productName: 'Cheerios Original 18oz', brand: 'General Mills', category: 'Cereal / Breakfast', upc: '01600012700', price: '$4.79', packageSize: '18 oz', shelfLocation: 'Aisle 3 — Cereal' },
        after: { productName: 'Cheerios Original 18oz', brand: 'General Mills', category: 'Cereal / Breakfast', upc: '01600012700', price: '$4.79', packageSize: '18 oz', shelfLocation: 'Aisle 3 — Cereal', calories: 140, totalFat: '2.5g', sodium: '190mg', totalCarbs: '29g', dietaryFiber: '4g', totalSugars: '2g', addedSugars: '2g', protein: '5g', iron: '45% DV', vitaminB12: '25% DV', servingSize: '1.5 cups (39g)', servingsPerContainer: 13, ingredientsParsed: ['Whole Grain Oats', 'Modified Corn Starch', 'Sugar', 'Salt', 'Tripotassium Phosphate', 'Oat Fiber', 'Wheat Starch'], allergens: ['Wheat'], dietaryFlags: ['Vegetarian', 'Low-Fat', 'Whole-Grain', 'Heart-Healthy'], certifications: ['Heart-Healthy (AHA)'], foodCompassScore: 58, nutriScore: 'B', novaGroup: 4, novaLabel: 'Ultra-Processed', flavorProfile: ['Mild', 'Oat-Forward', 'Lightly Sweet'], cuisineTags: ['American'], mealSuggestions: ['Breakfast', 'Snack'], identityEmbedding: 'vec_768d_cheerios_orig', nutritionEmbedding: 'vec_768d_nutr_cereal_oat', descriptionEmbedding: 'vec_768d_desc_cheerios', propensityFeatures: { stapleItem: 0.92, familySize: 0.90, heartHealth: 0.75 } },
        fieldsAdded: 24,
      },

      // ── Health & Wellness ───────────────────────────────────────────────────
      {
        name: 'Nature Made Vitamin D3 2000 IU',
        brand: 'Nature Made',
        category: 'Health / Vitamins',
        tier: 'health',
        gtin: '03190401565',
        before: { productName: 'Nature Made Vitamin D3 2000 IU', brand: 'Nature Made', category: 'Health / Vitamins', upc: '03190401565', price: '$9.99', packageSize: '220 Softgels' },
        after: { productName: 'Nature Made Vitamin D3 2000 IU', brand: 'Nature Made', category: 'Health / Vitamins', upc: '03190401565', price: '$9.99', packageSize: '220 Softgels', supplementFacts: true, activeIngredient: 'Cholecalciferol (Vitamin D3)', dosagePerServing: '2000 IU (50 mcg)', servingSize: '1 Softgel', servingsPerContainer: 220, otherIngredients: ['Soybean Oil', 'Gelatin', 'Glycerin', 'Corn Oil', 'Water'], allergens: ['Soy'], certifications: ['USP Verified', 'Gluten-Free', 'No Artificial Flavors'], dailyValuePct: '250% DV', formType: 'Softgel', targetDemographic: 'Adults', useCaseTags: ['Bone Health', 'Immune Support', 'Calcium Absorption'], materialComposition: 'Gelatin softgel capsule with oil-based fill', storageInstructions: 'Store at room temperature. Keep out of reach of children.', identityEmbedding: 'vec_768d_natmade_d3', descriptionEmbedding: 'vec_768d_desc_vitamin_d3', propensityFeatures: { healthFocus: 0.92, supplementUser: 0.88 } },
        fieldsAdded: 16,
      },
      {
        name: 'Optimum Nutrition Gold Standard Whey 2lb',
        brand: 'Optimum Nutrition',
        category: 'Health / Sports Nutrition',
        tier: 'health',
        gtin: '07484561040',
        before: { productName: 'Optimum Nutrition Gold Standard Whey 2lb', brand: 'Optimum Nutrition', category: 'Health / Sports Nutrition', upc: '07484561040', price: '$34.99', packageSize: '2 lb (908g)' },
        after: { productName: 'Optimum Nutrition Gold Standard Whey 2lb', brand: 'Optimum Nutrition', category: 'Health / Sports Nutrition', upc: '07484561040', price: '$34.99', packageSize: '2 lb (908g)', supplementFacts: true, activeIngredient: 'Whey Protein Isolate', proteinPerServing: '24g', bcaaContent: '5.5g', servingSize: '1 rounded scoop (31g)', servingsPerContainer: 29, otherIngredients: ['Whey Protein Isolate', 'Whey Protein Concentrate', 'Cocoa', 'Soy Lecithin', 'Natural & Artificial Flavors', 'Aminogen'], allergens: ['Milk', 'Soy'], certifications: ['Informed Sport Certified', 'Banned Substance Tested'], mixability: 'Instantly in cold water or milk', formType: 'Powder', targetDemographic: 'Athletes & Active Adults', useCaseTags: ['Muscle Recovery', 'Post-Workout', 'Protein Supplementation'], flavorOptions: ['Double Rich Chocolate', 'Vanilla Ice Cream', 'Strawberry Banana'], identityEmbedding: 'vec_768d_on_whey', descriptionEmbedding: 'vec_768d_desc_whey_protein', propensityFeatures: { fitnessEnthusiast: 0.95, highProtein: 0.98, supplementUser: 0.92 } },
        fieldsAdded: 18,
      },
      {
        name: 'Garden of Life Raw Probiotics Ultimate Care',
        brand: 'Garden of Life',
        category: 'Health / Probiotics',
        tier: 'health',
        gtin: '06583600009',
        before: { productName: 'Garden of Life Raw Probiotics Ultimate Care', brand: 'Garden of Life', category: 'Health / Probiotics', upc: '06583600009', price: '$44.99', packageSize: '30 Capsules' },
        after: { productName: 'Garden of Life Raw Probiotics Ultimate Care', brand: 'Garden of Life', category: 'Health / Probiotics', upc: '06583600009', price: '$44.99', packageSize: '30 Capsules', supplementFacts: true, activeIngredient: '100 Billion CFU Probiotic Blend', strainCount: '34 probiotic strains', servingSize: '1 Capsule', servingsPerContainer: 30, otherIngredients: ['Organic Acacia Fiber', 'Organic Potato Starch (capsule)'], allergens: ['Milk', 'Soy'], certifications: ['Non-GMO Project Verified', 'NSF Gluten-Free', 'Vegetarian'], storageInstructions: 'Refrigerate to maintain potency', formType: 'Vegetarian Capsule', targetDemographic: 'Adults 50+', useCaseTags: ['Digestive Health', 'Immune Support', 'Gut Flora Restoration'], materialComposition: 'Vegetable cellulose capsule', identityEmbedding: 'vec_768d_gol_probiotics', descriptionEmbedding: 'vec_768d_desc_raw_probiotics', propensityFeatures: { healthFocus: 0.94, gutHealth: 0.96, premiumBuyer: 0.82 } },
        fieldsAdded: 16,
      },
      {
        name: 'Nordic Naturals Ultimate Omega 60ct',
        brand: 'Nordic Naturals',
        category: 'Health / Fish Oil',
        tier: 'health',
        gtin: '07681041280',
        before: { productName: 'Nordic Naturals Ultimate Omega 60ct', brand: 'Nordic Naturals', category: 'Health / Fish Oil', upc: '07681041280', price: '$27.95', packageSize: '60 Soft Gels' },
        after: { productName: 'Nordic Naturals Ultimate Omega 60ct', brand: 'Nordic Naturals', category: 'Health / Fish Oil', upc: '07681041280', price: '$27.95', packageSize: '60 Soft Gels', supplementFacts: true, activeIngredient: 'Concentrated Omega-3 Fish Oil', epaContent: '650mg', dhaContent: '450mg', totalOmega3: '1280mg per serving', servingSize: '2 Soft Gels', servingsPerContainer: 30, otherIngredients: ['Purified Deep Sea Fish Oil', 'Soft Gel Capsule (Gelatin, Glycerin, Water)', 'Natural Lemon Flavor', 'Vitamin E', 'Rosemary Extract'], allergens: ['Fish'], certifications: ['Friend of the Sea', 'Non-GMO Verified', 'Award-Winning Purity'], formType: 'Soft Gel', targetDemographic: 'Adults', useCaseTags: ['Heart Health', 'Brain Function', 'Joint Health', 'Anti-Inflammatory'], materialComposition: 'Gelatin soft gel with fish oil fill', identityEmbedding: 'vec_768d_nordic_omega', descriptionEmbedding: 'vec_768d_desc_fish_oil', propensityFeatures: { healthFocus: 0.91, heartHealth: 0.93, supplementUser: 0.87 } },
        fieldsAdded: 18,
      },
      {
        name: "Nature's Bounty Melatonin 5mg 90ct",
        brand: "Nature's Bounty",
        category: 'Health / Sleep Aids',
        tier: 'health',
        gtin: '07431232252',
        before: { productName: "Nature's Bounty Melatonin 5mg 90ct", brand: "Nature's Bounty", category: 'Health / Sleep Aids', upc: '07431232252', price: '$6.99', packageSize: '90 Tablets' },
        after: { productName: "Nature's Bounty Melatonin 5mg 90ct", brand: "Nature's Bounty", category: 'Health / Sleep Aids', upc: '07431232252', price: '$6.99', packageSize: '90 Tablets', supplementFacts: true, activeIngredient: 'Melatonin', dosagePerServing: '5mg', servingSize: '1 Tablet', servingsPerContainer: 90, otherIngredients: ['Dicalcium Phosphate', 'Vegetable Cellulose', 'Vegetable Magnesium Stearate'], allergens: [], certifications: ['Non-GMO', 'No Artificial Flavors'], formType: 'Tablet', targetDemographic: 'Adults with occasional sleeplessness', useCaseTags: ['Sleep Support', 'Jet Lag Relief', 'Circadian Rhythm'], storageInstructions: 'Store at room temperature', materialComposition: 'Compressed tablet', identityEmbedding: 'vec_768d_nb_melatonin', descriptionEmbedding: 'vec_768d_desc_melatonin', propensityFeatures: { sleepWellness: 0.88, supplementUser: 0.75 } },
        fieldsAdded: 14,
      },

      // ── Non-Food & Household ────────────────────────────────────────────────
      {
        name: 'Clorox Disinfecting Wipes Fresh Scent 75ct',
        brand: 'Clorox',
        category: 'Household / Cleaning',
        tier: 'nonFood',
        gtin: '04460001608',
        before: { productName: 'Clorox Disinfecting Wipes Fresh Scent 75ct', brand: 'Clorox', category: 'Household / Cleaning', upc: '04460001608', price: '$5.49', packageSize: '75 wipes' },
        after: { productName: 'Clorox Disinfecting Wipes Fresh Scent 75ct', brand: 'Clorox', category: 'Household / Cleaning', upc: '04460001608', price: '$5.49', packageSize: '75 wipes', activeChemicals: ['Alkyl Dimethyl Benzyl Ammonium Chloride (0.184%)'], inactiveIngredients: ['Water', 'Substrate (Polyester)', 'Fragrance'], surfaceCompatibility: ['Hard Non-Porous Surfaces', 'Glass', 'Stainless Steel'], killsClaims: ['99.9% of bacteria', 'Viruses (Cold & Flu)'], safetyWarnings: ['Keep out of reach of children', 'Do not use on skin', 'Avoid contact with eyes'], epaRegistration: 'EPA Reg. No. 5813-79', useCaseTags: ['Kitchen', 'Bathroom', 'General Disinfection'], materialComposition: 'Pre-moistened polyester wipe substrate', scent: 'Fresh', disposalInstructions: 'Do not flush. Dispose in trash.', identityEmbedding: 'vec_768d_clorox_wipes', descriptionEmbedding: 'vec_768d_desc_disinfect_wipes', propensityFeatures: { householdBuyer: 0.78, cleaningFrequency: 0.84 } },
        fieldsAdded: 13,
      },
      {
        name: 'OPI Nail Lacquer Big Apple Red',
        brand: 'OPI',
        category: 'Beauty / Nail Care',
        tier: 'nonFood',
        gtin: '09460319178',
        before: { productName: 'OPI Nail Lacquer Big Apple Red', brand: 'OPI', category: 'Beauty / Nail Care', upc: '09460319178', price: '$10.99', packageSize: '0.5 fl oz' },
        after: { productName: 'OPI Nail Lacquer Big Apple Red', brand: 'OPI', category: 'Beauty / Nail Care', upc: '09460319178', price: '$10.99', packageSize: '0.5 fl oz', colorFamily: 'Red', finishType: 'Cream / Opaque', chemicalIngredients: ['Butyl Acetate', 'Ethyl Acetate', 'Nitrocellulose', 'Tosylamide/Formaldehyde Resin'], formulaClaims: ['Chip-Resistant', 'Salon-Quality', 'Long-Wearing'], safetyWarnings: ['Flammable', 'Keep away from heat/flame', 'Use in well-ventilated area'], applicationTips: 'Apply 2 thin coats for best color payoff. Use with OPI base and top coat.', useCaseTags: ['Manicure', 'Pedicure', 'Nail Art'], materialComposition: 'Solvent-based nail lacquer with nitrocellulose film-former', dryTime: '1-2 minutes per coat', identityEmbedding: 'vec_768d_opi_big_apple', descriptionEmbedding: 'vec_768d_desc_nail_lacquer', propensityFeatures: { beautyBuyer: 0.91, premiumBrand: 0.78 } },
        fieldsAdded: 12,
      },
      {
        name: 'Dawn Ultra Dish Soap Original 19.4oz',
        brand: 'Dawn',
        category: 'Household / Dish Care',
        tier: 'nonFood',
        gtin: '03700091064',
        before: { productName: 'Dawn Ultra Dish Soap Original 19.4oz', brand: 'Dawn', category: 'Household / Dish Care', upc: '03700091064', price: '$3.99', packageSize: '19.4 fl oz' },
        after: { productName: 'Dawn Ultra Dish Soap Original 19.4oz', brand: 'Dawn', category: 'Household / Dish Care', upc: '03700091064', price: '$3.99', packageSize: '19.4 fl oz', activeSurfactants: ['Sodium Lauryl Sulfate', 'Sodium Laureth Sulfate', 'C10-16 Alkyldimethylamine Oxide'], greaseCuttingClaims: ['3x grease cleaning power', 'Tough on grease, gentle on hands'], scent: 'Original', biodegradable: 'Partially (surfactants)', safetyWarnings: ['Avoid contact with eyes', 'Keep out of reach of children'], useCaseTags: ['Hand Dishwashing', 'Pre-Soaking', 'General Cleaning'], materialComposition: 'Aqueous surfactant solution in HDPE bottle', concentratedFormula: true, identityEmbedding: 'vec_768d_dawn_original', descriptionEmbedding: 'vec_768d_desc_dish_soap', propensityFeatures: { householdBuyer: 0.82, stapleItem: 0.91, valueSeeker: 0.70 } },
        fieldsAdded: 12,
      },
      {
        name: 'Duracell Coppertop AA Batteries 8pk',
        brand: 'Duracell',
        category: 'Household / Batteries',
        tier: 'nonFood',
        gtin: '04133321501',
        before: { productName: 'Duracell Coppertop AA Batteries 8pk', brand: 'Duracell', category: 'Household / Batteries', upc: '04133321501', price: '$8.99', packageSize: '8 count' },
        after: { productName: 'Duracell Coppertop AA Batteries 8pk', brand: 'Duracell', category: 'Household / Batteries', upc: '04133321501', price: '$8.99', packageSize: '8 count', batteryType: 'Alkaline', voltage: '1.5V', chemistry: 'Zinc-Manganese Dioxide', shelfLife: 'Up to 12 years in storage', safetyWarnings: ['Do not recharge', 'Do not dispose in fire', 'Keep away from children'], useCaseTags: ['Remote Controls', 'Toys', 'Flashlights', 'Wireless Devices'], materialComposition: 'Steel can, zinc anode, manganese dioxide cathode', recyclable: 'Check local regulations for battery recycling', identityEmbedding: 'vec_768d_duracell_aa', descriptionEmbedding: 'vec_768d_desc_aa_batteries', propensityFeatures: { householdBuyer: 0.76, stapleItem: 0.68 } },
        fieldsAdded: 10,
      },
      {
        name: 'KitchenAid Silicone Spatula Set 3pc',
        brand: 'KitchenAid',
        category: 'Kitchen / Utensils',
        tier: 'nonFood',
        gtin: '02469100320',
        before: { productName: 'KitchenAid Silicone Spatula Set 3pc', brand: 'KitchenAid', category: 'Kitchen / Utensils', upc: '02469100320', price: '$12.99', packageSize: '3-piece set' },
        after: { productName: 'KitchenAid Silicone Spatula Set 3pc', brand: 'KitchenAid', category: 'Kitchen / Utensils', upc: '02469100320', price: '$12.99', packageSize: '3-piece set', materialComposition: 'BPA-free silicone heads with nylon core and polypropylene handles', heatResistance: 'Up to 450°F (232°C)', dishwasherSafe: true, colorOptions: ['Empire Red', 'Onyx Black', 'Aqua Sky'], safetyFeatures: ['BPA-Free', 'Non-Scratch', 'Food-Grade Silicone'], useCaseTags: ['Baking', 'Cooking', 'Mixing', 'Scraping'], includedPieces: ['Large Spatula', 'Medium Spatula', 'Spoon Spatula'], identityEmbedding: 'vec_768d_ka_spatula', descriptionEmbedding: 'vec_768d_desc_spatula_set', propensityFeatures: { homeCook: 0.87, premiumBrand: 0.72, giftPotential: 0.65 } },
        fieldsAdded: 10,
      },
    ],
  },

  // ─── User Intelligence Data ───────────────────────────────────────────────────
  userIntelligence: {
    propensityDimensions: [
      { name: 'Organic Preference', score: 0.91, category: 'dietary', color: '#10b981' },
      { name: 'High Protein', score: 0.89, category: 'dietary', color: '#10b981' },
      { name: 'Low Sodium', score: 0.82, category: 'dietary', color: '#10b981' },
      { name: 'Gluten-Free', score: 0.78, category: 'dietary', color: '#10b981' },
      { name: 'Plant-Based', score: 0.34, category: 'dietary', color: '#10b981' },
      { name: 'Premium Brand Affinity', score: 0.74, category: 'brand', color: '#3b82f6' },
      { name: 'Harvest Store Brand Loyalty', score: 0.62, category: 'brand', color: '#3b82f6' },
      { name: 'Promo Responsiveness', score: 0.67, category: 'behavioral', color: '#f59e0b' },
      { name: 'New Product Explorer', score: 0.55, category: 'behavioral', color: '#f59e0b' },
      { name: 'Price Sensitivity', score: 0.31, category: 'behavioral', color: '#f59e0b' },
      { name: 'Impulse Purchase', score: 0.28, category: 'behavioral', color: '#f59e0b' },
    ],
    propensityComputation: [
      { step: 1, name: 'Transaction Ingestion', desc: '2-year purchase history (48M rows)', color: 'bg-blue-600' },
      { step: 2, name: 'Enrichment Join', desc: 'Each purchased UPC joined to enriched catalog attributes', color: 'bg-purple-600' },
      { step: 3, name: 'Feature Aggregation', desc: 'Per-shopper rolling aggregates over dietary, brand, price signals', color: 'bg-emerald-600' },
      { step: 4, name: 'Score Normalization', desc: 'Min-max normalization to 0-1 per dimension', color: 'bg-teal-600' },
    ],
    flavorDNA: {
      flavorDimensions: [
        { name: 'Umami', value: 0.81, color: '#a855f7' },
        { name: 'Salty', value: 0.68, color: '#60a5fa' },
        { name: 'Sweet', value: 0.42, color: '#f472b6' },
        { name: 'Spicy', value: 0.35, color: '#ef4444' },
        { name: 'Sour', value: 0.24, color: '#fbbf24' },
        { name: 'Bitter', value: 0.15, color: '#6b7280' },
      ],
      cuisineAffinity: [
        { name: 'Italian', pct: 32, color: '#10b981' },
        { name: 'Mediterranean', pct: 24, color: '#3b82f6' },
        { name: 'Asian', pct: 18, color: '#f59e0b' },
        { name: 'American', pct: 15, color: '#ef4444' },
        { name: 'Mexican', pct: 11, color: '#8b5cf6' },
      ],
      topIngredients: [
        'Olive Oil', 'Garlic', 'Chicken', 'Tomatoes', 'Basil',
        'Brown Rice', 'Almonds', 'Lemon', 'Spinach', 'Avocado',
        'Quinoa', 'Salmon', 'Greek Yogurt', 'Sweet Potato', 'Broccoli',
        'Bell Peppers', 'Oats', 'Eggs', 'Blueberries', 'Ginger',
      ],
    },
    pantryModel: {
      items: [
        { name: 'Chicken Breast', consumptionRate: '200g/day', reorderIn: 1, confidence: 0.94 },
        { name: 'Greek Yogurt', consumptionRate: '150g/day', reorderIn: 0, confidence: 0.91 },
        { name: 'Almond Milk', consumptionRate: '350ml/day', reorderIn: 4, confidence: 0.88 },
        { name: 'Brown Rice', consumptionRate: '85g/day', reorderIn: 6, confidence: 0.79 },
        { name: 'Olive Oil', consumptionRate: '18ml/day', reorderIn: 12, confidence: 0.92 },
      ],
      householdSize: { estimated: 2, confidence: 0.85, method: 'Purchase volume + product variety analysis' },
      seasonalAdjustments: [
        { season: 'Spring', change: '+20% fresh produce, +15% salad ingredients', color: '#10b981' },
        { season: 'Summer', change: '+40% beverages, +25% grilling items', color: '#f59e0b' },
        { season: 'Fall', change: '+30% baking supplies, +20% soups', color: '#ef4444' },
        { season: 'Winter', change: '+35% comfort foods, +25% hot beverages', color: '#3b82f6' },
      ],
    },
    consumptionModel: {
      weeklyCalories: 14200,
      macroBalance: [
        { macro: 'Carbs', pct: 42, color: '#3b82f6' },
        { macro: 'Fat', pct: 30, color: '#f59e0b' },
        { macro: 'Protein', pct: 28, color: '#ef4444' },
      ],
      mealPatterns: [
        { meal: 'Breakfast', intensity: 'Light', typicalCal: 350, pct: 17, color: '#fbbf24' },
        { meal: 'Lunch', intensity: 'Moderate', typicalCal: 550, pct: 27, color: '#10b981' },
        { meal: 'Dinner', intensity: 'Heavy', typicalCal: 750, pct: 37, color: '#8b5cf6' },
        { meal: 'Snacks', intensity: 'Frequent', typicalCal: 380, pct: 19, color: '#f472b6' },
      ],
      healthTrajectory: {
        trend: 'Improving',
        period: '6 months',
        trendColor: '#10b981',
        indicators: [
          { label: 'Organic purchase %', change: '+12%' },
          { label: 'Avg NOVA score', change: '-0.4' },
          { label: 'Produce variety', change: '+8 items' },
        ],
      },
    },
    householding: {
      householdId: 'HH-40001-A',
      confidence: 0.78,
      members: [
        { role: 'Primary Shopper', age: 'Adult (32-38)', preferences: 'Health-focused, organic, high-protein', shopperId: '40001000512', identified: true },
        { role: 'Secondary Member', age: 'Adult (30-36)', preferences: 'Convenience-oriented, price-aware', shopperId: 'inferred', identified: false },
      ],
      sharedPreferences: ['Organic Produce', 'Whole Grain Bread', 'Low Sodium', 'Fresh Vegetables'],
      personalPreferences: {
        primary: ['Greek Yogurt', 'Protein Bars', 'Kombucha', 'Quinoa'],
        secondary: ['Craft Beer', 'Frozen Pizza', 'Chips', 'Ice Cream'],
      },
      detections: { children: false, pets: false, elderly: false },
    },
    dataQuality: {
      summary: {
        totalLoyaltyUsers: 135000,
        flaggedUsers: 4820,
        flaggedPct: 3.6,
        cleanUsers: 130180,
      },
      anomalyTypes: [
        {
          code: 'multi_mparticle',
          label: 'Multiple mParticle IDs',
          count: 2140,
          color: '#ef4444',
          severity: 'high',
          desc: 'A single loyalty card number is linked to 2+ distinct mParticle identity profiles. Indicates the shopper used different devices/browsers without being properly stitched, or a shared account across household members.',
          impact: 'Propensity scores may be diluted across fragmented profiles. Flavor DNA and consumption model lose accuracy when purchase history is split.',
          remediation: 'Identity resolution pass: merge mParticle profiles sharing the same loyalty_card_no using deterministic matching. Flag ambiguous cases for probabilistic ID stitching.',
        },
        {
          code: 'anomalous_volume',
          label: 'Anomalously High Transaction Volume',
          count: 890,
          color: '#f59e0b',
          severity: 'high',
          desc: 'Loyalty number shows 10x+ the median transaction frequency or basket size. Common cause: store employees scanning their own card for non-member customers, or a loyalty number used at a self-checkout kiosk as a default.',
          impact: 'Inflated purchase history corrupts propensity models — a cashier\'s loyalty card looks like it buys everything in the store. Consumption model becomes meaningless.',
          remediation: 'Flag accounts exceeding 3 std deviations from median weekly transactions. Exclude from model training or apply cashier-detection heuristic (>15 transactions/day, >50 unique categories/week).',
        },
        {
          code: 'stale_profile',
          label: 'Stale / Dormant Profiles',
          count: 1240,
          color: '#8b5cf6',
          severity: 'medium',
          desc: 'No purchase activity in the last 12+ months despite having historical data. Shopper may have moved, switched stores, or abandoned the loyalty program.',
          impact: 'Pantry model predictions are outdated. Propensity scores reflect past behavior that no longer applies. Including these in aggregates skews mission cluster distributions.',
          remediation: 'Decay weighting: reduce influence of transactions older than 6 months. Flag profiles with no activity in 12+ months as dormant. Exclude from active model training.',
        },
        {
          code: 'event_spam',
          label: 'Anomalous Behavioral Events',
          count: 550,
          color: '#06b6d4',
          severity: 'medium',
          desc: 'Loyalty number associated with an abnormal volume of behavioral events (searches, page views, clicks) — often 100x normal rate. Could be bot traffic, automated testing, or a kiosk/shared device.',
          impact: 'Behavioral propensity signals (New Product Explorer, Impulse Purchase) become unreliable. Event-based features for the knowledge graph are polluted.',
          remediation: 'Rate-limit behavioral event ingestion per loyalty ID. Apply bot-detection heuristics (uniform click intervals, no cart additions). Quarantine flagged events from feature pipelines.',
        },
      ],
      flaggedExamples: [
        { loyaltyId: '40001082934', issue: 'multi_mparticle', detail: '4 mParticle profiles linked — 2 iOS, 1 Android, 1 web', mparticleIds: 4, weeklyTxns: 3.2, eventRate: 'Normal' },
        { loyaltyId: '40001015677', issue: 'anomalous_volume', detail: 'Avg 47 transactions/week (median: 2.8) — likely cashier card', mparticleIds: 1, weeklyTxns: 47.0, eventRate: 'Normal' },
        { loyaltyId: '40001127840', issue: 'anomalous_volume', detail: 'Avg 23 transactions/week, 180+ unique UPCs/week', mparticleIds: 1, weeklyTxns: 23.0, eventRate: 'High' },
        { loyaltyId: '40001003291', issue: 'stale_profile', detail: 'Last transaction 2023-04-12, 420+ days dormant', mparticleIds: 1, weeklyTxns: 0.0, eventRate: 'None' },
        { loyaltyId: '40001098456', issue: 'multi_mparticle', detail: '3 mParticle profiles — appears to be shared household account', mparticleIds: 3, weeklyTxns: 5.1, eventRate: 'Normal' },
        { loyaltyId: '40001200112', issue: 'event_spam', detail: '12,400 page views in 7 days, 0 purchases — suspected bot', mparticleIds: 1, weeklyTxns: 0.0, eventRate: '12.4K/wk' },
        { loyaltyId: '40001054823', issue: 'anomalous_volume', detail: 'Self-checkout default card — 310 transactions in 30 days', mparticleIds: 1, weeklyTxns: 77.5, eventRate: 'Normal' },
        { loyaltyId: '40001176500', issue: 'stale_profile', detail: 'Last transaction 2022-11-30, likely relocated', mparticleIds: 2, weeklyTxns: 0.0, eventRate: 'None' },
      ],
    },
  },

  // ─── Knowledge Graph Data ─────────────────────────────────────────────────────
  knowledgeGraph: {
    nodeTypes: [
      { type: 'Product', count: 70000, displayCount: '70K', color: '#3b82f6' },
      { type: 'Shopper', count: 135000, displayCount: '135K', color: '#10b981' },
      { type: 'Transaction', count: 48000000, displayCount: '48M', color: '#f59e0b' },
      { type: 'Category', count: 1200, displayCount: '1.2K', color: '#8b5cf6' },
      { type: 'Brand', count: 4800, displayCount: '4.8K', color: '#ef4444' },
      { type: 'Ingredient', count: 12400, displayCount: '12.4K', color: '#ec4899' },
      { type: 'Nutrient', count: 68, displayCount: '68', color: '#06b6d4' },
      { type: 'Flavor', count: 24, displayCount: '24', color: '#f472b6' },
      { type: 'Household', count: 82000, displayCount: '82K', color: '#84cc16' },
    ],
    edgeTypes: [
      { type: 'purchased', from: 'Shopper', to: 'Product', count: '48M', color: '#f59e0b' },
      { type: 'contains_ingredient', from: 'Product', to: 'Ingredient', count: '890K', color: '#ec4899' },
      { type: 'belongs_to_category', from: 'Product', to: 'Category', count: '70K', color: '#8b5cf6' },
      { type: 'has_nutrient', from: 'Product', to: 'Nutrient', count: '1.2M', color: '#06b6d4' },
      { type: 'preferred_by', from: 'Product', to: 'Shopper', count: '2.1M', color: '#10b981' },
      { type: 'similar_to', from: 'Product', to: 'Product', count: '4.2M', color: '#3b82f6' },
      { type: 'member_of', from: 'Shopper', to: 'Household', count: '135K', color: '#84cc16' },
      { type: 'manufactured_by', from: 'Product', to: 'Brand', count: '70K', color: '#ef4444' },
    ],
    stats: {
      totalNodes: '48.3M',
      totalEdges: '57.4M',
      nodeTypeCount: 9,
      edgeTypeCount: 8,
      avgDegree: 2.38,
      density: 'Sparse (grocery-domain typical)',
    },
    queryExamples: [
      {
        name: 'Health-Conscious Alternatives',
        path: 'Shopper → purchased → Product → similar_to → Product (health_score > 70)',
        desc: 'Find healthier alternatives to frequently purchased products by traversing similarity edges filtered by health score.',
      },
      {
        name: 'Ingredient-Based Discovery',
        path: 'Shopper → preferred_by ← Product → contains_ingredient → Ingredient ← contains_ingredient ← Product',
        desc: 'Discover new products that share key ingredients with shopper favorites.',
      },
      {
        name: 'Household Recommendations',
        path: 'Shopper → member_of → Household ← member_of ← Shopper → purchased → Product',
        desc: 'Surface products that other household members buy but this shopper hasn\'t tried.',
      },
    ],
    graphValue: [
      { title: 'Cross-Domain Inference', desc: 'Purchase patterns + nutrition data → health trajectory insights not visible in any single data source', color: '#8b5cf6' },
      { title: 'Relationship Discovery', desc: 'Products connected through shared ingredients, nutrients, and flavor profiles enable serendipitous recommendations', color: '#3b82f6' },
      { title: 'Real-Time Personalization', desc: 'Sub-100ms graph traversals power live agent recommendations during conversations', color: '#10b981' },
      { title: 'ML Feature Generation', desc: 'Graph embeddings (Node2Vec, GNN) become features for propensity, churn, and recommender models', color: '#f59e0b' },
    ],
    dataSources: [
      { source: 'Product Catalog', creates: 'Product + Category + Brand nodes', edgesCreated: 'belongs_to_category, manufactured_by', color: 'border-blue-500', records: '70K products' },
      { source: 'Transactions & Loyalty', creates: 'Purchase edges with temporal data', edgesCreated: 'purchased (timestamp, amount, store)', color: 'border-emerald-500', records: '48M transactions' },
      { source: 'Customer Data', creates: 'Shopper nodes + demographics', edgesCreated: 'member_of (household linkage)', color: 'border-yellow-500', records: '135K shoppers' },
      { source: 'Behavioral Events', creates: 'Interaction signals + session data', edgesCreated: 'searched_for, viewed, clicked, added_to_cart', color: 'border-teal-500', records: '12M events' },
      { source: 'Enrichment Data', creates: 'Ingredient + Nutrient + Flavor nodes', edgesCreated: 'contains_ingredient, has_nutrient, flavor_profile', color: 'border-purple-500', records: '12.4K ingredients' },
    ],
  },
};

// ─── Entity Connection Graph (Data Pipeline) ───────────────────────────────────

const PipelineGraph = ({ connections }) => {
  const nodes = {
    'Shoppers':         { x: 60,  y: 55,  color: '#3b82f6' },
    'Purchase History': { x: 180, y: 30,  color: '#10b981' },
    'Products':         { x: 300, y: 55,  color: '#f59e0b' },
    'Embeddings':       { x: 420, y: 30,  color: '#8b5cf6' },
    'Agent':            { x: 500, y: 90,  color: '#ef4444' },
  };

  return (
    <svg viewBox="0 0 560 140" className="w-full h-44">
      {connections.map((conn, i) => {
        const from = nodes[conn.source];
        const to = nodes[conn.target];
        if (!from || !to) return null;
        return (
          <g key={i}>
            <line
              x1={from.x} y1={from.y} x2={to.x} y2={to.y}
              stroke={`rgba(148, 163, 184, ${conn.strength / 100})`}
              strokeWidth={Math.max(1.5, conn.strength / 30)}
            />
            <text
              x={(from.x + to.x) / 2}
              y={(from.y + to.y) / 2 - 6}
              fontSize="8"
              fill="#94a3b8"
              textAnchor="middle"
              fontFamily="monospace"
            >
              {conn.joinKey}
            </text>
          </g>
        );
      })}
      {Object.entries(nodes).map(([name, pos]) => (
        <g key={name}>
          <circle cx={pos.x} cy={pos.y} r="18" fill={pos.color} opacity="0.9" />
          <text
            x={pos.x} y={pos.y + 32}
            fontSize="9"
            fill="#cbd5e1"
            textAnchor="middle"
            fontWeight="600"
          >
            {name}
          </text>
        </g>
      ))}
    </svg>
  );
};

// ─── Knowledge Graph SVG Visualization ──────────────────────────────────────────

const KnowledgeGraphSVG = () => {
  const nodes = {
    'Product':     { x: 280, y: 80,  color: '#3b82f6' },
    'Shopper':     { x: 80,  y: 80,  color: '#10b981' },
    'Transaction': { x: 180, y: 30,  color: '#f59e0b' },
    'Category':    { x: 430, y: 30,  color: '#8b5cf6' },
    'Brand':       { x: 480, y: 110, color: '#ef4444' },
    'Ingredient':  { x: 380, y: 170, color: '#ec4899' },
    'Nutrient':    { x: 280, y: 210, color: '#06b6d4' },
    'Flavor':      { x: 180, y: 200, color: '#f472b6' },
    'Household':   { x: 60,  y: 180, color: '#84cc16' },
  };

  const edges = [
    { from: 'Shopper', to: 'Product', label: 'purchased' },
    { from: 'Product', to: 'Category', label: 'belongs_to' },
    { from: 'Product', to: 'Brand', label: 'made_by' },
    { from: 'Product', to: 'Ingredient', label: 'contains' },
    { from: 'Product', to: 'Nutrient', label: 'has_nutrient' },
    { from: 'Ingredient', to: 'Flavor', label: 'flavor' },
    { from: 'Shopper', to: 'Household', label: 'member_of' },
    { from: 'Shopper', to: 'Transaction', label: 'initiated' },
    { from: 'Transaction', to: 'Product', label: 'included' },
  ];

  return (
    <svg viewBox="0 0 560 250" className="w-full h-64">
      {edges.map((edge, i) => {
        const from = nodes[edge.from];
        const to = nodes[edge.to];
        if (!from || !to) return null;
        return (
          <g key={i}>
            <line x1={from.x} y1={from.y} x2={to.x} y2={to.y} stroke="rgba(148,163,184,0.3)" strokeWidth={1.5} />
            <text
              x={(from.x + to.x) / 2}
              y={(from.y + to.y) / 2 - 5}
              fontSize="7"
              fill="#64748b"
              textAnchor="middle"
              fontFamily="monospace"
            >
              {edge.label}
            </text>
          </g>
        );
      })}
      {Object.entries(nodes).map(([name, pos]) => (
        <g key={name}>
          <circle cx={pos.x} cy={pos.y} r="16" fill={pos.color} opacity="0.9" />
          <text x={pos.x} y={pos.y + 4} fontSize="7" fill="white" textAnchor="middle" fontWeight="600">
            {name.slice(0, 4)}
          </text>
          <text x={pos.x} y={pos.y + 28} fontSize="8" fill="#cbd5e1" textAnchor="middle" fontWeight="500">
            {name}
          </text>
        </g>
      ))}
    </svg>
  );
};

// ─── Main Dashboard ─────────────────────────────────────────────────────────────

const DataInsightsDashboard = () => {
  const [activeTab, setActiveTab] = useState('overview');
  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState([]);
  const [searchLoading, setSearchLoading] = useState(false);
  const [searchSource, setSearchSource] = useState('');
  const [activeVectorQuery, setActiveVectorQuery] = useState(0);
  const [unenrichedFilter, setUnenrichedFilter] = useState('all');
  const [unenrichedSearch, setUnenrichedSearch] = useState('');
  const [unenrichedPage, setUnenrichedPage] = useState(0);
  const UNENRICHED_PAGE_SIZE = 10;

  const filteredUnenriched = useMemo(() => {
    let items = EAGLE_DATA.catalogEnrichment.unenrichedProducts.items;
    if (unenrichedFilter !== 'all') {
      items = items.filter(p => p.reason === unenrichedFilter);
    }
    if (unenrichedSearch.trim()) {
      const q = unenrichedSearch.toLowerCase();
      items = items.filter(p =>
        p.name.toLowerCase().includes(q) ||
        p.brand.toLowerCase().includes(q) ||
        p.category.toLowerCase().includes(q) ||
        p.gtin.includes(q)
      );
    }
    return items;
  }, [unenrichedFilter, unenrichedSearch]);

  const unenrichedTotalPages = Math.max(1, Math.ceil(filteredUnenriched.length / UNENRICHED_PAGE_SIZE));
  const paginatedUnenriched = filteredUnenriched.slice(unenrichedPage * UNENRICHED_PAGE_SIZE, (unenrichedPage + 1) * UNENRICHED_PAGE_SIZE);

  // Reset page when filter/search changes
  useEffect(() => { setUnenrichedPage(0); }, [unenrichedFilter, unenrichedSearch]);

  // ─── Enrichment Explorer (Before & After) ──────────────────────────────────
  const [enrichmentSearch, setEnrichmentSearch] = useState('');
  const [enrichmentPage, setEnrichmentPage] = useState(0);
  const [enrichmentSort, setEnrichmentSort] = useState('fieldsAdded');
  const [expandedProduct, setExpandedProduct] = useState(null);
  const ENRICHMENT_PAGE_SIZE = 10;

  const filteredEnriched = useMemo(() => {
    let items = [...EAGLE_DATA.catalogEnrichment.enrichedProducts];
    if (enrichmentSearch.trim()) {
      const q = enrichmentSearch.toLowerCase();
      items = items.filter(p =>
        p.name.toLowerCase().includes(q) ||
        p.brand.toLowerCase().includes(q) ||
        p.category.toLowerCase().includes(q) ||
        p.gtin.includes(q)
      );
    }
    if (enrichmentSort === 'fieldsAdded') {
      items.sort((a, b) => b.fieldsAdded - a.fieldsAdded);
    } else {
      items.sort((a, b) => a.name.localeCompare(b.name));
    }
    return items;
  }, [enrichmentSearch, enrichmentSort]);

  const enrichmentTotalPages = Math.max(1, Math.ceil(filteredEnriched.length / ENRICHMENT_PAGE_SIZE));
  const paginatedEnriched = filteredEnriched.slice(enrichmentPage * ENRICHMENT_PAGE_SIZE, (enrichmentPage + 1) * ENRICHMENT_PAGE_SIZE);

  useEffect(() => { setEnrichmentPage(0); }, [enrichmentSearch, enrichmentSort]);

  const handleSemanticSearch = async (query) => {
    if (!query.trim()) return;
    setSearchLoading(true);
    setSearchResults([]);
    setSearchSource('');

    // Try the live Delectable AI agent endpoint first
    try {
      const res = await fetch('/api/agent', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          message: `Search for: ${query}`,
          context: { retailer: 'your-grocer', searchMode: 'vertex' },
        }),
      });
      if (res.ok) {
        const data = await res.json();
        const products = data.products || data.results || [];
        if (products.length > 0) {
          setSearchResults(products.map(p => (typeof p === 'string') ? p : (p.name || p.title || JSON.stringify(p))));
          setSearchSource('live');
          setSearchLoading(false);
          return;
        }
      }
    } catch (_) {
      // API unavailable — fall through to local keyword matching
    }

    // Fallback: keyword-matching against demo data
    const q = query.toLowerCase();
    let bestMatch = null;
    let bestScore = 0;
    EAGLE_DATA.semanticSearchDemo.forEach((d) => {
      const score = d.keywords.filter(kw => q.includes(kw)).length;
      if (score > bestScore) { bestScore = score; bestMatch = d; }
    });
    if (!bestMatch || bestScore === 0) {
      bestMatch = EAGLE_DATA.semanticSearchDemo.find(
        d => d.query.toLowerCase().includes(q) || q.includes(d.query.toLowerCase())
      );
    }
    setSearchResults(bestMatch ? bestMatch.results : ['No exact matches — try "chicken breast", "high-protein snack", or "pasta dinner"']);
    setSearchSource('demo');
    setSearchLoading(false);
  };

  const tabs = [
    { id: 'overview',           label: 'Overview',            icon: <ChartBarIcon /> },
    { id: 'pipeline',           label: 'Data Pipeline',       icon: <DatabaseIcon /> },
    { id: 'customer360',        label: 'Customer 360',        icon: <UsersIcon /> },
    { id: 'agentAnalytics',     label: 'Agent Analytics',     icon: <ActivityIcon /> },
    { id: 'vectorSearch',       label: 'Vector Search',       icon: <SearchIcon /> },
    { id: 'embeddingsProjector',label: 'Embeddings Projector',icon: <CubeIcon /> },
    { id: 'catalogEnrichment',  label: 'Catalog Enrichment',  icon: <LayersIcon /> },
    { id: 'userIntelligence',   label: 'User Intelligence',   icon: <UserCircleIcon /> },
    { id: 'knowledgeGraph',     label: 'Knowledge Graph',     icon: <GraphIcon /> },
    { id: 'agentContext',       label: 'Agent Context',       icon: <CodeIcon /> },
  ];

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900">
      {/* ── Header ──────────────────────────────────────────────────────────── */}
      <header className="py-5 px-8 sticky top-0 z-50" style={{ background: 'rgba(15,23,42,0.9)', backdropFilter: 'blur(16px)', borderBottom: '1px solid rgba(255,255,255,0.06)' }}>
        <div className="max-w-7xl mx-auto flex items-center justify-between">
          <div className="flex items-center gap-4">
            <span style={{ fontWeight: 800, fontSize: 14, padding: '6px 14px', borderRadius: 999, background: '#0F172A', color: '#fff', border: '1px solid rgba(255,255,255,0.12)', fontFamily: 'Space Grotesk, sans-serif' }}>Delectable AI</span>
            <div>
              <h1 className="text-xl font-semibold text-white" style={{ fontFamily: 'Space Grotesk, sans-serif' }}>Data Insights</h1>
              <p className="text-xs" style={{ color: '#94a3b8' }}>Grocery Agent Platform Analytics</p>
            </div>
          </div>
          <span className="ai-badge teal">Live</span>
        </div>
      </header>

      <main className="max-w-7xl mx-auto px-8 py-8">
        {/* ── Tab Navigation ────────────────────────────────────────────────── */}
        <div className="flex gap-2 mb-8 overflow-x-auto pb-2">
          {tabs.map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`flex items-center gap-2 px-4 py-2 rounded-lg font-medium transition-all whitespace-nowrap ${
                activeTab === tab.id
                  ? 'bg-teal-600 text-white shadow-lg'
                  : 'bg-white/10 text-gray-300 hover:bg-white/20'
              }`}
            >
              {tab.icon}
              {tab.label}
            </button>
          ))}
        </div>

        {/* ================================================================= */}
        {/* TAB 1 — Overview                                                  */}
        {/* ================================================================= */}
        {activeTab === 'overview' && (
          <div className="space-y-6">
            {/* Metric Cards */}
            <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
              {[
                { label: 'Products in Catalog', value: EAGLE_DATA.overview.productsInCatalog, suffix: '+', icon: <DatabaseIcon />, color: 'from-blue-500 to-blue-600' },
                { label: 'Propensity Profiles', value: EAGLE_DATA.overview.propensityProfiles, icon: <UsersIcon />, color: 'from-emerald-500 to-emerald-600' },
                { label: 'Virtual Pantries', value: EAGLE_DATA.overview.virtualPantryEstimates, icon: <CartIcon />, color: 'from-purple-500 to-purple-600' },
                { label: 'Conversations (30d)', value: EAGLE_DATA.overview.agentConversations30d, icon: <BotIcon />, color: 'from-orange-500 to-orange-600' },
                { label: 'Lists Optimized', value: EAGLE_DATA.overview.shoppingListsOptimized, icon: <SparklesIcon />, color: 'from-pink-500 to-pink-600' },
                { label: 'Personalization Rate', value: EAGLE_DATA.overview.personalizationRate, suffix: '%', icon: <ActivityIcon />, color: 'from-teal-500 to-teal-600' },
              ].map((m) => (
                <div key={m.label} className={`bg-gradient-to-br ${m.color} rounded-xl p-4 text-white shadow-lg`}>
                  <div className="flex items-center gap-2 mb-2 opacity-80">
                    {m.icon}
                    <span className="text-xs font-medium leading-tight">{m.label}</span>
                  </div>
                  <div className="text-2xl font-bold">
                    <AnimatedCounter value={m.value} suffix={m.suffix} />
                  </div>
                </div>
              ))}
            </div>

            {/* Mission Cluster Distribution */}
            <div className="bg-white/5 backdrop-blur rounded-xl p-6">
              <h3 className="text-lg font-semibold text-white mb-1">Mission Cluster Distribution</h3>
              <p className="text-gray-400 text-sm mb-5">6 shopper mission segments derived from purchase pattern clustering</p>
              <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
                {EAGLE_DATA.missionClusters.map((seg) => (
                  <div key={seg.name} className="bg-white/10 rounded-lg p-4">
                    <div className="flex items-center gap-2 mb-2">
                      <div className="w-3 h-3 rounded-full" style={{ backgroundColor: seg.color }} />
                      <span className="text-gray-300 text-sm font-medium">{seg.name}</span>
                    </div>
                    <div className="text-2xl font-bold text-white">{seg.count.toLocaleString()}</div>
                    <div className="text-gray-400 text-xs mb-2">{seg.pct}% of shoppers</div>
                    <ProgressBar value={seg.pct} max={30} color={seg.color} />
                    <p className="text-gray-500 text-xs mt-2">{seg.desc}</p>
                  </div>
                ))}
              </div>
            </div>

            {/* Platform Highlights */}
            <div className="grid md:grid-cols-3 gap-4">
              <div className="bg-gradient-to-br from-blue-600/20 to-cyan-600/20 rounded-xl p-5 border border-blue-500/30">
                <div className="text-blue-400 font-semibold mb-2">Data Foundation</div>
                <div className="text-3xl font-bold text-white mb-1">4 tables</div>
                <p className="text-gray-400 text-sm">Delectable Data Platform tables power every agent conversation: shopper profiles, product catalog, purchase history, and product embeddings.</p>
              </div>
              <div className="bg-gradient-to-br from-emerald-600/20 to-teal-600/20 rounded-xl p-5 border border-emerald-500/30">
                <div className="text-emerald-400 font-semibold mb-2">Personalization Depth</div>
                <div className="text-3xl font-bold text-white mb-1">11 dietary signals</div>
                <p className="text-gray-400 text-sm">Per-shopper propensity scores across 11 dietary dimensions power proactive filtering and alternative suggestions.</p>
              </div>
              <div className="bg-gradient-to-br from-purple-600/20 to-pink-600/20 rounded-xl p-5 border border-purple-500/30">
                <div className="text-purple-400 font-semibold mb-2">Multi-Aspect Search</div>
                <div className="text-3xl font-bold text-white mb-1">3 embedding types</div>
                <p className="text-gray-400 text-sm">Identity, nutrition, and description embeddings enable nuanced product discovery beyond simple keyword matching.</p>
              </div>
            </div>
          </div>
        )}

        {/* ================================================================= */}
        {/* TAB 2 — Data Pipeline                                             */}
        {/* ================================================================= */}
        {activeTab === 'pipeline' && (
          <div className="space-y-6">
            {/* Source Tables */}
            <div className="bg-white/5 backdrop-blur rounded-xl p-6">
              <h3 className="text-lg font-semibold text-white mb-4">Delectable Data Platform Source Tables</h3>
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                {EAGLE_DATA.pipeline.tables.map((t) => (
                  <div key={t.name} className="bg-slate-800/60 rounded-lg p-4 border border-white/10">
                    <div className="flex items-center gap-2 mb-2 text-blue-400">
                      {t.icon === 'users' && <UsersIcon />}
                      {t.icon === 'db' && <DatabaseIcon />}
                      {t.icon === 'cart' && <CartIcon />}
                      {t.icon === 'cube' && <CubeIcon />}
                      <code className="text-sm font-mono">{t.name}</code>
                    </div>
                    <div className="text-2xl font-bold text-white">{t.rows}</div>
                    <div className="text-gray-400 text-xs mt-1">{t.desc}</div>
                  </div>
                ))}
              </div>
            </div>

            {/* Entity Connection Graph */}
            <div className="bg-white/5 backdrop-blur rounded-xl p-6">
              <h3 className="text-lg font-semibold text-white mb-2">Entity Connection Graph</h3>
              <p className="text-gray-400 text-sm mb-4">
                Data flows from shopper profiles through purchase history and product catalog into embeddings, which the agent queries via VECTOR_SEARCH.
              </p>
              <div className="bg-slate-800/50 rounded-xl p-4">
                <PipelineGraph connections={EAGLE_DATA.pipeline.connections} />
              </div>
            </div>

            {/* Data Volume Badges */}
            <div className="bg-white/5 backdrop-blur rounded-xl p-6">
              <h3 className="text-lg font-semibold text-white mb-4">Data Volume Summary</h3>
              <div className="flex flex-wrap gap-3">
                {[
                  { label: '135K Shoppers', color: 'bg-blue-600' },
                  { label: '70K Products', color: 'bg-emerald-600' },
                  { label: '48M Transactions', color: 'bg-orange-600' },
                  { label: '768-dim Embeddings', color: 'bg-purple-600' },
                  { label: '2yr History Window', color: 'bg-pink-600' },
                  { label: '11 Dietary Signals', color: 'bg-cyan-600' },
                ].map((b) => (
                  <span key={b.label} className={`${b.color} text-white px-4 py-2 rounded-full text-sm font-medium`}>{b.label}</span>
                ))}
              </div>
            </div>

            {/* Join Key Details */}
            <div className="bg-white/5 backdrop-blur rounded-xl p-6">
              <h3 className="text-lg font-semibold text-white mb-4">Join Key Details</h3>
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead>
                    <tr className="text-left text-gray-400 border-b border-white/10">
                      <th className="pb-3 pr-4">Source</th>
                      <th className="pb-3 pr-4">Target</th>
                      <th className="pb-3 pr-4">Join Key</th>
                      <th className="pb-3 pr-4">Match Rate</th>
                      <th className="pb-3">Purpose</th>
                    </tr>
                  </thead>
                  <tbody className="text-gray-300">
                    {EAGLE_DATA.pipeline.connections.map((conn, i) => (
                      <tr key={i} className="border-b border-white/5">
                        <td className="py-3 pr-4">{conn.source}</td>
                        <td className="py-3 pr-4">{conn.target}</td>
                        <td className="py-3 pr-4">
                          <code className="bg-white/10 px-2 py-1 rounded text-sm font-mono">{conn.joinKey}</code>
                        </td>
                        <td className="py-3 pr-4">
                          <div className="flex items-center gap-2">
                            <ProgressBar value={conn.strength} max={100} color={conn.strength > 90 ? '#10b981' : '#f59e0b'} />
                            <span className="w-12 text-sm">{conn.strength}%</span>
                          </div>
                        </td>
                        <td className="py-3 text-sm text-gray-400">
                          {conn.source === 'Shoppers' && conn.target === 'Purchase History' && 'Link shopper to transaction history'}
                          {conn.source === 'Purchase History' && conn.target === 'Products' && 'Resolve purchased products'}
                          {conn.source === 'Products' && conn.target === 'Embeddings' && 'Multi-aspect vector representation'}
                          {conn.source === 'Embeddings' && conn.target === 'Agent' && 'Semantic search at query time'}
                          {conn.source === 'Shoppers' && conn.target === 'Agent' && 'Real-time profile + pantry lookup'}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        )}

        {/* ================================================================= */}
        {/* TAB 3 — Customer 360 (Delectable AI Shopper Profile)                   */}
        {/* ================================================================= */}
        {activeTab === 'customer360' && (
          <div className="space-y-6">
            {/* Shopper Header */}
            <div className="bg-white/5 backdrop-blur rounded-xl p-6">
              <h3 className="text-lg font-semibold text-white mb-4">Delectable AI Shopper Profile</h3>
              <div className="grid md:grid-cols-4 gap-4">
                <div className="bg-white/10 rounded-lg p-4">
                  <div className="text-gray-400 text-sm mb-1">Shopper ID</div>
                  <div className="text-white font-mono text-lg">{EAGLE_DATA.shopper.id}</div>
                </div>
                <div className="bg-white/10 rounded-lg p-4">
                  <div className="text-gray-400 text-sm mb-1">Mission Cluster</div>
                  <div className="text-purple-400 font-semibold">{EAGLE_DATA.shopper.missionCluster}</div>
                  <div className="text-gray-500 text-xs">Cluster {EAGLE_DATA.shopper.clusterNumber} of 6</div>
                </div>
                <div className="bg-white/10 rounded-lg p-4">
                  <div className="text-gray-400 text-sm mb-1">Loyalty Tier</div>
                  <div className="text-yellow-400 font-semibold">{EAGLE_DATA.shopper.loyaltyTier}</div>
                </div>
                <div className="bg-white/10 rounded-lg p-4">
                  <div className="text-gray-400 text-sm mb-1">Dietary Dimensions</div>
                  <div className="text-white font-semibold">11 propensity scores</div>
                </div>
              </div>
            </div>

            {/* Dietary Propensity Scores */}
            <div className="bg-white/5 backdrop-blur rounded-xl p-6">
              <h3 className="text-lg font-semibold text-white mb-1">Dietary Propensity Scores</h3>
              <p className="text-gray-400 text-sm mb-4">Per-shopper scores (0-1) derived from 2-year purchase history</p>
              <div className="space-y-3">
                {EAGLE_DATA.shopper.dietaryScores.map((d) => {
                  const barColor = d.score >= 0.7 ? '#10b981' : d.score >= 0.4 ? '#f59e0b' : '#64748b';
                  return (
                    <div key={d.label} className="flex items-center gap-4">
                      <div className="w-32 text-gray-300 text-sm font-mono">{d.label}</div>
                      <div className="flex-1 bg-slate-700 rounded-full h-5 overflow-hidden">
                        <div
                          className="h-full rounded-full flex items-center justify-end pr-2 transition-all duration-700"
                          style={{ width: `${d.score * 100}%`, backgroundColor: barColor }}
                        >
                          <span className="text-xs font-bold text-white">{d.score.toFixed(2)}</span>
                        </div>
                      </div>
                      <div className="w-16 text-right">
                        {d.score >= 0.7 && <span className="text-emerald-400 text-xs font-semibold">HIGH</span>}
                        {d.score >= 0.4 && d.score < 0.7 && <span className="text-yellow-400 text-xs font-semibold">MED</span>}
                        {d.score < 0.4 && <span className="text-gray-500 text-xs font-semibold">LOW</span>}
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>

            {/* Virtual Pantry */}
            <div className="bg-white/5 backdrop-blur rounded-xl p-6">
              <h3 className="text-lg font-semibold text-white mb-1">Virtual Pantry Snapshot</h3>
              <p className="text-gray-400 text-sm mb-4">Estimated stock levels based on purchase frequency and typical consumption rates</p>
              <div className="grid md:grid-cols-5 gap-4">
                {EAGLE_DATA.shopper.pantry.map((item) => {
                  const stockColor = item.stock >= 0.5 ? '#10b981' : item.stock >= 0.2 ? '#f59e0b' : '#ef4444';
                  const stockLabel = item.stock >= 0.5 ? 'In Stock' : item.stock >= 0.2 ? 'Running Low' : 'Likely Out';
                  return (
                    <div key={item.name} className="bg-slate-800/60 rounded-lg p-4 border border-white/10">
                      <div className="text-white font-medium mb-2">{item.name}</div>
                      <div className="flex items-center gap-2 mb-1">
                        <ProgressBar value={item.stock} max={1} color={stockColor} height="h-3" />
                        <span className="text-sm text-white font-mono w-10 text-right">{(item.stock * 100).toFixed(0)}%</span>
                      </div>
                      <div className="text-xs mt-1" style={{ color: stockColor }}>{stockLabel}</div>
                    </div>
                  );
                })}
              </div>
            </div>

            {/* AI Insight */}
            <div className="bg-gradient-to-r from-blue-600/20 to-purple-600/20 rounded-xl p-5 border border-blue-500/30">
              <div className="flex items-center gap-2 text-blue-400 mb-3">
                <BotIcon />
                <span className="font-semibold">AI Personalization Insight</span>
              </div>
              <p className="text-gray-300 text-sm leading-relaxed">
                High propensity for <span className="text-emerald-400 font-medium">organic</span> (0.91),
                <span className="text-emerald-400 font-medium"> gluten_free</span> (0.78), and
                <span className="text-emerald-400 font-medium"> high_protein</span> (0.89).
                The agent will prioritize organic products in search results, flag gluten-containing items with warnings,
                and proactively suggest protein-rich alternatives. Virtual pantry shows
                <span className="text-red-400 font-medium"> Greek Yogurt</span> and
                <span className="text-red-400 font-medium"> Chicken Breast</span> are likely depleted —
                these will be auto-suggested for replenishment.
              </p>
            </div>
          </div>
        )}

        {/* ================================================================= */}
        {/* TAB 4 — Agent Analytics                                           */}
        {/* ================================================================= */}
        {activeTab === 'agentAnalytics' && (
          <div className="space-y-6">
            {/* Top-level KPIs */}
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              {[
                { label: 'eagle_ai_searches', value: EAGLE_DATA.agentAnalytics.searches, sub: 'Total searches logged', color: 'from-blue-500 to-blue-600' },
                { label: 'eagle_ai_selections', value: EAGLE_DATA.agentAnalytics.selections, sub: `${EAGLE_DATA.agentAnalytics.addToCartRate}% add-to-cart rate`, color: 'from-emerald-500 to-emerald-600' },
                { label: 'eagle_ai_conversations', value: EAGLE_DATA.agentAnalytics.conversations, sub: `Avg ${EAGLE_DATA.agentAnalytics.avgTurns} turns / convo`, color: 'from-purple-500 to-purple-600' },
                { label: 'Personalization Rate', value: EAGLE_DATA.agentAnalytics.personalizationRate, suffix: '%', sub: 'Use at least 1 signal', color: 'from-teal-500 to-teal-600' },
              ].map((m) => (
                <div key={m.label} className={`bg-gradient-to-br ${m.color} rounded-xl p-5 text-white shadow-lg`}>
                  <div className="text-xs font-mono opacity-80 mb-1">{m.label}</div>
                  <div className="text-3xl font-bold">
                    <AnimatedCounter value={m.value} suffix={m.suffix} />
                  </div>
                  <div className="text-sm opacity-70 mt-1">{m.sub}</div>
                </div>
              ))}
            </div>

            {/* Conversation Stats */}
            <div className="grid md:grid-cols-3 gap-4">
              <div className="bg-white/5 backdrop-blur rounded-xl p-5">
                <div className="text-gray-400 text-sm mb-1">Avg Turns per Conversation</div>
                <div className="text-4xl font-bold text-white">{EAGLE_DATA.agentAnalytics.avgTurns}</div>
                <div className="text-gray-500 text-xs mt-1">User messages per session</div>
              </div>
              <div className="bg-white/5 backdrop-blur rounded-xl p-5">
                <div className="text-gray-400 text-sm mb-1">Avg Tool Calls per Conversation</div>
                <div className="text-4xl font-bold text-white">{EAGLE_DATA.agentAnalytics.avgToolCalls}</div>
                <div className="text-gray-500 text-xs mt-1">Agent function invocations</div>
              </div>
              <div className="bg-white/5 backdrop-blur rounded-xl p-5">
                <div className="text-gray-400 text-sm mb-1">Add-to-Cart Rate</div>
                <div className="text-4xl font-bold text-emerald-400">{EAGLE_DATA.agentAnalytics.addToCartRate}%</div>
                <div className="text-gray-500 text-xs mt-1">Selections resulting in cart add</div>
              </div>
            </div>

            {/* Tool Call Distribution */}
            <div className="bg-white/5 backdrop-blur rounded-xl p-6">
              <h3 className="text-lg font-semibold text-white mb-4">Tool Call Distribution</h3>
              <div className="space-y-4">
                {EAGLE_DATA.agentAnalytics.toolBreakdown.map((t) => (
                  <div key={t.tool} className="flex items-center gap-4">
                    <div className="w-48 text-gray-300 text-sm font-mono">{t.tool}</div>
                    <div className="flex-1 bg-slate-700 rounded-full h-7 overflow-hidden">
                      <div
                        className="h-full rounded-full flex items-center px-3 transition-all duration-700"
                        style={{ width: `${t.pct}%`, backgroundColor: t.color }}
                      >
                        <span className="text-xs font-bold text-white">{t.pct}%</span>
                      </div>
                    </div>
                    <div className="w-20 text-right text-gray-400 text-sm">{t.calls.toLocaleString()}</div>
                  </div>
                ))}
              </div>
            </div>

            {/* Logging Tables Summary */}
            <div className="bg-white/5 backdrop-blur rounded-xl p-6">
              <h3 className="text-lg font-semibold text-white mb-4">Platform Logging Tables</h3>
              <div className="grid md:grid-cols-3 gap-4">
                {[
                  {
                    table: 'eagle_ai_searches',
                    rows: '48,200',
                    desc: 'Every product search the agent executes, with query text, embedding type used, result count, and latency.',
                    fields: ['search_id', 'shopper_id', 'query', 'embedding_type', 'result_count', 'latency_ms'],
                    color: 'border-blue-500',
                  },
                  {
                    table: 'eagle_ai_selections',
                    rows: '31,400',
                    desc: 'Products selected or added to cart from agent suggestions, including position rank and personalization signals.',
                    fields: ['selection_id', 'search_id', 'product_id', 'position', 'added_to_cart', 'signals_used'],
                    color: 'border-emerald-500',
                  },
                  {
                    table: 'eagle_ai_conversations',
                    rows: '12,400',
                    desc: 'Full conversation metadata: turn count, tool calls, duration, and personalization coverage.',
                    fields: ['conversation_id', 'shopper_id', 'turns', 'tool_calls', 'duration_sec', 'personalized'],
                    color: 'border-purple-500',
                  },
                ].map((t) => (
                  <div key={t.table} className={`bg-slate-800/50 rounded-lg p-4 border-l-4 ${t.color}`}>
                    <code className="text-white font-semibold text-sm">{t.table}</code>
                    <div className="text-gray-400 text-xs mt-1 mb-2">{t.rows} rows</div>
                    <p className="text-gray-400 text-sm mb-3">{t.desc}</p>
                    <div className="flex flex-wrap gap-1">
                      {t.fields.map((f) => (
                        <span key={f} className="bg-white/10 text-gray-300 px-2 py-0.5 rounded text-xs font-mono">{f}</span>
                      ))}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}

        {/* ================================================================= */}
        {/* TAB 5 — Vector Search                                             */}
        {/* ================================================================= */}
        {activeTab === 'vectorSearch' && (
          <div className="space-y-6">
            {/* Embedding Type Cards */}
            <div className="bg-white/5 backdrop-blur rounded-xl p-6">
              <h3 className="text-lg font-semibold text-white mb-1 flex items-center gap-2">
                <SparklesIcon />
                Multi-Aspect Embedding Search
              </h3>
              <p className="text-gray-400 text-sm mb-5">Three complementary embedding types power nuanced product discovery via Delectable VECTOR_SEARCH</p>
              <div className="grid md:grid-cols-3 gap-4">
                {EAGLE_DATA.vectorSearch.embeddingTypes.map((emb) => (
                  <div key={emb.name} className={`bg-gradient-to-br ${emb.color} rounded-xl p-5 text-white border ${emb.borderColor}`}>
                    <div className="flex items-center gap-2 mb-2">
                      <CubeIcon />
                      <span className="font-bold">{emb.name}</span>
                    </div>
                    <div className="text-sm opacity-90 mb-3">{emb.dim}d vector</div>
                    <div className="text-sm mb-2">
                      <span className="opacity-70">Fields: </span>{emb.fields}
                    </div>
                    <p className="text-sm opacity-80">{emb.purpose}</p>
                  </div>
                ))}
              </div>
            </div>

            {/* Interactive Search Demo */}
            <div className="bg-white/5 backdrop-blur rounded-xl p-6">
              <h3 className="text-lg font-semibold text-white mb-4">Try a Search</h3>
              <div className="flex gap-2 mb-4">
                <input
                  type="text"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  onKeyPress={(e) => e.key === 'Enter' && handleSemanticSearch(searchQuery)}
                  placeholder='Try: "marinated chicken breast", "high-protein snack", "pasta dinner"'
                  className="flex-1 bg-white/10 border border-white/20 rounded-lg px-4 py-3 text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-teal-500"
                />
                <button
                  onClick={() => handleSemanticSearch(searchQuery)}
                  disabled={searchLoading}
                  className={`text-white px-6 py-3 rounded-lg font-medium transition-colors ${searchLoading ? 'bg-gray-600 cursor-wait' : 'bg-teal-600 hover:bg-teal-700'}`}
                >
                  {searchLoading ? 'Searching...' : 'Search'}
                </button>
              </div>

              {searchLoading && (
                <div className="bg-white/10 rounded-lg p-4 mb-4 flex items-center gap-3">
                  <div className="w-4 h-4 border-2 border-teal-500 border-t-transparent rounded-full animate-spin" />
                  <span className="text-gray-400 text-sm">Querying Delectable AI agent endpoint...</span>
                </div>
              )}

              {searchResults.length > 0 && !searchLoading && (
                <div className="bg-white/10 rounded-lg p-4 mb-4">
                  <div className="flex items-center justify-between mb-3">
                    <div className="text-gray-400 text-sm">Semantic Search Results:</div>
                    {searchSource && (
                      <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${
                        searchSource === 'live'
                          ? 'bg-emerald-600/30 text-emerald-400'
                          : 'bg-amber-600/30 text-amber-400'
                      }`}>
                        {searchSource === 'live' ? 'Live API' : 'Demo Fallback'}
                      </span>
                    )}
                  </div>
                  <div className="flex flex-wrap gap-2">
                    {searchResults.map((r, i) => (
                      <span key={`${r}-${i}`} className="bg-green-600/30 text-green-300 px-4 py-2 rounded-lg">{r}</span>
                    ))}
                  </div>
                </div>
              )}
            </div>

            {/* Example Queries with Multi-Aspect Scores */}
            <div className="bg-white/5 backdrop-blur rounded-xl p-6">
              <h3 className="text-lg font-semibold text-white mb-4">Multi-Aspect Search Results</h3>
              <div className="flex gap-2 mb-4">
                {EAGLE_DATA.vectorSearch.exampleQueries.map((eq, i) => (
                  <button
                    key={i}
                    onClick={() => setActiveVectorQuery(i)}
                    className={`px-4 py-2 rounded-lg text-sm font-medium transition-all ${
                      activeVectorQuery === i
                        ? 'bg-teal-600 text-white'
                        : 'bg-white/10 text-gray-300 hover:bg-white/20'
                    }`}
                  >
                    "{eq.query}"
                  </button>
                ))}
              </div>

              {(() => {
                const eq = EAGLE_DATA.vectorSearch.exampleQueries[activeVectorQuery];
                return (
                  <div>
                    <div className="flex items-center gap-2 mb-3 text-gray-400 text-sm">
                      <span>Primary embedding: </span>
                      <span className={`px-2 py-0.5 rounded text-xs font-semibold ${
                        eq.primary === 'Nutrition' ? 'bg-emerald-600 text-white' :
                        eq.primary === 'Description' ? 'bg-purple-600 text-white' :
                        'bg-blue-600 text-white'
                      }`}>{eq.primary}</span>
                    </div>
                    <div className="overflow-x-auto">
                      <table className="w-full">
                        <thead>
                          <tr className="text-left text-gray-400 border-b border-white/10 text-sm">
                            <th className="pb-2 pr-4">Product</th>
                            <th className="pb-2 pr-4 text-center">Identity</th>
                            <th className="pb-2 pr-4 text-center">Nutrition</th>
                            <th className="pb-2 text-center">Description</th>
                          </tr>
                        </thead>
                        <tbody className="text-gray-300">
                          {eq.results.map((r, ri) => (
                            <tr key={ri} className="border-b border-white/5">
                              <td className="py-3 pr-4">
                                <div className="flex items-center gap-2">
                                  <span className="w-6 h-6 bg-teal-600 rounded-full flex items-center justify-center text-white text-xs font-bold">{ri + 1}</span>
                                  <span className="text-white font-medium">{r.name}</span>
                                </div>
                              </td>
                              {['identity', 'nutrition', 'description'].map((dim) => {
                                const val = r[dim];
                                const isPrimary = dim.charAt(0).toUpperCase() + dim.slice(1) === eq.primary;
                                return (
                                  <td key={dim} className="py-3 pr-4">
                                    <div className="flex items-center gap-2 justify-center">
                                      <div className="w-20">
                                        <ProgressBar
                                          value={val}
                                          max={1}
                                          color={isPrimary ? '#ef4444' : '#64748b'}
                                          height="h-2"
                                        />
                                      </div>
                                      <span className={`text-sm font-mono ${isPrimary ? 'text-red-400 font-bold' : ''}`}>
                                        {val.toFixed(2)}
                                      </span>
                                    </div>
                                  </td>
                                );
                              })}
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  </div>
                );
              })()}
            </div>

            {/* How It Works */}
            <div className="bg-white/5 backdrop-blur rounded-xl p-6">
              <h3 className="text-lg font-semibold text-white mb-4">How It Works</h3>
              <div className="grid md:grid-cols-5 gap-4">
                {[
                  { step: '1', title: 'User Query', desc: 'Natural language search input from the shopper', color: 'bg-gray-600' },
                  { step: '2', title: 'text-embedding-005', desc: 'Query converted to 768-dim vector via Delectable AI Platform', color: 'bg-blue-600' },
                  { step: '3', title: 'VECTOR_SEARCH', desc: 'Cosine similarity across 3 embedding types', color: 'bg-purple-600' },
                  { step: '4', title: 'Dietary Re-rank', desc: 'Results re-ranked by shopper dietary propensities', color: 'bg-emerald-600' },
                  { step: '5', title: 'Results', desc: 'Personalized, scored product recommendations', color: 'bg-teal-600' },
                ].map((s, i) => (
                  <div key={s.step} className="flex flex-col items-center text-center">
                    <div className={`w-12 h-12 ${s.color} rounded-full flex items-center justify-center text-white text-lg font-bold mb-2`}>
                      {s.step}
                    </div>
                    <div className="text-white font-medium text-sm mb-1">{s.title}</div>
                    <p className="text-gray-400 text-xs">{s.desc}</p>
                    {i < 4 && (
                      <div className="hidden md:block text-gray-500 mt-2">
                        <ArrowRightIcon />
                      </div>
                    )}
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}

        {/* ================================================================= */}
        {/* TAB 5.5 — Embeddings Projector (3D point cloud)                   */}
        {/* ================================================================= */}
        {activeTab === 'embeddingsProjector' && window.EmbeddingsProjector && (
          <window.EmbeddingsProjector />
        )}

        {/* ================================================================= */}
        {/* TAB 6 — Food Intelligence                                         */}
        {/* ================================================================= */}
        {activeTab === 'catalogEnrichment' && (
          <div className="space-y-6">
            {/* ── Coverage Impact Hero ──────────────────────────────────────── */}
            <div className="bg-gradient-to-r from-emerald-600/20 to-cyan-600/20 backdrop-blur rounded-xl p-6 border border-emerald-500/30">
              <h3 className="text-xl font-bold text-white mb-2">Catalog Enrichment Impact</h3>
              <p className="text-gray-400 text-sm mb-5">How Delectable AI transformed Acme Grocer's raw product catalog into an intelligence-rich data asset</p>
              <div className="grid grid-cols-3 gap-6 mb-6">
                <div className="text-center">
                  <div className="text-5xl font-bold text-emerald-400"><AnimatedCounter value={91} suffix="%" /></div>
                  <div className="text-gray-300 font-medium mt-1">Catalog Enriched</div>
                  <div className="text-gray-500 text-sm">{EAGLE_DATA.catalogEnrichment.coverageImpact.enrichedCount.toLocaleString()} of 70,000 products</div>
                </div>
                <div className="text-center">
                  <div className="text-5xl font-bold text-blue-400"><AnimatedCounter value={34} /></div>
                  <div className="text-gray-300 font-medium mt-1">Avg New Data Points</div>
                  <div className="text-gray-500 text-sm">Per product across all enrichment layers</div>
                </div>
                <div className="text-center">
                  <div className="text-5xl font-bold text-amber-400"><AnimatedCounter value={6300} /></div>
                  <div className="text-gray-300 font-medium mt-1">Products Untouched</div>
                  <div className="text-gray-500 text-sm">{EAGLE_DATA.catalogEnrichment.coverageImpact.untouchedPct}% — mostly discontinued or pending</div>
                </div>
              </div>

              {/* Untouched Reasons */}
              <div className="grid grid-cols-4 gap-3 mb-6">
                {EAGLE_DATA.catalogEnrichment.coverageImpact.untouchedReasons.map((r) => (
                  <div key={r.reason} className="bg-white/5 rounded-lg p-3 text-center">
                    <div className="text-amber-400 font-bold text-lg">{r.count.toLocaleString()}</div>
                    <div className="text-gray-400 text-xs">{r.reason}</div>
                  </div>
                ))}
              </div>

              {/* Before / After Comparison */}
              <div className="grid grid-cols-2 gap-4">
                <div className="bg-red-600/10 border border-red-500/20 rounded-lg p-4">
                  <div className="text-red-400 font-semibold text-sm mb-2">Before Enrichment</div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <div className="text-2xl font-bold text-white">{EAGLE_DATA.catalogEnrichment.coverageImpact.beforeAfter.before.avgFields}</div>
                      <div className="text-gray-400 text-xs">avg fields per product</div>
                    </div>
                    <div>
                      <div className="text-2xl font-bold text-white">{(EAGLE_DATA.catalogEnrichment.coverageImpact.beforeAfter.before.totalDataPoints / 1000).toFixed(0)}K</div>
                      <div className="text-gray-400 text-xs">total data points</div>
                    </div>
                  </div>
                </div>
                <div className="bg-emerald-600/10 border border-emerald-500/20 rounded-lg p-4">
                  <div className="text-emerald-400 font-semibold text-sm mb-2">After Enrichment</div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <div className="text-2xl font-bold text-white">{EAGLE_DATA.catalogEnrichment.coverageImpact.beforeAfter.after.avgFields}</div>
                      <div className="text-gray-400 text-xs">avg fields per product</div>
                    </div>
                    <div>
                      <div className="text-2xl font-bold text-white">{(EAGLE_DATA.catalogEnrichment.coverageImpact.beforeAfter.after.totalDataPoints / 1000000).toFixed(2)}M</div>
                      <div className="text-gray-400 text-xs">total data points</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            {/* ── Enrichment Layers Waterfall ───────────────────────────────── */}
            <div className="bg-white/5 backdrop-blur rounded-xl p-6">
              <h3 className="text-lg font-semibold text-white mb-1">Enrichment Layers</h3>
              <p className="text-gray-400 text-sm mb-5">Six progressive layers of intelligence applied to the catalog — each layer builds on the previous</p>
              <div className="space-y-3">
                {EAGLE_DATA.catalogEnrichment.enrichmentLayers.map((layer) => (
                  <div key={layer.layer} className="flex items-center gap-4">
                    <div className="w-8 h-8 rounded-full flex items-center justify-center text-white text-sm font-bold shrink-0" style={{ backgroundColor: layer.color }}>
                      {layer.layer}
                    </div>
                    <div className="w-48 shrink-0">
                      <div className="text-white text-sm font-medium">{layer.name}</div>
                      <div className="text-gray-500 text-xs">{layer.desc}</div>
                    </div>
                    <div className="flex-1 bg-slate-700 rounded-full h-7 overflow-hidden">
                      <div
                        className="h-full rounded-full flex items-center justify-end pr-3 transition-all duration-1000"
                        style={{ width: `${(layer.count / 70000) * 100}%`, backgroundColor: layer.color }}
                      >
                        <span className="text-xs font-bold text-white">{layer.count.toLocaleString()}</span>
                      </div>
                    </div>
                    <div className="w-16 text-right text-gray-400 text-sm">{((layer.count / 70000) * 100).toFixed(0)}%</div>
                  </div>
                ))}
              </div>
            </div>

            {/* ── Food vs Non-Food Enrichment Breakdown ─────────────────────── */}
            <div className="bg-white/5 backdrop-blur rounded-xl p-6">
              <h3 className="text-lg font-semibold text-white mb-1">Catalog Composition & Enrichment Tiers</h3>
              <p className="text-gray-400 text-sm mb-5">Acme Grocer's catalog spans food, health & wellness, and non-food — each tier receives tailored enrichments</p>
              <div className="grid md:grid-cols-3 gap-6">
                {EAGLE_DATA.catalogEnrichment.catalogBreakdown.map((tier) => (
                  <div key={tier.tier} className="bg-slate-800/60 rounded-xl p-5 border border-white/10">
                    <div className="flex items-center justify-between mb-3">
                      <h4 className="text-white font-semibold">{tier.tier}</h4>
                      <span className="text-2xl font-bold" style={{ color: tier.color }}>{tier.pct}%</span>
                    </div>
                    <div className="text-gray-400 text-sm mb-3">{tier.count.toLocaleString()} products</div>
                    <ProgressBar value={tier.pct} max={100} color={tier.color} height="h-2" />
                    <div className="flex flex-wrap gap-1.5 mt-4 mb-4">
                      {tier.enrichments.map((e) => (
                        <span key={e} className="bg-white/10 text-gray-300 px-2 py-0.5 rounded text-xs">{e}</span>
                      ))}
                    </div>
                    <div className="space-y-2">
                      {tier.examples.map((ex) => (
                        <div key={ex.name} className="bg-white/5 rounded-lg p-2.5">
                          <div className="flex items-center justify-between">
                            <span className="text-white text-sm font-medium">{ex.name}</span>
                            <span className="text-xs font-mono" style={{ color: tier.color }}>{ex.dataPoints} pts</span>
                          </div>
                          <div className="text-gray-500 text-xs mt-0.5">{ex.note}</div>
                        </div>
                      ))}
                    </div>
                  </div>
                ))}
              </div>
            </div>

            {/* ── How Enrichments Drive Value ───────────────────────────────── */}
            <div className="bg-gradient-to-r from-blue-600/20 to-purple-600/20 backdrop-blur rounded-xl p-6 border border-blue-500/30">
              <h3 className="text-xl font-bold text-white mb-2">How Enrichments Drive Value</h3>
              <p className="text-gray-400 text-sm mb-5">Each enrichment layer translates directly into measurable business outcomes across personalization, advertising, and operational efficiency</p>
              <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-4">
                {EAGLE_DATA.catalogEnrichment.valueDrivers.map((driver) => (
                  <div key={driver.name} className="bg-white/5 rounded-lg p-4">
                    <div className="flex items-center gap-2 mb-2">
                      <div className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: driver.color }} />
                      <span className="text-white font-semibold text-sm">{driver.name}</span>
                    </div>
                    <p className="text-gray-400 text-sm mb-2">{driver.desc}</p>
                    <div className="text-xs font-mono px-2 py-1 rounded bg-white/10 inline-block" style={{ color: driver.color }}>
                      {driver.metric}
                    </div>
                  </div>
                ))}
              </div>
            </div>

            {/* ── Enrichment Explorer — Before & After ─────────────────────── */}
            <div className="bg-white/5 backdrop-blur rounded-xl p-6">
              <h3 className="text-lg font-semibold text-white mb-1">Enrichment Explorer — Before & After</h3>
              <p className="text-gray-400 text-sm mb-5">
                Browse the top enriched products by enrichment gain, or search for a specific product
                to see a side-by-side comparison of raw catalog data vs. enriched intelligence.
              </p>

              {/* Search + Sort controls */}
              <div className="flex gap-3 mb-4">
                <input
                  type="text"
                  value={enrichmentSearch}
                  onChange={(e) => setEnrichmentSearch(e.target.value)}
                  placeholder="Search by product name, brand, category, or GTIN..."
                  className="flex-1 bg-white/10 border border-white/20 rounded-lg px-4 py-2.5 text-white text-sm placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-emerald-500"
                />
                <select
                  value={enrichmentSort}
                  onChange={(e) => setEnrichmentSort(e.target.value)}
                  className="bg-white/10 border border-white/20 rounded-lg px-4 py-2.5 text-white text-sm focus:outline-none focus:ring-2 focus:ring-emerald-500 cursor-pointer pr-8"
                >
                  <option value="fieldsAdded" style={{ background: '#1e293b' }}>Most Enriched First</option>
                  <option value="alpha" style={{ background: '#1e293b' }}>Alphabetical</option>
                </select>
                {enrichmentSearch && (
                  <button
                    onClick={() => setEnrichmentSearch('')}
                    className="bg-white/10 hover:bg-white/20 text-gray-300 px-4 py-2.5 rounded-lg text-sm transition-colors"
                  >
                    Clear
                  </button>
                )}
              </div>

              {/* Results count */}
              <div className="flex items-center justify-between mb-3">
                <div className="text-gray-500 text-xs">
                  Showing {Math.min(enrichmentPage * ENRICHMENT_PAGE_SIZE + 1, filteredEnriched.length)}–{Math.min((enrichmentPage + 1) * ENRICHMENT_PAGE_SIZE, filteredEnriched.length)} of {filteredEnriched.length} products
                  {enrichmentSearch && <span> matching &ldquo;<span className="text-gray-300">{enrichmentSearch}</span>&rdquo;</span>}
                </div>
                <div className="text-gray-500 text-xs">
                  Page {enrichmentPage + 1} of {enrichmentTotalPages}
                </div>
              </div>

              {/* Product cards */}
              <div className="space-y-3">
                {paginatedEnriched.length === 0 ? (
                  <div className="py-8 text-center text-gray-500">No products match your search</div>
                ) : paginatedEnriched.map((product) => {
                  const isExpanded = expandedProduct === product.gtin;
                  const beforeKeys = Object.keys(product.before);
                  const afterKeys = Object.keys(product.after);
                  const newKeys = afterKeys.filter(k => !beforeKeys.includes(k));
                  const tierColors = {
                    food:    { bg: 'bg-emerald-500/20', text: 'text-emerald-400', label: 'Food & Grocery' },
                    health:  { bg: 'bg-purple-500/20',  text: 'text-purple-400',  label: 'Health & Wellness' },
                    nonFood: { bg: 'bg-amber-500/20',   text: 'text-amber-400',   label: 'Non-Food' },
                  };
                  const tc = tierColors[product.tier] || tierColors.food;

                  return (
                    <div key={product.gtin} className={`bg-white/5 rounded-lg border transition-all ${isExpanded ? 'border-emerald-500/30' : 'border-white/10 hover:border-white/20'}`}>
                      {/* Card header */}
                      <button
                        onClick={() => setExpandedProduct(isExpanded ? null : product.gtin)}
                        className="w-full flex items-center gap-4 p-4 text-left"
                      >
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center gap-2 mb-1">
                            <span className="text-white font-medium text-sm truncate">{product.name}</span>
                            <span className={`${tc.bg} ${tc.text} px-2 py-0.5 rounded text-xs font-medium shrink-0`}>
                              {tc.label}
                            </span>
                          </div>
                          <div className="text-gray-500 text-xs">{product.brand} &middot; {product.category}</div>
                        </div>
                        <div className="text-right shrink-0">
                          <div className="flex items-center gap-2 text-sm">
                            <span className="text-red-400 font-mono">{beforeKeys.length}</span>
                            <span className="text-gray-600">&rarr;</span>
                            <span className="text-emerald-400 font-mono">{afterKeys.length}</span>
                          </div>
                          <div className="text-xs text-emerald-400 font-medium">+{product.fieldsAdded} fields</div>
                        </div>
                        <svg className={`w-5 h-5 text-gray-500 transition-transform shrink-0 ${isExpanded ? 'rotate-180' : ''}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                        </svg>
                      </button>

                      {/* Expanded: side-by-side before / after */}
                      {isExpanded && (
                        <div className="px-4 pb-4">
                          <div className="grid md:grid-cols-2 gap-4">
                            {/* BEFORE column */}
                            <div className="bg-red-600/10 border border-red-500/20 rounded-lg p-4">
                              <div className="text-red-400 font-semibold text-sm mb-3 flex items-center gap-2">
                                <span>Before Enrichment</span>
                                <span className="bg-red-500/20 text-red-400 px-2 py-0.5 rounded text-xs">{beforeKeys.length} fields</span>
                              </div>
                              <div className="space-y-1.5">
                                {beforeKeys.map(key => (
                                  <div key={key} className="flex items-start gap-2 text-xs">
                                    <span className="text-gray-500 font-mono shrink-0 w-36 truncate" title={key}>{key}</span>
                                    <span className="text-gray-300 break-all">
                                      {typeof product.before[key] === 'object'
                                        ? JSON.stringify(product.before[key])
                                        : String(product.before[key])}
                                    </span>
                                  </div>
                                ))}
                              </div>
                            </div>

                            {/* AFTER column */}
                            <div className="bg-emerald-600/10 border border-emerald-500/20 rounded-lg p-4">
                              <div className="text-emerald-400 font-semibold text-sm mb-3 flex items-center gap-2">
                                <span>After Enrichment</span>
                                <span className="bg-emerald-500/20 text-emerald-400 px-2 py-0.5 rounded text-xs">{afterKeys.length} fields</span>
                                <span className="bg-emerald-500/20 text-emerald-300 px-2 py-0.5 rounded text-xs">+{newKeys.length} new</span>
                              </div>
                              <div className="space-y-1.5">
                                {afterKeys.map(key => {
                                  const isNew = !beforeKeys.includes(key);
                                  const val = product.after[key];
                                  return (
                                    <div key={key} className={`flex items-start gap-2 text-xs ${isNew ? 'bg-emerald-500/10 -mx-1 px-1 py-0.5 rounded' : ''}`}>
                                      <span className={`font-mono shrink-0 w-36 truncate ${isNew ? 'text-emerald-400' : 'text-gray-500'}`} title={key}>{key}</span>
                                      <span className={`break-all flex-1 ${isNew ? 'text-emerald-300' : 'text-gray-300'}`}>
                                        {typeof val === 'object'
                                          ? (Array.isArray(val) ? val.join(', ') : JSON.stringify(val))
                                          : String(val)}
                                      </span>
                                      {isNew && <span className="text-emerald-500 text-[10px] font-bold shrink-0 uppercase">new</span>}
                                    </div>
                                  );
                                })}
                              </div>
                            </div>
                          </div>
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>

              {/* Pagination */}
              {enrichmentTotalPages > 1 && (
                <div className="flex items-center justify-center gap-2 mt-4">
                  <button onClick={() => setEnrichmentPage(0)} disabled={enrichmentPage === 0}
                    className={`px-3 py-1.5 rounded text-xs font-medium transition-colors ${enrichmentPage === 0 ? 'bg-white/5 text-gray-600 cursor-not-allowed' : 'bg-white/10 text-gray-300 hover:bg-white/20'}`}>
                    First
                  </button>
                  <button onClick={() => setEnrichmentPage(Math.max(0, enrichmentPage - 1))} disabled={enrichmentPage === 0}
                    className={`px-3 py-1.5 rounded text-xs font-medium transition-colors ${enrichmentPage === 0 ? 'bg-white/5 text-gray-600 cursor-not-allowed' : 'bg-white/10 text-gray-300 hover:bg-white/20'}`}>
                    Prev
                  </button>
                  {Array.from({ length: enrichmentTotalPages }, (_, i) => (
                    <button key={i} onClick={() => setEnrichmentPage(i)}
                      className={`w-8 h-8 rounded text-xs font-bold transition-colors ${enrichmentPage === i ? 'bg-emerald-600 text-white' : 'bg-white/10 text-gray-300 hover:bg-white/20'}`}>
                      {i + 1}
                    </button>
                  ))}
                  <button onClick={() => setEnrichmentPage(Math.min(enrichmentTotalPages - 1, enrichmentPage + 1))} disabled={enrichmentPage === enrichmentTotalPages - 1}
                    className={`px-3 py-1.5 rounded text-xs font-medium transition-colors ${enrichmentPage === enrichmentTotalPages - 1 ? 'bg-white/5 text-gray-600 cursor-not-allowed' : 'bg-white/10 text-gray-300 hover:bg-white/20'}`}>
                    Next
                  </button>
                  <button onClick={() => setEnrichmentPage(enrichmentTotalPages - 1)} disabled={enrichmentPage === enrichmentTotalPages - 1}
                    className={`px-3 py-1.5 rounded text-xs font-medium transition-colors ${enrichmentPage === enrichmentTotalPages - 1 ? 'bg-white/5 text-gray-600 cursor-not-allowed' : 'bg-white/10 text-gray-300 hover:bg-white/20'}`}>
                    Last
                  </button>
                </div>
              )}
            </div>

            {/* ── Unenriched Products Explorer ──────────────────────────────── */}
            <div className="bg-white/5 backdrop-blur rounded-xl p-6">
              <h3 className="text-lg font-semibold text-white mb-1">Unenriched Products Explorer</h3>
              <p className="text-gray-400 text-sm mb-5">
                {EAGLE_DATA.catalogEnrichment.coverageImpact.untouchedCount.toLocaleString()} products were not enriched.
                Browse by reason, category, brand, or keyword to understand why and identify remediation paths.
              </p>

              {/* Reason breakdown cards */}
              <div className="grid grid-cols-2 md:grid-cols-5 gap-3 mb-5">
                {EAGLE_DATA.catalogEnrichment.unenrichedProducts.reasons.map((r) => (
                  <button
                    key={r.code}
                    onClick={() => setUnenrichedFilter(unenrichedFilter === r.code ? 'all' : r.code)}
                    className={`rounded-lg p-3 text-left transition-all border ${
                      unenrichedFilter === r.code
                        ? 'bg-white/15 border-white/30'
                        : 'bg-white/5 border-white/10 hover:bg-white/10'
                    }`}
                  >
                    <div className="font-bold text-lg" style={{ color: r.color }}>{r.count.toLocaleString()}</div>
                    <div className="text-white text-xs font-medium">{r.label}</div>
                  </button>
                ))}
              </div>

              {/* Active reason description */}
              {unenrichedFilter !== 'all' && (() => {
                const active = EAGLE_DATA.catalogEnrichment.unenrichedProducts.reasons.find(r => r.code === unenrichedFilter);
                return active ? (
                  <div className="bg-white/5 rounded-lg p-4 mb-5 border-l-4" style={{ borderColor: active.color }}>
                    <div className="text-white font-semibold text-sm mb-1">{active.label}</div>
                    <p className="text-gray-400 text-sm">{active.desc}</p>
                  </div>
                ) : null;
              })()}

              {/* Search bar */}
              <div className="flex gap-2 mb-4">
                <input
                  type="text"
                  value={unenrichedSearch}
                  onChange={(e) => setUnenrichedSearch(e.target.value)}
                  placeholder="Search by product name, brand, category, or GTIN..."
                  className="flex-1 bg-white/10 border border-white/20 rounded-lg px-4 py-2.5 text-white text-sm placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-amber-500"
                />
                {(unenrichedFilter !== 'all' || unenrichedSearch) && (
                  <button
                    onClick={() => { setUnenrichedFilter('all'); setUnenrichedSearch(''); }}
                    className="bg-white/10 hover:bg-white/20 text-gray-300 px-4 py-2.5 rounded-lg text-sm transition-colors"
                  >
                    Clear
                  </button>
                )}
              </div>

              {/* Results count */}
              <div className="flex items-center justify-between mb-3">
                <div className="text-gray-500 text-xs">
                  Showing {unenrichedPage * UNENRICHED_PAGE_SIZE + 1}–{Math.min((unenrichedPage + 1) * UNENRICHED_PAGE_SIZE, filteredUnenriched.length)} of {filteredUnenriched.length} products
                  {unenrichedFilter !== 'all' && <span> · filtered by <span className="text-gray-300">{EAGLE_DATA.catalogEnrichment.unenrichedProducts.reasons.find(r => r.code === unenrichedFilter)?.label}</span></span>}
                  {unenrichedSearch && <span> · matching "<span className="text-gray-300">{unenrichedSearch}</span>"</span>}
                </div>
                <div className="text-gray-500 text-xs">
                  Page {unenrichedPage + 1} of {unenrichedTotalPages}
                </div>
              </div>

              {/* Product table */}
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead>
                    <tr className="text-left text-gray-400 border-b border-white/10 text-xs uppercase tracking-wide">
                      <th className="pb-2 pr-4">Product</th>
                      <th className="pb-2 pr-4">Brand</th>
                      <th className="pb-2 pr-4">Category</th>
                      <th className="pb-2 pr-4">GTIN</th>
                      <th className="pb-2 pr-4 text-center">Existing Fields</th>
                      <th className="pb-2">Reason</th>
                    </tr>
                  </thead>
                  <tbody className="text-gray-300">
                    {paginatedUnenriched.length === 0 ? (
                      <tr>
                        <td colSpan="6" className="py-8 text-center text-gray-500">No products match your current filters</td>
                      </tr>
                    ) : paginatedUnenriched.map((p, i) => {
                      const reasonMeta = EAGLE_DATA.catalogEnrichment.unenrichedProducts.reasons.find(r => r.code === p.reason);
                      return (
                        <tr key={`${p.name}-${i}`} className="border-b border-white/5 hover:bg-white/5 transition-colors">
                          <td className="py-2.5 pr-4 text-white text-sm font-medium">{p.name}</td>
                          <td className="py-2.5 pr-4 text-sm">{p.brand}</td>
                          <td className="py-2.5 pr-4 text-sm">{p.category}</td>
                          <td className="py-2.5 pr-4 font-mono text-xs text-gray-500">{p.gtin}</td>
                          <td className="py-2.5 pr-4 text-center">
                            <span className={`text-sm font-bold ${p.existingFields >= 30 ? 'text-emerald-400' : p.existingFields >= 10 ? 'text-yellow-400' : 'text-red-400'}`}>
                              {p.existingFields}
                            </span>
                          </td>
                          <td className="py-2.5">
                            <span className="text-xs px-2 py-0.5 rounded-full font-medium" style={{ backgroundColor: (reasonMeta?.color || '#64748b') + '25', color: reasonMeta?.color || '#64748b' }}>
                              {reasonMeta?.label || p.reason}
                            </span>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>

              {/* Pagination controls */}
              {unenrichedTotalPages > 1 && (
                <div className="flex items-center justify-center gap-2 mt-4">
                  <button
                    onClick={() => setUnenrichedPage(0)}
                    disabled={unenrichedPage === 0}
                    className={`px-3 py-1.5 rounded text-xs font-medium transition-colors ${unenrichedPage === 0 ? 'bg-white/5 text-gray-600 cursor-not-allowed' : 'bg-white/10 text-gray-300 hover:bg-white/20'}`}
                  >
                    First
                  </button>
                  <button
                    onClick={() => setUnenrichedPage(Math.max(0, unenrichedPage - 1))}
                    disabled={unenrichedPage === 0}
                    className={`px-3 py-1.5 rounded text-xs font-medium transition-colors ${unenrichedPage === 0 ? 'bg-white/5 text-gray-600 cursor-not-allowed' : 'bg-white/10 text-gray-300 hover:bg-white/20'}`}
                  >
                    Prev
                  </button>
                  {Array.from({ length: unenrichedTotalPages }, (_, i) => (
                    <button
                      key={i}
                      onClick={() => setUnenrichedPage(i)}
                      className={`w-8 h-8 rounded text-xs font-bold transition-colors ${unenrichedPage === i ? 'bg-teal-600 text-white' : 'bg-white/10 text-gray-300 hover:bg-white/20'}`}
                    >
                      {i + 1}
                    </button>
                  ))}
                  <button
                    onClick={() => setUnenrichedPage(Math.min(unenrichedTotalPages - 1, unenrichedPage + 1))}
                    disabled={unenrichedPage === unenrichedTotalPages - 1}
                    className={`px-3 py-1.5 rounded text-xs font-medium transition-colors ${unenrichedPage === unenrichedTotalPages - 1 ? 'bg-white/5 text-gray-600 cursor-not-allowed' : 'bg-white/10 text-gray-300 hover:bg-white/20'}`}
                  >
                    Next
                  </button>
                  <button
                    onClick={() => setUnenrichedPage(unenrichedTotalPages - 1)}
                    disabled={unenrichedPage === unenrichedTotalPages - 1}
                    className={`px-3 py-1.5 rounded text-xs font-medium transition-colors ${unenrichedPage === unenrichedTotalPages - 1 ? 'bg-white/5 text-gray-600 cursor-not-allowed' : 'bg-white/10 text-gray-300 hover:bg-white/20'}`}
                  >
                    Last
                  </button>
                </div>
              )}

              {/* Remediation callout */}
              <div className="bg-blue-600/10 border border-blue-500/20 rounded-lg p-4 mt-5">
                <div className="flex items-center gap-2 text-blue-400 text-sm font-semibold mb-1">
                  <BrainIcon />
                  Remediation Paths
                </div>
                <div className="grid md:grid-cols-3 gap-3 mt-3">
                  <div className="bg-white/5 rounded p-3">
                    <div className="text-white text-sm font-medium mb-1">No GTIN Match</div>
                    <p className="text-gray-400 text-xs">Request GTINs from store-brand team, or match by product name + brand against fuzzy lookup in USDA/Open Food Facts.</p>
                  </div>
                  <div className="bg-white/5 rounded p-3">
                    <div className="text-white text-sm font-medium mb-1">Insufficient Source Data</div>
                    <p className="text-gray-400 text-xs">GTIN resolved but external sources returned incomplete or conflicting data below the confidence threshold. Re-process with additional data providers or manual review.</p>
                  </div>
                  <div className="bg-white/5 rounded p-3">
                    <div className="text-white text-sm font-medium mb-1">Discontinued</div>
                    <p className="text-gray-400 text-xs">Archive or flag in catalog. Can be bulk-enriched if historical analytics (e.g., substitution modeling) require the data.</p>
                  </div>
                </div>
              </div>
            </div>

            {/* How Food Intelligence Powers the Agent */}
            <div className="bg-gradient-to-r from-emerald-600/20 to-blue-600/20 backdrop-blur rounded-xl p-6 border border-emerald-500/30">
              <h3 className="text-xl font-bold text-white mb-3">How Food Intelligence Powers the Agent</h3>
              <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-4">
                {[
                  {
                    title: 'Auto Health Badges',
                    desc: 'Agent auto-annotates search results with Food Compass, Nutri-Score, and NOVA badges so shoppers see health context instantly.',
                    icon: <SparklesIcon />,
                    color: 'text-emerald-400',
                  },
                  {
                    title: 'Proactive Filtering',
                    desc: 'When dietary propensity > 0.5, the agent proactively filters results. E.g., gluten_free: 0.78 excludes gluten products by default.',
                    icon: <CheckIcon />,
                    color: 'text-blue-400',
                  },
                  {
                    title: 'Healthier Alternatives',
                    desc: 'Food Compass score drives "healthier alternative" suggestions. Low-scoring items trigger a swap recommendation.',
                    icon: <BrainIcon />,
                    color: 'text-purple-400',
                  },
                  {
                    title: 'Processing Warnings',
                    desc: 'NOVA Group 4 (ultra-processed) items get a gentle warning. Agent suggests less-processed alternatives when available.',
                    icon: <AlertIcon />,
                    color: 'text-yellow-400',
                  },
                ].map((item) => (
                  <div key={item.title} className="bg-white/5 rounded-lg p-4">
                    <div className={`flex items-center gap-2 ${item.color} mb-2`}>
                      {item.icon}
                      <span className="font-semibold text-sm">{item.title}</span>
                    </div>
                    <p className="text-gray-400 text-sm">{item.desc}</p>
                  </div>
                ))}
              </div>
            </div>

            {/* Gap Analysis Metrics */}
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="bg-white/5 backdrop-blur rounded-xl p-5">
                <div className="text-3xl font-bold text-white">70,000+</div>
                <div className="text-gray-400 text-sm">Total Products</div>
              </div>
              <div className="bg-white/5 backdrop-blur rounded-xl p-5">
                <div className="text-3xl font-bold text-emerald-400">68.3%</div>
                <div className="text-gray-400 text-sm">With Nutrition</div>
                <div className="text-emerald-400 text-xs mt-1">+15.4% from enrichment</div>
              </div>
              <div className="bg-white/5 backdrop-blur rounded-xl p-5">
                <div className="text-3xl font-bold text-amber-400">42.1%</div>
                <div className="text-gray-400 text-sm">Health Scores</div>
                <div className="text-amber-400 text-xs mt-1">+42.1% from Tufts</div>
              </div>
              <div className="bg-white/5 backdrop-blur rounded-xl p-5">
                <div className="text-3xl font-bold text-emerald-400">71.2%</div>
                <div className="text-gray-400 text-sm">With Ingredients</div>
                <div className="text-emerald-400 text-xs mt-1">+12.7% from enrichment</div>
              </div>
            </div>

            {/* Field Coverage Chart */}
            <div className="bg-white/5 backdrop-blur rounded-xl p-6">
              <h4 className="text-lg font-semibold text-white mb-4">Field Coverage Analysis</h4>
              <div className="space-y-3">
                {[
                  { field: 'Name', coverage: 100, color: 'bg-emerald-500' },
                  { field: 'Category', coverage: 99.8, color: 'bg-emerald-500' },
                  { field: 'Brand', coverage: 94.6, color: 'bg-emerald-500' },
                  { field: 'Description', coverage: 87.3, color: 'bg-emerald-500' },
                  { field: 'Ingredients', coverage: 71.2, color: 'bg-yellow-500' },
                  { field: 'Nutrition Facts', coverage: 68.3, color: 'bg-yellow-500' },
                  { field: 'Health Labels', coverage: 62.8, color: 'bg-yellow-500' },
                  { field: 'Serving Size', coverage: 58.4, color: 'bg-yellow-500' },
                  { field: 'Calories Data', coverage: 65.7, color: 'bg-yellow-500' },
                  { field: 'Health Scores', coverage: 42.1, color: 'bg-orange-500' },
                ].map(item => (
                  <div key={item.field} className="flex items-center gap-4">
                    <div className="w-36 text-gray-300 text-sm">{item.field}</div>
                    <div className="flex-1 bg-slate-700 rounded-full h-6 overflow-hidden">
                      <div
                        className={`h-full ${item.color} flex items-center justify-end pr-2`}
                        style={{ width: `${Math.max(item.coverage, 5)}%` }}
                      >
                        <span className="text-xs font-medium text-white">{item.coverage}%</span>
                      </div>
                    </div>
                    <div className="w-24 text-right text-gray-400 text-sm">
                      {Math.round(70000 * (100 - item.coverage) / 100).toLocaleString()} gap
                    </div>
                  </div>
                ))}
              </div>
            </div>

            {/* Enrichment Sources */}
            <div className="bg-white/5 backdrop-blur rounded-xl p-6">
              <h4 className="text-lg font-semibold text-white mb-4">Enrichment Data Sources</h4>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                {[
                  { name: 'USDA FoodData Central', type: 'Government', coverage: '500K+ products', status: 'Primary', color: 'border-emerald-500', label: 'GOV' },
                  { name: 'Open Food Facts', type: 'Open Source', coverage: '4M+ products', status: 'Active', color: 'border-blue-500', label: 'OSS' },
                  { name: 'Tufts Food Compass', type: 'Academic', coverage: 'Scoring engine', status: 'Ready', color: 'border-purple-500', label: 'EDU' },
                  { name: 'Edamam API', type: 'Commercial', coverage: '2.3M+ recipes', status: 'API Ready', color: 'border-yellow-500', label: 'API' },
                  { name: 'Nutritionix', type: 'Commercial', coverage: '600K+ UPCs', status: 'API Ready', color: 'border-pink-500', label: 'API' },
                  { name: 'Recipe1M+', type: 'Research', coverage: '1M+ recipes', status: 'Dataset', color: 'border-orange-500', label: 'R&D' },
                ].map(source => (
                  <div key={source.name} className={`bg-slate-800/50 rounded-lg p-4 border-l-4 ${source.color}`}>
                    <div className="flex items-center gap-2 mb-2">
                      <span className="bg-white/10 text-gray-300 px-2 py-0.5 rounded text-xs font-bold">{source.label}</span>
                      <div>
                        <div className="text-white font-medium">{source.name}</div>
                        <div className="text-gray-400 text-xs">{source.type}</div>
                      </div>
                    </div>
                    <div className="text-gray-300 text-sm">{source.coverage}</div>
                    <div className="mt-2">
                      <span className="px-2 py-0.5 bg-white/10 rounded text-xs text-gray-300">{source.status}</span>
                    </div>
                  </div>
                ))}
              </div>
            </div>

            {/* Health Scoring Systems */}
            <div className="bg-white/5 backdrop-blur rounded-xl p-6">
              <h4 className="text-lg font-semibold text-white mb-4">Health Scoring Framework</h4>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div className="bg-gradient-to-br from-purple-900/50 to-purple-800/30 rounded-lg p-5 border border-purple-500/30">
                  <h5 className="text-white font-semibold mb-2">Tufts Food Compass</h5>
                  <p className="text-gray-300 text-sm mb-3">Scores 1-100 based on 54 attributes across 9 health domains</p>
                  <div className="space-y-1 text-xs text-gray-400">
                    <div className="flex justify-between"><span>70-100:</span><span className="text-emerald-400">Encourage</span></div>
                    <div className="flex justify-between"><span>31-69:</span><span className="text-yellow-400">Moderate</span></div>
                    <div className="flex justify-between"><span>1-30:</span><span className="text-red-400">Limit</span></div>
                  </div>
                </div>
                <div className="bg-gradient-to-br from-green-900/50 to-green-800/30 rounded-lg p-5 border border-green-500/30">
                  <h5 className="text-white font-semibold mb-2">Nutri-Score</h5>
                  <p className="text-gray-300 text-sm mb-3">European front-of-pack label from A (best) to E (worst)</p>
                  <div className="flex gap-1 mt-3">
                    {['A', 'B', 'C', 'D', 'E'].map((grade, i) => (
                      <div key={grade} className={`w-8 h-8 rounded flex items-center justify-center text-white font-bold text-sm ${
                        i === 0 ? 'bg-green-600' : i === 1 ? 'bg-lime-500' : i === 2 ? 'bg-yellow-500' : i === 3 ? 'bg-orange-500' : 'bg-red-500'
                      }`}>{grade}</div>
                    ))}
                  </div>
                </div>
                <div className="bg-gradient-to-br from-blue-900/50 to-blue-800/30 rounded-lg p-5 border border-blue-500/30">
                  <h5 className="text-white font-semibold mb-2">NOVA Classification</h5>
                  <p className="text-gray-300 text-sm mb-3">Food processing level from 1 (minimal) to 4 (ultra-processed)</p>
                  <div className="space-y-1 text-xs text-gray-400">
                    <div className="flex justify-between"><span>Group 1:</span><span className="text-emerald-400">Unprocessed</span></div>
                    <div className="flex justify-between"><span>Group 2:</span><span className="text-blue-400">Culinary</span></div>
                    <div className="flex justify-between"><span>Group 3:</span><span className="text-yellow-400">Processed</span></div>
                    <div className="flex justify-between"><span>Group 4:</span><span className="text-red-400">Ultra-processed</span></div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* ================================================================= */}
        {/* TAB 7 — Agent Context                                             */}
        {/* ================================================================= */}
        {activeTab === 'agentContext' && (
          <div className="space-y-6">
            {/* Context JSON Viewer */}
            <div className="bg-white/5 backdrop-blur rounded-xl p-6">
              <h3 className="text-lg font-semibold text-white mb-2">Agent Context Structure</h3>
              <p className="text-gray-400 text-sm mb-4">
                This is the actual context payload assembled for the LLM at the start of each conversation turn.
                Every tool call enriches this context further.
              </p>

              <div className="bg-slate-950 rounded-lg p-5 font-mono text-sm overflow-x-auto">
                <pre className="text-green-400 leading-relaxed">{`{
  "shopper_profile": {
    "shopper_id": "40001000512",
    "mission_cluster": "health_focus",
    "loyalty_tier": "MyPerks Gold"
  },
  "dietary_propensities": {
    "organic": 0.91,
    "gluten_free": 0.78,
    "high_protein": 0.89,
    "low_sodium": 0.82,
    "high_fiber": 0.76,
    "low_sugar": 0.71,
    "dairy_free": 0.65,
    "vegetarian": 0.34,
    "nut_free": 0.15,
    "vegan": 0.12,
    "keto": 0.08
  },
  "virtual_pantry": [
    { "product_name": "Olive Oil",       "stock_level": 0.65, "days_until_reorder": 12 },
    { "product_name": "Almond Milk",     "stock_level": 0.72, "days_until_reorder": 15 },
    { "product_name": "Brown Rice",      "stock_level": 0.45, "days_until_reorder": 6  },
    { "product_name": "Chicken Breast",  "stock_level": 0.12, "days_until_reorder": 1  },
    { "product_name": "Greek Yogurt",    "stock_level": 0.08, "days_until_reorder": 0  }
  ],
  "active_promos": [
    { "promo_id": "P2024-1182", "type": "BOGO", "product": "Organic Pasta", "expires": "2024-12-15" },
    { "promo_id": "P2024-1195", "type": "20% OFF", "product": "Almond Milk", "expires": "2024-12-20" }
  ],
  "session": {
    "conversation_id": "conv_abc123",
    "turn_count": 3,
    "tools_called": ["search_products", "get_dietary_propensities"],
    "cart_items": 2,
    "cart_total": 18.47
  }
}`}</pre>
              </div>
            </div>

            {/* Sample Conversation */}
            <div className="bg-white/5 backdrop-blur rounded-xl p-6">
              <h3 className="text-lg font-semibold text-white mb-4">Sample Conversation: Context-Driven Personalization</h3>

              <div className="space-y-4">
                {/* User message */}
                <div className="flex gap-4">
                  <div className="w-10 h-10 bg-gray-600 rounded-full flex items-center justify-center text-white font-bold shrink-0">U</div>
                  <div className="bg-white/10 rounded-lg p-4 flex-1">
                    <p className="text-white">I need ingredients for a pasta dinner</p>
                  </div>
                </div>

                {/* Agent internal reasoning */}
                <div className="bg-slate-800/60 rounded-lg p-4 border border-slate-600/50 ml-14">
                  <div className="text-gray-400 text-xs font-semibold uppercase tracking-wide mb-3">Agent Internal Reasoning</div>
                  <div className="space-y-3">
                    <div className="flex items-start gap-3">
                      <div className="mt-0.5">
                        <span className="bg-blue-600 text-white px-2 py-0.5 rounded text-xs font-mono">search_products</span>
                      </div>
                      <div className="text-gray-300 text-sm">Query: "pasta dinner ingredients" — returns pasta, sauce, cheese, chicken, vegetables</div>
                    </div>
                    <div className="flex items-start gap-3">
                      <div className="mt-0.5">
                        <span className="bg-purple-600 text-white px-2 py-0.5 rounded text-xs font-mono">get_dietary_propensities</span>
                      </div>
                      <div className="text-sm">
                        <span className="text-yellow-400 font-medium">gluten_free: 0.78 </span>
                        <span className="text-gray-300">triggers dietary warning for regular pasta. Agent flags this and searches for gluten-free alternatives.</span>
                      </div>
                    </div>
                    <div className="flex items-start gap-3">
                      <div className="mt-0.5">
                        <span className="bg-emerald-600 text-white px-2 py-0.5 rounded text-xs font-mono">get_virtual_pantry</span>
                      </div>
                      <div className="text-sm">
                        <span className="text-emerald-400 font-medium">Olive Oil: 0.65 (in stock) </span>
                        <span className="text-gray-300">— excluded from shopping list since shopper already has it.</span>
                      </div>
                    </div>
                    <div className="flex items-start gap-3">
                      <div className="mt-0.5">
                        <span className="bg-teal-600 text-white px-2 py-0.5 rounded text-xs font-mono">optimize_shopping_list</span>
                      </div>
                      <div className="text-gray-300 text-sm">Removes pantry duplicates, applies active promos (20% off Almond Milk), sorts by aisle.</div>
                    </div>
                  </div>
                </div>

                {/* Agent response */}
                <div className="flex gap-4">
                  <div className="w-10 h-10 bg-teal-600 rounded-full flex items-center justify-center text-white shrink-0">
                    <BotIcon />
                  </div>
                  <div className="bg-gradient-to-r from-teal-600/20 to-purple-600/20 rounded-lg p-4 flex-1 border border-teal-500/30">
                    <p className="text-white mb-3">
                      Here is your pasta dinner shopping list! I noticed a few things:
                    </p>

                    <div className="bg-yellow-600/20 border border-yellow-500/30 rounded-lg p-3 mb-3">
                      <div className="flex items-center gap-2 text-yellow-400 text-sm font-semibold mb-1">
                        <AlertIcon />
                        Dietary Note
                      </div>
                      <p className="text-gray-300 text-sm">
                        Based on your preferences, I've included <span className="text-emerald-400 font-medium">gluten-free pasta</span> instead
                        of regular pasta. Your gluten-free preference score is high (0.78).
                      </p>
                    </div>

                    <div className="grid grid-cols-2 gap-2 mb-3">
                      {[
                        { name: 'Barilla GF Penne', price: '$3.49', note: 'Gluten-free' },
                        { name: 'Rao\'s Marinara', price: '$7.99', note: 'NOVA Group 1' },
                        { name: 'Organic Chicken Breast', price: '$8.99', note: 'High protein' },
                        { name: 'Fresh Basil', price: '$2.49', note: 'Organic available' },
                      ].map((item) => (
                        <div key={item.name} className="bg-white/10 rounded p-2 text-sm">
                          <div className="text-white font-medium">{item.name}</div>
                          <div className="flex items-center justify-between">
                            <span className="text-green-400">{item.price}</span>
                            <span className="text-gray-400 text-xs">{item.note}</span>
                          </div>
                        </div>
                      ))}
                    </div>

                    <div className="bg-emerald-600/20 border border-emerald-500/30 rounded-lg p-3">
                      <div className="flex items-center gap-2 text-emerald-400 text-sm font-semibold mb-1">
                        <CheckIcon />
                        Pantry Awareness
                      </div>
                      <p className="text-gray-300 text-sm">
                        I see you already have <span className="text-white font-medium">Olive Oil</span> in stock (65%),
                        so I've left it off the list. Your
                        <span className="text-white font-medium"> Greek Yogurt</span> is running very low — want me to add it?
                      </p>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            {/* Context Signals Used */}
            <div className="bg-white/5 backdrop-blur rounded-xl p-6">
              <h3 className="text-lg font-semibold text-white mb-4">Context Signals Used in This Conversation</h3>
              <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-4">
                {[
                  {
                    signal: 'Dietary Propensities',
                    value: 'gluten_free: 0.78',
                    action: 'Swapped regular pasta for GF alternative, added warning badge',
                    color: 'border-yellow-500',
                  },
                  {
                    signal: 'Virtual Pantry',
                    value: 'Olive Oil: 0.65',
                    action: 'Excluded from list (already in stock); flagged Greek Yogurt for reorder',
                    color: 'border-emerald-500',
                  },
                  {
                    signal: 'Mission Cluster',
                    value: 'Health Focus',
                    action: 'Prioritized organic and clean-label options in search results',
                    color: 'border-purple-500',
                  },
                  {
                    signal: 'Active Promos',
                    value: '20% off Almond Milk',
                    action: 'Surfaced promo for pantry item running low on stock',
                    color: 'border-pink-500',
                  },
                ].map((s) => (
                  <div key={s.signal} className={`bg-slate-800/50 rounded-lg p-4 border-l-4 ${s.color}`}>
                    <div className="text-white font-semibold text-sm mb-1">{s.signal}</div>
                    <div className="text-gray-300 font-mono text-xs mb-2">{s.value}</div>
                    <p className="text-gray-400 text-xs">{s.action}</p>
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}

        {/* ================================================================= */}
        {/* TAB — User Intelligence                                           */}
        {/* ================================================================= */}
        {activeTab === 'userIntelligence' && (
          <div className="space-y-6">
            {/* ── Propensity Graph ──────────────────────────────────────────── */}
            <div className="bg-white/5 backdrop-blur rounded-xl p-6">
              <h3 className="text-lg font-semibold text-white mb-1">Shopper Propensity Model</h3>
              <p className="text-gray-400 text-sm mb-5">11+ dimensions of preference scoring derived from 2-year purchase history joined against enriched catalog data</p>

              {/* Dietary Propensities */}
              <div className="mb-4">
                <div className="text-emerald-400 text-xs font-semibold uppercase tracking-wide mb-3">Dietary Propensities</div>
                <div className="space-y-2">
                  {EAGLE_DATA.userIntelligence.propensityDimensions.filter(d => d.category === 'dietary').map((d) => {
                    const barColor = d.score >= 0.7 ? '#10b981' : d.score >= 0.4 ? '#f59e0b' : '#64748b';
                    return (
                      <div key={d.name} className="flex items-center gap-4">
                        <div className="w-40 text-gray-300 text-sm">{d.name}</div>
                        <div className="flex-1 bg-slate-700 rounded-full h-5 overflow-hidden">
                          <div className="h-full rounded-full flex items-center justify-end pr-2 transition-all duration-700" style={{ width: `${d.score * 100}%`, backgroundColor: barColor }}>
                            <span className="text-xs font-bold text-white">{d.score.toFixed(2)}</span>
                          </div>
                        </div>
                        <div className="w-12 text-right">
                          {d.score >= 0.7 && <span className="text-emerald-400 text-xs font-semibold">HIGH</span>}
                          {d.score >= 0.4 && d.score < 0.7 && <span className="text-yellow-400 text-xs font-semibold">MED</span>}
                          {d.score < 0.4 && <span className="text-gray-500 text-xs font-semibold">LOW</span>}
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>

              {/* Brand Affinities */}
              <div className="mb-4">
                <div className="text-blue-400 text-xs font-semibold uppercase tracking-wide mb-3">Brand Affinities</div>
                <div className="space-y-2">
                  {EAGLE_DATA.userIntelligence.propensityDimensions.filter(d => d.category === 'brand').map((d) => {
                    const barColor = d.score >= 0.7 ? '#3b82f6' : d.score >= 0.4 ? '#60a5fa' : '#64748b';
                    return (
                      <div key={d.name} className="flex items-center gap-4">
                        <div className="w-40 text-gray-300 text-sm">{d.name}</div>
                        <div className="flex-1 bg-slate-700 rounded-full h-5 overflow-hidden">
                          <div className="h-full rounded-full flex items-center justify-end pr-2 transition-all duration-700" style={{ width: `${d.score * 100}%`, backgroundColor: barColor }}>
                            <span className="text-xs font-bold text-white">{d.score.toFixed(2)}</span>
                          </div>
                        </div>
                        <div className="w-12 text-right">
                          {d.score >= 0.7 && <span className="text-blue-400 text-xs font-semibold">HIGH</span>}
                          {d.score >= 0.4 && d.score < 0.7 && <span className="text-blue-300 text-xs font-semibold">MED</span>}
                          {d.score < 0.4 && <span className="text-gray-500 text-xs font-semibold">LOW</span>}
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>

              {/* Behavioral Signals */}
              <div className="mb-6">
                <div className="text-yellow-400 text-xs font-semibold uppercase tracking-wide mb-3">Behavioral Signals</div>
                <div className="space-y-2">
                  {EAGLE_DATA.userIntelligence.propensityDimensions.filter(d => d.category === 'behavioral').map((d) => {
                    const barColor = d.score >= 0.7 ? '#f59e0b' : d.score >= 0.4 ? '#fbbf24' : '#64748b';
                    return (
                      <div key={d.name} className="flex items-center gap-4">
                        <div className="w-40 text-gray-300 text-sm">{d.name}</div>
                        <div className="flex-1 bg-slate-700 rounded-full h-5 overflow-hidden">
                          <div className="h-full rounded-full flex items-center justify-end pr-2 transition-all duration-700" style={{ width: `${d.score * 100}%`, backgroundColor: barColor }}>
                            <span className="text-xs font-bold text-white">{d.score.toFixed(2)}</span>
                          </div>
                        </div>
                        <div className="w-12 text-right">
                          {d.score >= 0.7 && <span className="text-yellow-400 text-xs font-semibold">HIGH</span>}
                          {d.score >= 0.4 && d.score < 0.7 && <span className="text-yellow-300 text-xs font-semibold">MED</span>}
                          {d.score < 0.4 && <span className="text-gray-500 text-xs font-semibold">LOW</span>}
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>

              {/* How Propensity Scores Are Computed */}
              <div className="border-t border-white/10 pt-5">
                <h4 className="text-white font-semibold text-sm mb-4">How Propensity Scores Are Computed</h4>
                <div className="grid grid-cols-4 gap-4">
                  {EAGLE_DATA.userIntelligence.propensityComputation.map((s, i) => (
                    <div key={s.step} className="flex flex-col items-center text-center">
                      <div className={`w-10 h-10 ${s.color} rounded-full flex items-center justify-center text-white text-sm font-bold mb-2`}>
                        {s.step}
                      </div>
                      <div className="text-white font-medium text-sm mb-1">{s.name}</div>
                      <p className="text-gray-400 text-xs">{s.desc}</p>
                      {i < 3 && <div className="hidden md:block text-gray-500 mt-2"><ArrowRightIcon /></div>}
                    </div>
                  ))}
                </div>
              </div>
            </div>

            {/* ── Flavor DNA ────────────────────────────────────────────────── */}
            <div className="bg-white/5 backdrop-blur rounded-xl p-6">
              <h3 className="text-lg font-semibold text-white mb-1">Flavor DNA Profile</h3>
              <p className="text-gray-400 text-sm mb-5">Unique taste fingerprint derived from ingredient extraction across all purchased products</p>

              <div className="grid md:grid-cols-2 gap-6 mb-6">
                {/* Flavor Dimensions */}
                <div>
                  <h4 className="text-gray-400 text-xs font-semibold uppercase tracking-wide mb-3">Flavor Dimensions</h4>
                  <div className="space-y-3">
                    {EAGLE_DATA.userIntelligence.flavorDNA.flavorDimensions.map((f) => (
                      <div key={f.name} className="flex items-center gap-3">
                        <div className="w-16 text-gray-300 text-sm font-medium">{f.name}</div>
                        <div className="flex-1 bg-slate-700 rounded-full h-5 overflow-hidden">
                          <div
                            className="h-full rounded-full flex items-center justify-end pr-2 transition-all duration-700"
                            style={{ width: `${f.value * 100}%`, backgroundColor: f.color }}
                          >
                            <span className="text-xs font-bold text-white">{(f.value * 100).toFixed(0)}%</span>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>

                {/* Cuisine Affinity */}
                <div>
                  <h4 className="text-gray-400 text-xs font-semibold uppercase tracking-wide mb-3">Cuisine Affinity</h4>
                  <div className="space-y-3">
                    {EAGLE_DATA.userIntelligence.flavorDNA.cuisineAffinity.map((c) => (
                      <div key={c.name} className="flex items-center gap-3">
                        <div className="w-28 text-gray-300 text-sm font-medium">{c.name}</div>
                        <div className="flex-1 bg-slate-700 rounded-full h-5 overflow-hidden">
                          <div
                            className="h-full rounded-full flex items-center justify-end pr-2 transition-all duration-700"
                            style={{ width: `${c.pct}%`, backgroundColor: c.color }}
                          >
                            <span className="text-xs font-bold text-white">{c.pct}%</span>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              </div>

              {/* Top Ingredients */}
              <div>
                <h4 className="text-gray-400 text-xs font-semibold uppercase tracking-wide mb-3">Top 20 Ingredient Preferences</h4>
                <div className="flex flex-wrap gap-2">
                  {EAGLE_DATA.userIntelligence.flavorDNA.topIngredients.map((ing, i) => (
                    <span key={ing} className={`px-3 py-1.5 rounded-full text-sm font-medium ${
                      i < 5 ? 'bg-emerald-600/30 text-emerald-300' :
                      i < 10 ? 'bg-blue-600/30 text-blue-300' :
                      i < 15 ? 'bg-purple-600/30 text-purple-300' :
                      'bg-white/10 text-gray-300'
                    }`}>
                      {ing}
                    </span>
                  ))}
                </div>
              </div>

              {/* Computation Note */}
              <div className="bg-blue-600/10 border border-blue-500/20 rounded-lg p-4 mt-5">
                <div className="flex items-center gap-2 text-blue-400 text-sm font-semibold mb-1">
                  <BrainIcon />
                  How Flavor DNA Is Built
                </div>
                <p className="text-gray-400 text-sm">
                  Every product purchased is decomposed into its ingredient list via enriched catalog data. Ingredients are mapped to flavor
                  compounds (sweet, salty, spicy, umami, sour, bitter) using our food ontology. Purchase frequency weights each ingredient,
                  producing a per-shopper flavor fingerprint that powers cuisine recommendations and novel product discovery.
                </p>
              </div>
            </div>

            {/* ── Predictive Pantry Model ───────────────────────────────────── */}
            <div className="bg-white/5 backdrop-blur rounded-xl p-6">
              <h3 className="text-lg font-semibold text-white mb-1">Predictive Pantry Model</h3>
              <p className="text-gray-400 text-sm mb-5">ML-estimated stock levels, consumption rates, and reorder predictions for each shopper's household</p>

              <div className="grid grid-cols-2 md:grid-cols-5 gap-4 mb-6">
                {EAGLE_DATA.userIntelligence.pantryModel.items.map((item) => {
                  const urgencyColor = item.reorderIn <= 1 ? '#ef4444' : item.reorderIn <= 5 ? '#f59e0b' : '#10b981';
                  const urgencyLabel = item.reorderIn <= 1 ? 'Urgent' : item.reorderIn <= 5 ? 'Soon' : 'Stocked';
                  return (
                    <div key={item.name} className="bg-slate-800/60 rounded-lg p-4 border border-white/10">
                      <div className="text-white font-medium text-sm mb-2">{item.name}</div>
                      <div className="text-gray-400 text-xs mb-1">Rate: <span className="text-gray-300 font-mono">{item.consumptionRate}</span></div>
                      <div className="flex items-center gap-2 mb-1">
                        <span className="text-xs" style={{ color: urgencyColor }}>Reorder in:</span>
                        <span className="text-white font-bold">{item.reorderIn}d</span>
                      </div>
                      <div className="flex items-center justify-between">
                        <span className="text-xs px-1.5 py-0.5 rounded" style={{ backgroundColor: urgencyColor + '30', color: urgencyColor }}>{urgencyLabel}</span>
                        <span className="text-gray-500 text-xs">conf: {(item.confidence * 100).toFixed(0)}%</span>
                      </div>
                    </div>
                  );
                })}
              </div>

              <div className="grid md:grid-cols-2 gap-4">
                {/* Household Size */}
                <div className="bg-slate-800/40 rounded-lg p-4 border border-white/10">
                  <div className="text-gray-400 text-xs font-semibold uppercase tracking-wide mb-2">Household Size Inference</div>
                  <div className="flex items-center gap-4">
                    <div className="text-3xl font-bold text-white">{EAGLE_DATA.userIntelligence.pantryModel.householdSize.estimated}</div>
                    <div>
                      <div className="text-gray-300 text-sm">estimated members</div>
                      <div className="text-gray-500 text-xs">{EAGLE_DATA.userIntelligence.pantryModel.householdSize.method}</div>
                      <div className="text-gray-500 text-xs">Confidence: {(EAGLE_DATA.userIntelligence.pantryModel.householdSize.confidence * 100).toFixed(0)}%</div>
                    </div>
                  </div>
                </div>

                {/* Seasonal Adjustments */}
                <div className="bg-slate-800/40 rounded-lg p-4 border border-white/10">
                  <div className="text-gray-400 text-xs font-semibold uppercase tracking-wide mb-2">Seasonal Adjustments</div>
                  <div className="grid grid-cols-2 gap-2">
                    {EAGLE_DATA.userIntelligence.pantryModel.seasonalAdjustments.map((s) => (
                      <div key={s.season} className="bg-white/5 rounded p-2">
                        <div className="font-medium text-sm" style={{ color: s.color }}>{s.season}</div>
                        <div className="text-gray-400 text-xs">{s.change}</div>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            </div>

            {/* ── Consumption Model ─────────────────────────────────────────── */}
            <div className="bg-white/5 backdrop-blur rounded-xl p-6">
              <h3 className="text-lg font-semibold text-white mb-1">Consumption Model</h3>
              <p className="text-gray-400 text-sm mb-5">Inferred nutritional intake patterns from purchase history and household modeling</p>

              <div className="grid md:grid-cols-2 gap-6 mb-6">
                {/* Weekly Calories */}
                <div className="bg-slate-800/40 rounded-lg p-5 border border-white/10">
                  <div className="text-gray-400 text-sm mb-1">Estimated Weekly Caloric Intake</div>
                  <div className="text-4xl font-bold text-white mb-1">
                    <AnimatedCounter value={EAGLE_DATA.userIntelligence.consumptionModel.weeklyCalories} />
                  </div>
                  <div className="text-gray-500 text-xs">~{Math.round(EAGLE_DATA.userIntelligence.consumptionModel.weeklyCalories / 7).toLocaleString()} cal/day per household member</div>
                </div>

                {/* Macro Balance */}
                <div className="bg-slate-800/40 rounded-lg p-5 border border-white/10">
                  <div className="text-gray-400 text-sm mb-3">Macro Nutrient Balance</div>
                  <div className="flex h-8 rounded-full overflow-hidden mb-3">
                    {EAGLE_DATA.userIntelligence.consumptionModel.macroBalance.map((m) => (
                      <div key={m.macro} className="flex items-center justify-center text-xs font-bold text-white" style={{ width: `${m.pct}%`, backgroundColor: m.color }}>
                        {m.pct}%
                      </div>
                    ))}
                  </div>
                  <div className="flex justify-between">
                    {EAGLE_DATA.userIntelligence.consumptionModel.macroBalance.map((m) => (
                      <div key={m.macro} className="flex items-center gap-1.5">
                        <div className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: m.color }} />
                        <span className="text-gray-400 text-xs">{m.macro}</span>
                      </div>
                    ))}
                  </div>
                </div>
              </div>

              {/* Meal Patterns */}
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
                {EAGLE_DATA.userIntelligence.consumptionModel.mealPatterns.map((m) => (
                  <div key={m.meal} className="bg-slate-800/60 rounded-lg p-4 border border-white/10">
                    <div className="flex items-center justify-between mb-2">
                      <span className="text-white font-medium">{m.meal}</span>
                      <span className="text-xs px-2 py-0.5 rounded-full" style={{ backgroundColor: m.color + '30', color: m.color }}>{m.intensity}</span>
                    </div>
                    <div className="text-2xl font-bold text-white">{m.typicalCal}</div>
                    <div className="text-gray-400 text-xs">avg cal · {m.pct}% of daily</div>
                  </div>
                ))}
              </div>

              {/* Health Trajectory */}
              <div className="bg-gradient-to-r from-emerald-600/15 to-blue-600/15 rounded-lg p-5 border border-emerald-500/20">
                <div className="flex items-center gap-3 mb-3">
                  <div className="flex items-center gap-2">
                    <SparklesIcon />
                    <span className="text-white font-semibold">Health Trajectory</span>
                  </div>
                  <span className="px-3 py-1 rounded-full text-sm font-semibold" style={{ backgroundColor: EAGLE_DATA.userIntelligence.consumptionModel.healthTrajectory.trendColor + '30', color: EAGLE_DATA.userIntelligence.consumptionModel.healthTrajectory.trendColor }}>
                    {EAGLE_DATA.userIntelligence.consumptionModel.healthTrajectory.trend}
                  </span>
                  <span className="text-gray-500 text-sm">over {EAGLE_DATA.userIntelligence.consumptionModel.healthTrajectory.period}</span>
                </div>
                <div className="flex gap-4">
                  {EAGLE_DATA.userIntelligence.consumptionModel.healthTrajectory.indicators.map((ind) => (
                    <div key={ind.label} className="bg-white/5 rounded-lg px-4 py-2 flex-1">
                      <div className="text-emerald-400 font-bold text-sm">{ind.change}</div>
                      <div className="text-gray-400 text-xs">{ind.label}</div>
                    </div>
                  ))}
                </div>
              </div>
            </div>

            {/* ── Householding Model ────────────────────────────────────────── */}
            <div className="bg-white/5 backdrop-blur rounded-xl p-6">
              <h3 className="text-lg font-semibold text-white mb-1">Householding Model</h3>
              <p className="text-gray-400 text-sm mb-5">De-averaging from loyalty card to individual household members using purchase pattern analysis and GNN inference</p>

              {/* Household Header */}
              <div className="flex items-center gap-4 mb-5 bg-slate-800/40 rounded-lg p-4 border border-white/10">
                <div>
                  <div className="text-gray-400 text-xs">Household ID</div>
                  <div className="text-white font-mono font-semibold">{EAGLE_DATA.userIntelligence.householding.householdId}</div>
                </div>
                <div className="border-l border-white/10 pl-4">
                  <div className="text-gray-400 text-xs">Confidence</div>
                  <div className="text-white font-semibold">{(EAGLE_DATA.userIntelligence.householding.confidence * 100).toFixed(0)}%</div>
                </div>
                <div className="border-l border-white/10 pl-4">
                  <div className="text-gray-400 text-xs">Members Detected</div>
                  <div className="text-white font-semibold">{EAGLE_DATA.userIntelligence.householding.members.length}</div>
                </div>
                <div className="border-l border-white/10 pl-4 flex gap-4">
                  {Object.entries(EAGLE_DATA.userIntelligence.householding.detections).map(([key, val]) => (
                    <div key={key} className="text-center">
                      <div className="text-gray-400 text-xs capitalize">{key}</div>
                      <div className={`text-sm font-semibold ${val ? 'text-emerald-400' : 'text-gray-600'}`}>{val ? 'Yes' : 'No'}</div>
                    </div>
                  ))}
                </div>
              </div>

              {/* Members */}
              <div className="grid md:grid-cols-2 gap-4 mb-5">
                {EAGLE_DATA.userIntelligence.householding.members.map((member) => (
                  <div key={member.role} className={`bg-slate-800/60 rounded-lg p-4 border ${member.identified ? 'border-emerald-500/30' : 'border-amber-500/30'}`}>
                    <div className="flex items-center justify-between mb-2">
                      <span className="text-white font-semibold">{member.role}</span>
                      <span className={`text-xs px-2 py-0.5 rounded ${member.identified ? 'bg-emerald-600/30 text-emerald-400' : 'bg-amber-600/30 text-amber-400'}`}>
                        {member.identified ? 'Identified' : 'Inferred'}
                      </span>
                    </div>
                    <div className="text-gray-400 text-sm mb-1">Age: <span className="text-gray-300">{member.age}</span></div>
                    <div className="text-gray-400 text-sm mb-1">Preferences: <span className="text-gray-300">{member.preferences}</span></div>
                    <div className="text-gray-400 text-sm">ID: <span className="text-gray-300 font-mono text-xs">{member.shopperId}</span></div>
                  </div>
                ))}
              </div>

              {/* Shared vs Personal Preferences */}
              <div className="grid md:grid-cols-3 gap-4">
                <div className="bg-slate-800/40 rounded-lg p-4 border border-white/10">
                  <div className="text-emerald-400 text-xs font-semibold uppercase tracking-wide mb-2">Shared Preferences</div>
                  <div className="flex flex-wrap gap-1.5">
                    {EAGLE_DATA.userIntelligence.householding.sharedPreferences.map((p) => (
                      <span key={p} className="bg-emerald-600/20 text-emerald-300 px-2 py-1 rounded text-xs">{p}</span>
                    ))}
                  </div>
                </div>
                <div className="bg-slate-800/40 rounded-lg p-4 border border-white/10">
                  <div className="text-blue-400 text-xs font-semibold uppercase tracking-wide mb-2">Primary Member Only</div>
                  <div className="flex flex-wrap gap-1.5">
                    {EAGLE_DATA.userIntelligence.householding.personalPreferences.primary.map((p) => (
                      <span key={p} className="bg-blue-600/20 text-blue-300 px-2 py-1 rounded text-xs">{p}</span>
                    ))}
                  </div>
                </div>
                <div className="bg-slate-800/40 rounded-lg p-4 border border-white/10">
                  <div className="text-amber-400 text-xs font-semibold uppercase tracking-wide mb-2">Secondary Member Only</div>
                  <div className="flex flex-wrap gap-1.5">
                    {EAGLE_DATA.userIntelligence.householding.personalPreferences.secondary.map((p) => (
                      <span key={p} className="bg-amber-600/20 text-amber-300 px-2 py-1 rounded text-xs">{p}</span>
                    ))}
                  </div>
                </div>
              </div>

              {/* Householding Value Callout */}
              <div className="bg-purple-600/10 border border-purple-500/20 rounded-lg p-4 mt-5">
                <div className="flex items-center gap-2 text-purple-400 text-sm font-semibold mb-1">
                  <NetworkIcon />
                  Why Householding Matters
                </div>
                <p className="text-gray-400 text-sm">
                  A single loyalty card often represents multiple people with different tastes. By de-averaging to the individual level,
                  propensity scores become dramatically more accurate — the health-conscious primary shopper gets organic recommendations
                  while the convenience-oriented secondary member gets quick-meal suggestions. This lifts personalization accuracy from
                  ~60% (household-averaged) to ~94% (individual-level).
                </p>
              </div>
            </div>

            {/* ── Data Quality & Anomalies ──────────────────────────────────── */}
            <div className="bg-white/5 backdrop-blur rounded-xl p-6">
              <h3 className="text-lg font-semibold text-white mb-1">Data Quality & Anomalies</h3>
              <p className="text-gray-400 text-sm mb-4">
                Of {EAGLE_DATA.userIntelligence.dataQuality.summary.totalLoyaltyUsers.toLocaleString()} loyalty users,{' '}
                <span className="text-red-400 font-semibold">{EAGLE_DATA.userIntelligence.dataQuality.summary.flaggedUsers.toLocaleString()}</span>{' '}
                ({EAGLE_DATA.userIntelligence.dataQuality.summary.flaggedPct}%) are flagged with anomalies that could degrade model accuracy if left unresolved.
              </p>

              {/* Summary bar */}
              <div className="flex items-center gap-2 mb-6">
                <div className="flex-1 h-4 bg-slate-700 rounded-full overflow-hidden flex">
                  <div className="h-full bg-emerald-500" style={{ width: `${100 - EAGLE_DATA.userIntelligence.dataQuality.summary.flaggedPct}%` }} title="Clean users" />
                  {EAGLE_DATA.userIntelligence.dataQuality.anomalyTypes.map((a) => (
                    <div key={a.code} className="h-full" style={{ backgroundColor: a.color, width: `${(a.count / EAGLE_DATA.userIntelligence.dataQuality.summary.totalLoyaltyUsers * 100).toFixed(1)}%` }} title={a.label} />
                  ))}
                </div>
                <div className="text-emerald-400 text-xs font-semibold whitespace-nowrap">{(100 - EAGLE_DATA.userIntelligence.dataQuality.summary.flaggedPct).toFixed(1)}% Clean</div>
              </div>

              {/* Anomaly Type Cards */}
              <div className="grid md:grid-cols-2 gap-4 mb-6">
                {EAGLE_DATA.userIntelligence.dataQuality.anomalyTypes.map((a) => (
                  <div key={a.code} className="bg-slate-800/60 rounded-lg p-4 border border-white/5">
                    <div className="flex items-center justify-between mb-2">
                      <div className="flex items-center gap-2">
                        <div className="w-3 h-3 rounded-full" style={{ backgroundColor: a.color }} />
                        <span className="text-white text-sm font-semibold">{a.label}</span>
                      </div>
                      <div className="flex items-center gap-2">
                        <span className={`px-2 py-0.5 rounded text-xs font-semibold ${a.severity === 'high' ? 'bg-red-500/20 text-red-400' : 'bg-amber-500/20 text-amber-400'}`}>
                          {a.severity}
                        </span>
                        <span className="text-white font-mono text-sm font-bold">{a.count.toLocaleString()}</span>
                      </div>
                    </div>
                    <p className="text-gray-400 text-xs mb-2">{a.desc}</p>
                    <div className="bg-slate-900/50 rounded p-2 mt-2">
                      <div className="text-amber-400 text-xs font-semibold mb-1">Impact</div>
                      <p className="text-gray-500 text-xs">{a.impact}</p>
                    </div>
                    <div className="bg-slate-900/50 rounded p-2 mt-2">
                      <div className="text-blue-400 text-xs font-semibold mb-1">Remediation</div>
                      <p className="text-gray-500 text-xs">{a.remediation}</p>
                    </div>
                  </div>
                ))}
              </div>

              {/* Flagged Accounts Table */}
              <div className="bg-slate-800/40 rounded-lg p-4 border border-white/5">
                <h4 className="text-white text-sm font-semibold mb-3">Flagged Account Examples</h4>
                <div className="overflow-x-auto">
                  <table className="w-full text-xs">
                    <thead>
                      <tr className="text-gray-400 border-b border-white/10">
                        <th className="text-left py-2 px-2 font-medium">Loyalty ID</th>
                        <th className="text-left py-2 px-2 font-medium">Issue</th>
                        <th className="text-left py-2 px-2 font-medium">Detail</th>
                        <th className="text-center py-2 px-2 font-medium">mParticle IDs</th>
                        <th className="text-center py-2 px-2 font-medium">Weekly Txns</th>
                        <th className="text-center py-2 px-2 font-medium">Event Rate</th>
                      </tr>
                    </thead>
                    <tbody>
                      {EAGLE_DATA.userIntelligence.dataQuality.flaggedExamples.map((ex) => {
                        const anomaly = EAGLE_DATA.userIntelligence.dataQuality.anomalyTypes.find(a => a.code === ex.issue);
                        return (
                          <tr key={ex.loyaltyId} className="border-b border-white/5 hover:bg-white/5 transition-colors">
                            <td className="py-2 px-2 font-mono text-white">{ex.loyaltyId}</td>
                            <td className="py-2 px-2">
                              <span className="inline-flex items-center gap-1">
                                <span className="w-2 h-2 rounded-full" style={{ backgroundColor: anomaly?.color || '#666' }} />
                                <span style={{ color: anomaly?.color || '#999' }}>{anomaly?.label || ex.issue}</span>
                              </span>
                            </td>
                            <td className="py-2 px-2 text-gray-400 max-w-[280px]">{ex.detail}</td>
                            <td className="py-2 px-2 text-center">
                              <span className={ex.mparticleIds > 1 ? 'text-red-400 font-semibold' : 'text-gray-400'}>{ex.mparticleIds}</span>
                            </td>
                            <td className="py-2 px-2 text-center">
                              <span className={ex.weeklyTxns > 10 ? 'text-amber-400 font-semibold' : 'text-gray-400'}>{ex.weeklyTxns}</span>
                            </td>
                            <td className="py-2 px-2 text-center">
                              <span className={ex.eventRate !== 'Normal' && ex.eventRate !== 'None' ? 'text-cyan-400 font-semibold' : 'text-gray-400'}>{ex.eventRate}</span>
                            </td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
              </div>

              {/* Data Quality Impact Callout */}
              <div className="bg-red-600/10 border border-red-500/20 rounded-lg p-4 mt-5">
                <div className="flex items-center gap-2 text-red-400 text-sm font-semibold mb-1">
                  <ActivityIcon />
                  Why This Matters
                </div>
                <p className="text-gray-400 text-sm">
                  Without data quality hygiene, the {EAGLE_DATA.userIntelligence.dataQuality.summary.flaggedPct}% of flagged accounts can disproportionately skew model outputs.
                  A single cashier card with 47 transactions/week pollutes propensity distributions more than 100 normal shoppers.
                  Identity fragmentation (multiple mParticle IDs) dilutes individual taste signals, causing the flavor DNA and
                  consumption models to under-represent preferences. Resolving these anomalies before model training is critical for
                  production-grade personalization.
                </p>
              </div>
            </div>
          </div>
        )}

        {/* ================================================================= */}
        {/* TAB — Knowledge Graph                                             */}
        {/* ================================================================= */}
        {activeTab === 'knowledgeGraph' && (
          <div className="space-y-6">
            {/* ── Graph Architecture ────────────────────────────────────────── */}
            <div className="bg-white/5 backdrop-blur rounded-xl p-6">
              <h3 className="text-lg font-semibold text-white mb-1">Knowledge Graph Architecture</h3>
              <p className="text-gray-400 text-sm mb-4">
                A unified neural graph combining catalog, transaction, customer, behavioral, and enrichment data into a single queryable intelligence layer
              </p>
              <div className="bg-slate-800/50 rounded-xl p-4">
                <KnowledgeGraphSVG />
              </div>
            </div>

            {/* ── Graph Statistics ──────────────────────────────────────────── */}
            <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
              {[
                { label: 'Total Nodes', value: EAGLE_DATA.knowledgeGraph.stats.totalNodes, color: 'from-blue-500 to-blue-600' },
                { label: 'Total Edges', value: EAGLE_DATA.knowledgeGraph.stats.totalEdges, color: 'from-emerald-500 to-emerald-600' },
                { label: 'Node Types', value: EAGLE_DATA.knowledgeGraph.stats.nodeTypeCount, color: 'from-purple-500 to-purple-600' },
                { label: 'Edge Types', value: EAGLE_DATA.knowledgeGraph.stats.edgeTypeCount, color: 'from-orange-500 to-orange-600' },
                { label: 'Avg Degree', value: EAGLE_DATA.knowledgeGraph.stats.avgDegree, color: 'from-pink-500 to-pink-600' },
                { label: 'Density', value: 'Sparse', color: 'from-cyan-500 to-cyan-600' },
              ].map((m) => (
                <div key={m.label} className={`bg-gradient-to-br ${m.color} rounded-xl p-4 text-white shadow-lg`}>
                  <div className="text-xs font-medium opacity-80 mb-1">{m.label}</div>
                  <div className="text-2xl font-bold">{m.value}</div>
                </div>
              ))}
            </div>

            {/* ── Node & Edge Types ─────────────────────────────────────────── */}
            <div className="grid md:grid-cols-2 gap-6">
              {/* Node Types */}
              <div className="bg-white/5 backdrop-blur rounded-xl p-6">
                <h4 className="text-white font-semibold mb-4">Node Types</h4>
                <div className="overflow-x-auto">
                  <table className="w-full">
                    <thead>
                      <tr className="text-left text-gray-400 border-b border-white/10 text-sm">
                        <th className="pb-2 pr-4">Type</th>
                        <th className="pb-2 pr-4 text-right">Count</th>
                      </tr>
                    </thead>
                    <tbody className="text-gray-300">
                      {EAGLE_DATA.knowledgeGraph.nodeTypes.map((n) => (
                        <tr key={n.type} className="border-b border-white/5">
                          <td className="py-2.5 pr-4">
                            <div className="flex items-center gap-2">
                              <div className="w-3 h-3 rounded-full" style={{ backgroundColor: n.color }} />
                              <span className="text-white text-sm font-medium">{n.type}</span>
                            </div>
                          </td>
                          <td className="py-2.5 text-right font-mono text-sm">{n.displayCount}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>

              {/* Edge Types */}
              <div className="bg-white/5 backdrop-blur rounded-xl p-6">
                <h4 className="text-white font-semibold mb-4">Edge Types</h4>
                <div className="overflow-x-auto">
                  <table className="w-full">
                    <thead>
                      <tr className="text-left text-gray-400 border-b border-white/10 text-sm">
                        <th className="pb-2 pr-4">Relationship</th>
                        <th className="pb-2 pr-4">From → To</th>
                        <th className="pb-2 text-right">Count</th>
                      </tr>
                    </thead>
                    <tbody className="text-gray-300">
                      {EAGLE_DATA.knowledgeGraph.edgeTypes.map((e) => (
                        <tr key={e.type} className="border-b border-white/5">
                          <td className="py-2.5 pr-4">
                            <code className="text-xs font-mono px-1.5 py-0.5 rounded bg-white/10" style={{ color: e.color }}>{e.type}</code>
                          </td>
                          <td className="py-2.5 pr-4 text-sm">{e.from} → {e.to}</td>
                          <td className="py-2.5 text-right font-mono text-sm">{e.count}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            </div>

            {/* ── Graph Traversal Examples ──────────────────────────────────── */}
            <div className="bg-white/5 backdrop-blur rounded-xl p-6">
              <h3 className="text-lg font-semibold text-white mb-4">Example Graph Traversals</h3>
              <div className="grid md:grid-cols-3 gap-4">
                {EAGLE_DATA.knowledgeGraph.queryExamples.map((q) => (
                  <div key={q.name} className="bg-slate-800/50 rounded-lg p-4 border-l-4 border-purple-500">
                    <div className="text-white font-semibold text-sm mb-2">{q.name}</div>
                    <div className="bg-slate-900/80 rounded p-2.5 mb-3 font-mono text-xs text-purple-300 leading-relaxed break-all">
                      {q.path}
                    </div>
                    <p className="text-gray-400 text-sm">{q.desc}</p>
                  </div>
                ))}
              </div>
            </div>

            {/* ── Value of the Knowledge Graph ─────────────────────────────── */}
            <div className="bg-gradient-to-r from-purple-600/20 to-blue-600/20 backdrop-blur rounded-xl p-6 border border-purple-500/30">
              <h3 className="text-xl font-bold text-white mb-2">Value of the Knowledge Graph</h3>
              <p className="text-gray-400 text-sm mb-5">The graph isn't just a data store — it's an intelligence multiplier that enables capabilities impossible with flat tables</p>
              <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-4">
                {EAGLE_DATA.knowledgeGraph.graphValue.map((v) => (
                  <div key={v.title} className="bg-white/5 rounded-lg p-4">
                    <div className="flex items-center gap-2 mb-2">
                      <div className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: v.color }} />
                      <span className="text-white font-semibold text-sm">{v.title}</span>
                    </div>
                    <p className="text-gray-400 text-sm">{v.desc}</p>
                  </div>
                ))}
              </div>
            </div>

            {/* ── Data Sources → Graph ─────────────────────────────────────── */}
            <div className="bg-white/5 backdrop-blur rounded-xl p-6">
              <h3 className="text-lg font-semibold text-white mb-4">Data Sources → Graph Integration</h3>
              <div className="grid md:grid-cols-5 gap-4">
                {EAGLE_DATA.knowledgeGraph.dataSources.map((ds) => (
                  <div key={ds.source} className={`bg-slate-800/50 rounded-lg p-4 border-l-4 ${ds.color}`}>
                    <div className="text-white font-semibold text-sm mb-2">{ds.source}</div>
                    <div className="text-gray-500 text-xs mb-2">{ds.records}</div>
                    <div className="text-gray-400 text-xs mb-1"><span className="text-gray-500">Creates:</span> {ds.creates}</div>
                    <div className="text-gray-400 text-xs"><span className="text-gray-500">Edges:</span> {ds.edgesCreated}</div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}
      </main>

      {/* ── Footer ──────────────────────────────────────────────────────────── */}
      <footer className="bg-black/30 text-gray-400 py-6 px-8 mt-8">
        <div className="max-w-7xl mx-auto text-center text-sm">
          Data Insights Dashboard — Delectable AI · Powered by the Delectable Data Platform
        </div>
      </footer>
    </div>
  );
};

// ─── Expose data for PPTX export ─────────────────────────────────────────────────
window.EAGLE_DATA = EAGLE_DATA;

// ─── Render ─────────────────────────────────────────────────────────────────────

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<DataInsightsDashboard />);
