jQuery(document).ready(function($) {

  if (typeof window.driver === 'undefined' ||
    typeof window.driver.js !== 'object' ||
    typeof window.driver.js.driver !== 'function') {
    console.error('[MindWeb Tour] Driver.js not loaded correctly.');
    return;
  }

  const driverJs = window.driver.js.driver;
  const href = window.location.href;

  const isMindMediaFilesPage = href.includes('mind-web-files');
  const isSubscriptionPage = href.includes('mind-web-subscriptions');
  const isMindSpacesPage = href.includes('mind-web-spaces');
  const isMindWebModelUsagePage = href.includes('mind-web-model-usage');
  const isMindWebConversationsPage = href.includes('mind-web-conversations');
  const isProductCatalogPage = href.includes('mind-web-product-catalog');
  const isSettingsPage = href.includes('page=mind-web') &&
    !isSubscriptionPage &&
    !isMindSpacesPage &&
    !isMindWebModelUsagePage &&
    !isMindWebConversationsPage &&
    !isProductCatalogPage &&
    !isMindMediaFilesPage;

  function filterSteps(steps) {
    return steps.filter(function(step) {
      if (!step.element) return true;
      return $(step.element).length > 0;
    });
  }

  function getSettingsSteps() {
    return [{
        popover: {
          title: '🎉 Welcome!',
          description: 'Welcome to <strong>Mind Web Concierge</strong>! We\'ll guide you through the core features step by step, so you can get the most out of Mind Web right away 🚀',
        }
      },
      {
        element: '#mindweco-indexing-chat-settings-card',
        popover: {
          title: '⚙️ Item Settings',
          description: 'Use these settings to control how posts and pages are prepared for the assistant. Smaller chunks are easier to match precisely; overlap keeps context from being split apart.',
          side: 'bottom',
          align: 'start'
        }
      },
      {
        element: '#mindweco-chunk-size',
        popover: {
          title: '↔️ Chunk Size',
          description: 'Sets the maximum amount of text included in each indexed content chunk. Use the default 300 characters for balanced accuracy and speed unless your content needs larger passages.',
          side: 'bottom',
          align: 'start'
        }
      },
      {
        element: '#mindweco-chunk-overlap',
        popover: {
          title: '⧉ Chunk Overlap',
          description: 'Sets how many characters are repeated between neighboring chunks. This helps the assistant keep context when an important sentence or section crosses a chunk boundary. Recommended: 60 characters.',
          side: 'bottom',
          align: 'start'
        }
      },
      {
        element: '#mindweco-header-levels',
        popover: {
          title: '🔤 Header Levels',
          description: 'Enter the heading tags that should be used to understand your page structure, such as h2, h3, and h4. These headings help keep answers aligned with the right sections of your content.',
          side: 'bottom',
          align: 'start'
        }
      },
      {
        element: '#mindweco_ask_setting',
        popover: {
          title: '⚙️ Ask Configuration',
          description: 'Controls how many relevant indexed chunks the assistant reviews before answering. Lower values produce focused answers faster; higher values can include more detail when your content is broad.',
          side: 'bottom',
          align: 'start'
        }
      },
      {
        element: '#mindweco_show_powered_by',
        popover: {
          title: '⚙️ Powered By',
          description: 'Enable this when you want the chat window to show the SmartMind.it attribution link. Disable it when you prefer a cleaner widget footer.',
          side: 'bottom',
          align: 'start'
        }
      },
      {
        element: '#mindweco-services-options-card',
        popover: {
          title: '🧩 Services & Options',
          description: 'Services are the links visitors can open from the chat widget, such as booking pages, contact forms, quotes, support portals, or any useful external resource.',
          side: 'bottom',
          align: 'start'
        }
      },
      {
        element: '#mindweco_services_count',
        popover: {
          title: '🧩 Number of Services',
          description: 'Set how many service rows should be shown below. Enter 0 to hide services, 1 to open a single service directly, or more than 1 to show visitors a set of service cards.',
          side: 'bottom',
          align: 'start'
        }
      },
      {
        element: '#mindweco-services-repeater',
        popover: {
          title: '🔗 Service Rows',
          description: 'Each row defines one visitor option. Add a clear title and a valid URL for every service so the chat widget can display and open the right destination.',
          side: 'bottom',
          align: 'start'
        }
      },
      {
        element: '.mindweco-service-title-input',
        popover: {
          title: '🏷️ Service Title',
          description: 'Use a short, action-oriented label visitors will understand immediately, such as Book a Demo, Request a Quote, Contact Support, or Schedule a Consultation.',
          side: 'bottom',
          align: 'start'
        }
      },
      {
        element: '.mindweco-service-url-input',
        popover: {
          title: '🌐 Service URL',
          description: 'Enter the full destination URL for this service, including https://. This can point to a booking tool, form, product page, support page, or another resource.',
          side: 'bottom',
          align: 'start'
        }
      },
      {
        element: '.mindweco-custom-css-input',
        popover: {
          title: 'Custom CSS',
          description: 'Use this box to customize the widget appearance. Any styles you add here will be applied after the default widget design.',
          side: 'bottom',
          align: 'start'
        }
      },
      {
        element: '.save-settings',
        popover: {
          title: '💾 Save Your Changes',
          description: 'Click this button to save your settings.<br><strong>After saving, go to the Indexing tab to start indexing your content.</strong>',
          side: 'top',
          align: 'start',
          onNextClick: function() {
            $('[data-tab="selection"]').trigger('click');
            setTimeout(function() {
              window._mwTour.moveNext();
            }, 300);
          }
        }
      },
      // ── Index Selection Tab ──────────────────────────────
      {
        popover: {
          title: '⚡ Welcome to Exclude Indexing Tab',
          description: 'Here all pages and posts are selected by default. Deselect any you do not want to index.',
        }
      },
      {
        element: '#tab-selection',
        popover: {
          title: '📋 Exclude Indexing List',
          description: 'Choose the pages and posts you do not want to index.',
          side: 'bottom',
          align: 'start'
        }
      },
      {
        element: '.mindweco-select-checkbox',
        popover: {
          title: '✅ Select Items',
          description: 'Uncheck any page you do not want included.',
          side: 'bottom',
          align: 'start'
        }
      },
      {
        element: '#mindweco-search-input-index-selection',
        popover: {
          title: '🔍 Search Items',
          description: 'Type to quickly find specific posts or pages to include/exclude from indexing.',
          side: 'bottom',
          align: 'start'
        }
      },
      {
        element: '#mindweco-select-all',
        popover: {
          title: '✅ Select All',
          description: 'Click this button to select all posts and pages for indexing at once.',
          side: 'bottom',
          align: 'start'
        }
      },
      {
        element: '#mindweco-deselect-all',
        popover: {
          title: '❌ Deselect All',
          description: 'Click this button to deselect all posts and pages from indexing at once.',
          side: 'bottom',
          align: 'start',
          onNextClick: function() {
            $('[data-tab="indexing"]').trigger('click');
            setTimeout(function() {
              window._mwTour.moveNext();
            }, 300);
          }
        }
      },
      // ── Indexing Tab ─────────────────────────────────────
      {
        popover: {
          title: '⚡ Welcome to Indexing Tab',
          description: 'Here you can tell the system to start reading and organizing your content.',
        }
      },
      {
        element: '.indexing-status',
        popover: {
          title: '📊 Indexing Status Dashboard',
          description: 'Shows your indexing statistics: Total Posts, Not Indexed, Successfully Indexed, and Progress percentage.',
          side: 'bottom',
          align: 'start'
        }
      },
      {
        element: '#mindweco-refresh-summary',
        popover: {
          title: '🔄 Regenerate Sumary',
          description: 'Click to regenerate the welcome message summary based on your latest data and content.',
          side: 'bottom',
          align: 'start',
        }
      },
      {
        element: '#mindweco-index-all-items',
        popover: {
          title: '▶️ Start Indexing',
          description: 'Click to begin indexing all your posts and pages.<br><strong>After indexing, visit the Manage Items tab.</strong>',
          side: 'bottom',
          align: 'start',
          onNextClick: function() {
            $('[data-tab="manage"]').trigger('click');
            setTimeout(function() {
              window._mwTour.moveNext();
            }, 300);
          }
        }
      },
      // ── Manage Tab ───────────────────────────────────────
      {
        popover: {
          title: '☑️ Welcome to Manage Indexed Items',
          description: 'Displays all your successfully indexed posts and pages. You can view details and remove items.',
        }
      },
      {
        element: '#table-indexed',
        popover: {
          title: '📦 Indexed Items Table',
          description: 'Shows all indexed items with details like Item ID, Post ID, Category, Author, Title, and Status.',
          side: 'top',
          align: 'start'
        }
      },
      {
        element: '#mindweco-unindex-all-items',
        popover: {
          title: '🗑️ Unindex All Items',
          description: 'Remove all indexed items at once. <strong>Use with caution!</strong>',
          side: 'bottom',
          align: 'start'
        }
      },
      {
        element: '#pagination',
        popover: {
          title: '↔️ Pagination Controls',
          description: 'Navigate through pages of indexed items.<br><strong>Next: Technical Options tab.</strong>',
          side: 'top',
          align: 'start',
          onNextClick: function() {
            $('[data-tab="technical_options"]').trigger('click');
            setTimeout(function() {
              window._mwTour.moveNext();
            }, 300);
          }
        }
      },
      // ── Technical Options Tab ────────────────────────────
      {
        popover: {
          title: '⚙️ Welcome to Technical Options',
          description: 'Advanced technical settings including your Base URL, username, and credentials.',
        }
      },
      {
        element: '#mindweco-base-url',
        popover: {
          title: '🔗 Base URL',
          description: 'Your platform\'s Base URL for API requests.',
          side: 'bottom',
          align: 'start'
        }
      },
      {
        element: '#mindweco-username',
        popover: {
          title: '👤 Username',
          description: 'Your registered username for the Mind Web Concierge system.',
          side: 'bottom',
          align: 'start'
        }
      },
      {
        element: '#mindweco-indexing-id',
        popover: {
          title: '#️⃣ Indexing Information',
          description: 'The ID the system uses to track your indexed content.',
          side: 'bottom',
          align: 'start'
        }
      },
      {
        element: '#indexing-title-settings',
        popover: {
          title: '🏷️ Indexing Title',
          description: 'Shows the unique title the system uses to track your indexed content.',
          side: 'bottom',
          align: 'start'
        }
      },
      {
        element: '#category-settings',
        popover: {
          title: '🏷️ Category Configuration',
          description: 'Shows the ID and name of your category.<br><br><strong>After this, visit the Subscriptions page.</strong>',
          side: 'top',
          align: 'start'
        }
      }
    ];
  }

  function getMediaFilesSteps() {
    return [{
        popover: {
          title: '🎉 Welcome to Media Files!',
          description: 'Welcome to <strong>Mind Web Media Files</strong>! We\'ll guide you through indexing your PDF and DOCX files step by step 🚀',
        }
      },
      {
        element: '#mindweco-chunk-size',
        popover: {
          title: '↔️ Chunk Size',
          description: 'Controls how much text the system reads at one time. Default is 300 characters, which works well for most content.',
          side: 'bottom',
          align: 'start'
        }
      },
      {
        element: '#indexing-status',
        popover: {
          title: '📊 Indexing Status',
          description: 'Shows your file indexing statistics: Total Files, Not Indexed, Successfully Indexed, and Progress percentage.',
          side: 'bottom',
          align: 'start'
        }
      },
      {
        element: '#mindweco-index-all-files',
        popover: {
          title: '▶️ Start Indexing Files',
          description: 'Click this button to start indexing all your PDF and DOCX files.<br><strong>After indexing, visit the Manage Files tab.</strong>',
          side: 'top',
          align: 'start',
          onNextClick: function() {
            $('[data-tab="manage-files"]').trigger('click');
            setTimeout(function() {
              window._mwTour.moveNext();
            }, 400);
          }
        }
      },
      // ── Manage Files Tab ─────────────────────────────────
      {
        popover: {
          title: '⚡ Welcome to Manage Files Tab',
          description: 'View and manage all your indexed PDF and DOCX files. You can search, unindex individual files, or unindex all at once.',
        },
        onHighlightStarted: function() {
          $('[data-tab="manage-files"]').trigger('click');
        }
      },
      {
        element: '#table-indexed-files',
        popover: {
          title: '📋 Indexed Files Table',
          description: 'Lists all your indexed files with details like title, file size, author, and file type.',
          side: 'top',
          align: 'start'
        },
        onHighlightStarted: function() {
          if ($('#table-indexed-files').is(':hidden')) {
            $('[data-tab="manage-files"]').trigger('click');
          }
        }
      },
      {
        element: '#search-input-files',
        popover: {
          title: '🔍 Search Files',
          description: 'Type to quickly find specific files by name.',
          side: 'bottom',
          align: 'start'
        }
      },
      {
        element: '#mindweco-unindex-all-files',
        popover: {
          title: '🗑️ Unindex All Files',
          description: 'Remove all indexed files at once. Useful to start fresh. <strong>Use with caution!</strong>',
          side: 'bottom',
          align: 'start'
        }
      },
      {
        element: '.unindex-file',
        popover: {
          title: '❌ Unindex Single File',
          description: 'Click this button to remove a single file from the index.',
          side: 'bottom',
          align: 'start'
        }
      },
    ];
  }

  function getSubscriptionSteps() {
    var steps = [{
        popover: {
          title: '💳 Welcome to Subscriptions!',
          description: 'Manage your Mind Web Concierge subscription, view your trial status, and access subscription history.',
        }
      },
      {
        element: '#mindweco-guid',
        popover: {
          title: '🔑 Plugin GUID',
          description: 'Your unique plugin identifier.',
          side: 'bottom',
          align: 'start'
        }
      },
      {
        element: '#site-url',
        popover: {
          title: '🌐 Site URL',
          description: 'Your WordPress site address.<br><strong>Next: Subscriptions Overview tab.</strong>',
          side: 'bottom',
          align: 'start',
          onNextClick: function() {
            $('[data-tab="subscriptions"]').trigger('click');
            setTimeout(function() {
              window._mwTour.moveNext();
            }, 300);
          }
        }
      },
      {
        popover: {
          title: '💳 Welcome to Subscriptions Overview',
          description: 'Keep track of your subscription and trial status.',
        }
      }
    ];

    if ($('#buy_subscription').length && $('#buy_subscription').is(':visible')) {
      steps.push({
        element: '#buy_subscription',
        popover: {
          title: '🛒 Buy Subscription',
          description: 'Click here to purchase a Mind Web Concierge subscription.',
          side: 'bottom',
          align: 'start'
        }
      });
    }

    if ($('#refresh-plugin').length && $('#refresh-plugin').is(':visible')) {
      steps.push({
        element: '#refresh-plugin',
        popover: {
          title: '🔄 Refresh Subscription Status',
          description: 'Refresh your subscription details after a purchase.',
          side: 'bottom',
          align: 'start'
        }
      });
    }

    steps.push({
      element: '#subscription-cards-container',
      popover: {
        title: '⊞ Subscription Details',
        description: 'View all details: ID, creation date, billing period, type, status.<br><strong>Next: Subscription History tab.</strong>',
        side: 'top',
        align: 'start',
        onNextClick: function() {
          $('[data-tab="logs"]').trigger('click');
          setTimeout(function() {
            window._mwTour.moveNext();
          }, 300);
        }
      }
    }, {
      popover: {
        title: '🕐 Welcome to Subscriptions History',
        description: 'Review all past subscription events, updates, and important messages.',
      }
    }, {
      element: '#logs-cards-container',
      popover: {
        title: '≡ Activity Logs',
        description: 'Track your subscription history with detailed logs.',
        side: 'top',
        align: 'start'
      }
    });

    return steps;
  }

  function getMindSpacesSteps() {
    return [{
        popover: {
          title: '⚡ Welcome to Mind Spaces!',
          description: 'Manage your Mind Spaces and connect them to your WordPress pages.',
        }
      },
      {
        element: '#mindweco-base-url',
        popover: {
          title: '🔗 Base URL',
          description: 'The Mind Spaces server URL.',
          side: 'bottom',
          align: 'start'
        }
      },
      {
        element: '#mindweco-username',
        popover: {
          title: '👤 Username',
          description: 'Enter your Mind Spaces account email.',
          side: 'bottom',
          align: 'start'
        }
      },
      {
        element: '#mindweco-password',
        popover: {
          title: '🔒 Password',
          description: 'Enter your Mind Spaces password.',
          side: 'bottom',
          align: 'start',
          onNextClick: function() {
            $('[data-tab="page_based_notebooks"]').trigger('click');
            setTimeout(function() {
              window._mwTour.moveNext();
            }, 300);
          }
        }
      },
      {
        popover: {
          title: '💡 Welcome to Mind Spaces',
          description: 'View and manage all your Mind Spaces.',
        }
      },
      {
        popover: {
          title: '📓 Welcome to Page Based Spaces',
          description: 'Link specific spaces to individual WordPress pages.',
        }
      },
      {
        element: '#add-page-based-notebook',
        popover: {
          title: '➕ Add Knowledge Base',
          description: 'Click here to add a new page-based space.',
          side: 'bottom',
          align: 'start'
        }
      },
      {
        element: '.page-notebook-card',
        popover: {
          title: '⊞ Page Spaces Table',
          description: 'Lists all your Mind Spaces with name, ID, and Ref.',
          side: 'top',
          align: 'start'
        }
      },
      {
        element: '#remove-all-page-notebooks',
        popover: {
          title: '🗑 Remove All',
          description: 'Remove all page-based space associations at once.',
          side: 'bottom',
          align: 'start'
        }
      },
      {
        popover: {
          title: '✅ All Set!',
          description: '🎉 Congratulations! You\'ve completed the Mind Web Concierge tour.',
        }
      }
    ];
  }

  function getModelUsageSteps() {
    return [{
        popover: {
          title: '😊 Welcome to Model Configuration',
          description: '<p>This quick tour guides you through LLM configuration.</p>',
        }
      },
      {
        element: '#tab-build_model',
        popover: {
          title: '⊞ Welcome to Build a Model Overview',
          description: 'Shows which model provider you\'re currently using.',
          side: 'top',
          align: 'start',
          onNextClick: function() {
            $('[data-tab="openai_provider"]').trigger('click');
            setTimeout(function() {
              window._mwTour.moveNext();
            }, 300);
          }
        }
      },
      {
        element: '[data-tab="openai_provider"]',
        popover: {
          title: '⚙️ Welcome to OpenAI Configuration',
          description: 'Set up your API credentials and model settings.',
          side: 'bottom',
          align: 'start'
        }
      },
      {
        element: '.btn-update-llm',
        popover: {
          title: '✏️ Edit Configuration',
          description: 'Click to enable editing of your LLM configuration.',
          side: 'left',
          align: 'start'
        }
      },
      {
        element: '#api-llm-name',
        popover: {
          title: '🪪 Configuration Name',
          description: 'Give your LLM configuration a memorable name.',
          side: 'right',
          align: 'start'
        }
      },
      {
        element: '#api-base-url-llm',
        popover: {
          title: '🔗 API Base URL',
          description: 'Enter the API endpoint URL.',
          side: 'right',
          align: 'start'
        }
      },
      {
        element: '#api-model-name',
        popover: {
          title: '🖥️ Model Identifier',
          description: 'Specify the exact model: e.g. <code>gpt-4</code>.',
          side: 'right',
          align: 'start'
        }
      },
      {
        element: '#api-key',
        popover: {
          title: '🔑 API Key',
          description: 'Enter your OpenAI API key here. It will be encrypted and stored securely.',
          side: 'right',
          align: 'start'
        }
      },
      {
        element: '#toggle-api-key',
        popover: {
          title: '👁️ Show/Hide API Key',
          description: 'Toggle visibility of your API key.',
          side: 'left',
          align: 'start'
        }
      }
    ];
  }

  function getConversationsSteps() {
    return [{
        popover: {
          title: '💬 Welcome to Conversations!',
          description: 'View and manage all Mind Web Concierge conversations with your visitors.',
        }
      },
      {
        element: '.datepicker-wrapper',
        popover: {
          title: '📅 Date Filter Inputs',
          description: 'Choose a start and end date, then apply the filter to update both Conversations and Unanswered Questions.',
          side: 'right',
          align: 'start'
        }
      },
      {
        element: '#filter-conversations',
        popover: {
          title: 'Apply Filter',
          description: 'Runs the selected date filter. If you are viewing Unanswered Questions, the Conversations tab is updated too.',
          side: 'bottom',
          align: 'start'
        }
      },
      {
        element: '#clear-filter',
        popover: {
          title: 'Clear Filter',
          description: 'Clears the selected dates and restores the current conversation results.',
          side: 'bottom',
          align: 'start'
        }
      },
      {
        element: '.load-convs',
        popover: {
          title: '📋 Show Today\'s Chats',
          description: 'Load today\'s conversations or refresh.',
          side: 'right',
          align: 'start'
        }
      },
      {
        element: '.mindweco-nav-tabs',
        popover: {
          title: '⊞ Conversations Card',
          title: 'Conversation Tabs',
          description: 'Switch between all conversations and unanswered questions. On mobile, results are shown as stacked rows for easier reading.',
          side: 'bottom',
          align: 'start'
        }
      },
      {
        element: '#conversations-results',
        popover: {
          title: 'Conversations Results',
          description: 'This area lists conversations. Use See Chat to view the transcript, Conversation Info for session details, or the delete button to remove a conversation.',
          side: 'top',
          align: 'start'
        }
      },
      {
        element: '.mindweco-nav-tab[data-tab="unanswered_questions"]',
        popover: {
          title: 'Unanswered Questions',
          description: 'This tab lists questions without useful answers. It uses the same date filter and keeps long question text visible.',
          side: 'right',
          align: 'start'
        }
      }
    ];
  }

  function getProductCatalogSteps() {
    return [{
        popover: {
          title: '🛍️ Welcome to Product Catalog!',
          description: 'Manage and index your WooCommerce products.',
        }
      },
      {
        element: '.indexing-status',
        popover: {
          title: '📊 Indexing Status Dashboard',
          description: 'Shows product indexing statistics.',
          side: 'bottom',
          align: 'start'
        }
      },
      {
        element: '#mindweco-index-all-products',
        popover: {
          title: '▶️ Start Indexing Products',
          description: 'Click to begin indexing all WooCommerce products.',
          side: 'bottom',
          align: 'start',
          onNextClick: function() {
            $('[data-tab="manage-product"]').trigger('click');
            setTimeout(function() {
              window._mwTour.moveNext();
            }, 300);
          }
        }
      },
      {
        popover: {
          title: '☑️ Welcome to Manage Indexed Products',
          description: 'Displays all successfully indexed products.',
        }
      },
      {
        element: '#table-indexed-products',
        popover: {
          title: '⊞ Indexed Products Table',
          description: 'Shows all indexed products with full details.',
          side: 'top',
          align: 'start'
        }
      },
      {
        element: '#mindweco-unindex-all-products',
        popover: {
          title: '🗑️ Unindex All Products',
          description: 'Remove all indexed products at once. <strong>Use with caution!</strong>',
          side: 'bottom',
          align: 'start'
        }
      }
    ];
  }

  function buildSteps() {
    if (isSettingsPage) return filterSteps(getSettingsSteps());
    if (isMindMediaFilesPage) return filterSteps(getMediaFilesSteps())
    if (isSubscriptionPage) return filterSteps(getSubscriptionSteps());
    if (isMindSpacesPage) return filterSteps(getMindSpacesSteps());
    if (isMindWebModelUsagePage) return filterSteps(getModelUsageSteps());
    if (isMindWebConversationsPage) return filterSteps(getConversationsSteps());
    if (isProductCatalogPage) return filterSteps(getProductCatalogSteps());
    return [];
  }

  function getStartIndex(steps) {
    var currentTab = $('.nav-tab-active').data('tab');
    if (!currentTab) return 0;

    var tabTitleMap = {
      'settings': 'Welcome!',
      'selection': 'Index Selection Tab',
      'indexing': 'Indexing Tab',
      'manage': 'Manage Indexed Items',
      'manage-files': 'Manage Files Tab', // ← add this
      'technical_options': 'Technical Options',
      'subscriptions': 'Subscriptions Overview',
      'logs': 'Subscriptions History',
      'notebooks': 'Mind Spaces',
      'page_based_notebooks': 'Page Based Spaces',
      'openai_provider': 'OpenAI Configuration',
      'build_model': 'Build a Model Overview',
      'manage-product': 'Manage Indexed Products',
      'conversations': 'Conversations Results',
      'unanswered_questions': 'Unanswered Questions'
    };

    var keyword = tabTitleMap[currentTab];
    if (!keyword) return 0;

    var idx = -1;
    $.each(steps, function(i, s) {
      if (s.popover && s.popover.title && s.popover.title.includes(keyword)) {
        idx = i;
        return false;
      }
    });

    if (idx < 0) return 0;

    if (idx > 0 && !steps[idx - 1].element) {
      return idx - 1;
    }

    return idx;
  }

  function startTour() {
    var steps = buildSteps();
    if (!steps.length) {
      console.warn('[MindWeb Tour] No steps found for this page.');
      return;
    }

    var startIndex = getStartIndex(steps);
    var tourInstance = driverJs({
      animate: true,
      smoothScroll: true,
      allowClose: true,
      stagePadding: 10,
      stageRadius: 8,
      showProgress: true,
      progressText: '{{current}} / {{total}}',
      nextBtnText: 'Next →',
      prevBtnText: '← Back',
      doneBtnText: 'Finish',
      onDestroyed: function() {
        $('#start-tour-btn').prop('disabled', false);
      },
      steps: steps
    });

    window._mwTour = tourInstance;
    tourInstance.drive(startIndex);
  }

  var $btn = $('#start-tour-btn');
  var $tooltip = $btn.find('span');

  $btn.on('mouseover', function() {
    if ($tooltip.length) $tooltip.css('opacity', '1');
  });

  $btn.on('mouseout', function() {
    if ($tooltip.length) $tooltip.css('opacity', '0');
  });

  $btn.on('mouseenter', function() {
    $(this).css({
      'transform': 'scale(1.1)',
      'box-shadow': '0 6px 16px rgba(37,99,235,0.5)'
    });
  }).on('mouseleave', function() {
    $(this).css({
      'transform': 'scale(1)',
      'box-shadow': '0 4px 12px rgba(102,126,234,0.3)'
    });
  });

  $btn.on('click', function() {
    $(this).prop('disabled', true);
    startTour();
  });

  window.mindwebTourStart = startTour;

});
