web-agent-bridge 3.2.0 โ†’ 3.3.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 (202) hide show
  1. package/LICENSE +72 -72
  2. package/README.ar.md +1286 -1152
  3. package/README.md +1764 -1635
  4. package/bin/agent-runner.js +474 -474
  5. package/bin/cli.js +237 -138
  6. package/bin/wab.js +80 -80
  7. package/examples/bidi-agent.js +119 -119
  8. package/examples/cross-site-agent.js +91 -91
  9. package/examples/mcp-agent.js +94 -94
  10. package/examples/next-app-router/README.md +44 -44
  11. package/examples/puppeteer-agent.js +108 -108
  12. package/examples/saas-dashboard/README.md +55 -55
  13. package/examples/shopify-hydrogen/README.md +74 -74
  14. package/examples/vision-agent.js +171 -171
  15. package/examples/wordpress-elementor/README.md +77 -77
  16. package/package.json +16 -3
  17. package/public/.well-known/agent-tools.json +180 -180
  18. package/public/.well-known/ai-assets.json +59 -59
  19. package/public/.well-known/security.txt +8 -0
  20. package/public/agent-workspace.html +349 -349
  21. package/public/ai.html +198 -198
  22. package/public/api.html +413 -412
  23. package/public/browser.html +486 -486
  24. package/public/commander-dashboard.html +243 -243
  25. package/public/cookies.html +210 -210
  26. package/public/css/agent-workspace.css +1713 -1713
  27. package/public/css/premium.css +317 -317
  28. package/public/css/styles.css +1235 -1235
  29. package/public/dashboard.html +706 -706
  30. package/public/dns.html +507 -0
  31. package/public/docs.html +587 -587
  32. package/public/feed.xml +89 -89
  33. package/public/growth.html +463 -463
  34. package/public/index.html +1070 -982
  35. package/public/integrations.html +556 -0
  36. package/public/js/agent-workspace.js +1740 -1740
  37. package/public/js/auth-nav.js +31 -31
  38. package/public/js/auth-redirect.js +12 -12
  39. package/public/js/cookie-consent.js +56 -56
  40. package/public/js/wab-demo-page.js +721 -721
  41. package/public/js/ws-client.js +74 -74
  42. package/public/llms-full.txt +360 -360
  43. package/public/llms.txt +125 -125
  44. package/public/login.html +85 -85
  45. package/public/mesh-dashboard.html +328 -328
  46. package/public/openapi.json +580 -580
  47. package/public/phone-shield.html +281 -0
  48. package/public/premium-dashboard.html +2489 -2489
  49. package/public/premium.html +793 -793
  50. package/public/privacy.html +297 -297
  51. package/public/register.html +105 -105
  52. package/public/robots.txt +87 -87
  53. package/public/script/wab-consent.d.ts +36 -36
  54. package/public/script/wab-consent.js +104 -104
  55. package/public/script/wab-schema.js +131 -131
  56. package/public/script/wab.d.ts +108 -108
  57. package/public/script/wab.min.js +580 -580
  58. package/public/security.txt +8 -0
  59. package/public/terms.html +256 -256
  60. package/script/ai-agent-bridge.js +1754 -1754
  61. package/sdk/README.md +99 -99
  62. package/sdk/agent-mesh.js +449 -449
  63. package/sdk/commander.js +262 -262
  64. package/sdk/index.d.ts +464 -464
  65. package/sdk/index.js +12 -1
  66. package/sdk/multi-agent.js +318 -318
  67. package/sdk/package.json +1 -1
  68. package/sdk/safety-shield.js +219 -0
  69. package/sdk/schema-discovery.js +83 -83
  70. package/server/adapters/index.js +520 -520
  71. package/server/config/plans.js +367 -367
  72. package/server/config/secrets.js +102 -102
  73. package/server/control-plane/index.js +301 -301
  74. package/server/data-plane/index.js +354 -354
  75. package/server/index.js +531 -427
  76. package/server/llm/index.js +404 -404
  77. package/server/middleware/adminAuth.js +35 -35
  78. package/server/middleware/auth.js +50 -50
  79. package/server/middleware/featureGate.js +88 -88
  80. package/server/middleware/rateLimits.js +100 -100
  81. package/server/middleware/sensitiveAction.js +157 -0
  82. package/server/migrations/001_add_analytics_indexes.sql +7 -7
  83. package/server/migrations/002_premium_features.sql +418 -418
  84. package/server/migrations/003_ads_integer_cents.sql +33 -33
  85. package/server/migrations/004_agent_os.sql +158 -158
  86. package/server/migrations/005_marketplace_metering.sql +126 -126
  87. package/server/models/adapters/index.js +33 -33
  88. package/server/models/adapters/mysql.js +183 -183
  89. package/server/models/adapters/postgresql.js +172 -172
  90. package/server/models/adapters/sqlite.js +7 -7
  91. package/server/models/db.js +681 -681
  92. package/server/observability/failure-analysis.js +337 -337
  93. package/server/observability/index.js +394 -394
  94. package/server/protocol/capabilities.js +223 -223
  95. package/server/protocol/index.js +243 -243
  96. package/server/protocol/schema.js +584 -584
  97. package/server/registry/certification.js +271 -271
  98. package/server/registry/index.js +326 -326
  99. package/server/routes/admin-premium.js +671 -671
  100. package/server/routes/admin.js +261 -261
  101. package/server/routes/ads.js +130 -130
  102. package/server/routes/agent-workspace.js +540 -540
  103. package/server/routes/api.js +150 -150
  104. package/server/routes/auth.js +71 -71
  105. package/server/routes/billing.js +45 -45
  106. package/server/routes/commander.js +316 -316
  107. package/server/routes/demo-showcase.js +332 -332
  108. package/server/routes/demo-store.js +154 -0
  109. package/server/routes/discovery.js +417 -417
  110. package/server/routes/gateway.js +173 -157
  111. package/server/routes/license.js +251 -240
  112. package/server/routes/mesh.js +469 -469
  113. package/server/routes/noscript.js +543 -543
  114. package/server/routes/premium-v2.js +686 -686
  115. package/server/routes/premium.js +724 -724
  116. package/server/routes/runtime.js +2148 -2147
  117. package/server/routes/sovereign.js +465 -385
  118. package/server/routes/universal.js +200 -185
  119. package/server/routes/wab-api.js +850 -501
  120. package/server/runtime/container-worker.js +111 -111
  121. package/server/runtime/container.js +448 -448
  122. package/server/runtime/distributed-worker.js +362 -362
  123. package/server/runtime/event-bus.js +210 -210
  124. package/server/runtime/index.js +253 -253
  125. package/server/runtime/queue.js +599 -599
  126. package/server/runtime/replay.js +666 -666
  127. package/server/runtime/sandbox.js +266 -266
  128. package/server/runtime/scheduler.js +534 -534
  129. package/server/runtime/session-engine.js +293 -293
  130. package/server/runtime/state-manager.js +188 -188
  131. package/server/security/cross-site-redactor.js +196 -0
  132. package/server/security/dry-run.js +180 -0
  133. package/server/security/human-gate-rate-limit.js +147 -0
  134. package/server/security/human-gate-transports.js +178 -0
  135. package/server/security/human-gate.js +281 -0
  136. package/server/security/index.js +368 -368
  137. package/server/security/intent-engine.js +245 -0
  138. package/server/security/reward-guard.js +171 -0
  139. package/server/security/rollback-store.js +239 -0
  140. package/server/security/token-scope.js +404 -0
  141. package/server/security/url-policy.js +139 -0
  142. package/server/services/agent-chat.js +506 -506
  143. package/server/services/agent-learning.js +601 -575
  144. package/server/services/agent-memory.js +625 -625
  145. package/server/services/agent-mesh.js +555 -539
  146. package/server/services/agent-symphony.js +717 -717
  147. package/server/services/agent-tasks.js +1807 -1807
  148. package/server/services/api-key-engine.js +292 -261
  149. package/server/services/cluster.js +894 -894
  150. package/server/services/commander.js +738 -738
  151. package/server/services/edge-compute.js +440 -440
  152. package/server/services/email.js +204 -204
  153. package/server/services/hosted-runtime.js +205 -205
  154. package/server/services/lfd.js +635 -635
  155. package/server/services/local-ai.js +389 -389
  156. package/server/services/marketplace.js +270 -270
  157. package/server/services/metering.js +182 -182
  158. package/server/services/modules/affiliate-intelligence.js +93 -93
  159. package/server/services/modules/agent-firewall.js +90 -90
  160. package/server/services/modules/bounty.js +89 -89
  161. package/server/services/modules/collective-bargaining.js +92 -92
  162. package/server/services/modules/dark-pattern.js +66 -66
  163. package/server/services/modules/gov-intelligence.js +45 -45
  164. package/server/services/modules/neural.js +55 -55
  165. package/server/services/modules/notary.js +49 -49
  166. package/server/services/modules/price-time-machine.js +86 -86
  167. package/server/services/modules/protocol.js +104 -104
  168. package/server/services/negotiation.js +439 -439
  169. package/server/services/plugins.js +771 -771
  170. package/server/services/price-intelligence.js +566 -566
  171. package/server/services/price-shield.js +1137 -1137
  172. package/server/services/reputation.js +465 -465
  173. package/server/services/search-engine.js +357 -357
  174. package/server/services/security.js +513 -513
  175. package/server/services/self-healing.js +843 -843
  176. package/server/services/sovereign-shield.js +542 -0
  177. package/server/services/stripe.js +192 -192
  178. package/server/services/swarm.js +788 -788
  179. package/server/services/universal-scraper.js +662 -661
  180. package/server/services/verification.js +481 -481
  181. package/server/services/vision.js +1163 -1163
  182. package/server/utils/cache.js +125 -125
  183. package/server/utils/migrate.js +81 -81
  184. package/server/utils/safe-fetch.js +228 -0
  185. package/server/utils/secureFields.js +50 -50
  186. package/server/ws.js +161 -161
  187. package/templates/artisan-marketplace.yaml +104 -104
  188. package/templates/book-price-scout.yaml +98 -98
  189. package/templates/electronics-price-tracker.yaml +108 -108
  190. package/templates/flight-deal-hunter.yaml +113 -113
  191. package/templates/freelancer-direct.yaml +116 -116
  192. package/templates/grocery-price-compare.yaml +93 -93
  193. package/templates/hotel-direct-booking.yaml +113 -113
  194. package/templates/local-services.yaml +98 -98
  195. package/templates/olive-oil-tunisia.yaml +88 -88
  196. package/templates/organic-farm-fresh.yaml +101 -101
  197. package/templates/restaurant-direct.yaml +97 -97
  198. package/public/score.html +0 -263
  199. package/server/migrations/006_growth_suite.sql +0 -138
  200. package/server/routes/growth.js +0 -962
  201. package/server/services/fairness-engine.js +0 -409
  202. package/server/services/fairness.js +0 -420
@@ -1,1740 +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
- }
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
+ }