@eventop/sdk 1.2.2 → 1.2.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/core.js CHANGED
@@ -1,229 +1,507 @@
1
- function _mergeNamespaces(n, m) {
2
- m.forEach(function (e) {
3
- e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) {
4
- if (k !== 'default' && !(k in n)) {
5
- var d = Object.getOwnPropertyDescriptor(e, k);
6
- Object.defineProperty(n, k, d.get ? d : {
7
- enumerable: true,
8
- get: function () { return e[k]; }
9
- });
10
- }
11
- });
12
- });
13
- return Object.freeze(n);
1
+ // Single source of truth for all mutable SDK state.
2
+ // Every module imports from here so there is no circular dependency on core.js.
3
+ //
4
+ // NOTE: modules should mutate these properties directly, e.g.
5
+ // import * as state from './state.js';
6
+ // state.tour = new Shepherd.Tour(...);
7
+
8
+ /** @type {Function|null} The resolved AI provider function */
9
+ let provider = null;
10
+
11
+ /** @type {object|null} The merged SDK config object */
12
+ let config = null;
13
+
14
+ /** @type {Function|null} Framework router function (e.g. React Router's navigate) */
15
+ let router = null;
16
+
17
+ /** @type {object|null} Active Shepherd.Tour instance */
18
+ let tour = null;
19
+
20
+ /** @type {boolean} Whether the chat panel is currently visible */
21
+ let isOpen = false;
22
+
23
+ /** @type {Array<{role:string,content:string}>} AI conversation history */
24
+ let messages = [];
25
+
26
+ /** @type {Array<object>|null} Steps saved when a tour is paused */
27
+ let pausedSteps = null;
28
+
29
+ /** @type {number} Step index to resume from after a pause */
30
+ let pausedIndex = 0;
31
+
32
+ /** @type {Array<Function>} Cleanup callbacks — called when tour ends or is paused */
33
+ let cleanups = [];
34
+
35
+ // ─── Setters ─────────────────────────────────────────────────────────────────
36
+ // Using setter functions keeps mutations explicit and grep-friendly.
37
+
38
+ function setProvider(v) {
39
+ provider = v;
40
+ }
41
+ function setConfig(v) {
42
+ config = v;
43
+ }
44
+ function setRouter(v) {
45
+ router = v;
46
+ }
47
+ function setTour(v) {
48
+ tour = v;
49
+ }
50
+ function setIsOpen(v) {
51
+ isOpen = v;
52
+ }
53
+ function setMessages(v) {
54
+ messages = v;
55
+ }
56
+ function setPausedSteps(v) {
57
+ pausedSteps = v;
58
+ }
59
+ function setPausedIndex(v) {
60
+ pausedIndex = v;
61
+ }
62
+ function pushCleanup(fn) {
63
+ cleanups.push(fn);
64
+ }
65
+ function runAndClearCleanups() {
66
+ cleanups.forEach(fn => fn());
67
+ cleanups = [];
14
68
  }
15
69
 
16
- var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
70
+ // Factory helpers for creating AI provider functions.
71
+ // Extend this file to add new built-in providers (OpenAI, Gemini, etc.).
17
72
 
18
- var core$1 = {exports: {}};
73
+ const providers = {
74
+ custom(fn) {
75
+ if (typeof fn !== 'function') {
76
+ throw new Error('[Eventop] providers.custom() requires a function');
77
+ }
78
+ return fn;
79
+ }
80
+ };
81
+
82
+ // Resolves design tokens from user config and builds CSS variable strings.
83
+
84
+ const DARK_TOKENS = {
85
+ accent: '#e94560',
86
+ accentSecondary: '#a855f7',
87
+ bg: '#0f0f1a',
88
+ surface: '#1a1a2e',
89
+ border: '#2a2a4a',
90
+ text: '#e0e0f0',
91
+ textDim: '#6060a0',
92
+ radius: '16px',
93
+ fontFamily: "system-ui, -apple-system, 'Segoe UI', sans-serif"
94
+ };
95
+ const LIGHT_TOKENS = {
96
+ accent: '#e94560',
97
+ accentSecondary: '#7c3aed',
98
+ bg: '#ffffff',
99
+ surface: '#f8f8fc',
100
+ border: '#e4e4f0',
101
+ text: '#1a1a2e',
102
+ textDim: '#888899',
103
+ radius: '16px',
104
+ fontFamily: "system-ui, -apple-system, 'Segoe UI', sans-serif"
105
+ };
106
+ const PRESETS = {
107
+ default: {},
108
+ minimal: {
109
+ accent: '#000000',
110
+ accentSecondary: '#333333',
111
+ radius: '8px'
112
+ },
113
+ soft: {
114
+ accent: '#6366f1',
115
+ accentSecondary: '#8b5cf6',
116
+ radius: '20px'
117
+ },
118
+ glass: {
119
+ radius: '14px'
120
+ }
121
+ };
122
+ function resolveTheme(themeConfig = {}) {
123
+ var _window$matchMedia, _window;
124
+ const {
125
+ mode = 'auto',
126
+ preset = 'default',
127
+ tokens = {}
128
+ } = themeConfig;
129
+ const isDark = mode === 'auto' ? ((_window$matchMedia = (_window = window).matchMedia) === null || _window$matchMedia === void 0 ? void 0 : _window$matchMedia.call(_window, '(prefers-color-scheme: dark)').matches) ?? true : mode === 'dark';
130
+ const base = isDark ? {
131
+ ...DARK_TOKENS
132
+ } : {
133
+ ...LIGHT_TOKENS
134
+ };
135
+ return {
136
+ ...base,
137
+ ...(PRESETS[preset] || {}),
138
+ ...tokens,
139
+ _isDark: isDark
140
+ };
141
+ }
142
+ function buildCSSVars(t) {
143
+ return `
144
+ --sai-accent: ${t.accent};
145
+ --sai-accent2: ${t.accentSecondary};
146
+ --sai-bg: ${t.bg};
147
+ --sai-surface: ${t.surface};
148
+ --sai-border: ${t.border};
149
+ --sai-text: ${t.text};
150
+ --sai-text-dim: ${t.textDim};
151
+ --sai-radius: ${t.radius};
152
+ --sai-font: ${t.fontFamily};
153
+ `;
154
+ }
155
+ function applyTheme(t) {
156
+ const panel = document.getElementById('sai-panel');
157
+ const trigger = document.getElementById('sai-trigger');
158
+ if (panel) panel.style.cssText += buildCSSVars(t);
159
+ if (trigger) trigger.style.cssText += buildCSSVars(t);
160
+ }
161
+
162
+ // Converts a corner/offset config into CSS position values for the
163
+ // trigger button and the chat panel.
164
+
165
+ function resolvePosition(posConfig = {}) {
166
+ const {
167
+ corner = 'bottom-right',
168
+ offsetX = 28,
169
+ offsetY = 28
170
+ } = posConfig;
171
+ const isLeft = corner.includes('left');
172
+ const isTop = corner.includes('top');
173
+ return {
174
+ trigger: {
175
+ [isLeft ? 'left' : 'right']: `${offsetX}px`,
176
+ [isTop ? 'top' : 'bottom']: `${offsetY}px`
177
+ },
178
+ panel: {
179
+ [isLeft ? 'left' : 'right']: `${offsetX}px`,
180
+ [isTop ? 'top' : 'bottom']: `${offsetY + 56 + 12}px`,
181
+ transformOrigin: isTop ? 'top center' : 'bottom center'
182
+ }
183
+ };
184
+ }
185
+ function positionToCSS(obj) {
186
+ return Object.entries(obj).map(([k, v]) => `${k}:${v}`).join(';');
187
+ }
188
+
189
+ // Injects the single <style> block that themes both the chat panel and the
190
+ // Shepherd step overlays. Split from the UI builder so styles can be refreshed
191
+ // independently on theme changes.
192
+
193
+ const SHEPHERD_CSS = 'https://cdn.jsdelivr.net/npm/shepherd.js@11.2.0/dist/css/shepherd.css';
194
+ function loadShepherdCSS() {
195
+ if (document.querySelector(`link[href="${SHEPHERD_CSS}"]`)) return;
196
+ const l = document.createElement('link');
197
+ l.rel = 'stylesheet';
198
+ l.href = SHEPHERD_CSS;
199
+ document.head.appendChild(l);
200
+ }
19
201
 
20
202
  /**
21
- * ╔══════════════════════════════════════════════════════════════╗
22
- * ║ @eventop/sdk v1.1.0 ║
23
- * ║ AI-powered guided tours themeable, provider-agnostic ║
24
- * ║ ║
25
- * ║ Provider: always proxy through your own server. ║
26
- * ║ Never expose API keys in client-side code. ║
27
- * ╚══════════════════════════════════════════════════════════════╝
203
+ * Injects (or replaces) the #sai-styles <style> element.
204
+ *
205
+ * @param {object} theme resolved theme token object
206
+ * @param {object} pos — resolved position object from resolvePosition()
28
207
  */
29
- (function (module) {
30
- (function (global, factory) {
31
- const Eventop = factory();
32
- if (module.exports) {
33
- module.exports = Eventop;
208
+ function injectStyles(theme, pos) {
209
+ if (document.getElementById('sai-styles')) return;
210
+ const triggerCSS = positionToCSS(pos.trigger);
211
+ const panelCSS = positionToCSS(pos.panel);
212
+ const isDark = theme._isDark;
213
+ const stepBg = isDark ? 'var(--sai-bg)' : '#ffffff';
214
+ const stepSurf = isDark ? 'var(--sai-surface)' : '#f8f8fc';
215
+ const stepText = isDark ? 'var(--sai-text)' : '#1a1a2e';
216
+ const stepBorder = isDark ? 'var(--sai-border)' : '#e4e4f0';
217
+ const style = document.createElement('style');
218
+ style.id = 'sai-styles';
219
+ style.textContent = `
220
+ #sai-trigger, #sai-panel { ${buildCSSVars(theme)} }
221
+
222
+ /* ── Trigger ── */
223
+ #sai-trigger {
224
+ position: fixed; ${triggerCSS};
225
+ width: 54px; height: 54px; border-radius: 50%;
226
+ background: var(--sai-surface); border: 2px solid var(--sai-accent);
227
+ color: var(--sai-text); font-size: 20px; cursor: pointer; z-index: 99998;
228
+ display: flex; align-items: center; justify-content: center;
229
+ box-shadow: 0 4px 20px color-mix(in srgb, var(--sai-accent) 40%, transparent);
230
+ transition: transform .2s ease, box-shadow .2s ease;
231
+ font-family: var(--sai-font); padding: 0;
34
232
  }
35
- // Always set on global in browser environments
36
- if (typeof window !== 'undefined') {
37
- window.Eventop = Eventop;
38
- } else if (typeof global !== 'undefined') {
39
- global.Eventop = Eventop;
233
+ #sai-trigger:hover {
234
+ transform: scale(1.08);
235
+ box-shadow: 0 6px 28px color-mix(in srgb, var(--sai-accent) 55%, transparent);
40
236
  }
41
- })(typeof globalThis !== 'undefined' ? globalThis : commonjsGlobal, function () {
42
-
43
- const SHEPHERD_CSS = 'https://cdn.jsdelivr.net/npm/shepherd.js@11.2.0/dist/css/shepherd.css';
44
- const SHEPHERD_JS = 'https://cdn.jsdelivr.net/npm/shepherd.js@11.2.0/dist/js/shepherd.min.js';
45
-
46
- // ─── Internal state ──────────────────────────────────────────────────────────
47
- let _provider = null;
48
- let _config = null;
49
- let _tour = null;
50
- let _isOpen = false;
51
- let _messages = [];
52
- let _mediaQuery = null;
53
-
54
- // Pause/resume state
55
- let _pausedSteps = null;
56
- let _pausedIndex = 0;
57
-
58
- // Active cleanup callbacks — cleared when tour ends or is paused
59
- let _cleanups = [];
60
-
61
- // ═══════════════════════════════════════════════════════════════════════════
62
- // THEME ENGINE
63
- // ═══════════════════════════════════════════════════════════════════════════
64
-
65
- const DARK_TOKENS = {
66
- accent: '#e94560',
67
- accentSecondary: '#a855f7',
68
- bg: '#0f0f1a',
69
- surface: '#1a1a2e',
70
- border: '#2a2a4a',
71
- text: '#e0e0f0',
72
- textDim: '#6060a0',
73
- radius: '16px',
74
- fontFamily: "system-ui, -apple-system, 'Segoe UI', sans-serif"
75
- };
76
- const LIGHT_TOKENS = {
77
- accent: '#e94560',
78
- accentSecondary: '#7c3aed',
79
- bg: '#ffffff',
80
- surface: '#f8f8fc',
81
- border: '#e4e4f0',
82
- text: '#1a1a2e',
83
- textDim: '#888899',
84
- radius: '16px',
85
- fontFamily: "system-ui, -apple-system, 'Segoe UI', sans-serif"
86
- };
87
- const PRESETS = {
88
- default: {},
89
- minimal: {
90
- accent: '#000000',
91
- accentSecondary: '#333333',
92
- radius: '8px'
93
- },
94
- soft: {
95
- accent: '#6366f1',
96
- accentSecondary: '#8b5cf6',
97
- radius: '20px'
98
- },
99
- glass: {
100
- radius: '14px'
101
- }
102
- };
103
- function resolveTheme(themeConfig = {}) {
104
- var _window$matchMedia, _window;
105
- const {
106
- mode = 'auto',
107
- preset = 'default',
108
- tokens = {}
109
- } = themeConfig;
110
- const isDark = mode === 'auto' ? ((_window$matchMedia = (_window = window).matchMedia) === null || _window$matchMedia === void 0 ? void 0 : _window$matchMedia.call(_window, '(prefers-color-scheme: dark)').matches) ?? true : mode === 'dark';
111
- const base = isDark ? {
112
- ...DARK_TOKENS
113
- } : {
114
- ...LIGHT_TOKENS
115
- };
116
- return {
117
- ...base,
118
- ...(PRESETS[preset] || {}),
119
- ...tokens,
120
- _isDark: isDark
121
- };
237
+ #sai-trigger .sai-pulse {
238
+ position: absolute; width: 100%; height: 100%; border-radius: 50%;
239
+ background: color-mix(in srgb, var(--sai-accent) 30%, transparent);
240
+ animation: sai-pulse 2.2s ease-out infinite; pointer-events: none;
122
241
  }
123
- function buildCSSVars(t) {
124
- return `
125
- --sai-accent: ${t.accent};
126
- --sai-accent2: ${t.accentSecondary};
127
- --sai-bg: ${t.bg};
128
- --sai-surface: ${t.surface};
129
- --sai-border: ${t.border};
130
- --sai-text: ${t.text};
131
- --sai-text-dim: ${t.textDim};
132
- --sai-radius: ${t.radius};
133
- --sai-font: ${t.fontFamily};
134
- `;
242
+ #sai-trigger.sai-paused .sai-pulse { animation: none; }
243
+ #sai-trigger.sai-paused::after {
244
+ content: '⏸'; position: absolute; bottom: -2px; right: -2px;
245
+ font-size: 12px; background: var(--sai-accent); border-radius: 50%;
246
+ width: 18px; height: 18px; display: flex; align-items: center;
247
+ justify-content: center; color: #fff; line-height: 1;
135
248
  }
136
- function applyTheme(t) {
137
- const panel = document.getElementById('sai-panel');
138
- const trigger = document.getElementById('sai-trigger');
139
- if (panel) {
140
- panel.style.cssText += buildCSSVars(t);
141
- }
142
- if (trigger) {
143
- trigger.style.cssText += buildCSSVars(t);
144
- }
249
+ @keyframes sai-pulse {
250
+ 0% { transform: scale(1); opacity: .8; }
251
+ 100% { transform: scale(1.75); opacity: 0; }
252
+ }
253
+
254
+ /* ── Panel ── */
255
+ #sai-panel {
256
+ position: fixed; ${panelCSS};
257
+ width: 340px; background: var(--sai-bg);
258
+ border: 1px solid var(--sai-border); border-radius: var(--sai-radius);
259
+ display: flex; flex-direction: column; z-index: 99999; overflow: hidden;
260
+ box-shadow: 0 16px 48px rgba(0,0,0,.18); font-family: var(--sai-font);
261
+ transform: translateY(12px) scale(.97); opacity: 0; pointer-events: none;
262
+ transition: transform .25s cubic-bezier(.34,1.56,.64,1), opacity .2s ease;
263
+ max-height: 520px;
145
264
  }
265
+ #sai-panel.sai-open { transform: translateY(0) scale(1); opacity: 1; pointer-events: all; }
146
266
 
147
- // ═══════════════════════════════════════════════════════════════════════════
148
- // POSITIONING
149
- // ═══════════════════════════════════════════════════════════════════════════
150
-
151
- function resolvePosition(posConfig = {}) {
152
- const {
153
- corner = 'bottom-right',
154
- offsetX = 28,
155
- offsetY = 28
156
- } = posConfig;
157
- const isLeft = corner.includes('left');
158
- const isTop = corner.includes('top');
159
- return {
160
- trigger: {
161
- [isLeft ? 'left' : 'right']: `${offsetX}px`,
162
- [isTop ? 'top' : 'bottom']: `${offsetY}px`
163
- },
164
- panel: {
165
- [isLeft ? 'left' : 'right']: `${offsetX}px`,
166
- [isTop ? 'top' : 'bottom']: `${offsetY + 56 + 12}px`,
167
- transformOrigin: isTop ? 'top center' : 'bottom center'
168
- }
169
- };
267
+ /* ── Header ── */
268
+ #sai-header {
269
+ display: flex; align-items: center; gap: 10px; padding: 13px 15px;
270
+ background: var(--sai-surface); border-bottom: 1px solid var(--sai-border);
170
271
  }
171
- function positionToCSS(obj) {
172
- return Object.entries(obj).map(([k, v]) => `${k}:${v}`).join(';');
272
+ #sai-avatar {
273
+ width: 30px; height: 30px; border-radius: 50%;
274
+ background: linear-gradient(135deg, var(--sai-accent), var(--sai-accent2));
275
+ display: flex; align-items: center; justify-content: center;
276
+ font-size: 14px; flex-shrink: 0; color: #fff;
173
277
  }
278
+ #sai-header-info { flex: 1; min-width: 0; }
279
+ #sai-header-info h4 {
280
+ margin: 0; font-size: 13px; font-weight: 600; color: var(--sai-text);
281
+ white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
282
+ }
283
+ #sai-header-info p {
284
+ margin: 0; font-size: 11px; color: var(--sai-text-dim);
285
+ white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
286
+ }
287
+ #sai-close {
288
+ background: none; border: none; color: var(--sai-text-dim); cursor: pointer;
289
+ font-size: 18px; line-height: 1; padding: 0; flex-shrink: 0; transition: color .15s;
290
+ }
291
+ #sai-close:hover { color: var(--sai-text); }
174
292
 
175
- // ═══════════════════════════════════════════════════════════════════════════
176
- // PROVIDER
177
- // Only custom() is supported route AI calls through your own server.
178
- //
179
- // Your endpoint receives: POST { systemPrompt, messages }
180
- // Your endpoint must return: { message: string, steps: Step[] }
181
- //
182
- // @example
183
- // Eventop.init({
184
- // provider: Eventop.providers.custom(async ({ systemPrompt, messages }) => {
185
- // const res = await fetch('/api/guide', {
186
- // method: 'POST',
187
- // headers: { 'Content-Type': 'application/json' },
188
- // body: JSON.stringify({ systemPrompt, messages }),
189
- // });
190
- // return res.json();
191
- // }),
192
- // config: { ... },
193
- // });
194
- // ═══════════════════════════════════════════════════════════════════════════
195
-
196
- const providers = {
197
- custom(fn) {
198
- if (typeof fn !== 'function') throw new Error('[Eventop] providers.custom() requires a function');
199
- return fn;
200
- }
201
- };
293
+ /* ── Messages ── */
294
+ #sai-messages {
295
+ flex: 1; overflow-y: auto; padding: 12px;
296
+ display: flex; flex-direction: column; gap: 9px;
297
+ min-height: 160px; max-height: 280px;
298
+ scrollbar-width: thin; scrollbar-color: var(--sai-border) transparent;
299
+ }
300
+ #sai-messages::-webkit-scrollbar { width: 4px; }
301
+ #sai-messages::-webkit-scrollbar-thumb { background: var(--sai-border); border-radius: 2px; }
302
+ .sai-msg {
303
+ max-width: 86%; padding: 8px 11px; border-radius: 11px;
304
+ font-size: 13px; line-height: 1.55; animation: sai-in .18s ease both;
305
+ }
306
+ @keyframes sai-in {
307
+ from { opacity: 0; transform: translateY(5px); }
308
+ to { opacity: 1; transform: translateY(0); }
309
+ }
310
+ .sai-msg.sai-ai {
311
+ background: var(--sai-surface); color: var(--sai-text);
312
+ border-bottom-left-radius: 3px; align-self: flex-start;
313
+ border: 1px solid var(--sai-border);
314
+ }
315
+ .sai-msg.sai-user {
316
+ background: var(--sai-accent); color: #fff;
317
+ border-bottom-right-radius: 3px; align-self: flex-end;
318
+ }
319
+ .sai-msg.sai-error {
320
+ background: color-mix(in srgb, #ef4444 10%, var(--sai-bg));
321
+ color: #ef4444;
322
+ border: 1px solid color-mix(in srgb, #ef4444 25%, var(--sai-bg));
323
+ align-self: flex-start;
324
+ }
325
+ .sai-msg.sai-nav {
326
+ background: color-mix(in srgb, var(--sai-accent2) 8%, var(--sai-surface));
327
+ color: var(--sai-text);
328
+ border: 1px solid color-mix(in srgb, var(--sai-accent2) 20%, var(--sai-border));
329
+ border-bottom-left-radius: 3px; align-self: flex-start;
330
+ font-size: 12px;
331
+ }
202
332
 
203
- // ═══════════════════════════════════════════════════════════════════════════
204
- // SYSTEM PROMPT
205
- // ═══════════════════════════════════════════════════════════════════════════
206
-
207
- function buildSystemPrompt() {
208
- const screens = [...new Set((_config.features || []).filter(f => {
209
- var _f$screen;
210
- return (_f$screen = f.screen) === null || _f$screen === void 0 ? void 0 : _f$screen.id;
211
- }).map(f => f.screen.id))];
212
- const featureSummary = (_config.features || []).map(f => {
213
- var _f$screen2, _f$flow;
214
- const entry = {
215
- id: f.id,
216
- name: f.name,
217
- description: f.description,
218
- screen: ((_f$screen2 = f.screen) === null || _f$screen2 === void 0 ? void 0 : _f$screen2.id) || 'default'
219
- };
220
- if ((_f$flow = f.flow) !== null && _f$flow !== void 0 && _f$flow.length) {
221
- entry.note = `This feature has ${f.flow.length} sequential sub-steps. Include ONE step per flow entry.`;
222
- }
223
- return entry;
224
- });
225
- return `
226
- You are an in-app assistant called "${_config.assistantName || 'AI Guide'}" for "${_config.appName}".
333
+ /* ── Typing indicator ── */
334
+ .sai-typing {
335
+ display: flex; gap: 4px; padding: 9px 12px; align-self: flex-start;
336
+ background: var(--sai-surface); border: 1px solid var(--sai-border);
337
+ border-radius: 11px; border-bottom-left-radius: 3px;
338
+ }
339
+ .sai-typing span {
340
+ width: 5px; height: 5px; border-radius: 50%;
341
+ background: var(--sai-text-dim); animation: sai-bounce 1.2s infinite;
342
+ }
343
+ .sai-typing span:nth-child(2) { animation-delay: .15s; }
344
+ .sai-typing span:nth-child(3) { animation-delay: .3s; }
345
+ @keyframes sai-bounce {
346
+ 0%,80%,100% { transform: translateY(0); }
347
+ 40% { transform: translateY(-5px); }
348
+ }
349
+
350
+ /* ── Suggestions ── */
351
+ #sai-suggestions { display: flex; flex-wrap: wrap; gap: 6px; padding: 0 12px 10px; }
352
+ .sai-chip {
353
+ font-size: 11px; padding: 5px 10px; border-radius: 20px;
354
+ background: transparent; border: 1px solid var(--sai-border);
355
+ color: var(--sai-text-dim); cursor: pointer; font-family: inherit; transition: all .15s;
356
+ }
357
+ .sai-chip:hover {
358
+ border-color: var(--sai-accent); color: var(--sai-accent);
359
+ background: color-mix(in srgb, var(--sai-accent) 6%, transparent);
360
+ }
361
+
362
+ /* ── Input row ── */
363
+ #sai-inputrow {
364
+ display: flex; align-items: center; gap: 7px; padding: 9px 11px;
365
+ border-top: 1px solid var(--sai-border); background: var(--sai-bg);
366
+ }
367
+ #sai-input {
368
+ flex: 1; background: var(--sai-surface); border: 1px solid var(--sai-border);
369
+ border-radius: 8px; padding: 7px 11px; color: var(--sai-text);
370
+ font-size: 13px; outline: none; transition: border-color .15s; font-family: inherit;
371
+ }
372
+ #sai-input::placeholder { color: var(--sai-text-dim); }
373
+ #sai-input:focus { border-color: var(--sai-accent); }
374
+ #sai-send {
375
+ width: 32px; height: 32px; flex-shrink: 0; border-radius: 8px;
376
+ background: var(--sai-accent); border: none; color: #fff; font-size: 14px;
377
+ cursor: pointer; display: flex; align-items: center; justify-content: center;
378
+ transition: filter .15s, transform .1s; line-height: 1;
379
+ }
380
+ #sai-send:hover { filter: brightness(1.1); }
381
+ #sai-send:active { transform: scale(.93); }
382
+ #sai-send:disabled { background: var(--sai-border); cursor: not-allowed; }
383
+
384
+ /* ── Shepherd step overrides ── */
385
+ .sai-shepherd-step {
386
+ background: ${stepBg} !important;
387
+ border: 1px solid ${stepBorder} !important;
388
+ border-radius: 12px !important;
389
+ box-shadow: 0 8px 36px rgba(0,0,0,.18) !important;
390
+ max-width: 290px !important;
391
+ font-family: var(--sai-font, system-ui) !important;
392
+ }
393
+ .sai-shepherd-step.shepherd-has-title .shepherd-content .shepherd-header {
394
+ background: ${stepSurf} !important; padding: 11px 15px 8px !important;
395
+ border-bottom: 1px solid ${stepBorder} !important;
396
+ }
397
+ .sai-shepherd-step .shepherd-title {
398
+ color: var(--sai-accent, #e94560) !important;
399
+ font-size: 13px !important; font-weight: 700 !important;
400
+ }
401
+ .sai-shepherd-step .shepherd-text {
402
+ color: ${stepText} !important; font-size: 13px !important;
403
+ line-height: 1.6 !important; padding: 10px 15px !important;
404
+ }
405
+ .sai-shepherd-step .shepherd-footer {
406
+ border-top: 1px solid ${stepBorder} !important; padding: 8px 11px !important;
407
+ background: ${stepBg} !important; display: flex; gap: 5px; flex-wrap: wrap;
408
+ }
409
+ .sai-shepherd-step .shepherd-button {
410
+ background: var(--sai-accent, #e94560) !important; color: #fff !important;
411
+ border: none !important; border-radius: 6px !important; padding: 6px 13px !important;
412
+ font-size: 12px !important; font-weight: 600 !important; cursor: pointer !important;
413
+ transition: filter .15s !important; font-family: var(--sai-font, system-ui) !important;
414
+ }
415
+ .sai-shepherd-step .shepherd-button:hover { filter: brightness(1.1) !important; }
416
+ .sai-shepherd-step .shepherd-button-secondary {
417
+ background: transparent !important; color: var(--sai-text-dim, #888) !important;
418
+ border: 1px solid ${stepBorder} !important;
419
+ }
420
+ .sai-shepherd-step .shepherd-button-secondary:hover {
421
+ background: ${stepSurf} !important; color: ${stepText} !important;
422
+ }
423
+ .sai-shepherd-step .shepherd-cancel-icon { color: var(--sai-text-dim, #888) !important; }
424
+ .sai-shepherd-step .shepherd-cancel-icon:hover { color: ${stepText} !important; }
425
+ .sai-shepherd-step[data-popper-placement] > .shepherd-arrow::before {
426
+ background: ${stepBorder} !important;
427
+ }
428
+
429
+ /* ── Progress bar ── */
430
+ .sai-progress { display: flex; align-items: center; gap: 8px; margin-left: auto; flex-shrink: 0; }
431
+ .sai-progress-bar {
432
+ width: 60px; height: 3px; border-radius: 2px; background: ${stepBorder}; overflow: hidden;
433
+ }
434
+ .sai-progress-fill {
435
+ height: 100%; border-radius: 2px;
436
+ background: var(--sai-accent, #e94560); transition: width .3s ease;
437
+ }
438
+ .sai-progress-label {
439
+ font-size: 10px; color: var(--sai-text-dim, #888);
440
+ white-space: nowrap; font-family: var(--sai-font, system-ui);
441
+ }
442
+
443
+ /* ── Step error ── */
444
+ .sai-step-error {
445
+ margin-top: 8px; padding: 6px 10px;
446
+ background: color-mix(in srgb, #ef4444 12%, ${stepBg});
447
+ border: 1px solid color-mix(in srgb, #ef4444 25%, ${stepBorder});
448
+ border-radius: 6px; color: #ef4444; font-size: 12px; line-height: 1.5;
449
+ animation: sai-in .18s ease;
450
+ }
451
+
452
+ /* ── Glass preset ── */
453
+ .sai-glass-preset .sai-shepherd-step {
454
+ background: rgba(255, 255, 255, 0.10) !important;
455
+ backdrop-filter: blur(18px) saturate(180%) !important;
456
+ -webkit-backdrop-filter: blur(18px) saturate(180%) !important;
457
+ border: 1px solid rgba(255, 255, 255, 0.22) !important;
458
+ box-shadow: 0 8px 36px rgba(0,0,0,.12) !important;
459
+ }
460
+ .sai-glass-preset .sai-shepherd-step .shepherd-text,
461
+ .sai-glass-preset .sai-shepherd-step .shepherd-title {
462
+ color: #ffffff !important;
463
+ text-shadow: 0 1px 3px rgba(0,0,0,.35);
464
+ }
465
+ .sai-glass-preset .sai-shepherd-step .shepherd-footer,
466
+ .sai-glass-preset .sai-shepherd-step .shepherd-header {
467
+ background: transparent !important;
468
+ border-color: rgba(255,255,255,0.15) !important;
469
+ }
470
+ `;
471
+ document.head.appendChild(style);
472
+ }
473
+
474
+ // Builds the system prompt that is sent to the AI on every request.
475
+ // Keeping this separate makes it easy to iterate on prompt engineering
476
+ // without touching tour or UI logic.
477
+
478
+ /**
479
+ * @param {object} config — the live _config object from state.js
480
+ * @returns {string}
481
+ */
482
+ function buildSystemPrompt(config) {
483
+ const screens = [...new Set((config.features || []).filter(f => {
484
+ var _f$screen;
485
+ return (_f$screen = f.screen) === null || _f$screen === void 0 ? void 0 : _f$screen.id;
486
+ }).map(f => f.screen.id))];
487
+ const featureSummary = (config.features || []).map(f => {
488
+ var _f$screen2, _f$flow;
489
+ const entry = {
490
+ id: f.id,
491
+ name: f.name,
492
+ description: f.description,
493
+ screen: ((_f$screen2 = f.screen) === null || _f$screen2 === void 0 ? void 0 : _f$screen2.id) || 'default',
494
+ ...(f.route ? {
495
+ route: f.route
496
+ } : {})
497
+ };
498
+ if ((_f$flow = f.flow) !== null && _f$flow !== void 0 && _f$flow.length) {
499
+ entry.note = `This feature has ${f.flow.length} sequential sub-steps. Include ONE step per flow entry.`;
500
+ }
501
+ return entry;
502
+ });
503
+ return `
504
+ You are an in-app assistant called "${config.assistantName || 'AI Guide'}" for "${config.appName}".
227
505
  Your ONLY job: guide users step-by-step through tasks using the feature map below.
228
506
 
229
507
  ${screens.length > 1 ? `SCREENS: This app has multiple screens: ${screens.join(', ')}. Features are screen-specific. The SDK handles navigation — just pick the right features.` : ''}
@@ -257,816 +535,902 @@ RULES:
257
535
  the SDK expands them automatically.
258
536
  8. Never skip features in a required sequence. Include every step end-to-end.
259
537
  `.trim();
260
- }
261
- async function callAI(userMessage) {
262
- const systemPrompt = buildSystemPrompt();
263
- const messagesWithNew = [..._messages, {
264
- role: 'user',
265
- content: userMessage
266
- }];
267
- const result = await _provider({
268
- systemPrompt,
269
- messages: messagesWithNew
270
- });
271
- _messages.push({
272
- role: 'user',
273
- content: userMessage
274
- });
275
- _messages.push({
276
- role: 'assistant',
277
- content: result.message
278
- });
279
- return result;
280
- }
538
+ }
539
+
540
+ // Handles the request/response cycle with the AI provider.
541
+ // Parses the structured JSON the AI must return and maintains conversation history.
542
+
543
+
544
+ /**
545
+ * Sends the user's message to the provider, updates conversation history,
546
+ * and returns the parsed AI result.
547
+ *
548
+ * @param {string} userMessage
549
+ * @returns {Promise<{ message: string, steps: Array }>}
550
+ */
551
+ async function callAI(userMessage) {
552
+ const systemPrompt = buildSystemPrompt(config);
553
+ const messagesWithNew = [...messages, {
554
+ role: 'user',
555
+ content: userMessage
556
+ }];
557
+ const result = await provider({
558
+ systemPrompt,
559
+ messages: messagesWithNew
560
+ });
561
+ setMessages([...messages, {
562
+ role: 'user',
563
+ content: userMessage
564
+ }, {
565
+ role: 'assistant',
566
+ content: result.message
567
+ }]);
568
+ return result;
569
+ }
570
+
571
+ // Handles all navigation concerns:
572
+ // • Route-based navigation (new, preferred)
573
+ // • Legacy screen-based navigation (backward-compat)
574
+ // • Pre-tour route announcement
575
+ // • Waiting for DOM elements and URL changes
576
+
577
+
578
+ // ─── Helpers ─────────────────────────────────────────────────────────────────
579
+
580
+ /**
581
+ * Returns the current pathname. Centralised so it's easy to mock in tests.
582
+ */
583
+ function getCurrentRoute() {
584
+ return typeof window !== 'undefined' ? window.location.pathname : '/';
585
+ }
281
586
 
282
- // ═══════════════════════════════════════════════════════════════════════════
283
- // SCREEN NAVIGATION
284
- // ═══════════════════════════════════════════════════════════════════════════
587
+ /**
588
+ * Polls until `window.location.pathname === targetRoute` or timeout.
589
+ * Resolves (never rejects) so a slow router doesn't blow up the tour.
590
+ *
591
+ * @param {string} targetRoute
592
+ * @param {number} [timeout=8000]
593
+ * @returns {Promise<void>}
594
+ */
595
+ function waitForRouteChange(targetRoute, timeout = 8000) {
596
+ return new Promise(resolve => {
597
+ if (window.location.pathname === targetRoute) return resolve();
598
+ const interval = setInterval(() => {
599
+ if (window.location.pathname === targetRoute) {
600
+ clearInterval(interval);
601
+ clearTimeout(timer);
602
+ resolve();
603
+ }
604
+ }, 50);
605
+ const timer = setTimeout(() => {
606
+ clearInterval(interval);
607
+ console.warn(`[Eventop] Route change to "${targetRoute}" timed out — continuing`);
608
+ resolve();
609
+ }, timeout);
610
+ pushCleanup(() => {
611
+ clearInterval(interval);
612
+ clearTimeout(timer);
613
+ });
614
+ });
615
+ }
285
616
 
286
- async function ensureOnCorrectScreen(feature) {
287
- if (!feature.screen) return;
288
- if (typeof feature.screen.check === 'function' && feature.screen.check()) return;
289
- addMsg('ai', 'Taking you to the right screen first…');
290
- if (typeof feature.screen.navigate === 'function') {
291
- feature.screen.navigate();
617
+ /**
618
+ * Waits for a CSS selector to appear in the DOM (up to `timeout` ms).
619
+ * Resolves without throwing so a missing element doesn't crash the tour.
620
+ *
621
+ * @param {string} selector
622
+ * @param {number} [timeout=8000]
623
+ * @returns {Promise<void>}
624
+ */
625
+ function waitForElement(selector, timeout = 8000) {
626
+ return new Promise(resolve => {
627
+ if (document.querySelector(selector)) return resolve();
628
+ const timer = setTimeout(() => {
629
+ observer.disconnect();
630
+ console.warn(`[Eventop] waitFor("${selector}") timed out — continuing`);
631
+ resolve();
632
+ }, timeout);
633
+ const observer = new MutationObserver(() => {
634
+ if (document.querySelector(selector)) {
635
+ clearTimeout(timer);
636
+ observer.disconnect();
637
+ resolve();
292
638
  }
293
- const waitSelector = feature.screen.waitFor || feature.selector;
294
- if (waitSelector) await waitForElement(waitSelector, 10000);
295
- }
639
+ });
640
+ observer.observe(document.body, {
641
+ childList: true,
642
+ subtree: true
643
+ });
644
+ pushCleanup(() => {
645
+ clearTimeout(timer);
646
+ observer.disconnect();
647
+ });
648
+ });
649
+ }
650
+
651
+ // ─── Route navigation ─────────────────────────────────────────────────────────
296
652
 
297
- // ═══════════════════════════════════════════════════════════════════════════
298
- // FLOW EXPANSION
299
- // A feature with flow[] gets expanded into multiple Shepherd steps.
300
- // Developer supplies selectors; AI supplies copy for the parent step.
301
- // ═══════════════════════════════════════════════════════════════════════════
302
-
303
- function expandFlowSteps(aiStep, feature) {
304
- var _feature$flow;
305
- if (!((_feature$flow = feature.flow) !== null && _feature$flow !== void 0 && _feature$flow.length)) return [aiStep];
306
- return feature.flow.map((entry, i) => ({
307
- id: `${aiStep.id}-flow-${i}`,
308
- title: i === 0 ? aiStep.title : `${aiStep.title} (${i + 1}/${feature.flow.length})`,
309
- text: i === 0 ? aiStep.text : `Step ${i + 1} of ${feature.flow.length}: continue with the action highlighted below.`,
310
- position: aiStep.position || 'bottom',
311
- selector: entry.selector || null,
312
- waitFor: entry.waitFor || null,
313
- advanceOn: entry.advanceOn || null,
314
- _parentId: aiStep.id
653
+ /**
654
+ * Navigate to `route` using (in priority order):
655
+ * 1. state.router the function passed by the developer
656
+ * 2. window.history.pushState + popstate best-effort fallback for SPAs
657
+ *
658
+ * Shows a friendly chat message, then waits for the URL to confirm the change.
659
+ *
660
+ * @param {string} route
661
+ * @param {string} [featureName]
662
+ * @returns {Promise<void>}
663
+ */
664
+ async function navigateToRoute(route, featureName) {
665
+ if (!route || getCurrentRoute() === route) return;
666
+ addMsg('ai', `↗ Taking you to ${featureName ? `the ${featureName} area` : route}…`);
667
+ try {
668
+ if (router) {
669
+ await Promise.resolve(router(route));
670
+ } else {
671
+ window.history.pushState({}, '', route);
672
+ window.dispatchEvent(new PopStateEvent('popstate', {
673
+ state: {}
315
674
  }));
316
675
  }
676
+ } catch (err) {
677
+ console.warn('[Eventop] Navigation error:', err);
678
+ }
679
+ await waitForRouteChange(route, 8000);
680
+ await new Promise(r => setTimeout(r, 80));
681
+ }
317
682
 
318
- // ═══════════════════════════════════════════════════════════════════════════
319
- // SHEPHERD RUNNER
320
- // ═══════════════════════════════════════════════════════════════════════════
683
+ // ─── Route preview / announcement ────────────────────────────────────────────
321
684
 
322
- function loadCSS(href) {
323
- if (document.querySelector(`link[href="${href}"]`)) return;
324
- const l = document.createElement('link');
325
- l.rel = 'stylesheet';
326
- l.href = href;
327
- document.head.appendChild(l);
328
- }
329
- function loadScript(src) {
330
- return new Promise((res, rej) => {
331
- if (document.querySelector(`script[src="${src}"]`)) return res();
332
- const s = document.createElement('script');
333
- s.src = src;
334
- s.onload = res;
335
- s.onerror = rej;
336
- document.head.appendChild(s);
337
- });
338
- }
339
- async function ensureShepherd() {
340
- if (typeof Shepherd !== 'undefined') return;
341
- loadCSS(SHEPHERD_CSS);
342
- await loadScript(SHEPHERD_JS);
343
- }
344
- function waitForElement(selector, timeout = 8000) {
345
- return new Promise(resolve => {
346
- if (document.querySelector(selector)) return resolve();
347
- const timer = setTimeout(() => {
348
- observer.disconnect();
349
- console.warn(`[Eventop] waitFor("${selector}") timed out — continuing`);
350
- resolve();
351
- }, timeout);
352
- const observer = new MutationObserver(() => {
353
- if (document.querySelector(selector)) {
354
- clearTimeout(timer);
355
- observer.disconnect();
356
- resolve();
357
- }
358
- });
359
- observer.observe(document.body, {
360
- childList: true,
361
- subtree: true
362
- });
363
- _cleanups.push(() => {
364
- clearTimeout(timer);
365
- observer.disconnect();
366
- });
367
- });
368
- }
369
- function mergeWithFeature(step) {
370
- var _config2;
371
- if (!((_config2 = _config) !== null && _config2 !== void 0 && _config2.features)) return step;
372
- const feature = _config.features.find(f => f.id === step.id);
373
- if (!feature) return step;
374
- return {
375
- waitFor: feature.waitFor || null,
376
- advanceOn: feature.advanceOn || null,
377
- validate: feature.validate || null,
378
- screen: feature.screen || null,
379
- flow: feature.flow || null,
380
- ...step,
381
- selector: feature.selector || step.selector // feature map always wins
382
- };
383
- }
384
- function wireAdvanceOn(shepherdStep, advanceOn, tour) {
385
- if (!(advanceOn !== null && advanceOn !== void 0 && advanceOn.selector) || !(advanceOn !== null && advanceOn !== void 0 && advanceOn.event)) return;
386
- function handler(e) {
387
- if (e.target.matches(advanceOn.selector) || e.target.closest(advanceOn.selector)) {
388
- setTimeout(() => {
389
- if (tour && !tour.isActive()) return;
390
- tour.next();
391
- }, advanceOn.delay || 300);
392
- }
393
- }
394
- document.addEventListener(advanceOn.event, handler, true);
395
- _cleanups.push(() => document.removeEventListener(advanceOn.event, handler, true));
396
- shepherdStep.on('show', () => {
397
- var _shepherdStep$getElem;
398
- const nextBtn = (_shepherdStep$getElem = shepherdStep.getElement()) === null || _shepherdStep$getElem === void 0 ? void 0 : _shepherdStep$getElem.querySelector('.shepherd-footer .shepherd-button:not(.shepherd-button-secondary)');
399
- if (nextBtn && !shepherdStep._isLast) {
400
- nextBtn.style.opacity = '0.4';
401
- nextBtn.title = 'Complete the action above to continue';
402
- }
403
- });
404
- }
405
- function addProgressIndicator(shepherdStep, index, total) {
406
- shepherdStep.on('show', () => {
407
- var _shepherdStep$getElem2;
408
- const header = (_shepherdStep$getElem2 = shepherdStep.getElement()) === null || _shepherdStep$getElem2 === void 0 ? void 0 : _shepherdStep$getElem2.querySelector('.shepherd-header');
409
- if (!header || header.querySelector('.sai-progress')) return;
410
- const pct = Math.round((index + 1) / total * 100);
411
- const wrapper = document.createElement('div');
412
- wrapper.className = 'sai-progress';
413
- wrapper.innerHTML = `
414
- <div class="sai-progress-bar">
415
- <div class="sai-progress-fill" style="width:${pct}%"></div>
416
- </div>
417
- <span class="sai-progress-label">${index + 1} / ${total}</span>
418
- `;
419
- header.appendChild(wrapper);
420
- });
421
- }
422
- function showResumeButton(fromIndex) {
423
- var _document$getElementB, _document$getElementB2;
424
- const msgs = document.getElementById('sai-messages');
425
- if (!msgs) return;
426
- (_document$getElementB = document.getElementById('sai-resume-prompt')) === null || _document$getElementB === void 0 || _document$getElementB.remove();
427
- const div = document.createElement('div');
428
- div.id = 'sai-resume-prompt';
429
- div.className = 'sai-msg sai-ai';
430
- div.innerHTML = `
431
- Tour paused. Ready when you are.
432
- <br/>
433
- <button class="sai-chip" id="sai-resume-btn" style="display:inline-block;margin-top:8px;">
434
- ▶ Resume from step ${fromIndex + 1}
435
- </button>
436
- `;
437
- msgs.appendChild(div);
438
- msgs.scrollTop = msgs.scrollHeight;
439
- (_document$getElementB2 = document.getElementById('sai-resume-btn')) === null || _document$getElementB2 === void 0 || _document$getElementB2.addEventListener('click', () => {
440
- div.remove();
441
- if (!_pausedSteps) return;
442
- const steps = _pausedSteps;
443
- const idx = _pausedIndex;
444
- _pausedSteps = null;
445
- _pausedIndex = 0;
446
- if (_isOpen) togglePanel();
447
- runTour(steps.slice(idx));
685
+ /**
686
+ * Inspects the AI's step list and returns which routes will be visited
687
+ * that the user isn't already on — in visit order, deduplicated.
688
+ *
689
+ * @param {Array} aiSteps
690
+ * @returns {Array<{ route: string, featureName: string }>}
691
+ */
692
+ function previewRoutesNeeded(aiSteps) {
693
+ const currentRoute = getCurrentRoute();
694
+ const seen = new Set([currentRoute]);
695
+ const ordered = [];
696
+ aiSteps.forEach(step => {
697
+ var _state$config;
698
+ const feature = (_state$config = config) === null || _state$config === void 0 || (_state$config = _state$config.features) === null || _state$config === void 0 ? void 0 : _state$config.find(f => f.id === step.id);
699
+ if (feature !== null && feature !== void 0 && feature.route && !seen.has(feature.route)) {
700
+ seen.add(feature.route);
701
+ ordered.push({
702
+ route: feature.route,
703
+ featureName: feature.name
448
704
  });
449
- if (!_isOpen) togglePanel();
450
705
  }
451
- async function runTour(steps, options = {}) {
452
- var _config3;
453
- await ensureShepherd();
454
- if (_tour) {
455
- _tour.cancel();
456
- }
457
- _cleanups.forEach(fn => fn());
458
- _cleanups = [];
459
- _tour = null;
460
- if (!(steps !== null && steps !== void 0 && steps.length)) return;
461
- const {
462
- showProgress = true,
463
- waitTimeout = 8000
464
- } = options;
465
-
466
- // Merge AI steps with feature map
467
- const mergedSteps = steps.map(mergeWithFeature);
468
-
469
- // Navigate to the correct screen for the first step if needed
470
- const firstFeature = (_config3 = _config) === null || _config3 === void 0 || (_config3 = _config3.features) === null || _config3 === void 0 ? void 0 : _config3.find(f => {
471
- var _mergedSteps$;
472
- return f.id === ((_mergedSteps$ = mergedSteps[0]) === null || _mergedSteps$ === void 0 ? void 0 : _mergedSteps$.id);
473
- });
474
- if (firstFeature) await ensureOnCorrectScreen(firstFeature);
706
+ });
707
+ return ordered;
708
+ }
475
709
 
476
- // Expand flow[] features into individual Shepherd steps
477
- const expandedSteps = mergedSteps.flatMap(step => {
478
- var _config4;
479
- const feature = (_config4 = _config) === null || _config4 === void 0 || (_config4 = _config4.features) === null || _config4 === void 0 ? void 0 : _config4.find(f => f.id === step.id);
480
- return feature ? expandFlowSteps(step, feature) : [step];
481
- });
482
- const ShepherdClass = typeof Shepherd !== 'undefined' ? Shepherd : window.Shepherd;
483
- _tour = new ShepherdClass.Tour({
484
- useModalOverlay: true,
485
- defaultStepOptions: {
486
- scrollTo: {
487
- behavior: 'smooth',
488
- block: 'center'
489
- },
490
- cancelIcon: {
491
- enabled: true
492
- },
493
- classes: 'sai-shepherd-step'
494
- }
495
- });
496
- expandedSteps.forEach((step, i) => {
497
- var _step$advanceOn, _step$advanceOn2;
498
- const isLast = i === expandedSteps.length - 1;
499
- const hasAuto = !!((_step$advanceOn = step.advanceOn) !== null && _step$advanceOn !== void 0 && _step$advanceOn.selector && (_step$advanceOn2 = step.advanceOn) !== null && _step$advanceOn2 !== void 0 && _step$advanceOn2.event);
500
- const buttons = [];
501
- if (i > 0) {
502
- buttons.push({
503
- text: '← Back',
504
- action: _tour.back,
505
- secondary: true
506
- });
507
- }
508
- buttons.push({
509
- text: isLast ? 'Done ✓' : 'Next →',
510
- action: isLast ? _tour.complete : _tour.next
511
- });
512
- buttons.push({
513
- text: '⏸ Pause',
514
- secondary: true,
515
- action: function () {
516
- _tour.cancel();
517
- }
518
- });
519
- const shepherdStep = _tour.addStep({
520
- id: step.id || `sai-step-${i}`,
521
- title: step.title,
522
- text: step.text,
523
- attachTo: step.selector ? {
524
- element: step.selector,
525
- on: step.position || 'bottom'
526
- } : undefined,
527
- beforeShowPromise: step.waitFor ? () => waitForElement(step.waitFor, waitTimeout) : undefined,
528
- buttons
529
- });
530
- shepherdStep._isLast = isLast;
531
- if (hasAuto) wireAdvanceOn(shepherdStep, step.advanceOn, _tour);
532
- if (showProgress && expandedSteps.length > 1) {
533
- addProgressIndicator(shepherdStep, i, expandedSteps.length);
534
- }
535
- });
536
- _tour.on('complete', () => {
537
- _cleanups.forEach(fn => fn());
538
- _cleanups = [];
539
- _pausedSteps = null;
540
- _pausedIndex = 0;
541
- _tour = null;
542
- });
710
+ /**
711
+ * Adds a human-readable pre-tour navigation announcement to the chat.
712
+ *
713
+ * @param {Array<{ route: string, featureName: string }>} routesNeeded
714
+ */
715
+ function announceNavigationPlan(routesNeeded) {
716
+ if (!routesNeeded.length) return;
717
+ const names = routesNeeded.map(r => r.featureName || r.route);
718
+ let msg;
719
+ if (names.length === 1) {
720
+ msg = `🗺 I'll navigate you to the ${names[0]} area automatically — no need to go there yourself.`;
721
+ } else {
722
+ const list = names.slice(0, -1).join(', ') + ' and ' + names[names.length - 1];
723
+ msg = `🗺 This tour visits ${names.length} areas: ${list}. I'll navigate between them automatically.`;
724
+ }
725
+ addMsg('ai', msg);
726
+ }
543
727
 
544
- // Cancel pause instead of hard destroy
545
- _tour.on('cancel', () => {
546
- const currentStepEl = _tour.getCurrentStep();
547
- const currentIdx = currentStepEl ? expandedSteps.findIndex(s => s.id === currentStepEl.id) : 0;
548
- _cleanups.forEach(fn => fn());
549
- _cleanups = [];
550
- _pausedSteps = expandedSteps;
551
- _pausedIndex = Math.max(0, currentIdx);
552
- _tour = null;
553
- showResumeButton(_pausedIndex);
554
- });
555
- _tour.start();
556
- }
557
- function stepComplete() {
558
- var _tour2;
559
- if ((_tour2 = _tour) !== null && _tour2 !== void 0 && _tour2.isActive()) _tour.next();
560
- }
561
- function stepFail(message) {
562
- var _tour3, _el$querySelector;
563
- if (!((_tour3 = _tour) !== null && _tour3 !== void 0 && _tour3.isActive())) return;
564
- const current = _tour.getCurrentStep();
565
- if (!current) return;
566
- const el = current.getElement();
567
- el === null || el === void 0 || (_el$querySelector = el.querySelector('.sai-step-error')) === null || _el$querySelector === void 0 || _el$querySelector.remove();
568
- if (message) {
569
- var _el$querySelector2;
570
- const err = document.createElement('div');
571
- err.className = 'sai-step-error';
572
- err.textContent = '⚠ ' + message;
573
- el === null || el === void 0 || (_el$querySelector2 = el.querySelector('.shepherd-text')) === null || _el$querySelector2 === void 0 || _el$querySelector2.appendChild(err);
574
- }
575
- }
728
+ // ─── Legacy screen navigation ─────────────────────────────────────────────────
576
729
 
577
- // ═══════════════════════════════════════════════════════════════════════════
578
- // STYLES
579
- // ═══════════════════════════════════════════════════════════════════════════
580
-
581
- function injectStyles(theme, pos) {
582
- if (document.getElementById('sai-styles')) return;
583
- const triggerCSS = positionToCSS(pos.trigger);
584
- const panelCSS = positionToCSS(pos.panel);
585
- const isDark = theme._isDark;
586
- const stepBg = isDark ? 'var(--sai-bg)' : '#ffffff';
587
- const stepSurf = isDark ? 'var(--sai-surface)' : '#f8f8fc';
588
- const stepText = isDark ? 'var(--sai-text)' : '#1a1a2e';
589
- const stepBorder = isDark ? 'var(--sai-border)' : '#e4e4f0';
590
- const style = document.createElement('style');
591
- style.id = 'sai-styles';
592
- style.textContent = `
593
- #sai-trigger, #sai-panel { ${buildCSSVars(theme)} }
594
-
595
- /* ── Trigger ── */
596
- #sai-trigger {
597
- position: fixed; ${triggerCSS};
598
- width: 54px; height: 54px; border-radius: 50%;
599
- background: var(--sai-surface); border: 2px solid var(--sai-accent);
600
- color: var(--sai-text); font-size: 20px; cursor: pointer; z-index: 99998;
601
- display: flex; align-items: center; justify-content: center;
602
- box-shadow: 0 4px 20px color-mix(in srgb, var(--sai-accent) 40%, transparent);
603
- transition: transform .2s ease, box-shadow .2s ease;
604
- font-family: var(--sai-font); padding: 0;
605
- }
606
- #sai-trigger:hover {
607
- transform: scale(1.08);
608
- box-shadow: 0 6px 28px color-mix(in srgb, var(--sai-accent) 55%, transparent);
609
- }
610
- #sai-trigger .sai-pulse {
611
- position: absolute; width: 100%; height: 100%; border-radius: 50%;
612
- background: color-mix(in srgb, var(--sai-accent) 30%, transparent);
613
- animation: sai-pulse 2.2s ease-out infinite; pointer-events: none;
614
- }
615
- #sai-trigger.sai-paused .sai-pulse { animation: none; }
616
- #sai-trigger.sai-paused::after {
617
- content: '⏸'; position: absolute; bottom: -2px; right: -2px;
618
- font-size: 12px; background: var(--sai-accent); border-radius: 50%;
619
- width: 18px; height: 18px; display: flex; align-items: center;
620
- justify-content: center; color: #fff; line-height: 1;
621
- }
622
- @keyframes sai-pulse {
623
- 0% { transform: scale(1); opacity: .8; }
624
- 100% { transform: scale(1.75); opacity: 0; }
625
- }
730
+ /**
731
+ * Handles the legacy `screen` prop on features (backward-compat).
732
+ * Checks `screen.check()` and calls `screen.navigate()` if needed,
733
+ * then waits for `screen.waitFor` or `feature.selector` to appear.
734
+ *
735
+ * @param {object} feature — a feature config object
736
+ * @returns {Promise<void>}
737
+ */
738
+ async function ensureOnCorrectScreen(feature) {
739
+ if (!feature.screen) return;
740
+ if (typeof feature.screen.check === 'function' && feature.screen.check()) return;
741
+ addMsg('ai', 'Taking you to the right screen first…');
742
+ if (typeof feature.screen.navigate === 'function') {
743
+ feature.screen.navigate();
744
+ }
745
+ const waitSelector = feature.screen.waitFor || feature.selector;
746
+ if (waitSelector) await waitForElement(waitSelector, 10000);
747
+ }
626
748
 
627
- /* ── Panel ── */
628
- #sai-panel {
629
- position: fixed; ${panelCSS};
630
- width: 340px; background: var(--sai-bg);
631
- border: 1px solid var(--sai-border); border-radius: var(--sai-radius);
632
- display: flex; flex-direction: column; z-index: 99999; overflow: hidden;
633
- box-shadow: 0 16px 48px rgba(0,0,0,.18); font-family: var(--sai-font);
634
- transform: translateY(12px) scale(.97); opacity: 0; pointer-events: none;
635
- transition: transform .25s cubic-bezier(.34,1.56,.64,1), opacity .2s ease;
636
- max-height: 520px;
637
- }
638
- #sai-panel.sai-open { transform: translateY(0) scale(1); opacity: 1; pointer-events: all; }
749
+ // Builds and manages the chat panel DOM.
750
+ // Also exports the low-level message helpers used by navigation.js and tour.js
751
+ // so they can surface status messages without importing the full chat module.
639
752
 
640
- /* ── Header ── */
641
- #sai-header {
642
- display: flex; align-items: center; gap: 10px; padding: 13px 15px;
643
- background: var(--sai-surface); border-bottom: 1px solid var(--sai-border);
644
- }
645
- #sai-avatar {
646
- width: 30px; height: 30px; border-radius: 50%;
647
- background: linear-gradient(135deg, var(--sai-accent), var(--sai-accent2));
648
- display: flex; align-items: center; justify-content: center;
649
- font-size: 14px; flex-shrink: 0; color: #fff;
650
- }
651
- #sai-header-info { flex: 1; min-width: 0; }
652
- #sai-header-info h4 {
653
- margin: 0; font-size: 13px; font-weight: 600; color: var(--sai-text);
654
- white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
655
- }
656
- #sai-header-info p {
657
- margin: 0; font-size: 11px; color: var(--sai-text-dim);
658
- white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
659
- }
660
- #sai-close {
661
- background: none; border: none; color: var(--sai-text-dim); cursor: pointer;
662
- font-size: 18px; line-height: 1; padding: 0; flex-shrink: 0; transition: color .15s;
663
- }
664
- #sai-close:hover { color: var(--sai-text); }
665
-
666
- /* ── Messages ── */
667
- #sai-messages {
668
- flex: 1; overflow-y: auto; padding: 12px;
669
- display: flex; flex-direction: column; gap: 9px;
670
- min-height: 160px; max-height: 280px;
671
- scrollbar-width: thin; scrollbar-color: var(--sai-border) transparent;
672
- }
673
- #sai-messages::-webkit-scrollbar { width: 4px; }
674
- #sai-messages::-webkit-scrollbar-thumb { background: var(--sai-border); border-radius: 2px; }
675
- .sai-msg {
676
- max-width: 86%; padding: 8px 11px; border-radius: 11px;
677
- font-size: 13px; line-height: 1.55; animation: sai-in .18s ease both;
678
- }
679
- @keyframes sai-in {
680
- from { opacity: 0; transform: translateY(5px); }
681
- to { opacity: 1; transform: translateY(0); }
682
- }
683
- .sai-msg.sai-ai {
684
- background: var(--sai-surface); color: var(--sai-text);
685
- border-bottom-left-radius: 3px; align-self: flex-start;
686
- border: 1px solid var(--sai-border);
687
- }
688
- .sai-msg.sai-user {
689
- background: var(--sai-accent); color: #fff;
690
- border-bottom-right-radius: 3px; align-self: flex-end;
691
- }
692
- .sai-msg.sai-error {
693
- background: color-mix(in srgb, #ef4444 10%, var(--sai-bg));
694
- color: #ef4444;
695
- border: 1px solid color-mix(in srgb, #ef4444 25%, var(--sai-bg));
696
- align-self: flex-start;
697
- }
698
753
 
699
- /* ── Typing indicator ── */
700
- .sai-typing {
701
- display: flex; gap: 4px; padding: 9px 12px; align-self: flex-start;
702
- background: var(--sai-surface); border: 1px solid var(--sai-border);
703
- border-radius: 11px; border-bottom-left-radius: 3px;
704
- }
705
- .sai-typing span {
706
- width: 5px; height: 5px; border-radius: 50%;
707
- background: var(--sai-text-dim); animation: sai-bounce 1.2s infinite;
708
- }
709
- .sai-typing span:nth-child(2) { animation-delay: .15s; }
710
- .sai-typing span:nth-child(3) { animation-delay: .3s; }
711
- @keyframes sai-bounce {
712
- 0%,80%,100% { transform: translateY(0); }
713
- 40% { transform: translateY(-5px); }
714
- }
754
+ // Imported lazily inside handleSend to avoid a circular dep at module parse time.
755
+ // (chat → tour → chat would otherwise cycle.)
756
+ let _runTour = null;
757
+ function setRunTour(fn) {
758
+ _runTour = fn;
759
+ }
715
760
 
716
- /* ── Suggestions ── */
717
- #sai-suggestions { display: flex; flex-wrap: wrap; gap: 6px; padding: 0 12px 10px; }
718
- .sai-chip {
719
- font-size: 11px; padding: 5px 10px; border-radius: 20px;
720
- background: transparent; border: 1px solid var(--sai-border);
721
- color: var(--sai-text-dim); cursor: pointer; font-family: inherit; transition: all .15s;
722
- }
723
- .sai-chip:hover {
724
- border-color: var(--sai-accent); color: var(--sai-accent);
725
- background: color-mix(in srgb, var(--sai-accent) 6%, transparent);
726
- }
761
+ // ─── Helpers ──────────────────────────────────────────────────────────────────
727
762
 
728
- /* ── Input row ── */
729
- #sai-inputrow {
730
- display: flex; align-items: center; gap: 7px; padding: 9px 11px;
731
- border-top: 1px solid var(--sai-border); background: var(--sai-bg);
732
- }
733
- #sai-input {
734
- flex: 1; background: var(--sai-surface); border: 1px solid var(--sai-border);
735
- border-radius: 8px; padding: 7px 11px; color: var(--sai-text);
736
- font-size: 13px; outline: none; transition: border-color .15s; font-family: inherit;
737
- }
738
- #sai-input::placeholder { color: var(--sai-text-dim); }
739
- #sai-input:focus { border-color: var(--sai-accent); }
740
- #sai-send {
741
- width: 32px; height: 32px; flex-shrink: 0; border-radius: 8px;
742
- background: var(--sai-accent); border: none; color: #fff; font-size: 14px;
743
- cursor: pointer; display: flex; align-items: center; justify-content: center;
744
- transition: filter .15s, transform .1s; line-height: 1;
745
- }
746
- #sai-send:hover { filter: brightness(1.1); }
747
- #sai-send:active { transform: scale(.93); }
748
- #sai-send:disabled { background: var(--sai-border); cursor: not-allowed; }
749
-
750
- /* ── Shepherd step overrides ── */
751
- .sai-shepherd-step {
752
- background: ${stepBg} !important;
753
- border: 1px solid ${stepBorder} !important;
754
- border-radius: 12px !important;
755
- box-shadow: 0 8px 36px rgba(0,0,0,.18) !important;
756
- max-width: 290px !important;
757
- font-family: var(--sai-font, system-ui) !important;
758
- }
759
- .sai-shepherd-step.shepherd-has-title .shepherd-content .shepherd-header {
760
- background: ${stepSurf} !important; padding: 11px 15px 8px !important;
761
- border-bottom: 1px solid ${stepBorder} !important;
762
- }
763
- .sai-shepherd-step .shepherd-title {
764
- color: var(--sai-accent, #e94560) !important;
765
- font-size: 13px !important; font-weight: 700 !important;
766
- }
767
- .sai-shepherd-step .shepherd-text {
768
- color: ${stepText} !important; font-size: 13px !important;
769
- line-height: 1.6 !important; padding: 10px 15px !important;
770
- }
771
- .sai-shepherd-step .shepherd-footer {
772
- border-top: 1px solid ${stepBorder} !important; padding: 8px 11px !important;
773
- background: ${stepBg} !important; display: flex; gap: 5px; flex-wrap: wrap;
774
- }
775
- .sai-shepherd-step .shepherd-button {
776
- background: var(--sai-accent, #e94560) !important; color: #fff !important;
777
- border: none !important; border-radius: 6px !important; padding: 6px 13px !important;
778
- font-size: 12px !important; font-weight: 600 !important; cursor: pointer !important;
779
- transition: filter .15s !important; font-family: var(--sai-font, system-ui) !important;
780
- }
781
- .sai-shepherd-step .shepherd-button:hover { filter: brightness(1.1) !important; }
782
- .sai-shepherd-step .shepherd-button-secondary {
783
- background: transparent !important; color: var(--sai-text-dim, #888) !important;
784
- border: 1px solid ${stepBorder} !important;
785
- }
786
- .sai-shepherd-step .shepherd-button-secondary:hover {
787
- background: ${stepSurf} !important; color: ${stepText} !important;
788
- }
789
- .sai-shepherd-step .shepherd-cancel-icon { color: var(--sai-text-dim, #888) !important; }
790
- .sai-shepherd-step .shepherd-cancel-icon:hover { color: ${stepText} !important; }
791
- .sai-shepherd-step[data-popper-placement] > .shepherd-arrow::before {
792
- background: ${stepBorder} !important;
793
- }
763
+ function escHTML(str) {
764
+ return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
765
+ }
794
766
 
795
- /* ── Progress bar ── */
796
- .sai-progress { display: flex; align-items: center; gap: 8px; margin-left: auto; flex-shrink: 0; }
797
- .sai-progress-bar {
798
- width: 60px; height: 3px; border-radius: 2px; background: ${stepBorder}; overflow: hidden;
799
- }
800
- .sai-progress-fill {
801
- height: 100%; border-radius: 2px;
802
- background: var(--sai-accent, #e94560); transition: width .3s ease;
803
- }
804
- .sai-progress-label {
805
- font-size: 10px; color: var(--sai-text-dim, #888);
806
- white-space: nowrap; font-family: var(--sai-font, system-ui);
807
- }
767
+ // ─── Panel visibility ─────────────────────────────────────────────────────────
808
768
 
809
- /* ── Step error ── */
810
- .sai-step-error {
811
- margin-top: 8px; padding: 6px 10px;
812
- background: color-mix(in srgb, #ef4444 12%, ${stepBg});
813
- border: 1px solid color-mix(in srgb, #ef4444 25%, ${stepBorder});
814
- border-radius: 6px; color: #ef4444; font-size: 12px; line-height: 1.5;
815
- animation: sai-in .18s ease;
816
- }
769
+ function togglePanel() {
770
+ var _document$getElementB, _document$getElementB2, _document$getElementB3;
771
+ setIsOpen(!isOpen);
772
+ (_document$getElementB = document.getElementById('sai-panel')) === null || _document$getElementB === void 0 || _document$getElementB.classList.toggle('sai-open', isOpen);
773
+ (_document$getElementB2 = document.getElementById('sai-trigger')) === null || _document$getElementB2 === void 0 || _document$getElementB2.classList.toggle('sai-paused', !!pausedSteps);
774
+ if (isOpen) (_document$getElementB3 = document.getElementById('sai-input')) === null || _document$getElementB3 === void 0 || _document$getElementB3.focus();
775
+ }
817
776
 
818
- /* ── Glass preset ── */
819
- .sai-glass-preset .sai-shepherd-step {
820
- background: rgba(255, 255, 255, 0.10) !important;
821
- backdrop-filter: blur(18px) saturate(180%) !important;
822
- -webkit-backdrop-filter: blur(18px) saturate(180%) !important;
823
- border: 1px solid rgba(255, 255, 255, 0.22) !important;
824
- box-shadow: 0 8px 36px rgba(0,0,0,.12) !important;
825
- }
826
- .sai-glass-preset .sai-shepherd-step .shepherd-text,
827
- .sai-glass-preset .sai-shepherd-step .shepherd-title {
828
- color: #ffffff !important;
829
- text-shadow: 0 1px 3px rgba(0,0,0,.35);
830
- }
831
- .sai-glass-preset .sai-shepherd-step .shepherd-footer,
832
- .sai-glass-preset .sai-shepherd-step .shepherd-header {
833
- background: transparent !important;
834
- border-color: rgba(255,255,255,0.15) !important;
777
+ // ─── Message helpers (also used by navigation.js / tour.js) ──────────────────
778
+
779
+ function addMsg(type, text) {
780
+ const msgs = document.getElementById('sai-messages');
781
+ if (!msgs) return;
782
+ const div = document.createElement('div');
783
+ div.className = `sai-msg sai-${type}`;
784
+ div.textContent = text;
785
+ msgs.appendChild(div);
786
+ msgs.scrollTop = msgs.scrollHeight;
787
+ }
788
+ function showTyping() {
789
+ const msgs = document.getElementById('sai-messages');
790
+ const el = document.createElement('div');
791
+ el.className = 'sai-typing';
792
+ el.id = 'sai-typing';
793
+ el.innerHTML = '<span></span><span></span><span></span>';
794
+ msgs.appendChild(el);
795
+ msgs.scrollTop = msgs.scrollHeight;
796
+ }
797
+ function hideTyping() {
798
+ var _document$getElementB4;
799
+ (_document$getElementB4 = document.getElementById('sai-typing')) === null || _document$getElementB4 === void 0 || _document$getElementB4.remove();
800
+ }
801
+ function setDisabled(d) {
802
+ ['sai-input', 'sai-send'].forEach(id => {
803
+ const el = document.getElementById(id);
804
+ if (el) el.disabled = d;
805
+ });
806
+ }
807
+
808
+ // ─── Pause/resume UI ──────────────────────────────────────────────────────────
809
+
810
+ /**
811
+ * Renders the "Tour paused — Resume from step N" bubble in the chat.
812
+ * Also opens the panel if it's currently closed.
813
+ *
814
+ * @param {number} fromIndex — zero-based step index to resume from
815
+ */
816
+ function showResumeButton(fromIndex) {
817
+ var _document$getElementB5, _document$getElementB6;
818
+ const msgs = document.getElementById('sai-messages');
819
+ if (!msgs) return;
820
+ (_document$getElementB5 = document.getElementById('sai-resume-prompt')) === null || _document$getElementB5 === void 0 || _document$getElementB5.remove();
821
+ const div = document.createElement('div');
822
+ div.id = 'sai-resume-prompt';
823
+ div.className = 'sai-msg sai-ai';
824
+ div.innerHTML = `
825
+ Tour paused. Ready when you are.
826
+ <br/>
827
+ <button class="sai-chip" id="sai-resume-btn" style="display:inline-block;margin-top:8px;">
828
+ ▶ Resume from step ${fromIndex + 1}
829
+ </button>
830
+ `;
831
+ msgs.appendChild(div);
832
+ msgs.scrollTop = msgs.scrollHeight;
833
+ (_document$getElementB6 = document.getElementById('sai-resume-btn')) === null || _document$getElementB6 === void 0 || _document$getElementB6.addEventListener('click', () => {
834
+ var _runTour2;
835
+ div.remove();
836
+ if (!pausedSteps) return;
837
+ const steps = pausedSteps;
838
+ const idx = pausedIndex;
839
+ setPausedSteps(null);
840
+ setPausedIndex(0);
841
+ if (isOpen) togglePanel();
842
+ (_runTour2 = _runTour) === null || _runTour2 === void 0 || _runTour2(steps.slice(idx));
843
+ });
844
+ if (!isOpen) togglePanel();
845
+ }
846
+
847
+ // ─── Send / AI round-trip ─────────────────────────────────────────────────────
848
+
849
+ async function handleSend(text) {
850
+ var _document$getElementB7, _document$getElementB8;
851
+ const input = document.getElementById('sai-input');
852
+ if (input) input.value = '';
853
+ document.getElementById('sai-suggestions').style.display = 'none';
854
+
855
+ // New message clears any existing pause state
856
+ setPausedSteps(null);
857
+ setPausedIndex(0);
858
+ (_document$getElementB7 = document.getElementById('sai-resume-prompt')) === null || _document$getElementB7 === void 0 || _document$getElementB7.remove();
859
+ (_document$getElementB8 = document.getElementById('sai-trigger')) === null || _document$getElementB8 === void 0 || _document$getElementB8.classList.remove('sai-paused');
860
+ addMsg('user', text);
861
+ setDisabled(true);
862
+ showTyping();
863
+ try {
864
+ var _result$steps;
865
+ const result = await callAI(text);
866
+ hideTyping();
867
+ addMsg('ai', result.message);
868
+ if ((_result$steps = result.steps) !== null && _result$steps !== void 0 && _result$steps.length) {
869
+ const routesNeeded = previewRoutesNeeded(result.steps);
870
+ if (routesNeeded.length > 0) {
871
+ announceNavigationPlan(routesNeeded);
835
872
  }
836
- `;
837
- document.head.appendChild(style);
873
+ const delay = routesNeeded.length > 0 ? 1200 : 600;
874
+ setTimeout(() => {
875
+ var _runTour3;
876
+ togglePanel();
877
+ (_runTour3 = _runTour) === null || _runTour3 === void 0 || _runTour3(result.steps);
878
+ }, delay);
838
879
  }
880
+ } catch (err) {
881
+ hideTyping();
882
+ addMsg('error', err.message || 'Something went wrong. Please try again.');
883
+ console.error('[Eventop]', err);
884
+ } finally {
885
+ var _document$getElementB9;
886
+ setDisabled(false);
887
+ (_document$getElementB9 = document.getElementById('sai-input')) === null || _document$getElementB9 === void 0 || _document$getElementB9.focus();
888
+ }
889
+ }
839
890
 
840
- // ═══════════════════════════════════════════════════════════════════════════
841
- // CHAT UI
842
- // ═══════════════════════════════════════════════════════════════════════════
843
-
844
- function buildChat(theme, positionCSS) {
845
- var _config$theme, _config$suggestions, _config$theme2, _config$theme3;
846
- if (document.getElementById('sai-trigger')) return;
847
- injectStyles(theme, positionCSS);
848
- const trigger = document.createElement('button');
849
- trigger.id = 'sai-trigger';
850
- trigger.title = 'Need help?';
851
- trigger.setAttribute('aria-label', 'Open help assistant');
852
- trigger.innerHTML = '<span class="sai-pulse" aria-hidden="true"></span>✦';
853
- document.body.appendChild(trigger);
854
- const panel = document.createElement('div');
855
- panel.id = 'sai-panel';
856
- panel.setAttribute('role', 'dialog');
857
- panel.setAttribute('aria-label', `${_config.assistantName || 'AI Guide'} chat`);
858
- panel.innerHTML = `
859
- <div id="sai-header">
860
- <div id="sai-avatar" aria-hidden="true">✦</div>
861
- <div id="sai-header-info">
862
- <h4>${escHTML(_config.assistantName || 'AI Guide')}</h4>
863
- <p>Ask me anything about ${escHTML(_config.appName)}</p>
864
- </div>
865
- <button id="sai-close" aria-label="Close help assistant">×</button>
866
- </div>
867
- <div id="sai-messages" role="log" aria-live="polite"></div>
868
- <div id="sai-suggestions" aria-label="Suggested questions"></div>
869
- <div id="sai-inputrow">
870
- <input id="sai-input" type="text" placeholder="What do you need help with?"
871
- autocomplete="off" aria-label="Ask a question"/>
872
- <button id="sai-send" aria-label="Send message">➤</button>
891
+ // ─── DOM builder ─────────────────────────────────────────────────────────────
892
+
893
+ /**
894
+ * Mounts the trigger button and chat panel into document.body.
895
+ * Idempotent — safe to call multiple times (exits early if already mounted).
896
+ *
897
+ * @param {object} theme — resolved theme tokens
898
+ * @param {object} posCSS — resolved position object from resolvePosition()
899
+ */
900
+ function buildChat(theme, posCSS) {
901
+ var _state$config$theme, _state$config$suggest, _state$config$theme2, _state$config$theme3;
902
+ if (document.getElementById('sai-trigger')) return;
903
+ loadShepherdCSS();
904
+ injectStyles(theme, posCSS);
905
+
906
+ // ── Trigger button ──
907
+ const trigger = document.createElement('button');
908
+ trigger.id = 'sai-trigger';
909
+ trigger.title = 'Need help?';
910
+ trigger.setAttribute('aria-label', 'Open help assistant');
911
+ trigger.innerHTML = '<span class="sai-pulse" aria-hidden="true"></span>✦';
912
+ document.body.appendChild(trigger);
913
+
914
+ // ── Panel ──
915
+ const panel = document.createElement('div');
916
+ panel.id = 'sai-panel';
917
+ panel.setAttribute('role', 'dialog');
918
+ panel.setAttribute('aria-label', `${config.assistantName || 'AI Guide'} chat`);
919
+ panel.innerHTML = `
920
+ <div id="sai-header">
921
+ <div id="sai-avatar" aria-hidden="true">✦</div>
922
+ <div id="sai-header-info">
923
+ <h4>${escHTML(config.assistantName || 'AI Guide')}</h4>
924
+ <p>Ask me anything about ${escHTML(config.appName)}</p>
873
925
  </div>
874
- `;
875
- document.body.appendChild(panel);
876
- if (((_config$theme = _config.theme) === null || _config$theme === void 0 ? void 0 : _config$theme.preset) === 'glass') {
877
- document.body.classList.add('sai-glass-preset');
878
- }
879
- if ((_config$suggestions = _config.suggestions) !== null && _config$suggestions !== void 0 && _config$suggestions.length) {
880
- const container = panel.querySelector('#sai-suggestions');
881
- _config.suggestions.forEach(s => {
882
- const btn = document.createElement('button');
883
- btn.className = 'sai-chip';
884
- btn.textContent = s;
885
- btn.addEventListener('click', () => handleSend(s));
886
- container.appendChild(btn);
887
- });
888
- }
889
- trigger.addEventListener('click', togglePanel);
890
- panel.querySelector('#sai-close').addEventListener('click', togglePanel);
891
- panel.querySelector('#sai-send').addEventListener('click', () => {
892
- const v = panel.querySelector('#sai-input').value.trim();
893
- if (v) handleSend(v);
894
- });
895
- panel.querySelector('#sai-input').addEventListener('keydown', e => {
896
- if (e.key === 'Enter' && !e.shiftKey) {
897
- e.preventDefault();
898
- const v = e.target.value.trim();
899
- if (v) handleSend(v);
900
- }
901
- });
902
- addMsg('ai', `Hey! 👋 I can guide you through ${_config.appName}. What would you like to do?`);
903
-
904
- // Auto theme switching
905
- if (((_config$theme2 = _config.theme) === null || _config$theme2 === void 0 ? void 0 : _config$theme2.mode) === 'auto' || !((_config$theme3 = _config.theme) !== null && _config$theme3 !== void 0 && _config$theme3.mode)) {
906
- _mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
907
- _mediaQuery.addEventListener('change', () => {
908
- var _document$getElementB3;
909
- const newTheme = resolveTheme(_config.theme);
910
- applyTheme(newTheme);
911
- (_document$getElementB3 = document.getElementById('sai-styles')) === null || _document$getElementB3 === void 0 || _document$getElementB3.remove();
912
- injectStyles(newTheme, positionCSS);
913
- });
926
+ <button id="sai-close" aria-label="Close help assistant">×</button>
927
+ </div>
928
+ <div id="sai-messages" role="log" aria-live="polite"></div>
929
+ <div id="sai-suggestions" aria-label="Suggested questions"></div>
930
+ <div id="sai-inputrow">
931
+ <input id="sai-input" type="text" placeholder="What do you need help with?"
932
+ autocomplete="off" aria-label="Ask a question"/>
933
+ <button id="sai-send" aria-label="Send message">➤</button>
934
+ </div>
935
+ `;
936
+ document.body.appendChild(panel);
937
+ if (((_state$config$theme = config.theme) === null || _state$config$theme === void 0 ? void 0 : _state$config$theme.preset) === 'glass') {
938
+ document.body.classList.add('sai-glass-preset');
939
+ }
940
+
941
+ // ── Suggestion chips ──
942
+ if ((_state$config$suggest = config.suggestions) !== null && _state$config$suggest !== void 0 && _state$config$suggest.length) {
943
+ const container = panel.querySelector('#sai-suggestions');
944
+ config.suggestions.forEach(s => {
945
+ const btn = document.createElement('button');
946
+ btn.className = 'sai-chip';
947
+ btn.textContent = s;
948
+ btn.addEventListener('click', () => handleSend(s));
949
+ container.appendChild(btn);
950
+ });
951
+ }
952
+
953
+ // ── Event listeners ──
954
+ trigger.addEventListener('click', togglePanel);
955
+ panel.querySelector('#sai-close').addEventListener('click', togglePanel);
956
+ panel.querySelector('#sai-send').addEventListener('click', () => {
957
+ const v = panel.querySelector('#sai-input').value.trim();
958
+ if (v) handleSend(v);
959
+ });
960
+ panel.querySelector('#sai-input').addEventListener('keydown', e => {
961
+ if (e.key === 'Enter' && !e.shiftKey) {
962
+ e.preventDefault();
963
+ const v = e.target.value.trim();
964
+ if (v) handleSend(v);
965
+ }
966
+ });
967
+ addMsg('ai', `Hey! 👋 I can guide you through ${config.appName}. What would you like to do?`);
968
+
969
+ // ── Auto theme switching ──
970
+ if (((_state$config$theme2 = config.theme) === null || _state$config$theme2 === void 0 ? void 0 : _state$config$theme2.mode) === 'auto' || !((_state$config$theme3 = config.theme) !== null && _state$config$theme3 !== void 0 && _state$config$theme3.mode)) {
971
+ const mq = window.matchMedia('(prefers-color-scheme: dark)');
972
+ mq.addEventListener('change', () => {
973
+ var _document$getElementB0;
974
+ const newTheme = resolveTheme(config.theme);
975
+ applyTheme(newTheme);
976
+ (_document$getElementB0 = document.getElementById('sai-styles')) === null || _document$getElementB0 === void 0 || _document$getElementB0.remove();
977
+ injectStyles(newTheme, posCSS);
978
+ });
979
+ }
980
+ }
981
+
982
+ // Expands a feature's `flow[]` array into individual Shepherd-ready step objects.
983
+ // A feature with no `flow` is returned as-is (wrapped in an array).
984
+
985
+ /**
986
+ * @param {object} aiStep — the step object returned by the AI
987
+ * @param {object} feature — the matching feature config (may have a .flow array)
988
+ * @returns {Array<object>} one or more expanded step objects
989
+ */
990
+ function expandFlowSteps(aiStep, feature) {
991
+ var _feature$flow;
992
+ if (!((_feature$flow = feature.flow) !== null && _feature$flow !== void 0 && _feature$flow.length)) return [aiStep];
993
+ return feature.flow.map((entry, i) => ({
994
+ id: `${aiStep.id}-flow-${i}`,
995
+ title: i === 0 ? aiStep.title : `${aiStep.title} (${i + 1}/${feature.flow.length})`,
996
+ text: i === 0 ? aiStep.text : `Step ${i + 1} of ${feature.flow.length}: continue with the action highlighted below.`,
997
+ position: aiStep.position || 'bottom',
998
+ selector: entry.selector || null,
999
+ waitFor: entry.waitFor || null,
1000
+ advanceOn: entry.advanceOn || null,
1001
+ _parentId: aiStep.id
1002
+ }));
1003
+ }
1004
+
1005
+ // Loads Shepherd.js, builds + runs tours, wires up advanceOn listeners,
1006
+ // progress indicators, pause/resume, and step-level error display.
1007
+
1008
+ const SHEPHERD_JS = 'https://cdn.jsdelivr.net/npm/shepherd.js@11.2.0/dist/js/shepherd.min.js';
1009
+
1010
+ // ─── Shepherd loader ──────────────────────────────────────────────────────────
1011
+
1012
+ function loadScript(src) {
1013
+ return new Promise((res, rej) => {
1014
+ if (document.querySelector(`script[src="${src}"]`)) return res();
1015
+ const s = document.createElement('script');
1016
+ s.src = src;
1017
+ s.onload = res;
1018
+ s.onerror = rej;
1019
+ document.head.appendChild(s);
1020
+ });
1021
+ }
1022
+ async function ensureShepherd() {
1023
+ if (typeof Shepherd !== 'undefined') return;
1024
+ await loadScript(SHEPHERD_JS);
1025
+ }
1026
+
1027
+ // ─── Feature-map merge ────────────────────────────────────────────────────────
1028
+
1029
+ /**
1030
+ * Merges an AI step with its matching entry from the live feature map.
1031
+ * The feature map always wins for `selector` so mismatches are impossible.
1032
+ *
1033
+ * @param {object} step
1034
+ * @returns {object}
1035
+ */
1036
+ function mergeWithFeature(step) {
1037
+ var _state$config;
1038
+ if (!((_state$config = config) !== null && _state$config !== void 0 && _state$config.features)) return step;
1039
+ const feature = config.features.find(f => f.id === (step._parentId || step.id));
1040
+ if (!feature) return step;
1041
+ return {
1042
+ waitFor: feature.waitFor || null,
1043
+ advanceOn: feature.advanceOn || null,
1044
+ validate: feature.validate || null,
1045
+ screen: feature.screen || null,
1046
+ flow: feature.flow || null,
1047
+ route: feature.route || null,
1048
+ ...step,
1049
+ selector: feature.selector || step.selector // feature map always wins
1050
+ };
1051
+ }
1052
+
1053
+ // ─── Step orchestration ───────────────────────────────────────────────────────
1054
+
1055
+ /**
1056
+ * Builds a `beforeShowPromise` for a Shepherd step that handles:
1057
+ * 1. Cross-page navigation (route prop) with automatic waiting
1058
+ * 2. Legacy screen navigation (screen.navigate)
1059
+ * 3. Element waiting (waitFor prop)
1060
+ *
1061
+ * @param {object} step
1062
+ * @param {number} waitTimeout
1063
+ * @returns {() => Promise<void>}
1064
+ */
1065
+ function makeBeforeShowPromise(step, waitTimeout) {
1066
+ return () => (async () => {
1067
+ const freshMerged = mergeWithFeature(step);
1068
+ const targetRoute = freshMerged.route;
1069
+ if (targetRoute && getCurrentRoute() !== targetRoute) {
1070
+ await navigateToRoute(targetRoute, freshMerged.name || step.title);
1071
+ const postNavMerge = mergeWithFeature(step);
1072
+ if (postNavMerge.selector) {
1073
+ try {
1074
+ var _step$_shepherdRef, _step$_shepherdRef$up;
1075
+ (_step$_shepherdRef = step._shepherdRef) === null || _step$_shepherdRef === void 0 || (_step$_shepherdRef$up = _step$_shepherdRef.updateStepOptions) === null || _step$_shepherdRef$up === void 0 || _step$_shepherdRef$up.call(_step$_shepherdRef, {
1076
+ attachTo: {
1077
+ element: postNavMerge.selector,
1078
+ on: step.position || 'bottom'
1079
+ }
1080
+ });
1081
+ } catch (_) {/* non-fatal */}
1082
+ await waitForElement(postNavMerge.selector, waitTimeout);
1083
+ return;
914
1084
  }
915
1085
  }
916
- function escHTML(str) {
917
- return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
1086
+ if (freshMerged.screen) {
1087
+ await ensureOnCorrectScreen(freshMerged);
918
1088
  }
919
- function togglePanel() {
920
- var _document$getElementB4, _document$getElementB5, _document$getElementB6;
921
- _isOpen = !_isOpen;
922
- (_document$getElementB4 = document.getElementById('sai-panel')) === null || _document$getElementB4 === void 0 || _document$getElementB4.classList.toggle('sai-open', _isOpen);
923
- (_document$getElementB5 = document.getElementById('sai-trigger')) === null || _document$getElementB5 === void 0 || _document$getElementB5.classList.toggle('sai-paused', !!_pausedSteps);
924
- if (_isOpen) (_document$getElementB6 = document.getElementById('sai-input')) === null || _document$getElementB6 === void 0 || _document$getElementB6.focus();
1089
+ if (freshMerged.waitFor) {
1090
+ await waitForElement(freshMerged.waitFor, waitTimeout);
925
1091
  }
926
- function addMsg(type, text) {
927
- const msgs = document.getElementById('sai-messages');
928
- if (!msgs) return;
929
- const div = document.createElement('div');
930
- div.className = `sai-msg sai-${type}`;
931
- div.textContent = text;
932
- msgs.appendChild(div);
933
- msgs.scrollTop = msgs.scrollHeight;
1092
+ })();
1093
+ }
1094
+
1095
+ // ─── Event wiring ─────────────────────────────────────────────────────────────
1096
+
1097
+ function wireAdvanceOn(shepherdStep, advanceOn, tour) {
1098
+ if (!(advanceOn !== null && advanceOn !== void 0 && advanceOn.selector) || !(advanceOn !== null && advanceOn !== void 0 && advanceOn.event)) return;
1099
+ function handler(e) {
1100
+ if (e.target.matches(advanceOn.selector) || e.target.closest(advanceOn.selector)) {
1101
+ setTimeout(() => {
1102
+ if (tour && !tour.isActive()) return;
1103
+ tour.next();
1104
+ }, advanceOn.delay || 300);
934
1105
  }
935
- function showTyping() {
936
- const msgs = document.getElementById('sai-messages');
937
- const el = document.createElement('div');
938
- el.className = 'sai-typing';
939
- el.id = 'sai-typing';
940
- el.innerHTML = '<span></span><span></span><span></span>';
941
- msgs.appendChild(el);
942
- msgs.scrollTop = msgs.scrollHeight;
1106
+ }
1107
+ document.addEventListener(advanceOn.event, handler, true);
1108
+ pushCleanup(() => document.removeEventListener(advanceOn.event, handler, true));
1109
+ shepherdStep.on('show', () => {
1110
+ var _shepherdStep$getElem;
1111
+ const nextBtn = (_shepherdStep$getElem = shepherdStep.getElement()) === null || _shepherdStep$getElem === void 0 ? void 0 : _shepherdStep$getElem.querySelector('.shepherd-footer .shepherd-button:not(.shepherd-button-secondary)');
1112
+ if (nextBtn && !shepherdStep._isLast) {
1113
+ nextBtn.style.opacity = '0.4';
1114
+ nextBtn.title = 'Complete the action above to continue';
943
1115
  }
944
- function hideTyping() {
945
- var _document$getElementB7;
946
- (_document$getElementB7 = document.getElementById('sai-typing')) === null || _document$getElementB7 === void 0 || _document$getElementB7.remove();
1116
+ });
1117
+ }
1118
+ function addProgressIndicator(shepherdStep, index, total) {
1119
+ shepherdStep.on('show', () => {
1120
+ var _shepherdStep$getElem2;
1121
+ const header = (_shepherdStep$getElem2 = shepherdStep.getElement()) === null || _shepherdStep$getElem2 === void 0 ? void 0 : _shepherdStep$getElem2.querySelector('.shepherd-header');
1122
+ if (!header || header.querySelector('.sai-progress')) return;
1123
+ const pct = Math.round((index + 1) / total * 100);
1124
+ const wrapper = document.createElement('div');
1125
+ wrapper.className = 'sai-progress';
1126
+ wrapper.innerHTML = `
1127
+ <div class="sai-progress-bar">
1128
+ <div class="sai-progress-fill" style="width:${pct}%"></div>
1129
+ </div>
1130
+ <span class="sai-progress-label">${index + 1} / ${total}</span>
1131
+ `;
1132
+ header.appendChild(wrapper);
1133
+ });
1134
+ }
1135
+
1136
+ // ─── Public API ───────────────────────────────────────────────────────────────
1137
+
1138
+ /**
1139
+ * Starts a Shepherd tour from the given steps array.
1140
+ *
1141
+ * @param {Array} steps
1142
+ * @param {object} [options]
1143
+ * @param {boolean} [options.showProgress=true]
1144
+ * @param {number} [options.waitTimeout=8000]
1145
+ */
1146
+ async function runTour(steps, options = {}) {
1147
+ var _state$config2;
1148
+ await ensureShepherd();
1149
+ if (tour) {
1150
+ tour.cancel();
1151
+ }
1152
+ runAndClearCleanups();
1153
+ setTour(null);
1154
+ if (!(steps !== null && steps !== void 0 && steps.length)) return;
1155
+ const {
1156
+ showProgress = true,
1157
+ waitTimeout = 8000
1158
+ } = options;
1159
+ const mergedSteps = steps.map(mergeWithFeature);
1160
+
1161
+ // Legacy: navigate to the correct screen for the first step
1162
+ const firstFeature = (_state$config2 = config) === null || _state$config2 === void 0 || (_state$config2 = _state$config2.features) === null || _state$config2 === void 0 ? void 0 : _state$config2.find(f => {
1163
+ var _mergedSteps$;
1164
+ return f.id === ((_mergedSteps$ = mergedSteps[0]) === null || _mergedSteps$ === void 0 ? void 0 : _mergedSteps$.id);
1165
+ });
1166
+ if (firstFeature !== null && firstFeature !== void 0 && firstFeature.screen) await ensureOnCorrectScreen(firstFeature);
1167
+
1168
+ // Expand flow[] into individual Shepherd steps
1169
+ const expandedSteps = mergedSteps.flatMap(step => {
1170
+ var _state$config3;
1171
+ const feature = (_state$config3 = config) === null || _state$config3 === void 0 || (_state$config3 = _state$config3.features) === null || _state$config3 === void 0 ? void 0 : _state$config3.find(f => f.id === step.id);
1172
+ return feature ? expandFlowSteps(step, feature) : [step];
1173
+ });
1174
+ const ShepherdClass = typeof Shepherd !== 'undefined' ? Shepherd : window.Shepherd;
1175
+ const tour$1 = new ShepherdClass.Tour({
1176
+ useModalOverlay: true,
1177
+ defaultStepOptions: {
1178
+ scrollTo: {
1179
+ behavior: 'smooth',
1180
+ block: 'center'
1181
+ },
1182
+ cancelIcon: {
1183
+ enabled: true
1184
+ },
1185
+ classes: 'sai-shepherd-step'
947
1186
  }
948
- function setDisabled(d) {
949
- ['sai-input', 'sai-send'].forEach(id => {
950
- const el = document.getElementById(id);
951
- if (el) el.disabled = d;
1187
+ });
1188
+ setTour(tour$1);
1189
+ expandedSteps.forEach((step, i) => {
1190
+ var _step$advanceOn, _step$advanceOn2;
1191
+ const isLast = i === expandedSteps.length - 1;
1192
+ const hasAuto = !!((_step$advanceOn = step.advanceOn) !== null && _step$advanceOn !== void 0 && _step$advanceOn.selector && (_step$advanceOn2 = step.advanceOn) !== null && _step$advanceOn2 !== void 0 && _step$advanceOn2.event);
1193
+ const buttons = [];
1194
+ if (i > 0) {
1195
+ buttons.push({
1196
+ text: '← Back',
1197
+ action: tour$1.back,
1198
+ secondary: true
952
1199
  });
953
1200
  }
954
- async function handleSend(text) {
955
- var _document$getElementB8, _document$getElementB9;
956
- const input = document.getElementById('sai-input');
957
- if (input) input.value = '';
958
- document.getElementById('sai-suggestions').style.display = 'none';
959
-
960
- // New message clears any existing pause state
961
- _pausedSteps = null;
962
- _pausedIndex = 0;
963
- (_document$getElementB8 = document.getElementById('sai-resume-prompt')) === null || _document$getElementB8 === void 0 || _document$getElementB8.remove();
964
- (_document$getElementB9 = document.getElementById('sai-trigger')) === null || _document$getElementB9 === void 0 || _document$getElementB9.classList.remove('sai-paused');
965
- addMsg('user', text);
966
- setDisabled(true);
967
- showTyping();
968
- try {
969
- var _result$steps;
970
- const result = await callAI(text);
971
- hideTyping();
972
- addMsg('ai', result.message);
973
- if ((_result$steps = result.steps) !== null && _result$steps !== void 0 && _result$steps.length) {
974
- setTimeout(() => {
975
- togglePanel();
976
- runTour(result.steps);
977
- }, 600);
978
- }
979
- } catch (err) {
980
- hideTyping();
981
- addMsg('error', err.message || 'Something went wrong. Please try again.');
982
- console.error('[Eventop]', err);
983
- } finally {
984
- var _document$getElementB0;
985
- setDisabled(false);
986
- (_document$getElementB0 = document.getElementById('sai-input')) === null || _document$getElementB0 === void 0 || _document$getElementB0.focus();
1201
+ buttons.push({
1202
+ text: isLast ? 'Done ✓' : 'Next →',
1203
+ action: isLast ? tour$1.complete : tour$1.next
1204
+ });
1205
+ buttons.push({
1206
+ text: '⏸ Pause',
1207
+ secondary: true,
1208
+ action: function () {
1209
+ tour$1.cancel();
987
1210
  }
1211
+ });
1212
+ const shepherdStep = tour$1.addStep({
1213
+ id: step.id || `sai-step-${i}`,
1214
+ title: step.title,
1215
+ text: step.text,
1216
+ attachTo: step.selector ? {
1217
+ element: step.selector,
1218
+ on: step.position || 'bottom'
1219
+ } : undefined,
1220
+ beforeShowPromise: makeBeforeShowPromise(step, waitTimeout),
1221
+ buttons
1222
+ });
1223
+ step._shepherdRef = shepherdStep;
1224
+ shepherdStep._isLast = isLast;
1225
+ if (hasAuto) wireAdvanceOn(shepherdStep, step.advanceOn, tour$1);
1226
+ if (showProgress && expandedSteps.length > 1) {
1227
+ addProgressIndicator(shepherdStep, i, expandedSteps.length);
988
1228
  }
1229
+ });
1230
+ tour$1.on('complete', () => {
1231
+ runAndClearCleanups();
1232
+ setPausedSteps(null);
1233
+ setPausedIndex(0);
1234
+ setTour(null);
1235
+ });
989
1236
 
990
- // ═══════════════════════════════════════════════════════════════════════════
991
- // PUBLIC API
992
- // ═══════════════════════════════════════════════════════════════════════════
993
-
994
- const Eventop = {
995
- providers,
996
- init(opts = {}) {
997
- var _opts$config, _opts$config2;
998
- if (!opts.provider) throw new Error('[Eventop] provider is required');
999
- if (!((_opts$config = opts.config) !== null && _opts$config !== void 0 && _opts$config.appName)) throw new Error('[Eventop] config.appName is required');
1000
- if (!((_opts$config2 = opts.config) !== null && _opts$config2 !== void 0 && _opts$config2.features)) throw new Error('[Eventop] config.features is required');
1001
- _provider = opts.provider;
1002
- _config = opts.config;
1003
- const theme = resolveTheme(_config.theme);
1004
- const posCSS = resolvePosition(_config.position);
1005
- if (document.readyState === 'loading') {
1006
- document.addEventListener('DOMContentLoaded', () => buildChat(theme, posCSS));
1007
- } else {
1008
- buildChat(theme, posCSS);
1009
- }
1010
- ensureShepherd();
1011
- },
1012
- open() {
1013
- if (!_isOpen) togglePanel();
1014
- },
1015
- close() {
1016
- if (_isOpen) togglePanel();
1017
- },
1018
- runTour,
1019
- cancelTour() {
1020
- var _document$getElementB1, _document$getElementB10;
1021
- _pausedSteps = null;
1022
- _pausedIndex = 0;
1023
- if (_tour) {
1024
- _tour.cancel();
1025
- }
1026
- _cleanups.forEach(fn => fn());
1027
- _cleanups = [];
1028
- _tour = null;
1029
- (_document$getElementB1 = document.getElementById('sai-trigger')) === null || _document$getElementB1 === void 0 || _document$getElementB1.classList.remove('sai-paused');
1030
- (_document$getElementB10 = document.getElementById('sai-resume-prompt')) === null || _document$getElementB10 === void 0 || _document$getElementB10.remove();
1031
- document.body.classList.remove('sai-glass-preset');
1032
- },
1033
- resumeTour() {
1034
- var _document$getElementB11, _document$getElementB12;
1035
- if (!_pausedSteps) return;
1036
- const steps = _pausedSteps;
1037
- const idx = _pausedIndex;
1038
- _pausedSteps = null;
1039
- _pausedIndex = 0;
1040
- (_document$getElementB11 = document.getElementById('sai-resume-prompt')) === null || _document$getElementB11 === void 0 || _document$getElementB11.remove();
1041
- (_document$getElementB12 = document.getElementById('sai-trigger')) === null || _document$getElementB12 === void 0 || _document$getElementB12.classList.remove('sai-paused');
1042
- if (_isOpen) togglePanel();
1043
- runTour(steps.slice(idx));
1044
- },
1045
- isPaused() {
1046
- return !!_pausedSteps;
1047
- },
1048
- isActive() {
1049
- var _tour4;
1050
- return !!((_tour4 = _tour) !== null && _tour4 !== void 0 && _tour4.isActive());
1051
- },
1052
- stepComplete,
1053
- stepFail,
1054
- /** @internal — used by the React package to sync the live feature registry */
1055
- _updateConfig(partial) {
1056
- if (!_config) return;
1057
- _config = {
1058
- ..._config,
1059
- ...partial
1060
- };
1061
- }
1062
- };
1063
- return Eventop;
1237
+ // Cancel → pause (not hard destroy)
1238
+ tour$1.on('cancel', () => {
1239
+ const currentStepEl = tour$1.getCurrentStep();
1240
+ const currentIdx = currentStepEl ? expandedSteps.findIndex(s => s.id === currentStepEl.id) : 0;
1241
+ runAndClearCleanups();
1242
+ setPausedSteps(expandedSteps);
1243
+ setPausedIndex(Math.max(0, currentIdx));
1244
+ setTour(null);
1245
+ showResumeButton(pausedIndex);
1064
1246
  });
1065
- })(core$1);
1066
- var coreExports = core$1.exports;
1247
+ tour$1.start();
1248
+ }
1067
1249
 
1068
- var core = /*#__PURE__*/_mergeNamespaces({
1069
- __proto__: null
1070
- }, [coreExports]);
1250
+ /**
1251
+ * Advances the active tour to the next step programmatically.
1252
+ * Useful when your own UI signals step completion.
1253
+ */
1254
+ function stepComplete() {
1255
+ var _state$tour;
1256
+ if ((_state$tour = tour) !== null && _state$tour !== void 0 && _state$tour.isActive()) tour.next();
1257
+ }
1071
1258
 
1072
- export { core as c };
1259
+ /**
1260
+ * Injects an error message into the current Shepherd step's text area.
1261
+ *
1262
+ * @param {string} [message]
1263
+ */
1264
+ function stepFail(message) {
1265
+ var _state$tour2, _el$querySelector;
1266
+ if (!((_state$tour2 = tour) !== null && _state$tour2 !== void 0 && _state$tour2.isActive())) return;
1267
+ const current = tour.getCurrentStep();
1268
+ if (!current) return;
1269
+ const el = current.getElement();
1270
+ el === null || el === void 0 || (_el$querySelector = el.querySelector('.sai-step-error')) === null || _el$querySelector === void 0 || _el$querySelector.remove();
1271
+ if (message) {
1272
+ var _el$querySelector2;
1273
+ const err = document.createElement('div');
1274
+ err.className = 'sai-step-error';
1275
+ err.textContent = '⚠ ' + message;
1276
+ el === null || el === void 0 || (_el$querySelector2 = el.querySelector('.shepherd-text')) === null || _el$querySelector2 === void 0 || _el$querySelector2.appendChild(err);
1277
+ }
1278
+ }
1279
+
1280
+ // Break the navigation.js ↔ chat.js circular dependency:
1281
+ // chat.js needs runTour but can't import tour.js (tour imports chat).
1282
+ // We inject runTour into chat after both modules are loaded.
1283
+ setRunTour(runTour);
1284
+
1285
+ /**
1286
+ * ╔══════════════════════════════════════════════════════════════╗
1287
+ * ║ @eventop/sdk v1.3.0 ║
1288
+ * ║ AI-powered guided tours — themeable, provider-agnostic ║
1289
+ * ║ ║
1290
+ * ║ Provider: always proxy through your own server. ║
1291
+ * ║ Never expose API keys in client-side code. ║
1292
+ * ╚══════════════════════════════════════════════════════════════╝
1293
+ *
1294
+ * Module map
1295
+ * ──────────────────────────────────────────────────────────────
1296
+ * state.js Shared mutable state — single source of truth
1297
+ * theme.js Design tokens + CSS variable builder
1298
+ * positioning.js Corner/offset → CSS position values
1299
+ * providers.js AI provider factory helpers
1300
+ * prompt.js System prompt builder
1301
+ * ai.js Provider request/response + conversation history
1302
+ * navigation.js Route navigation, element waiting, announcements
1303
+ * flow.js Expands feature flow[] into step arrays
1304
+ * tour.js Shepherd.js runner, pause/resume, step helpers
1305
+ * styles.js <style> injection (chat panel + Shepherd overrides)
1306
+ * chat.js Chat panel DOM, messaging, send handler
1307
+ * core.js ← YOU ARE HERE — public API + UMD wrapper
1308
+ */
1309
+
1310
+ (function (global, factory) {
1311
+ const Eventop = factory();
1312
+ if (typeof module === 'object' && module.exports) {
1313
+ module.exports = Eventop;
1314
+ }
1315
+ if (typeof window !== 'undefined') {
1316
+ window.Eventop = Eventop;
1317
+ } else if (typeof global !== 'undefined') {
1318
+ global.Eventop = Eventop;
1319
+ }
1320
+ })(typeof globalThis !== 'undefined' ? globalThis : undefined, function
1321
+ // Dependencies are injected by the bundler (Rollup / esbuild / Vite).
1322
+ // When building for the browser, run: rollup -i core.js -o dist/eventop.umd.js -f umd -n Eventop
1323
+ //
1324
+ // The factory receives nothing — all imports are resolved at bundle time
1325
+ // because static `import` statements are hoisted above the UMD wrapper by
1326
+ // modern bundlers. This file must be processed by a bundler before use in
1327
+ // a plain <script> tag.
1328
+ () {
1329
+
1330
+ // ═══════════════════════════════════════════════════════════════════════════
1331
+ // PUBLIC API
1332
+ // ═══════════════════════════════════════════════════════════════════════════
1333
+ const Eventop = {
1334
+ providers,
1335
+ /**
1336
+ * Initialise the SDK. Must be called once before anything else.
1337
+ *
1338
+ * @param {object} opts
1339
+ * @param {Function} opts.provider — AI provider function
1340
+ * @param {object} opts.config — app config
1341
+ * @param {string} opts.config.appName
1342
+ * @param {Array} opts.config.features
1343
+ * @param {Function} [opts.config.router] — framework navigate fn
1344
+ * @param {object} [opts.config.theme]
1345
+ * @param {object} [opts.config.position]
1346
+ * @param {string[]} [opts.config.suggestions]
1347
+ * @param {string} [opts.config.assistantName]
1348
+ */
1349
+ init(opts = {}) {
1350
+ var _opts$config, _opts$config2;
1351
+ if (!opts.provider) throw new Error('[Eventop] provider is required');
1352
+ if (!((_opts$config = opts.config) !== null && _opts$config !== void 0 && _opts$config.appName)) throw new Error('[Eventop] config.appName is required');
1353
+ if (!((_opts$config2 = opts.config) !== null && _opts$config2 !== void 0 && _opts$config2.features)) throw new Error('[Eventop] config.features is required');
1354
+ setProvider(opts.provider);
1355
+ setConfig(opts.config);
1356
+ setRouter(opts.config.router || null);
1357
+ const theme = resolveTheme(opts.config.theme);
1358
+ const posCSS = resolvePosition(opts.config.position);
1359
+ if (document.readyState === 'loading') {
1360
+ document.addEventListener('DOMContentLoaded', () => buildChat(theme, posCSS));
1361
+ } else {
1362
+ buildChat(theme, posCSS);
1363
+ }
1364
+ ensureShepherd();
1365
+ },
1366
+ /** Programmatically open the chat panel. */
1367
+ open() {
1368
+ if (!isOpen) togglePanel();
1369
+ },
1370
+ /** Programmatically close the chat panel. */
1371
+ close() {
1372
+ if (isOpen) togglePanel();
1373
+ },
1374
+ /** Start a tour directly with a pre-built step array. */
1375
+ runTour,
1376
+ /** Cancel any active or paused tour and clean up completely. */
1377
+ cancelTour() {
1378
+ var _document$getElementB, _document$getElementB2;
1379
+ setPausedSteps(null);
1380
+ setPausedIndex(0);
1381
+ if (tour) {
1382
+ tour.cancel();
1383
+ }
1384
+ runAndClearCleanups();
1385
+ setTour(null);
1386
+ (_document$getElementB = document.getElementById('sai-trigger')) === null || _document$getElementB === void 0 || _document$getElementB.classList.remove('sai-paused');
1387
+ (_document$getElementB2 = document.getElementById('sai-resume-prompt')) === null || _document$getElementB2 === void 0 || _document$getElementB2.remove();
1388
+ document.body.classList.remove('sai-glass-preset');
1389
+ },
1390
+ /** Resume a paused tour from where it was cancelled. */
1391
+ resumeTour() {
1392
+ var _document$getElementB3, _document$getElementB4;
1393
+ if (!pausedSteps) return;
1394
+ const steps = pausedSteps;
1395
+ const idx = pausedIndex;
1396
+ setPausedSteps(null);
1397
+ setPausedIndex(0);
1398
+ (_document$getElementB3 = document.getElementById('sai-resume-prompt')) === null || _document$getElementB3 === void 0 || _document$getElementB3.remove();
1399
+ (_document$getElementB4 = document.getElementById('sai-trigger')) === null || _document$getElementB4 === void 0 || _document$getElementB4.classList.remove('sai-paused');
1400
+ if (isOpen) togglePanel();
1401
+ runTour(steps.slice(idx));
1402
+ },
1403
+ /** @returns {boolean} true if a tour is currently paused */
1404
+ isPaused() {
1405
+ return !!pausedSteps;
1406
+ },
1407
+ /** @returns {boolean} true if a Shepherd tour is actively running */
1408
+ isActive() {
1409
+ var _state$tour;
1410
+ return !!((_state$tour = tour) !== null && _state$tour !== void 0 && _state$tour.isActive());
1411
+ },
1412
+ /**
1413
+ * Advance the active tour step programmatically.
1414
+ * Call this from your own UI when you want to signal step completion.
1415
+ */
1416
+ stepComplete,
1417
+ /**
1418
+ * Inject an error message into the current tour step.
1419
+ * @param {string} message
1420
+ */
1421
+ stepFail,
1422
+ /**
1423
+ * @internal — used by the React package to sync the live feature registry.
1424
+ * @param {object} partial — partial config to merge
1425
+ */
1426
+ _updateConfig(partial) {
1427
+ if (!config) return;
1428
+ setConfig({
1429
+ ...config,
1430
+ ...partial
1431
+ });
1432
+ if (partial.router !== undefined) setRouter(partial.router);
1433
+ }
1434
+ };
1435
+ return Eventop;
1436
+ });