web-agent-bridge 2.3.0 → 2.4.0

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.
Files changed (66) hide show
  1. package/README.ar.md +506 -31
  2. package/README.md +574 -47
  3. package/bin/agent-runner.js +10 -1
  4. package/package.json +12 -4
  5. package/public/agent-workspace.html +347 -0
  6. package/public/browser.html +484 -0
  7. package/public/commander-dashboard.html +243 -0
  8. package/public/css/agent-workspace.css +1713 -0
  9. package/public/css/premium.css +317 -317
  10. package/public/demo.html +259 -259
  11. package/public/index.html +738 -644
  12. package/public/js/agent-workspace.js +1740 -0
  13. package/public/mesh-dashboard.html +309 -382
  14. package/public/premium-dashboard.html +2487 -2487
  15. package/public/premium.html +791 -791
  16. package/public/script/wab.min.js +124 -87
  17. package/script/ai-agent-bridge.js +154 -84
  18. package/sdk/agent-mesh.js +287 -171
  19. package/sdk/commander.js +262 -0
  20. package/sdk/index.d.ts +83 -0
  21. package/sdk/index.js +374 -260
  22. package/sdk/package.json +1 -1
  23. package/server/config/secrets.js +13 -5
  24. package/server/index.js +191 -5
  25. package/server/middleware/adminAuth.js +6 -1
  26. package/server/middleware/auth.js +11 -2
  27. package/server/middleware/rateLimits.js +78 -2
  28. package/server/migrations/002_premium_features.sql +418 -418
  29. package/server/migrations/003_ads_integer_cents.sql +33 -0
  30. package/server/models/db.js +121 -1
  31. package/server/routes/admin-premium.js +671 -671
  32. package/server/routes/admin.js +16 -2
  33. package/server/routes/ads.js +130 -0
  34. package/server/routes/agent-workspace.js +378 -0
  35. package/server/routes/api.js +21 -2
  36. package/server/routes/auth.js +26 -6
  37. package/server/routes/commander.js +316 -0
  38. package/server/routes/mesh.js +370 -201
  39. package/server/routes/premium-v2.js +686 -686
  40. package/server/routes/premium.js +724 -724
  41. package/server/routes/sovereign.js +78 -0
  42. package/server/routes/universal.js +177 -0
  43. package/server/routes/wab-api.js +20 -5
  44. package/server/services/agent-chat.js +506 -0
  45. package/server/services/agent-learning.js +230 -77
  46. package/server/services/agent-memory.js +625 -625
  47. package/server/services/agent-mesh.js +260 -67
  48. package/server/services/agent-symphony.js +553 -517
  49. package/server/services/agent-tasks.js +1807 -0
  50. package/server/services/commander.js +738 -0
  51. package/server/services/edge-compute.js +440 -0
  52. package/server/services/fairness-engine.js +409 -0
  53. package/server/services/local-ai.js +389 -0
  54. package/server/services/plugins.js +771 -747
  55. package/server/services/price-intelligence.js +565 -0
  56. package/server/services/price-shield.js +1137 -0
  57. package/server/services/search-engine.js +357 -0
  58. package/server/services/security.js +513 -0
  59. package/server/services/self-healing.js +843 -843
  60. package/server/services/swarm.js +788 -788
  61. package/server/services/universal-scraper.js +661 -0
  62. package/server/services/vision.js +871 -871
  63. package/server/ws.js +61 -1
  64. package/public/admin/dashboard.html +0 -848
  65. package/public/admin/login.html +0 -84
  66. package/public/video/tutorial.mp4 +0 -0
@@ -0,0 +1,1740 @@
1
+ /**
2
+ * WAB Agent Workspace — Frontend Controller
3
+ * ════════════════════════════════════════════════════════════════════════
4
+ * Manages the 4-panel workspace: Browser, Chat, Monitor, Results
5
+ * Handles auth, subscription, real-time updates, agent communication
6
+ * Full bilingual (AR/EN) with auto-detection and multilingual agent
7
+ */
8
+
9
+ // ─── i18n Dictionary ─────────────────────────────────────────────────
10
+
11
+ const I18N = {
12
+ // Page
13
+ page_title: { ar: 'WAB Agent Workspace — مساحة عمل الوكيل الذكي', en: 'WAB Agent Workspace — Smart Agent Workspace' },
14
+
15
+ // Auth
16
+ auth_welcome: { ar: 'مرحباً بك في WAB', en: 'Welcome to WAB' },
17
+ auth_subtitle: { ar: 'سجّل دخولك للوصول إلى مساحة عمل الوكيل الذكي', en: 'Sign in to access the Smart Agent Workspace' },
18
+ auth_email: { ar: 'البريد الإلكتروني', en: 'Email' },
19
+ auth_email_ph: { ar: 'you@email.com', en: 'you@email.com' },
20
+ auth_password: { ar: 'كلمة المرور', en: 'Password' },
21
+ auth_password_ph: { ar: '••••••••', en: '••••••••' },
22
+ auth_login_btn: { ar: 'تسجيل الدخول', en: 'Sign In' },
23
+ auth_no_account: { ar: 'ليس لديك حساب؟', en: "Don't have an account?" },
24
+ auth_create_account: { ar: 'إنشاء حساب جديد', en: 'Create a new account' },
25
+ auth_register_title: { ar: 'إنشاء حساب جديد', en: 'Create New Account' },
26
+ auth_register_subtitle:{ ar: 'ابدأ مع الوكيل الذكي — ابحث، قارن، وفاوض بذكاء', en: 'Start with the Smart Agent — Search, Compare & Negotiate' },
27
+ auth_name: { ar: 'الاسم', en: 'Name' },
28
+ auth_name_ph: { ar: 'محمد', en: 'John' },
29
+ auth_reg_password_ph: { ar: '6 أحرف على الأقل', en: 'At least 6 characters' },
30
+ auth_register_btn: { ar: 'إنشاء حساب', en: 'Create Account' },
31
+ auth_has_account: { ar: 'لديك حساب بالفعل؟', en: 'Already have an account?' },
32
+ auth_signin_link: { ar: 'تسجيل الدخول', en: 'Sign In' },
33
+ auth_plan_title: { ar: 'اختر خطتك', en: 'Choose Your Plan' },
34
+ auth_demo: { ar: 'تجربة بدون حساب (وضع تجريبي)', en: 'Try without account (Demo Mode)' },
35
+ auth_plan_subtitle: { ar: 'ابدأ مجاناً أو اختر خطة تناسبك', en: 'Start free or pick a plan that fits you' },
36
+ auth_signing_in: { ar: 'جارِ التحقق...', en: 'Signing in...' },
37
+ auth_creating: { ar: 'جارِ الإنشاء...', en: 'Creating...' },
38
+
39
+ // Plans
40
+ plan_free: { ar: 'مجاني', en: 'Free' },
41
+ plan_per_month: { ar: '/شهر', en: '/month' },
42
+ plan_free_f1: { ar: '5 مهام يومياً', en: '5 tasks/day' },
43
+ plan_free_f2: { ar: 'بحث أساسي', en: 'Basic search' },
44
+ plan_free_f3: { ar: 'نتائج محدودة', en: 'Limited results' },
45
+ plan_pro_f1: { ar: 'مهام غير محدودة', en: 'Unlimited tasks' },
46
+ plan_pro_f2: { ar: 'تفاوض متقدم', en: 'Advanced negotiation' },
47
+ plan_pro_f3: { ar: 'وكيل يُتمم الصفقات', en: 'Agent completes deals' },
48
+ plan_pro_f4: { ar: 'أولوية في الدعم', en: 'Priority support' },
49
+ plan_ent_f1: { ar: 'كل ميزات Pro', en: 'All Pro features' },
50
+ plan_ent_f2: { ar: 'API مخصص', en: 'Custom API' },
51
+ plan_ent_f3: { ar: 'فريق متعدد', en: 'Multi-team' },
52
+ plan_ent_f4: { ar: 'دعم مخصص 24/7', en: '24/7 Dedicated support' },
53
+
54
+ // Topbar
55
+ topbar_settings: { ar: 'الإعدادات', en: 'Settings' },
56
+ topbar_logout: { ar: 'خروج', en: 'Logout' },
57
+
58
+ // Panels
59
+ panel_browser: { ar: 'المتصفح', en: 'Browser' },
60
+ panel_agent: { ar: 'الوكيل الذكي', en: 'Smart Agent' },
61
+ panel_monitor: { ar: 'شاشة التفاوض', en: 'Negotiation Monitor' },
62
+ panel_results: { ar: 'النتائج والإجراءات', en: 'Results & Actions' },
63
+
64
+ // Status
65
+ status_ready: { ar: 'جاهز', en: 'Ready' },
66
+ status_connected: { ar: 'متصل', en: 'Connected' },
67
+ status_waiting: { ar: 'في الانتظار', en: 'Waiting' },
68
+ status_awaiting: { ar: 'بانتظار النتائج', en: 'Awaiting Results' },
69
+ status_loading: { ar: 'يحمّل...', en: 'Loading...' },
70
+ status_loaded: { ar: 'محمّل', en: 'Loaded' },
71
+ status_working: { ar: 'يعمل', en: 'Working' },
72
+ status_done: { ar: 'مكتمل', en: 'Done' },
73
+ status_failed: { ar: 'فشل', en: 'Failed' },
74
+
75
+ // Browser
76
+ browser_url_ph: { ar: 'أدخل الرابط أو ابحث...', en: 'Enter a URL or search...' },
77
+ browser_empty: { ar: 'اطلب من الوكيل البحث عن شيء أو أدخل رابطاً في شريط العنوان', en: 'Ask the agent to search or enter a URL in the address bar' },
78
+ browser_refresh: { ar: 'تحديث', en: 'Refresh' },
79
+ browser_back: { ar: 'رجوع', en: 'Back' },
80
+ browser_forward: { ar: 'تقدم', en: 'Forward' },
81
+ panel_maximize: { ar: 'تكبير', en: 'Maximize' },
82
+
83
+ // Chat
84
+ chat_input_ph: { ar: 'اكتب رسالتك هنا... (لا قيود — اكتب بحرية)', en: 'Type your message... (no limits — write freely)' },
85
+ chat_send: { ar: 'إرسال', en: 'Send' },
86
+ chat_new: { ar: 'محادثة جديدة', en: 'New Chat' },
87
+
88
+ // Suggestion chips
89
+ chip_hotels: { ar: '🏨 فنادق تونس', en: '🏨 Tunisia Hotels' },
90
+ chip_hotels_query: { ar: 'ابحث عن فنادق رخيصة في تونس', en: 'Search for cheap hotels in Tunisia' },
91
+ chip_laptop: { ar: '🎮 لابتوب قيمنق', en: '🎮 Gaming Laptop' },
92
+ chip_laptop_query: { ar: 'اشتري لابتوب قيمنق بأقل سعر', en: 'Buy a gaming laptop at the lowest price' },
93
+ chip_iphone: { ar: '📱 iPhone 16', en: '📱 iPhone 16' },
94
+ chip_iphone_query: { ar: 'قارن أسعار iPhone 16 Pro', en: 'Compare iPhone 16 Pro prices' },
95
+ chip_flight: { ar: '✈️ رحلة طيران', en: '✈️ Flight' },
96
+ chip_flight_query: { ar: 'احجز رحلة من تونس إلى إسطنبول', en: 'Book a flight from Tunisia to Istanbul' },
97
+ chip_url_paste: { ar: '🔗 لصق رابط حجز', en: '🔗 Paste Booking Link' },
98
+ chip_url_paste_prompt: { ar: 'الصق رابط الحجز هنا وسأبحث لك عن سعر أفضل...', en: 'Paste your booking link here and I\'ll find you a better price...' },
99
+ chip_security: { ar: '🔒 فحص أمان', en: '🔒 Security Check' },
100
+ chip_security_query: { ar: 'هل هذا الموقع آمن؟', en: 'Is this website safe?' },
101
+
102
+ // Welcome message
103
+ welcome_msg: {
104
+ ar: '🤖 مرحباً! أنا وكيل WAB الذكي — مساعدك الشخصي للبحث والتفاوض والشراء.<br><br>أخبرني ماذا تحتاج:<br>• ✈️ "احجز لي رحلة إلى إسطنبول"<br>• 🏨 "ابحث عن فندق رخيص في تونس"<br>• 🛒 "اشتري لابتوب بأقل سعر"<br>• 🔍 "قارن أسعار iPhone 16"<br><br>اكتب بأي لغة وسأبدأ فوراً! 💪',
105
+ en: '🤖 Hello! I\'m WAB Smart Agent — your personal assistant for searching, negotiating & buying.<br><br>Tell me what you need:<br>• ✈️ "Book me a flight to Istanbul"<br>• 🏨 "Find a cheap hotel in Tunisia"<br>• 🛒 "Buy a gaming laptop at the best price"<br>• 🔍 "Compare iPhone 16 prices"<br><br>Type in any language and I\'ll start right away! 💪'
106
+ },
107
+ welcome_now: { ar: 'الآن', en: 'Now' },
108
+
109
+ // Monitor
110
+ monitor_empty: { ar: 'عندما يبدأ الوكيل بالبحث والتفاوض، ستراقب كل خطوة هنا مباشرة', en: 'When the agent starts searching and negotiating, you\'ll monitor every step here in real-time' },
111
+
112
+ // Results
113
+ results_empty: { ar: 'ستظهر هنا أفضل النتائج والروابط بعد انتهاء الوكيل من البحث والتفاوض', en: 'Best results and links will appear here after the agent finishes searching and negotiating' },
114
+ summary_results: { ar: '🔍 نتائج:', en: '🔍 Results:' },
115
+ summary_best_saving: { ar: '💰 أفضل توفير:', en: '💰 Best Saving:' },
116
+ summary_time: { ar: '⏱️ الوقت:', en: '⏱️ Time:' },
117
+ result_best: { ar: '⭐ الأفضل', en: '⭐ Best' },
118
+ result_savings: { ar: 'توفير', en: 'off' },
119
+ result_save: { ar: 'وفّر', en: 'Save' },
120
+ result_open: { ar: '🔗 فتح الصفقة', en: '🔗 Open Deal' },
121
+ result_agent_do: { ar: '🤖 الوكيل يُتمم', en: '🤖 Agent Do It' },
122
+ result_view: { ar: '🌐 عرض', en: '🌐 View' },
123
+
124
+ // Mobile nav
125
+ nav_browser: { ar: 'المتصفح', en: 'Browser' },
126
+ nav_agent: { ar: 'الوكيل', en: 'Agent' },
127
+ nav_monitor: { ar: 'التفاوض', en: 'Negotiate' },
128
+ nav_results: { ar: 'النتائج', en: 'Results' },
129
+
130
+ // Agent messages
131
+ agent_error: { ar: '⚠️ عذراً، حدث خطأ في الاتصال. حاول مرة أخرى.', en: '⚠️ Connection error. Please try again.' },
132
+ agent_task_started: { ar: '🚀 بدأ الوكيل بتنفيذ المهمة...', en: '🚀 Agent started executing task...' },
133
+ agent_done: { ar: '✅ انتهيت! راجع النتائج في شاشة النتائج ←', en: '✅ Done! Check the Results panel →' },
134
+ agent_new_chat: { ar: '🤖 محادثة جديدة! كيف أساعدك؟', en: '🤖 New chat! How can I help?' },
135
+ agent_found: { ar: 'وجدت', en: 'Found' },
136
+ agent_offers: { ar: 'عروض! الأفضل:', en: 'offers! Best:' },
137
+ agent_pick: { ar: '👆 اختر رقم العرض أو راجع التفاصيل في شاشة النتائج', en: '👆 Pick an offer number or check the Results panel for details' },
138
+ agent_login_required: { ar: '🔑 تسجيل دخول مطلوب', en: '🔑 Login Required' },
139
+ agent_login_site: { ar: 'الموقع {site} يتطلب تسجيل دخول لإتمام العملية. اختر طريقة:', en: '{site} requires login to complete. Choose how:' },
140
+ agent_give_creds: { ar: '🤖 أعطِ الوكيل بياناتي (مشفّر)', en: '🤖 Give agent my credentials (encrypted)' },
141
+ agent_manual_login: { ar: '🌐 سأسجل الدخول بنفسي في المتصفح', en: "🌐 I'll log in myself in the browser" },
142
+ agent_deal_start: { ar: '🤖 الوكيل يبدأ إتمام الصفقة من {source}...', en: '🤖 Agent starting to complete deal from {source}...' },
143
+ agent_deal_login: { ar: '🔑 الموقع {source} يتطلب تسجيل دخول. اختر الطريقة من شاشة النتائج.', en: '🔑 {source} requires login. Choose method from the Results panel.' },
144
+ agent_deal_opened: { ar: '✅ فتحت الصفقة في المتصفح. السعر: ${price}\n\n💡 أكمل الدفع من المتصفح، أو أخبرني إذا تحتاج مساعدة.', en: '✅ Opened the deal in the browser. Price: ${price}\n\n💡 Complete payment in the browser, or tell me if you need help.' },
145
+ agent_creds_request: { ar: '🔑 أرسل لي بيانات تسجيل الدخول (البريد وكلمة المرور) وسأسجّل الدخول بشكل آمن.\n\n🔒 بياناتك مشفّرة ولا تُخزّن.', en: '🔑 Send me the login credentials (email and password) and I\'ll log in securely.\n\n🔒 Your data is encrypted and not stored.' },
146
+ agent_manual_opened: { ar: '🌐 فتحت الموقع في المتصفح. سجّل دخولك ثم أخبرني "جاهز" لأُكمل.', en: '🌐 Opened the site in the browser. Log in and then tell me "ready" to continue.' },
147
+
148
+ // Tips
149
+ tips_title: { ar: '💡 نصائح ذكية', en: '💡 Smart Tips' },
150
+ tip_weekday: { ar: 'جرّب الحجز في أيام الأسبوع — الأسعار أقل عادةً', en: 'Try booking on weekdays — prices are usually lower' },
151
+ tip_agent_do: { ar: 'استخدم زر "الوكيل يُتمم" ليقوم الوكيل بإتمام العملية بدلاً عنك', en: 'Use "Agent Do It" to let the agent complete the purchase' },
152
+ tip_compare: { ar: 'قارن بين العروض جيداً — الأرخص ليس دائماً الأفضل', en: "Compare offers carefully — cheapest isn't always best" },
153
+ tip_login: { ar: 'إذا طلب الموقع تسجيل دخول، يمكنك إعطاء الوكيل إذناً أو تسجيل الدخول يدوياً', en: 'If a site requires login, you can authorize the agent or log in manually' },
154
+
155
+ // Toasts
156
+ toast_welcome: { ar: '🎉 مرحباً بك في WAB!', en: '🎉 Welcome to WAB!' },
157
+ toast_lang_ar: { ar: 'تم التبديل إلى العربية', en: 'Switched to Arabic' },
158
+ toast_lang_en: { ar: 'تم التبديل إلى الإنجليزية', en: 'Switched to English' },
159
+ toast_settings: { ar: 'الإعدادات قريباً', en: 'Settings coming soon' },
160
+ toast_no_results:{ ar: 'لا توجد نتائج', en: 'No results' },
161
+
162
+ // URL Paste Negotiation
163
+ url_paste_detected: { ar: '🔗 اكتشفت رابط حجز! سأحلله وأبحث عن سعر أفضل...', en: '🔗 Booking link detected! Analyzing and searching for better prices...' },
164
+ url_paste_hint: { ar: '💡 الصق رابط حجز لأبحث لك عن سعر أفضل', en: '💡 Paste a booking link and I\'ll find you a better price' },
165
+ url_original_label: { ar: '📌 الرابط الأصلي', en: '📌 Original Link' },
166
+ url_savings_found: { ar: '🎯 وجدت توفير!', en: '🎯 Savings found!' },
167
+ url_no_savings: { ar: 'لم أجد سعراً أفضل حالياً', en: 'No better price found currently' },
168
+
169
+ // Dynamic Pricing Shield
170
+ shield_title: { ar: 'درع التسعير الديناميكي', en: 'Dynamic Pricing Shield' },
171
+ shield_scanning: { ar: '🔍 يفحص الأسعار عبر {count} هوية مختلفة...', en: '🔍 Scanning prices across {count} different identities...' },
172
+ shield_probe_done: { ar: '✓ {persona}: {price}', en: '✓ {persona}: {price}' },
173
+ shield_analyzing: { ar: '🧮 يحلل فروقات الأسعار...', en: '🧮 Analyzing price differences...' },
174
+ shield_clean: { ar: '✅ لم يُكتشف تلاعب بالأسعار — السعر متسق عبر جميع الهويات', en: '✅ No price manipulation detected — price is consistent across all identities' },
175
+ shield_detected: { ar: '⚠️ تم اكتشاف تلاعب بالأسعار!', en: '⚠️ Price manipulation detected!' },
176
+ shield_score: { ar: 'درجة التلاعب: {score}/100 ({level})', en: 'Manipulation score: {score}/100 ({level})' },
177
+ shield_spread: { ar: 'فرق السعر: ${lowest} — ${highest} (فارق {pct}%)', en: 'Price spread: ${lowest} — ${highest} ({pct}% difference)' },
178
+ shield_best_price: { ar: '💰 أفضل سعر: ${price} عبر هوية "{persona}"', en: '💰 Best price: ${price} via "{persona}" identity' },
179
+ shield_savings: { ar: '🎯 توفير محتمل: ${amount} ({pct}%)', en: '🎯 Potential savings: ${amount} ({pct}%)' },
180
+ shield_tip_device: { ar: '📱 استخدم جهاز/متصفح مختلف للحصول على سعر أقل', en: '📱 Switch device/browser for a lower price' },
181
+ shield_tip_cookies: { ar: '🍪 امسح ملفات تعريف الارتباط وسجل التصفح قبل الشراء', en: '🍪 Clear cookies and browsing history before purchasing' },
182
+ shield_tip_geo: { ar: '🌍 استخدم VPN لتظهر من منطقة بأسعار أقل', en: '🌍 Use VPN to appear from a region with cheaper pricing' },
183
+ shield_tip_referral: { ar: '🔗 ادخل عبر موقع مقارنة أسعار للحصول على سعر أقل', en: '🔗 Arrive via a price comparison site for lower pricing' },
184
+ shield_tip_incognito: { ar: '🕵️ استخدم وضع التصفح المتخفي لتجنب رسوم الزيارات المتكررة', en: '🕵️ Use incognito mode to avoid repeat-visitor surcharges' },
185
+ shield_level_none: { ar: 'لا يوجد', en: 'none' },
186
+ shield_level_minor: { ar: 'طفيف', en: 'minor' },
187
+ shield_level_moderate: { ar: 'متوسط', en: 'moderate' },
188
+ shield_level_significant: { ar: 'كبير', en: 'significant' },
189
+ shield_level_severe: { ar: 'خطير', en: 'severe' },
190
+
191
+ // Universal Agent
192
+ chip_uni_analyze: { ar: '🔬 تحليل شامل', en: '🔬 Full Analysis' },
193
+ chip_uni_fairness: { ar: '⚖️ فحص عدالة', en: '⚖️ Fairness Check' },
194
+ chip_uni_compare: { ar: '📊 مقارنة أسعار', en: '📊 Compare Prices' },
195
+ uni_title: { ar: 'تحليل Universal Agent', en: 'Universal Agent Analysis' },
196
+ uni_bridge_installed: { ar: '🌉 WAB Bridge مثبت — أولوية في الترتيب', en: '🌉 WAB Bridge installed — priority ranking' },
197
+ uni_bridge_negotiate: { ar: '🤝 التفاوض متاح', en: '🤝 Negotiation available' },
198
+ uni_bridge_listed: { ar: '📋 مسجل في الدليل', en: '📋 Listed in directory' },
199
+ uni_bridge_none: { ar: '🌐 وضع شامل — يعمل بالاستخراج الذكي', en: '🌐 Universal mode — smart extraction' },
200
+ uni_fairness_label: { ar: '⚖️ درجة العدالة', en: '⚖️ Fairness Score' },
201
+ uni_recommended: { ar: '✅ موصى', en: '✅ Recommended' },
202
+ uni_caution: { ar: '⚠️ حذر', en: '⚠️ Caution' },
203
+ uni_neutral: { ar: '🟡 محايد', en: '🟡 Neutral' },
204
+ uni_products_title: { ar: '🛍️ منتجات مكتشفة', en: '🛍️ Products Found' },
205
+ uni_dark_title: { ar: '🚩 أنماط مظلمة', en: '🚩 Dark Patterns' },
206
+ uni_alerts_title: { ar: '🚨 تحذيرات احتيال', en: '🚨 Fraud Alerts' },
207
+ uni_compare_title: { ar: '📊 مقارنة الأسعار', en: '📊 Price Comparison' },
208
+ uni_analyzing: { ar: '🔬 جارِ التحليل الشامل...', en: '🔬 Running full analysis...' },
209
+ uni_fairness_checking: { ar: '⚖️ جارِ فحص العدالة...', en: '⚖️ Checking fairness...' },
210
+ uni_comparing: { ar: '📊 جارِ مقارنة الأسعار...', en: '📊 Comparing prices...' },
211
+ uni_done: { ar: '✅ اكتمل التحليل! راجع النتائج ←', en: '✅ Analysis complete! Check results →' },
212
+ uni_no_url: { ar: '⚠️ افتح موقعاً أولاً أو أدخل رابطاً في المتصفح', en: '⚠️ Open a site first or enter a URL in the browser' },
213
+ uni_compare_prompt: { ar: 'ما المنتج الذي تريد مقارنة أسعاره؟', en: 'What product would you like to compare prices for?' },
214
+ uni_sources_checked: { ar: 'مصادر تم فحصها', en: 'sources checked' },
215
+ };
216
+
217
+ /** Get translated string */
218
+ function i18n(key, replacements) {
219
+ const entry = I18N[key];
220
+ if (!entry) return key;
221
+ let text = entry[state.lang] || entry.en || key;
222
+ if (replacements) {
223
+ Object.entries(replacements).forEach(([k, v]) => {
224
+ text = text.replace(new RegExp('\\{' + k + '\\}', 'g'), v);
225
+ });
226
+ }
227
+ return text;
228
+ }
229
+
230
+ /** Apply i18n to all data-i18n elements in DOM */
231
+ function applyI18n() {
232
+ document.querySelectorAll('[data-i18n]').forEach(el => {
233
+ const key = el.getAttribute('data-i18n');
234
+ const entry = I18N[key];
235
+ if (entry) {
236
+ if (el.tagName === 'TITLE') {
237
+ document.title = entry[state.lang] || entry.en;
238
+ } else {
239
+ el.textContent = entry[state.lang] || entry.en;
240
+ }
241
+ }
242
+ });
243
+ document.querySelectorAll('[data-i18n-placeholder]').forEach(el => {
244
+ const key = el.getAttribute('data-i18n-placeholder');
245
+ const entry = I18N[key];
246
+ if (entry) el.placeholder = entry[state.lang] || entry.en;
247
+ });
248
+ document.querySelectorAll('[data-i18n-title]').forEach(el => {
249
+ const key = el.getAttribute('data-i18n-title');
250
+ const entry = I18N[key];
251
+ if (entry) el.title = entry[state.lang] || entry.en;
252
+ });
253
+ }
254
+
255
+ // ─── State ───────────────────────────────────────────────────────────
256
+
257
+ const API = window.location.origin;
258
+ let state = {
259
+ token: localStorage.getItem('wab_token') || null,
260
+ user: null,
261
+ sessionId: null,
262
+ currentTask: null,
263
+ lang: localStorage.getItem('wab_lang') || 'en',
264
+ layout: 'grid',
265
+ activeMobilePanel: 0,
266
+ ws: null,
267
+ taskStartTime: null,
268
+ currentOffers: null,
269
+ offlineMode: false,
270
+ };
271
+
272
+ // ─── Chat Archive (localStorage persistence) ────────────────────────
273
+
274
+ const ARCHIVE_KEY = 'wab_chat_archive';
275
+ const ARCHIVE_MAX = 200;
276
+
277
+ function saveArchive() {
278
+ try {
279
+ const container = document.getElementById('chatMessages');
280
+ if (!container) return;
281
+ const msgs = [];
282
+ container.querySelectorAll('.aws-msg').forEach(el => {
283
+ const role = el.classList.contains('user') ? 'user' : el.classList.contains('system') ? 'system' : 'agent';
284
+ msgs.push({ role, html: el.innerHTML, text: el.textContent });
285
+ });
286
+ // Keep only the last ARCHIVE_MAX messages
287
+ const trimmed = msgs.slice(-ARCHIVE_MAX);
288
+ localStorage.setItem(ARCHIVE_KEY, JSON.stringify(trimmed));
289
+ } catch (_) {}
290
+ }
291
+
292
+ function loadArchive() {
293
+ try {
294
+ const raw = localStorage.getItem(ARCHIVE_KEY);
295
+ if (!raw) return false;
296
+ const msgs = JSON.parse(raw);
297
+ if (!Array.isArray(msgs) || msgs.length === 0) return false;
298
+ const container = document.getElementById('chatMessages');
299
+ if (!container) return false;
300
+ container.innerHTML = '';
301
+ msgs.forEach(m => {
302
+ const div = document.createElement('div');
303
+ div.className = `aws-msg ${m.role}`;
304
+ if (m.role === 'system') {
305
+ div.textContent = m.text;
306
+ } else {
307
+ div.innerHTML = m.html;
308
+ }
309
+ container.appendChild(div);
310
+ });
311
+ container.scrollTop = container.scrollHeight;
312
+ return true;
313
+ } catch (_) { return false; }
314
+ }
315
+
316
+ function clearArchive() {
317
+ localStorage.removeItem(ARCHIVE_KEY);
318
+ }
319
+
320
+ // ─── Init ────────────────────────────────────────────────────────────
321
+
322
+ document.addEventListener('DOMContentLoaded', async () => {
323
+ setDirection();
324
+ applyI18n();
325
+
326
+ if (state.token) {
327
+ try {
328
+ const res = await apiFetch('/api/auth/me');
329
+ if (res.ok) {
330
+ const data = await res.json();
331
+ state.user = data.user || data;
332
+ state.sessionId = 'ws-' + Date.now() + '-' + Math.random().toString(36).slice(2, 8);
333
+ showWorkspace();
334
+ connectWebSocket();
335
+ // Load archived chat or inject welcome
336
+ if (!loadArchive()) injectWelcomeMessage();
337
+ return;
338
+ }
339
+ } catch (_) {
340
+ // Server unreachable — enter offline/demo mode
341
+ console.warn('[WAB] Server unreachable, entering offline mode');
342
+ state.offlineMode = true;
343
+ state.user = JSON.parse(localStorage.getItem('wab_user_cache') || 'null');
344
+ if (state.user && state.token) {
345
+ state.sessionId = 'offline-' + Date.now();
346
+ showWorkspace();
347
+ if (!loadArchive()) injectWelcomeMessage();
348
+ return;
349
+ }
350
+ }
351
+ // Only clear token if server explicitly rejected it (not if server is down)
352
+ if (!state.offlineMode) {
353
+ state.token = null;
354
+ localStorage.removeItem('wab_token');
355
+ }
356
+ }
357
+ showAuth();
358
+ });
359
+
360
+ function injectWelcomeMessage() {
361
+ const container = document.getElementById('chatMessages');
362
+ if (!container) return;
363
+ container.innerHTML = '';
364
+ const div = document.createElement('div');
365
+ div.className = 'aws-msg agent';
366
+ div.innerHTML = `${i18n('welcome_msg')}<span class="aws-msg-time">${i18n('welcome_now')}</span>`;
367
+ container.appendChild(div);
368
+ }
369
+
370
+ // ─── Auth ────────────────────────────────────────────────────────────
371
+
372
+ function showAuth() {
373
+ document.getElementById('authOverlay').classList.remove('hidden');
374
+ }
375
+
376
+ function hideAuth() {
377
+ document.getElementById('authOverlay').classList.add('hidden');
378
+ }
379
+
380
+ function showLogin() {
381
+ document.getElementById('authLogin').style.display = '';
382
+ document.getElementById('authRegister').style.display = 'none';
383
+ document.getElementById('authSubscription').style.display = 'none';
384
+ }
385
+
386
+ function showRegister() {
387
+ document.getElementById('authLogin').style.display = 'none';
388
+ document.getElementById('authRegister').style.display = '';
389
+ document.getElementById('authSubscription').style.display = 'none';
390
+ }
391
+
392
+ function showSubscriptions() {
393
+ document.getElementById('authLogin').style.display = 'none';
394
+ document.getElementById('authRegister').style.display = 'none';
395
+ document.getElementById('authSubscription').style.display = '';
396
+ }
397
+
398
+ document.getElementById('loginForm').addEventListener('submit', async (e) => {
399
+ e.preventDefault();
400
+ const email = document.getElementById('loginEmail').value.trim();
401
+ const password = document.getElementById('loginPassword').value;
402
+ const btn = document.getElementById('loginBtn');
403
+ const errEl = document.getElementById('authError');
404
+
405
+ btn.disabled = true;
406
+ btn.textContent = i18n('auth_signing_in');
407
+ errEl.classList.remove('visible');
408
+
409
+ try {
410
+ const res = await fetch(`${API}/api/auth/login`, {
411
+ method: 'POST',
412
+ headers: { 'Content-Type': 'application/json' },
413
+ body: JSON.stringify({ email, password }),
414
+ });
415
+ const data = await res.json();
416
+ if (!res.ok) throw new Error(data.error || 'Login failed');
417
+
418
+ state.token = data.token;
419
+ state.user = data.user || { email, name: email.split('@')[0] };
420
+ localStorage.setItem('wab_token', data.token);
421
+ state.sessionId = 'ws-' + Date.now() + '-' + Math.random().toString(36).slice(2, 8);
422
+ hideAuth();
423
+ showWorkspace();
424
+ connectWebSocket();
425
+ } catch (err) {
426
+ errEl.textContent = err.message;
427
+ errEl.classList.add('visible');
428
+ } finally {
429
+ btn.disabled = false;
430
+ btn.textContent = i18n('auth_login_btn');
431
+ }
432
+ });
433
+
434
+ document.getElementById('registerForm').addEventListener('submit', async (e) => {
435
+ e.preventDefault();
436
+ const name = document.getElementById('regName').value.trim();
437
+ const email = document.getElementById('regEmail').value.trim();
438
+ const password = document.getElementById('regPassword').value;
439
+ const btn = document.getElementById('regBtn');
440
+ const errEl = document.getElementById('regError');
441
+
442
+ btn.disabled = true;
443
+ btn.textContent = i18n('auth_creating');
444
+ errEl.classList.remove('visible');
445
+
446
+ try {
447
+ const res = await fetch(`${API}/api/auth/register`, {
448
+ method: 'POST',
449
+ headers: { 'Content-Type': 'application/json' },
450
+ body: JSON.stringify({ name, email, password }),
451
+ });
452
+ const data = await res.json();
453
+ if (!res.ok) throw new Error(data.error || 'Registration failed');
454
+
455
+ state.token = data.token;
456
+ state.user = data.user || { email, name };
457
+ localStorage.setItem('wab_token', data.token);
458
+ state.sessionId = 'ws-' + Date.now() + '-' + Math.random().toString(36).slice(2, 8);
459
+ showSubscriptions();
460
+ } catch (err) {
461
+ errEl.textContent = err.message;
462
+ errEl.classList.add('visible');
463
+ } finally {
464
+ btn.disabled = false;
465
+ btn.textContent = i18n('auth_register_btn');
466
+ }
467
+ });
468
+
469
+ async function selectPlan(plan) {
470
+ if (plan !== 'free') {
471
+ try {
472
+ await apiFetch('/api/billing/checkout', {
473
+ method: 'POST',
474
+ body: JSON.stringify({ plan }),
475
+ });
476
+ } catch (_) {}
477
+ }
478
+ hideAuth();
479
+ showWorkspace();
480
+ connectWebSocket();
481
+ showToast(i18n('toast_welcome'), 'success');
482
+ }
483
+
484
+ function logout() {
485
+ state.token = null;
486
+ state.user = null;
487
+ localStorage.removeItem('wab_token');
488
+ if (state.ws) state.ws.close();
489
+ location.reload();
490
+ }
491
+
492
+ // ─── Workspace Setup ─────────────────────────────────────────────────
493
+
494
+ function showWorkspace() {
495
+ const user = state.user || {};
496
+ const name = user.name || user.email || 'User';
497
+ document.getElementById('userName').textContent = name;
498
+ document.getElementById('userAvatar').textContent = name.charAt(0).toUpperCase();
499
+
500
+ // Cache user info for offline mode
501
+ try { localStorage.setItem('wab_user_cache', JSON.stringify(user)); } catch (_) {}
502
+
503
+ const tier = user.tier || 'premium';
504
+ const tierEl = document.getElementById('userTier');
505
+ tierEl.textContent = tier.charAt(0).toUpperCase() + tier.slice(1);
506
+ tierEl.className = 'aws-tier-badge ' + (tier === 'pro' ? 'pro' : tier === 'starter' ? 'starter' : 'premium');
507
+
508
+ if (state.offlineMode) {
509
+ showToast(state.lang === 'ar' ? '📡 وضع عدم الاتصال — البيانات محفوظة محلياً' : '📡 Offline mode — data saved locally', 'info');
510
+ }
511
+
512
+ // On mobile, activate the chat panel (index 1) by default
513
+ if (window.innerWidth <= 768) {
514
+ switchMobilePanel(1, document.querySelectorAll('.aws-mobile-nav-item')[1]);
515
+ }
516
+ }
517
+
518
+ // ─── WebSocket ───────────────────────────────────────────────────────
519
+
520
+ function connectWebSocket() {
521
+ try {
522
+ const wsProto = location.protocol === 'https:' ? 'wss:' : 'ws:';
523
+ state.ws = new WebSocket(`${wsProto}//${location.host}/ws/analytics`);
524
+
525
+ state.ws.onopen = () => {
526
+ state.ws.send(JSON.stringify({ type: 'auth', token: state.token }));
527
+ };
528
+
529
+ state.ws.onmessage = (event) => {
530
+ try {
531
+ const data = JSON.parse(event.data);
532
+ handleWsMessage(data);
533
+ } catch (_) {}
534
+ };
535
+
536
+ state.ws.onclose = () => {
537
+ setTimeout(connectWebSocket, 5000);
538
+ };
539
+ } catch (_) {}
540
+ }
541
+
542
+ function handleWsMessage(data) {
543
+ if (data.type === 'task_update') {
544
+ updateMonitorFromWs(data);
545
+ } else if (data.type === 'result') {
546
+ addResultFromWs(data);
547
+ }
548
+ }
549
+
550
+ // ─── Chat ────────────────────────────────────────────────────────────
551
+
552
+ async function sendMessage() {
553
+ const input = document.getElementById('chatInput');
554
+ const message = input.value.trim();
555
+ if (!message) return;
556
+
557
+ // Intercept compare mode
558
+ if (state._nextIsCompare) {
559
+ delete state._nextIsCompare;
560
+ input.value = '';
561
+ autoResize(input);
562
+ universalCompare(message);
563
+ return;
564
+ }
565
+
566
+ input.value = '';
567
+ autoResize(input);
568
+
569
+ addChatMessage('user', message);
570
+ document.getElementById('chatSuggestions').style.display = 'none';
571
+
572
+ // Detect URL paste — show immediate feedback
573
+ const hasUrl = /https?:\/\/[^\s]+/i.test(message);
574
+ if (hasUrl) {
575
+ addChatMessage('system', i18n('url_paste_detected'));
576
+ }
577
+
578
+ showTyping(true);
579
+
580
+ try {
581
+ const body = {
582
+ message,
583
+ context: { url: document.getElementById('urlInput').value, platform: 'workspace', lang: state.lang },
584
+ sessionId: state.sessionId,
585
+ };
586
+
587
+ if (state.currentTask && !hasUrl) {
588
+ body.taskId = state.currentTask.taskId;
589
+ body.taskAction = 'answer';
590
+ }
591
+
592
+ const res = await apiFetch('/api/wab/agent-chat', {
593
+ method: 'POST',
594
+ body: JSON.stringify(body),
595
+ });
596
+
597
+ const data = await res.json();
598
+ showTyping(false);
599
+
600
+ if (data.type === 'task') {
601
+ handleTaskResponse(data);
602
+ } else {
603
+ addChatMessage('agent', data.reply || data.message || 'OK');
604
+ }
605
+ } catch (err) {
606
+ showTyping(false);
607
+ // Offline fallback: generate smart local response
608
+ const fallback = offlineFallbackReply(message);
609
+ addChatMessage('agent', fallback);
610
+
611
+ // If URL detected, try to navigate to it
612
+ if (hasUrl) {
613
+ const urlMatch = message.match(/https?:\/\/[^\s]+/i);
614
+ if (urlMatch) navigateTo(urlMatch[0]);
615
+ }
616
+ }
617
+ }
618
+
619
+ function handleTaskResponse(data) {
620
+ state.currentTask = data;
621
+ state.taskStartTime = state.taskStartTime || Date.now();
622
+
623
+ if (data.status === 'clarifying') {
624
+ addChatMessage('agent', data.message || data.questions?.join('\n'));
625
+ } else if (data.status === 'planning') {
626
+ addChatMessage('agent', data.message);
627
+ addChatMessage('system', i18n('agent_task_started'));
628
+ startMonitor(data);
629
+ executeTask(data.taskId);
630
+ } else if (data.status === 'presenting') {
631
+ // Animate the monitor through all steps before showing results
632
+ startMonitor(data);
633
+ animateMonitorProgress(data);
634
+ addChatMessage('agent', formatChatOffers(data));
635
+ showResults(data);
636
+ // For URL tasks, load original URL in browser; otherwise load first offer
637
+ if (data.urlData?.url) {
638
+ navigateTo(data.urlData.url);
639
+ } else {
640
+ const firstUrl = data.offers?.[0]?.url;
641
+ if (firstUrl) navigateTo(firstUrl);
642
+ }
643
+ // Clear task so user can make new requests
644
+ state.currentTask = null;
645
+ } else if (data.status === 'completed') {
646
+ addChatMessage('agent', data.message);
647
+ if (data.action?.url) {
648
+ navigateTo(data.action.url);
649
+ }
650
+ state.currentTask = null;
651
+ } else if (data.status === 'failed') {
652
+ addChatMessage('agent', data.message);
653
+ updateMonitorFailed();
654
+ state.currentTask = null;
655
+ } else {
656
+ addChatMessage('agent', data.message || JSON.stringify(data));
657
+ }
658
+ }
659
+
660
+ async function executeTask(taskId) {
661
+ let tries = 0;
662
+ const maxTries = 30;
663
+
664
+ const poll = async () => {
665
+ if (tries++ >= maxTries) return;
666
+ try {
667
+ const res = await apiFetch(`/api/wab/agent-task/${taskId}`);
668
+ const data = await res.json();
669
+
670
+ updateMonitorFromTask(data);
671
+
672
+ if (['presenting', 'completed', 'failed', 'cancelled'].includes(data.status)) {
673
+ if (data.status === 'presenting') {
674
+ showResults({ offers: data.offers, updates: data.messages });
675
+ addChatMessage('agent', i18n('agent_done'));
676
+ updateMonitorComplete();
677
+ }
678
+ return;
679
+ }
680
+
681
+ setTimeout(poll, 2000);
682
+ } catch (_) {
683
+ setTimeout(poll, 3000);
684
+ }
685
+ };
686
+
687
+ setTimeout(poll, 2000);
688
+ }
689
+
690
+ function addChatMessage(role, content) {
691
+ const container = document.getElementById('chatMessages');
692
+ const div = document.createElement('div');
693
+ div.className = `aws-msg ${role}`;
694
+
695
+ const time = new Date().toLocaleTimeString(state.lang === 'ar' ? 'ar-SA' : 'en-US', {
696
+ hour: '2-digit', minute: '2-digit'
697
+ });
698
+
699
+ if (role === 'system') {
700
+ div.textContent = content;
701
+ } else {
702
+ const formatted = content
703
+ .replace(/\n/g, '<br>')
704
+ .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
705
+ .replace(/`(.*?)`/g, '<code style="background:rgba(255,255,255,0.1);padding:1px 4px;border-radius:3px;font-size:0.8em">$1</code>');
706
+ div.innerHTML = `${formatted}<span class="aws-msg-time">${time}</span>`;
707
+ }
708
+
709
+ container.appendChild(div);
710
+ container.scrollTop = container.scrollHeight;
711
+ // Auto-save chat archive
712
+ saveArchive();
713
+ }
714
+
715
+ function formatChatOffers(data) {
716
+ const offers = data.offers || [];
717
+ if (offers.length === 0) return data.message || i18n('toast_no_results');
718
+
719
+ let text = `✅ ${i18n('agent_found')} ${offers.length} ${i18n('agent_offers')}\n\n`;
720
+
721
+ offers.forEach((o, idx) => {
722
+ const priceDisplay = o.price || (o.priceNum ? `$${o.priceNum}` : '');
723
+ const savings = o.negotiation?.savings ? ` (${i18n('result_save')} $${o.negotiation.savings})` : '';
724
+ text += `${idx + 1}. ${o.title || o.name} — **${priceDisplay}**${savings}\n 📍 ${o.source}\n\n`;
725
+ });
726
+
727
+ text += i18n('agent_pick');
728
+ return text;
729
+ }
730
+
731
+ function showTyping(show) {
732
+ const el = document.getElementById('typingIndicator');
733
+ el.classList.toggle('visible', show);
734
+ if (show) {
735
+ const container = document.getElementById('chatMessages');
736
+ container.scrollTop = container.scrollHeight;
737
+ }
738
+ }
739
+
740
+ function useSuggestion(text) {
741
+ document.getElementById('chatInput').value = text;
742
+ sendMessage();
743
+ }
744
+
745
+ function promptUrlPaste() {
746
+ const input = document.getElementById('chatInput');
747
+ input.value = '';
748
+ input.placeholder = i18n('chip_url_paste_prompt');
749
+ input.focus();
750
+ // Try reading from clipboard
751
+ if (navigator.clipboard && navigator.clipboard.readText) {
752
+ navigator.clipboard.readText().then(text => {
753
+ if (/https?:\/\/[^\s]+/i.test(text)) {
754
+ input.value = text;
755
+ autoResize(input);
756
+ }
757
+ }).catch(() => { /* clipboard access denied, user will paste manually */ });
758
+ }
759
+ }
760
+
761
+ function clearChat() {
762
+ const container = document.getElementById('chatMessages');
763
+ container.innerHTML = '';
764
+ state.currentTask = null;
765
+ clearArchive();
766
+ addChatMessage('agent', i18n('agent_new_chat'));
767
+ document.getElementById('chatSuggestions').style.display = '';
768
+ }
769
+
770
+ function autoResize(el) {
771
+ el.style.height = 'auto';
772
+ el.style.height = Math.min(el.scrollHeight, 120) + 'px';
773
+ }
774
+
775
+ // ─── Monitor Panel ───────────────────────────────────────────────────
776
+
777
+ function startMonitor(data) {
778
+ document.getElementById('monitorEmpty').style.display = 'none';
779
+ document.getElementById('monitorSteps').style.display = '';
780
+ document.getElementById('monitorStatus').textContent = i18n('status_working');
781
+ document.getElementById('monitorStatus').className = 'aws-panel-status working';
782
+
783
+ const plan = data.plan || [];
784
+ const stepsEl = document.getElementById('progressSteps');
785
+ stepsEl.innerHTML = '';
786
+
787
+ plan.forEach((step, idx) => {
788
+ const desc = state.lang === 'ar' ? step.description_ar : step.description_en;
789
+ const div = document.createElement('div');
790
+ div.className = `aws-progress-step ${idx === 0 ? 'active' : 'pending'}`;
791
+ div.id = `step-${step.id}`;
792
+ div.innerHTML = `
793
+ <div class="aws-step-icon ${idx === 0 ? 'active' : 'pending'}">${idx === 0 ? '⏳' : '○'}</div>
794
+ <span>${desc || step.action}</span>
795
+ `;
796
+ stepsEl.appendChild(div);
797
+ });
798
+ }
799
+
800
+ function updateMonitorFromTask(taskData) {
801
+ const agents = taskData.agents || [];
802
+ const messages = taskData.messages || [];
803
+
804
+ const agentsEl = document.getElementById('monitorAgents');
805
+ agentsEl.innerHTML = '';
806
+
807
+ agents.forEach(agent => {
808
+ const card = document.createElement('div');
809
+ card.className = 'aws-agent-card';
810
+
811
+ const statusDot = agent.status === 'done' ? 'done' :
812
+ agent.status === 'failed' ? 'failed' :
813
+ agent.status === 'negotiating' ? 'negotiating' : 'searching';
814
+
815
+ const foundText = agent.findings?.count
816
+ ? (state.lang === 'ar' ? `وجد ${agent.findings.count} نتيجة` : `Found ${agent.findings.count} results`)
817
+ : '';
818
+
819
+ card.innerHTML = `
820
+ <div class="aws-agent-card-header">
821
+ <div class="aws-agent-name">
822
+ <span class="dot ${statusDot}"></span>
823
+ ${agent.agent_name}
824
+ </div>
825
+ <span style="font-size:0.7rem;color:#64748b">${agent.progress || 0}%</span>
826
+ </div>
827
+ <div class="aws-agent-progress">
828
+ <div class="aws-agent-progress-bar" style="width:${agent.progress || 0}%"></div>
829
+ </div>
830
+ ${foundText ? `<div class="aws-agent-finding">${foundText}</div>` : ''}
831
+ `;
832
+ agentsEl.appendChild(card);
833
+ });
834
+
835
+ const status = taskData.status;
836
+ const stepMap = { searching: 1, comparing: 2, negotiating: 3, presenting: 4 };
837
+ const currentStep = stepMap[status] || 0;
838
+
839
+ document.querySelectorAll('.aws-progress-step').forEach((el, idx) => {
840
+ const stepNum = idx + 1;
841
+ if (stepNum < currentStep) {
842
+ el.className = 'aws-progress-step completed';
843
+ el.querySelector('.aws-step-icon').className = 'aws-step-icon completed';
844
+ el.querySelector('.aws-step-icon').textContent = '✓';
845
+ } else if (stepNum === currentStep) {
846
+ el.className = 'aws-progress-step active';
847
+ el.querySelector('.aws-step-icon').className = 'aws-step-icon active';
848
+ el.querySelector('.aws-step-icon').textContent = '⏳';
849
+ }
850
+ });
851
+
852
+ const negEl = document.getElementById('monitorNegotiations');
853
+ const negLabel = state.lang === 'ar' ? '🤝 تفاوض' : '🤝 Negotiation';
854
+ const updateLabel = state.lang === 'ar' ? '🔍 تحديث' : '🔍 Update';
855
+
856
+ messages.filter(m => m.metadata?.type === 'progress' || m.role === 'agent').forEach(m => {
857
+ if (!document.getElementById(`neg-${m.id}`)) {
858
+ const round = document.createElement('div');
859
+ round.className = 'aws-neg-round';
860
+ round.id = `neg-${m.id}`;
861
+ round.innerHTML = `
862
+ <div class="aws-neg-round-header">
863
+ <span>${m.metadata?.step === 'negotiate' ? negLabel : updateLabel}</span>
864
+ <span>${new Date(m.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}</span>
865
+ </div>
866
+ <div class="aws-neg-round-body">${m.content}</div>
867
+ `;
868
+ negEl.appendChild(round);
869
+ }
870
+ });
871
+ }
872
+
873
+ function updateMonitorFromWs(data) {
874
+ if (data.step) {
875
+ const agentsEl = document.getElementById('monitorAgents');
876
+ const card = document.createElement('div');
877
+ card.className = 'aws-agent-card';
878
+ card.innerHTML = `
879
+ <div class="aws-agent-card-header">
880
+ <div class="aws-agent-name">
881
+ <span class="dot searching"></span>
882
+ ${data.agent || 'Agent'}
883
+ </div>
884
+ </div>
885
+ <div class="aws-agent-progress">
886
+ <div class="aws-agent-progress-bar" style="width:${data.progress || 50}%"></div>
887
+ </div>
888
+ <div class="aws-agent-finding">${data.message || ''}</div>
889
+ `;
890
+ agentsEl.appendChild(card);
891
+ }
892
+ }
893
+
894
+ function updateMonitorComplete() {
895
+ document.getElementById('monitorStatus').textContent = i18n('status_done');
896
+ document.getElementById('monitorStatus').className = 'aws-panel-status active';
897
+
898
+ document.querySelectorAll('.aws-progress-step').forEach(el => {
899
+ el.className = 'aws-progress-step completed';
900
+ const icon = el.querySelector('.aws-step-icon');
901
+ if (icon) {
902
+ icon.className = 'aws-step-icon completed';
903
+ icon.textContent = '✓';
904
+ }
905
+ });
906
+ }
907
+
908
+ /**
909
+ * Animate monitor steps from searching → comparing → negotiating → done
910
+ * Gives the user a visual sense of progress even when the server returns results instantly.
911
+ */
912
+ function animateMonitorProgress(data) {
913
+ const steps = document.querySelectorAll('.aws-progress-step');
914
+ if (steps.length === 0) return;
915
+
916
+ const updates = data.updates || [];
917
+ const agentsEl = document.getElementById('monitorAgents');
918
+ const negEl = document.getElementById('monitorNegotiations');
919
+
920
+ document.getElementById('monitorStatus').textContent = i18n('status_working');
921
+ document.getElementById('monitorStatus').className = 'aws-panel-status working';
922
+
923
+ let delay = 0;
924
+ const stepDelay = 800;
925
+
926
+ steps.forEach((step, idx) => {
927
+ setTimeout(() => {
928
+ // Mark previous steps as completed
929
+ for (let i = 0; i < idx; i++) {
930
+ steps[i].className = 'aws-progress-step completed';
931
+ const icon = steps[i].querySelector('.aws-step-icon');
932
+ if (icon) { icon.className = 'aws-step-icon completed'; icon.textContent = '✓'; }
933
+ }
934
+ // Mark current step as active
935
+ step.className = 'aws-progress-step active';
936
+ const icon = step.querySelector('.aws-step-icon');
937
+ if (icon) { icon.className = 'aws-step-icon active'; icon.textContent = '⏳'; }
938
+
939
+ // Show agent cards during search step
940
+ if (idx === 0 && data.offers) {
941
+ agentsEl.innerHTML = '';
942
+ const sources = [...new Set(data.offers.map(o => o.source))];
943
+ sources.forEach(src => {
944
+ const card = document.createElement('div');
945
+ card.className = 'aws-agent-card';
946
+ card.innerHTML = `
947
+ <div class="aws-agent-card-header">
948
+ <div class="aws-agent-name"><span class="dot searching"></span>${src} Agent</div>
949
+ <span style="font-size:0.7rem;color:#64748b">searching...</span>
950
+ </div>
951
+ <div class="aws-agent-progress"><div class="aws-agent-progress-bar" style="width:50%"></div></div>
952
+ `;
953
+ agentsEl.appendChild(card);
954
+ });
955
+ }
956
+
957
+ // Update agent cards to done during compare step
958
+ if (idx === 1) {
959
+ agentsEl.querySelectorAll('.dot').forEach(d => d.className = 'dot done');
960
+ agentsEl.querySelectorAll('.aws-agent-progress-bar').forEach(b => b.style.width = '100%');
961
+ agentsEl.querySelectorAll('.aws-agent-card-header span:last-child').forEach(s => {
962
+ s.textContent = state.lang === 'ar' ? 'تم' : 'done';
963
+ });
964
+ }
965
+
966
+ // Show negotiation details
967
+ if (idx >= 2 && updates.length > 0) {
968
+ updates.forEach(u => {
969
+ if (u.message && !document.querySelector(`[data-update-msg="${u.step}"]`)) {
970
+ const round = document.createElement('div');
971
+ round.className = 'aws-neg-round';
972
+ round.setAttribute('data-update-msg', u.step || idx);
973
+ round.innerHTML = `
974
+ <div class="aws-neg-round-header"><span>${u.step === 'negotiate' ? '🤝' : '🔍'}</span>
975
+ <span>${new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}</span></div>
976
+ <div class="aws-neg-round-body">${u.message}</div>
977
+ `;
978
+ negEl.appendChild(round);
979
+ }
980
+ });
981
+ }
982
+ }, delay);
983
+ delay += stepDelay;
984
+ });
985
+
986
+ // Final: mark all completed
987
+ setTimeout(() => {
988
+ updateMonitorComplete();
989
+ }, delay + 300);
990
+ }
991
+
992
+ function updateMonitorFailed() {
993
+ document.getElementById('monitorStatus').textContent = i18n('status_failed');
994
+ document.getElementById('monitorStatus').className = 'aws-panel-status idle';
995
+ }
996
+
997
+ // ─── Results Panel ───────────────────────────────────────────────────
998
+
999
+ function showResults(data) {
1000
+ const offers = data.offers || [];
1001
+ if (offers.length === 0) return;
1002
+
1003
+ document.getElementById('resultsEmpty').style.display = 'none';
1004
+ document.getElementById('resultsStatus').textContent = `${offers.length} ${state.lang === 'ar' ? 'نتائج' : 'results'}`;
1005
+ document.getElementById('resultsStatus').className = 'aws-panel-status active';
1006
+
1007
+ const cardsEl = document.getElementById('resultsCards');
1008
+ cardsEl.innerHTML = '';
1009
+
1010
+ offers.forEach((offer, idx) => {
1011
+ const card = document.createElement('div');
1012
+ card.className = `aws-result-card ${idx === 0 ? 'recommended' : ''}`;
1013
+
1014
+ // Normalize price — handle "$95/night", "$285", or numeric values
1015
+ const rawPrice = offer.price || offer.finalPrice || offer.final_price;
1016
+ const priceNum = offer.priceNum || parseFloat(String(rawPrice).replace(/[^\d.]/g, '')) || null;
1017
+ const priceDisplay = rawPrice ? String(rawPrice) : (priceNum ? `$${priceNum}` : '');
1018
+
1019
+ // Calculate savings from negotiation
1020
+ const origPriceNum = offer.negotiation?.originalPrice
1021
+ ? parseFloat(String(offer.negotiation.originalPrice).replace(/[^\d.]/g, ''))
1022
+ : priceNum;
1023
+ const negPrice = offer.negotiation?.negotiatedPrice || priceNum;
1024
+ const savings = origPriceNum && negPrice && origPriceNum > negPrice
1025
+ ? (origPriceNum - negPrice).toFixed(0) : null;
1026
+ const savingsPct = savings && origPriceNum ? Math.round((savings / origPriceNum) * 100) : null;
1027
+
1028
+ // Rating display
1029
+ const rating = offer.rating ? `⭐ ${offer.rating}` : '';
1030
+
1031
+ // Details chips
1032
+ const details = offer.details || [];
1033
+ const detailsHtml = details.length > 0
1034
+ ? `<div class="aws-result-details">${details.map(d => `<span class="aws-result-detail">${d}</span>`).join('')}</div>`
1035
+ : '';
1036
+
1037
+ card.innerHTML = `
1038
+ ${idx === 0 ? `<span class="aws-result-badge best">${i18n('result_best')}</span>` : ''}
1039
+ ${savingsPct && savingsPct > 0 ? `<span class="aws-result-badge savings">${savingsPct}% ${i18n('result_savings')}</span>` : ''}
1040
+
1041
+ <div class="aws-result-title">
1042
+ ${offer.title || offer.name || 'Offer ' + (idx + 1)}
1043
+ <span class="aws-result-source">${offer.source || ''}</span>
1044
+ </div>
1045
+
1046
+ ${rating ? `<div class="aws-result-rating">${rating}</div>` : ''}
1047
+
1048
+ <div class="aws-result-prices">
1049
+ ${savings > 0 ? `<span class="aws-result-original">$${origPriceNum}</span>` : ''}
1050
+ <span class="aws-result-final">${priceDisplay || '—'}</span>
1051
+ ${offer.totalPrice ? `<span class="aws-result-total">(${state.lang === 'ar' ? 'المجموع' : 'total'}: $${offer.totalPrice})</span>` : ''}
1052
+ ${savings > 0 ? `<span class="aws-result-savings-tag">${i18n('result_save')} $${savings}</span>` : ''}
1053
+ </div>
1054
+
1055
+ ${detailsHtml}
1056
+
1057
+ <div class="aws-result-actions">
1058
+ <a href="${sanitizeUrl(offer.url || '#')}" target="_blank" rel="noopener" class="aws-result-btn primary"
1059
+ onclick="trackClick(${idx})">
1060
+ ${i18n('result_open')}
1061
+ </a>
1062
+ <button class="aws-result-btn agent-do" onclick="agentExecuteDeal(${idx})">
1063
+ ${i18n('result_agent_do')}
1064
+ </button>
1065
+ <button class="aws-result-btn secondary" onclick="openInBrowser(${idx})">
1066
+ ${i18n('result_view')}
1067
+ </button>
1068
+ </div>
1069
+ `;
1070
+ cardsEl.appendChild(card);
1071
+ });
1072
+
1073
+ showTips(offers);
1074
+
1075
+ const summaryEl = document.getElementById('resultsSummary');
1076
+ summaryEl.style.display = '';
1077
+ document.getElementById('summaryCount').textContent = offers.length;
1078
+
1079
+ if (offers[0]) {
1080
+ const best = offers[0];
1081
+ const neg = best.negotiation;
1082
+ if (neg && neg.savings) {
1083
+ document.getElementById('summaryBestSaving').textContent = `$${neg.savings}`;
1084
+ } else {
1085
+ document.getElementById('summaryBestSaving').textContent = '-';
1086
+ }
1087
+ }
1088
+
1089
+ if (state.taskStartTime) {
1090
+ const elapsed = Math.round((Date.now() - state.taskStartTime) / 1000);
1091
+ document.getElementById('summaryTime').textContent = `${elapsed}s`;
1092
+ }
1093
+
1094
+ state.currentOffers = offers;
1095
+
1096
+ // On mobile, auto-switch to results panel
1097
+ if (window.innerWidth <= 768) {
1098
+ switchMobilePanel(3, document.querySelectorAll('.aws-mobile-nav-item')[3]);
1099
+ }
1100
+ }
1101
+
1102
+ function showTips(offers) {
1103
+ const tipsArea = document.getElementById('tipsArea');
1104
+ tipsArea.style.display = '';
1105
+
1106
+ const tips = [i18n('tip_weekday'), i18n('tip_agent_do')];
1107
+ if (offers.length > 1) tips.push(i18n('tip_compare'));
1108
+ tips.push(i18n('tip_login'));
1109
+
1110
+ tipsArea.innerHTML = `
1111
+ <div class="aws-tips-section">
1112
+ <h4>${i18n('tips_title')}</h4>
1113
+ ${tips.map(t => `<div class="aws-tip-item">${t}</div>`).join('')}
1114
+ </div>
1115
+ `;
1116
+ }
1117
+
1118
+ function showLoginRequest(site, offerIndex) {
1119
+ const area = document.getElementById('loginRequestArea');
1120
+ area.style.display = '';
1121
+ area.innerHTML = `
1122
+ <div class="aws-login-request">
1123
+ <h4>${i18n('agent_login_required')}</h4>
1124
+ <p>${i18n('agent_login_site', { site })}</p>
1125
+ <div class="aws-login-options">
1126
+ <button class="aws-login-option-btn agent-login" onclick="agentLogin(${offerIndex})">
1127
+ ${i18n('agent_give_creds')}
1128
+ </button>
1129
+ <button class="aws-login-option-btn manual-login" onclick="manualLogin(${offerIndex})">
1130
+ ${i18n('agent_manual_login')}
1131
+ </button>
1132
+ </div>
1133
+ </div>
1134
+ `;
1135
+ }
1136
+
1137
+ // ─── Deal Execution ──────────────────────────────────────────────────
1138
+
1139
+ function trackClick(index) {
1140
+ try {
1141
+ apiFetch('/api/license/track', {
1142
+ method: 'POST',
1143
+ body: JSON.stringify({ action: 'deal_click', index, sessionId: state.sessionId }),
1144
+ });
1145
+ } catch (_) {}
1146
+ }
1147
+
1148
+ async function agentExecuteDeal(index) {
1149
+ const offer = state.currentOffers?.[index];
1150
+ if (!offer) return;
1151
+
1152
+ addChatMessage('system', i18n('agent_deal_start', { source: offer.source }));
1153
+
1154
+ if (offer.requiresLogin) {
1155
+ showLoginRequest(offer.source, index);
1156
+ addChatMessage('agent', i18n('agent_deal_login', { source: offer.source }));
1157
+ return;
1158
+ }
1159
+
1160
+ if (offer.url) navigateTo(offer.url);
1161
+
1162
+ addChatMessage('agent', i18n('agent_deal_opened', { price: offer.finalPrice || offer.price }));
1163
+ }
1164
+
1165
+ function agentLogin(index) {
1166
+ addChatMessage('agent', i18n('agent_creds_request'));
1167
+ state.currentTask = { ...state.currentTask, awaitingLogin: true, offerIndex: index };
1168
+ }
1169
+
1170
+ function manualLogin(index) {
1171
+ const offer = state.currentOffers?.[index];
1172
+ if (offer?.url) {
1173
+ navigateTo(offer.url);
1174
+ addChatMessage('agent', i18n('agent_manual_opened'));
1175
+ }
1176
+ }
1177
+
1178
+ function openInBrowser(index) {
1179
+ const offer = state.currentOffers?.[index];
1180
+ if (offer?.url) navigateTo(offer.url);
1181
+ }
1182
+
1183
+ // ─── Browser Panel ───────────────────────────────────────────────────
1184
+
1185
+ function navigateTo(url) {
1186
+ if (!url) return;
1187
+ if (!url.startsWith('http://') && !url.startsWith('https://')) {
1188
+ url = `https://www.google.com/search?q=${encodeURIComponent(url)}`;
1189
+ }
1190
+
1191
+ const urlInput = document.getElementById('urlInput');
1192
+ const frame = document.getElementById('browserFrame');
1193
+ const empty = document.getElementById('browserEmpty');
1194
+
1195
+ urlInput.value = url;
1196
+ empty.style.display = 'none';
1197
+ frame.style.display = '';
1198
+ frame.src = url;
1199
+
1200
+ document.getElementById('browserStatus').textContent = i18n('status_loading');
1201
+ document.getElementById('browserStatus').className = 'aws-panel-status working';
1202
+
1203
+ frame.onload = () => {
1204
+ document.getElementById('browserStatus').textContent = i18n('status_loaded');
1205
+ document.getElementById('browserStatus').className = 'aws-panel-status active';
1206
+ updateUrlLock(url);
1207
+ };
1208
+ }
1209
+
1210
+ function updateUrlLock(url) {
1211
+ const lock = document.getElementById('urlLock');
1212
+ lock.textContent = url.startsWith('https://') ? '🔒' : '⚠️';
1213
+ lock.style.color = url.startsWith('https://') ? '#10b981' : '#f59e0b';
1214
+ }
1215
+
1216
+ function browserBack() {
1217
+ const frame = document.getElementById('browserFrame');
1218
+ try { frame.contentWindow.history.back(); } catch (_) {}
1219
+ }
1220
+
1221
+ function browserForward() {
1222
+ const frame = document.getElementById('browserFrame');
1223
+ try { frame.contentWindow.history.forward(); } catch (_) {}
1224
+ }
1225
+
1226
+ function refreshBrowser() {
1227
+ const frame = document.getElementById('browserFrame');
1228
+ try { frame.contentWindow.location.reload(); } catch (_) {
1229
+ if (frame.src) frame.src = frame.src;
1230
+ }
1231
+ }
1232
+
1233
+ // ─── Layout ──────────────────────────────────────────────────────────
1234
+
1235
+ function setLayout(layout) {
1236
+ state.layout = layout;
1237
+ const ws = document.getElementById('workspace');
1238
+ ws.className = 'aws-workspace';
1239
+ if (layout !== 'grid') ws.classList.add(`layout-${layout}`);
1240
+
1241
+ document.querySelectorAll('.aws-layout-btn').forEach(btn => btn.classList.remove('active'));
1242
+ event.target.classList.add('active');
1243
+ }
1244
+
1245
+ function maximizePanel(panelId) {
1246
+ const panel = document.getElementById(panelId);
1247
+ if (panel.style.gridColumn === '1 / -1') {
1248
+ panel.style.gridColumn = '';
1249
+ panel.style.gridRow = '';
1250
+ document.querySelectorAll('.aws-panel').forEach(p => p.style.display = '');
1251
+ } else {
1252
+ document.querySelectorAll('.aws-panel').forEach(p => {
1253
+ if (p.id !== panelId) p.style.display = 'none';
1254
+ });
1255
+ panel.style.gridColumn = '1 / -1';
1256
+ panel.style.gridRow = '1 / -1';
1257
+ }
1258
+ }
1259
+
1260
+ // ─── Mobile ──────────────────────────────────────────────────────────
1261
+
1262
+ function switchMobilePanel(index, btn) {
1263
+ state.activeMobilePanel = index;
1264
+ const panels = document.querySelectorAll('.aws-panel');
1265
+ panels.forEach((p, idx) => p.classList.toggle('active-mobile', idx === index));
1266
+
1267
+ document.querySelectorAll('.aws-mobile-nav-item').forEach(b => b.classList.remove('active'));
1268
+ if (btn) btn.classList.add('active');
1269
+ }
1270
+
1271
+ function toggleMobileMenu() {
1272
+ const nav = document.getElementById('mobileNav');
1273
+ nav.style.display = nav.style.display === 'flex' ? 'none' : 'flex';
1274
+ }
1275
+
1276
+ // ─── Language ────────────────────────────────────────────────────────
1277
+
1278
+ function toggleLang() {
1279
+ state.lang = state.lang === 'ar' ? 'en' : 'ar';
1280
+ localStorage.setItem('wab_lang', state.lang);
1281
+ setDirection();
1282
+ applyI18n();
1283
+ injectWelcomeMessage();
1284
+ showToast(state.lang === 'ar' ? i18n('toast_lang_ar') : i18n('toast_lang_en'), 'info');
1285
+ }
1286
+
1287
+ function setDirection() {
1288
+ const body = document.querySelector('.aws-body');
1289
+ const html = document.documentElement;
1290
+ if (state.lang === 'ar') {
1291
+ body.setAttribute('dir', 'rtl');
1292
+ html.setAttribute('dir', 'rtl');
1293
+ html.setAttribute('lang', 'ar');
1294
+ } else {
1295
+ body.setAttribute('dir', 'ltr');
1296
+ html.setAttribute('dir', 'ltr');
1297
+ html.setAttribute('lang', 'en');
1298
+ }
1299
+ }
1300
+
1301
+ // ─── Settings ────────────────────────────────────────────────────────
1302
+
1303
+ function toggleSettings() {
1304
+ showToast(i18n('toast_settings'), 'info');
1305
+ }
1306
+
1307
+ // ─── Toast ───────────────────────────────────────────────────────────
1308
+
1309
+ function showToast(message, type = 'info') {
1310
+ const toast = document.getElementById('toast');
1311
+ toast.textContent = message;
1312
+ toast.className = `aws-toast ${type} visible`;
1313
+ setTimeout(() => toast.classList.remove('visible'), 3500);
1314
+ }
1315
+
1316
+ // ─── API Helper ──────────────────────────────────────────────────────
1317
+
1318
+ function apiFetch(path, options = {}) {
1319
+ const headers = { 'Content-Type': 'application/json', ...options.headers };
1320
+ if (state.token) headers['Authorization'] = `Bearer ${state.token}`;
1321
+ return fetch(`${API}${path}`, { ...options, headers });
1322
+ }
1323
+
1324
+ // ─── Security ────────────────────────────────────────────────────────
1325
+
1326
+ function sanitizeUrl(url) {
1327
+ if (!url) return '#';
1328
+ try {
1329
+ const parsed = new URL(url);
1330
+ if (!['http:', 'https:'].includes(parsed.protocol)) return '#';
1331
+ return parsed.href;
1332
+ } catch (_) {
1333
+ return '#';
1334
+ }
1335
+ }
1336
+
1337
+ // ─── Offline Fallback Agent ──────────────────────────────────────────
1338
+
1339
+ function offlineFallbackReply(message) {
1340
+ const msg = message.toLowerCase();
1341
+ const isAr = /[\u0600-\u06FF]/.test(message);
1342
+
1343
+ // URL detection: open in browser panel
1344
+ const urlMatch = message.match(/https?:\/\/[^\s]+/i);
1345
+ if (urlMatch) {
1346
+ return isAr
1347
+ ? `🔗 فتحت الرابط في المتصفح.\n\n📡 الوكيل غير متصل حالياً بالخادم. يمكنك تصفح الصفحة مباشرة من لوحة المتصفح.`
1348
+ : `🔗 Opened the link in the browser.\n\n📡 Agent is currently offline. You can browse the page directly from the Browser panel.`;
1349
+ }
1350
+
1351
+ // Search/booking requests
1352
+ if (/ابحث|بحث|فندق|فنادق|رحل|طيران|حجز|احجز|hotel|flight|book|search|find/i.test(msg)) {
1353
+ const query = message.replace(/ابحث عن|ابحث|بحث عن|search for|find|look for/gi, '').trim();
1354
+ if (query.length > 2) {
1355
+ navigateTo(`https://www.google.com/search?q=${encodeURIComponent(query)}`);
1356
+ }
1357
+ return isAr
1358
+ ? `🔍 بحثت لك عن "${query}" — النتائج تظهر في لوحة المتصفح.\n\n📡 حالياً أعمل في الوضع المحلي. عند اتصال الخادم، سأتفاوض وأقارن الأسعار تلقائياً.`
1359
+ : `🔍 Searched for "${query}" — results shown in the Browser panel.\n\n📡 Currently in offline mode. When the server connects, I'll auto-negotiate and compare prices.`;
1360
+ }
1361
+
1362
+ // Shopping requests
1363
+ if (/اشتري|شراء|سعر|أسعار|مقارن|لابتوب|laptop|buy|price|compare|iphone|shop/i.test(msg)) {
1364
+ const query = message.replace(/اشتري|شراء|buy|compare prices|قارن أسعار/gi, '').trim();
1365
+ if (query.length > 2) {
1366
+ navigateTo(`https://www.google.com/search?q=${encodeURIComponent(query + ' price')}`);
1367
+ }
1368
+ return isAr
1369
+ ? `🛒 أبحث عن أسعار "${query}" — راجع المتصفح.\n\n💡 نصيحة: عند الاتصال بالخادم، سأقارن الأسعار من عدة مصادر وأوجد لك أفضل صفقة.`
1370
+ : `🛒 Searching prices for "${query}" — check the Browser panel.\n\n💡 Tip: When connected to the server, I'll compare prices from multiple sources to find the best deal.`;
1371
+ }
1372
+
1373
+ // Security check
1374
+ if (/أمان|آمن|safe|security|scam|احتيال/i.test(msg)) {
1375
+ return isAr
1376
+ ? `🔒 لفحص أمان موقع، الصق الرابط هنا وسأحلله عند اتصال الخادم.\n\n💡 تأكد دائماً من وجود 🔒 في شريط العنوان (HTTPS).`
1377
+ : `🔒 To check a site's security, paste the link here and I'll analyze it when the server connects.\n\n💡 Always look for 🔒 in the address bar (HTTPS).`;
1378
+ }
1379
+
1380
+ // General greeting/help
1381
+ if (/مرحب|هلا|سلام|أهلا|hi|hello|hey|help|مساعد/i.test(msg)) {
1382
+ return isAr
1383
+ ? `🤖 أهلاً! أنا وكيل WAB الذكي. يمكنني مساعدتك في:\n\n• 🔍 البحث عن أي شيء\n• ✈️ حجز رحلات وفنادق\n• 🛒 مقارنة الأسعار\n• 🔒 فحص أمان المواقع\n\nاكتب ما تحتاجه بأي لغة!`
1384
+ : `🤖 Hello! I'm WAB Smart Agent. I can help with:\n\n• 🔍 Searching for anything\n• ✈️ Booking flights & hotels\n• 🛒 Comparing prices\n• 🔒 Security checks\n\nType what you need in any language!`;
1385
+ }
1386
+
1387
+ // Navigate if it looks like a search
1388
+ if (msg.length > 3) {
1389
+ navigateTo(`https://www.google.com/search?q=${encodeURIComponent(message)}`);
1390
+ return isAr
1391
+ ? `🔍 بحثت عن "${message}" — راجع النتائج في لوحة المتصفح.\n\n📡 عند اتصال الخادم، سأقدم نتائج أذكى مع تفاوض ومقارنة.`
1392
+ : `🔍 Searched for "${message}" — check results in the Browser panel.\n\n📡 When the server connects, I'll provide smarter results with negotiation and comparison.`;
1393
+ }
1394
+
1395
+ return isAr
1396
+ ? `🤖 أنا هنا لمساعدتك! اكتب ما تريد البحث عنه أو الصق رابطاً.`
1397
+ : `🤖 I'm here to help! Type what you want to search for or paste a link.`;
1398
+ }
1399
+
1400
+ // ─── Dynamic Pricing Shield UI ───────────────────────────────────────
1401
+
1402
+ /**
1403
+ * Show the Price Shield scanning overlay in the monitor panel.
1404
+ * Call this when the agent starts a multi-identity price scan.
1405
+ */
1406
+ function showPriceShield(scanData) {
1407
+ const section = document.getElementById('priceShieldSection');
1408
+ const statusEl = document.getElementById('shieldStatus');
1409
+ const probesEl = document.getElementById('shieldProbes');
1410
+ const resultEl = document.getElementById('shieldResult');
1411
+ const badgeEl = document.getElementById('shieldBadge');
1412
+ if (!section) return;
1413
+
1414
+ section.style.display = 'block';
1415
+ badgeEl.textContent = '';
1416
+ badgeEl.className = 'aws-shield-badge';
1417
+ resultEl.innerHTML = '';
1418
+
1419
+ const personaCount = scanData?.personas?.length || 12;
1420
+ statusEl.innerHTML = `<div class="aws-shield-scanning">${i18n('shield_scanning', { count: personaCount })}</div>`;
1421
+ probesEl.innerHTML = '';
1422
+
1423
+ // Scroll monitor into view
1424
+ document.getElementById('monitorEmpty')?.style && (document.getElementById('monitorEmpty').style.display = 'none');
1425
+ }
1426
+
1427
+ /**
1428
+ * Update a single probe result as it comes in.
1429
+ */
1430
+ function updateShieldProbe(personaLabel, price, currency = 'USD') {
1431
+ const probesEl = document.getElementById('shieldProbes');
1432
+ if (!probesEl) return;
1433
+
1434
+ const div = document.createElement('div');
1435
+ div.className = 'aws-shield-probe-item';
1436
+ const priceStr = price != null ? `${currency === 'USD' ? '$' : currency}${price}` : '—';
1437
+ div.textContent = i18n('shield_probe_done', { persona: personaLabel, price: priceStr });
1438
+ probesEl.appendChild(div);
1439
+ }
1440
+
1441
+ /**
1442
+ * Show the final Price Shield analysis result.
1443
+ */
1444
+ function showShieldResult(analysis) {
1445
+ const statusEl = document.getElementById('shieldStatus');
1446
+ const resultEl = document.getElementById('shieldResult');
1447
+ const badgeEl = document.getElementById('shieldBadge');
1448
+ if (!resultEl) return;
1449
+
1450
+ statusEl.innerHTML = '';
1451
+
1452
+ if (!analysis || !analysis.manipulation || !analysis.manipulation.detected) {
1453
+ badgeEl.textContent = '✅';
1454
+ badgeEl.className = 'aws-shield-badge shield-clean';
1455
+ resultEl.innerHTML = `<div class="aws-shield-clean">${i18n('shield_clean')}</div>`;
1456
+ return;
1457
+ }
1458
+
1459
+ const m = analysis.manipulation;
1460
+ const p = analysis.prices;
1461
+ const r = analysis.recommendation;
1462
+
1463
+ const levelKey = `shield_level_${m.level || 'none'}`;
1464
+ const levelText = I18N[levelKey] ? i18n(levelKey) : m.level;
1465
+
1466
+ // Badge
1467
+ const badgeClass = m.score >= 70 ? 'shield-severe' : m.score >= 45 ? 'shield-significant' : m.score >= 20 ? 'shield-moderate' : 'shield-minor';
1468
+ badgeEl.textContent = `${m.score}/100`;
1469
+ badgeEl.className = `aws-shield-badge ${badgeClass}`;
1470
+
1471
+ let html = `<div class="aws-shield-alert">
1472
+ <div class="aws-shield-alert-title">${i18n('shield_detected')}</div>
1473
+ <div class="aws-shield-score">${i18n('shield_score', { score: m.score, level: levelText })}</div>
1474
+ <div class="aws-shield-spread">${i18n('shield_spread', { lowest: p.lowest, highest: p.highest, pct: p.spreadPct })}</div>`;
1475
+
1476
+ if (r && r.bestPrice) {
1477
+ html += `<div class="aws-shield-best">${i18n('shield_best_price', { price: r.bestPrice, persona: r.bestPersonaLabel || r.bestPersona })}</div>`;
1478
+ if (r.savings > 0) {
1479
+ html += `<div class="aws-shield-savings">${i18n('shield_savings', { amount: r.savings.toFixed(2), pct: r.savingsPct })}</div>`;
1480
+ }
1481
+ }
1482
+
1483
+ // Tips from strategy
1484
+ if (r && r.strategy && r.strategy.tips && r.strategy.tips.length > 0) {
1485
+ html += `<div class="aws-shield-tips">`;
1486
+ for (const tip of r.strategy.tips) {
1487
+ html += `<div class="aws-shield-tip">💡 ${escapeHtml(tip)}</div>`;
1488
+ }
1489
+ html += `</div>`;
1490
+ }
1491
+
1492
+ // Manipulation types
1493
+ if (analysis.manipulations && analysis.manipulations.length > 0) {
1494
+ html += `<div class="aws-shield-types">`;
1495
+ for (const manip of analysis.manipulations) {
1496
+ const severityClass = `severity-${manip.severity}`;
1497
+ html += `<div class="aws-shield-type-item ${severityClass}">
1498
+ <span class="aws-shield-type-label">${escapeHtml(manip.type.replace(/_/g, ' '))}</span>
1499
+ <span class="aws-shield-type-severity">${manip.severity}</span>
1500
+ </div>`;
1501
+ }
1502
+ html += `</div>`;
1503
+ }
1504
+
1505
+ // Probe comparison table
1506
+ if (analysis.probes && analysis.probes.length > 0) {
1507
+ html += `<div class="aws-shield-probes-table"><table>
1508
+ <tr><th>${state.lang === 'ar' ? 'الهوية' : 'Identity'}</th><th>${state.lang === 'ar' ? 'السعر' : 'Price'}</th></tr>`;
1509
+ const sortedProbes = [...analysis.probes].sort((a, b) => (a.price || 999999) - (b.price || 999999));
1510
+ for (const probe of sortedProbes) {
1511
+ const isBest = probe.price === p.lowest;
1512
+ const isWorst = probe.price === p.highest;
1513
+ const cls = isBest ? 'probe-best' : isWorst ? 'probe-worst' : '';
1514
+ html += `<tr class="${cls}">
1515
+ <td>${escapeHtml(probe.label)}</td>
1516
+ <td>${probe.price != null ? '$' + probe.price : '—'}${isBest ? ' ⭐' : ''}${isWorst ? ' ⚠️' : ''}</td>
1517
+ </tr>`;
1518
+ }
1519
+ html += `</table></div>`;
1520
+ }
1521
+
1522
+ html += `</div>`;
1523
+ resultEl.innerHTML = html;
1524
+ }
1525
+
1526
+ function escapeHtml(str) {
1527
+ if (!str) return '';
1528
+ return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
1529
+ }
1530
+
1531
+ // ══════════════════════════════════════════════════════════════
1532
+ // Universal Agent — Full Analysis, Fairness, Comparison
1533
+ // ══════════════════════════════════════════════════════════════
1534
+
1535
+ function _getWorkspaceUrl() {
1536
+ const input = document.getElementById('urlInput');
1537
+ const frame = document.getElementById('browserFrame');
1538
+ return (input && input.value) || (frame && frame.src && frame.src !== 'about:blank' ? frame.src : '') || '';
1539
+ }
1540
+
1541
+ function universalAnalyzePage() {
1542
+ const url = _getWorkspaceUrl();
1543
+ if (!url || url === 'about:blank') {
1544
+ addChatMessage('agent', i18n('uni_no_url'));
1545
+ return;
1546
+ }
1547
+ addChatMessage('user', `🔬 ${i18n('chip_uni_analyze')}: ${url}`);
1548
+ addChatMessage('agent', i18n('uni_analyzing'));
1549
+ document.getElementById('universalSection').style.display = '';
1550
+
1551
+ apiFetch('/api/universal/analyze', {
1552
+ method: 'POST',
1553
+ headers: { 'Content-Type': 'application/json' },
1554
+ body: JSON.stringify({ url })
1555
+ }).then(data => {
1556
+ renderUniversalWs(data, url);
1557
+ addChatMessage('agent', i18n('uni_done'));
1558
+ switchMobilePanel(3); // show results panel on mobile
1559
+ }).catch(err => {
1560
+ addChatMessage('agent', `⚠️ ${err.message || 'Analysis failed'}`);
1561
+ });
1562
+ }
1563
+
1564
+ function universalFairnessCheck() {
1565
+ const url = _getWorkspaceUrl();
1566
+ if (!url || url === 'about:blank') {
1567
+ addChatMessage('agent', i18n('uni_no_url'));
1568
+ return;
1569
+ }
1570
+ let domain;
1571
+ try { domain = new URL(url.startsWith('http') ? url : 'https://' + url).hostname.replace(/^www\./, ''); } catch(_) { domain = url; }
1572
+ addChatMessage('user', `⚖️ ${i18n('chip_uni_fairness')}: ${domain}`);
1573
+ addChatMessage('agent', i18n('uni_fairness_checking'));
1574
+ document.getElementById('universalSection').style.display = '';
1575
+
1576
+ apiFetch('/api/universal/fairness', {
1577
+ method: 'POST',
1578
+ headers: { 'Content-Type': 'application/json' },
1579
+ body: JSON.stringify({ domain })
1580
+ }).then(data => {
1581
+ renderFairnessWs(data);
1582
+ addChatMessage('agent', i18n('uni_done'));
1583
+ }).catch(err => {
1584
+ addChatMessage('agent', `⚠️ ${err.message || 'Fairness check failed'}`);
1585
+ });
1586
+ }
1587
+
1588
+ function universalComparePrompt() {
1589
+ const chatInput = document.getElementById('chatInput');
1590
+ chatInput.value = i18n('uni_compare_prompt');
1591
+ chatInput.focus();
1592
+ chatInput.select();
1593
+ // Override next send to route to compare
1594
+ state._nextIsCompare = true;
1595
+ }
1596
+
1597
+ // Hook into sendMessage to check for compare mode
1598
+ const _origSendMessage = typeof sendMessage === 'function' ? sendMessage : null;
1599
+
1600
+ function universalCompare(query) {
1601
+ addChatMessage('user', `📊 ${i18n('chip_uni_compare')}: ${query}`);
1602
+ addChatMessage('agent', i18n('uni_comparing'));
1603
+ document.getElementById('universalSection').style.display = '';
1604
+
1605
+ apiFetch('/api/universal/deals', {
1606
+ method: 'POST',
1607
+ headers: { 'Content-Type': 'application/json' },
1608
+ body: JSON.stringify({ query, category: 'product', lang: state.lang })
1609
+ }).then(data => {
1610
+ renderCompareWs(data);
1611
+ addChatMessage('agent', i18n('uni_done'));
1612
+ switchMobilePanel(3);
1613
+ }).catch(err => {
1614
+ addChatMessage('agent', `⚠️ ${err.message || 'Comparison failed'}`);
1615
+ });
1616
+ }
1617
+
1618
+ function closeUniversalSection() {
1619
+ document.getElementById('universalSection').style.display = 'none';
1620
+ }
1621
+
1622
+ // ──── Rendering ────
1623
+
1624
+ function renderUniversalWs(data, url) {
1625
+ let domain;
1626
+ try { domain = new URL(url.startsWith('http') ? url : 'https://' + url).hostname.replace(/^www\./, ''); } catch(_) { domain = url; }
1627
+
1628
+ // Bridge
1629
+ const bridge = data.fairness?.wabBridge || { installed: false };
1630
+ const bridgeEl = document.getElementById('uniBridgeWs');
1631
+ if (bridge.installed) {
1632
+ bridgeEl.innerHTML = `
1633
+ <div class="aws-uni-badge bridge">🌉 ${i18n('uni_bridge_installed')}</div>
1634
+ ${bridge.hasNegotiation ? `<div class="aws-uni-badge negotiate">${i18n('uni_bridge_negotiate')}</div>` : ''}
1635
+ ${bridge.isListed ? `<div class="aws-uni-badge listed">${i18n('uni_bridge_listed')}</div>` : ''}`;
1636
+ } else {
1637
+ bridgeEl.innerHTML = `<div class="aws-uni-badge neutral">${i18n('uni_bridge_none')}</div>`;
1638
+ }
1639
+
1640
+ // Fairness
1641
+ if (data.fairness) renderFairnessWs(data.fairness);
1642
+
1643
+ // Products
1644
+ const products = data.products || [];
1645
+ const productsEl = document.getElementById('uniProductsWs');
1646
+ if (products.length > 0) {
1647
+ productsEl.style.display = '';
1648
+ productsEl.innerHTML = `<h4>${i18n('uni_products_title')}</h4>` + products.slice(0, 8).map(p => `
1649
+ <div class="aws-uni-product">
1650
+ <span class="aws-uni-product-name">${escapeHtml(String(p.name || '').slice(0, 100))}</span>
1651
+ <span class="aws-uni-product-details">
1652
+ ${p.price ? `<strong>${p.currency || '$'}${p.price}</strong>` : ''}
1653
+ ${p.originalPrice ? `<s>${p.currency || '$'}${p.originalPrice}</s>` : ''}
1654
+ ${p.rating ? `⭐ ${p.rating}` : ''}
1655
+ </span>
1656
+ </div>
1657
+ `).join('');
1658
+ }
1659
+
1660
+ // Dark Patterns
1661
+ const darkPatterns = data.darkPatterns || [];
1662
+ const darkEl = document.getElementById('uniDarkWs');
1663
+ if (darkPatterns.length > 0) {
1664
+ darkEl.style.display = '';
1665
+ darkEl.innerHTML = `<h4>${i18n('uni_dark_title')}</h4>` + darkPatterns.map(dp => `
1666
+ <div class="aws-uni-dark-item ${dp.severity || 'low'}">
1667
+ 🚩 ${escapeHtml(dp.type || dp.name || '')} ${dp.matches ? '— ' + dp.matches.slice(0, 3).map(m => escapeHtml(m)).join(', ') : ''}
1668
+ </div>
1669
+ `).join('');
1670
+ }
1671
+
1672
+ // Alerts
1673
+ const alerts = data.alerts || [];
1674
+ const alertsEl = document.getElementById('uniAlertsWs');
1675
+ if (alerts.length > 0) {
1676
+ alertsEl.style.display = '';
1677
+ alertsEl.innerHTML = `<h4>${i18n('uni_alerts_title')}</h4>` + alerts.map(a => `
1678
+ <div class="aws-uni-alert-item ${a.severity || 'medium'}">
1679
+ ${a.severity === 'high' ? '🚨' : '⚠️'} <strong>${escapeHtml(a.title || '')}</strong> — ${escapeHtml(a.description || '')}
1680
+ </div>
1681
+ `).join('');
1682
+ }
1683
+ }
1684
+
1685
+ function renderFairnessWs(f) {
1686
+ const el = document.getElementById('uniFairnessWs');
1687
+ if (!f || !f.total) { el.innerHTML = ''; return; }
1688
+ const barColor = f.total >= 70 ? '#22c55e' : f.total >= 45 ? '#eab308' : '#ef4444';
1689
+ const catKey = f.category === 'recommended' ? 'uni_recommended' : f.category === 'caution' ? 'uni_caution' : 'uni_neutral';
1690
+ el.innerHTML = `
1691
+ <h4>${i18n('uni_fairness_label')}</h4>
1692
+ <div class="aws-uni-score-bar"><div class="aws-uni-score-fill" style="width:${f.total}%;background:${barColor}"></div></div>
1693
+ <div class="aws-uni-score-row">
1694
+ <span class="aws-uni-score-val">${f.total}/100</span>
1695
+ <span class="aws-uni-score-cat">${i18n(catKey)}</span>
1696
+ </div>
1697
+ ${f.platform ? `<div class="aws-uni-meta">📏 ${f.platform.size} · 💸 ${f.platform.commission}% comm.</div>` : ''}
1698
+ ${f.wabBridge?.bonus > 0 ? `<div class="aws-uni-meta bridge-bonus">🌉 WAB bonus: +${f.wabBridge.bonus}</div>` : ''}
1699
+ <div class="aws-uni-breakdown">
1700
+ <span>📐 Size: ${f.breakdown?.sizeScore || '-'}</span>
1701
+ <span>🤝 Trust: ${f.breakdown?.trustScore || '-'}</span>
1702
+ <span>💰 Price: ${f.breakdown?.priceHonesty || '-'}</span>
1703
+ <span>🔍 Transparency: ${f.breakdown?.transparency || '-'}</span>
1704
+ </div>`;
1705
+ }
1706
+
1707
+ function renderCompareWs(data) {
1708
+ const deals = data.deals || data.results || [];
1709
+ const el = document.getElementById('uniCompareWs');
1710
+ if (deals.length === 0) {
1711
+ showToast(i18n('toast_no_results'));
1712
+ return;
1713
+ }
1714
+ el.style.display = '';
1715
+ const badges = ['🥇', '🥈', '🥉'];
1716
+ el.innerHTML = `
1717
+ <h4>${i18n('uni_compare_title')}</h4>
1718
+ ${(data.insights || []).map(ins => `
1719
+ <div class="aws-uni-insight">${ins.icon || '💡'} ${escapeHtml(ins.text)}</div>
1720
+ `).join('')}
1721
+ ${deals.slice(0, 10).map((d, i) => `
1722
+ <div class="aws-uni-deal ${i === 0 ? 'best' : ''} ${d.wabBridge ? 'wab-bridge' : ''}">
1723
+ <div class="aws-uni-deal-header">
1724
+ <span>${badges[i] || '#' + (i + 1)}</span>
1725
+ <span class="aws-uni-deal-source">${escapeHtml(d.source || d.domain || '')}</span>
1726
+ ${d.wabBridge ? '<span class="aws-uni-badge bridge small">🌉 WAB</span>' : ''}
1727
+ ${d.canNegotiate ? '<span class="aws-uni-badge negotiate small">🤝</span>' : ''}
1728
+ <span class="aws-uni-deal-score">${d.compositeScore || d.score || ''}</span>
1729
+ </div>
1730
+ <div class="aws-uni-deal-name">${escapeHtml(String(d.name || '').slice(0, 80))}</div>
1731
+ <div class="aws-uni-deal-row">
1732
+ ${d.priceUsd ? `<strong>$${d.priceUsd}</strong>` : ''}
1733
+ ${d.fairness ? `<span class="aws-uni-fairness-chip ${d.fairness.category}">${d.fairness.total}/100</span>` : ''}
1734
+ ${d.rating ? `⭐ ${d.rating}` : ''}
1735
+ </div>
1736
+ ${d.url ? `<a href="${escapeHtml(d.url)}" target="_blank" class="aws-uni-deal-link">🔗 ${state.lang === 'ar' ? 'فتح' : 'Open'}</a>` : ''}
1737
+ </div>
1738
+ `).join('')}
1739
+ <div class="aws-uni-compare-summary">${data.sourcesChecked || 0} ${i18n('uni_sources_checked')}</div>`;
1740
+ }