/**
 * Giant Eagle — Eagle AI Data Insights Dashboard
 *
 * Interactive visualization of the Eagle 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>
);

// ─── 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: 'GE 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', results: ['Chobani Greek Yogurt', 'KIND Protein Bar', 'Roasted Almonds', 'Cottage Cheese Cups'] },
    { query: 'something like Greek yogurt but dairy-free', results: ['Kite Hill Almond Yogurt', 'So Delicious Coconut Yogurt', 'Silk Soy Yogurt'] },
    { query: 'organic chicken breast', results: ['GE Organic Chicken Breast', 'Bell & Evans Organic', 'Perdue Harvestland Organic'] },
  ],
};

// ─── 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>
  );
};

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

const DataInsightsDashboard = () => {
  const [activeTab, setActiveTab] = useState('overview');
  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState([]);
  const [activeVectorQuery, setActiveVectorQuery] = useState(0);

  const handleSemanticSearch = (query) => {
    if (!query.trim()) return;
    const demo = EAGLE_DATA.semanticSearchDemo.find(
      d => d.query.toLowerCase().includes(query.toLowerCase())
    );
    setSearchResults(demo ? demo.results : ['Chobani Greek Yogurt', 'KIND Protein Bar', 'Nature Valley Oats']);
  };

  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: 'foodIntel',      label: 'Food Intelligence',  icon: <BrainIcon /> },
    { 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="bg-gradient-to-r from-red-700 to-red-600 text-white py-6 px-8">
        <div className="max-w-7xl mx-auto">
          <div className="flex items-center gap-4">
            <div className="w-12 h-12 bg-white rounded-lg flex items-center justify-center">
              <span className="text-red-600 font-bold text-xl">GE</span>
            </div>
            <div>
              <h1 className="text-2xl font-bold">Eagle AI Data Insights</h1>
              <p className="text-red-200">Grocery Agent Platform Analytics</p>
            </div>
          </div>
        </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-red-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-red-500 to-red-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">BigQuery 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">
            {/* BigQuery Tables */}
            <div className="bg-white/5 backdrop-blur rounded-xl p-6">
              <h3 className="text-lg font-semibold text-white mb-4">BigQuery 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 BigQuery 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 (Eagle 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">Eagle 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-red-500 to-red-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">BigQuery 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 BigQuery 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: "healthy high-protein snack" or "organic chicken breast"'
                  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-red-500"
                />
                <button
                  onClick={() => handleSemanticSearch(searchQuery)}
                  className="bg-red-600 hover:bg-red-700 text-white px-6 py-3 rounded-lg font-medium transition-colors"
                >
                  Search
                </button>
              </div>

              {searchResults.length > 0 && (
                <div className="bg-white/10 rounded-lg p-4 mb-4">
                  <div className="text-gray-400 text-sm mb-3">Semantic Search Results:</div>
                  <div className="flex flex-wrap gap-2">
                    {searchResults.map((r) => (
                      <span key={r} 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-red-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-red-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 Vertex AI', color: 'bg-blue-600' },
                  { step: '3', title: 'VECTOR_SEARCH', desc: 'BigQuery 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-red-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 6 — Food Intelligence                                         */}
        {/* ================================================================= */}
        {activeTab === 'foodIntel' && (
          <div className="space-y-6">
            {/* 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 Gemini 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-red-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-red-600 rounded-full flex items-center justify-center text-white shrink-0">
                    <BotIcon />
                  </div>
                  <div className="bg-gradient-to-r from-red-600/20 to-orange-600/20 rounded-lg p-4 flex-1 border border-red-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>
        )}
      </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">
          Giant Eagle Eagle AI Data Insights Dashboard — Powered by BigQuery + Vertex AI Embeddings + Gemini
        </div>
      </footer>
    </div>
  );
};

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

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