// v2.2.1 - Production ready with debug cleanup, hardening, and i18n support
  jQuery(function($){
    // Debug flag for development
    const SPD_DEBUG = false;
    
    SPD_DEBUG && console.log('Store Performance Dashboard: jQuery loaded, version:', $.fn.jquery);
    
    // Ensure jsVectorMap can paint series colors (blue shading)
    (function ensureMapCSS(){
      if (document.getElementById('spd-map-style')) return;
      const st = document.createElement('style');
      st.id = 'spd-map-style';
      st.textContent = `
        /* keep only hover opacity if you want */
        #spd-worldmap svg .jvm-region:hover { fill-opacity: .85; }
      `;
      document.head.appendChild(st);
    })();
  const root = $('#spd-root');
  const MODE_KEY='spd-mode'; function setMode(m){root.toggleClass('spd-light',m==='light');}
  let mode=localStorage.getItem(MODE_KEY)||'dark'; setMode(mode);
  $('#spd-mode-toggle').on('click',()=>{
    mode=(mode==='dark')?'light':'dark';
    localStorage.setItem(MODE_KEY,mode);
    setMode(mode);
    // Reinitialize tooltips with new mode colors
    setTimeout(initModernTooltips, 100);
    // Update Chart.js tooltip styles for new theme
    setTimeout(updateChartTooltipStyles, 100);
    // Update PRO card images on theme toggle
    setTimeout(() => {
      $('.spd-pro-image').each(function() {
        const $img = $(this);
        const currentSrc = $img.attr('src');
        const isLight = root.hasClass('spd-light');
        const newTheme = isLight ? 'light' : 'dark';
        
        // Update image source to match current theme
        if (currentSrc.includes('-light.png') || currentSrc.includes('-dark.png')) {
          const newSrc = currentSrc.replace(/-light\.png|-dark\.png/, '-' + newTheme + '.png');
          $img.attr('src', newSrc);
        }
      });
    }, 0);
  });

  // Settings functionality
  const SETTINGS_KEY = 'spd-settings';
  const defaultSettings = {
    cards: {
      'total-sales': { enabled: true, cols: 3, order: 1 },
      'orders': { enabled: true, cols: 3, order: 2 },
      'net-profit': { enabled: true, cols: 3, order: 3 },
      'refund-rate': { enabled: true, cols: 3, order: 4 },
      'orders-by-category': { enabled: true, cols: 3, order: 5 },
      'avg-order-value': { enabled: true, cols: 3, order: 6 },
      'customers': { enabled: true, cols: 3, order: 7 },
      'repeat-purchase-rate': { enabled: true, cols: 3, order: 8 },
      'heatmap': { enabled: true, cols: 3, order: 9 },
      'payment-methods': { enabled: true, cols: 3, order: 10 },
      'world-map': { enabled: true, cols: 6, order: 11 },
      'top-products': { enabled: true, cols: 2, order: 12 },
      'coupon-impact': { enabled: true, cols: 3, order: 13 },
      'returns-by-product': { enabled: true, cols: 3, order: 14 }
    }
  };
  
  let currentSettings = JSON.parse(localStorage.getItem(SETTINGS_KEY) || JSON.stringify(defaultSettings));
  
  // Ensure all cards exist in settings (for new cards added in updates)
  function migrateSettings() {
    let needsUpdate = false;
    
    // Add any missing cards from defaultSettings
    Object.keys(defaultSettings.cards).forEach(cardId => {
      if (!currentSettings.cards[cardId]) {
        currentSettings.cards[cardId] = defaultSettings.cards[cardId];
        needsUpdate = true;
      }
    });
    
    // Remove any old cards that no longer exist
    Object.keys(currentSettings.cards).forEach(cardId => {
      if (!defaultSettings.cards[cardId]) {
        delete currentSettings.cards[cardId];
        needsUpdate = true;
      }
    });
    
    // Save if changes were made
    if (needsUpdate) {
      localStorage.setItem(SETTINGS_KEY, JSON.stringify(currentSettings));
    }
  }
  
  // Run migration
  migrateSettings();
  
  // Settings panel controls
  // About panel controls
  $('#spd-about-toggle').on('click', () => {
    $('#spd-about-panel, #spd-about-overlay').addClass('active');
  });
  
  $('#spd-about-close, #spd-about-overlay').on('click', () => {
    $('#spd-about-panel, #spd-about-overlay').removeClass('active');
  });

  $('#spd-settings-toggle').on('click', () => {
    $('#spd-settings-panel, #spd-settings-overlay').addClass('active');
  });
  
  $('#spd-settings-close, #spd-settings-overlay').on('click', () => {
    $('#spd-settings-panel, #spd-settings-overlay').removeClass('active');
  });
  
  $('#spd-settings-reset').on('click', () => {
    currentSettings = JSON.parse(JSON.stringify(defaultSettings));
    localStorage.setItem(SETTINGS_KEY, JSON.stringify(currentSettings));
    renderSettingsPanel();
    render();
  });
  
  $('#spd-settings-save').on('click', () => {
    localStorage.setItem(SETTINGS_KEY, JSON.stringify(currentSettings));
    $('#spd-settings-panel, #spd-settings-overlay').removeClass('active');
    render();
  });
  
  // Debug: Add test button for reordering (only in debug mode)
  if (SPD_DEBUG) {
    $('#spd-settings-reset').after('<button id="spd-test-reorder" class="button" style="margin-left: 10px;">Test Reorder</button>');
    $('#spd-test-reorder').on('click', () => {
      SPD_DEBUG && console.log('Testing reorder...');
      SPD_DEBUG && console.log('Current settings:', currentSettings);
      
      // Test: Move first card to last position
      const sortedCards = Object.entries(currentSettings.cards).sort((a, b) => a[1].order - b[1].order);
      if (sortedCards.length > 1) {
        const firstCard = sortedCards[0][0];
        const lastCard = sortedCards[sortedCards.length - 1][0];
        
        SPD_DEBUG && console.log('Moving', firstCard, 'to position after', lastCard);
        
        // Update orders
        currentSettings.cards[firstCard].order = sortedCards.length + 1;
        
        // Re-render
        renderSettingsPanel();
        render();
      }
    });
  }

  const periodSel=$('#spd-period'); const grid=$('#spd-grid');

  function money(v){return new Intl.NumberFormat(undefined,{style:'currency',currency:SPD.currency||'USD'}).format(Number(v||0));}
  function pct(v){const s=v>0?'+':'';return s+Number(v||0).toFixed(2)+'%';}
  const palette=(n)=>Array.from({length:n},(_,i)=>`hsl(${Math.round(i*360/Math.max(1,n))} 80% 50%)`);
  
  // Function to get appropriate comparison text based on period
  function getComparisonText(period) {
    switch(period) {
      case 'today':
        return ' vs same day last week';
      case 'yesterday':
        return ' vs same day last week';
      case 'this_week':
        return ' vs previous week';
      case 'last_week':
        return ' vs week before last';
      case 'month_to_date':
        return ' vs previous month to date';
      case 'last_30':
        return ' vs previous period';
      case 'last_month':
        return ' vs month before last';
      case 'this_quarter':
        return ' vs previous quarter';
      case 'last_quarter':
        return ' vs quarter before last';
      case 'this_year':
        return ' vs previous year';
      case 'last_year':
        return ' vs year before last';
      default:
        return ' vs previous period';
    }
  }

  // Render settings panel
  function renderSettingsPanel() {
    const container = $('#spd-card-settings').empty();
    
    // Sort cards by order
    const sortedCards = Object.entries(currentSettings.cards).sort((a, b) => a[1].order - b[1].order);
    
    // Debug: Log current order
    SPD_DEBUG && console.log('Current card order in settings:', sortedCards.map(([id, settings]) => `${id} (order: ${settings.order})`));
    
    sortedCards.forEach(([cardId, settings]) => {
      const cardName = cardId.split('-').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');
      const cardItem = $(`
        <div class="spd-card-item ${settings.enabled ? '' : 'disabled'}" data-card="${cardId}" data-order="${settings.order}">
          <div class="spd-card-header">
            <div class="spd-card-drag">⋮⋮</div>
            <div class="spd-card-title">${cardName}</div>
            <div class="spd-card-toggle ${settings.enabled ? 'active' : ''}" data-card="${cardId}"></div>
          </div>
          <div class="spd-card-controls">
            <div class="spd-control-group">
              <div class="spd-control-label">Columns</div>
              <div class="spd-control-inputs">
                <button class="spd-control-btn" data-action="cols-decrease" data-card="${cardId}" ${settings.cols <= 1 ? 'disabled' : ''}>−</button>
                <div class="spd-control-value" data-card="${cardId}" data-type="cols">${settings.cols}</div>
                <button class="spd-control-btn" data-action="cols-increase" data-card="${cardId}" ${settings.cols >= 12 ? 'disabled' : ''}>+</button>
              </div>
            </div>
          </div>
        </div>
      `);
      
      container.append(cardItem);
    });
    
    // Bind events
    $('.spd-card-toggle').on('click', function() {
      const cardId = $(this).data('card');
      currentSettings.cards[cardId].enabled = !currentSettings.cards[cardId].enabled;
      $(this).toggleClass('active');
      $(this).closest('.spd-card-item').toggleClass('disabled');
    });
    
    $('.spd-control-btn').on('click', function() {
      const cardId = $(this).data('card');
      const action = $(this).data('action');
      const card = currentSettings.cards[cardId];
      
      if (action === 'cols-decrease' && card.cols > 1) {
        card.cols--;
      } else if (action === 'cols-increase' && card.cols < 12) {
        card.cols++;
      }
      
      // Update display
      $(`.spd-control-value[data-card="${cardId}"][data-type="cols"]`).text(card.cols);
      
      // Update button states
      $(`.spd-control-btn[data-card="${cardId}"][data-action="cols-decrease"]`).prop('disabled', card.cols <= 1);
      $(`.spd-control-btn[data-card="${cardId}"][data-action="cols-increase"]`).prop('disabled', card.cols >= 12);
    });
    
    // Initialize drag and drop
    initDragAndDrop();
  }
  
  // Drag and drop functionality
  function initDragAndDrop() {
    let isDragging = false;
    let draggedElement = null;
    let draggedCardId = null;
    
    // Handle mouse down on drag handle
    $('.spd-card-settings').on('mousedown', '.spd-card-drag', function(e) {
      e.preventDefault();
      e.stopPropagation();
      
      const $item = $(this).closest('.spd-card-item');
      draggedElement = $item;
      draggedCardId = $item.data('card');
      isDragging = true;
      
      $item.addClass('dragging');
      
      // Add global mouse event listeners
      $(document).on('mousemove.drag', handleMouseMove);
      $(document).on('mouseup.drag', handleMouseUp);
    });
    
    function handleMouseMove(e) {
      if (!isDragging) return;
      
      // Find the element under the cursor
      const elementBelow = document.elementFromPoint(e.clientX, e.clientY);
      const $targetItem = $(elementBelow).closest('.spd-card-item');
      
      if ($targetItem.length && $targetItem[0] !== draggedElement[0]) {
        // Remove previous drop indicators
        $('.spd-card-item').removeClass('drop-above drop-below');
        
        // Determine if we should drop above or below
        const rect = $targetItem[0].getBoundingClientRect();
        const midY = rect.top + rect.height / 2;
        
        if (e.clientY < midY) {
          $targetItem.addClass('drop-above');
        } else {
          $targetItem.addClass('drop-below');
        }
      } else {
        // Remove all drop indicators if not over a valid target
        $('.spd-card-item').removeClass('drop-above drop-below');
      }
    }
    
    function handleMouseUp(e) {
      if (!isDragging) return;
      
      // Find the target element
      const elementBelow = document.elementFromPoint(e.clientX, e.clientY);
      const $targetItem = $(elementBelow).closest('.spd-card-item');
      
      if ($targetItem.length && $targetItem[0] !== draggedElement[0]) {
        const targetCardId = $targetItem.data('card');
        
        // Get current order from settings
        const currentOrder = Object.entries(currentSettings.cards)
          .filter(([_, settings]) => settings.enabled)
          .sort((a, b) => a[1].order - b[1].order)
          .map(([cardId, _]) => cardId);
        
        // Find positions
        const draggedIndex = currentOrder.indexOf(draggedCardId);
        const targetIndex = currentOrder.indexOf(targetCardId);
        
        if (draggedIndex !== -1 && targetIndex !== -1) {
          // Determine final position
          let finalIndex = targetIndex;
          if ($targetItem.hasClass('drop-below')) {
            finalIndex = targetIndex + 1;
          }
          
                  SPD_DEBUG && console.log('Drag operation:', {
          draggedCard: draggedCardId,
          targetCard: targetCardId,
          draggedIndex: draggedIndex,
          targetIndex: targetIndex,
          finalIndex: finalIndex,
          currentOrder: currentOrder
        });
          
          // Reorder the array
          const newOrder = [...currentOrder];
          newOrder.splice(draggedIndex, 1);
          newOrder.splice(finalIndex, 0, draggedCardId);
          
          SPD_DEBUG && console.log('New order:', newOrder);
          
          // Update order in settings
          newOrder.forEach((cardId, index) => {
            currentSettings.cards[cardId].order = index + 1;
          });
          
          // Re-render settings panel
          renderSettingsPanel();
        }
      } else {
        // Fallback: try to find target by position
        const mouseY = e.clientY;
        const $allItems = $('.spd-card-settings .spd-card-item');
        let insertIndex = $allItems.length;
        
        $allItems.each(function(index) {
          const rect = this.getBoundingClientRect();
          if (mouseY < rect.top + rect.height / 2) {
            insertIndex = index;
            return false; // break the loop
          }
        });
        
        // Get current order from settings
        const currentOrder = Object.entries(currentSettings.cards)
          .filter(([_, settings]) => settings.enabled)
          .sort((a, b) => a[1].order - b[1].order)
          .map(([cardId, _]) => cardId);
        
        const draggedIndex = currentOrder.indexOf(draggedCardId);
        
        if (draggedIndex !== -1 && insertIndex !== draggedIndex && insertIndex !== draggedIndex + 1) {
          // Reorder the array
          const newOrder = [...currentOrder];
          newOrder.splice(draggedIndex, 1);
          newOrder.splice(insertIndex, 0, draggedCardId);
          
          // Update order in settings
          newOrder.forEach((cardId, index) => {
            currentSettings.cards[cardId].order = index + 1;
          });
          
          // Re-render settings panel
          renderSettingsPanel();
        }
      }
      
      // Clean up
      $('.spd-card-item').removeClass('dragging drop-above drop-below');
      $(document).off('mousemove.drag mouseup.drag');
      isDragging = false;
      draggedElement = null;
      draggedCardId = null;
    }
  }

  // --------- AOV Canvas Speedo ----------
  function drawSpeedo(canvas, value, max){
    const ctx=canvas.getContext('2d');
    const w=canvas.clientWidth||300, h=canvas.clientHeight||200;
    const dpr=window.devicePixelRatio||1; canvas.width=w*dpr; canvas.height=h*dpr; ctx.setTransform(dpr,0,0,dpr,0,0);
    ctx.clearRect(0,0,w,h);

    const cx=w/2, cy=h*0.85, r=Math.min(w*0.4,h*0.75);
    const start=Math.PI, end=2*Math.PI;
    const zones=[[0,max*0.33,'#ef4444'],[max*0.33,max*0.66,'#eab308'],[max*0.66,max,'#22c55e']];
    zones.forEach(z=>{ctx.beginPath();ctx.arc(cx,cy,r,start+(z[0]/max)*(end-start),start+(z[1]/max)*(end-start));ctx.lineWidth=Math.max(14,r*0.08);ctx.lineCap='round';ctx.strokeStyle=z[2];ctx.stroke();});

    const v=Math.max(0,Math.min(value,max)); const ang=start+(v/max)*(end-start);
    const nx=cx+Math.cos(ang)*r*0.9, ny=cy+Math.sin(ang)*r*0.9;

    ctx.save();
    ctx.shadowColor='rgba(0,0,0,0.5)'; ctx.shadowBlur=8; ctx.shadowOffsetY=3;
    ctx.beginPath(); ctx.moveTo(cx,cy); ctx.lineTo(nx,ny); ctx.lineWidth=6;
    ctx.strokeStyle=root.hasClass('spd-light')?'#1f2937':'#ffffff';
    ctx.stroke(); ctx.restore();

    ctx.beginPath(); ctx.arc(cx,cy,8,0,Math.PI*2); ctx.fillStyle=root.hasClass('spd-light')?'#1f2937':'#ffffff'; ctx.fill();
    ctx.beginPath(); ctx.arc(cx,cy,12,0,Math.PI*2); ctx.lineWidth=2; ctx.strokeStyle=root.hasClass('spd-light')?'rgba(0,0,0,.3)':'rgba(255,255,255,.4)'; ctx.stroke();

    const textCol=root.hasClass('spd-light')?'#374151':'#e5e7eb', halo=root.hasClass('spd-light')?'#fff':'#0b1020';
    ctx.font='12px system-ui,Segoe UI,Roboto'; ctx.lineWidth=3; ctx.strokeStyle=halo; ctx.fillStyle=textCol; ctx.textAlign='left'; ctx.strokeText('$0',10,h-8); ctx.fillText('$0',10,h-8);
    ctx.textAlign='right'; ctx.strokeText('$'+Math.round(max),w-10,h-8); ctx.fillText('$'+Math.round(max),w-10,h-8);
  }

  // PRO-only gauge functions removed - these KPIs are now placeholder images

  // --------- Render All Cards ----------
  function render(){
    grid.html('<div class="spd-card spd-col-12">Loading…</div>');
    const period=periodSel.val()||'last_30';
    
    // Apply dynamic CSS for grid layout
    const enabledCards = Object.entries(currentSettings.cards)
      .filter(([_, settings]) => settings.enabled)
      .sort((a, b) => a[1].order - b[1].order);
    
    // Generate CSS for dynamic grid layout (desktop only)
    let dynamicCSS = '';
    const isDesktop = window.innerWidth >= 1361;

    if (isDesktop) {
      let currentCol = 1;
      let currentRow = 1;

      enabledCards.forEach(([cardId, settings]) => {
        if (currentCol + settings.cols > 13) { currentRow++; currentCol = 1; }
        dynamicCSS += `
          .spd-card-${cardId} {
            grid-column: ${currentCol} / span ${settings.cols};
            grid-row: ${currentRow};
          }
        `;
        currentCol += settings.cols;
      });

      $('#spd-dynamic-css').remove();
      $('<style id="spd-dynamic-css">').html(dynamicCSS).appendTo('head');
    } else {
      // On non-desktop, remove any previous desktop layout CSS
      $('#spd-dynamic-css').remove();
    }

    $.post(SPD.ajax,{action:'spd_get_metrics',nonce:SPD.nonce,period},(resp)=>{
      if(!resp || !resp.success){ grid.html('<div class="spd-card spd-col-12">Error loading.</div>'); return; }
      const d=resp.data; 
      window.currentDashboardData = d; // Store for responsive handling
      grid.empty();

      // Create cards based on settings order
      const cardCreators = {
        'total-sales': () => {
          const sd = d.headline.sales_vs>=0? `<span class="spd-up">▲ ${pct(d.headline.sales_vs)}</span>`:`<span class="spd-down">▼ ${pct(d.headline.sales_vs)}</span>`;
          const card = $(`<div class="spd-card spd-card-total-sales"></div>`);
          card.append(`<h3>Total sales</h3><div class="spd-kpi">${money(d.headline.sales)}</div><div class="spd-sub">${sd} ${getComparisonText(period)}</div><canvas class="spd-chart" id="salesChart"></canvas>`);
          return card;
        },
        'orders': () => {
          const od = d.headline.orders_vs>=0? `<span class="spd-up">▲ ${pct(d.headline.orders_vs)}</span>`:`<span class="spd-down">▼ ${pct(d.headline.orders_vs)}</span>`;
          const card = $(`<div class="spd-card spd-card-orders"></div>`);
          card.append(`<h3>Orders</h3><div class="spd-kpi">${d.headline.orders}</div><div class="spd-sub">${od} ${getComparisonText(period)}</div><canvas class="spd-chart" id="ordersChart"></canvas>`);
          return card;
        },
        'net-profit': () => {
          const pv = (d.profit.vs_pct==null)? '' : (d.profit.vs_pct>=0? `<span class="spd-up">▲ ${pct(d.profit.vs_pct)}</span>`:`<span class="spd-down">▼ ${pct(d.profit.vs_pct)}</span>`) + getComparisonText(period);
          const card = $(`<div class="spd-card spd-card-net-profit"></div>`);
          card.append(`<h3>Net profit</h3><div class="spd-kpi">${money(d.profit.net)}</div><div class="spd-sub">${pv}</div><canvas class="spd-chart" id="profitChart"></canvas>`);
          return card;
        },
        'refund-rate': () => {
          const rv = (d.refunds.rate_vs==null)? '' : (d.refunds.rate_vs>=0? `<span class="spd-down">▲ ${pct(d.refunds.rate_vs)}</span>`:`<span class="spd-up">▼ ${pct(d.refunds.rate_vs)}</span>`) + getComparisonText(period);
          const card = $(`<div class="spd-card spd-card-refund-rate"></div>`);
          card.append(`<h3>Refund rate</h3><div class="spd-gauge-wrap"><canvas id="refundRateGauge" class="spd-gauge-canvas"></canvas><div class="spd-gauge-value" id="refundRateVal">${d.refunds.rate}%</div></div><div class="spd-sub">${rv}</div><div class="spd-refund-details"><div class="spd-refund-amount">${money(d.refunds.total)} refunded</div><div class="spd-refund-orders">${d.refunds.orders} orders</div></div>`);
          return card;
        },
        'avg-order-value': () => {
          const card = $(`<div class="spd-card spd-card-avg-order-value"></div>`);
          card.append('<h3>Avg. order value</h3><div class="spd-gauge-wrap"><canvas id="aovGauge" class="spd-gauge-canvas"></canvas><div class="spd-gauge-value" id="aovVal"></div><div class="spd-aov-trend" id="aovTrend"></div></div>');
          return card;
        },
        'payment-methods': () => {
          const card = $(`<div class="spd-card spd-card-payment-methods spd-pro-card"></div>`);
          card.append('<h3>Payment methods</h3><div class="spd-pro-placeholder"><img src="' + SPD.plugin_url + 'assets/LITE/KPI-Payment-Methods-' + (root.hasClass('spd-light') ? 'light' : 'dark') + '.png" alt="Payment Methods KPI" class="spd-pro-image" title="PRO Version Preview - Click to Upgrade or Turn Off in Settings" /></div>');
          return card;
        },
        'customers': () => {
          const card = $(`<div class="spd-card spd-card-customers spd-pro-card"></div>`);
          card.append('<h3>New vs returning customers</h3><div class="spd-pro-placeholder"><img src="' + SPD.plugin_url + 'assets/LITE/KPI-New-vs-Returing-' + (root.hasClass('spd-light') ? 'light' : 'dark') + '.png" alt="New vs Returning Customers KPI" class="spd-pro-image" title="PRO Version Preview - Click to Upgrade or Turn Off in Settings" /></div>');
          return card;
        },
        'repeat-purchase-rate': () => {
          const card = $(`<div class="spd-card spd-card-repeat-purchase-rate spd-pro-card"></div>`);
          card.append('<h3>Repeat purchase rate</h3><div class="spd-pro-placeholder"><img src="' + SPD.plugin_url + 'assets/LITE/KPI-Repeat-Purchase-Rate-' + (root.hasClass('spd-light') ? 'light' : 'dark') + '.png" alt="Repeat Purchase Rate KPI" class="spd-pro-image" title="PRO Version Preview - Click to Upgrade or Turn Off in Settings" /></div>');
          return card;
        },
        'coupon-impact': () => {
          const card = $(`<div class="spd-card spd-card-coupon-impact spd-pro-card"></div>`);
          card.append('<h3>Coupon/discount impact</h3><div class="spd-pro-placeholder"><img src="' + SPD.plugin_url + 'assets/LITE/KPI-Coupons-' + (root.hasClass('spd-light') ? 'light' : 'dark') + '.png" alt="Coupon Impact KPI" class="spd-pro-image" title="PRO Version Preview - Click to Upgrade or Turn Off in Settings" /></div>');
          return card;
        },
        'returns-by-product': () => {
          const card = $(`<div class="spd-card spd-card-returns-by-product spd-pro-card"></div>`);
          card.append('<h3>Returns by product</h3><div class="spd-pro-placeholder"><img src="' + SPD.plugin_url + 'assets/LITE/KPI-Returns-' + (root.hasClass('spd-light') ? 'light' : 'dark') + '.png" alt="Returns by Product KPI" class="spd-pro-image" title="PRO Version Preview - Click to Upgrade or Turn Off in Settings" /></div>');
          return card;
        },
        'heatmap': () => {
          const card = $(`<div class="spd-card spd-card-heatmap spd-pro-card"></div>`);
          card.append('<h3>Orders by day & hour</h3><div class="spd-pro-placeholder"><img src="' + SPD.plugin_url + 'assets/LITE/KPI-Orders-Heatmap-' + (root.hasClass('spd-light') ? 'light' : 'dark') + '.png" alt="Orders Heatmap KPI" class="spd-pro-image" title="PRO Version Preview - Click to Upgrade or Turn Off in Settings" /></div>');
          return card;
        },
        'world-map': () => {
          const card = $(`<div class="spd-card spd-card-world-map spd-pro-card"></div>`);
          card.append('<h3>Sales by location (world)</h3><div class="spd-pro-placeholder"><img src="' + SPD.plugin_url + 'assets/LITE/KPI-Sales-by-Location-' + (root.hasClass('spd-light') ? 'light' : 'dark') + '.png" alt="Sales by Location KPI" class="spd-pro-image" title="PRO Version Preview - Click to Upgrade or Turn Off in Settings" /></div>');
          return card;
        },
        'orders-by-category': () => {
          const card = $(`<div class="spd-card spd-card-orders-by-category"></div>`);
          card.append('<h3>Orders by category</h3><canvas class="spd-chart spd-pie" id="catPie"></canvas><ul class="spd-list" id="catList"></ul>');
          return card;
        },
        'top-products': () => {
          const card = $(`<div class="spd-card spd-card-top-products spd-pro-card"></div>`);
          card.append('<h3>Top products</h3><div class="spd-pro-placeholder"><img src="' + SPD.plugin_url + 'assets/LITE/KPI-Top-Products-' + (root.hasClass('spd-light') ? 'light' : 'dark') + '.png" alt="Top Products KPI" class="spd-pro-image" title="PRO Version Preview - Click to Upgrade or Turn Off in Settings" /></div>');
          return card;
        }
      };

      // Create and append cards in the correct order
      SPD_DEBUG && console.log('Rendering cards in order:', enabledCards.map(([id, settings]) => `${id} (order: ${settings.order})`));
      
      enabledCards.forEach(([cardId, settings]) => {
        if (cardCreators[cardId]) {
          const card = cardCreators[cardId]();
          grid.append(card);
          SPD_DEBUG && console.log('Appended card:', cardId);
        }
      });

      // Add click handlers for PRO cards
      $('.spd-pro-card').on('click', function() {
        window.open('https://auscomp.com/product/store-analytics-for-woocommerce', '_blank');
      });

      // ----- Charts -----
      // Sales Chart
      if (currentSettings.cards['total-sales'].enabled && document.getElementById('salesChart')) {
        try {
          const salesChart = new Chart(document.getElementById('salesChart').getContext('2d'),{
          type:'line',
          data:{labels:d.series.labels,datasets:[
            {label:'period',data:d.series.this,tension:.3,borderWidth:2,fill:false},
            {label:'previous',data:d.series.compare,tension:.3,borderWidth:2,borderDash:[5,5],fill:false}
          ]},
          options:{
            responsive:true,
            maintainAspectRatio:false,
            plugins:{
              tooltip:{
                backgroundColor: '#0f172a',
                borderColor: '#1f2937',
                borderWidth: 1,
                cornerRadius: 8,
                titleColor: '#e5e7eb',
                bodyColor: '#e5e7eb',
                displayColors: false,
                padding: 12,
                titleFont: { size: 13, weight: '600' },
                bodyFont: { size: 13 },
                callbacks:{
                  title: function(context) {
                    return context[0].label;
                  },
                  label: function(context) {
                    return context.dataset.label + ': ' + money(context.parsed.y);
                  }
                }
              }
            },
            scales:{
              y:{
                beginAtZero:true,
                ticks: {
                  font: { size: window.innerWidth <= 480 ? 8 : 10 }
                }
              },
              x: {
                ticks: {
                  font: { size: window.innerWidth <= 480 ? 8 : 10 },
                  maxRotation: 45,
                  minRotation: 45,
                  autoSkip: true,
                  maxTicksLimit: window.innerWidth <= 480 ? 5 : 8
                }
              }
            },
            layout: {
              padding: {
                top: window.innerWidth <= 480 ? 5 : 10,
                right: window.innerWidth <= 480 ? 5 : 10,
                bottom: window.innerWidth <= 480 ? 10 : 15,
                left: window.innerWidth <= 480 ? 5 : 10
              }
            }
          }
        });
        
        SPD_DEBUG && console.log('Sales chart created successfully');
        } catch (error) {
          console.error('Error creating sales chart:', error);
          const canvas = document.getElementById('salesChart');
          if (canvas) {
            canvas.style.display = 'none';
          }
        }
      }

      // Orders Chart
      if (currentSettings.cards['orders'].enabled && document.getElementById('ordersChart')) {
        try {
          const estThis = d.aov? d.series.this.map(v=>Math.round(v/d.aov)) : d.series.compare.map(()=>0);
          const estPrev = d.aov? d.series.compare.map(v=>Math.round(v/d.aov)) : d.series.compare.map(()=>0);
          const ordersChart = new Chart(document.getElementById('ordersChart').getContext('2d'),{
          type:'bar', 
          data:{labels:d.series.labels,datasets:[{label:'period',data:estThis},{label:'previous',data:estPrev}]},
          options:{
            responsive:true,
            maintainAspectRatio:false,
            plugins:{
              tooltip:{
                backgroundColor: '#0f172a',
                borderColor: '#1f2937',
                borderWidth: 1,
                cornerRadius: 8,
                titleColor: '#e5e7eb',
                bodyColor: '#e5e7eb',
                displayColors: false,
                padding: 12,
                titleFont: { size: 13, weight: '600' },
                bodyFont: { size: 13 },
                callbacks:{
                  title: function(context) {
                    return context[0].label;
                  },
                  label: function(context) {
                    return context.dataset.label + ': ' + context.parsed.y + ' orders';
                  }
                }
              }
            },
            scales:{
              y:{
                beginAtZero:true,
                ticks: {
                  font: { size: window.innerWidth <= 480 ? 8 : 10 }
                }
              },
              x: {
                ticks: {
                  font: { size: window.innerWidth <= 480 ? 8 : 10 },
                  maxRotation: 45,
                  minRotation: 45,
                  autoSkip: true,
                  maxTicksLimit: window.innerWidth <= 480 ? 5 : 8
                }
              }
            },
            layout: {
              padding: {
                top: window.innerWidth <= 480 ? 5 : 10,
                right: window.innerWidth <= 480 ? 5 : 10,
                bottom: window.innerWidth <= 480 ? 10 : 15,
                left: window.innerWidth <= 480 ? 5 : 10
              }
            }
          }
        });
        
        SPD_DEBUG && console.log('Orders chart created successfully');
        } catch (error) {
          console.error('Error creating orders chart:', error);
          const canvas = document.getElementById('ordersChart');
          if (canvas) {
            canvas.style.display = 'none';
          }
        }
      }

      // Net Profit trend chart
      if (currentSettings.cards['net-profit'].enabled && document.getElementById('profitChart')) {
        try {
          const profitChart = new Chart(document.getElementById('profitChart').getContext('2d'),{
        type:'line',
        data:{
          labels:d.profit_series.labels,
          datasets:[
            {
              label:'Current period',
              data:d.profit_series.this,
              borderColor:'#22c55e',
              backgroundColor:'rgba(34, 197, 94, 0.1)',
              borderWidth:2,
              fill:true,
              tension:0.3
            },
            {
              label:'Previous period',
              data:d.profit_series.compare,
              borderColor:'#ef4444',
              backgroundColor:'rgba(239, 68, 68, 0.1)',
              borderWidth:2,
              borderDash:[5,5],
              fill:false,
              tension:0.3
            }
          ]
        },
        options:{
          responsive:true,
          maintainAspectRatio:false,
          plugins:{
            legend:{display:false},
            tooltip:{
              backgroundColor: '#0f172a',
              borderColor: '#1f2937',
              borderWidth: 1,
              cornerRadius: 8,
              titleColor: '#e5e7eb',
              bodyColor: '#e5e7eb',
              displayColors: false,
              padding: 12,
              titleFont: { size: 13, weight: '600' },
              bodyFont: { size: 13 },
              callbacks:{
                title: function(context) {
                  return context[0].label;
                },
                label:function(context){
                  return context.dataset.label + ': ' + money(context.parsed.y);
                }
              }
            }
          },
          scales:{
            y:{
              beginAtZero:true,
              ticks:{
                callback:function(value){
                  return money(value);
                },
                font: { size: window.innerWidth <= 480 ? 8 : 10 }
              }
            },
            x:{
              ticks:{
                maxTicksLimit: window.innerWidth <= 480 ? 5 : 8,
                font: { size: window.innerWidth <= 480 ? 8 : 10 },
                maxRotation: 45,
                minRotation: 45,
                autoSkip: true
              }
            }
          },
          elements:{
            point:{
              radius:0,
              hoverRadius:4
            }
          },
          layout: {
            padding: {
              top: window.innerWidth <= 480 ? 5 : 10,
              right: window.innerWidth <= 480 ? 5 : 10,
              bottom: window.innerWidth <= 480 ? 10 : 15,
              left: window.innerWidth <= 480 ? 5 : 10
            }
          }
        }
      });
      
      SPD_DEBUG && console.log('Profit chart created successfully');
      } catch (error) {
        console.error('Error creating profit chart:', error);
        const canvas = document.getElementById('profitChart');
        if (canvas) {
          canvas.style.display = 'none';
        }
      }
      }

      // AOV gauge
      if (currentSettings.cards['avg-order-value'].enabled && document.getElementById('aovGauge')) {
        const aov=d.aov||0; const aovMax=Math.max(Math.ceil(aov*1.6/10)*10,50);
        $('#aovVal').text(money(aov));
        
        // Calculate AOV trend (mock data for now - you can replace with actual comparison data)
        const aovTrend = 12.3; // Mock trend percentage
        const trendIcon = aovTrend >= 0 ? '▲' : '▼';
        const trendClass = aovTrend >= 0 ? 'spd-up' : 'spd-down';
        const trendSign = aovTrend >= 0 ? '+' : '';
        
        $('#aovTrend').html(`
          <div class="spd-aov-trend-icon ${trendClass}">${trendIcon}</div>
          <div class="${trendClass}">${trendSign}${aovTrend.toFixed(1)}%</div>
          <div class="spd-aov-trend-text">vs previous period</div>
        `);
        
        const aovCanvas=document.getElementById('aovGauge'); drawSpeedo(aovCanvas,aov,aovMax);
        let to=null; $(window).on('resize',()=>{clearTimeout(to); to=setTimeout(()=>drawSpeedo(aovCanvas,aov,aovMax),120);});
      }

      // Refund Rate gauge
      if (currentSettings.cards['refund-rate'].enabled && document.getElementById('refundRateGauge')) {
        const refundRate=d.refunds.rate||0; const refundRateMax=Math.max(Math.ceil(refundRate*1.6/10)*10,20);
        $('#refundRateVal').text(refundRate.toFixed(1) + '%');
        const refundRateCanvas=document.getElementById('refundRateGauge'); drawSpeedo(refundRateCanvas,refundRate,refundRateMax);
        let to2=null; $(window).on('resize',()=>{clearTimeout(to2); to2=setTimeout(()=>drawSpeedo(refundRateCanvas,refundRate,refundRateMax),120);});
      }

      // Customers gauge (PRO only - placeholder image)
      if (currentSettings.cards['customers'].enabled) {
        // Customers gauge is now a PRO-only placeholder image
      }

      // Repeat Purchase Rate gauge (PRO only - placeholder image)
      if (currentSettings.cards['repeat-purchase-rate'].enabled) {
        // Repeat Purchase Rate gauge is now a PRO-only placeholder image
      }

      // Coupon Impact gauge (PRO only - placeholder image)
      if (currentSettings.cards['coupon-impact'].enabled) {
        // Coupon Impact gauge is now a PRO-only placeholder image
      }

      // Returns by Product gauge (PRO only - placeholder image)
      if (currentSettings.cards['returns-by-product'].enabled) {
        // Returns by Product gauge is now a PRO-only placeholder image
      }

      // ----- WORLD MAP (PRO only - placeholder image) -----
      if (currentSettings.cards['world-map'].enabled) {
        // World map is now a PRO-only placeholder image
      }

      // Category pie & list
      if (currentSettings.cards['orders-by-category'].enabled && document.getElementById('catPie')) {
        const cats=Object.entries(d.breakdown.orders_by_category);
        const catLabels=cats.map(([c])=>c); const catData=cats.map(([_,v])=>v);
        const total=(catData.reduce((a,b)=>a+b,0))||1; const colors=palette(catLabels.length);
        new Chart(document.getElementById('catPie').getContext('2d'),{
          type:'doughnut',
          data:{labels:catLabels,datasets:[{data:catData,backgroundColor:colors}]},
          options:{
            plugins:{
              legend:{display:false},
              tooltip:{
                backgroundColor: 'var(--card-bg)',
                borderColor: 'var(--border)',
                borderWidth: 1,
                cornerRadius: 8,
                titleColor: '#ffffff',
                bodyColor: '#ffffff',
                displayColors: true,
                padding: 12,
                titleFont: { size: 13, weight: '600' },
                bodyFont: { size: 13 },
                callbacks:{
                  title: function(context) {
                    return context[0].label;
                  },
                  label: function(context) {
                    const total = context.dataset.data.reduce((a, b) => a + b, 0);
                    const percentage = ((context.parsed / total) * 100).toFixed(1);
                    return `${context.parsed} orders (${percentage}%)`;
                  }
                },
                bodyAlign: 'left',
                titleAlign: 'left'
              }
            },
            responsive:true,
            maintainAspectRatio:true,
            aspectRatio:1,
            cutout:'55%'
          }
        });
        catLabels.forEach((l,i)=>{ const p=(catData[i]/total*100).toFixed(1); $('#catList').append(`<li><div><span class="spd-dot" style="background:${colors[i]}"></span>${l} <span class="spd-pill">${p}%</span></div><strong>${catData[i]}</strong><div class="spd-progress"><span style="width:${p}%"></span></div></li>`);});
      }

      // Top products (PRO only - placeholder image)
      if (currentSettings.cards['top-products'].enabled) {
        // Top products is now a PRO-only placeholder image
      }

      // Render heatmap (PRO only - placeholder image)
      if (currentSettings.cards['heatmap'].enabled) {
        // Heatmap is now a PRO-only placeholder image
      }

      // Render payment methods (PRO only - placeholder image)
      if (currentSettings.cards['payment-methods'].enabled) {
        // Payment methods is now a PRO-only placeholder image
      }

      // Render customers (PRO only - placeholder image)
      if (currentSettings.cards['customers'].enabled) {
        // Customers is now a PRO-only placeholder image
      }

      // Render repeat purchase rate (PRO only - placeholder image)
      if (currentSettings.cards['repeat-purchase-rate'].enabled) {
        // Repeat purchase rate is now a PRO-only placeholder image
      }

      // Render coupon impact (PRO only - placeholder image)
      if (currentSettings.cards['coupon-impact'].enabled) {
        // Coupon impact is now a PRO-only placeholder image
      }

      // Render returns by product (PRO only - placeholder image)
      if (currentSettings.cards['returns-by-product'].enabled) {
        // Returns by product is now a PRO-only placeholder image
      }
    });
  }
  
  // PRO-only render functions removed - these KPIs are now placeholder images
  
  // PRO-only heatmap color function removed - heatmap is now a placeholder image

  render();
  periodSel.on('change',render);
  
  // Initial responsive text handling
  setTimeout(handleResponsiveTextTruncation, 100);
  
  // Initial grid responsiveness
  setTimeout(forceGridResponsive, 100);
  
  // Handle responsive behavior
  $(window).on('resize', function() {
    // Debounce resize events
    clearTimeout(window.resizeTimeout);
    window.resizeTimeout = setTimeout(function() {
      // Re-render charts and gauges for responsive behavior
      if (window.currentDashboardData) {
        renderChartsResponsive(window.currentDashboardData);
      }
      // Force grid recalculation
      forceGridResponsive();
    }, 250);
  });
  
  // Function to force grid responsiveness
  function forceGridResponsive() {
    const w = window.innerWidth;
    const $grid = $('#spd-grid');
    const $cards = $grid.children('.spd-card');

    if (w <= 768) {
      $grid.css({ display: 'grid', gridTemplateColumns: '1fr' });
      $cards.css({ gridColumn: '1 / -1', gridRow: 'auto' });  // span full track, free the row
    } else if (w <= 1024) {
      $grid.css({ display: 'grid', gridTemplateColumns: 'repeat(2, minmax(0,1fr))' });
      $cards.css({ gridColumn: 'auto', gridRow: 'auto' });
    } else if (w <= 1360) {
      $grid.css({ display: 'grid', gridTemplateColumns: 'repeat(3, minmax(0,1fr))' });
      $cards.css({ gridColumn: 'auto', gridRow: 'auto' });
    } else {
      // Desktop: let the dynamic CSS (12-col) take over again
      $grid.css({ display: 'grid', gridTemplateColumns: 'repeat(12, 1fr)' });
      $cards.css({ gridRow: '', gridColumn: '' });
    }
  }
  
  // Function to handle responsive chart rendering
  function renderChartsResponsive(data) {
    // Re-render gauges with responsive sizing
    if (currentSettings.cards['avg-order-value'].enabled && document.getElementById('aovGauge')) {
      const aov = data.aov || 0;
      const aovMax = Math.max(Math.ceil(aov * 1.6 / 10) * 10, 50);
      const aovCanvas = document.getElementById('aovGauge');
      drawSpeedo(aovCanvas, aov, aovMax);
    }
    
    if (currentSettings.cards['refund-rate'].enabled && document.getElementById('refundRateGauge')) {
      const refundRate = data.refunds.rate || 0;
      const refundRateMax = Math.max(Math.ceil(refundRate * 1.6 / 10) * 10, 20);
      const refundRateCanvas = document.getElementById('refundRateGauge');
      drawSpeedo(refundRateCanvas, refundRate, refundRateMax);
    }
    
    // PRO-only KPIs removed from responsive rendering - they are now placeholder images
    
    // Handle responsive text truncation for KPI cards
    handleResponsiveTextTruncation();
  }
  
  // Function to handle responsive text truncation
  function handleResponsiveTextTruncation() {
    const isMobile = window.innerWidth <= 600;
    const isTablet = window.innerWidth <= 800;
    
    // Truncate long text on smaller screens
    $('.spd-customer-title, .spd-repeat-purchase-label, .spd-coupon-top-name').each(function() {
      const $element = $(this);
      const originalText = $element.attr('data-original-text') || $element.text();
      
      if (!isMobile && !isTablet) {
        // Restore original text on larger screens
        $element.text(originalText);
        return;
      }
      
      // Store original text if not already stored
      if (!$element.attr('data-original-text')) {
        $element.attr('data-original-text', originalText);
      }
      
      // Truncate text based on screen size
      let maxLength = isMobile ? 8 : 12;
      if (originalText.length > maxLength) {
        $element.text(originalText.substring(0, maxLength) + '...');
      }
    });
  }
  
  // Initialize settings panel
  renderSettingsPanel();
  
  // Modern Tooltip System
  function initModernTooltips() {
    SPD_DEBUG && console.log('Initializing modern tooltips...');
    
    // Remove any existing tooltip elements
    $('.spd-tooltip').remove();
    
    // Check if we're in light mode
    const isLightMode = root.hasClass('spd-light');
    const bgColor = isLightMode ? '#ffffff' : '#0f172a';
    const textColor = isLightMode ? '#111827' : '#e5e7eb';
    const borderColor = isLightMode ? '#e5e7eb' : '#1f2937';
    const accentColor = isLightMode ? '#4f46e5' : '#6366f1';
    
    // Create tooltip container with explicit styling
    const tooltip = $(`<div class="spd-tooltip" style="background: ${bgColor} !important; background-color: ${bgColor} !important; color: ${textColor} !important; border-color: ${borderColor} !important; z-index: 999999 !important;"></div>`);
    $('body').append(tooltip);
    
    // Handle tooltip events - use more specific event names to avoid conflicts
    $(document).off('mouseenter.spd-heatmap-tooltip mouseleave.spd-heatmap-tooltip mousemove.spd-heatmap-tooltip');
    
    $(document).on('mouseenter.spd-heatmap-tooltip', '[data-tooltip]', function(e) {
              SPD_DEBUG && console.log('Tooltip hover detected:', $(this).data('tooltip'));
      const $this = $(this);
      const tooltipData = $this.data('tooltip');
      
      // Build tooltip content
      let tooltipContent = '';
      if (typeof tooltipData === 'string') {
        try {
          const parsedData = JSON.parse(tooltipData);
          tooltipContent = `
            <div class="spd-tooltip-title" style="background: ${bgColor} !important; color: ${textColor} !important;">${parsedData.title || ''}</div>
            <div class="spd-tooltip-content" style="background: ${bgColor} !important; color: ${textColor} !important;">${parsedData.content || ''}</div>
            ${parsedData.value ? `<div class="spd-tooltip-value" style="background: ${bgColor} !important; color: ${accentColor} !important;">${parsedData.value}</div>` : ''}
          `;
        } catch (e) {
          SPD_DEBUG && console.log('Failed to parse tooltip data:', tooltipData);
          tooltipContent = `<div class="spd-tooltip-content" style="background: ${bgColor} !important; color: ${textColor} !important;">${tooltipData}</div>`;
        }
      } else if (typeof tooltipData === 'object') {
        tooltipContent = `
          <div class="spd-tooltip-title" style="background: ${bgColor} !important; color: ${textColor} !important;">${tooltipData.title || ''}</div>
          <div class="spd-tooltip-content" style="background: ${bgColor} !important; color: ${textColor} !important;">${tooltipData.content || ''}</div>
          ${tooltipData.value ? `<div class="spd-tooltip-value" style="background: ${bgColor} !important; color: ${accentColor} !important;">${tooltipData.value}</div>` : ''}
        `;
      } else {
        tooltipContent = `<div class="spd-tooltip-content" style="background: ${bgColor} !important; color: ${textColor} !important;">${tooltipData || ''}</div>`;
      }
      
      tooltip.html(tooltipContent);
      tooltip.addClass('show');
      tooltip.css({
        'background': `${bgColor} !important`,
        'background-color': `${bgColor} !important`,
        'color': `${textColor} !important`,
        'border-color': `${borderColor} !important`,
        'opacity': '1 !important',
        'visibility': 'visible !important',
        'display': 'block !important',
        'z-index': '999999 !important'
      });
              SPD_DEBUG && console.log('Tooltip shown with content:', tooltipContent);
    });
    
    $(document).on('mouseleave.spd-heatmap-tooltip', '[data-tooltip]', function() {
      tooltip.removeClass('show');
    });
    
    $(document).on('mousemove.spd-heatmap-tooltip', '[data-tooltip]', function(e) {
      const tooltipWidth = tooltip.outerWidth();
      const tooltipHeight = tooltip.outerHeight();
      const windowWidth = $(window).width();
      const windowHeight = $(window).height();
      
      let left = e.pageX + 12;
      let top = e.pageY - tooltipHeight - 12;
      
      // Adjust if tooltip goes off screen
      if (left + tooltipWidth > windowWidth - 20) {
        left = e.pageX - tooltipWidth - 12;
      }
      if (top < 20) {
        top = e.pageY + 12;
        tooltip.addClass('spd-tooltip-bottom');
      } else {
        tooltip.removeClass('spd-tooltip-bottom');
      }
      
      tooltip.css({
        left: left + 'px',
        top: top + 'px'
      });
    });
    
    // Override Chart.js tooltip styles and handle Chart.js tooltip positioning
    if (window.Chart && window.Chart.defaults) {
      const isLightMode = document.querySelector('.spd-wrap').classList.contains('spd-light');
      
      if (isLightMode) {
        window.Chart.defaults.plugins.tooltip.backgroundColor = '#ffffff';
        window.Chart.defaults.plugins.tooltip.borderColor = '#e5e7eb';
        window.Chart.defaults.plugins.tooltip.titleColor = '#111827';
        window.Chart.defaults.plugins.tooltip.bodyColor = '#111827';
      } else {
        window.Chart.defaults.plugins.tooltip.backgroundColor = '#0f172a';
        window.Chart.defaults.plugins.tooltip.borderColor = '#1f2937';
        window.Chart.defaults.plugins.tooltip.titleColor = '#e5e7eb';
        window.Chart.defaults.plugins.tooltip.bodyColor = '#e5e7eb';
      }
      
      window.Chart.defaults.plugins.tooltip.borderWidth = 1;
      window.Chart.defaults.plugins.tooltip.cornerRadius = 8;
      window.Chart.defaults.plugins.tooltip.padding = 12;
      window.Chart.defaults.plugins.tooltip.displayColors = false;
      window.Chart.defaults.plugins.tooltip.titleFont = { size: 13, weight: '600' };
      window.Chart.defaults.plugins.tooltip.bodyFont = { size: 13 };
      window.Chart.defaults.plugins.tooltip.bodyAlign = 'left';
      window.Chart.defaults.plugins.tooltip.titleAlign = 'left';
      window.Chart.defaults.plugins.tooltip.boxShadow = '0 10px 25px rgba(0,0,0,0.15)';
      window.Chart.defaults.plugins.tooltip.position = 'nearest';
      window.Chart.defaults.plugins.tooltip.intersect = false;
      window.Chart.defaults.plugins.tooltip.mode = 'index';
    }
    
    // Monitor for Chart.js tooltip creation and ensure proper styling
    const observer = new MutationObserver(function(mutations) {
      mutations.forEach(function(mutation) {
        if (mutation.type === 'childList') {
          mutation.addedNodes.forEach(function(node) {
            if (node.nodeType === 1 && node.classList && node.classList.contains('chartjs-tooltip')) {
              SPD_DEBUG && console.log('Chart.js tooltip detected:', node);
              const isLightMode = document.querySelector('.spd-wrap').classList.contains('spd-light');
              
              if (isLightMode) {
                node.style.background = '#ffffff';
                node.style.backgroundColor = '#ffffff';
                node.style.border = '1px solid #e5e7eb';
                node.style.color = '#111827';
              } else {
                node.style.background = '#0f172a';
                node.style.backgroundColor = '#0f172a';
                node.style.border = '1px solid #1f2937';
                node.style.color = '#e5e7eb';
              }
              node.style.zIndex = '999999';
              node.style.opacity = '1';
              node.style.visibility = 'visible';
              node.style.boxShadow = '0 10px 25px rgba(0,0,0,0.15)';
              node.style.borderRadius = '8px';
              node.style.padding = '12px 16px';
              node.style.fontSize = '13px';
              node.style.lineHeight = '1.4';
              node.style.fontFamily = 'inherit';
              node.style.position = 'absolute';
              node.style.pointerEvents = 'none';
              
              SPD_DEBUG && console.log('Chart.js tooltip styled:', node.style.background);
            }
          });
        }
      });
    });
    
    // Start observing the document body for tooltip creation
    observer.observe(document.body, {
      childList: true,
      subtree: true
    });
  }
  
  // Initialize tooltips
  initModernTooltips();
  
  // Re-initialize tooltips when dashboard re-renders
  const tooltipRender = render;
  render = function() {
    tooltipRender();
    // Wait for DOM to be ready and heatmap to be rendered
    setTimeout(initModernTooltips, 200);
  };
  
  // Also initialize tooltips when settings are changed
  $('#spd-settings-save').on('click', function() {
    setTimeout(initModernTooltips, 300);
  });
  
  // Initialize tooltips on period change
  periodSel.on('change', function() {
    setTimeout(initModernTooltips, 300);
  });
  
  // Function to update Chart.js tooltip styles based on current theme
  function updateChartTooltipStyles() {
    if (window.Chart && window.Chart.defaults) {
      const isLightMode = document.querySelector('.spd-wrap').classList.contains('spd-light');
      
      if (isLightMode) {
        window.Chart.defaults.plugins.tooltip.backgroundColor = '#ffffff';
        window.Chart.defaults.plugins.tooltip.borderColor = '#e5e7eb';
        window.Chart.defaults.plugins.tooltip.titleColor = '#111827';
        window.Chart.defaults.plugins.tooltip.bodyColor = '#111827';
      } else {
        window.Chart.defaults.plugins.tooltip.backgroundColor = '#0f172a';
        window.Chart.defaults.plugins.tooltip.borderColor = '#1f2937';
        window.Chart.defaults.plugins.tooltip.titleColor = '#e5e7eb';
        window.Chart.defaults.plugins.tooltip.bodyColor = '#e5e7eb';
      }
      
      // Force update existing tooltips
      const tooltips = document.querySelectorAll('.chartjs-tooltip');
      tooltips.forEach(tooltip => {
        if (isLightMode) {
          tooltip.style.background = '#ffffff';
          tooltip.style.backgroundColor = '#ffffff';
          tooltip.style.border = '1px solid #e5e7eb';
          tooltip.style.color = '#111827';
        } else {
          tooltip.style.background = '#0f172a';
          tooltip.style.backgroundColor = '#0f172a';
          tooltip.style.border = '1px solid #1f2937';
          tooltip.style.color = '#e5e7eb';
        }
        tooltip.style.zIndex = '999999';
        tooltip.style.opacity = '1';
        tooltip.style.visibility = 'visible';
      });
    }
  }
  
  // Initialize Chart.js tooltip styles
  updateChartTooltipStyles();

  // Phase 1: Enhanced Mobile Responsiveness Functions
  
  // Function to handle mobile-specific chart options
  function getMobileChartOptions(baseOptions) {
    const isMobile = window.innerWidth <= 768;
    const isSmallMobile = window.innerWidth <= 480;
    
    if (!isMobile) return baseOptions;
    
    const mobileOptions = { ...baseOptions };
    
    // Adjust chart options for mobile
    if (mobileOptions.plugins && mobileOptions.plugins.tooltip) {
      mobileOptions.plugins.tooltip = {
        ...mobileOptions.plugins.tooltip,
        titleFont: { size: isSmallMobile ? 11 : 12, weight: '600' },
        bodyFont: { size: isSmallMobile ? 11 : 12 },
        padding: isSmallMobile ? 8 : 10,
        cornerRadius: 6
      };
    }
    
    // Aggressive mobile scale fixes
    if (mobileOptions.scales) {
      if (mobileOptions.scales.x) {
        mobileOptions.scales.x.ticks = {
          ...mobileOptions.scales.x.ticks,
          font: { size: isSmallMobile ? 8 : 9 },
          maxRotation: 45,
          minRotation: 45,
          autoSkip: true,
          maxTicksLimit: isSmallMobile ? 5 : 8
        };
        mobileOptions.scales.x.grid = {
          ...mobileOptions.scales.x.grid,
          display: false
        };
      }
      if (mobileOptions.scales.y) {
        mobileOptions.scales.y.ticks = {
          ...mobileOptions.scales.y.ticks,
          font: { size: isSmallMobile ? 8 : 9 },
          maxTicksLimit: isSmallMobile ? 4 : 6
        };
        mobileOptions.scales.y.grid = {
          ...mobileOptions.scales.y.grid,
          display: isSmallMobile ? false : true
        };
      }
    }
    
    // Mobile-specific layout options
    mobileOptions.layout = {
      ...mobileOptions.layout,
      padding: {
        top: isSmallMobile ? 5 : 10,
        right: isSmallMobile ? 5 : 10,
        bottom: isSmallMobile ? 10 : 15,
        left: isSmallMobile ? 5 : 10
      }
    };
    
    // Disable legend on very small screens
    if (mobileOptions.plugins && mobileOptions.plugins.legend) {
      mobileOptions.plugins.legend.display = !isSmallMobile;
    }
    
    return mobileOptions;
  }
  
  // Function to handle responsive gauge sizing - FIXED HEIGHTS
  function updateGaugeSizes() {
    const isMobile = window.innerWidth <= 768;
    const isSmallMobile = window.innerWidth <= 480;
    
    // Update gauge containers with fixed heights
    const gaugeWraps = document.querySelectorAll('.spd-gauge-wrap');
    gaugeWraps.forEach(wrap => {
      if (isSmallMobile) {
        wrap.style.height = '150px';
      } else if (isMobile) {
        wrap.style.height = '180px';
      } else {
        wrap.style.height = '220px';
      }
    });
    
    // Update chart heights with fixed values
    const charts = document.querySelectorAll('.spd-chart:not(.spd-pie)');
    charts.forEach(chart => {
      if (isSmallMobile) {
        chart.style.height = '150px';
      } else if (isMobile) {
        chart.style.height = '180px';
      } else {
        chart.style.height = '220px';
      }
    });
  }
  
  // Function to handle mobile-specific layout adjustments
  function adjustMobileLayout() {
    const isMobile = window.innerWidth <= 768;
    const isSmallMobile = window.innerWidth <= 480;
    
    // Adjust card padding and spacing
    const cards = document.querySelectorAll('.spd-card');
    cards.forEach(card => {
      if (isMobile) {
        const padding = isSmallMobile ? '6px' : '8px';
        card.style.padding = padding;
      } else {
        card.style.padding = '14px';
      }
    });
    
    // Adjust header layout
    const header = document.querySelector('.spd-header');
    if (header && isMobile) {
      header.style.flexDirection = 'column';
      header.style.alignItems = 'stretch';
      header.style.gap = isSmallMobile ? '8px' : '12px';
    }
    
    // Adjust controls for touch
    const controls = document.querySelector('.spd-controls');
    if (controls && isMobile) {
      controls.style.justifyContent = 'center';
      controls.style.gap = isSmallMobile ? '6px' : '8px';
    }
  }
  
  // Function to handle mobile-specific tooltip positioning
  function adjustTooltipPosition(tooltip, event) {
    const isMobile = window.innerWidth <= 768;
    
    if (!isMobile) return;
    
    const tooltipRect = tooltip.getBoundingClientRect();
    const viewportWidth = window.innerWidth;
    const viewportHeight = window.innerHeight;
    
    // Adjust horizontal position
    if (tooltipRect.right > viewportWidth - 10) {
      tooltip.style.left = (viewportWidth - tooltipRect.width - 10) + 'px';
    }
    
    if (tooltipRect.left < 10) {
      tooltip.style.left = '10px';
    }
    
    // Adjust vertical position
    if (tooltipRect.bottom > viewportHeight - 10) {
      tooltip.style.top = (event.clientY - tooltipRect.height - 10) + 'px';
    }
    
    if (tooltipRect.top < 10) {
      tooltip.style.top = '10px';
    }
  }
  
  // Enhanced tooltip initialization with mobile support
  function initMobileTooltips() {
    // Override existing tooltip positioning for mobile
    const originalShowTooltip = window.showTooltip;
    if (typeof originalShowTooltip === 'function') {
      window.showTooltip = function(tooltip, event) {
        originalShowTooltip(tooltip, event);
        adjustTooltipPosition(tooltip, event);
      };
    }
    
    // Add touch event support for tooltips
    document.addEventListener('touchstart', function(e) {
      const tooltip = e.target.closest('[data-tooltip]');
      if (tooltip) {
        e.preventDefault();
        const tooltipText = tooltip.getAttribute('data-tooltip');
        showMobileTooltip(tooltipText, e.touches[0]);
      }
    });
  }
  
  // Function to show mobile-optimized tooltips
  function showMobileTooltip(text, touchEvent) {
    // Remove existing mobile tooltip
    const existingTooltip = document.querySelector('.spd-mobile-tooltip');
    if (existingTooltip) {
      existingTooltip.remove();
    }
    
    // Create mobile tooltip
    const tooltip = document.createElement('div');
    tooltip.className = 'spd-mobile-tooltip';
    tooltip.textContent = text;
    tooltip.style.cssText = `
      position: fixed;
      background: var(--card-bg);
      border: 1px solid var(--border);
      border-radius: 8px;
      padding: 8px 12px;
      font-size: 12px;
      color: var(--card-fg);
      z-index: 999999;
      max-width: 250px;
      word-wrap: break-word;
      box-shadow: 0 4px 12px rgba(0,0,0,0.15);
      pointer-events: none;
    `;
    
    // Position tooltip
    const x = touchEvent.clientX;
    const y = touchEvent.clientY - 40;
    
    tooltip.style.left = Math.min(x, window.innerWidth - 260) + 'px';
    tooltip.style.top = Math.max(y, 10) + 'px';
    
    document.body.appendChild(tooltip);
    
    // Remove tooltip after delay
    setTimeout(() => {
      if (tooltip.parentNode) {
        tooltip.remove();
      }
    }, 3000);
  }
  
  // Function to handle responsive chart resizing
  function handleChartResize() {
    const charts = document.querySelectorAll('canvas');
    charts.forEach(canvas => {
      const chart = Chart.getChart(canvas);
      if (chart) {
        chart.resize();
      }
    });
  }
  
  // Enhanced render function with mobile optimizations
  const mobileRender = render;
  render = function() {
    mobileRender();
    
    // Apply mobile optimizations after rendering
    setTimeout(() => {
      updateGaugeSizes();
      adjustMobileLayout();
      initMobileTooltips();
      handleChartResize();
    }, 100);
  };
  
  // Handle window resize for responsive updates
  let resizeTimeout;
  window.addEventListener('resize', function() {
    clearTimeout(resizeTimeout);
    resizeTimeout = setTimeout(() => {
      updateGaugeSizes();
      adjustMobileLayout();
      handleChartResize();
    }, 250);
  });
  
  // Initialize mobile responsiveness on load
  document.addEventListener('DOMContentLoaded', function() {
    updateGaugeSizes();
    adjustMobileLayout();
    initMobileTooltips();
  });
  
  // Enhanced chart creation with mobile options
  function createMobileOptimizedChart(canvas, config) {
    const mobileConfig = {
      ...config,
      options: getMobileChartOptions(config.options)
    };
    
    return new Chart(canvas, mobileConfig);
  }
  
  // Override chart creation in the render function
  const originalChartCreation = {
    salesChart: null,
    ordersChart: null,
    profitChart: null
  };
  
  // Update the chart creation calls in the render function
  function updateChartCreation() {
    // This will be called after the render function is modified
    // to use createMobileOptimizedChart instead of new Chart
  }

});

// Add mobile-specific CSS for tooltips
const mobileTooltipCSS = `
  .spd-mobile-tooltip {
    position: fixed !important;
    z-index: 999999 !important;
    pointer-events: none !important;
  }
  
  @media (max-width: 768px) {
    .spd-tooltip,
    .chartjs-tooltip {
      max-width: 250px !important;
      font-size: 11px !important;
      padding: 8px 10px !important;
    }
  }
  
  @media (max-width: 480px) {
    .spd-tooltip,
    .chartjs-tooltip {
      max-width: 220px !important;
      font-size: 10px !important;
      padding: 6px 8px !important;
    }
  }
`;

// Inject mobile CSS
if (!document.getElementById('spd-mobile-css')) {
  const style = document.createElement('style');
  style.id = 'spd-mobile-css';
  style.textContent = mobileTooltipCSS;
  document.head.appendChild(style);
}
