{"type":"session","version":3,"id":"5aea7647-7998-4612-b11f-e2547fac8b03","timestamp":"2026-02-20T19:01:32.916Z","cwd":"/home/ccuser/the-50-dollar-app"} {"type":"model_change","id":"a4be4c5f","parentId":null,"timestamp":"2026-02-20T19:01:32.918Z","provider":"anthropic","modelId":"claude-opus-4-6"} {"type":"thinking_level_change","id":"d23b3f27","parentId":"a4be4c5f","timestamp":"2026-02-20T19:01:32.918Z","thinkingLevel":"low"} {"type":"custom","customType":"model-snapshot","data":{"timestamp":1771614092918,"provider":"anthropic","modelApi":"anthropic-messages","modelId":"claude-opus-4-6"},"id":"d90d612c","parentId":"d23b3f27","timestamp":"2026-02-20T19:01:32.918Z"} {"type":"custom","customType":"clawdbot.cache-ttl","data":{"timestamp":1771614092923,"provider":"anthropic","modelId":"claude-opus-4-6"},"id":"7a8d9ad1","parentId":"d90d612c","timestamp":"2026-02-20T19:01:32.923Z"} {"type":"message","id":"6be3c29c","parentId":"7a8d9ad1","timestamp":"2026-02-20T19:01:32.927Z","message":{"role":"user","content":[{"type":"text","text":"PRICING PURGE: rateright-growth repo (Growth Engine CRM)\n\nYou are Builder. You need to purge ALL references to the old 9.9% commission pricing model in `/home/ccuser/rateright-growth`. Replace with $50 flat fee per hire messaging. Workers pay NOTHING. Contractors pay $50 per successful hire.\n\nDO NOT delete any records/data. Only update pricing language.\n\nFiles that need fixing (confirmed by grep):\n\n**src/services/ai.js** — Multiple 9.9% references in AI prompts (lines 37, 103, 207-208, 849-850, 864, 871, 878, 881, 1639, 1821)\n- Replace \"9.9% fee\" with \"$50 flat fee per hire\" \n- Replace \"workers pay 9.9%\" with \"workers pay nothing — contractors pay a flat $50 per hire\"\n- Replace competitive comparisons: \"$50 flat fee vs 30-40% agency margins\"\n\n**src/services/perplexity.js** — Lines 119, 275: \"9.9% fee vs 30-40% agency margins\"\n- Replace with \"$50 flat fee per hire vs 30-40% agency margins\"\n\n**src/services/compliance.js** — Line 313: mentions 9.9% fee for workers\n- Update to reflect workers pay $0, contractors pay $50 flat fee\n\n**src/services/stageDiagnosis.js** — Line 234: \"9.9% fee vs 30-40% agency margins\"\n- Replace with \"$50 flat fee vs 30-40% agency margins\"\n\n**src/routes/playbook.js** — Lines 594, 687: \"9.9% when you get paid\"\n- Replace with \"$50 flat fee per hire — workers keep 100%\"\n\n**admin/src/components/LiveCopilot.jsx** — Line 84: \"at 9.9% we're typically...\"\n- Replace with \"at $50 flat fee per hire, we're a fraction of what agencies charge\"\n\n**admin/src/components/CallSalesFunnel.jsx** — Line 33: \"at just 9.9%\"\n- Replace with \"for just $50 per hire\"\n\n**admin/src/components/EliteCallUI.jsx** — Line 143: \"at just 9.9%\"\n- Replace with \"for just $50 per hire\"\n\n**scripts/update-sms-sequences.js** and **scripts/update-all-sms-sequences.js** — These reference 9.9% but are update scripts (they may already fix old values). Check them and update if they still propagate 9.9%.\n\nAfter ALL edits, run:\n```bash\ncd /home/ccuser/rateright-growth && npm run build 2>&1 | tail -20\n```\n\nIf build succeeds, commit:\n```bash\ncd /home/ccuser/rateright-growth && git add -A && git commit -m \"fix: purge all 9.9% pricing refs — now \\$50 flat fee per hire\"\n```\n\nReport back what you changed."}],"timestamp":1771614092923}} {"type":"message","id":"e1d1f790","parentId":"6be3c29c","timestamp":"2026-02-20T19:01:40.882Z","message":{"role":"assistant","content":[{"type":"thinking","thinking":"Let me start by reading all the files that need changes to understand the context around each 9.9% reference.","thinkingSignature":"EpUCCkYICxgCKkCO7jNZoiSqYU4Nred7xFl5a4mh4fjdqf40OqnBgwzr8jJQYBE62pMzSe7tUwVAFiNyBvYxqAw3tcwONUrgssjbEgza1M8Eq0jjnoytyYoaDKJOyX1ODjHkykPZBSIwE6m8IgD85pVH2Wg2riyBPXOeXclbZTLxwq0KJRu20uN0dv4fvTFj1WfK4XzjZC/gKn0amjYn6feElz38UEwSysmUWp4Fei3vmltonN6YhYn3ueM4QmypwB7nvF//ZOG1nw0BB2n1StrKyfjRngRBfC49rt94OxmKHNjfkPZLCsRbrSoeB/DqnXdsNVXgBj31I/+v6K63iZ1fkmWW0ferOSYBk/oQaOhyZL+AsNJyOBgB"},{"type":"text","text":"Let me read all the affected files in parallel to understand the context around each 9.9% reference."},{"type":"toolCall","id":"toolu_018mZojwTnMHz7V2LpCKqP6v","name":"exec","arguments":{"command":"cd /home/ccuser/rateright-growth && grep -n \"9\\.9\" src/services/ai.js"}},{"type":"toolCall","id":"toolu_01WMSDEYFLSKPik2YVjnbPg1","name":"exec","arguments":{"command":"cd /home/ccuser/rateright-growth && grep -n \"9\\.9\" src/services/perplexity.js"}},{"type":"toolCall","id":"toolu_01Myp69vaMJHRQzkHQesGFMR","name":"exec","arguments":{"command":"cd /home/ccuser/rateright-growth && grep -n \"9\\.9\" src/services/compliance.js"}},{"type":"toolCall","id":"toolu_015uwk3EtVd15e1DsjMrQcmQ","name":"exec","arguments":{"command":"cd /home/ccuser/rateright-growth && grep -n \"9\\.9\" src/services/stageDiagnosis.js"}},{"type":"toolCall","id":"toolu_0138gPfJ1gsd52MPi8FVRsfL","name":"exec","arguments":{"command":"cd /home/ccuser/rateright-growth && grep -n \"9\\.9\" src/routes/playbook.js"}},{"type":"toolCall","id":"toolu_01KWgcsjunZueKkHuQqYMd89","name":"exec","arguments":{"command":"cd /home/ccuser/rateright-growth && grep -n \"9\\.9\" admin/src/components/LiveCopilot.jsx"}},{"type":"toolCall","id":"toolu_014AV6hNKAR8UNsN92xpgUSB","name":"exec","arguments":{"command":"cd /home/ccuser/rateright-growth && grep -n \"9\\.9\" admin/src/components/CallSalesFunnel.jsx"}},{"type":"toolCall","id":"toolu_01KPusU7SCyZJ9g9nnti6qBs","name":"exec","arguments":{"command":"cd /home/ccuser/rateright-growth && grep -n \"9\\.9\" admin/src/components/EliteCallUI.jsx"}},{"type":"toolCall","id":"toolu_01P3ZMHg9Eht8eTu5jGXTdhx","name":"exec","arguments":{"command":"cd /home/ccuser/rateright-growth && grep -n \"9\\.9\" scripts/update-sms-sequences.js scripts/update-all-sms-sequences.js 2>/dev/null"}}],"api":"anthropic-messages","provider":"anthropic","model":"claude-opus-4-6","usage":{"input":10,"output":668,"cacheRead":0,"cacheWrite":11164,"totalTokens":11842,"cost":{"input":0.00005,"output":0.0167,"cacheRead":0,"cacheWrite":0.069775,"total":0.086525}},"stopReason":"toolUse","timestamp":1771614092926}} {"type":"message","id":"c25c2d6f","parentId":"e1d1f790","timestamp":"2026-02-20T19:01:40.906Z","message":{"role":"toolResult","toolCallId":"toolu_018mZojwTnMHz7V2LpCKqP6v","toolName":"exec","content":[{"type":"text","text":"37:- 9.9% platform fee vs 30-40% agency margins - massive savings\n103: const prompt = `You are an elite sales AI assistant analyzing a call with a potential customer for RateRight, Australia's worker marketplace (NOT an agency - a direct marketplace connecting contractors with workers at 9.9% fee vs 30-40% agency margins).\n207:- For contractors: RateRight is FREE (workers pay 9.9% fee)\n208:- For workers: mention the 9.9% platform fee honestly`;\n849:- For contractors: RateRight is FREE (workers pay 9.9%)\n850:- For workers: mention the 9.9% platform fee honestly\n864:- RateRight charges just 9.9%\n871:- 9.9% platform fee vs 30-40% agency margins - massive savings\n878:- PRICE: \"Agencies take 30-40% cut. On RateRight you post the job, workers apply direct, and we take just 9.9%. You're paying $${agencyMarkup}/week in agency fat - with us that's $${weeklySavings} back in your pocket.\"\n881:- HAPPY WITH CURRENT AGENCY: \"What are you paying in margins? Because agencies take 30-40% on top. With RateRight you deal direct with workers, see their ratings, and pay just 9.9%. No middleman.\"\n1639:- RateRight is a worker marketplace (9.9% fee vs 30-40% agency margins)\n1821:- Workers: 9.9% platform fee (vs 30-40% agency fees)"}],"details":{"status":"completed","exitCode":0,"durationMs":23,"aggregated":"37:- 9.9% platform fee vs 30-40% agency margins - massive savings\n103: const prompt = `You are an elite sales AI assistant analyzing a call with a potential customer for RateRight, Australia's worker marketplace (NOT an agency - a direct marketplace connecting contractors with workers at 9.9% fee vs 30-40% agency margins).\n207:- For contractors: RateRight is FREE (workers pay 9.9% fee)\n208:- For workers: mention the 9.9% platform fee honestly`;\n849:- For contractors: RateRight is FREE (workers pay 9.9%)\n850:- For workers: mention the 9.9% platform fee honestly\n864:- RateRight charges just 9.9%\n871:- 9.9% platform fee vs 30-40% agency margins - massive savings\n878:- PRICE: \"Agencies take 30-40% cut. On RateRight you post the job, workers apply direct, and we take just 9.9%. You're paying $${agencyMarkup}/week in agency fat - with us that's $${weeklySavings} back in your pocket.\"\n881:- HAPPY WITH CURRENT AGENCY: \"What are you paying in margins? Because agencies take 30-40% on top. With RateRight you deal direct with workers, see their ratings, and pay just 9.9%. No middleman.\"\n1639:- RateRight is a worker marketplace (9.9% fee vs 30-40% agency margins)\n1821:- Workers: 9.9% platform fee (vs 30-40% agency fees)","cwd":"/home/ccuser/the-50-dollar-app"},"isError":false,"timestamp":1771614100897}} {"type":"message","id":"7f3b24de","parentId":"c25c2d6f","timestamp":"2026-02-20T19:01:40.919Z","message":{"role":"toolResult","toolCallId":"toolu_01WMSDEYFLSKPik2YVjnbPg1","toolName":"exec","content":[{"type":"text","text":"119: \"ai_sales_angle\": \"Best approach for pitching RateRight (a marketplace where contractors post jobs and workers apply direct, 9.9% fee vs 30-40% agency margins, no middleman). Focus on their likely pain points.\"\n275: \"ai_talking_points\": \"Personalized talking points for pitching RateRight - a marketplace where they post jobs and workers apply direct (9.9% fee vs 30-40% agency margins). Focus on their role and likely pain points with finding reliable workers.\""}],"details":{"status":"completed","exitCode":0,"durationMs":12,"aggregated":"119: \"ai_sales_angle\": \"Best approach for pitching RateRight (a marketplace where contractors post jobs and workers apply direct, 9.9% fee vs 30-40% agency margins, no middleman). Focus on their likely pain points.\"\n275: \"ai_talking_points\": \"Personalized talking points for pitching RateRight - a marketplace where they post jobs and workers apply direct (9.9% fee vs 30-40% agency margins). Focus on their role and likely pain points with finding reliable workers.\"","cwd":"/home/ccuser/the-50-dollar-app"},"isError":false,"timestamp":1771614100910}} {"type":"message","id":"e12c489c","parentId":"7f3b24de","timestamp":"2026-02-20T19:01:40.931Z","message":{"role":"toolResult","toolCallId":"toolu_01Myp69vaMJHRQzkHQesGFMR","toolName":"exec","content":[{"type":"text","text":"313: 'free': 'For contractors: \"no cost to you\". For workers: mention the 9.9% fee',"}],"details":{"status":"completed","exitCode":0,"durationMs":12,"aggregated":"313: 'free': 'For contractors: \"no cost to you\". For workers: mention the 9.9% fee',","cwd":"/home/ccuser/the-50-dollar-app"},"isError":false,"timestamp":1771614100922}} {"type":"message","id":"cf64bdde","parentId":"e12c489c","timestamp":"2026-02-20T19:01:40.947Z","message":{"role":"toolResult","toolCallId":"toolu_015uwk3EtVd15e1DsjMrQcmQ","toolName":"exec","content":[{"type":"text","text":"234:- 9.9% fee vs 30-40% agency margins"}],"details":{"status":"completed","exitCode":0,"durationMs":15,"aggregated":"234:- 9.9% fee vs 30-40% agency margins","cwd":"/home/ccuser/the-50-dollar-app"},"isError":false,"timestamp":1771614100937}} {"type":"message","id":"0b6030e5","parentId":"cf64bdde","timestamp":"2026-02-20T19:01:40.959Z","message":{"role":"toolResult","toolCallId":"toolu_0138gPfJ1gsd52MPi8FVRsfL","toolName":"exec","content":[{"type":"text","text":"594: ? 'Connect quality tradies with jobs. Only pay 9.9% when you get paid - no upfront costs.'\n687: ? 'Connect tradies with jobs. 9.9% only when you get paid.'"}],"details":{"status":"completed","exitCode":0,"durationMs":12,"aggregated":"594: ? 'Connect quality tradies with jobs. Only pay 9.9% when you get paid - no upfront costs.'\n687: ? 'Connect tradies with jobs. 9.9% only when you get paid.'","cwd":"/home/ccuser/the-50-dollar-app"},"isError":false,"timestamp":1771614100949}} {"type":"message","id":"933517fc","parentId":"0b6030e5","timestamp":"2026-02-20T19:01:40.972Z","message":{"role":"toolResult","toolCallId":"toolu_01KWgcsjunZueKkHuQqYMd89","toolName":"exec","content":[{"type":"text","text":"84: response: \"Yes, at 9.9% we're typically 30-50% less than traditional agencies, with no lock-in contracts.\","}],"details":{"status":"completed","exitCode":0,"durationMs":11,"aggregated":"84: response: \"Yes, at 9.9% we're typically 30-50% less than traditional agencies, with no lock-in contracts.\",","cwd":"/home/ccuser/the-50-dollar-app"},"isError":false,"timestamp":1771614100962}} {"type":"message","id":"bb7c396c","parentId":"933517fc","timestamp":"2026-02-20T19:01:40.984Z","message":{"role":"toolResult","toolCallId":"toolu_014AV6hNKAR8UNsN92xpgUSB","toolName":"exec","content":[{"type":"text","text":"33: script: \"We connect you with pre-vetted workers at just 9.9% - no lock-in contracts.\","}],"details":{"status":"completed","exitCode":0,"durationMs":12,"aggregated":"33: script: \"We connect you with pre-vetted workers at just 9.9% - no lock-in contracts.\",","cwd":"/home/ccuser/the-50-dollar-app"},"isError":false,"timestamp":1771614100975}} {"type":"message","id":"5faa7ae8","parentId":"bb7c396c","timestamp":"2026-02-20T19:01:40.996Z","message":{"role":"toolResult","toolCallId":"toolu_01KPusU7SCyZJ9g9nnti6qBs","toolName":"exec","content":[{"type":"text","text":"143: return script.value_props?.[0]?.prop || \"We connect you with pre-vetted workers at just 9.9% - no lock-in contracts.\";"}],"details":{"status":"completed","exitCode":0,"durationMs":12,"aggregated":"143: return script.value_props?.[0]?.prop || \"We connect you with pre-vetted workers at just 9.9% - no lock-in contracts.\";","cwd":"/home/ccuser/the-50-dollar-app"},"isError":false,"timestamp":1771614100987}} {"type":"message","id":"d7d7c102","parentId":"5faa7ae8","timestamp":"2026-02-20T19:01:41.002Z","message":{"role":"toolResult","toolCallId":"toolu_01P3ZMHg9Eht8eTu5jGXTdhx","toolName":"exec","content":[{"type":"text","text":"scripts/update-sms-sequences.js:196: console.log('- Removed old \"9.9%\" messaging');\nscripts/update-all-sms-sequences.js:11: * - Remove \"9.9%\", \"FREE to use\" (for contractors), misleading fee language\nscripts/update-all-sms-sequences.js:264: // FIX: Remove \"Rocky\", remove \"9.9%\"\nscripts/update-all-sms-sequences.js:364: console.log(' ✓ 9.9% → $0 for workers');"}],"details":{"status":"completed","exitCode":0,"durationMs":12,"aggregated":"scripts/update-sms-sequences.js:196: console.log('- Removed old \"9.9%\" messaging');\nscripts/update-all-sms-sequences.js:11: * - Remove \"9.9%\", \"FREE to use\" (for contractors), misleading fee language\nscripts/update-all-sms-sequences.js:264: // FIX: Remove \"Rocky\", remove \"9.9%\"\nscripts/update-all-sms-sequences.js:364: console.log(' ✓ 9.9% → $0 for workers');","cwd":"/home/ccuser/the-50-dollar-app"},"isError":false,"timestamp":1771614101000}} {"type":"message","id":"575abcc1","parentId":"d7d7c102","timestamp":"2026-02-20T19:01:49.960Z","message":{"role":"assistant","content":[{"type":"text","text":"Now let me get the exact lines with context for precise edits:"},{"type":"toolCall","id":"toolu_015i2za8TQbJE4XZN7TS2oFD","name":"read","arguments":{"path":"/home/ccuser/rateright-growth/src/services/ai.js","offset":35,"limit":5}},{"type":"toolCall","id":"toolu_014ewSmK71RZP4nrnWv5Yi9D","name":"read","arguments":{"path":"/home/ccuser/rateright-growth/src/services/ai.js","offset":101,"limit":5}},{"type":"toolCall","id":"toolu_01V7QUoW811yoDTuB8UJV3Bd","name":"read","arguments":{"path":"/home/ccuser/rateright-growth/src/services/ai.js","offset":205,"limit":6}},{"type":"toolCall","id":"toolu_01Nqqo6FUkBeh5JQhfFCUpmb","name":"read","arguments":{"path":"/home/ccuser/rateright-growth/src/services/ai.js","offset":847,"limit":6}},{"type":"toolCall","id":"toolu_01APHZLbG4j6E9gi1oiXET8P","name":"read","arguments":{"path":"/home/ccuser/rateright-growth/src/services/ai.js","offset":862,"limit":4}},{"type":"toolCall","id":"toolu_01WPAY7MSJkMqGHu1woh2o5R","name":"read","arguments":{"path":"/home/ccuser/rateright-growth/src/services/ai.js","offset":869,"limit":4}},{"type":"toolCall","id":"toolu_01NunEnswid5najPi7mo9DEV","name":"read","arguments":{"path":"/home/ccuser/rateright-growth/src/services/ai.js","offset":876,"limit":8}},{"type":"toolCall","id":"toolu_01CB28YXVuCZL2cJze8h2bEz","name":"read","arguments":{"path":"/home/ccuser/rateright-growth/src/services/ai.js","offset":1637,"limit":4}},{"type":"toolCall","id":"toolu_01PyoLCFKT9UgidqWqbHt9LL","name":"read","arguments":{"path":"/home/ccuser/rateright-growth/src/services/ai.js","offset":1819,"limit":4}}],"api":"anthropic-messages","provider":"anthropic","model":"claude-opus-4-6","usage":{"input":1,"output":808,"cacheRead":11164,"cacheWrite":1729,"totalTokens":13702,"cost":{"input":0.000005,"output":0.020200000000000003,"cacheRead":0.005582,"cacheWrite":0.01080625,"total":0.03659325000000001}},"stopReason":"toolUse","timestamp":1771614101002}} {"type":"message","id":"7b34ca39","parentId":"575abcc1","timestamp":"2026-02-20T19:01:49.975Z","message":{"role":"toolResult","toolCallId":"toolu_015i2za8TQbJE4XZN7TS2oFD","toolName":"read","content":[{"type":"text","text":"WHAT RATERIGHT IS:\n- A marketplace that connects contractors DIRECTLY with workers (not an agency)\n- 9.9% platform fee vs 30-40% agency margins - massive savings\n- Contractors post jobs, workers apply - direct relationship\n- Rating system for worker reliability - see before you book\n\n[2268 more lines in file. Use offset=40 to continue]"}],"isError":false,"timestamp":1771614109973}} {"type":"message","id":"0a416825","parentId":"7b34ca39","timestamp":"2026-02-20T19:01:49.981Z","message":{"role":"toolResult","toolCallId":"toolu_014ewSmK71RZP4nrnWv5Yi9D","toolName":"read","content":[{"type":"text","text":" }\n\n const prompt = `You are an elite sales AI assistant analyzing a call with a potential customer for RateRight, Australia's worker marketplace (NOT an agency - a direct marketplace connecting contractors with workers at 9.9% fee vs 30-40% agency margins).\n\nLEAD: ${lead.first_name} ${lead.last_name || ''} from ${lead.company || 'Unknown company'}\n\n[2202 more lines in file. Use offset=106 to continue]"}],"isError":false,"timestamp":1771614109979}} {"type":"message","id":"cc154c52","parentId":"0a416825","timestamp":"2026-02-20T19:01:49.986Z","message":{"role":"toolResult","toolCallId":"toolu_01V7QUoW811yoDTuB8UJV3Bd","toolName":"read","content":[{"type":"text","text":"- Keep it conversational, not corporate\n- Always include a clear next step\n- For contractors: RateRight is FREE (workers pay 9.9% fee)\n- For workers: mention the 9.9% platform fee honestly`;\n\n const prompt = isRefinement\n\n[2097 more lines in file. Use offset=211 to continue]"}],"isError":false,"timestamp":1771614109984}} {"type":"message","id":"9ba59a2e","parentId":"cc154c52","timestamp":"2026-02-20T19:01:49.991Z","message":{"role":"toolResult","toolCallId":"toolu_01Nqqo6FUkBeh5JQhfFCUpmb","toolName":"read","content":[{"type":"text","text":"- Use words like: ${(guidelines.tone_keywords || []).slice(0, 5).join(', ')}\n- NEVER use: ${(guidelines.banned_words || []).join(', ')}\n- For contractors: RateRight is FREE (workers pay 9.9%)\n- For workers: mention the 9.9% platform fee honestly\n\nTHE SITUATION:\n\n[1455 more lines in file. Use offset=853 to continue]"}],"isError":false,"timestamp":1771614109989}} {"type":"message","id":"94f4aefd","parentId":"9ba59a2e","timestamp":"2026-02-20T19:01:49.996Z","message":{"role":"toolResult","toolCallId":"toolu_01APHZLbG4j6E9gi1oiXET8P","toolName":"read","content":[{"type":"text","text":"THE MATH (use this!):\n- Agencies charge 30-40% margin on workers\n- RateRight charges just 9.9%\n- That's $${weeklySavings}/week savings per worker\n\n[1442 more lines in file. Use offset=866 to continue]"}],"isError":false,"timestamp":1771614109994}} {"type":"message","id":"709d69db","parentId":"94f4aefd","timestamp":"2026-02-20T19:01:50.001Z","message":{"role":"toolResult","toolCallId":"toolu_01WPAY7MSJkMqGHu1woh2o5R","toolName":"read","content":[{"type":"text","text":"WHAT RATERIGHT IS (GET THIS RIGHT!):\n- A MARKETPLACE, not an agency - contractors post jobs, workers apply directly\n- 9.9% platform fee vs 30-40% agency margins - massive savings\n- Direct relationship between you and the worker - no middleman\n\n[1435 more lines in file. Use offset=873 to continue]"}],"isError":false,"timestamp":1771614109999}} {"type":"message","id":"6cc5a499","parentId":"709d69db","timestamp":"2026-02-20T19:01:50.007Z","message":{"role":"toolResult","toolCallId":"toolu_01NunEnswid5najPi7mo9DEV","toolName":"read","content":[{"type":"text","text":"\nOBJECTION PLAYBOOK:\n- PRICE: \"Agencies take 30-40% cut. On RateRight you post the job, workers apply direct, and we take just 9.9%. You're paying $${agencyMarkup}/week in agency fat - with us that's $${weeklySavings} back in your pocket.\"\n- ALREADY HAVE WORKERS: \"Perfect - keep them! But what happens when Dave calls in sick Monday morning and you've got a concrete pour? Post a job on RateRight, get applicants in hours.\"\n- NEED TO THINK: \"Totally fair. What's the main thing you'd want to check? Happy to send you some numbers to look at.\"\n- HAPPY WITH CURRENT AGENCY: \"What are you paying in margins? Because agencies take 30-40% on top. With RateRight you deal direct with workers, see their ratings, and pay just 9.9%. No middleman.\"\n- TOO BUSY: \"I get it - that's exactly why tradies use us. 5 minutes to post a job, workers come to you. No hunting, no agencies, just blokes applying direct.\"\n- CONTRACTS/LOCKED IN: \"No contracts. Post one job, try it out. Most blokes try us once and stick around because the direct connection just works better.\"\n\n[1424 more lines in file. Use offset=884 to continue]"}],"isError":false,"timestamp":1771614110005}} {"type":"message","id":"d464ec62","parentId":"6cc5a499","timestamp":"2026-02-20T19:01:50.012Z","message":{"role":"toolResult","toolCallId":"toolu_01CB28YXVuCZL2cJze8h2bEz","toolName":"read","content":[{"type":"text","text":"\nCONTEXT:\n- RateRight is a worker marketplace (9.9% fee vs 30-40% agency margins)\n- They're signing up again = high intent signal\n\n[667 more lines in file. Use offset=1641 to continue]"}],"isError":false,"timestamp":1771614110010}} {"type":"message","id":"6860e42e","parentId":"d464ec62","timestamp":"2026-02-20T19:01:50.017Z","message":{"role":"toolResult","toolCallId":"toolu_01PyoLCFKT9UgidqWqbHt9LL","toolName":"read","content":[{"type":"text","text":"- Marketplace connecting contractors with workers DIRECTLY (not an agency)\n- Contractors: FREE to use, post jobs and get matched\n- Workers: 9.9% platform fee (vs 30-40% agency fees)\n- Rating system shows worker reliability before booking\n\n[485 more lines in file. Use offset=1823 to continue]"}],"isError":false,"timestamp":1771614110015}} {"type":"message","id":"2ba653e7","parentId":"6860e42e","timestamp":"2026-02-20T19:01:58.874Z","message":{"role":"assistant","content":[{"type":"text","text":"Now let me read the remaining files to get exact context:"},{"type":"toolCall","id":"toolu_01N6xrFEEyriMsbZrwdcqmZ6","name":"read","arguments":{"path":"/home/ccuser/rateright-growth/src/services/perplexity.js","offset":117,"limit":5}},{"type":"toolCall","id":"toolu_015hi4Z7DjLt28sxqMPdeXHA","name":"read","arguments":{"path":"/home/ccuser/rateright-growth/src/services/perplexity.js","offset":273,"limit":5}},{"type":"toolCall","id":"toolu_012v6hoZBjU6GTxFKVzRqbfD","name":"read","arguments":{"path":"/home/ccuser/rateright-growth/src/services/compliance.js","offset":311,"limit":5}},{"type":"toolCall","id":"toolu_01JqNJFnjx1EXkT2H3qkygHQ","name":"read","arguments":{"path":"/home/ccuser/rateright-growth/src/services/stageDiagnosis.js","offset":232,"limit":5}},{"type":"toolCall","id":"toolu_01LmZheqkoN2nkLCFfcXohkd","name":"read","arguments":{"path":"/home/ccuser/rateright-growth/src/routes/playbook.js","offset":592,"limit":5}},{"type":"toolCall","id":"toolu_01N8M24T3icxEtdat6FbPm3n","name":"read","arguments":{"path":"/home/ccuser/rateright-growth/src/routes/playbook.js","offset":685,"limit":5}},{"type":"toolCall","id":"toolu_01Srp2cQEdhFZAyM5kRwBEBJ","name":"read","arguments":{"path":"/home/ccuser/rateright-growth/admin/src/components/LiveCopilot.jsx","offset":82,"limit":5}},{"type":"toolCall","id":"toolu_01M5QuJw5gT74Z15vDZPpyGP","name":"read","arguments":{"path":"/home/ccuser/rateright-growth/admin/src/components/CallSalesFunnel.jsx","offset":31,"limit":5}},{"type":"toolCall","id":"toolu_015HpG7vyogcdxzouYL4LGeu","name":"read","arguments":{"path":"/home/ccuser/rateright-growth/admin/src/components/EliteCallUI.jsx","offset":141,"limit":5}}],"api":"anthropic-messages","provider":"anthropic","model":"claude-opus-4-6","usage":{"input":1,"output":834,"cacheRead":12893,"cacheWrite":2003,"totalTokens":15731,"cost":{"input":0.000005,"output":0.02085,"cacheRead":0.0064465,"cacheWrite":0.01251875,"total":0.03982025}},"stopReason":"toolUse","timestamp":1771614110017}} {"type":"message","id":"00bd7202","parentId":"2ba653e7","timestamp":"2026-02-20T19:01:58.890Z","message":{"role":"toolResult","toolCallId":"toolu_01N6xrFEEyriMsbZrwdcqmZ6","toolName":"read","content":[{"type":"text","text":" \"recent_projects\": [\"Recent project or news 1\", \"Recent project or news 2\"],\n \"hiring_signals\": [\"Any hiring activity or growth signals\"],\n \"ai_sales_angle\": \"Best approach for pitching RateRight (a marketplace where contractors post jobs and workers apply direct, 9.9% fee vs 30-40% agency margins, no middleman). Focus on their likely pain points.\"\n}\n\n\n[593 more lines in file. Use offset=122 to continue]"}],"isError":false,"timestamp":1771614118888}} {"type":"message","id":"af81c7e1","parentId":"00bd7202","timestamp":"2026-02-20T19:01:58.916Z","message":{"role":"toolResult","toolCallId":"toolu_015hi4Z7DjLt28sxqMPdeXHA","toolName":"read","content":[{"type":"text","text":" ],\n\n \"ai_talking_points\": \"Personalized talking points for pitching RateRight - a marketplace where they post jobs and workers apply direct (9.9% fee vs 30-40% agency margins). Focus on their role and likely pain points with finding reliable workers.\"\n}\n\n\n[437 more lines in file. Use offset=278 to continue]"}],"isError":false,"timestamp":1771614118913}} {"type":"message","id":"125b2f00","parentId":"af81c7e1","timestamp":"2026-02-20T19:01:58.920Z","message":{"role":"toolResult","toolCallId":"toolu_012v6hoZBjU6GTxFKVzRqbfD","toolName":"read","content":[{"type":"text","text":" 'best': 'Try: \"great\" or \"solid\"',\n 'cheapest': 'Try: \"competitive\" or \"fair\"',\n 'free': 'For contractors: \"no cost to you\". For workers: mention the 9.9% fee',\n 'urgent': 'Try: \"when you get a chance\" or \"worth looking at\"',\n 'final': 'Try: \"following up\" or \"checking in\"',\n\n[264 more lines in file. Use offset=316 to continue]"}],"isError":false,"timestamp":1771614118918}} {"type":"message","id":"2f44ecf5","parentId":"125b2f00","timestamp":"2026-02-20T19:01:58.924Z","message":{"role":"toolResult","toolCallId":"toolu_01JqNJFnjx1EXkT2H3qkygHQ","toolName":"read","content":[{"type":"text","text":"RATERIGHT VALUE PROPS:\n- Direct connection (no agency middleman)\n- 9.9% fee vs 30-40% agency margins\n- Same-day matching for urgent jobs\n- Rating system for reliability\n\n[198 more lines in file. Use offset=237 to continue]"}],"isError":false,"timestamp":1771614118922}} {"type":"message","id":"5f233632","parentId":"2f44ecf5","timestamp":"2026-02-20T19:01:58.934Z","message":{"role":"toolResult","toolCallId":"toolu_01LmZheqkoN2nkLCFfcXohkd","toolName":"read","content":[{"type":"text","text":"- Company: RateRight\n- What we do: ${isWorker\n ? 'Connect quality tradies with jobs. Only pay 9.9% when you get paid - no upfront costs.'\n : 'Connect contractors with quality tradies. FREE for contractors to use.'}\n\n\n[499 more lines in file. Use offset=597 to continue]"}],"isError":false,"timestamp":1771614118932}} {"type":"message","id":"cf8537ab","parentId":"5f233632","timestamp":"2026-02-20T19:01:58.941Z","message":{"role":"toolResult","toolCallId":"toolu_01N8M24T3icxEtdat6FbPm3n","toolName":"read","content":[{"type":"text","text":"- Company: RateRight\n- What we do: ${isWorker\n ? 'Connect tradies with jobs. 9.9% only when you get paid.'\n : 'Connect contractors with quality tradies. FREE to use.'}\n\n\n[406 more lines in file. Use offset=690 to continue]"}],"isError":false,"timestamp":1771614118938}} {"type":"message","id":"85546a72","parentId":"cf8537ab","timestamp":"2026-02-20T19:01:58.947Z","message":{"role":"toolResult","toolCallId":"toolu_01Srp2cQEdhFZAyM5kRwBEBJ","toolName":"read","content":[{"type":"text","text":" 'cheaper': {\n type: 'value',\n response: \"Yes, at 9.9% we're typically 30-50% less than traditional agencies, with no lock-in contracts.\",\n followUp: \"Would you like me to calculate the savings based on your team size?\",\n keyPoint: \"Reinforce the value!\",\n\n[965 more lines in file. Use offset=87 to continue]"}],"isError":false,"timestamp":1771614118945}} {"type":"message","id":"a77c9bb7","parentId":"85546a72","timestamp":"2026-02-20T19:01:58.952Z","message":{"role":"toolResult","toolCallId":"toolu_01M5QuJw5gT74Z15vDZPpyGP","toolName":"read","content":[{"type":"text","text":" },\n value_prop: {\n script: \"We connect you with pre-vetted workers at just 9.9% - no lock-in contracts.\",\n tip: \"Focus on their pain points. Make it about them.\",\n alternatives: [\n\n[341 more lines in file. Use offset=36 to continue]"}],"isError":false,"timestamp":1771614118950}} {"type":"message","id":"e7dd942f","parentId":"a77c9bb7","timestamp":"2026-02-20T19:01:58.958Z","message":{"role":"toolResult","toolCallId":"toolu_015HpG7vyogcdxzouYL4LGeu","toolName":"read","content":[{"type":"text","text":" return script.discovery_questions?.[0]?.question || \"What's your biggest challenge finding workers right now?\";\n case 'value_prop':\n return script.value_props?.[0]?.prop || \"We connect you with pre-vetted workers at just 9.9% - no lock-in contracts.\";\n case 'objections':\n return \"Listen for concerns and address them directly.\";\n\n[409 more lines in file. Use offset=146 to continue]"}],"isError":false,"timestamp":1771614118955}} {"type":"message","id":"f02ceb2c","parentId":"e7dd942f","timestamp":"2026-02-20T19:02:04.216Z","message":{"role":"assistant","content":[{"type":"text","text":"Now let me check the SMS update scripts:"},{"type":"toolCall","id":"toolu_018qp24aL5NtUzhn9or7NWTR","name":"read","arguments":{"path":"/home/ccuser/rateright-growth/scripts/update-sms-sequences.js","offset":190,"limit":10}},{"type":"toolCall","id":"toolu_01XkfyzHmNWV1154ZnSSRtiA","name":"read","arguments":{"path":"/home/ccuser/rateright-growth/scripts/update-all-sms-sequences.js","offset":5,"limit":15}},{"type":"toolCall","id":"toolu_0144YMvAhjzE8DALua9jSAZj","name":"read","arguments":{"path":"/home/ccuser/rateright-growth/scripts/update-all-sms-sequences.js","offset":258,"limit":15}},{"type":"toolCall","id":"toolu_01K6UAfA1WhGmveDzSfjEcgJ","name":"read","arguments":{"path":"/home/ccuser/rateright-growth/scripts/update-all-sms-sequences.js","offset":358,"limit":12}}],"api":"anthropic-messages","provider":"anthropic","model":"claude-opus-4-6","usage":{"input":1,"output":389,"cacheRead":14896,"cacheWrite":1872,"totalTokens":17158,"cost":{"input":0.000005,"output":0.009725000000000001,"cacheRead":0.007448,"cacheWrite":0.0117,"total":0.028878}},"stopReason":"toolUse","timestamp":1771614118958}} {"type":"message","id":"e18c1e59","parentId":"f02ceb2c","timestamp":"2026-02-20T19:02:04.233Z","message":{"role":"toolResult","toolCallId":"toolu_018qp24aL5NtUzhn9or7NWTR","toolName":"read","content":[{"type":"text","text":" console.log('Based on new messaging from sms-sequences.md');\n console.log('Brand voice: Direct, no bullshit, workers-first');\n console.log('');\n console.log('KEY CHANGES:');\n console.log('- Workers: Focus on $0 fees, keeping 100%');\n console.log('- Contractors: Focus on $50 flat fee, no subscriptions');\n console.log('- Removed old \"9.9%\" messaging');\n console.log('- Removed \"FREE\" for contractors (it\\'s $50, be honest)');\n console.log('');\n\n\n[36 more lines in file. Use offset=200 to continue]"}],"isError":false,"timestamp":1771614124231}} {"type":"message","id":"445c3e40","parentId":"e18c1e59","timestamp":"2026-02-20T19:02:04.239Z","message":{"role":"toolResult","toolCallId":"toolu_01XkfyzHmNWV1154ZnSSRtiA","toolName":"read","content":[{"type":"text","text":" * Covers all 35 SMS steps across 15 sequences.\n * \n * Changes:\n * - Correct pricing: Workers $0 fees, Contractors $50 flat fee per hire\n * - \"Reply STOP to opt out\" on EVERY SMS (ACMA compliance)\n * - \"Rocky\" → \"Michael\" / \"RateRight\"\n * - Remove \"9.9%\", \"FREE to use\" (for contractors), misleading fee language\n * - Australian tradie tone, short punchy messages\n * \n * DRY_RUN=true (default) — only shows before/after, no writes\n * DRY_RUN=false — actually updates Supabase\n */\n\nconst { createClient } = require('@supabase/supabase-js');\nrequire('dotenv').config();\n\n[420 more lines in file. Use offset=20 to continue]"}],"isError":false,"timestamp":1771614124236}} {"type":"message","id":"d313cc98","parentId":"445c3e40","timestamp":"2026-02-20T19:02:04.245Z","message":{"role":"toolResult","toolCallId":"toolu_0144YMvAhjzE8DALua9jSAZj","toolName":"read","content":[{"type":"text","text":" // ─── 14. New Worker Outreach (156b8768) — Legacy ──────────\n {\n id: '102d33bc',\n sequence: 'New Worker Outreach',\n step: 1,\n field: 'message_template',\n // FIX: Remove \"Rocky\", remove \"9.9%\"\n new_text: 'Hey {first_name}, Michael from RateRight. We connect tradies with work — zero fees, you keep 100%. Worth a look? rateright.com.au\\n\\nReply STOP to opt out',\n },\n // Step 2 (23d59852) is a Follow-up Call — no SMS template to update\n {\n id: '63196ac8',\n sequence: 'New Worker Outreach',\n step: 3,\n field: 'message_template',\n\n[167 more lines in file. Use offset=273 to continue]"}],"isError":false,"timestamp":1771614124242}} {"type":"message","id":"3ebec489","parentId":"d313cc98","timestamp":"2026-02-20T19:02:04.251Z","message":{"role":"toolResult","toolCallId":"toolu_01K6UAfA1WhGmveDzSfjEcgJ","toolName":"read","content":[{"type":"text","text":" console.log(`║ Mode: ${DRY_RUN ? 'DRY RUN (no writes)' : '🔴 LIVE — WRITING TO DB'} ║`);\n console.log('╚══════════════════════════════════════════════════════════╝');\n console.log('');\n console.log('Changes applied:');\n console.log(' ✓ \"Reply STOP to opt out\" on every SMS');\n console.log(' ✓ Rocky → Michael / RateRight');\n console.log(' ✓ 9.9% → $0 for workers');\n console.log(' ✓ \"FREE to use\" → $50 flat fee for contractors');\n console.log(' ✓ \"No fees until you get paid\" → \"Zero fees. You keep 100%\"');\n console.log(' ✓ Platform Seeding: both template + message_template fields');\n console.log('');\n\n\n[70 more lines in file. Use offset=370 to continue]"}],"isError":false,"timestamp":1771614124248}} {"type":"message","id":"d3db5fd4","parentId":"3ebec489","timestamp":"2026-02-20T19:02:33.225Z","message":{"role":"assistant","content":[{"type":"text","text":"The SMS scripts are already updated — they're migration scripts that fix the old 9.9% values. The references are just in comments/logs describing what they changed. Those are fine to leave.\n\nNow I have all the context. Let me make all the edits:"},{"type":"toolCall","id":"toolu_01WmyJuFpqdnhag42Wfx7zXT","name":"edit","arguments":{"path":"/home/ccuser/rateright-growth/src/services/ai.js","oldText":"- 9.9% platform fee vs 30-40% agency margins - massive savings\n- Contractors post jobs, workers apply - direct relationship","newText":"- $50 flat fee per hire vs 30-40% agency margins - massive savings\n- Contractors post jobs, workers apply - direct relationship"}},{"type":"toolCall","id":"toolu_0138eK1ee6SbC6dc3uQiffXc","name":"edit","arguments":{"path":"/home/ccuser/rateright-growth/src/services/ai.js","oldText":"connecting contractors with workers at 9.9% fee vs 30-40% agency margins)","newText":"connecting contractors with workers at a $50 flat fee per hire vs 30-40% agency margins)"}},{"type":"toolCall","id":"toolu_01UoYtwECM8QUgN6cmM1NefA","name":"edit","arguments":{"path":"/home/ccuser/rateright-growth/src/services/ai.js","oldText":"- For contractors: RateRight is FREE (workers pay 9.9% fee)\n- For workers: mention the 9.9% platform fee honestly`;","newText":"- For contractors: contractors pay a flat $50 per successful hire\n- For workers: workers pay nothing — they keep 100% of what they earn`;"}},{"type":"toolCall","id":"toolu_019TwUVpBDA8Z6BsYMo9uXkh","name":"edit","arguments":{"path":"/home/ccuser/rateright-growth/src/services/ai.js","oldText":"- For contractors: RateRight is FREE (workers pay 9.9%)\n- For workers: mention the 9.9% platform fee honestly\n\nTHE SITUATION:","newText":"- For contractors: contractors pay a flat $50 per successful hire\n- For workers: workers pay nothing — they keep 100% of what they earn\n\nTHE SITUATION:"}},{"type":"toolCall","id":"toolu_01SjD1FeXQn4KrFFqrEMJ8mt","name":"edit","arguments":{"path":"/home/ccuser/rateright-growth/src/services/ai.js","oldText":"- RateRight charges just 9.9%","newText":"- RateRight charges just $50 flat fee per hire"}},{"type":"toolCall","id":"toolu_01YUvrhmusFmMTNQErSVy5eQ","name":"edit","arguments":{"path":"/home/ccuser/rateright-growth/src/services/ai.js","oldText":"- 9.9% platform fee vs 30-40% agency margins - massive savings\n- Direct relationship between you and the worker - no middleman","newText":"- $50 flat fee per hire vs 30-40% agency margins - massive savings\n- Direct relationship between you and the worker - no middleman"}},{"type":"toolCall","id":"toolu_01XU8FhERbQZoa9a51aHyRK9","name":"edit","arguments":{"path":"/home/ccuser/rateright-growth/src/services/ai.js","oldText":"- PRICE: \"Agencies take 30-40% cut. On RateRight you post the job, workers apply direct, and we take just 9.9%. You're paying $${agencyMarkup}/week in agency fat - with us that's $${weeklySavings} back in your pocket.\"","newText":"- PRICE: \"Agencies take 30-40% cut. On RateRight you post the job, workers apply direct, and it's just a flat $50 per hire. You're paying $${agencyMarkup}/week in agency fat - with us that's $${weeklySavings} back in your pocket.\""}},{"type":"toolCall","id":"toolu_016EQ8UvSkds4yoHk8VEz7uv","name":"edit","arguments":{"path":"/home/ccuser/rateright-growth/src/services/ai.js","oldText":"- HAPPY WITH CURRENT AGENCY: \"What are you paying in margins? Because agencies take 30-40% on top. With RateRight you deal direct with workers, see their ratings, and pay just 9.9%. No middleman.\"","newText":"- HAPPY WITH CURRENT AGENCY: \"What are you paying in margins? Because agencies take 30-40% on top. With RateRight you deal direct with workers, see their ratings, and pay just a flat $50 per hire. No middleman.\""}},{"type":"toolCall","id":"toolu_0196SfhCvVoKMZFV7XAqCj4h","name":"edit","arguments":{"path":"/home/ccuser/rateright-growth/src/services/ai.js","oldText":"- RateRight is a worker marketplace (9.9% fee vs 30-40% agency margins)","newText":"- RateRight is a worker marketplace ($50 flat fee per hire vs 30-40% agency margins)"}},{"type":"toolCall","id":"toolu_01KKc4ENGdY9BjusgLoVAZLZ","name":"edit","arguments":{"path":"/home/ccuser/rateright-growth/src/services/ai.js","oldText":"- Workers: 9.9% platform fee (vs 30-40% agency fees)","newText":"- Workers: pay nothing — keep 100% of what they earn"}},{"type":"toolCall","id":"toolu_01PNtysiNaoqKZb4bDiJpk9e","name":"edit","arguments":{"path":"/home/ccuser/rateright-growth/src/services/perplexity.js","oldText":"9.9% fee vs 30-40% agency margins, no middleman). Focus on their likely pain points.\"","newText":"$50 flat fee per hire vs 30-40% agency margins, no middleman). Focus on their likely pain points.\""}},{"type":"toolCall","id":"toolu_011dGmznAeNzMCriuqBPACBk","name":"edit","arguments":{"path":"/home/ccuser/rateright-growth/src/services/perplexity.js","oldText":"(9.9% fee vs 30-40% agency margins). Focus on their role and likely pain points with finding reliable workers.\"","newText":"($50 flat fee per hire vs 30-40% agency margins). Focus on their role and likely pain points with finding reliable workers.\""}},{"type":"toolCall","id":"toolu_01EbAHsubQeL4okYwfEnguCv","name":"edit","arguments":{"path":"/home/ccuser/rateright-growth/src/services/compliance.js","oldText":"'free': 'For contractors: \"no cost to you\". For workers: mention the 9.9% fee',","newText":"'free': 'For contractors: \"$50 flat fee per hire\". For workers: \"you pay nothing — keep 100%\"',"}},{"type":"toolCall","id":"toolu_01GNjVSRirfafwM4dUYdgXp5","name":"edit","arguments":{"path":"/home/ccuser/rateright-growth/src/services/stageDiagnosis.js","oldText":"- 9.9% fee vs 30-40% agency margins","newText":"- $50 flat fee per hire vs 30-40% agency margins"}},{"type":"toolCall","id":"toolu_01NMVMhdDNpSJ91SLNhL8ifS","name":"edit","arguments":{"path":"/home/ccuser/rateright-growth/src/routes/playbook.js","oldText":"? 'Connect quality tradies with jobs. Only pay 9.9% when you get paid - no upfront costs.'","newText":"? 'Connect quality tradies with jobs. Workers pay nothing — you keep 100% of what you earn.'"}},{"type":"toolCall","id":"toolu_01A8YhxP2q6kE4WRMrzS94au","name":"edit","arguments":{"path":"/home/ccuser/rateright-growth/src/routes/playbook.js","oldText":"? 'Connect tradies with jobs. 9.9% only when you get paid.'","newText":"? 'Connect tradies with jobs. Workers pay nothing — keep 100%.'"}},{"type":"toolCall","id":"toolu_01NmWHpG7hEun8tU1LwTW4pH","name":"edit","arguments":{"path":"/home/ccuser/rateright-growth/admin/src/components/LiveCopilot.jsx","oldText":"response: \"Yes, at 9.9% we're typically 30-50% less than traditional agencies, with no lock-in contracts.\",","newText":"response: \"Yes, at $50 flat fee per hire, we're a fraction of what agencies charge — no lock-in contracts.\","}},{"type":"toolCall","id":"toolu_01FQoNmnNiYHAvwXwn7mF7FN","name":"edit","arguments":{"path":"/home/ccuser/rateright-growth/admin/src/components/CallSalesFunnel.jsx","oldText":"script: \"We connect you with pre-vetted workers at just 9.9% - no lock-in contracts.\",","newText":"script: \"We connect you with pre-vetted workers for just $50 per hire - no lock-in contracts.\","}},{"type":"toolCall","id":"toolu_01S8AJ3hrWB6jGKo4fhZLMrc","name":"edit","arguments":{"path":"/home/ccuser/rateright-growth/admin/src/components/EliteCallUI.jsx","oldText":"return script.value_props?.[0]?.prop || \"We connect you with pre-vetted workers at just 9.9% - no lock-in contracts.\";","newText":"return script.value_props?.[0]?.prop || \"We connect you with pre-vetted workers for just $50 per hire - no lock-in contracts.\";"}}],"api":"anthropic-messages","provider":"anthropic","model":"claude-opus-4-6","usage":{"input":1,"output":2870,"cacheRead":16768,"cacheWrite":1364,"totalTokens":21003,"cost":{"input":0.000005,"output":0.07175000000000001,"cacheRead":0.008383999999999999,"cacheWrite":0.008525,"total":0.08866400000000002}},"stopReason":"toolUse","timestamp":1771614124251}} {"type":"message","id":"b57be1bf","parentId":"d3db5fd4","timestamp":"2026-02-20T19:02:33.247Z","message":{"role":"toolResult","toolCallId":"toolu_01WmyJuFpqdnhag42Wfx7zXT","toolName":"edit","content":[{"type":"text","text":"Successfully replaced text in /home/ccuser/rateright-growth/src/services/ai.js."}],"details":{"diff":" ...\n 33 const prompt = `You are an elite sales intelligence AI for RateRight, Australia's worker marketplace.\n 34 \n 35 WHAT RATERIGHT IS:\n 36 - A marketplace that connects contractors DIRECTLY with workers (not an agency)\n- 37 - 9.9% platform fee vs 30-40% agency margins - massive savings\n+ 37 - $50 flat fee per hire vs 30-40% agency margins - massive savings\n 38 - Contractors post jobs, workers apply - direct relationship\n 39 - Rating system for worker reliability - see before you book\n 40 - Same-day matching - urgent jobs sorted in hours\n 41 - No lock-in contracts - use us when you need us\n ...","firstChangedLine":37},"isError":false,"timestamp":1771614153245}} {"type":"message","id":"2602250c","parentId":"b57be1bf","timestamp":"2026-02-20T19:02:33.257Z","message":{"role":"toolResult","toolCallId":"toolu_0138eK1ee6SbC6dc3uQiffXc","toolName":"edit","content":[{"type":"text","text":"Successfully replaced text in /home/ccuser/rateright-growth/src/services/ai.js."}],"details":{"diff":" ...\n 99 if (!openai) {\n 100 return { success: false, error: 'AI features not configured - OPENAI_API_KEY not set' };\n 101 }\n 102 \n- 103 const prompt = `You are an elite sales AI assistant analyzing a call with a potential customer for RateRight, Australia's worker marketplace (NOT an agency - a direct marketplace connecting contractors with workers at 9.9% fee vs 30-40% agency margins).\n+ 103 const prompt = `You are an elite sales AI assistant analyzing a call with a potential customer for RateRight, Australia's worker marketplace (NOT an agency - a direct marketplace connecting contractors with workers at a $50 flat fee per hire vs 30-40% agency margins).\n 104 \n 105 LEAD: ${lead.first_name} ${lead.last_name || ''} from ${lead.company || 'Unknown company'}\n 106 CALL DURATION: ${Math.floor(callDuration / 60)} minutes ${callDuration % 60} seconds\n 107 \n ...","firstChangedLine":103},"isError":false,"timestamp":1771614153254}} {"type":"message","id":"d9ce8efb","parentId":"2602250c","timestamp":"2026-02-20T19:02:33.267Z","message":{"role":"toolResult","toolCallId":"toolu_01UoYtwECM8QUgN6cmM1NefA","toolName":"edit","content":[{"type":"text","text":"Successfully replaced text in /home/ccuser/rateright-growth/src/services/ai.js."}],"details":{"diff":" ...\n 203 - NEVER use these phrases: ${(guidelines.banned_phrases || []).join(', ')}\n 204 - Max 1 exclamation mark per message\n 205 - Keep it conversational, not corporate\n 206 - Always include a clear next step\n- 207 - For contractors: RateRight is FREE (workers pay 9.9% fee)\n- 208 - For workers: mention the 9.9% platform fee honestly`;\n+ 207 - For contractors: contractors pay a flat $50 per successful hire\n+ 208 - For workers: workers pay nothing — they keep 100% of what they earn`;\n 209 \n 210 const prompt = isRefinement\n 211 ? `You are refining an SMS message for a RateRight sales rep.\n 212 ${brandVoiceRules}\n ...","firstChangedLine":207},"isError":false,"timestamp":1771614153265}} {"type":"message","id":"e2358258","parentId":"d9ce8efb","timestamp":"2026-02-20T19:02:33.276Z","message":{"role":"toolResult","toolCallId":"toolu_019TwUVpBDA8Z6BsYMo9uXkh","toolName":"edit","content":[{"type":"text","text":"Successfully replaced text in /home/ccuser/rateright-growth/src/services/ai.js."}],"details":{"diff":" ...\n 845 BRAND VOICE (IMPORTANT!):\n 846 - Tone: ${guidelines.tone_description}\n 847 - Use words like: ${(guidelines.tone_keywords || []).slice(0, 5).join(', ')}\n 848 - NEVER use: ${(guidelines.banned_words || []).join(', ')}\n- 849 - For contractors: RateRight is FREE (workers pay 9.9%)\n- 850 - For workers: mention the 9.9% platform fee honestly\n+ 849 - For contractors: contractors pay a flat $50 per successful hire\n+ 850 - For workers: workers pay nothing — they keep 100% of what they earn\n 851 \n 852 THE SITUATION:\n 853 ${leadContext.name} from ${leadContext.company}${leadContext.trade ? ` (${leadContext.trade} trade)` : ''} just said:\n 854 \"${objection}\"\n ...","firstChangedLine":849},"isError":false,"timestamp":1771614153273}} {"type":"message","id":"b5ba1393","parentId":"e2358258","timestamp":"2026-02-20T19:02:33.284Z","message":{"role":"toolResult","toolCallId":"toolu_01SjD1FeXQn4KrFFqrEMJ8mt","toolName":"edit","content":[{"type":"text","text":"Successfully replaced text in /home/ccuser/rateright-growth/src/services/ai.js."}],"details":{"diff":" ...\n 860 ${leadContext.previousObjections?.length > 0 ? `- They've objected before about: ${leadContext.previousObjections.join(', ')}` : ''}\n 861 \n 862 THE MATH (use this!):\n 863 - Agencies charge 30-40% margin on workers\n- 864 - RateRight charges just 9.9%\n+ 864 - RateRight charges just $50 flat fee per hire\n 865 - That's $${weeklySavings}/week savings per worker\n 866 - Or $${yearlySavingsPerWorker.toLocaleString()}/year per full-time worker\n 867 - For a team of 5 workers = $${(yearlySavingsPerWorker * 5).toLocaleString()}/year back in their pocket\n 868 \n ...","firstChangedLine":864},"isError":false,"timestamp":1771614153282}} {"type":"message","id":"b213ea1e","parentId":"b5ba1393","timestamp":"2026-02-20T19:02:33.298Z","message":{"role":"toolResult","toolCallId":"toolu_01YUvrhmusFmMTNQErSVy5eQ","toolName":"edit","content":[{"type":"text","text":"Successfully replaced text in /home/ccuser/rateright-growth/src/services/ai.js."}],"details":{"diff":" ...\n 867 - For a team of 5 workers = $${(yearlySavingsPerWorker * 5).toLocaleString()}/year back in their pocket\n 868 \n 869 WHAT RATERIGHT IS (GET THIS RIGHT!):\n 870 - A MARKETPLACE, not an agency - contractors post jobs, workers apply directly\n- 871 - 9.9% platform fee vs 30-40% agency margins - massive savings\n+ 871 - $50 flat fee per hire vs 30-40% agency margins - massive savings\n 872 - Direct relationship between you and the worker - no middleman\n 873 - Rating system - see worker reliability before you hire\n 874 - Same-day matching - post a job, get applicants within hours\n 875 - No lock-in contracts - use it when you need it\n ...","firstChangedLine":871},"isError":false,"timestamp":1771614153295}} {"type":"message","id":"94075479","parentId":"b213ea1e","timestamp":"2026-02-20T19:02:33.309Z","message":{"role":"toolResult","toolCallId":"toolu_01XU8FhERbQZoa9a51aHyRK9","toolName":"edit","content":[{"type":"text","text":"Successfully replaced text in /home/ccuser/rateright-growth/src/services/ai.js."}],"details":{"diff":" ...\n 874 - Same-day matching - post a job, get applicants within hours\n 875 - No lock-in contracts - use it when you need it\n 876 \n 877 OBJECTION PLAYBOOK:\n- 878 - PRICE: \"Agencies take 30-40% cut. On RateRight you post the job, workers apply direct, and we take just 9.9%. You're paying $${agencyMarkup}/week in agency fat - with us that's $${weeklySavings} back in your pocket.\"\n+ 878 - PRICE: \"Agencies take 30-40% cut. On RateRight you post the job, workers apply direct, and it's just a flat $50 per hire. You're paying $${agencyMarkup}/week in agency fat - with us that's $${weeklySavings} back in your pocket.\"\n 879 - ALREADY HAVE WORKERS: \"Perfect - keep them! But what happens when Dave calls in sick Monday morning and you've got a concrete pour? Post a job on RateRight, get applicants in hours.\"\n 880 - NEED TO THINK: \"Totally fair. What's the main thing you'd want to check? Happy to send you some numbers to look at.\"\n 881 - HAPPY WITH CURRENT AGENCY: \"What are you paying in margins? Because agencies take 30-40% on top. With RateRight you deal direct with workers, see their ratings, and pay just 9.9%. No middleman.\"\n 882 - TOO BUSY: \"I get it - that's exactly why tradies use us. 5 minutes to post a job, workers come to you. No hunting, no agencies, just blokes applying direct.\"\n ...","firstChangedLine":878},"isError":false,"timestamp":1771614153306}} {"type":"message","id":"af88358f","parentId":"94075479","timestamp":"2026-02-20T19:02:33.317Z","message":{"role":"toolResult","toolCallId":"toolu_016EQ8UvSkds4yoHk8VEz7uv","toolName":"edit","content":[{"type":"text","text":"Successfully replaced text in /home/ccuser/rateright-growth/src/services/ai.js."}],"details":{"diff":" ...\n 877 OBJECTION PLAYBOOK:\n 878 - PRICE: \"Agencies take 30-40% cut. On RateRight you post the job, workers apply direct, and it's just a flat $50 per hire. You're paying $${agencyMarkup}/week in agency fat - with us that's $${weeklySavings} back in your pocket.\"\n 879 - ALREADY HAVE WORKERS: \"Perfect - keep them! But what happens when Dave calls in sick Monday morning and you've got a concrete pour? Post a job on RateRight, get applicants in hours.\"\n 880 - NEED TO THINK: \"Totally fair. What's the main thing you'd want to check? Happy to send you some numbers to look at.\"\n- 881 - HAPPY WITH CURRENT AGENCY: \"What are you paying in margins? Because agencies take 30-40% on top. With RateRight you deal direct with workers, see their ratings, and pay just 9.9%. No middleman.\"\n+ 881 - HAPPY WITH CURRENT AGENCY: \"What are you paying in margins? Because agencies take 30-40% on top. With RateRight you deal direct with workers, see their ratings, and pay just a flat $50 per hire. No middleman.\"\n 882 - TOO BUSY: \"I get it - that's exactly why tradies use us. 5 minutes to post a job, workers come to you. No hunting, no agencies, just blokes applying direct.\"\n 883 - CONTRACTS/LOCKED IN: \"No contracts. Post one job, try it out. Most blokes try us once and stick around because the direct connection just works better.\"\n 884 \n 885 YOUR JOB RIGHT NOW:\n ...","firstChangedLine":881},"isError":false,"timestamp":1771614153315}} {"type":"message","id":"94394b09","parentId":"af88358f","timestamp":"2026-02-20T19:02:33.326Z","message":{"role":"toolResult","toolCallId":"toolu_0196SfhCvVoKMZFV7XAqCj4h","toolName":"edit","content":[{"type":"text","text":"Successfully replaced text in /home/ccuser/rateright-growth/src/services/ai.js."}],"details":{"diff":" ...\n 1635 PREVIOUS COMMUNICATIONS:\n 1636 ${historySummary}\n 1637 \n 1638 CONTEXT:\n-1639 - RateRight is a worker marketplace (9.9% fee vs 30-40% agency margins)\n+1639 - RateRight is a worker marketplace ($50 flat fee per hire vs 30-40% agency margins)\n 1640 - They're signing up again = high intent signal\n 1641 - This is a hot opportunity\n 1642 \n 1643 Generate ONE short insight (1-2 sentences) about why they might be back and how to approach them.\n ...","firstChangedLine":1639},"isError":false,"timestamp":1771614153324}} {"type":"message","id":"e75ed614","parentId":"94394b09","timestamp":"2026-02-20T19:02:33.335Z","message":{"role":"toolResult","toolCallId":"toolu_01KKc4ENGdY9BjusgLoVAZLZ","toolName":"edit","content":[{"type":"text","text":"Successfully replaced text in /home/ccuser/rateright-growth/src/services/ai.js."}],"details":{"diff":" ...\n 1817 ═══════════════════════════════════════════════════════════════\n 1818 ABOUT RATERIGHT (use this in your pitch):\n 1819 - Marketplace connecting contractors with workers DIRECTLY (not an agency)\n 1820 - Contractors: FREE to use, post jobs and get matched\n-1821 - Workers: 9.9% platform fee (vs 30-40% agency fees)\n+1821 - Workers: pay nothing — keep 100% of what they earn\n 1822 - Rating system shows worker reliability before booking\n 1823 - Same-day matching for urgent jobs\n 1824 ═══════════════════════════════════════════════════════════════\n 1825 \n ...","firstChangedLine":1821},"isError":false,"timestamp":1771614153332}} {"type":"message","id":"e9988d1b","parentId":"e75ed614","timestamp":"2026-02-20T19:02:33.343Z","message":{"role":"toolResult","toolCallId":"toolu_01PNtysiNaoqKZb4bDiJpk9e","toolName":"edit","content":[{"type":"text","text":"Successfully replaced text in /home/ccuser/rateright-growth/src/services/perplexity.js."}],"details":{"diff":" ...\n 115 \"linkedin_url\": \"LinkedIn company page URL if found, or null\",\n 116 \"facebook_url\": \"Facebook business page URL if found, or null\",\n 117 \"recent_projects\": [\"Recent project or news 1\", \"Recent project or news 2\"],\n 118 \"hiring_signals\": [\"Any hiring activity or growth signals\"],\n-119 \"ai_sales_angle\": \"Best approach for pitching RateRight (a marketplace where contractors post jobs and workers apply direct, 9.9% fee vs 30-40% agency margins, no middleman). Focus on their likely pain points.\"\n+119 \"ai_sales_angle\": \"Best approach for pitching RateRight (a marketplace where contractors post jobs and workers apply direct, $50 flat fee per hire vs 30-40% agency margins, no middleman). Focus on their likely pain points.\"\n 120 }\n 121 \n 122 IMPORTANT: Try hard to find the actual company website URL. Search for \"[company name] construction australia website\" if needed.\n 123 If you can't find specific information, make reasonable inferences based on the company name and industry.\n ...","firstChangedLine":119},"isError":false,"timestamp":1771614153341}} {"type":"message","id":"2473a725","parentId":"e9988d1b","timestamp":"2026-02-20T19:02:33.349Z","message":{"role":"toolResult","toolCallId":"toolu_011dGmznAeNzMCriuqBPACBk","toolName":"edit","content":[{"type":"text","text":"Successfully replaced text in /home/ccuser/rateright-growth/src/services/perplexity.js."}],"details":{"diff":" ...\n 271 \"Mention [local team/event] if they're a fan\",\n 272 \"They [posted/mentioned] something about [topic] recently\"\n 273 ],\n 274 \n-275 \"ai_talking_points\": \"Personalized talking points for pitching RateRight - a marketplace where they post jobs and workers apply direct (9.9% fee vs 30-40% agency margins). Focus on their role and likely pain points with finding reliable workers.\"\n+275 \"ai_talking_points\": \"Personalized talking points for pitching RateRight - a marketplace where they post jobs and workers apply direct ($50 flat fee per hire vs 30-40% agency margins). Focus on their role and likely pain points with finding reliable workers.\"\n 276 }\n 277 \n 278 TIPS FOR FINDING PERSONAL INFO:\n 279 - Check LinkedIn for interests, volunteer work, posts about hobbies\n ...","firstChangedLine":275},"isError":false,"timestamp":1771614153347}} {"type":"message","id":"324b9ec9","parentId":"2473a725","timestamp":"2026-02-20T19:02:33.355Z","message":{"role":"toolResult","toolCallId":"toolu_01EbAHsubQeL4okYwfEnguCv","toolName":"edit","content":[{"type":"text","text":"Successfully replaced text in /home/ccuser/rateright-growth/src/services/compliance.js."}],"details":{"diff":" ...\n 309 'guaranteed': 'Try: \"we can help you\" or \"you\\'ll likely see\"',\n 310 'promise': 'Try: \"we aim to\" or \"our goal is\"',\n 311 'best': 'Try: \"great\" or \"solid\"',\n 312 'cheapest': 'Try: \"competitive\" or \"fair\"',\n-313 'free': 'For contractors: \"no cost to you\". For workers: mention the 9.9% fee',\n+313 'free': 'For contractors: \"$50 flat fee per hire\". For workers: \"you pay nothing — keep 100%\"',\n 314 'urgent': 'Try: \"when you get a chance\" or \"worth looking at\"',\n 315 'final': 'Try: \"following up\" or \"checking in\"',\n 316 'hurry': 'Try: \"when you\\'re ready\" or \"no rush\"',\n 317 'exclusive': 'Try: \"available to you\" or \"you can access\"'\n ...","firstChangedLine":313},"isError":false,"timestamp":1771614153353}} {"type":"message","id":"dbaf48b4","parentId":"324b9ec9","timestamp":"2026-02-20T19:02:33.361Z","message":{"role":"toolResult","toolCallId":"toolu_01GNjVSRirfafwM4dUYdgXp5","toolName":"edit","content":[{"type":"text","text":"Successfully replaced text in /home/ccuser/rateright-growth/src/services/stageDiagnosis.js."}],"details":{"diff":" ...\n 230 LIKELY BLOCKER: ${blocker}\n 231 \n 232 RATERIGHT VALUE PROPS:\n 233 - Direct connection (no agency middleman)\n-234 - 9.9% fee vs 30-40% agency margins\n+234 - $50 flat fee per hire vs 30-40% agency margins\n 235 - Same-day matching for urgent jobs\n 236 - Rating system for reliability\n 237 - No lock-in contracts\n 238 \n ...","firstChangedLine":234},"isError":false,"timestamp":1771614153358}} {"type":"message","id":"0d090e18","parentId":"dbaf48b4","timestamp":"2026-02-20T19:02:33.368Z","message":{"role":"toolResult","toolCallId":"toolu_01NMVMhdDNpSJ91SLNhL8ifS","toolName":"edit","content":[{"type":"text","text":"Successfully replaced text in /home/ccuser/rateright-growth/src/routes/playbook.js."}],"details":{"diff":" ...\n 590 SENDER INFO:\n 591 - Name: Rocky McLoughlin\n 592 - Company: RateRight\n 593 - What we do: ${isWorker\n- 594 ? 'Connect quality tradies with jobs. Only pay 9.9% when you get paid - no upfront costs.'\n+ 594 ? 'Connect quality tradies with jobs. Workers pay nothing — you keep 100% of what you earn.'\n 595 : 'Connect contractors with quality tradies. FREE for contractors to use.'}\n 596 \n 597 LEAD CONTEXT:\n 598 - Name: ${lead.first_name || 'there'} (${lead.company || 'Unknown company'})\n ...","firstChangedLine":594},"isError":false,"timestamp":1771614153366}} {"type":"message","id":"c9cf4f25","parentId":"0d090e18","timestamp":"2026-02-20T19:02:33.375Z","message":{"role":"toolResult","toolCallId":"toolu_01A8YhxP2q6kE4WRMrzS94au","toolName":"edit","content":[{"type":"text","text":"Successfully replaced text in /home/ccuser/rateright-growth/src/routes/playbook.js."}],"details":{"diff":" ...\n 683 SENDER INFO:\n 684 - Name: Rocky McLoughlin\n 685 - Company: RateRight\n 686 - What we do: ${isWorker\n- 687 ? 'Connect tradies with jobs. 9.9% only when you get paid.'\n+ 687 ? 'Connect tradies with jobs. Workers pay nothing — keep 100%.'\n 688 : 'Connect contractors with quality tradies. FREE to use.'}\n 689 \n 690 LEAD:\n 691 - Name: ${lead.first_name || 'there'}\n ...","firstChangedLine":687},"isError":false,"timestamp":1771614153372}} {"type":"message","id":"f8911661","parentId":"c9cf4f25","timestamp":"2026-02-20T19:02:33.381Z","message":{"role":"toolResult","toolCallId":"toolu_01NmWHpG7hEun8tU1LwTW4pH","toolName":"edit","content":[{"type":"text","text":"Successfully replaced text in /home/ccuser/rateright-growth/admin/src/components/LiveCopilot.jsx."}],"details":{"diff":" ...\n 80 keyPoint: \"Qualify the opportunity!\",\n 81 },\n 82 'cheaper': {\n 83 type: 'value',\n- 84 response: \"Yes, at 9.9% we're typically 30-50% less than traditional agencies, with no lock-in contracts.\",\n+ 84 response: \"Yes, at $50 flat fee per hire, we're a fraction of what agencies charge — no lock-in contracts.\",\n 85 followUp: \"Would you like me to calculate the savings based on your team size?\",\n 86 keyPoint: \"Reinforce the value!\",\n 87 },\n 88 default: {\n ...","firstChangedLine":84},"isError":false,"timestamp":1771614153378}} {"type":"message","id":"a654fa21","parentId":"f8911661","timestamp":"2026-02-20T19:02:33.387Z","message":{"role":"toolResult","toolCallId":"toolu_01FQoNmnNiYHAvwXwn7mF7FN","toolName":"edit","content":[{"type":"text","text":"Successfully replaced text in /home/ccuser/rateright-growth/admin/src/components/CallSalesFunnel.jsx."}],"details":{"diff":" ...\n 29 \"How many workers do you typically need on a job?\"\n 30 ]\n 31 },\n 32 value_prop: {\n- 33 script: \"We connect you with pre-vetted workers at just 9.9% - no lock-in contracts.\",\n+ 33 script: \"We connect you with pre-vetted workers for just $50 per hire - no lock-in contracts.\",\n 34 tip: \"Focus on their pain points. Make it about them.\",\n 35 alternatives: [\n 36 \"Most of our contractors find workers within 24 hours.\",\n 37 \"You only pay when they work - no upfront fees.\",\n ...","firstChangedLine":33},"isError":false,"timestamp":1771614153384}} {"type":"message","id":"46696ccc","parentId":"a654fa21","timestamp":"2026-02-20T19:02:33.393Z","message":{"role":"toolResult","toolCallId":"toolu_01S8AJ3hrWB6jGKo4fhZLMrc","toolName":"edit","content":[{"type":"text","text":"Successfully replaced text in /home/ccuser/rateright-growth/admin/src/components/EliteCallUI.jsx."}],"details":{"diff":" ...\n 139 return script.opening || openingLine || \"Hey, it's [your name] from RateRight. How's it going?\";\n 140 case 'discovery':\n 141 return script.discovery_questions?.[0]?.question || \"What's your biggest challenge finding workers right now?\";\n 142 case 'value_prop':\n-143 return script.value_props?.[0]?.prop || \"We connect you with pre-vetted workers at just 9.9% - no lock-in contracts.\";\n+143 return script.value_props?.[0]?.prop || \"We connect you with pre-vetted workers for just $50 per hire - no lock-in contracts.\";\n 144 case 'objections':\n 145 return \"Listen for concerns and address them directly.\";\n 146 case 'close':\n 147 return script.closing_techniques?.[0]?.script || \"Let me get you set up - it takes about 2 minutes. What's your email?\";\n ...","firstChangedLine":143},"isError":false,"timestamp":1771614153390}} {"type":"message","id":"38ed7083","parentId":"46696ccc","timestamp":"2026-02-20T19:02:37.849Z","message":{"role":"assistant","content":[{"type":"text","text":"All 19 edits applied. Let me verify no 9.9% references remain (excluding the SMS migration scripts which just document what they changed):"},{"type":"toolCall","id":"toolu_01CQB9d8rMUrH7UCbnuZ1Lzs","name":"exec","arguments":{"command":"cd /home/ccuser/rateright-growth && grep -rn \"9\\.9%\" --include=\"*.js\" --include=\"*.jsx\" --include=\"*.ts\" --include=\"*.tsx\" ."}}],"api":"anthropic-messages","provider":"anthropic","model":"claude-opus-4-6","usage":{"input":1,"output":130,"cacheRead":10107,"cacheWrite":11812,"totalTokens":22050,"cost":{"input":0.000005,"output":0.0032500000000000003,"cacheRead":0.0050535,"cacheWrite":0.073825,"total":0.0821335}},"stopReason":"toolUse","timestamp":1771614153393}} {"type":"message","id":"1fdbf300","parentId":"38ed7083","timestamp":"2026-02-20T19:02:38.117Z","message":{"role":"toolResult","toolCallId":"toolu_01CQB9d8rMUrH7UCbnuZ1Lzs","toolName":"exec","content":[{"type":"text","text":"./public/assets/index-2HMepUD5.js:18: `),()=>{D.contains(R)&&D.removeChild(R)}},[s]),c.jsx(JA,{isPresent:s,childRef:d,sizeRef:f,children:b.cloneElement(t,{ref:y})})}const e2=({children:t,initial:s,isPresent:i,onExitComplete:l,custom:o,presenceAffectsLayout:d,mode:f,anchorX:m,root:p})=>{const y=bh(t2),x=b.useId();let g=!0,w=b.useMemo(()=>(g=!1,{id:x,initial:s,isPresent:i,custom:o,onExitComplete:S=>{y.set(S,!0);for(const T of y.values())if(!T)return;l&&l()},register:S=>(y.set(S,!1),()=>y.delete(S))}),[i,y,l]);return d&&g&&(w={...w}),b.useMemo(()=>{y.forEach((S,T)=>y.set(T,!1))},[i]),b.useEffect(()=>{!i&&!y.size&&l&&l()},[i]),f===\"popLayout\"&&(t=c.jsx(WA,{isPresent:i,anchorX:m,root:p,children:t})),c.jsx(Cc.Provider,{value:w,children:t})};function t2(){return new Map}function rw(t=!0){const s=b.useContext(Cc);if(s===null)return[!0,null];const{isPresent:i,onExitComplete:l,register:o}=s,d=b.useId();b.useEffect(()=>{if(t)return o(d)},[t]);const f=b.useCallback(()=>t&&l&&l(d),[d,l,t]);return!i&&l?[!1,f]:[!0]}const $o=t=>t.key||\"\";function yx(t){const s=[];return b.Children.forEach(t,i=>{b.isValidElement(i)&&s.push(i)}),s}const si=({children:t,custom:s,initial:i=!0,onExitComplete:l,presenceAffectsLayout:o=!0,mode:d=\"sync\",propagate:f=!1,anchorX:m=\"left\",root:p})=>{const[y,x]=rw(f),g=b.useMemo(()=>yx(t),[t]),w=f&&!y?[]:g.map($o),S=b.useRef(!0),T=b.useRef(g),N=bh(()=>new Map),R=b.useRef(new Set),[D,A]=b.useState(g),[C,B]=b.useState(g);Vb(()=>{S.current=!1,T.current=g;for(let P=0;P{const H=$o(P),z=f&&!y?!1:g===C||w.includes(H),X=()=>{if(R.current.has(H))return;if(R.current.add(H),N.has(H))N.set(H,!0);else return;let te=!0;N.forEach(Y=>{Y||(te=!1)}),te&&(F?.(),B(T.current),f&&x?.(),l&&l())};return c.jsx(e2,{isPresent:z,initial:!S.current||i?void 0:!1,custom:s,presenceAffectsLayout:o,mode:d,root:p,onExitComplete:z?void 0:X,anchorX:m,children:P},H)})})},ow=b.createContext({strict:!1}),xx={animation:[\"animate\",\"variants\",\"whileHover\",\"whileTap\",\"exit\",\"whileInView\",\"whileFocus\",\"whileDrag\"],exit:[\"exit\"],drag:[\"drag\",\"dragControls\"],focus:[\"whileFocus\"],hover:[\"whileHover\",\"onHoverStart\",\"onHoverEnd\"],tap:[\"whileTap\",\"onTap\",\"onTapStart\",\"onTapCancel\"],pan:[\"onPan\",\"onPanStart\",\"onPanSessionStart\",\"onPanEnd\"],inView:[\"whileInView\",\"onViewportEnter\",\"onViewportLeave\"],layout:[\"layout\",\"layoutId\"]};let bx=!1;function n2(){if(bx)return;const t={};for(const s in xx)t[s]={isEnabled:i=>xx[s].some(l=>!!i[l])};Bv(t),bx=!0}function cw(){return n2(),qC()}function s2(t){const s=cw();for(const i in t)s[i]={...s[i],...t[i]};Bv(s)}const a2=new Set([\"animate\",\"exit\",\"variants\",\"initial\",\"style\",\"values\",\"variants\",\"transition\",\"transformTemplate\",\"custom\",\"inherit\",\"onBeforeLayoutMeasure\",\"onAnimationStart\",\"onAnimationComplete\",\"onUpdate\",\"onDragStart\",\"onDrag\",\"onDragEnd\",\"onMeasureDragConstraints\",\"onDirectionLock\",\"onDragTransitionEnd\",\"_dragX\",\"_dragY\",\"onHoverStart\",\"onHoverEnd\",\"onViewportEnter\",\"onViewportLeave\",\"globalTapTarget\",\"ignoreStrict\",\"viewport\"]);function fc(t){return t.startsWith(\"while\")||t.startsWith(\"drag\")&&t!==\"draggable\"||t.startsWith(\"layout\")||t.startsWith(\"onTap\")||t.startsWith(\"onPan\")||t.startsWith(\"onLayout\")||a2.has(t)}let uw=t=>!fc(t);function i2(t){typeof t==\"function\"&&(uw=s=>s.startsWith(\"on\")?!fc(s):t(s))}try{i2(require(\"@emotion/is-prop-valid\").default)}catch{}function l2(t,s,i){const l={};for(const o in t)o===\"values\"&&typeof t.values==\"object\"||(uw(o)||i===!0&&fc(o)||!s&&!fc(o)||t.draggable&&o.startsWith(\"onDrag\"))&&(l[o]=t[o]);return l}const Dc=b.createContext({});function r2(t,s){if(Ec(t)){const{initial:i,animate:l}=t;return{initial:i===!1||mr(i)?i:void 0,animate:mr(l)?l:void 0}}return t.inherit!==!1?s:{}}function o2(t){const{initial:s,animate:i}=r2(t,b.useContext(Dc));return b.useMemo(()=>({initial:s,animate:i}),[vx(s),vx(i)])}function vx(t){return Array.isArray(t)?t.join(\" \"):t}const Xh=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function dw(t,s,i){for(const l in s)!$t(s[l])&&!$v(l,i)&&(t[l]=s[l])}function c2({transformTemplate:t},s){return b.useMemo(()=>{const i=Xh();return Gh(i,s,t),Object.assign({},i.vars,i.style)},[s])}function u2(t,s){const i=t.style||{},l={};return dw(l,i,t),Object.assign(l,c2(t,s)),l}function d2(t,s){const i={},l=u2(t,s);return t.drag&&t.dragListener!==!1&&(i.draggable=!1,l.userSelect=l.WebkitUserSelect=l.WebkitTouchCallout=\"none\",l.touchAction=t.drag===!0?\"none\":`pan-${t.drag===\"x\"?\"y\":\"x\"}`),t.tabIndex===void 0&&(t.onTap||t.onTapStart||t.whileTap)&&(i.tabIndex=0),i.style=l,i}const fw=()=>({...Xh(),attrs:{}});function f2(t,s,i,l){const o=b.useMemo(()=>{const d=fw();return Gv(d,s,Fv(l),t.transformTemplate,t.style),{...d.attrs,style:{...d.style}}},[s]);if(t.style){const d={};dw(d,t.style,t),o.style={...d,...o.style}}return o}const h2=[\"animate\",\"circle\",\"defs\",\"desc\",\"ellipse\",\"g\",\"image\",\"line\",\"filter\",\"marker\",\"mask\",\"metadata\",\"path\",\"pattern\",\"polygon\",\"polyline\",\"rect\",\"stop\",\"switch\",\"symbol\",\"svg\",\"text\",\"tspan\",\"use\",\"view\"];function Kh(t){return typeof t!=\"string\"||t.includes(\"-\")?!1:!!(h2.indexOf(t)>-1||/[A-Z]/u.test(t))}function m2(t,s,i,{latestValues:l},o,d=!1,f){const p=(f??Kh(t)?f2:d2)(s,l,o,t),y=l2(s,typeof t==\"string\",d),x=t!==b.Fragment?{...y,...p,ref:i}:{},{children:g}=s,w=b.useMemo(()=>$t(g)?g.get():g,[g]);return b.createElement(t,{...x,children:w})}function p2({scrapeMotionValuesFromProps:t,createRenderState:s},i,l,o){return{latestValues:g2(i,l,o,t),renderState:s()}}function g2(t,s,i,l){const o={},d=l(t,{});for(const w in d)o[w]=ec(d[w]);let{initial:f,animate:m}=t;const p=Ec(t),y=zv(t);s&&y&&!p&&t.inherit!==!1&&(f===void 0&&(f=s.initial),m===void 0&&(m=s.animate));let x=i?i.initial===!1:!1;x=x||f===!1;const g=x?m:f;if(g&&typeof g!=\"boolean\"&&!Ac(g)){const w=Array.isArray(g)?g:[g];for(let S=0;S(s,i)=>{const l=b.useContext(Dc),o=b.useContext(Cc),d=()=>p2(t,s,l,o);return i?d():bh(d)},y2=hw({scrapeMotionValuesFromProps:Yh,createRenderState:Xh}),x2=hw({scrapeMotionValuesFromProps:Xv,createRenderState:fw}),b2=Symbol.for(\"motionComponentSymbol\");function v2(t,s,i){const l=b.useRef(i);b.useInsertionEffect(()=>{l.current=i});const o=b.useRef(null);return b.useCallback(d=>{d&&t.onMount?.(d),s&&(d?s.mount(d):s.unmount());const f=l.current;if(typeof f==\"function\")if(d){const m=f(d);typeof m==\"function\"&&(o.current=m)}else o.current?(o.current(),o.current=null):f(d);else f&&(f.current=d)},[s])}const mw=b.createContext({});function sr(t){return t&&typeof t==\"object\"&&Object.prototype.hasOwnProperty.call(t,\"current\")}function w2(t,s,i,l,o,d){const{visualElement:f}=b.useContext(Dc),m=b.useContext(ow),p=b.useContext(Cc),y=b.useContext(Fh).reducedMotion,x=b.useRef(null);l=l||m.renderer,!x.current&&l&&(x.current=l(t,{visualState:s,parent:f,props:i,presenceContext:p,blockInitialAnimation:p?p.initial===!1:!1,reducedMotionConfig:y,isSVG:d}));const g=x.current,w=b.useContext(mw);g&&!g.projection&&o&&(g.type===\"html\"||g.type===\"svg\")&&S2(x.current,i,o,w);const S=b.useRef(!1);b.useInsertionEffect(()=>{g&&S.current&&g.update(i,p)});const T=i[wv],N=b.useRef(!!T&&!window.MotionHandoffIsComplete?.(T)&&window.MotionHasOptimisedAnimation?.(T));return Vb(()=>{g&&(S.current=!0,window.MotionIsMounted=!0,g.updateFeatures(),g.scheduleRenderMicrotask(),N.current&&g.animationState&&g.animationState.animateChanges())}),b.useEffect(()=>{g&&(!N.current&&g.animationState&&g.animationState.animateChanges(),N.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(T)}),N.current=!1),g.enteringChildren=void 0)}),g}function S2(t,s,i,l){const{layoutId:o,layout:d,drag:f,dragConstraints:m,layoutScroll:p,layoutRoot:y,layoutCrossfade:x}=s;t.projection=new i(t.latestValues,s[\"data-framer-portal-id\"]?void 0:pw(t.parent)),t.projection.setOptions({layoutId:o,layout:d,alwaysMeasureLayout:!!f||m&&sr(m),visualElement:t,animationType:typeof d==\"string\"?d:\"both\",initialPromotionConfig:l,crossfade:x,layoutScroll:p,layoutRoot:y})}function pw(t){if(t)return t.options.allowProjection!==!1?t.projection:pw(t.parent)}function ff(t,{forwardMotionProps:s=!1,type:i}={},l,o){l&&s2(l);const d=i?i===\"svg\":Kh(t),f=d?x2:y2;function m(y,x){let g;const w={...b.useContext(Fh),...y,layoutId:j2(y)},{isStatic:S}=w,T=o2(y),N=f(y,S);if(!S&&Bb){T2();const R=N2(w);g=R.MeasureLayout,T.visualElement=w2(t,N,w,o,R.ProjectionNode,d)}return c.jsxs(Dc.Provider,{value:T,children:[g&&T.visualElement?c.jsx(g,{visualElement:T.visualElement,...w}):null,m2(t,y,v2(N,T.visualElement,x),N,S,s,d)]})}m.displayName=`motion.${typeof t==\"string\"?t:`create(${t.displayName??t.name??\"\"})`}`;const p=b.forwardRef(m);return p[b2]=t,p}function j2({layoutId:t}){const s=b.useContext(xh).id;return s&&t!==void 0?s+\"-\"+t:t}function T2(t,s){b.useContext(ow).strict}function N2(t){const s=cw(),{drag:i,layout:l}=s;if(!i&&!l)return{};const o={...i,...l};return{MeasureLayout:i?.isEnabled(t)||l?.isEnabled(t)?o.MeasureLayout:void 0,ProjectionNode:o.ProjectionNode}}function C2(t,s){if(typeof Proxy>\"u\")return ff;const i=new Map,l=(d,f)=>ff(d,f,t,s),o=(d,f)=>l(d,f);return new Proxy(o,{get:(d,f)=>f===\"create\"?l:(i.has(f)||i.set(f,ff(f,void 0,t,s)),i.get(f))})}const A2=(t,s)=>s.isSVG??Kh(t)?new iA(s):new WC(s,{allowProjection:t!==b.Fragment});class E2 extends Na{constructor(s){super(s),s.animationState||(s.animationState=uA(s))}updateAnimationControlsSubscription(){const{animate:s}=this.node.getProps();Ac(s)&&(this.unmountControls=s.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:s}=this.node.getProps(),{animate:i}=this.node.prevProps||{};s!==i&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}}let D2=0;class k2 extends Na{constructor(){super(...arguments),this.id=D2++}update(){if(!this.node.presenceContext)return;const{isPresent:s,onExitComplete:i}=this.node.presenceContext,{isPresent:l}=this.node.prevPresenceContext||{};if(!this.node.animationState||s===l)return;const o=this.node.animationState.setActive(\"exit\",!s);i&&!s&&o.then(()=>{i(this.id)})}mount(){const{register:s,onExitComplete:i}=this.node.presenceContext||{};i&&i(this.id),s&&(this.unmount=s(this.id))}unmount(){}}const R2={animation:{Feature:E2},exit:{Feature:k2}};function jr(t){return{point:{x:t.pageX,y:t.pageY}}}const M2=t=>s=>qh(s)&&t(s,jr(s));function rr(t,s,i,l){return pr(t,s,M2(i),l)}const gw=({current:t})=>t?t.ownerDocument.defaultView:null,wx=(t,s)=>Math.abs(t-s);function O2(t,s){const i=wx(t.x,s.x),l=wx(t.y,s.y);return Math.sqrt(i**2+l**2)}const Sx=new Set([\"auto\",\"scroll\"]);class yw{constructor(s,i,{transformPagePoint:l,contextWindow:o=window,dragSnapToOrigin:d=!1,distanceThreshold:f=3,element:m}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=S=>{this.handleScroll(S.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const S=mf(this.lastMoveEventInfo,this.history),T=this.startEvent!==null,N=O2(S.offset,{x:0,y:0})>=this.distanceThreshold;if(!T&&!N)return;const{point:R}=S,{timestamp:D}=Bt;this.history.push({...R,timestamp:D});const{onStart:A,onMove:C}=this.handlers;T||(A&&A(this.lastMoveEvent,S),this.startEvent=this.lastMoveEvent),C&&C(this.lastMoveEvent,S)},this.handlePointerMove=(S,T)=>{this.lastMoveEvent=S,this.lastMoveEventInfo=hf(T,this.transformPagePoint),We.update(this.updatePoint,!0)},this.handlePointerUp=(S,T)=>{this.end();const{onEnd:N,onSessionEnd:R,resumeAnimation:D}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&D&&D(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const A=mf(S.type===\"pointercancel\"?this.lastMoveEventInfo:hf(T,this.transformPagePoint),this.history);this.startEvent&&N&&N(S,A),R&&R(S,A)},!qh(s))return;this.dragSnapToOrigin=d,this.handlers=i,this.transformPagePoint=l,this.distanceThreshold=f,this.contextWindow=o||window;const p=jr(s),y=hf(p,this.transformPagePoint),{point:x}=y,{timestamp:g}=Bt;this.history=[{...x,timestamp:g}];const{onSessionStart:w}=i;w&&w(s,mf(y,this.history)),this.removeListeners=vr(rr(this.contextWindow,\"pointermove\",this.handlePointerMove),rr(this.contextWindow,\"pointerup\",this.handlePointerUp),rr(this.contextWindow,\"pointercancel\",this.handlePointerUp)),m&&this.startScrollTracking(m)}startScrollTracking(s){let i=s.parentElement;for(;i;){const l=getComputedStyle(i);(Sx.has(l.overflowX)||Sx.has(l.overflowY))&&this.scrollPositions.set(i,{x:i.scrollLeft,y:i.scrollTop}),i=i.parentElement}this.scrollPositions.set(window,{x:window.scrollX,y:window.scrollY}),window.addEventListener(\"scroll\",this.onElementScroll,{capture:!0,passive:!0}),window.addEventListener(\"scroll\",this.onWindowScroll,{passive:!0}),this.removeScrollListeners=()=>{window.removeEventListener(\"scroll\",this.onElementScroll,{capture:!0}),window.removeEventListener(\"scroll\",this.onWindowScroll)}}handleScroll(s){const i=this.scrollPositions.get(s);if(!i)return;const l=s===window,o=l?{x:window.scrollX,y:window.scrollY}:{x:s.scrollLeft,y:s.scrollTop},d={x:o.x-i.x,y:o.y-i.y};d.x===0&&d.y===0||(l?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=d.x,this.lastMoveEventInfo.point.y+=d.y):this.history.length>0&&(this.history[0].x-=d.x,this.history[0].y-=d.y),this.scrollPositions.set(s,o),We.update(this.updatePoint,!0))}updateHandlers(s){this.handlers=s}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),va(this.updatePoint)}}function hf(t,s){return s?{point:s(t.point)}:t}function jx(t,s){return{x:t.x-s.x,y:t.y-s.y}}function mf({point:t},s){return{point:t,delta:jx(t,xw(s)),offset:jx(t,_2(s)),velocity:L2(s,.1)}}function _2(t){return t[0]}function xw(t){return t[t.length-1]}function L2(t,s){if(t.length<2)return{x:0,y:0};let i=t.length-1,l=null;const o=xw(t);for(;i>=0&&(l=t[i],!(o.timestamp-l.timestamp>Us(s)));)i--;if(!l)return{x:0,y:0};const d=Mn(o.timestamp-l.timestamp);if(d===0)return{x:0,y:0};const f={x:(o.x-l.x)/d,y:(o.y-l.y)/d};return f.x===1/0&&(f.x=0),f.y===1/0&&(f.y=0),f}function z2(t,{min:s,max:i},l){return s!==void 0&&ti&&(t=l?it(i,t,l.max):Math.min(t,i)),t}function Tx(t,s,i){return{min:s!==void 0?t.min+s:void 0,max:i!==void 0?t.max+i-(t.max-t.min):void 0}}function B2(t,{top:s,left:i,bottom:l,right:o}){return{x:Tx(t.x,i,o),y:Tx(t.y,s,l)}}function Nx(t,s){let i=s.min-t.min,l=s.max-t.max;return s.max-s.minl?i=dr(s.min,s.max-l,t.min):l>o&&(i=dr(t.min,t.max-o,s.min)),cs(0,1,i)}function P2(t,s){const i={};return s.min!==void 0&&(i.min=s.min-t.min),s.max!==void 0&&(i.max=s.max-t.min),i}const Xf=.35;function H2(t=Xf){return t===!1?t=0:t===!0&&(t=Xf),{x:Cx(t,\"left\",\"right\"),y:Cx(t,\"top\",\"bottom\")}}function Cx(t,s,i){return{min:Ax(t,s),max:Ax(t,i)}}function Ax(t,s){return typeof t==\"number\"?t:t[s]||0}const q2=new WeakMap;class I2{constructor(s){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=Tt(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=s}start(s,{snapToCursor:i=!1,distanceThreshold:l}={}){const{presenceContext:o}=this.visualElement;if(o&&o.isPresent===!1)return;const d=g=>{i?(this.stopAnimation(),this.snapToCursor(jr(g).point)):this.pauseAnimation()},f=(g,w)=>{this.stopAnimation();const{drag:S,dragPropagation:T,onDragStart:N}=this.getProps();if(S&&!T&&(this.openDragLock&&this.openDragLock(),this.openDragLock=kC(S),!this.openDragLock))return;this.latestPointerEvent=g,this.latestPanInfo=w,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Rn(D=>{let A=this.getAxisMotionValue(D).get()||0;if(rs.test(A)){const{projection:C}=this.visualElement;if(C&&C.layout){const B=C.layout.layoutBox[D];B&&(A=Jt(B)*(parseFloat(A)/100))}}this.originPoint[D]=A}),N&&We.postRender(()=>N(g,w)),Hf(this.visualElement,\"transform\");const{animationState:R}=this.visualElement;R&&R.setActive(\"whileDrag\",!0)},m=(g,w)=>{this.latestPointerEvent=g,this.latestPanInfo=w;const{dragPropagation:S,dragDirectionLock:T,onDirectionLock:N,onDrag:R}=this.getProps();if(!S&&!this.openDragLock)return;const{offset:D}=w;if(T&&this.currentDirection===null){this.currentDirection=$2(D),this.currentDirection!==null&&N&&N(this.currentDirection);return}this.updateAxis(\"x\",w.point,D),this.updateAxis(\"y\",w.point,D),this.visualElement.render(),R&&R(g,w)},p=(g,w)=>{this.latestPointerEvent=g,this.latestPanInfo=w,this.stop(g,w),this.latestPointerEvent=null,this.latestPanInfo=null},y=()=>Rn(g=>this.getAnimationState(g)===\"paused\"&&this.getAxisMotionValue(g).animation?.play()),{dragSnapToOrigin:x}=this.getProps();this.panSession=new yw(s,{onSessionStart:d,onStart:f,onMove:m,onSessionEnd:p,resumeAnimation:y},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:x,distanceThreshold:l,contextWindow:gw(this.visualElement),element:this.visualElement.current})}stop(s,i){const l=s||this.latestPointerEvent,o=i||this.latestPanInfo,d=this.isDragging;if(this.cancel(),!d||!o||!l)return;const{velocity:f}=o;this.startAnimation(f);const{onDragEnd:m}=this.getProps();m&&We.postRender(()=>m(l,o))}cancel(){this.isDragging=!1;const{projection:s,animationState:i}=this.visualElement;s&&(s.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:l}=this.getProps();!l&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),i&&i.setActive(\"whileDrag\",!1)}updateAxis(s,i,l){const{drag:o}=this.getProps();if(!l||!Go(s,o,this.currentDirection))return;const d=this.getAxisMotionValue(s);let f=this.originPoint[s]+l[s];this.constraints&&this.constraints[s]&&(f=z2(f,this.constraints[s],this.elastic[s])),d.set(f)}resolveConstraints(){const{dragConstraints:s,dragElastic:i}=this.getProps(),l=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,o=this.constraints;s&&sr(s)?this.constraints||(this.constraints=this.resolveRefConstraints()):s&&l?this.constraints=B2(l.layoutBox,s):this.constraints=!1,this.elastic=H2(i),o!==this.constraints&&l&&this.constraints&&!this.hasMutatedConstraints&&Rn(d=>{this.constraints!==!1&&this.getAxisMotionValue(d)&&(this.constraints[d]=P2(l.layoutBox[d],this.constraints[d]))})}resolveRefConstraints(){const{dragConstraints:s,onMeasureDragConstraints:i}=this.getProps();if(!s||!sr(s))return!1;const l=s.current,{projection:o}=this.visualElement;if(!o||!o.layout)return!1;const d=FC(l,o.root,this.visualElement.getTransformPagePoint());let f=V2(o.layout.layoutBox,d);if(i){const m=i($C(f));this.hasMutatedConstraints=!!m,m&&(f=Uv(m))}return f}startAnimation(s){const{drag:i,dragMomentum:l,dragElastic:o,dragTransition:d,dragSnapToOrigin:f,onDragTransitionEnd:m}=this.getProps(),p=this.constraints||{},y=Rn(x=>{if(!Go(x,i,this.currentDirection))return;let g=p&&p[x]||{};f&&(g={min:0,max:0});const w=o?200:1e6,S=o?40:1e7,T={type:\"inertia\",velocity:l?s[x]:0,bounceStiffness:w,bounceDamping:S,timeConstant:750,restDelta:1,restSpeed:10,...d,...g};return this.startAxisValueAnimation(x,T)});return Promise.all(y).then(m)}startAxisValueAnimation(s,i){const l=this.getAxisMotionValue(s);return Hf(this.visualElement,s),l.start(Bh(s,l,0,i,this.visualElement,!1))}stopAnimation(){Rn(s=>this.getAxisMotionValue(s).stop())}pauseAnimation(){Rn(s=>this.getAxisMotionValue(s).animation?.pause())}getAnimationState(s){return this.getAxisMotionValue(s).animation?.state}getAxisMotionValue(s){const i=`_drag${s.toUpperCase()}`,l=this.visualElement.getProps(),o=l[i];return o||this.visualElement.getValue(s,(l.initial?l.initial[s]:void 0)||0)}snapToCursor(s){Rn(i=>{const{drag:l}=this.getProps();if(!Go(i,l,this.currentDirection))return;const{projection:o}=this.visualElement,d=this.getAxisMotionValue(i);if(o&&o.layout){const{min:f,max:m}=o.layout.layoutBox[i],p=d.get()||0;d.set(s[i]-it(f,m,.5)+p)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:s,dragConstraints:i}=this.getProps(),{projection:l}=this.visualElement;if(!sr(i)||!l||!this.constraints)return;this.stopAnimation();const o={x:0,y:0};Rn(f=>{const m=this.getAxisMotionValue(f);if(m&&this.constraints!==!1){const p=m.get();o[f]=U2({min:p,max:p},this.constraints[f])}});const{transformTemplate:d}=this.visualElement.getProps();this.visualElement.current.style.transform=d?d({},\"\"):\"none\",l.root&&l.root.updateScroll(),l.updateLayout(),this.resolveConstraints(),Rn(f=>{if(!Go(f,s,null))return;const m=this.getAxisMotionValue(f),{min:p,max:y}=this.constraints[f];m.set(it(p,y,o[f]))})}addListeners(){if(!this.visualElement.current)return;q2.set(this.visualElement,this);const s=this.visualElement.current,i=rr(s,\"pointerdown\",p=>{const{drag:y,dragListener:x=!0}=this.getProps();y&&x&&!Ov(p.target)&&this.start(p)}),l=()=>{const{dragConstraints:p}=this.getProps();sr(p)&&p.current&&(this.constraints=this.resolveRefConstraints())},{projection:o}=this.visualElement,d=o.addEventListener(\"measure\",l);o&&!o.layout&&(o.root&&o.root.updateScroll(),o.updateLayout()),We.read(l);const f=pr(window,\"resize\",()=>this.scalePositionWithinConstraints()),m=o.addEventListener(\"didUpdate\",(({delta:p,hasLayoutChanged:y})=>{this.isDragging&&y&&(Rn(x=>{const g=this.getAxisMotionValue(x);g&&(this.originPoint[x]+=p[x].translate,g.set(g.get()+p[x].translate))}),this.visualElement.render())}));return()=>{f(),i(),d(),m&&m()}}getProps(){const s=this.visualElement.getProps(),{drag:i=!1,dragDirectionLock:l=!1,dragPropagation:o=!1,dragConstraints:d=!1,dragElastic:f=Xf,dragMomentum:m=!0}=s;return{...s,drag:i,dragDirectionLock:l,dragPropagation:o,dragConstraints:d,dragElastic:f,dragMomentum:m}}}function Go(t,s,i){return(s===!0||s===t)&&(i===null||i===t)}function $2(t,s=10){let i=null;return Math.abs(t.y)>s?i=\"y\":Math.abs(t.x)>s&&(i=\"x\"),i}class G2 extends Na{constructor(s){super(s),this.removeGroupControls=On,this.removeListeners=On,this.controls=new I2(s)}mount(){const{dragControls:s}=this.node.getProps();s&&(this.removeGroupControls=s.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||On}update(){const{dragControls:s}=this.node.getProps(),{dragControls:i}=this.node.prevProps||{};s!==i&&(this.removeGroupControls(),s&&(this.removeGroupControls=s.subscribe(this.controls)))}unmount(){this.removeGroupControls(),this.removeListeners()}}const Ex=t=>(s,i)=>{t&&We.postRender(()=>t(s,i))};class Y2 extends Na{constructor(){super(...arguments),this.removePointerDownListener=On}onPointerDown(s){this.session=new yw(s,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:gw(this.node)})}createPanHandlers(){const{onPanSessionStart:s,onPanStart:i,onPan:l,onPanEnd:o}=this.node.getProps();return{onSessionStart:Ex(s),onStart:Ex(i),onMove:l,onEnd:(d,f)=>{delete this.session,o&&We.postRender(()=>o(d,f))}}}mount(){this.removePointerDownListener=rr(this.node.current,\"pointerdown\",s=>this.onPointerDown(s))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}let pf=!1;class F2 extends b.Component{componentDidMount(){const{visualElement:s,layoutGroup:i,switchLayoutGroup:l,layoutId:o}=this.props,{projection:d}=s;d&&(i.group&&i.group.add(d),l&&l.register&&o&&l.register(d),pf&&d.root.didUpdate(),d.addEventListener(\"animationComplete\",()=>{this.safeToRemove()}),d.setOptions({...d.options,onExitComplete:()=>this.safeToRemove()})),tc.hasEverUpdated=!0}getSnapshotBeforeUpdate(s){const{layoutDependency:i,visualElement:l,drag:o,isPresent:d}=this.props,{projection:f}=l;return f&&(f.isPresent=d,pf=!0,o||s.layoutDependency!==i||i===void 0||s.isPresent!==d?f.willUpdate():this.safeToRemove(),s.isPresent!==d&&(d?f.promote():f.relegate()||We.postRender(()=>{const m=f.getStack();(!m||!m.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:s}=this.props.visualElement;s&&(s.root.didUpdate(),Hh.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:s,layoutGroup:i,switchLayoutGroup:l}=this.props,{projection:o}=s;pf=!0,o&&(o.scheduleCheckAfterUnmount(),i&&i.group&&i.group.remove(o),l&&l.deregister&&l.deregister(o))}safeToRemove(){const{safeToRemove:s}=this.props;s&&s()}render(){return null}}function bw(t){const[s,i]=rw(),l=b.useContext(xh);return c.jsx(F2,{...t,layoutGroup:l,switchLayoutGroup:b.useContext(mw),isPresent:s,safeToRemove:i})}const X2={pan:{Feature:Y2},drag:{Feature:G2,ProjectionNode:lw,MeasureLayout:bw}};function Dx(t,s,i){const{props:l}=t;t.animationState&&l.whileHover&&t.animationState.setActive(\"whileHover\",i===\"Start\");const o=\"onHover\"+i,d=l[o];d&&We.postRender(()=>d(s,jr(s)))}class K2 extends Na{mount(){const{current:s}=this.node;s&&(this.unmount=RC(s,(i,l)=>(Dx(this.node,l,\"Start\"),o=>Dx(this.node,o,\"End\"))))}unmount(){}}class Q2 extends Na{constructor(){super(...arguments),this.isActive=!1}onFocus(){let s=!1;try{s=this.node.current.matches(\":focus-visible\")}catch{s=!0}!s||!this.node.animationState||(this.node.animationState.setActive(\"whileFocus\",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive(\"whileFocus\",!1),this.isActive=!1)}mount(){this.unmount=vr(pr(this.node.current,\"focus\",()=>this.onFocus()),pr(this.node.current,\"blur\",()=>this.onBlur()))}unmount(){}}function kx(t,s,i){const{props:l}=t;if(t.current instanceof HTMLButtonElement&&t.current.disabled)return;t.animationState&&l.whileTap&&t.animationState.setActive(\"whileTap\",i===\"Start\");const o=\"onTap\"+(i===\"End\"?\"\":i),d=l[o];d&&We.postRender(()=>d(s,jr(s)))}class Z2 extends Na{mount(){const{current:s}=this.node;s&&(this.unmount=_C(s,(i,l)=>(kx(this.node,l,\"Start\"),(o,{success:d})=>kx(this.node,o,d?\"End\":\"Cancel\")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const Kf=new WeakMap,gf=new WeakMap,J2=t=>{const s=Kf.get(t.target);s&&s(t)},W2=t=>{t.forEach(J2)};function eE({root:t,...s}){const i=t||document;gf.has(i)||gf.set(i,{});const l=gf.get(i),o=JSON.stringify(s);return l[o]||(l[o]=new IntersectionObserver(W2,{root:t,...s})),l[o]}function tE(t,s,i){const l=eE(s);return Kf.set(t,i),l.observe(t),()=>{Kf.delete(t),l.unobserve(t)}}const nE={some:0,all:1};class sE extends Na{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:s={}}=this.node.getProps(),{root:i,margin:l,amount:o=\"some\",once:d}=s,f={root:i?i.current:void 0,rootMargin:l,threshold:typeof o==\"number\"?o:nE[o]},m=p=>{const{isIntersecting:y}=p;if(this.isInView===y||(this.isInView=y,d&&!y&&this.hasEnteredView))return;y&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive(\"whileInView\",y);const{onViewportEnter:x,onViewportLeave:g}=this.node.getProps(),w=y?x:g;w&&w(p)};return tE(this.node.current,f,m)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>\"u\")return;const{props:s,prevProps:i}=this.node;[\"amount\",\"margin\",\"root\"].some(aE(s,i))&&this.startObserver()}unmount(){}}function aE({viewport:t={}},{viewport:s={}}={}){return i=>t[i]!==s[i]}const iE={inView:{Feature:sE},tap:{Feature:Z2},focus:{Feature:Q2},hover:{Feature:K2}},lE={layout:{ProjectionNode:lw,MeasureLayout:bw}},rE={...R2,...iE,...X2,...lE},Le=C2(rE,A2),Qh=\"https://rateright-growth-production.up.railway.app\";async function Zh(){try{const{data:{session:t}}=await Nt.auth.getSession();return t?.access_token||null}catch{return null}}async function k(t,s={}){const i=`${Qh}${t}`,l=await Zh(),d={headers:{\"Content-Type\":\"application/json\",...l?{Authorization:`Bearer ${l}`}:{},...s.headers},...s},f=await fetch(i,d);if(!f.ok){const m=await f.json().catch(()=>({error:\"Request failed\"}));throw new Error(m.error||`HTTP ${f.status}`)}return f.status===204?null:f.json()}const Tr={list:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/leads${s?`?${s}`:\"\"}`)},get:t=>k(`/api/leads/${t}`),create:t=>k(\"/api/leads\",{method:\"POST\",body:JSON.stringify(t)}),update:(t,s)=>k(`/api/leads/${t}`,{method:\"PATCH\",body:JSON.stringify(s)}),updateLead:(t,s)=>k(`/api/leads/${t}`,{method:\"PATCH\",body:JSON.stringify(s)}),delete:t=>k(`/api/leads/${t}`,{method:\"DELETE\"}),archive:(t,s)=>k(`/api/leads/${t}/archive`,{method:\"POST\",body:JSON.stringify({reason:s})}),archiveLead:(t,s)=>k(`/api/leads/${t}/archive`,{method:\"POST\",body:JSON.stringify({reason:s})}),importFromSheet:()=>k(\"/api/leads/import-sheet\",{method:\"POST\"}),search:t=>k(`/api/leads/search?q=${encodeURIComponent(t)}`),claim:t=>k(`/api/leads/${t}/claim`,{method:\"POST\"}),release:t=>k(`/api/leads/${t}/release`,{method:\"POST\"}),assignments:()=>k(\"/api/leads/assignments\")},Jk={get:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/call-list${s?`?${s}`:\"\"}`)},stats:()=>k(\"/api/call-list/stats\"),activity:t=>k(`/api/call-list/activity${t?`?date=${t}`:\"\"}`)},Wk={send:t=>k(\"/api/sms/send\",{method:\"POST\",body:JSON.stringify(t)}),batch:t=>k(\"/api/sms/batch\",{method:\"POST\",body:JSON.stringify(t)}),preview:t=>k(\"/api/sms/preview\",{method:\"POST\",body:JSON.stringify(t)}),requestContact:t=>k(\"/api/sms/request-contact\",{method:\"POST\",body:JSON.stringify({leadId:t})}),getTemplates:t=>k(`/api/sms/templates${t?`?category=${t}`:\"\"}`),getTemplate:t=>k(`/api/sms/templates/${t}`),createTemplate:t=>k(\"/api/sms/templates\",{method:\"POST\",body:JSON.stringify(t)}),updateTemplate:(t,s)=>k(`/api/sms/templates/${t}`,{method:\"PUT\",body:JSON.stringify(s)}),deleteTemplate:t=>k(`/api/sms/templates/${t}`,{method:\"DELETE\"}),useTemplate:t=>k(`/api/sms/templates/${t}/use`,{method:\"POST\"}),getConversations:(t=\"all\")=>k(`/api/sms/conversations?filter=${t}`),getConversation:t=>k(`/api/sms/conversation/${t}`),markAsRead:t=>k(`/api/sms/conversation/${t}/read`,{method:\"PATCH\"}),handleConversation:(t,s=!0)=>k(`/api/sms/conversation/${t}/handle`,{method:\"PATCH\",body:JSON.stringify({handled:s})}),getPrioritized:(t=50)=>k(`/api/sms/conversations/prioritized?limit=${t}`),getAiSuggestion:(t,s)=>k(\"/api/sms/ai-suggest\",{method:\"POST\",body:JSON.stringify({leadId:t,lastMessage:s})}),getScheduled:t=>k(`/api/sms/scheduled${t?`?leadId=${t}`:\"\"}`),cancelScheduled:t=>k(`/api/sms/scheduled/${t}`,{method:\"DELETE\"}),getStats:(t=30)=>k(`/api/sms/stats?days=${t}`),sendBatch:t=>k(\"/api/sms/send-batch\",{method:\"POST\",body:JSON.stringify({messages:t})})},oE={log:t=>k(\"/api/calls/log\",{method:\"POST\",body:JSON.stringify(t)}),outcomes:()=>k(\"/api/calls/outcomes\"),getHistory:(t,s=1)=>k(`/api/calls/history/${t}?limit=${s}`)},eR={get:t=>k(`/api/dossier/${t}`),update:(t,s)=>k(`/api/dossier/${t}`,{method:\"PATCH\",body:JSON.stringify(s)}),addFact:(t,s,i=\"manual\")=>k(`/api/dossier/${t}/add-fact`,{method:\"POST\",body:JSON.stringify({fact:s,source:i})}),addCallSummary:(t,s)=>k(`/api/dossier/${t}/add-call-summary`,{method:\"POST\",body:JSON.stringify(s)}),addObjection:(t,s)=>k(`/api/dossier/${t}/add-objection`,{method:\"POST\",body:JSON.stringify(s)})},tR={getAll:()=>k(\"/api/dashboard/all\"),getStats:()=>k(\"/api/dashboard/stats\"),getWisdom:()=>k(\"/api/dashboard/wisdom\"),rateWisdom:(t,s)=>k(\"/api/dashboard/wisdom/rate\",{method:\"POST\",body:JSON.stringify({wisdomId:t,rating:s})}),getStrategy:()=>k(\"/api/dashboard/strategy\"),getPriorityAction:()=>k(\"/api/dashboard/priority-action\"),getSlipping:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/dashboard/slipping${s?`?${s}`:\"\"}`)}},nc={getToken:()=>k(\"/api/voice/token\"),status:()=>k(\"/api/voice/status\"),lookupCaller:t=>k(`/api/voice/lookup-caller?phone=${encodeURIComponent(t)}`)},cE={submit:t=>k(\"/api/bug-report\",{method:\"POST\",body:JSON.stringify(t)})},It={getIntelBrief:t=>k(`/api/ai/intel-brief/${t}`),getLiveIntel:t=>k(`/api/ai/live-intel/${t}`),postCallSummary:t=>k(\"/api/ai/post-call-summary\",{method:\"POST\",body:JSON.stringify(t)}),draftMessage:t=>k(\"/api/ai/draft-message\",{method:\"POST\",body:JSON.stringify(t)}),transcribe:async t=>{const s=new FormData;s.append(\"audio\",t,\"audio.webm\");const i=`${Qh}/api/ai/transcribe`,l=await Zh(),o=l?{Authorization:`Bearer ${l}`}:{},d=await fetch(i,{method:\"POST\",body:s,headers:o});if(!d.ok)throw new Error(\"Transcription failed\");return d.json()},voiceCommand:t=>k(\"/api/ai/voice-command\",{method:\"POST\",body:JSON.stringify(t)}),objectionResponse:t=>k(\"/api/ai/objection-response\",{method:\"POST\",body:JSON.stringify(t)}),getConversionProbability:t=>k(`/api/ai/conversion-probability/${t}`),weeklyInsights:()=>k(\"/api/ai/weekly-insights\",{method:\"POST\"}),cleanupNotes:t=>k(\"/api/ai/cleanup-notes\",{method:\"POST\",body:JSON.stringify(t)}),getInsights:()=>k(\"/api/ai/insights\"),getDeepgramCredentials:()=>k(\"/api/ai/deepgram-credentials\"),saveCopilotSession:t=>k(\"/api/ai/copilot-session\",{method:\"POST\",body:JSON.stringify(t)}),suggestionFeedback:t=>k(\"/api/ai/suggestion-feedback\",{method:\"POST\",body:JSON.stringify(t)}),getSimilarWins:t=>k(`/api/ai/similar-wins/${t}`),getEffectiveResponses:(t,s)=>{const i=s?`?trade=${encodeURIComponent(s)}`:\"\";return k(`/api/ai/effective-responses/${t}${i}`)},companyResearch:(t,s=!1)=>{const i=s?\"?refresh=true\":\"\";return k(`/api/ai/company-research/${encodeURIComponent(t)}${i}`)},personResearch:(t,s=!1)=>k(`/api/ai/person-research/${t}${s?\"?refresh=true\":\"\"}`),updateIntel:t=>k(\"/api/ai/update-intel\",{method:\"POST\",body:JSON.stringify(t)}),parseIntelVoiceNote:t=>k(\"/api/ai/parse-intel-voice\",{method:\"POST\",body:JSON.stringify(t)}),extractContractor:t=>k(\"/api/ai/extract-contractor\",{method:\"POST\",body:JSON.stringify(t)}),addContractorLead:t=>k(\"/api/ai/extract-contractor\",{method:\"POST\",body:JSON.stringify({...t,createLead:!0})}),extractLeadCorrections:t=>k(\"/api/ai/extract-lead-corrections\",{method:\"POST\",body:JSON.stringify(t)}),draftSimilar:t=>k(\"/api/ai/draft-similar\",{method:\"POST\",body:JSON.stringify(t)})},nR={status:()=>k(\"/api/sync/platform/status\"),stats:()=>k(\"/api/sync/platform/stats\"),syncAll:(t={})=>k(\"/api/sync/platform\",{method:\"POST\",body:JSON.stringify(t)}),syncRecent:()=>k(\"/api/sync/platform/recent\",{method:\"POST\"})},sR={getFunnel:()=>k(\"/api/activation/funnel\"),getLeadsAtStage:(t,s)=>{const i=new URLSearchParams({stage:t});return s&&i.append(\"type\",s),k(`/api/activation/leads-at-stage?${i}`)},getStuck:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/activation/stuck${s?`?${s}`:\"\"}`)},getRevenueAtRisk:()=>k(\"/api/activation/revenue-at-risk\"),getMetrics:(t=30)=>k(`/api/activation/metrics?days=${t}`),getTransitions:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/activation/stage-transitions${s?`?${s}`:\"\"}`)},analyze:()=>k(\"/api/activation/analyze\"),generateNudge:t=>k(\"/api/activation/nudge\",{method:\"POST\",body:JSON.stringify({leadId:t})}),bulkNudge:t=>k(\"/api/activation/bulk-nudge\",{method:\"POST\",body:JSON.stringify(t)}),addToCallList:t=>k(\"/api/activation/add-to-call-list\",{method:\"POST\",body:JSON.stringify(t)}),getActionScript:(t,s=\"contractor\")=>k(`/api/activation/action-script?stage=${t}&type=${s}`),getDropoffAnalysis:(t,s=\"contractor\")=>k(`/api/activation/dropoff-analysis?stage=${t}&type=${s}`),getNudgeTemplates:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/activation/nudge-templates${s?`?${s}`:\"\"}`)},createNudgeTemplate:t=>k(\"/api/activation/nudge-templates\",{method:\"POST\",body:JSON.stringify(t)}),updateNudgeTemplate:(t,s)=>k(`/api/activation/nudge-templates/${t}`,{method:\"PATCH\",body:JSON.stringify(s)}),deleteNudgeTemplate:t=>k(`/api/activation/nudge-templates/${t}`,{method:\"DELETE\"}),getJourney:t=>k(`/api/activation/journey/${t}`),getDiagnosis:t=>k(`/api/activation/diagnose/${t}`),getSimilarWins:(t,s=5)=>k(`/api/activation/similar-wins/${t}?limit=${s}`)},hc={list:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/scripts${s?`?${s}`:\"\"}`)},get:t=>k(`/api/scripts/${t}`),create:t=>k(\"/api/scripts\",{method:\"POST\",body:JSON.stringify(t)}),update:(t,s)=>k(`/api/scripts/${t}`,{method:\"PATCH\",body:JSON.stringify(s)}),delete:t=>k(`/api/scripts/${t}`,{method:\"DELETE\"}),startSession:(t,s)=>k(`/api/scripts/${t}/use`,{method:\"POST\",body:JSON.stringify({lead_id:s})}),endSession:(t,s)=>k(`/api/scripts/sessions/${t}`,{method:\"PATCH\",body:JSON.stringify(s)}),getForLead:t=>k(`/api/scripts/for-lead/${t}`),getAIRecommendation:t=>k(`/api/scripts/ai-recommend/${t}`),recordUsage:(t,s=!1)=>k(`/api/scripts/${t}/use`,{method:\"POST\",body:JSON.stringify({replied:s})}),getAnalytics:(t=30)=>k(`/api/scripts/analytics/overview?days=${t}`),getObjections:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/scripts/objections/list${s?`?${s}`:\"\"}`)},getObjection:t=>k(`/api/scripts/objections/${t}`),createObjection:t=>k(\"/api/scripts/objections\",{method:\"POST\",body:JSON.stringify(t)}),addObjectionResponse:(t,s)=>k(`/api/scripts/objections/${t}/response`,{method:\"POST\",body:JSON.stringify({response:s})}),getGuidelines:()=>k(\"/api/scripts/guidelines\"),updateGuidelines:t=>k(\"/api/scripts/guidelines\",{method:\"PUT\",body:JSON.stringify(t)}),getGuidelinesHistory:(t=20)=>k(`/api/scripts/guidelines/history?limit=${t}`),checkCompliance:(t,s={})=>k(\"/api/scripts/compliance/check\",{method:\"POST\",body:JSON.stringify({message:t,options:s})}),autoFix:t=>k(\"/api/scripts/compliance/auto-fix\",{method:\"POST\",body:JSON.stringify({message:t})}),validateScript:t=>k(`/api/scripts/compliance/validate/${t}`,{method:\"POST\"}),batchValidate:t=>k(\"/api/scripts/compliance/batch-validate\",{method:\"POST\",body:JSON.stringify({scriptIds:t})}),getComplianceStats:()=>k(\"/api/scripts/compliance/stats\"),getQueue:(t=\"pending\",s=20)=>k(`/api/scripts/compliance/queue?status=${t}&limit=${s}`),approveItem:t=>k(`/api/scripts/compliance/queue/${t}/approve`,{method:\"POST\"}),rejectItem:(t,s)=>k(`/api/scripts/compliance/queue/${t}/reject`,{method:\"POST\",body:JSON.stringify({reason:s})}),editItem:(t,s)=>k(`/api/scripts/compliance/queue/${t}/edit`,{method:\"POST\",body:JSON.stringify({final_content:s})})},aR={list:()=>k(\"/api/achievements\"),getUserAchievements:()=>k(\"/api/achievements/user\"),check:()=>k(\"/api/achievements/check\",{method:\"POST\"})},iR={getUser:()=>k(\"/api/xp/user\"),award:t=>k(\"/api/xp/award\",{method:\"POST\",body:JSON.stringify(t)}),getHistory:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/xp/history${s?`?${s}`:\"\"}`)},getLeaderboard:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/xp/leaderboard${s?`?${s}`:\"\"}`)}},Rx={list:t=>k(`/api/sequences${t?`?channel=${t}`:\"\"}`),get:t=>k(`/api/sequences/${t}`),enroll:(t,s)=>k(`/api/sequences/${t}/enroll`,{method:\"POST\",body:JSON.stringify({lead_ids:Array.isArray(s)?s:[s]})}),unenroll:(t,s)=>k(`/api/sequences/${t}/unenroll`,{method:\"POST\",body:JSON.stringify({lead_id:s})}),getActiveEnrollments:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/sequences/enrollments/active${s?`?${s}`:\"\"}`)},getLeadEnrollments:t=>k(`/api/sequences/enrollments/lead/${t}`),pauseEnrollment:(t,s)=>k(`/api/sequences/enrollments/${t}/pause`,{method:\"POST\",body:JSON.stringify({reason:s})}),resumeEnrollment:t=>k(`/api/sequences/enrollments/${t}/resume`,{method:\"POST\"}),skipStep:t=>k(`/api/sequences/enrollments/${t}/skip`,{method:\"POST\"}),sendNow:t=>k(`/api/sequences/enrollments/${t}/send-now`,{method:\"POST\"}),getOptOutStatus:t=>k(`/api/sequences/lead/${t}/opt-out`),setOptOut:(t,s)=>k(`/api/sequences/lead/${t}/opt-out`,{method:\"POST\",body:JSON.stringify({opted_out:s})}),bulkEnrollPreview:(t,s=100,i)=>{const l=new URLSearchParams({dry_run:\"true\",limit:s.toString()});return i&&l.set(\"source\",i),k(`/api/sequences/${t}/bulk-enroll?${l}`,{method:\"POST\"})},bulkEnroll:(t,s=100,i)=>{const l=new URLSearchParams({limit:s.toString()});return i&&l.set(\"source\",i),k(`/api/sequences/${t}/bulk-enroll?${l}`,{method:\"POST\"})}},lR={getScores:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/coaching/scores${s?`?${s}`:\"\"}`)},scoreCall:t=>k(\"/api/coaching/score\",{method:\"POST\",body:JSON.stringify(t)}),getTips:()=>k(\"/api/coaching/tips\"),getWeekly:()=>k(\"/api/coaching/weekly\"),getPatterns:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/coaching/patterns${s?`?${s}`:\"\"}`)}},rR={getTrends:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/analytics/trends${s?`?${s}`:\"\"}`)},getPatterns:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/analytics/patterns${s?`?${s}`:\"\"}`)},getFunnel:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/analytics/funnel${s?`?${s}`:\"\"}`)},getBestTimes:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/analytics/best-times${s?`?${s}`:\"\"}`)},getSources:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/analytics/sources${s?`?${s}`:\"\"}`)},savePattern:t=>k(\"/api/analytics/patterns\",{method:\"POST\",body:JSON.stringify(t)})},oR={list:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/ai-alerts${s?`?${s}`:\"\"}`)},create:t=>k(\"/api/ai-alerts\",{method:\"POST\",body:JSON.stringify(t)}),markRead:t=>k(`/api/ai-alerts/${t}/read`,{method:\"PATCH\"}),dismiss:t=>k(`/api/ai-alerts/${t}/dismiss`,{method:\"PATCH\"}),markAllRead:()=>k(\"/api/ai-alerts/read-all\",{method:\"POST\"}),generate:()=>k(\"/api/ai-alerts/generate\",{method:\"POST\"})},cR={getLeaderboard:(t=\"today\")=>k(`/api/battleground/leaderboard?period=${t}`),getUserStats:t=>k(`/api/battleground/leaderboard/${t}`),saveSnapshot:()=>k(\"/api/battleground/leaderboard/snapshot\",{method:\"POST\"}),getHallOfFame:()=>k(\"/api/battleground/hall-of-fame\"),checkRecord:(t,s,i,l,o)=>k(\"/api/battleground/hall-of-fame/check\",{method:\"POST\",body:JSON.stringify({recordType:t,userId:s,userName:i,value:l,details:o})}),getChallenges:()=>k(\"/api/battleground/challenges\"),updateChallengeProgress:(t,s=1)=>k(\"/api/battleground/challenges/progress\",{method:\"POST\",body:JSON.stringify({actionType:t,count:s})}),generateChallenges:()=>k(\"/api/battleground/challenges/generate\",{method:\"POST\"}),getTeamPulse:(t=20)=>k(`/api/battleground/pulse?limit=${t}`),createPulseEvent:t=>k(\"/api/battleground/pulse\",{method:\"POST\",body:JSON.stringify(t)}),getUserBadges:t=>k(`/api/battleground/badges/${t}`),getCurrentBadges:()=>k(\"/api/battleground/badges\"),awardWeeklyBadges:()=>k(\"/api/battleground/badges/award-weekly\",{method:\"POST\"}),updateStreakTier:(t,s)=>k(\"/api/battleground/streak/update\",{method:\"POST\",body:JSON.stringify({userId:t,streakDays:s})}),getActiveDuels:()=>k(\"/api/battleground/duels/active\"),getDuelHistory:(t=10)=>k(`/api/battleground/duels/history?limit=${t}`),getDuelOdds:(t,s)=>k(`/api/battleground/duels/odds?targetId=${t}&duelType=${s}`),createDuel:(t,s,i)=>k(\"/api/battleground/duels/challenge\",{method:\"POST\",body:JSON.stringify({targetId:t,duelType:s,stakeAmount:i})}),acceptDuel:t=>k(`/api/battleground/duels/${t}/accept`,{method:\"POST\"}),declineDuel:t=>k(`/api/battleground/duels/${t}/decline`,{method:\"POST\"}),getDuelScores:t=>k(`/api/battleground/duels/${t}/scores`),createChallenge:t=>k(\"/api/battleground/challenges\",{method:\"POST\",body:JSON.stringify(t)}),joinChallenge:t=>k(`/api/battleground/challenges/${t}/join`,{method:\"POST\"}),getChallengeDetails:t=>k(`/api/battleground/challenges/${t}`),getTeam:()=>k(\"/api/battleground/team\"),getCelebrations:(t=10)=>k(`/api/battleground/celebrations?limit=${t}`)},uR={getToday:()=>k(\"/api/playbook/today\"),send:(t,s,i)=>k(\"/api/playbook/send\",{method:\"POST\",body:JSON.stringify({leadId:t,messageId:s,messageText:i})}),getBulkPreview:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/playbook/bulk-preview${s?`?${s}`:\"\"}`)},bulkSend:(t,s,i={})=>k(\"/api/playbook/bulk-send\",{method:\"POST\",body:JSON.stringify({batchId:t,leadIds:s,edits:i})})},Mx={getRecordings:()=>k(\"/api/voicemail/recordings\"),createRecording:async t=>{const s=await Zh(),i=await fetch(`${Qh}/api/voicemail/recordings`,{method:\"POST\",headers:{Authorization:`Bearer ${s}`},body:t});if(!i.ok){const l=await i.json().catch(()=>({error:\"Upload failed\"}));throw new Error(l.error||\"Failed to upload\")}return i.json()},createRecordingFromUrl:t=>k(\"/api/voicemail/recordings\",{method:\"POST\",body:JSON.stringify(t)}),deleteRecording:t=>k(`/api/voicemail/recordings/${t}`,{method:\"DELETE\"}),setDefault:t=>k(`/api/voicemail/recordings/${t}/default`,{method:\"PATCH\"}),drop:(t,s,i)=>k(\"/api/voicemail/drop\",{method:\"POST\",body:JSON.stringify({callSid:t,recordingId:s,leadId:i})}),getStats:()=>k(\"/api/voicemail/drops/stats\")},dR={getDashboard:(t=\"week\")=>k(`/api/manager/dashboard?period=${t}`),getAnalytics:(t=\"week\")=>k(`/api/manager/analytics?period=${t}`),getRepDetail:(t,s=\"week\")=>k(`/api/manager/rep/${t}?period=${s}`)},fR={getDashboard:()=>k(\"/api/intelligence/dashboard\"),track:t=>k(\"/api/intelligence/track\",{method:\"POST\",body:JSON.stringify(t)}),trackBatch:t=>k(\"/api/intelligence/track-batch\",{method:\"POST\",body:JSON.stringify({events:t})}),getSuggestions:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/intelligence/suggestions${s?`?${s}`:\"\"}`)},updateSuggestionStatus:(t,s)=>k(`/api/intelligence/suggestions/${t}/status`,{method:\"PATCH\",body:JSON.stringify(s)}),getFriction:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/intelligence/friction${s?`?${s}`:\"\"}`)},getPageStats:(t=7)=>k(`/api/intelligence/page-stats?days=${t}`),getMetrics:(t,s,i)=>{const l=new URLSearchParams({start_date:t});return s&&l.append(\"end_date\",s),i&&l.append(\"metric_name\",i),k(`/api/intelligence/metrics?${l}`)}},Ox={getVapidKey:()=>k(\"/api/notifications/vapid-public-key\"),subscribe:t=>k(\"/api/notifications/subscribe\",{method:\"POST\",body:JSON.stringify({subscription:t})}),unsubscribe:(t=null)=>k(\"/api/notifications/unsubscribe\",{method:\"DELETE\",body:JSON.stringify({endpoint:t})}),getPreferences:()=>k(\"/api/notifications/preferences\"),updatePreferences:t=>k(\"/api/notifications/preferences\",{method:\"PUT\",body:JSON.stringify(t)}),test:()=>k(\"/api/notifications/test\",{method:\"POST\"}),getStatus:()=>k(\"/api/notifications/status\")},qn=[{id:\"opener\",label:\"Opener\",icon:\"👋\"},{id:\"discovery\",label:\"Discovery\",icon:\"🔍\"},{id:\"value_prop\",label:\"Value Prop\",icon:\"💎\"},{id:\"objections\",label:\"Objections\",icon:\"🛡️\"},{id:\"close\",label:\"Close\",icon:\"🎯\"}],uE={opener:{script:\"Hey, it's [your name] from RateRight. How's it going?\",tip:\"Be warm and conversational. Match their energy.\",alternatives:[\"Hi [name], this is [you] from RateRight - got a quick minute?\",\"G'day [name], [you] here from RateRight. How's business?\"]},discovery:{script:\"What's your biggest challenge finding workers right now?\",tip:\"Listen more than you talk. Take mental notes.\",alternatives:[\"How are you currently sourcing your workers?\",\"What trades are hardest to find good people for?\",\"How many workers do you typically need on a job?\"]},value_prop:{script:\"We connect you with pre-vetted workers at just 9.9% - no lock-in contracts.\",tip:\"Focus on their pain points. Make it about them.\",alternatives:[\"Most of our contractors find workers within 24 hours.\",\"You only pay when they work - no upfront fees.\",\"Every worker is vetted with references and qualifications checked.\"]},objections:{script:\"I hear you. What would need to change for this to make sense?\",tip:\"Don't argue. Acknowledge and redirect.\",alternatives:[\"That's a fair point. Here's how other contractors handle that...\",\"I understand. Can I ask what you're comparing us to?\",\"Makes sense. What if we could address that concern?\"]},close:{script:\"Let me get you set up - it takes about 2 minutes. What's your email?\",tip:\"Assume the sale. Be confident.\",alternatives:[\"When's your next job starting? Let's get you ready.\",\"I'll send you the link now - what email should I use?\",\"Want me to walk you through it while we're on the phone?\"]}};function dE({lead:t,duration:s,onHangUp:i,onMute:l,isMuted:o,onMarkHot:d}){const[f,m]=b.useState(0),[p,y]=b.useState(null),[x,g]=b.useState(null),[w,S]=b.useState(!1),[T,N]=b.useState([]),[R,D]=b.useState(null),[A,C]=b.useState([]);b.useEffect(()=>{t?.id&&(B(),_())},[t?.id]);const B=async()=>{try{const $=await hc.getRecommendation(t.id);$?.script&&y($.script)}catch{console.log(\"Using default scripts\")}},_=async()=>{try{const $=await It.getIntelBrief(t.id);if($){D($);const W=[];$.openingLine&&W.push({type:\"opener\",text:$.openingLine}),$.talkingPoints?.length&&$.talkingPoints.forEach(se=>W.push({type:\"point\",text:se})),$.similarWins?.length&&W.push({type:\"win\",text:`Similar win: ${$.similarWins[0].name} - \"${$.similarWins[0].whatWorked}\"`}),$.company?.sales_angle&&W.push({type:\"angle\",text:$.company.sales_angle}),C(W)}}catch{console.log(\"Intel not available\")}},F=$=>{const W=uE[$];if(!p)return W;switch($){case\"opener\":return{...W,script:p.opening||W.script};case\"discovery\":return{...W,script:p.discovery_questions?.[0]?.question||W.script,alternatives:p.discovery_questions?.slice(1,4).map(se=>se.question)||W.alternatives};case\"value_prop\":return{...W,script:p.value_props?.[0]?.prop||W.script,alternatives:p.value_props?.slice(1,4).map(se=>se.prop)||W.alternatives};case\"objections\":return W;case\"close\":return{...W,script:p.closing_techniques?.[0]?.script||W.script,alternatives:p.closing_techniques?.slice(1,4).map(se=>se.script)||W.alternatives};default:return W}},P=async($,W)=>{await navigator.clipboard.writeText($),g(W),setTimeout(()=>g(null),500)},H=()=>{f{m($)},X=()=>{S(!0),d?.()},te=$=>{const W=Math.floor($/60),se=$%60;return`${W}:${se.toString().padStart(2,\"0\")}`},Y=`${t?.first_name||\"\"} ${t?.last_name||\"\"}`.trim()||\"Unknown\";return c.jsxs(\"div\",{className:\"fixed inset-0 z-[60] bg-slate-900 flex flex-col\",children:[c.jsxs(\"div\",{className:\"bg-slate-800 px-4 py-3 flex items-center justify-between safe-area-top\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-3\",children:[c.jsx(\"div\",{className:\"w-10 h-10 rounded-full bg-slate-700 flex items-center justify-center\",children:c.jsx(cr,{className:\"w-5 h-5 text-slate-400\"})}),c.jsxs(\"div\",{children:[c.jsx(\"h2\",{className:\"font-bold text-white\",children:Y}),c.jsxs(\"div\",{className:\"flex items-center gap-2\",children:[c.jsx(\"div\",{className:\"w-2 h-2 rounded-full bg-green-500 animate-pulse\"}),c.jsx(\"span\",{className:\"text-green-400 font-mono text-sm\",children:te(s)})]})]})]}),c.jsx(\"button\",{onClick:X,disabled:w,className:`p-2 rounded-full ${w?\"bg-amber-500 text-white\":\"bg-slate-700 text-slate-400\"}`,children:c.jsx(nl,{className:\"w-5 h-5\"})})]}),c.jsx(\"div\",{className:\"bg-slate-800/50 px-4 py-3 flex items-center gap-2\",children:qn.map(($,W)=>c.jsxs(\"button\",{onClick:()=>z(W),className:`flex-1 py-2 rounded-lg text-center transition-all ${T.includes(W)?\"bg-emerald-600 text-white\":W===f?\"bg-violet-600 text-white ring-2 ring-violet-400\":\"bg-slate-700/50 text-slate-400\"}`,children:[c.jsx(\"span\",{className:\"text-lg\",children:$.icon}),c.jsx(\"p\",{className:\"text-[10px] font-bold mt-0.5\",children:T.includes(W)?\"✓\":$.label})]},$.id))}),c.jsx(\"div\",{className:\"flex-1 overflow-y-auto pb-40\",children:c.jsxs(\"div\",{className:\"p-4 space-y-4\",children:[A.length>0&&c.jsxs(\"div\",{className:\"bg-blue-500/10 border border-blue-500/20 rounded-xl p-3\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-2 mb-2\",children:[c.jsx(ac,{className:\"w-4 h-4 text-blue-400\"}),c.jsx(\"span\",{className:\"text-xs font-bold text-blue-400 uppercase\",children:\"Intel & Talking Points\"})]}),c.jsx(\"div\",{className:\"space-y-2\",children:A.slice(0,4).map(($,W)=>c.jsxs(\"div\",{className:\"flex items-start gap-2\",children:[c.jsx(\"span\",{className:\"text-blue-400 mt-0.5\",children:$.type===\"opener\"?\"💬\":$.type===\"win\"?\"🏆\":$.type===\"angle\"?\"🎯\":\"•\"}),c.jsx(\"p\",{className:\"text-blue-200/80 text-sm\",children:$.text})]},W))})]}),R?.company?.name&&c.jsxs(\"div\",{className:\"flex items-center gap-2 px-1\",children:[c.jsx(jc,{className:\"w-4 h-4 text-slate-500\"}),c.jsxs(\"span\",{className:\"text-slate-400 text-sm\",children:[R.company.name,R.company.industry&&` • ${R.company.industry}`,R.company.size&&` • ${R.company.size}`]})]}),c.jsxs(\"div\",{className:\"text-center py-2\",children:[c.jsx(\"span\",{className:\"text-3xl\",children:qn[f].icon}),c.jsx(\"h3\",{className:\"text-xl font-bold text-white mt-2\",children:qn[f].label}),c.jsxs(\"p\",{className:\"text-slate-400 text-sm\",children:[\"Stage \",f+1,\" of \",qn.length]})]}),c.jsxs(\"div\",{className:\"bg-gradient-to-br from-violet-600/20 to-purple-600/10 border border-violet-500/30 rounded-2xl p-4\",children:[c.jsxs(\"div\",{className:\"flex items-start justify-between mb-2\",children:[c.jsx(\"span\",{className:\"text-xs font-bold text-violet-400 uppercase\",children:\"Say This\"}),c.jsx(\"button\",{onClick:()=>P(F(qn[f].id).script,\"main\"),className:\"p-2 -m-2 text-slate-400 hover:text-white\",children:x===\"main\"?c.jsx(ba,{className:\"w-4 h-4 text-green-400\"}):c.jsx(Cf,{className:\"w-4 h-4\"})})]}),c.jsxs(\"p\",{className:\"text-white text-lg leading-relaxed\",children:['\"',F(qn[f].id).script,'\"']})]}),c.jsxs(\"div\",{className:\"bg-amber-500/10 border border-amber-500/20 rounded-xl px-4 py-3\",children:[c.jsx(\"span\",{className:\"text-xs font-bold text-amber-400 uppercase\",children:\"💡 Tip\"}),c.jsx(\"p\",{className:\"text-amber-200/80 text-sm mt-1\",children:F(qn[f].id).tip})]}),c.jsxs(\"div\",{children:[c.jsx(\"h4\",{className:\"text-sm font-bold text-slate-400 mb-2 px-1\",children:\"Or Try These:\"}),c.jsx(\"div\",{className:\"space-y-2\",children:F(qn[f].id).alternatives.map(($,W)=>c.jsxs(\"div\",{className:\"bg-slate-800/50 border border-slate-700 rounded-xl p-3 flex items-start gap-3\",children:[c.jsxs(\"p\",{className:\"text-slate-300 text-sm flex-1\",children:['\"',$,'\"']}),c.jsx(\"button\",{onClick:()=>P($,`alt-${W}`),className:\"p-1 text-slate-500 hover:text-white flex-shrink-0\",children:x===`alt-${W}`?c.jsx(ba,{className:\"w-4 h-4 text-green-400\"}):c.jsx(Cf,{className:\"w-4 h-4\"})})]},W))})]}),f(i&&s?W(s):se(),()=>{ie()}),[]);const W=ee=>{console.log(\"[TwilioCall] Attaching to inbound call\"),X.current=ee,p(\"in-progress\"),Y.current=Date.now(),I();const ge=ee.parameters?.CallSid||null;console.log(\"[TwilioCall] Inbound call CallSid:\",ge),d?.(ge),ee.on(\"disconnect\",()=>{const Ee=Y.current?Math.floor((Date.now()-Y.current)/1e3):0;console.log(\"[TwilioCall] Inbound call disconnected, duration:\",Ee),p(\"ended\"),K(),$.current||($.current=!0,setTimeout(()=>{o?.(Ee)},500))}),ee.on(\"error\",Ee=>{console.error(\"[TwilioCall] Inbound call error:\",Ee),T(Ee.message),p(\"ended\"),K()})},se=async()=>{try{const{token:ee}=await nc.getToken(),ge=new Cb(ee,{logLevel:\"debug\",codecPreferences:[\"opus\",\"pcmu\"],enableRingingState:!0,edge:\"ashburn\"});ge.on(\"error\",Ee=>{console.error(\"Twilio Device error:\",Ee),T(Ee.message),p(\"ended\")}),z.current=ge,p(\"ready\"),O()}catch(ee){console.error(\"Failed to initialize Twilio:\",ee),T(ee.message),p(\"ended\")}},O=async()=>{if(z.current){if(!t?.phone){T(\"No phone number for this lead\"),p(\"ended\");return}try{p(\"connecting\");const ee=await z.current.connect({params:{To:t.phone,leadId:t?.id}});X.current=ee,ee.on(\"ringing\",()=>{p(\"ringing\")}),ee.on(\"accept\",()=>{p(\"in-progress\"),Y.current=Date.now(),I();const ge=ee.parameters?.CallSid||null;console.log(\"[TwilioCall] Call connected, CallSid:\",ge),d?.(ge)}),ee.on(\"disconnect\",()=>{const ge=Y.current?Math.floor((Date.now()-Y.current)/1e3):0;p(\"ended\"),K(),$.current||($.current=!0,setTimeout(()=>{o?.(ge)},500))}),ee.on(\"cancel\",()=>{p(\"ended\"),K(),$.current||($.current=!0,o?.(0))}),ee.on(\"error\",ge=>{console.error(\"Call error:\",ge),T(ge.message),p(\"ended\"),K()})}catch(ee){console.error(\"Failed to make call:\",ee),T(ee.message),p(\"ended\")}}},I=()=>{te.current=setInterval(()=>{Y.current&&x(Math.floor((Date.now()-Y.current)/1e3))},1e3)},K=()=>{te.current&&(clearInterval(te.current),te.current=null)},ie=()=>{K(),!i&&X.current&&X.current.disconnect(),!i&&z.current&&z.current.destroy()},oe=()=>{X.current?X.current.disconnect():l?.()},xe=()=>{X.current&&(g?X.current.mute(!1):X.current.mute(!0),w(!g))},Te=async()=>{if(!(D.length>0)){B(!0);try{const ee=await Mx.getRecordings();A(ee||[])}catch(ee){console.error(\"Failed to load VM recordings:\",ee)}finally{B(!1)}}},ae=async ee=>{const ge=X.current?.parameters?.CallSid;if(!ge){console.error(\"No CallSid available\");return}F(!0);try{await Mx.drop(ge,ee.id,t?.id),H(!0),R(!1)}catch(Ee){console.error(\"VM drop failed:\",Ee),T(\"Failed to drop voicemail\")}finally{F(!1)}},ce=ee=>{const ge=Math.floor(ee/60),Ee=ee%60;return`${ge}:${Ee.toString().padStart(2,\"0\")}`},ne=()=>{switch(m){case\"initializing\":return\"Setting up...\";case\"ready\":return\"Starting call...\";case\"connecting\":return\"Connecting...\";case\"ringing\":return\"Ringing...\";case\"in-progress\":return ce(y);case\"ended\":return\"Call ended\";default:return\"\"}},ue=()=>{switch(m){case\"ringing\":return\"text-amber-400\";case\"in-progress\":return\"text-green-400\";case\"ended\":return\"text-slate-400\";default:return\"text-blue-400\"}},de=`${t?.first_name||\"\"} ${t?.last_name||\"\"}`.trim()||\"Unknown\";return m===\"in-progress\"&&t?c.jsx(dE,{lead:t,duration:y,isMuted:g,onMute:xe,onHangUp:oe,onMarkHot:()=>{console.log(\"Marked hot during call\")}}):c.jsxs(Le.div,{initial:{y:100,opacity:0},animate:{y:0,opacity:1},exit:{y:100,opacity:0},className:\"fixed bottom-0 inset-x-0 z-[60] bg-gradient-to-t from-slate-900 via-slate-900 to-slate-900/95 rounded-t-3xl shadow-2xl pb-safe\",children:[c.jsxs(\"div\",{className:\"px-4 pt-4 pb-2 flex items-center gap-3\",children:[c.jsx(\"div\",{className:\"w-12 h-12 rounded-full bg-slate-700 flex items-center justify-center flex-shrink-0\",children:c.jsx(cr,{className:\"w-6 h-6 text-slate-400\"})}),c.jsxs(\"div\",{className:\"flex-1 min-w-0\",children:[c.jsx(\"h2\",{className:\"text-lg font-bold text-white truncate\",children:de}),c.jsxs(\"div\",{className:\"flex items-center gap-2\",children:[c.jsx(\"span\",{className:`text-sm font-medium ${ue()}`,children:ne()}),m===\"in-progress\"&&f&&c.jsxs(\"div\",{className:\"flex items-center gap-1\",children:[c.jsx(Yj,{className:\"w-3 h-3 text-emerald-400 animate-pulse\"}),c.jsx(\"span\",{className:\"text-xs text-emerald-400\",children:\"Recording\"})]})]})]}),m===\"ringing\"&&c.jsx(\"div\",{className:\"relative w-8 h-8\",children:c.jsx(Le.div,{className:\"absolute inset-0 rounded-full border-2 border-amber-400/50\",animate:{scale:[1,1.5],opacity:[.5,0]},transition:{duration:1.5,repeat:1/0}})})]}),S&&c.jsx(\"p\",{className:\"text-red-400 text-sm text-center px-4 pb-2\",children:S}),c.jsx(\"div\",{className:\"px-4 pb-6 pt-2\",children:m!==\"ended\"?c.jsxs(\"div\",{className:\"flex items-center justify-center gap-6\",children:[c.jsx(\"button\",{onClick:xe,disabled:m!==\"in-progress\",title:g?\"Unmute\":\"Mute\",className:`w-14 h-14 rounded-full flex items-center justify-center transition-colors ${g?\"bg-red-500 text-white\":\"bg-slate-700 text-white disabled:opacity-50\"}`,children:g?c.jsx(Tc,{className:\"w-6 h-6\"}):c.jsx(ti,{className:\"w-6 h-6\"})}),c.jsx(\"button\",{onClick:oe,title:\"End call\",className:\"w-16 h-16 rounded-full bg-red-500 text-white flex items-center justify-center shadow-lg shadow-red-500/30 active:scale-95 transition-transform\",children:c.jsx(ur,{className:\"w-8 h-8\"})}),c.jsx(\"button\",{onClick:()=>{R(!0),Te()},disabled:m===\"initializing\"||m===\"connecting\"||P,title:P?\"Voicemail dropped!\":\"Drop voicemail\",className:`w-14 h-14 rounded-full flex items-center justify-center transition-colors ${P?\"bg-green-600 text-white\":\"bg-amber-600 text-white disabled:opacity-50\"}`,children:P?c.jsx(ba,{className:\"w-6 h-6\"}):c.jsx(ey,{className:\"w-6 h-6\"})})]}):c.jsx(\"button\",{onClick:()=>{$.current||($.current=!0,o?.(y))},className:\"w-full py-4 bg-blue-600 text-white rounded-xl font-bold text-lg\",children:\"Continue\"})}),c.jsx(si,{children:N&&c.jsx(Le.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:\"fixed inset-0 z-[70] bg-black/60 flex items-end justify-center\",onClick:()=>R(!1),children:c.jsxs(Le.div,{initial:{y:\"100%\"},animate:{y:0},exit:{y:\"100%\"},className:\"w-full max-w-md bg-slate-800 rounded-t-2xl p-4 pb-8\",onClick:ee=>ee.stopPropagation(),children:[c.jsxs(\"div\",{className:\"flex items-center justify-between mb-4\",children:[c.jsx(\"h3\",{className:\"text-lg font-bold text-white\",children:\"Drop Voicemail\"}),c.jsx(\"button\",{onClick:()=>R(!1),className:\"w-8 h-8 rounded-full bg-slate-700 flex items-center justify-center\",children:c.jsx(Gt,{className:\"w-5 h-5 text-slate-400\"})})]}),C?c.jsx(\"div\",{className:\"flex items-center justify-center py-8\",children:c.jsx(_n,{className:\"w-6 h-6 text-blue-400 animate-spin\"})}):D.length===0?c.jsxs(\"div\",{className:\"text-center py-8 text-slate-400\",children:[\"No voicemail recordings yet.\",c.jsx(\"br\",{}),c.jsx(\"span\",{className:\"text-sm\",children:\"Add recordings in Settings → Voicemail\"})]}):c.jsx(\"div\",{className:\"space-y-2 max-h-64 overflow-y-auto\",children:D.map(ee=>c.jsxs(\"button\",{onClick:()=>ae(ee),disabled:_,className:\"w-full p-3 bg-slate-700/50 rounded-xl flex items-center gap-3 hover:bg-slate-700 transition-colors disabled:opacity-50\",children:[c.jsx(\"div\",{className:\"w-10 h-10 rounded-full bg-amber-600/20 flex items-center justify-center flex-shrink-0\",children:c.jsx(ey,{className:\"w-5 h-5 text-amber-400\"})}),c.jsxs(\"div\",{className:\"flex-1 text-left\",children:[c.jsx(\"p\",{className:\"text-white font-medium\",children:ee.name}),ee.description&&c.jsx(\"p\",{className:\"text-slate-400 text-sm truncate\",children:ee.description})]}),ee.is_default&&c.jsx(\"span\",{className:\"text-xs bg-blue-600/30 text-blue-400 px-2 py-0.5 rounded\",children:\"Default\"}),_&&c.jsx(_n,{className:\"w-4 h-4 text-blue-400 animate-spin\"})]},ee.id))}),c.jsx(\"p\",{className:\"text-xs text-slate-500 text-center mt-4\",children:\"Selecting a voicemail will play it to the recipient and end the call\"})]})})})]})}function hE({candidate:t,sourceLeadId:s,onAdd:i,onDismiss:l}){const{user:o}=br(),[d,f]=b.useState(!1),m=async()=>{f(!0);try{const x=await It.addContractorLead({sourceLeadId:s,companyName:t.company,projectName:t.project,userEmail:o?.email||\"unknown\"});x.success&&x.lead_id?i(x.lead_id,t):alert(\"Failed to create lead\")}catch(x){console.error(\"Add contractor error:\",x),alert(\"Failed to create lead: \"+x.message)}finally{f(!1)}},p=`${t.first_name||\"\"} ${t.last_name||\"\"}`.trim(),y=Math.round((t.confidence||.5)*100);return c.jsxs(\"div\",{className:\"fixed inset-0 z-50 flex items-center justify-center p-4\",children:[c.jsx(\"div\",{className:\"absolute inset-0 bg-black/60 backdrop-blur-sm\",onClick:l}),c.jsxs(\"div\",{className:\"relative w-full max-w-sm bg-white rounded-2xl shadow-2xl overflow-hidden animate-fade-in\",children:[c.jsx(\"div\",{className:\"bg-gradient-to-r from-amber-500 to-orange-500 px-5 py-4\",children:c.jsxs(\"div\",{className:\"flex items-center justify-between\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-3\",children:[c.jsx(\"div\",{className:\"w-10 h-10 bg-white/20 rounded-xl flex items-center justify-center\",children:c.jsx(nl,{className:\"w-5 h-5 text-white\"})}),c.jsxs(\"div\",{children:[c.jsx(\"h2\",{className:\"text-white font-bold text-lg\",children:\"Contractor Found!\"}),c.jsxs(\"p\",{className:\"text-white/80 text-sm\",children:[y,\"% confidence\"]})]})]}),c.jsx(\"button\",{onClick:l,className:\"w-8 h-8 bg-white/20 rounded-full flex items-center justify-center\",children:c.jsx(Gt,{className:\"w-4 h-4 text-white\"})})]})}),c.jsxs(\"div\",{className:\"p-5\",children:[c.jsxs(\"div\",{className:\"text-center mb-4\",children:[c.jsx(\"h3\",{className:\"text-xl font-bold text-slate-900\",children:p||\"Unknown\"}),t.job_title&&c.jsxs(\"div\",{className:\"flex items-center justify-center gap-2 mt-1 text-slate-600\",children:[c.jsx(Eb,{className:\"w-4 h-4\"}),c.jsx(\"span\",{children:t.job_title})]})]}),c.jsxs(\"div\",{className:\"bg-slate-50 rounded-xl p-4 mb-4 space-y-2\",children:[t.company&&c.jsxs(\"div\",{className:\"flex items-center gap-2 text-slate-700\",children:[c.jsx(Fj,{className:\"w-4 h-4 text-slate-400\"}),c.jsx(\"span\",{className:\"font-semibold\",children:t.company})]}),t.project&&c.jsxs(\"div\",{className:\"flex items-center gap-2 text-slate-600\",children:[c.jsx(ty,{className:\"w-4 h-4 text-slate-400\"}),c.jsxs(\"span\",{children:[t.project,\" Project\"]})]}),t.location&&c.jsxs(\"div\",{className:\"flex items-center gap-2 text-slate-500 text-sm\",children:[c.jsx(ty,{className:\"w-4 h-4 text-slate-400\"}),c.jsx(\"span\",{children:t.location})]})]}),t.linkedin_url&&c.jsxs(\"a\",{href:t.linkedin_url,target:\"_blank\",rel:\"noopener noreferrer\",className:\"flex items-center justify-center gap-2 mb-4 py-2 bg-[#0A66C2] text-white rounded-lg text-sm font-medium hover:bg-[#004182]\",children:[c.jsx(Xj,{className:\"w-4 h-4\"}),\"View LinkedIn Profile\"]}),t.source_worker&&c.jsx(\"div\",{className:\"bg-amber-50 rounded-lg p-3 mb-4 border border-amber-200\",children:c.jsxs(\"p\",{className:\"text-sm text-amber-800\",children:[c.jsx(\"span\",{className:\"font-semibold\",children:\"Source:\"}),\" Worker intel from \",t.source_worker]})}),c.jsxs(\"div\",{className:\"flex gap-3\",children:[c.jsx(\"button\",{onClick:l,className:\"flex-1 py-3 bg-slate-100 text-slate-700 rounded-xl font-semibold hover:bg-slate-200\",children:\"Dismiss\"}),c.jsxs(\"button\",{onClick:m,disabled:d,className:\"flex-1 py-3 bg-gradient-to-r from-green-500 to-emerald-500 text-white rounded-xl font-semibold flex items-center justify-center gap-2 hover:from-green-600 hover:to-emerald-600 disabled:opacity-50\",children:[d?c.jsx(_n,{className:\"w-5 h-5 animate-spin\"}):c.jsx(Af,{className:\"w-5 h-5\"}),\"Add as Lead\"]})]})]})]})]})}function mE(t){const s=Math.floor(t/60),i=t%60;return`${s}:${i.toString().padStart(2,\"0\")}`}const pE={opener:\"Opener\",discovery:\"Discovery\",value_prop:\"Value Props\",objections:\"Objections\",close:\"Close\"},_x=[\"opener\",\"discovery\",\"value_prop\",\"objections\",\"close\"];function gE({duration:t,leadName:s,isListening:i,onMinimize:l}){return c.jsxs(\"div\",{className:\"bg-slate-800 px-4 py-3 flex items-center justify-between safe-area-top\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-3\",children:[c.jsx(\"div\",{className:`w-2.5 h-2.5 rounded-full ${i?\"bg-red-500 animate-pulse\":\"bg-slate-500\"}`}),c.jsx(\"span\",{className:\"text-white font-mono text-lg font-bold tabular-nums\",children:mE(t)})]}),c.jsx(\"span\",{className:\"text-white font-medium truncate max-w-32\",children:s||\"Unknown\"}),c.jsx(\"button\",{onClick:l,className:\"p-2 -mr-2 text-slate-400 hover:text-white\",children:c.jsx(Kj,{className:\"w-5 h-5\"})})]})}function yE({intel:t}){const s=t?.personal_intel?.conversation_starters||t?.person?.conversation_starters||[],i=t?.personal_intel?.interest_news||t?.interest_news,l=[];return i?.items?.length>0&&i.items.slice(0,2).forEach(o=>{l.push({type:\"news\",text:o.talking_point||o.headline,source:o.topic||o.source,emoji:o.topic?.toLowerCase().includes(\"liverpool\")?\"⚽\":o.topic?.toLowerCase().includes(\"f1\")?\"🏎️\":o.topic?.toLowerCase().includes(\"gaa\")?\"🏐\":\"📰\"})}),s.slice(0,3-l.length).forEach(o=>{l.push({type:\"starter\",text:typeof o==\"string\"?o:o.text,source:typeof o==\"string\"?null:o.topic,emoji:\"💬\"})}),l.length===0?null:c.jsxs(\"div\",{className:\"bg-gradient-to-r from-blue-500/20 to-purple-500/20 border border-blue-500/30 rounded-2xl p-3\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-2 mb-2\",children:[c.jsx(\"span\",{className:\"text-sm\",children:\"🎯\"}),c.jsx(\"span\",{className:\"text-xs font-bold text-blue-300 uppercase tracking-wide\",children:\"Ice Breakers\"})]}),c.jsx(\"div\",{className:\"space-y-2\",children:l.map((o,d)=>c.jsxs(\"div\",{className:\"flex items-start gap-2\",children:[c.jsx(\"span\",{className:\"text-base flex-shrink-0\",children:o.emoji}),c.jsxs(\"div\",{className:\"flex-1 min-w-0\",children:[c.jsxs(\"p\",{className:\"text-white text-sm leading-snug\",children:['\"',o.text,'\"']}),o.source&&c.jsx(\"p\",{className:\"text-slate-400 text-xs mt-0.5\",children:o.source})]})]},d))})]})}function xE({stage:t,script:s,openingLine:i}){const[l,o]=b.useState(!1),d=_x.indexOf(t),m=(()=>{if(!s)return i||\"Hey, it's [your name] from RateRight. How's it going?\";switch(t){case\"opener\":return s.opening||i||\"Hey, it's [your name] from RateRight. How's it going?\";case\"discovery\":return s.discovery_questions?.[0]?.question||\"What's your biggest challenge finding workers right now?\";case\"value_prop\":return s.value_props?.[0]?.prop||\"We connect you with pre-vetted workers at just 9.9% - no lock-in contracts.\";case\"objections\":return\"Listen for concerns and address them directly.\";case\"close\":return s.closing_techniques?.[0]?.script||\"Let me get you set up - it takes about 2 minutes. What's your email?\";default:return s.opening||\"Start the conversation...\"}})(),p=async()=>{await navigator.clipboard.writeText(m),o(!0),setTimeout(()=>o(!1),500)};return c.jsxs(\"div\",{className:\"bg-slate-800/50 border border-slate-700 rounded-2xl p-4 relative\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-2 mb-3\",children:[c.jsx(\"span\",{className:\"text-xs font-bold text-violet-400 uppercase tracking-wide\",children:pE[t]||\"Script\"}),c.jsx(\"div\",{className:\"flex-1 h-px bg-slate-700\"}),c.jsxs(\"span\",{className:\"text-xs text-slate-500\",children:[d+1,\"/\",_x.length]})]}),c.jsxs(\"p\",{className:\"text-white text-base leading-relaxed pr-8\",children:['\"',m,'\"']}),c.jsx(\"button\",{onClick:p,className:\"absolute top-4 right-4 p-2 text-slate-400 hover:text-white transition-colors\",children:l?c.jsx(ba,{className:\"w-4 h-4 text-green-400\"}):c.jsx(Cf,{className:\"w-4 h-4\"})})]})}function bE({company:t,person:s,onExpand:i}){if(!t&&!s)return null;const l=[];return t?.name&&l.push(t.name),t?.industry&&l.push(t.industry),t?.size?l.push(t.size):s?.job_title&&l.push(s.job_title),l.length===0?null:c.jsxs(\"button\",{onClick:i,className:\"bg-slate-800/30 border border-slate-700/50 rounded-xl px-4 py-2.5 flex items-center gap-3 w-full text-left\",children:[c.jsx(jc,{className:\"w-4 h-4 text-blue-400 flex-shrink-0\"}),c.jsx(\"span\",{className:\"text-sm text-slate-300 truncate flex-1\",children:l.join(\" • \")}),c.jsx(Ab,{className:\"w-4 h-4 text-slate-500 flex-shrink-0\"})]})}function vE({type:t,trigger:s,suggestion:i,onDismiss:l}){const o=t===\"buying_signal\";return c.jsxs(Le.div,{initial:{y:100,opacity:0,scale:.95},animate:{y:0,opacity:1,scale:1},exit:{y:100,opacity:0,scale:.95},transition:{type:\"spring\",damping:25,stiffness:300},className:`w-full rounded-2xl overflow-hidden relative ${o?\"bg-gradient-to-br from-emerald-500/20 to-green-500/10 border border-emerald-500/50\":\"bg-gradient-to-br from-amber-500/20 to-orange-500/10 border border-amber-500/50\"}`,children:[c.jsxs(\"div\",{className:`px-4 py-2 flex items-center gap-2 ${o?\"bg-emerald-500/30\":\"bg-amber-500/30\"}`,children:[c.jsx(\"span\",{className:\"text-lg\",children:o?\"🔥\":\"⚠️\"}),c.jsx(\"span\",{className:`font-bold text-sm uppercase tracking-wide ${o?\"text-emerald-300\":\"text-amber-300\"}`,children:o?\"BUYING SIGNAL\":i?.objection_type===\"price\"?\"PRICE CONCERN\":i?.objection_type===\"timing\"?\"TIMING ISSUE\":i?.objection_type===\"trust\"?\"TRUST CONCERN\":\"OBJECTION\"})]}),c.jsx(\"div\",{className:\"px-4 pt-3 pb-2\",children:c.jsxs(\"p\",{className:\"text-slate-400 text-sm italic truncate\",children:['\"',s,'\"']})}),c.jsxs(\"div\",{className:\"px-4 pb-3\",children:[c.jsxs(\"p\",{className:\"text-white text-lg font-medium leading-snug\",children:['\"',i?.response||\"Handle this naturally...\",'\"']}),c.jsx(\"p\",{className:\"text-slate-500 text-xs italic mt-1\",children:\"Adapt in your own voice\"})]}),i?.key_point&&c.jsx(\"div\",{className:\"px-4 pb-2\",children:c.jsxs(\"div\",{className:`inline-flex items-center gap-1.5 rounded-full px-3 py-1 ${o?\"bg-emerald-500/20 border border-emerald-500/30\":\"bg-amber-500/20 border border-amber-500/30\"}`,children:[c.jsx(ac,{className:`w-3 h-3 ${o?\"text-emerald-400\":\"text-amber-400\"}`}),c.jsx(\"span\",{className:`text-xs font-medium ${o?\"text-emerald-300\":\"text-amber-300\"}`,children:i.key_point})]})}),i?.follow_up_question&&c.jsxs(\"div\",{className:\"px-4 pb-4 flex items-start gap-2\",children:[c.jsx(Qj,{className:`w-4 h-4 mt-0.5 flex-shrink-0 ${o?\"text-emerald-400\":\"text-amber-400\"}`}),c.jsxs(\"div\",{children:[c.jsx(\"span\",{className:`text-xs font-bold ${o?\"text-emerald-400\":\"text-amber-400\"}`,children:\"THEN ASK:\"}),c.jsxs(\"span\",{className:\"text-slate-300 text-sm ml-1\",children:['\"',i.follow_up_question,'\"']})]})]}),c.jsx(\"button\",{onClick:l,className:\"absolute top-2 right-2 p-2 text-slate-400 hover:text-white\",children:c.jsx(Gt,{className:\"w-4 h-4\"})})]})}function wE({isMuted:t,onMute:s,onMarkHot:i,onEndCall:l,markedHot:o}){return c.jsx(\"div\",{className:\"bg-slate-800 border-t border-slate-700 px-4 py-4 safe-area-bottom\",children:c.jsxs(\"div\",{className:\"flex items-center justify-center gap-4\",children:[c.jsx(\"button\",{onClick:s,className:`w-14 h-14 rounded-full flex items-center justify-center transition-colors ${t?\"bg-red-500 text-white\":\"bg-slate-700 text-slate-300\"}`,children:t?c.jsx(Tc,{className:\"w-6 h-6\"}):c.jsx(ti,{className:\"w-6 h-6\"})}),c.jsx(\"button\",{onClick:i,disabled:o,className:`w-14 h-14 rounded-full flex items-center justify-center transition-colors ${o?\"bg-amber-500 text-white\":\"bg-amber-500/20 border border-amber-500/50 text-amber-400\"}`,children:c.jsx(nl,{className:\"w-6 h-6\"})}),c.jsxs(\"button\",{onClick:l,className:\"px-8 py-4 rounded-full bg-red-500 text-white font-bold flex items-center gap-2 active:scale-95 transition-transform\",children:[c.jsx(ur,{className:\"w-5 h-5\"}),c.jsx(\"span\",{children:\"End\"})]})]})})}function SE({intel:t,leadName:s,onClose:i}){return t?c.jsx(Le.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:\"fixed inset-0 z-[60] bg-black/70 flex items-end\",onClick:i,children:c.jsx(Le.div,{initial:{y:\"100%\"},animate:{y:0},exit:{y:\"100%\"},transition:{type:\"spring\",damping:25,stiffness:300},className:\"bg-slate-800 rounded-t-3xl w-full max-h-[70vh] overflow-y-auto\",onClick:l=>l.stopPropagation(),children:c.jsxs(\"div\",{className:\"p-4\",children:[c.jsx(\"div\",{className:\"w-12 h-1 bg-slate-600 rounded-full mx-auto mb-4\"}),c.jsxs(\"h3\",{className:\"text-lg font-bold text-white mb-4\",children:[\"Intel: \",s]}),t.company&&c.jsxs(\"div\",{className:\"bg-slate-700/50 rounded-xl p-4 mb-3\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-2 mb-2\",children:[c.jsx(jc,{className:\"w-4 h-4 text-blue-400\"}),c.jsx(\"span\",{className:\"text-sm font-semibold text-white\",children:t.company.name})]}),c.jsxs(\"div\",{className:\"flex flex-wrap gap-2\",children:[t.company.industry&&c.jsx(\"span\",{className:\"px-2 py-1 bg-blue-500/20 text-blue-300 text-xs rounded\",children:t.company.industry}),t.company.size&&c.jsx(\"span\",{className:\"px-2 py-1 bg-slate-600 text-slate-300 text-xs rounded\",children:t.company.size}),t.company.location&&c.jsx(\"span\",{className:\"px-2 py-1 bg-slate-600 text-slate-300 text-xs rounded\",children:t.company.location})]}),t.company.sales_angle&&c.jsxs(\"div\",{className:\"mt-3 p-2 bg-emerald-500/10 border border-emerald-500/30 rounded-lg\",children:[c.jsx(\"span\",{className:\"text-xs text-emerald-400 font-semibold\",children:\"SALES ANGLE: \"}),c.jsx(\"span\",{className:\"text-sm text-slate-300\",children:t.company.sales_angle})]})]}),t.person?.job_title&&c.jsxs(\"div\",{className:\"bg-slate-700/50 rounded-xl p-4 mb-3\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-2 mb-1\",children:[c.jsx(\"span\",{className:\"text-lg\",children:\"👤\"}),c.jsx(\"span\",{className:\"text-sm font-semibold text-white\",children:s})]}),c.jsx(\"p\",{className:\"text-slate-400 text-sm\",children:t.person.job_title}),t.person.years_at_company&&c.jsxs(\"p\",{className:\"text-slate-500 text-xs mt-1\",children:[t.person.years_at_company,\" years at company\"]})]}),t.similar_wins?.length>0&&c.jsxs(\"div\",{className:\"bg-slate-700/50 rounded-xl p-4\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-2 mb-2\",children:[c.jsx(\"span\",{className:\"text-lg\",children:\"🏆\"}),c.jsx(\"span\",{className:\"text-sm font-semibold text-amber-400\",children:\"Similar Wins\"})]}),c.jsx(\"div\",{className:\"space-y-2\",children:t.similar_wins.slice(0,3).map((l,o)=>c.jsxs(\"div\",{className:\"text-sm\",children:[c.jsx(\"span\",{className:\"text-slate-300\",children:l.name}),l.key_factor&&c.jsxs(\"span\",{className:\"text-slate-500\",children:[' — \"',l.key_factor,'\"']})]},o))})]})]})})}):null}function jE({lead:t,duration:s,isListening:i,isMuted:l,script:o,scriptStage:d,intel:f,latestSuggestion:m,openingLine:p,error:y,onMinimize:x,onMute:g,onMarkHot:w,onEndCall:S,onDismissSuggestion:T}){const[N,R]=b.useState(!1),[D,A]=b.useState(!1),C=()=>{A(!0),w?.()};return c.jsxs(\"div\",{className:\"fixed inset-0 z-50 bg-slate-900 flex flex-col\",children:[c.jsx(gE,{duration:s,leadName:t?.first_name,isListening:i,onMinimize:x}),c.jsxs(\"div\",{className:\"flex-1 flex flex-col p-4 gap-3 overflow-hidden\",children:[c.jsx(yE,{intel:f}),c.jsx(xE,{stage:d,script:o,openingLine:p}),c.jsx(bE,{company:f?.company,person:f?.person,onExpand:()=>R(!0)}),y&&c.jsxs(\"div\",{className:\"bg-red-500/10 border border-red-500/30 rounded-xl px-4 py-2 flex items-center gap-2\",children:[c.jsx(Db,{className:\"w-4 h-4 text-red-400 flex-shrink-0\"}),c.jsx(\"span\",{className:\"text-red-400 text-sm\",children:y})]}),c.jsxs(\"div\",{className:\"flex-1 flex items-center justify-center px-2\",children:[c.jsx(si,{mode:\"wait\",children:m&&c.jsx(vE,{type:m.type,trigger:m.trigger,suggestion:m.suggestion,onDismiss:T},m.timestamp)}),!m&&i&&c.jsx(\"div\",{className:\"text-center\",children:c.jsxs(\"div\",{className:\"flex items-center justify-center gap-2 text-slate-500\",children:[c.jsx(\"div\",{className:\"w-2 h-2 bg-violet-500 rounded-full animate-pulse\"}),c.jsx(\"span\",{className:\"text-sm\",children:\"Listening for signals...\"})]})})]})]}),c.jsx(wE,{isMuted:l,onMute:g,onMarkHot:C,onEndCall:S,markedHot:D}),c.jsx(si,{children:N&&c.jsx(SE,{intel:f,leadName:t?.first_name,onClose:()=>R(!1)})})]})}const TE={discovery:[\"tell me about\",\"what do you\",\"how many\",\"when did\",\"how long\",\"what's your\",\"who is\"],value_prop:[\"we can help\",\"our platform\",\"rateright\",\"workers available\",\"save you\",\"percentage\"],objections:[\"price\",\"cost\",\"expensive\",\"not sure\",\"competitor\",\"think about\"],close:[\"next step\",\"sign up\",\"get started\",\"send you\",\"email\",\"ready to\"]},NE=[\"expensive\",\"cost\",\"price\",\"too much\",\"can't afford\",\"not sure\",\"think about\",\"need to check\",\"competitor\",\"already have\",\"not interested\",\"busy\",\"later\",\"call back\",\"happy with\",\"current provider\",\"contract\",\"locked in\"],CE=[/works?\\s+for\\s+(.+?)\\s+on\\s+(?:the\\s+)?(.+?)(?:\\s+project|\\s+site|\\s+job|[.!?]|$)/i,/(?:i|we)\\s+work\\s+for\\s+(.+?)(?:\\s+on|\\s+at|[.!?]|$)/i,/(?:my|the)\\s+boss\\s+(?:is\\s+)?(?:at\\s+)?(.+?)(?:[.!?]|$)/i,/working\\s+(?:for|with)\\s+(.+?)(?:\\s+on|\\s+at|[.!?]|$)/i],AE=[/^hey system[,:]?\\s*(.+)/i,/^command[,:]?\\s*(.+)/i,/^note[,:]?\\s*(.+)/i,/^mark\\s+(hot|warm|cold|engaged|converted|lost)/i,/^callback\\s+(.+)/i,/^skip$/i],EE=[\"when can you start\",\"when can we start\",\"how do i sign up\",\"how do we sign up\",\"what's the next step\",\"what is the next step\",\"next steps\",\"let's do it\",\"lets do it\",\"i'm ready\",\"we're ready\",\"sign me up\",\"sign us up\",\"send me the details\",\"send the details\",\"send me a quote\",\"need workers asap\",\"need someone today\",\"starting monday\",\"starting next week\",\"that's reasonable\",\"sounds fair\",\"cheaper than\",\"better than\",\"have a job starting\",\"got a project\",\"need workers\",\"how many workers\",\"do you have electricians\",\"do you have carpenters\"],Lx={\"next step\":{type:\"closing\",response:\"Great question! I can get you set up right now. I just need your email to send the signup link.\",followUp:\"What's the best email to send that to?\",keyPoint:\"They're ready to move forward!\"},sign:{type:\"closing\",response:\"Perfect! Let me get you started. The signup takes about 2 minutes.\",followUp:\"Do you have your ABN handy?\",keyPoint:\"Close the deal now!\"},\"when can\":{type:\"urgency\",response:\"We can have workers available within 24-48 hours once you're set up.\",followUp:\"What trade do you need first?\",keyPoint:\"Match their urgency!\"},\"need workers\":{type:\"qualification\",response:\"We've got a great pool of pre-vetted workers. Most contractors find someone within a day.\",followUp:\"How many workers are you looking for?\",keyPoint:\"Qualify the opportunity!\"},cheaper:{type:\"value\",response:\"Yes, at 9.9% we're typically 30-50% less than traditional agencies, with no lock-in contracts.\",followUp:\"Would you like me to calculate the savings based on your team size?\",keyPoint:\"Reinforce the value!\"},default:{type:\"interest\",response:\"I can hear you're interested! Let me show you how easy it is to get started.\",followUp:\"What's your biggest pain point with finding workers right now?\",keyPoint:\"Keep the momentum!\"}};function DE({lead:t,onClose:s,onEnd:i}){const{scriptSessionId:l,setScriptSessionId:o,preloadedIntel:d}=kc(),[f,m]=b.useState(!1),[p,y]=b.useState(\"\"),[x,g]=b.useState(\"\"),[w,S]=b.useState([]),[T,N]=b.useState(!1),[R,D]=b.useState(null),[A,C]=b.useState(0),[B,_]=b.useState(!1),[F,P]=b.useState(null),[H,z]=b.useState([]),[X,te]=b.useState(\"\"),[Y,$]=b.useState(!0),[W,se]=b.useState(!0),[O,I]=b.useState({}),[K,ie]=b.useState(null),[oe,xe]=b.useState(null),[Te,ae]=b.useState(null),[ce,ne]=b.useState(!1),ue=b.useRef(!1),[de,ee]=b.useState(null),[ge,Ee]=b.useState(!1),[wt,me]=b.useState(null),ze=b.useRef(null),[st,on]=b.useState(!0),[Wt,ms]=b.useState(null),[Yn,Yt]=b.useState(\"opener\"),[li,Ea]=b.useState([]),[Vt,Fn]=b.useState(null),[St,$s]=b.useState(null),[Xn,Da]=b.useState(d),[ps,ka]=b.useState(null),[Ln,ri]=b.useState(!1),cn=b.useRef(!1);b.useEffect(()=>{d&&!cn.current&&(console.log(\"[LiveCopilot] Syncing preloadedIntel from context:\",Object.keys(d)),Da(d),cn.current=!0)},[d]);const Ft=b.useRef(null),ft=b.useRef(null),Ut=b.useRef(null),Ct=b.useRef(null);b.useRef(!1);const Gs=b.useRef(null),Kn=b.useRef(\"\"),un=b.useRef([]),gs=b.useRef(0),Qn=b.useRef(!1),Pt=b.useRef(0),Xt=b.useRef(null),ve=b.useRef(null);b.useEffect(()=>{if(St){const re=setTimeout(()=>{$s(null)},5e3);return()=>clearTimeout(re)}},[St]),b.useEffect(()=>((async()=>(await Fe(),await ht(),await At(),await Zn(),console.log(\"[LiveCopilot] Starting real-time transcription\"),Rt()))(),()=>{xs(),Ut.current&&clearInterval(Ut.current)}),[]),b.useEffect(()=>{Ct.current?.scrollIntoView({behavior:\"smooth\"})},[w]),b.useEffect(()=>(Ut.current=setInterval(()=>{C(re=>(gs.current=re+1,re+1))},1e3),()=>clearInterval(Ut.current)),[]),b.useEffect(()=>{Kn.current=p},[p]),b.useEffect(()=>{un.current=w},[w]),b.useEffect(()=>()=>{!Qn.current&&t?.id&&Kn.current&&(console.log(\"[LiveCopilot] Saving session on unmount, transcript length:\",Kn.current.length),Qn.current=!0,It.saveCopilotSession({leadId:t.id,transcript:Kn.current,suggestions:un.current,duration:gs.current}).catch(re=>console.error(\"[LiveCopilot] Failed to save session on unmount:\",re)))},[t?.id]);const Fe=async()=>{try{const re=await It.getDeepgramCredentials();if(console.log(\"[LiveCopilot] Deepgram configured:\",re.configured),re.configured){const Ae=`wss://${window.location.host.includes(\"rateright.com.au\")?\"rateright-growth-production.up.railway.app\":window.location.host}/api/transcribe/ws`;console.log(\"[LiveCopilot] Using backend proxy:\",Ae),P({configured:!0,proxyUrl:Ae}),Gs.current={configured:!0,proxyUrl:Ae}}else console.log(\"[LiveCopilot] Deepgram not configured, will use Web Speech API fallback\"),Gs.current=null}catch(re){console.log(\"[LiveCopilot] Live transcription not available:\",re.message),Gs.current=null}},ht=async()=>{if(!t?.id){se(!1);return}try{if(t.ai_intel_brief?.talking_points){z(t.ai_intel_brief.talking_points||[]),te(t.ai_intel_brief.opening_line||\"\"),se(!1);return}const re=await It.getIntelBrief(t.id);re.brief&&(z(re.brief.talking_points||[]),te(re.brief.opening_line||\"\"));try{const je=await It.getSimilarWins(t.id);je?.wins?.length>0&&Fn(je.wins[0])}catch(je){console.log(\"Could not load similar wins:\",je)}}catch(re){console.log(\"Could not load intel brief:\",re)}finally{se(!1)}},At=async()=>{if(cn.current||Xn){console.log(\"[LiveCopilot] Intel already loaded, skipping API fetch\");return}if(d){console.log(\"[LiveCopilot] Preloaded intel exists, useEffect will sync\");return}if(t?.id)try{console.log(\"[LiveCopilot] No preloaded intel, fetching from API...\");const re=await It.getLiveIntel(t.id);re.success&&!cn.current&&Da(re)}catch(re){console.log(\"Could not load intel:\",re)}},Zn=async()=>{if(t?.id)try{const re=await hc.getForLead(t.id);if(re.recommendedScripts?.length>0){const je=await hc.get(re.recommendedScripts[0].id);ka(je.script),ms(je.script?.id)}}catch(re){console.log(\"Could not load script:\",re)}},Xe=b.useCallback(re=>{const je=re.toLowerCase();for(const[ye,Ae]of Object.entries(TE))for(const _e of Ae)if(je.includes(_e)){const et=[\"opener\",\"discovery\",\"value_prop\",\"objections\",\"close\"],Be=et.indexOf(Yn);if(et.indexOf(ye)>Be)return Ea(Bn=>[...new Set([...Bn,Yn])]),Yt(ye),!0}return!1},[Yn]),Ht=re=>{const je=Math.floor(re/60),ye=re%60;return`${je}:${ye.toString().padStart(2,\"0\")}`},Jn=b.useCallback(re=>{const je=re.toLowerCase();return NE.some(ye=>je.includes(ye))},[]),Dt=b.useCallback(re=>{const je=re.toLowerCase();for(const ye of EE)if(je.includes(ye)){if(ze.current===ye)return null;ze.current=ye;let Ae=Lx.default;for(const[_e,et]of Object.entries(Lx))if(_e!==\"default\"&&ye.includes(_e)){Ae=et;break}return{trigger:ye,...Ae}}return null},[]),kt=b.useCallback(re=>{me(re);const je={type:\"buying_signal\",trigger:re.trigger,suggestion:{signal_type:re.type,response:re.response,follow_up_question:re.followUp,key_point:re.keyPoint},timestamp:Date.now()};S(ye=>[...ye,je]),$s(je),setTimeout(()=>me(null),5e3)},[]),ys=async re=>{if(!T){N(!0);try{const je=await It.objectionResponse({objection:re,leadId:t?.id});if(je.success){const ye={type:\"objection\",trigger:re,suggestion:je.suggestion,timestamp:Date.now()};S(Ae=>[...Ae,ye]),$s(ye)}}catch(je){console.error(\"Failed to get objection response:\",je)}finally{N(!1)}}},qt=t?.metadata?.lead_type===\"worker\",oi=b.useCallback(re=>{if(!(!qt||ue.current||ce))for(const je of CE){const ye=re.match(je);if(ye){const Ae=ye[1]?.trim(),_e=ye[2]?.trim();if(Ae&&Ae.length>2){console.log(`[ContractorDetection] Found: ${Ae}, project: ${_e||\"N/A\"}`),Dr(Ae,_e);return}}}},[qt,ce]),Dr=async(re,je)=>{if(!(ue.current||ce)){ue.current=!0,ne(!0);try{const ye=await It.extractContractor({sourceLeadId:t?.id,companyName:re,projectName:je});ye.success&&ye.found&&ye.candidate&&ae(ye.candidate)}catch(ye){console.error(\"Contractor search error:\",ye)}finally{ne(!1)}}},Wn=(re,je)=>{ae(null),console.log(\"Contractor lead created:\",re,je)},mt=b.useCallback(async re=>{if(ge)return!1;const je=re.toLowerCase().trim();for(const ye of AE){const Ae=je.match(ye);if(Ae){let _e=Ae[1]||je;(ye.source.includes(\"mark\")||ye.source.includes(\"skip\"))&&(_e=je),console.log(\"[VoiceCommand] Detected:\",_e),Ee(!0);try{const et=await It.voiceCommand({transcript:_e,leadId:t?.id});et.success&&(ee({confirmation:et.parsed.confirmation,intent:et.parsed.intent}),setTimeout(()=>ee(null),3e3))}catch(et){console.error(\"Voice command error:\",et)}finally{Ee(!1)}return!0}}return!1},[t?.id,ge]),Rt=async()=>{try{console.log(\"[LiveCopilot] Requesting microphone access...\");const re=await navigator.mediaDevices.getUserMedia({audio:!0});ve.current=re,Pt.current=0,console.log(\"[LiveCopilot] Microphone access granted\");const je=Gs.current||F;if(console.log(\"[LiveCopilot] Using backend proxy:\",!!(je?.configured&&je?.proxyUrl)),je?.configured&&je?.proxyUrl){console.log(\"[LiveCopilot] Connecting to backend proxy...\"),console.log(\"[LiveCopilot] Proxy URL:\",je.proxyUrl),xe(\"deepgram\");const ye=new WebSocket(je.proxyUrl);console.log(\"[LiveCopilot] WebSocket created, readyState:\",ye.readyState);const Ae=setTimeout(()=>{console.error(\"[LiveCopilot] Connection timeout! readyState:\",ye.readyState),ye.readyState!==WebSocket.OPEN&&(D(\"Connection timeout - trying fallback...\"),ye.close())},1e4);ye.onopen=()=>{clearTimeout(Ae),console.log(\"[LiveCopilot] Connected to transcription proxy!\"),Pt.current=0,m(!0),D(null)},ye.onmessage=Qe=>{const Ke=JSON.parse(Qe.data);if(Ke.error){console.error(\"[LiveCopilot] Proxy error:\",Ke.error),D(Ke.error);return}if(Ke.type===\"Metadata\"&&console.log(\"[LiveCopilot] Transcription metadata:\",Ke),Ke.channel?.alternatives?.[0]?.transcript){console.log(\"[LiveCopilot] Transcript:\",Ke.channel.alternatives[0].transcript,\"is_final:\",Ke.is_final);const Kt=Ke.channel.alternatives[0].transcript;if(Ke.is_final){y(Fs=>Fs+\" \"+Kt),g(\"\"),mt(Kt),Xe(Kt);const Ys=Dt(Kt);Ys?kt(Ys):Jn(Kt)&&ys(Kt),qt&&oi(Kt)}else g(Kt)}},ye.onerror=Qe=>{clearTimeout(Ae),console.error(\"[LiveCopilot] Proxy WebSocket error:\",Qe),console.error(\"[LiveCopilot] Error type:\",Qe.type),console.error(\"[LiveCopilot] Socket readyState on error:\",ye.readyState),D(\"Transcription error - check console\")},ye.onclose=Qe=>{clearTimeout(Ae),console.log(\"[LiveCopilot] Proxy disconnected, code:\",Qe.code,\"reason:\",Qe.reason,\"wasClean:\",Qe.wasClean);const Ke=3;if(Pt.current{console.log(\"[LiveCopilot] Reconnecting WebSocket...\"),Rt()},Kt)}else m(!1),Pt.current>=Ke&&D(\"Transcription disconnected. Tap mic to restart.\")},Ft.current=ye;const _e=new AudioContext,et=_e.sampleRate;console.log(\"[LiveCopilot] AudioContext sample rate:\",et);const Be=`\n./scripts/update-sms-sequences.js:196: console.log('- Removed old \"9.9%\" messaging');\n./scripts/update-all-sms-sequences.js:11: * - Remove \"9.9%\", \"FREE to use\" (for contractors), misleading fee language\n./scripts/update-all-sms-sequences.js:264: // FIX: Remove \"Rocky\", remove \"9.9%\"\n./scripts/update-all-sms-sequences.js:364: console.log(' ✓ 9.9% → $0 for workers');\n./admin/dist/assets/index-2HMepUD5.js:18: `),()=>{D.contains(R)&&D.removeChild(R)}},[s]),c.jsx(JA,{isPresent:s,childRef:d,sizeRef:f,children:b.cloneElement(t,{ref:y})})}const e2=({children:t,initial:s,isPresent:i,onExitComplete:l,custom:o,presenceAffectsLayout:d,mode:f,anchorX:m,root:p})=>{const y=bh(t2),x=b.useId();let g=!0,w=b.useMemo(()=>(g=!1,{id:x,initial:s,isPresent:i,custom:o,onExitComplete:S=>{y.set(S,!0);for(const T of y.values())if(!T)return;l&&l()},register:S=>(y.set(S,!1),()=>y.delete(S))}),[i,y,l]);return d&&g&&(w={...w}),b.useMemo(()=>{y.forEach((S,T)=>y.set(T,!1))},[i]),b.useEffect(()=>{!i&&!y.size&&l&&l()},[i]),f===\"popLayout\"&&(t=c.jsx(WA,{isPresent:i,anchorX:m,root:p,children:t})),c.jsx(Cc.Provider,{value:w,children:t})};function t2(){return new Map}function rw(t=!0){const s=b.useContext(Cc);if(s===null)return[!0,null];const{isPresent:i,onExitComplete:l,register:o}=s,d=b.useId();b.useEffect(()=>{if(t)return o(d)},[t]);const f=b.useCallback(()=>t&&l&&l(d),[d,l,t]);return!i&&l?[!1,f]:[!0]}const $o=t=>t.key||\"\";function yx(t){const s=[];return b.Children.forEach(t,i=>{b.isValidElement(i)&&s.push(i)}),s}const si=({children:t,custom:s,initial:i=!0,onExitComplete:l,presenceAffectsLayout:o=!0,mode:d=\"sync\",propagate:f=!1,anchorX:m=\"left\",root:p})=>{const[y,x]=rw(f),g=b.useMemo(()=>yx(t),[t]),w=f&&!y?[]:g.map($o),S=b.useRef(!0),T=b.useRef(g),N=bh(()=>new Map),R=b.useRef(new Set),[D,A]=b.useState(g),[C,B]=b.useState(g);Vb(()=>{S.current=!1,T.current=g;for(let P=0;P{const H=$o(P),z=f&&!y?!1:g===C||w.includes(H),X=()=>{if(R.current.has(H))return;if(R.current.add(H),N.has(H))N.set(H,!0);else return;let te=!0;N.forEach(Y=>{Y||(te=!1)}),te&&(F?.(),B(T.current),f&&x?.(),l&&l())};return c.jsx(e2,{isPresent:z,initial:!S.current||i?void 0:!1,custom:s,presenceAffectsLayout:o,mode:d,root:p,onExitComplete:z?void 0:X,anchorX:m,children:P},H)})})},ow=b.createContext({strict:!1}),xx={animation:[\"animate\",\"variants\",\"whileHover\",\"whileTap\",\"exit\",\"whileInView\",\"whileFocus\",\"whileDrag\"],exit:[\"exit\"],drag:[\"drag\",\"dragControls\"],focus:[\"whileFocus\"],hover:[\"whileHover\",\"onHoverStart\",\"onHoverEnd\"],tap:[\"whileTap\",\"onTap\",\"onTapStart\",\"onTapCancel\"],pan:[\"onPan\",\"onPanStart\",\"onPanSessionStart\",\"onPanEnd\"],inView:[\"whileInView\",\"onViewportEnter\",\"onViewportLeave\"],layout:[\"layout\",\"layoutId\"]};let bx=!1;function n2(){if(bx)return;const t={};for(const s in xx)t[s]={isEnabled:i=>xx[s].some(l=>!!i[l])};Bv(t),bx=!0}function cw(){return n2(),qC()}function s2(t){const s=cw();for(const i in t)s[i]={...s[i],...t[i]};Bv(s)}const a2=new Set([\"animate\",\"exit\",\"variants\",\"initial\",\"style\",\"values\",\"variants\",\"transition\",\"transformTemplate\",\"custom\",\"inherit\",\"onBeforeLayoutMeasure\",\"onAnimationStart\",\"onAnimationComplete\",\"onUpdate\",\"onDragStart\",\"onDrag\",\"onDragEnd\",\"onMeasureDragConstraints\",\"onDirectionLock\",\"onDragTransitionEnd\",\"_dragX\",\"_dragY\",\"onHoverStart\",\"onHoverEnd\",\"onViewportEnter\",\"onViewportLeave\",\"globalTapTarget\",\"ignoreStrict\",\"viewport\"]);function fc(t){return t.startsWith(\"while\")||t.startsWith(\"drag\")&&t!==\"draggable\"||t.startsWith(\"layout\")||t.startsWith(\"onTap\")||t.startsWith(\"onPan\")||t.startsWith(\"onLayout\")||a2.has(t)}let uw=t=>!fc(t);function i2(t){typeof t==\"function\"&&(uw=s=>s.startsWith(\"on\")?!fc(s):t(s))}try{i2(require(\"@emotion/is-prop-valid\").default)}catch{}function l2(t,s,i){const l={};for(const o in t)o===\"values\"&&typeof t.values==\"object\"||(uw(o)||i===!0&&fc(o)||!s&&!fc(o)||t.draggable&&o.startsWith(\"onDrag\"))&&(l[o]=t[o]);return l}const Dc=b.createContext({});function r2(t,s){if(Ec(t)){const{initial:i,animate:l}=t;return{initial:i===!1||mr(i)?i:void 0,animate:mr(l)?l:void 0}}return t.inherit!==!1?s:{}}function o2(t){const{initial:s,animate:i}=r2(t,b.useContext(Dc));return b.useMemo(()=>({initial:s,animate:i}),[vx(s),vx(i)])}function vx(t){return Array.isArray(t)?t.join(\" \"):t}const Xh=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function dw(t,s,i){for(const l in s)!$t(s[l])&&!$v(l,i)&&(t[l]=s[l])}function c2({transformTemplate:t},s){return b.useMemo(()=>{const i=Xh();return Gh(i,s,t),Object.assign({},i.vars,i.style)},[s])}function u2(t,s){const i=t.style||{},l={};return dw(l,i,t),Object.assign(l,c2(t,s)),l}function d2(t,s){const i={},l=u2(t,s);return t.drag&&t.dragListener!==!1&&(i.draggable=!1,l.userSelect=l.WebkitUserSelect=l.WebkitTouchCallout=\"none\",l.touchAction=t.drag===!0?\"none\":`pan-${t.drag===\"x\"?\"y\":\"x\"}`),t.tabIndex===void 0&&(t.onTap||t.onTapStart||t.whileTap)&&(i.tabIndex=0),i.style=l,i}const fw=()=>({...Xh(),attrs:{}});function f2(t,s,i,l){const o=b.useMemo(()=>{const d=fw();return Gv(d,s,Fv(l),t.transformTemplate,t.style),{...d.attrs,style:{...d.style}}},[s]);if(t.style){const d={};dw(d,t.style,t),o.style={...d,...o.style}}return o}const h2=[\"animate\",\"circle\",\"defs\",\"desc\",\"ellipse\",\"g\",\"image\",\"line\",\"filter\",\"marker\",\"mask\",\"metadata\",\"path\",\"pattern\",\"polygon\",\"polyline\",\"rect\",\"stop\",\"switch\",\"symbol\",\"svg\",\"text\",\"tspan\",\"use\",\"view\"];function Kh(t){return typeof t!=\"string\"||t.includes(\"-\")?!1:!!(h2.indexOf(t)>-1||/[A-Z]/u.test(t))}function m2(t,s,i,{latestValues:l},o,d=!1,f){const p=(f??Kh(t)?f2:d2)(s,l,o,t),y=l2(s,typeof t==\"string\",d),x=t!==b.Fragment?{...y,...p,ref:i}:{},{children:g}=s,w=b.useMemo(()=>$t(g)?g.get():g,[g]);return b.createElement(t,{...x,children:w})}function p2({scrapeMotionValuesFromProps:t,createRenderState:s},i,l,o){return{latestValues:g2(i,l,o,t),renderState:s()}}function g2(t,s,i,l){const o={},d=l(t,{});for(const w in d)o[w]=ec(d[w]);let{initial:f,animate:m}=t;const p=Ec(t),y=zv(t);s&&y&&!p&&t.inherit!==!1&&(f===void 0&&(f=s.initial),m===void 0&&(m=s.animate));let x=i?i.initial===!1:!1;x=x||f===!1;const g=x?m:f;if(g&&typeof g!=\"boolean\"&&!Ac(g)){const w=Array.isArray(g)?g:[g];for(let S=0;S(s,i)=>{const l=b.useContext(Dc),o=b.useContext(Cc),d=()=>p2(t,s,l,o);return i?d():bh(d)},y2=hw({scrapeMotionValuesFromProps:Yh,createRenderState:Xh}),x2=hw({scrapeMotionValuesFromProps:Xv,createRenderState:fw}),b2=Symbol.for(\"motionComponentSymbol\");function v2(t,s,i){const l=b.useRef(i);b.useInsertionEffect(()=>{l.current=i});const o=b.useRef(null);return b.useCallback(d=>{d&&t.onMount?.(d),s&&(d?s.mount(d):s.unmount());const f=l.current;if(typeof f==\"function\")if(d){const m=f(d);typeof m==\"function\"&&(o.current=m)}else o.current?(o.current(),o.current=null):f(d);else f&&(f.current=d)},[s])}const mw=b.createContext({});function sr(t){return t&&typeof t==\"object\"&&Object.prototype.hasOwnProperty.call(t,\"current\")}function w2(t,s,i,l,o,d){const{visualElement:f}=b.useContext(Dc),m=b.useContext(ow),p=b.useContext(Cc),y=b.useContext(Fh).reducedMotion,x=b.useRef(null);l=l||m.renderer,!x.current&&l&&(x.current=l(t,{visualState:s,parent:f,props:i,presenceContext:p,blockInitialAnimation:p?p.initial===!1:!1,reducedMotionConfig:y,isSVG:d}));const g=x.current,w=b.useContext(mw);g&&!g.projection&&o&&(g.type===\"html\"||g.type===\"svg\")&&S2(x.current,i,o,w);const S=b.useRef(!1);b.useInsertionEffect(()=>{g&&S.current&&g.update(i,p)});const T=i[wv],N=b.useRef(!!T&&!window.MotionHandoffIsComplete?.(T)&&window.MotionHasOptimisedAnimation?.(T));return Vb(()=>{g&&(S.current=!0,window.MotionIsMounted=!0,g.updateFeatures(),g.scheduleRenderMicrotask(),N.current&&g.animationState&&g.animationState.animateChanges())}),b.useEffect(()=>{g&&(!N.current&&g.animationState&&g.animationState.animateChanges(),N.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(T)}),N.current=!1),g.enteringChildren=void 0)}),g}function S2(t,s,i,l){const{layoutId:o,layout:d,drag:f,dragConstraints:m,layoutScroll:p,layoutRoot:y,layoutCrossfade:x}=s;t.projection=new i(t.latestValues,s[\"data-framer-portal-id\"]?void 0:pw(t.parent)),t.projection.setOptions({layoutId:o,layout:d,alwaysMeasureLayout:!!f||m&&sr(m),visualElement:t,animationType:typeof d==\"string\"?d:\"both\",initialPromotionConfig:l,crossfade:x,layoutScroll:p,layoutRoot:y})}function pw(t){if(t)return t.options.allowProjection!==!1?t.projection:pw(t.parent)}function ff(t,{forwardMotionProps:s=!1,type:i}={},l,o){l&&s2(l);const d=i?i===\"svg\":Kh(t),f=d?x2:y2;function m(y,x){let g;const w={...b.useContext(Fh),...y,layoutId:j2(y)},{isStatic:S}=w,T=o2(y),N=f(y,S);if(!S&&Bb){T2();const R=N2(w);g=R.MeasureLayout,T.visualElement=w2(t,N,w,o,R.ProjectionNode,d)}return c.jsxs(Dc.Provider,{value:T,children:[g&&T.visualElement?c.jsx(g,{visualElement:T.visualElement,...w}):null,m2(t,y,v2(N,T.visualElement,x),N,S,s,d)]})}m.displayName=`motion.${typeof t==\"string\"?t:`create(${t.displayName??t.name??\"\"})`}`;const p=b.forwardRef(m);return p[b2]=t,p}function j2({layoutId:t}){const s=b.useContext(xh).id;return s&&t!==void 0?s+\"-\"+t:t}function T2(t,s){b.useContext(ow).strict}function N2(t){const s=cw(),{drag:i,layout:l}=s;if(!i&&!l)return{};const o={...i,...l};return{MeasureLayout:i?.isEnabled(t)||l?.isEnabled(t)?o.MeasureLayout:void 0,ProjectionNode:o.ProjectionNode}}function C2(t,s){if(typeof Proxy>\"u\")return ff;const i=new Map,l=(d,f)=>ff(d,f,t,s),o=(d,f)=>l(d,f);return new Proxy(o,{get:(d,f)=>f===\"create\"?l:(i.has(f)||i.set(f,ff(f,void 0,t,s)),i.get(f))})}const A2=(t,s)=>s.isSVG??Kh(t)?new iA(s):new WC(s,{allowProjection:t!==b.Fragment});class E2 extends Na{constructor(s){super(s),s.animationState||(s.animationState=uA(s))}updateAnimationControlsSubscription(){const{animate:s}=this.node.getProps();Ac(s)&&(this.unmountControls=s.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:s}=this.node.getProps(),{animate:i}=this.node.prevProps||{};s!==i&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}}let D2=0;class k2 extends Na{constructor(){super(...arguments),this.id=D2++}update(){if(!this.node.presenceContext)return;const{isPresent:s,onExitComplete:i}=this.node.presenceContext,{isPresent:l}=this.node.prevPresenceContext||{};if(!this.node.animationState||s===l)return;const o=this.node.animationState.setActive(\"exit\",!s);i&&!s&&o.then(()=>{i(this.id)})}mount(){const{register:s,onExitComplete:i}=this.node.presenceContext||{};i&&i(this.id),s&&(this.unmount=s(this.id))}unmount(){}}const R2={animation:{Feature:E2},exit:{Feature:k2}};function jr(t){return{point:{x:t.pageX,y:t.pageY}}}const M2=t=>s=>qh(s)&&t(s,jr(s));function rr(t,s,i,l){return pr(t,s,M2(i),l)}const gw=({current:t})=>t?t.ownerDocument.defaultView:null,wx=(t,s)=>Math.abs(t-s);function O2(t,s){const i=wx(t.x,s.x),l=wx(t.y,s.y);return Math.sqrt(i**2+l**2)}const Sx=new Set([\"auto\",\"scroll\"]);class yw{constructor(s,i,{transformPagePoint:l,contextWindow:o=window,dragSnapToOrigin:d=!1,distanceThreshold:f=3,element:m}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=S=>{this.handleScroll(S.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const S=mf(this.lastMoveEventInfo,this.history),T=this.startEvent!==null,N=O2(S.offset,{x:0,y:0})>=this.distanceThreshold;if(!T&&!N)return;const{point:R}=S,{timestamp:D}=Bt;this.history.push({...R,timestamp:D});const{onStart:A,onMove:C}=this.handlers;T||(A&&A(this.lastMoveEvent,S),this.startEvent=this.lastMoveEvent),C&&C(this.lastMoveEvent,S)},this.handlePointerMove=(S,T)=>{this.lastMoveEvent=S,this.lastMoveEventInfo=hf(T,this.transformPagePoint),We.update(this.updatePoint,!0)},this.handlePointerUp=(S,T)=>{this.end();const{onEnd:N,onSessionEnd:R,resumeAnimation:D}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&D&&D(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const A=mf(S.type===\"pointercancel\"?this.lastMoveEventInfo:hf(T,this.transformPagePoint),this.history);this.startEvent&&N&&N(S,A),R&&R(S,A)},!qh(s))return;this.dragSnapToOrigin=d,this.handlers=i,this.transformPagePoint=l,this.distanceThreshold=f,this.contextWindow=o||window;const p=jr(s),y=hf(p,this.transformPagePoint),{point:x}=y,{timestamp:g}=Bt;this.history=[{...x,timestamp:g}];const{onSessionStart:w}=i;w&&w(s,mf(y,this.history)),this.removeListeners=vr(rr(this.contextWindow,\"pointermove\",this.handlePointerMove),rr(this.contextWindow,\"pointerup\",this.handlePointerUp),rr(this.contextWindow,\"pointercancel\",this.handlePointerUp)),m&&this.startScrollTracking(m)}startScrollTracking(s){let i=s.parentElement;for(;i;){const l=getComputedStyle(i);(Sx.has(l.overflowX)||Sx.has(l.overflowY))&&this.scrollPositions.set(i,{x:i.scrollLeft,y:i.scrollTop}),i=i.parentElement}this.scrollPositions.set(window,{x:window.scrollX,y:window.scrollY}),window.addEventListener(\"scroll\",this.onElementScroll,{capture:!0,passive:!0}),window.addEventListener(\"scroll\",this.onWindowScroll,{passive:!0}),this.removeScrollListeners=()=>{window.removeEventListener(\"scroll\",this.onElementScroll,{capture:!0}),window.removeEventListener(\"scroll\",this.onWindowScroll)}}handleScroll(s){const i=this.scrollPositions.get(s);if(!i)return;const l=s===window,o=l?{x:window.scrollX,y:window.scrollY}:{x:s.scrollLeft,y:s.scrollTop},d={x:o.x-i.x,y:o.y-i.y};d.x===0&&d.y===0||(l?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=d.x,this.lastMoveEventInfo.point.y+=d.y):this.history.length>0&&(this.history[0].x-=d.x,this.history[0].y-=d.y),this.scrollPositions.set(s,o),We.update(this.updatePoint,!0))}updateHandlers(s){this.handlers=s}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),va(this.updatePoint)}}function hf(t,s){return s?{point:s(t.point)}:t}function jx(t,s){return{x:t.x-s.x,y:t.y-s.y}}function mf({point:t},s){return{point:t,delta:jx(t,xw(s)),offset:jx(t,_2(s)),velocity:L2(s,.1)}}function _2(t){return t[0]}function xw(t){return t[t.length-1]}function L2(t,s){if(t.length<2)return{x:0,y:0};let i=t.length-1,l=null;const o=xw(t);for(;i>=0&&(l=t[i],!(o.timestamp-l.timestamp>Us(s)));)i--;if(!l)return{x:0,y:0};const d=Mn(o.timestamp-l.timestamp);if(d===0)return{x:0,y:0};const f={x:(o.x-l.x)/d,y:(o.y-l.y)/d};return f.x===1/0&&(f.x=0),f.y===1/0&&(f.y=0),f}function z2(t,{min:s,max:i},l){return s!==void 0&&ti&&(t=l?it(i,t,l.max):Math.min(t,i)),t}function Tx(t,s,i){return{min:s!==void 0?t.min+s:void 0,max:i!==void 0?t.max+i-(t.max-t.min):void 0}}function B2(t,{top:s,left:i,bottom:l,right:o}){return{x:Tx(t.x,i,o),y:Tx(t.y,s,l)}}function Nx(t,s){let i=s.min-t.min,l=s.max-t.max;return s.max-s.minl?i=dr(s.min,s.max-l,t.min):l>o&&(i=dr(t.min,t.max-o,s.min)),cs(0,1,i)}function P2(t,s){const i={};return s.min!==void 0&&(i.min=s.min-t.min),s.max!==void 0&&(i.max=s.max-t.min),i}const Xf=.35;function H2(t=Xf){return t===!1?t=0:t===!0&&(t=Xf),{x:Cx(t,\"left\",\"right\"),y:Cx(t,\"top\",\"bottom\")}}function Cx(t,s,i){return{min:Ax(t,s),max:Ax(t,i)}}function Ax(t,s){return typeof t==\"number\"?t:t[s]||0}const q2=new WeakMap;class I2{constructor(s){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=Tt(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=s}start(s,{snapToCursor:i=!1,distanceThreshold:l}={}){const{presenceContext:o}=this.visualElement;if(o&&o.isPresent===!1)return;const d=g=>{i?(this.stopAnimation(),this.snapToCursor(jr(g).point)):this.pauseAnimation()},f=(g,w)=>{this.stopAnimation();const{drag:S,dragPropagation:T,onDragStart:N}=this.getProps();if(S&&!T&&(this.openDragLock&&this.openDragLock(),this.openDragLock=kC(S),!this.openDragLock))return;this.latestPointerEvent=g,this.latestPanInfo=w,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Rn(D=>{let A=this.getAxisMotionValue(D).get()||0;if(rs.test(A)){const{projection:C}=this.visualElement;if(C&&C.layout){const B=C.layout.layoutBox[D];B&&(A=Jt(B)*(parseFloat(A)/100))}}this.originPoint[D]=A}),N&&We.postRender(()=>N(g,w)),Hf(this.visualElement,\"transform\");const{animationState:R}=this.visualElement;R&&R.setActive(\"whileDrag\",!0)},m=(g,w)=>{this.latestPointerEvent=g,this.latestPanInfo=w;const{dragPropagation:S,dragDirectionLock:T,onDirectionLock:N,onDrag:R}=this.getProps();if(!S&&!this.openDragLock)return;const{offset:D}=w;if(T&&this.currentDirection===null){this.currentDirection=$2(D),this.currentDirection!==null&&N&&N(this.currentDirection);return}this.updateAxis(\"x\",w.point,D),this.updateAxis(\"y\",w.point,D),this.visualElement.render(),R&&R(g,w)},p=(g,w)=>{this.latestPointerEvent=g,this.latestPanInfo=w,this.stop(g,w),this.latestPointerEvent=null,this.latestPanInfo=null},y=()=>Rn(g=>this.getAnimationState(g)===\"paused\"&&this.getAxisMotionValue(g).animation?.play()),{dragSnapToOrigin:x}=this.getProps();this.panSession=new yw(s,{onSessionStart:d,onStart:f,onMove:m,onSessionEnd:p,resumeAnimation:y},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:x,distanceThreshold:l,contextWindow:gw(this.visualElement),element:this.visualElement.current})}stop(s,i){const l=s||this.latestPointerEvent,o=i||this.latestPanInfo,d=this.isDragging;if(this.cancel(),!d||!o||!l)return;const{velocity:f}=o;this.startAnimation(f);const{onDragEnd:m}=this.getProps();m&&We.postRender(()=>m(l,o))}cancel(){this.isDragging=!1;const{projection:s,animationState:i}=this.visualElement;s&&(s.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:l}=this.getProps();!l&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),i&&i.setActive(\"whileDrag\",!1)}updateAxis(s,i,l){const{drag:o}=this.getProps();if(!l||!Go(s,o,this.currentDirection))return;const d=this.getAxisMotionValue(s);let f=this.originPoint[s]+l[s];this.constraints&&this.constraints[s]&&(f=z2(f,this.constraints[s],this.elastic[s])),d.set(f)}resolveConstraints(){const{dragConstraints:s,dragElastic:i}=this.getProps(),l=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,o=this.constraints;s&&sr(s)?this.constraints||(this.constraints=this.resolveRefConstraints()):s&&l?this.constraints=B2(l.layoutBox,s):this.constraints=!1,this.elastic=H2(i),o!==this.constraints&&l&&this.constraints&&!this.hasMutatedConstraints&&Rn(d=>{this.constraints!==!1&&this.getAxisMotionValue(d)&&(this.constraints[d]=P2(l.layoutBox[d],this.constraints[d]))})}resolveRefConstraints(){const{dragConstraints:s,onMeasureDragConstraints:i}=this.getProps();if(!s||!sr(s))return!1;const l=s.current,{projection:o}=this.visualElement;if(!o||!o.layout)return!1;const d=FC(l,o.root,this.visualElement.getTransformPagePoint());let f=V2(o.layout.layoutBox,d);if(i){const m=i($C(f));this.hasMutatedConstraints=!!m,m&&(f=Uv(m))}return f}startAnimation(s){const{drag:i,dragMomentum:l,dragElastic:o,dragTransition:d,dragSnapToOrigin:f,onDragTransitionEnd:m}=this.getProps(),p=this.constraints||{},y=Rn(x=>{if(!Go(x,i,this.currentDirection))return;let g=p&&p[x]||{};f&&(g={min:0,max:0});const w=o?200:1e6,S=o?40:1e7,T={type:\"inertia\",velocity:l?s[x]:0,bounceStiffness:w,bounceDamping:S,timeConstant:750,restDelta:1,restSpeed:10,...d,...g};return this.startAxisValueAnimation(x,T)});return Promise.all(y).then(m)}startAxisValueAnimation(s,i){const l=this.getAxisMotionValue(s);return Hf(this.visualElement,s),l.start(Bh(s,l,0,i,this.visualElement,!1))}stopAnimation(){Rn(s=>this.getAxisMotionValue(s).stop())}pauseAnimation(){Rn(s=>this.getAxisMotionValue(s).animation?.pause())}getAnimationState(s){return this.getAxisMotionValue(s).animation?.state}getAxisMotionValue(s){const i=`_drag${s.toUpperCase()}`,l=this.visualElement.getProps(),o=l[i];return o||this.visualElement.getValue(s,(l.initial?l.initial[s]:void 0)||0)}snapToCursor(s){Rn(i=>{const{drag:l}=this.getProps();if(!Go(i,l,this.currentDirection))return;const{projection:o}=this.visualElement,d=this.getAxisMotionValue(i);if(o&&o.layout){const{min:f,max:m}=o.layout.layoutBox[i],p=d.get()||0;d.set(s[i]-it(f,m,.5)+p)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:s,dragConstraints:i}=this.getProps(),{projection:l}=this.visualElement;if(!sr(i)||!l||!this.constraints)return;this.stopAnimation();const o={x:0,y:0};Rn(f=>{const m=this.getAxisMotionValue(f);if(m&&this.constraints!==!1){const p=m.get();o[f]=U2({min:p,max:p},this.constraints[f])}});const{transformTemplate:d}=this.visualElement.getProps();this.visualElement.current.style.transform=d?d({},\"\"):\"none\",l.root&&l.root.updateScroll(),l.updateLayout(),this.resolveConstraints(),Rn(f=>{if(!Go(f,s,null))return;const m=this.getAxisMotionValue(f),{min:p,max:y}=this.constraints[f];m.set(it(p,y,o[f]))})}addListeners(){if(!this.visualElement.current)return;q2.set(this.visualElement,this);const s=this.visualElement.current,i=rr(s,\"pointerdown\",p=>{const{drag:y,dragListener:x=!0}=this.getProps();y&&x&&!Ov(p.target)&&this.start(p)}),l=()=>{const{dragConstraints:p}=this.getProps();sr(p)&&p.current&&(this.constraints=this.resolveRefConstraints())},{projection:o}=this.visualElement,d=o.addEventListener(\"measure\",l);o&&!o.layout&&(o.root&&o.root.updateScroll(),o.updateLayout()),We.read(l);const f=pr(window,\"resize\",()=>this.scalePositionWithinConstraints()),m=o.addEventListener(\"didUpdate\",(({delta:p,hasLayoutChanged:y})=>{this.isDragging&&y&&(Rn(x=>{const g=this.getAxisMotionValue(x);g&&(this.originPoint[x]+=p[x].translate,g.set(g.get()+p[x].translate))}),this.visualElement.render())}));return()=>{f(),i(),d(),m&&m()}}getProps(){const s=this.visualElement.getProps(),{drag:i=!1,dragDirectionLock:l=!1,dragPropagation:o=!1,dragConstraints:d=!1,dragElastic:f=Xf,dragMomentum:m=!0}=s;return{...s,drag:i,dragDirectionLock:l,dragPropagation:o,dragConstraints:d,dragElastic:f,dragMomentum:m}}}function Go(t,s,i){return(s===!0||s===t)&&(i===null||i===t)}function $2(t,s=10){let i=null;return Math.abs(t.y)>s?i=\"y\":Math.abs(t.x)>s&&(i=\"x\"),i}class G2 extends Na{constructor(s){super(s),this.removeGroupControls=On,this.removeListeners=On,this.controls=new I2(s)}mount(){const{dragControls:s}=this.node.getProps();s&&(this.removeGroupControls=s.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||On}update(){const{dragControls:s}=this.node.getProps(),{dragControls:i}=this.node.prevProps||{};s!==i&&(this.removeGroupControls(),s&&(this.removeGroupControls=s.subscribe(this.controls)))}unmount(){this.removeGroupControls(),this.removeListeners()}}const Ex=t=>(s,i)=>{t&&We.postRender(()=>t(s,i))};class Y2 extends Na{constructor(){super(...arguments),this.removePointerDownListener=On}onPointerDown(s){this.session=new yw(s,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:gw(this.node)})}createPanHandlers(){const{onPanSessionStart:s,onPanStart:i,onPan:l,onPanEnd:o}=this.node.getProps();return{onSessionStart:Ex(s),onStart:Ex(i),onMove:l,onEnd:(d,f)=>{delete this.session,o&&We.postRender(()=>o(d,f))}}}mount(){this.removePointerDownListener=rr(this.node.current,\"pointerdown\",s=>this.onPointerDown(s))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}let pf=!1;class F2 extends b.Component{componentDidMount(){const{visualElement:s,layoutGroup:i,switchLayoutGroup:l,layoutId:o}=this.props,{projection:d}=s;d&&(i.group&&i.group.add(d),l&&l.register&&o&&l.register(d),pf&&d.root.didUpdate(),d.addEventListener(\"animationComplete\",()=>{this.safeToRemove()}),d.setOptions({...d.options,onExitComplete:()=>this.safeToRemove()})),tc.hasEverUpdated=!0}getSnapshotBeforeUpdate(s){const{layoutDependency:i,visualElement:l,drag:o,isPresent:d}=this.props,{projection:f}=l;return f&&(f.isPresent=d,pf=!0,o||s.layoutDependency!==i||i===void 0||s.isPresent!==d?f.willUpdate():this.safeToRemove(),s.isPresent!==d&&(d?f.promote():f.relegate()||We.postRender(()=>{const m=f.getStack();(!m||!m.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:s}=this.props.visualElement;s&&(s.root.didUpdate(),Hh.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:s,layoutGroup:i,switchLayoutGroup:l}=this.props,{projection:o}=s;pf=!0,o&&(o.scheduleCheckAfterUnmount(),i&&i.group&&i.group.remove(o),l&&l.deregister&&l.deregister(o))}safeToRemove(){const{safeToRemove:s}=this.props;s&&s()}render(){return null}}function bw(t){const[s,i]=rw(),l=b.useContext(xh);return c.jsx(F2,{...t,layoutGroup:l,switchLayoutGroup:b.useContext(mw),isPresent:s,safeToRemove:i})}const X2={pan:{Feature:Y2},drag:{Feature:G2,ProjectionNode:lw,MeasureLayout:bw}};function Dx(t,s,i){const{props:l}=t;t.animationState&&l.whileHover&&t.animationState.setActive(\"whileHover\",i===\"Start\");const o=\"onHover\"+i,d=l[o];d&&We.postRender(()=>d(s,jr(s)))}class K2 extends Na{mount(){const{current:s}=this.node;s&&(this.unmount=RC(s,(i,l)=>(Dx(this.node,l,\"Start\"),o=>Dx(this.node,o,\"End\"))))}unmount(){}}class Q2 extends Na{constructor(){super(...arguments),this.isActive=!1}onFocus(){let s=!1;try{s=this.node.current.matches(\":focus-visible\")}catch{s=!0}!s||!this.node.animationState||(this.node.animationState.setActive(\"whileFocus\",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive(\"whileFocus\",!1),this.isActive=!1)}mount(){this.unmount=vr(pr(this.node.current,\"focus\",()=>this.onFocus()),pr(this.node.current,\"blur\",()=>this.onBlur()))}unmount(){}}function kx(t,s,i){const{props:l}=t;if(t.current instanceof HTMLButtonElement&&t.current.disabled)return;t.animationState&&l.whileTap&&t.animationState.setActive(\"whileTap\",i===\"Start\");const o=\"onTap\"+(i===\"End\"?\"\":i),d=l[o];d&&We.postRender(()=>d(s,jr(s)))}class Z2 extends Na{mount(){const{current:s}=this.node;s&&(this.unmount=_C(s,(i,l)=>(kx(this.node,l,\"Start\"),(o,{success:d})=>kx(this.node,o,d?\"End\":\"Cancel\")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const Kf=new WeakMap,gf=new WeakMap,J2=t=>{const s=Kf.get(t.target);s&&s(t)},W2=t=>{t.forEach(J2)};function eE({root:t,...s}){const i=t||document;gf.has(i)||gf.set(i,{});const l=gf.get(i),o=JSON.stringify(s);return l[o]||(l[o]=new IntersectionObserver(W2,{root:t,...s})),l[o]}function tE(t,s,i){const l=eE(s);return Kf.set(t,i),l.observe(t),()=>{Kf.delete(t),l.unobserve(t)}}const nE={some:0,all:1};class sE extends Na{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:s={}}=this.node.getProps(),{root:i,margin:l,amount:o=\"some\",once:d}=s,f={root:i?i.current:void 0,rootMargin:l,threshold:typeof o==\"number\"?o:nE[o]},m=p=>{const{isIntersecting:y}=p;if(this.isInView===y||(this.isInView=y,d&&!y&&this.hasEnteredView))return;y&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive(\"whileInView\",y);const{onViewportEnter:x,onViewportLeave:g}=this.node.getProps(),w=y?x:g;w&&w(p)};return tE(this.node.current,f,m)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>\"u\")return;const{props:s,prevProps:i}=this.node;[\"amount\",\"margin\",\"root\"].some(aE(s,i))&&this.startObserver()}unmount(){}}function aE({viewport:t={}},{viewport:s={}}={}){return i=>t[i]!==s[i]}const iE={inView:{Feature:sE},tap:{Feature:Z2},focus:{Feature:Q2},hover:{Feature:K2}},lE={layout:{ProjectionNode:lw,MeasureLayout:bw}},rE={...R2,...iE,...X2,...lE},Le=C2(rE,A2),Qh=\"https://rateright-growth-production.up.railway.app\";async function Zh(){try{const{data:{session:t}}=await Nt.auth.getSession();return t?.access_token||null}catch{return null}}async function k(t,s={}){const i=`${Qh}${t}`,l=await Zh(),d={headers:{\"Content-Type\":\"application/json\",...l?{Authorization:`Bearer ${l}`}:{},...s.headers},...s},f=await fetch(i,d);if(!f.ok){const m=await f.json().catch(()=>({error:\"Request failed\"}));throw new Error(m.error||`HTTP ${f.status}`)}return f.status===204?null:f.json()}const Tr={list:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/leads${s?`?${s}`:\"\"}`)},get:t=>k(`/api/leads/${t}`),create:t=>k(\"/api/leads\",{method:\"POST\",body:JSON.stringify(t)}),update:(t,s)=>k(`/api/leads/${t}`,{method:\"PATCH\",body:JSON.stringify(s)}),updateLead:(t,s)=>k(`/api/leads/${t}`,{method:\"PATCH\",body:JSON.stringify(s)}),delete:t=>k(`/api/leads/${t}`,{method:\"DELETE\"}),archive:(t,s)=>k(`/api/leads/${t}/archive`,{method:\"POST\",body:JSON.stringify({reason:s})}),archiveLead:(t,s)=>k(`/api/leads/${t}/archive`,{method:\"POST\",body:JSON.stringify({reason:s})}),importFromSheet:()=>k(\"/api/leads/import-sheet\",{method:\"POST\"}),search:t=>k(`/api/leads/search?q=${encodeURIComponent(t)}`),claim:t=>k(`/api/leads/${t}/claim`,{method:\"POST\"}),release:t=>k(`/api/leads/${t}/release`,{method:\"POST\"}),assignments:()=>k(\"/api/leads/assignments\")},Jk={get:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/call-list${s?`?${s}`:\"\"}`)},stats:()=>k(\"/api/call-list/stats\"),activity:t=>k(`/api/call-list/activity${t?`?date=${t}`:\"\"}`)},Wk={send:t=>k(\"/api/sms/send\",{method:\"POST\",body:JSON.stringify(t)}),batch:t=>k(\"/api/sms/batch\",{method:\"POST\",body:JSON.stringify(t)}),preview:t=>k(\"/api/sms/preview\",{method:\"POST\",body:JSON.stringify(t)}),requestContact:t=>k(\"/api/sms/request-contact\",{method:\"POST\",body:JSON.stringify({leadId:t})}),getTemplates:t=>k(`/api/sms/templates${t?`?category=${t}`:\"\"}`),getTemplate:t=>k(`/api/sms/templates/${t}`),createTemplate:t=>k(\"/api/sms/templates\",{method:\"POST\",body:JSON.stringify(t)}),updateTemplate:(t,s)=>k(`/api/sms/templates/${t}`,{method:\"PUT\",body:JSON.stringify(s)}),deleteTemplate:t=>k(`/api/sms/templates/${t}`,{method:\"DELETE\"}),useTemplate:t=>k(`/api/sms/templates/${t}/use`,{method:\"POST\"}),getConversations:(t=\"all\")=>k(`/api/sms/conversations?filter=${t}`),getConversation:t=>k(`/api/sms/conversation/${t}`),markAsRead:t=>k(`/api/sms/conversation/${t}/read`,{method:\"PATCH\"}),handleConversation:(t,s=!0)=>k(`/api/sms/conversation/${t}/handle`,{method:\"PATCH\",body:JSON.stringify({handled:s})}),getPrioritized:(t=50)=>k(`/api/sms/conversations/prioritized?limit=${t}`),getAiSuggestion:(t,s)=>k(\"/api/sms/ai-suggest\",{method:\"POST\",body:JSON.stringify({leadId:t,lastMessage:s})}),getScheduled:t=>k(`/api/sms/scheduled${t?`?leadId=${t}`:\"\"}`),cancelScheduled:t=>k(`/api/sms/scheduled/${t}`,{method:\"DELETE\"}),getStats:(t=30)=>k(`/api/sms/stats?days=${t}`),sendBatch:t=>k(\"/api/sms/send-batch\",{method:\"POST\",body:JSON.stringify({messages:t})})},oE={log:t=>k(\"/api/calls/log\",{method:\"POST\",body:JSON.stringify(t)}),outcomes:()=>k(\"/api/calls/outcomes\"),getHistory:(t,s=1)=>k(`/api/calls/history/${t}?limit=${s}`)},eR={get:t=>k(`/api/dossier/${t}`),update:(t,s)=>k(`/api/dossier/${t}`,{method:\"PATCH\",body:JSON.stringify(s)}),addFact:(t,s,i=\"manual\")=>k(`/api/dossier/${t}/add-fact`,{method:\"POST\",body:JSON.stringify({fact:s,source:i})}),addCallSummary:(t,s)=>k(`/api/dossier/${t}/add-call-summary`,{method:\"POST\",body:JSON.stringify(s)}),addObjection:(t,s)=>k(`/api/dossier/${t}/add-objection`,{method:\"POST\",body:JSON.stringify(s)})},tR={getAll:()=>k(\"/api/dashboard/all\"),getStats:()=>k(\"/api/dashboard/stats\"),getWisdom:()=>k(\"/api/dashboard/wisdom\"),rateWisdom:(t,s)=>k(\"/api/dashboard/wisdom/rate\",{method:\"POST\",body:JSON.stringify({wisdomId:t,rating:s})}),getStrategy:()=>k(\"/api/dashboard/strategy\"),getPriorityAction:()=>k(\"/api/dashboard/priority-action\"),getSlipping:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/dashboard/slipping${s?`?${s}`:\"\"}`)}},nc={getToken:()=>k(\"/api/voice/token\"),status:()=>k(\"/api/voice/status\"),lookupCaller:t=>k(`/api/voice/lookup-caller?phone=${encodeURIComponent(t)}`)},cE={submit:t=>k(\"/api/bug-report\",{method:\"POST\",body:JSON.stringify(t)})},It={getIntelBrief:t=>k(`/api/ai/intel-brief/${t}`),getLiveIntel:t=>k(`/api/ai/live-intel/${t}`),postCallSummary:t=>k(\"/api/ai/post-call-summary\",{method:\"POST\",body:JSON.stringify(t)}),draftMessage:t=>k(\"/api/ai/draft-message\",{method:\"POST\",body:JSON.stringify(t)}),transcribe:async t=>{const s=new FormData;s.append(\"audio\",t,\"audio.webm\");const i=`${Qh}/api/ai/transcribe`,l=await Zh(),o=l?{Authorization:`Bearer ${l}`}:{},d=await fetch(i,{method:\"POST\",body:s,headers:o});if(!d.ok)throw new Error(\"Transcription failed\");return d.json()},voiceCommand:t=>k(\"/api/ai/voice-command\",{method:\"POST\",body:JSON.stringify(t)}),objectionResponse:t=>k(\"/api/ai/objection-response\",{method:\"POST\",body:JSON.stringify(t)}),getConversionProbability:t=>k(`/api/ai/conversion-probability/${t}`),weeklyInsights:()=>k(\"/api/ai/weekly-insights\",{method:\"POST\"}),cleanupNotes:t=>k(\"/api/ai/cleanup-notes\",{method:\"POST\",body:JSON.stringify(t)}),getInsights:()=>k(\"/api/ai/insights\"),getDeepgramCredentials:()=>k(\"/api/ai/deepgram-credentials\"),saveCopilotSession:t=>k(\"/api/ai/copilot-session\",{method:\"POST\",body:JSON.stringify(t)}),suggestionFeedback:t=>k(\"/api/ai/suggestion-feedback\",{method:\"POST\",body:JSON.stringify(t)}),getSimilarWins:t=>k(`/api/ai/similar-wins/${t}`),getEffectiveResponses:(t,s)=>{const i=s?`?trade=${encodeURIComponent(s)}`:\"\";return k(`/api/ai/effective-responses/${t}${i}`)},companyResearch:(t,s=!1)=>{const i=s?\"?refresh=true\":\"\";return k(`/api/ai/company-research/${encodeURIComponent(t)}${i}`)},personResearch:(t,s=!1)=>k(`/api/ai/person-research/${t}${s?\"?refresh=true\":\"\"}`),updateIntel:t=>k(\"/api/ai/update-intel\",{method:\"POST\",body:JSON.stringify(t)}),parseIntelVoiceNote:t=>k(\"/api/ai/parse-intel-voice\",{method:\"POST\",body:JSON.stringify(t)}),extractContractor:t=>k(\"/api/ai/extract-contractor\",{method:\"POST\",body:JSON.stringify(t)}),addContractorLead:t=>k(\"/api/ai/extract-contractor\",{method:\"POST\",body:JSON.stringify({...t,createLead:!0})}),extractLeadCorrections:t=>k(\"/api/ai/extract-lead-corrections\",{method:\"POST\",body:JSON.stringify(t)}),draftSimilar:t=>k(\"/api/ai/draft-similar\",{method:\"POST\",body:JSON.stringify(t)})},nR={status:()=>k(\"/api/sync/platform/status\"),stats:()=>k(\"/api/sync/platform/stats\"),syncAll:(t={})=>k(\"/api/sync/platform\",{method:\"POST\",body:JSON.stringify(t)}),syncRecent:()=>k(\"/api/sync/platform/recent\",{method:\"POST\"})},sR={getFunnel:()=>k(\"/api/activation/funnel\"),getLeadsAtStage:(t,s)=>{const i=new URLSearchParams({stage:t});return s&&i.append(\"type\",s),k(`/api/activation/leads-at-stage?${i}`)},getStuck:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/activation/stuck${s?`?${s}`:\"\"}`)},getRevenueAtRisk:()=>k(\"/api/activation/revenue-at-risk\"),getMetrics:(t=30)=>k(`/api/activation/metrics?days=${t}`),getTransitions:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/activation/stage-transitions${s?`?${s}`:\"\"}`)},analyze:()=>k(\"/api/activation/analyze\"),generateNudge:t=>k(\"/api/activation/nudge\",{method:\"POST\",body:JSON.stringify({leadId:t})}),bulkNudge:t=>k(\"/api/activation/bulk-nudge\",{method:\"POST\",body:JSON.stringify(t)}),addToCallList:t=>k(\"/api/activation/add-to-call-list\",{method:\"POST\",body:JSON.stringify(t)}),getActionScript:(t,s=\"contractor\")=>k(`/api/activation/action-script?stage=${t}&type=${s}`),getDropoffAnalysis:(t,s=\"contractor\")=>k(`/api/activation/dropoff-analysis?stage=${t}&type=${s}`),getNudgeTemplates:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/activation/nudge-templates${s?`?${s}`:\"\"}`)},createNudgeTemplate:t=>k(\"/api/activation/nudge-templates\",{method:\"POST\",body:JSON.stringify(t)}),updateNudgeTemplate:(t,s)=>k(`/api/activation/nudge-templates/${t}`,{method:\"PATCH\",body:JSON.stringify(s)}),deleteNudgeTemplate:t=>k(`/api/activation/nudge-templates/${t}`,{method:\"DELETE\"}),getJourney:t=>k(`/api/activation/journey/${t}`),getDiagnosis:t=>k(`/api/activation/diagnose/${t}`),getSimilarWins:(t,s=5)=>k(`/api/activation/similar-wins/${t}?limit=${s}`)},hc={list:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/scripts${s?`?${s}`:\"\"}`)},get:t=>k(`/api/scripts/${t}`),create:t=>k(\"/api/scripts\",{method:\"POST\",body:JSON.stringify(t)}),update:(t,s)=>k(`/api/scripts/${t}`,{method:\"PATCH\",body:JSON.stringify(s)}),delete:t=>k(`/api/scripts/${t}`,{method:\"DELETE\"}),startSession:(t,s)=>k(`/api/scripts/${t}/use`,{method:\"POST\",body:JSON.stringify({lead_id:s})}),endSession:(t,s)=>k(`/api/scripts/sessions/${t}`,{method:\"PATCH\",body:JSON.stringify(s)}),getForLead:t=>k(`/api/scripts/for-lead/${t}`),getAIRecommendation:t=>k(`/api/scripts/ai-recommend/${t}`),recordUsage:(t,s=!1)=>k(`/api/scripts/${t}/use`,{method:\"POST\",body:JSON.stringify({replied:s})}),getAnalytics:(t=30)=>k(`/api/scripts/analytics/overview?days=${t}`),getObjections:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/scripts/objections/list${s?`?${s}`:\"\"}`)},getObjection:t=>k(`/api/scripts/objections/${t}`),createObjection:t=>k(\"/api/scripts/objections\",{method:\"POST\",body:JSON.stringify(t)}),addObjectionResponse:(t,s)=>k(`/api/scripts/objections/${t}/response`,{method:\"POST\",body:JSON.stringify({response:s})}),getGuidelines:()=>k(\"/api/scripts/guidelines\"),updateGuidelines:t=>k(\"/api/scripts/guidelines\",{method:\"PUT\",body:JSON.stringify(t)}),getGuidelinesHistory:(t=20)=>k(`/api/scripts/guidelines/history?limit=${t}`),checkCompliance:(t,s={})=>k(\"/api/scripts/compliance/check\",{method:\"POST\",body:JSON.stringify({message:t,options:s})}),autoFix:t=>k(\"/api/scripts/compliance/auto-fix\",{method:\"POST\",body:JSON.stringify({message:t})}),validateScript:t=>k(`/api/scripts/compliance/validate/${t}`,{method:\"POST\"}),batchValidate:t=>k(\"/api/scripts/compliance/batch-validate\",{method:\"POST\",body:JSON.stringify({scriptIds:t})}),getComplianceStats:()=>k(\"/api/scripts/compliance/stats\"),getQueue:(t=\"pending\",s=20)=>k(`/api/scripts/compliance/queue?status=${t}&limit=${s}`),approveItem:t=>k(`/api/scripts/compliance/queue/${t}/approve`,{method:\"POST\"}),rejectItem:(t,s)=>k(`/api/scripts/compliance/queue/${t}/reject`,{method:\"POST\",body:JSON.stringify({reason:s})}),editItem:(t,s)=>k(`/api/scripts/compliance/queue/${t}/edit`,{method:\"POST\",body:JSON.stringify({final_content:s})})},aR={list:()=>k(\"/api/achievements\"),getUserAchievements:()=>k(\"/api/achievements/user\"),check:()=>k(\"/api/achievements/check\",{method:\"POST\"})},iR={getUser:()=>k(\"/api/xp/user\"),award:t=>k(\"/api/xp/award\",{method:\"POST\",body:JSON.stringify(t)}),getHistory:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/xp/history${s?`?${s}`:\"\"}`)},getLeaderboard:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/xp/leaderboard${s?`?${s}`:\"\"}`)}},Rx={list:t=>k(`/api/sequences${t?`?channel=${t}`:\"\"}`),get:t=>k(`/api/sequences/${t}`),enroll:(t,s)=>k(`/api/sequences/${t}/enroll`,{method:\"POST\",body:JSON.stringify({lead_ids:Array.isArray(s)?s:[s]})}),unenroll:(t,s)=>k(`/api/sequences/${t}/unenroll`,{method:\"POST\",body:JSON.stringify({lead_id:s})}),getActiveEnrollments:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/sequences/enrollments/active${s?`?${s}`:\"\"}`)},getLeadEnrollments:t=>k(`/api/sequences/enrollments/lead/${t}`),pauseEnrollment:(t,s)=>k(`/api/sequences/enrollments/${t}/pause`,{method:\"POST\",body:JSON.stringify({reason:s})}),resumeEnrollment:t=>k(`/api/sequences/enrollments/${t}/resume`,{method:\"POST\"}),skipStep:t=>k(`/api/sequences/enrollments/${t}/skip`,{method:\"POST\"}),sendNow:t=>k(`/api/sequences/enrollments/${t}/send-now`,{method:\"POST\"}),getOptOutStatus:t=>k(`/api/sequences/lead/${t}/opt-out`),setOptOut:(t,s)=>k(`/api/sequences/lead/${t}/opt-out`,{method:\"POST\",body:JSON.stringify({opted_out:s})}),bulkEnrollPreview:(t,s=100,i)=>{const l=new URLSearchParams({dry_run:\"true\",limit:s.toString()});return i&&l.set(\"source\",i),k(`/api/sequences/${t}/bulk-enroll?${l}`,{method:\"POST\"})},bulkEnroll:(t,s=100,i)=>{const l=new URLSearchParams({limit:s.toString()});return i&&l.set(\"source\",i),k(`/api/sequences/${t}/bulk-enroll?${l}`,{method:\"POST\"})}},lR={getScores:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/coaching/scores${s?`?${s}`:\"\"}`)},scoreCall:t=>k(\"/api/coaching/score\",{method:\"POST\",body:JSON.stringify(t)}),getTips:()=>k(\"/api/coaching/tips\"),getWeekly:()=>k(\"/api/coaching/weekly\"),getPatterns:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/coaching/patterns${s?`?${s}`:\"\"}`)}},rR={getTrends:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/analytics/trends${s?`?${s}`:\"\"}`)},getPatterns:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/analytics/patterns${s?`?${s}`:\"\"}`)},getFunnel:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/analytics/funnel${s?`?${s}`:\"\"}`)},getBestTimes:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/analytics/best-times${s?`?${s}`:\"\"}`)},getSources:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/analytics/sources${s?`?${s}`:\"\"}`)},savePattern:t=>k(\"/api/analytics/patterns\",{method:\"POST\",body:JSON.stringify(t)})},oR={list:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/ai-alerts${s?`?${s}`:\"\"}`)},create:t=>k(\"/api/ai-alerts\",{method:\"POST\",body:JSON.stringify(t)}),markRead:t=>k(`/api/ai-alerts/${t}/read`,{method:\"PATCH\"}),dismiss:t=>k(`/api/ai-alerts/${t}/dismiss`,{method:\"PATCH\"}),markAllRead:()=>k(\"/api/ai-alerts/read-all\",{method:\"POST\"}),generate:()=>k(\"/api/ai-alerts/generate\",{method:\"POST\"})},cR={getLeaderboard:(t=\"today\")=>k(`/api/battleground/leaderboard?period=${t}`),getUserStats:t=>k(`/api/battleground/leaderboard/${t}`),saveSnapshot:()=>k(\"/api/battleground/leaderboard/snapshot\",{method:\"POST\"}),getHallOfFame:()=>k(\"/api/battleground/hall-of-fame\"),checkRecord:(t,s,i,l,o)=>k(\"/api/battleground/hall-of-fame/check\",{method:\"POST\",body:JSON.stringify({recordType:t,userId:s,userName:i,value:l,details:o})}),getChallenges:()=>k(\"/api/battleground/challenges\"),updateChallengeProgress:(t,s=1)=>k(\"/api/battleground/challenges/progress\",{method:\"POST\",body:JSON.stringify({actionType:t,count:s})}),generateChallenges:()=>k(\"/api/battleground/challenges/generate\",{method:\"POST\"}),getTeamPulse:(t=20)=>k(`/api/battleground/pulse?limit=${t}`),createPulseEvent:t=>k(\"/api/battleground/pulse\",{method:\"POST\",body:JSON.stringify(t)}),getUserBadges:t=>k(`/api/battleground/badges/${t}`),getCurrentBadges:()=>k(\"/api/battleground/badges\"),awardWeeklyBadges:()=>k(\"/api/battleground/badges/award-weekly\",{method:\"POST\"}),updateStreakTier:(t,s)=>k(\"/api/battleground/streak/update\",{method:\"POST\",body:JSON.stringify({userId:t,streakDays:s})}),getActiveDuels:()=>k(\"/api/battleground/duels/active\"),getDuelHistory:(t=10)=>k(`/api/battleground/duels/history?limit=${t}`),getDuelOdds:(t,s)=>k(`/api/battleground/duels/odds?targetId=${t}&duelType=${s}`),createDuel:(t,s,i)=>k(\"/api/battleground/duels/challenge\",{method:\"POST\",body:JSON.stringify({targetId:t,duelType:s,stakeAmount:i})}),acceptDuel:t=>k(`/api/battleground/duels/${t}/accept`,{method:\"POST\"}),declineDuel:t=>k(`/api/battleground/duels/${t}/decline`,{method:\"POST\"}),getDuelScores:t=>k(`/api/battleground/duels/${t}/scores`),createChallenge:t=>k(\"/api/battleground/challenges\",{method:\"POST\",body:JSON.stringify(t)}),joinChallenge:t=>k(`/api/battleground/challenges/${t}/join`,{method:\"POST\"}),getChallengeDetails:t=>k(`/api/battleground/challenges/${t}`),getTeam:()=>k(\"/api/battleground/team\"),getCelebrations:(t=10)=>k(`/api/battleground/celebrations?limit=${t}`)},uR={getToday:()=>k(\"/api/playbook/today\"),send:(t,s,i)=>k(\"/api/playbook/send\",{method:\"POST\",body:JSON.stringify({leadId:t,messageId:s,messageText:i})}),getBulkPreview:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/playbook/bulk-preview${s?`?${s}`:\"\"}`)},bulkSend:(t,s,i={})=>k(\"/api/playbook/bulk-send\",{method:\"POST\",body:JSON.stringify({batchId:t,leadIds:s,edits:i})})},Mx={getRecordings:()=>k(\"/api/voicemail/recordings\"),createRecording:async t=>{const s=await Zh(),i=await fetch(`${Qh}/api/voicemail/recordings`,{method:\"POST\",headers:{Authorization:`Bearer ${s}`},body:t});if(!i.ok){const l=await i.json().catch(()=>({error:\"Upload failed\"}));throw new Error(l.error||\"Failed to upload\")}return i.json()},createRecordingFromUrl:t=>k(\"/api/voicemail/recordings\",{method:\"POST\",body:JSON.stringify(t)}),deleteRecording:t=>k(`/api/voicemail/recordings/${t}`,{method:\"DELETE\"}),setDefault:t=>k(`/api/voicemail/recordings/${t}/default`,{method:\"PATCH\"}),drop:(t,s,i)=>k(\"/api/voicemail/drop\",{method:\"POST\",body:JSON.stringify({callSid:t,recordingId:s,leadId:i})}),getStats:()=>k(\"/api/voicemail/drops/stats\")},dR={getDashboard:(t=\"week\")=>k(`/api/manager/dashboard?period=${t}`),getAnalytics:(t=\"week\")=>k(`/api/manager/analytics?period=${t}`),getRepDetail:(t,s=\"week\")=>k(`/api/manager/rep/${t}?period=${s}`)},fR={getDashboard:()=>k(\"/api/intelligence/dashboard\"),track:t=>k(\"/api/intelligence/track\",{method:\"POST\",body:JSON.stringify(t)}),trackBatch:t=>k(\"/api/intelligence/track-batch\",{method:\"POST\",body:JSON.stringify({events:t})}),getSuggestions:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/intelligence/suggestions${s?`?${s}`:\"\"}`)},updateSuggestionStatus:(t,s)=>k(`/api/intelligence/suggestions/${t}/status`,{method:\"PATCH\",body:JSON.stringify(s)}),getFriction:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/intelligence/friction${s?`?${s}`:\"\"}`)},getPageStats:(t=7)=>k(`/api/intelligence/page-stats?days=${t}`),getMetrics:(t,s,i)=>{const l=new URLSearchParams({start_date:t});return s&&l.append(\"end_date\",s),i&&l.append(\"metric_name\",i),k(`/api/intelligence/metrics?${l}`)}},Ox={getVapidKey:()=>k(\"/api/notifications/vapid-public-key\"),subscribe:t=>k(\"/api/notifications/subscribe\",{method:\"POST\",body:JSON.stringify({subscription:t})}),unsubscribe:(t=null)=>k(\"/api/notifications/unsubscribe\",{method:\"DELETE\",body:JSON.stringify({endpoint:t})}),getPreferences:()=>k(\"/api/notifications/preferences\"),updatePreferences:t=>k(\"/api/notifications/preferences\",{method:\"PUT\",body:JSON.stringify(t)}),test:()=>k(\"/api/notifications/test\",{method:\"POST\"}),getStatus:()=>k(\"/api/notifications/status\")},qn=[{id:\"opener\",label:\"Opener\",icon:\"👋\"},{id:\"discovery\",label:\"Discovery\",icon:\"🔍\"},{id:\"value_prop\",label:\"Value Prop\",icon:\"💎\"},{id:\"objections\",label:\"Objections\",icon:\"🛡️\"},{id:\"close\",label:\"Close\",icon:\"🎯\"}],uE={opener:{script:\"Hey, it's [your name] from RateRight. How's it going?\",tip:\"Be warm and conversational. Match their energy.\",alternatives:[\"Hi [name], this is [you] from RateRight - got a quick minute?\",\"G'day [name], [you] here from RateRight. How's business?\"]},discovery:{script:\"What's your biggest challenge finding workers right now?\",tip:\"Listen more than you talk. Take mental notes.\",alternatives:[\"How are you currently sourcing your workers?\",\"What trades are hardest to find good people for?\",\"How many workers do you typically need on a job?\"]},value_prop:{script:\"We connect you with pre-vetted workers at just 9.9% - no lock-in contracts.\",tip:\"Focus on their pain points. Make it about them.\",alternatives:[\"Most of our contractors find workers within 24 hours.\",\"You only pay when they work - no upfront fees.\",\"Every worker is vetted with references and qualifications checked.\"]},objections:{script:\"I hear you. What would need to change for this to make sense?\",tip:\"Don't argue. Acknowledge and redirect.\",alternatives:[\"That's a fair point. Here's how other contractors handle that...\",\"I understand. Can I ask what you're comparing us to?\",\"Makes sense. What if we could address that concern?\"]},close:{script:\"Let me get you set up - it takes about 2 minutes. What's your email?\",tip:\"Assume the sale. Be confident.\",alternatives:[\"When's your next job starting? Let's get you ready.\",\"I'll send you the link now - what email should I use?\",\"Want me to walk you through it while we're on the phone?\"]}};function dE({lead:t,duration:s,onHangUp:i,onMute:l,isMuted:o,onMarkHot:d}){const[f,m]=b.useState(0),[p,y]=b.useState(null),[x,g]=b.useState(null),[w,S]=b.useState(!1),[T,N]=b.useState([]),[R,D]=b.useState(null),[A,C]=b.useState([]);b.useEffect(()=>{t?.id&&(B(),_())},[t?.id]);const B=async()=>{try{const $=await hc.getRecommendation(t.id);$?.script&&y($.script)}catch{console.log(\"Using default scripts\")}},_=async()=>{try{const $=await It.getIntelBrief(t.id);if($){D($);const W=[];$.openingLine&&W.push({type:\"opener\",text:$.openingLine}),$.talkingPoints?.length&&$.talkingPoints.forEach(se=>W.push({type:\"point\",text:se})),$.similarWins?.length&&W.push({type:\"win\",text:`Similar win: ${$.similarWins[0].name} - \"${$.similarWins[0].whatWorked}\"`}),$.company?.sales_angle&&W.push({type:\"angle\",text:$.company.sales_angle}),C(W)}}catch{console.log(\"Intel not available\")}},F=$=>{const W=uE[$];if(!p)return W;switch($){case\"opener\":return{...W,script:p.opening||W.script};case\"discovery\":return{...W,script:p.discovery_questions?.[0]?.question||W.script,alternatives:p.discovery_questions?.slice(1,4).map(se=>se.question)||W.alternatives};case\"value_prop\":return{...W,script:p.value_props?.[0]?.prop||W.script,alternatives:p.value_props?.slice(1,4).map(se=>se.prop)||W.alternatives};case\"objections\":return W;case\"close\":return{...W,script:p.closing_techniques?.[0]?.script||W.script,alternatives:p.closing_techniques?.slice(1,4).map(se=>se.script)||W.alternatives};default:return W}},P=async($,W)=>{await navigator.clipboard.writeText($),g(W),setTimeout(()=>g(null),500)},H=()=>{f{m($)},X=()=>{S(!0),d?.()},te=$=>{const W=Math.floor($/60),se=$%60;return`${W}:${se.toString().padStart(2,\"0\")}`},Y=`${t?.first_name||\"\"} ${t?.last_name||\"\"}`.trim()||\"Unknown\";return c.jsxs(\"div\",{className:\"fixed inset-0 z-[60] bg-slate-900 flex flex-col\",children:[c.jsxs(\"div\",{className:\"bg-slate-800 px-4 py-3 flex items-center justify-between safe-area-top\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-3\",children:[c.jsx(\"div\",{className:\"w-10 h-10 rounded-full bg-slate-700 flex items-center justify-center\",children:c.jsx(cr,{className:\"w-5 h-5 text-slate-400\"})}),c.jsxs(\"div\",{children:[c.jsx(\"h2\",{className:\"font-bold text-white\",children:Y}),c.jsxs(\"div\",{className:\"flex items-center gap-2\",children:[c.jsx(\"div\",{className:\"w-2 h-2 rounded-full bg-green-500 animate-pulse\"}),c.jsx(\"span\",{className:\"text-green-400 font-mono text-sm\",children:te(s)})]})]})]}),c.jsx(\"button\",{onClick:X,disabled:w,className:`p-2 rounded-full ${w?\"bg-amber-500 text-white\":\"bg-slate-700 text-slate-400\"}`,children:c.jsx(nl,{className:\"w-5 h-5\"})})]}),c.jsx(\"div\",{className:\"bg-slate-800/50 px-4 py-3 flex items-center gap-2\",children:qn.map(($,W)=>c.jsxs(\"button\",{onClick:()=>z(W),className:`flex-1 py-2 rounded-lg text-center transition-all ${T.includes(W)?\"bg-emerald-600 text-white\":W===f?\"bg-violet-600 text-white ring-2 ring-violet-400\":\"bg-slate-700/50 text-slate-400\"}`,children:[c.jsx(\"span\",{className:\"text-lg\",children:$.icon}),c.jsx(\"p\",{className:\"text-[10px] font-bold mt-0.5\",children:T.includes(W)?\"✓\":$.label})]},$.id))}),c.jsx(\"div\",{className:\"flex-1 overflow-y-auto pb-40\",children:c.jsxs(\"div\",{className:\"p-4 space-y-4\",children:[A.length>0&&c.jsxs(\"div\",{className:\"bg-blue-500/10 border border-blue-500/20 rounded-xl p-3\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-2 mb-2\",children:[c.jsx(ac,{className:\"w-4 h-4 text-blue-400\"}),c.jsx(\"span\",{className:\"text-xs font-bold text-blue-400 uppercase\",children:\"Intel & Talking Points\"})]}),c.jsx(\"div\",{className:\"space-y-2\",children:A.slice(0,4).map(($,W)=>c.jsxs(\"div\",{className:\"flex items-start gap-2\",children:[c.jsx(\"span\",{className:\"text-blue-400 mt-0.5\",children:$.type===\"opener\"?\"💬\":$.type===\"win\"?\"🏆\":$.type===\"angle\"?\"🎯\":\"•\"}),c.jsx(\"p\",{className:\"text-blue-200/80 text-sm\",children:$.text})]},W))})]}),R?.company?.name&&c.jsxs(\"div\",{className:\"flex items-center gap-2 px-1\",children:[c.jsx(jc,{className:\"w-4 h-4 text-slate-500\"}),c.jsxs(\"span\",{className:\"text-slate-400 text-sm\",children:[R.company.name,R.company.industry&&` • ${R.company.industry}`,R.company.size&&` • ${R.company.size}`]})]}),c.jsxs(\"div\",{className:\"text-center py-2\",children:[c.jsx(\"span\",{className:\"text-3xl\",children:qn[f].icon}),c.jsx(\"h3\",{className:\"text-xl font-bold text-white mt-2\",children:qn[f].label}),c.jsxs(\"p\",{className:\"text-slate-400 text-sm\",children:[\"Stage \",f+1,\" of \",qn.length]})]}),c.jsxs(\"div\",{className:\"bg-gradient-to-br from-violet-600/20 to-purple-600/10 border border-violet-500/30 rounded-2xl p-4\",children:[c.jsxs(\"div\",{className:\"flex items-start justify-between mb-2\",children:[c.jsx(\"span\",{className:\"text-xs font-bold text-violet-400 uppercase\",children:\"Say This\"}),c.jsx(\"button\",{onClick:()=>P(F(qn[f].id).script,\"main\"),className:\"p-2 -m-2 text-slate-400 hover:text-white\",children:x===\"main\"?c.jsx(ba,{className:\"w-4 h-4 text-green-400\"}):c.jsx(Cf,{className:\"w-4 h-4\"})})]}),c.jsxs(\"p\",{className:\"text-white text-lg leading-relaxed\",children:['\"',F(qn[f].id).script,'\"']})]}),c.jsxs(\"div\",{className:\"bg-amber-500/10 border border-amber-500/20 rounded-xl px-4 py-3\",children:[c.jsx(\"span\",{className:\"text-xs font-bold text-amber-400 uppercase\",children:\"💡 Tip\"}),c.jsx(\"p\",{className:\"text-amber-200/80 text-sm mt-1\",children:F(qn[f].id).tip})]}),c.jsxs(\"div\",{children:[c.jsx(\"h4\",{className:\"text-sm font-bold text-slate-400 mb-2 px-1\",children:\"Or Try These:\"}),c.jsx(\"div\",{className:\"space-y-2\",children:F(qn[f].id).alternatives.map(($,W)=>c.jsxs(\"div\",{className:\"bg-slate-800/50 border border-slate-700 rounded-xl p-3 flex items-start gap-3\",children:[c.jsxs(\"p\",{className:\"text-slate-300 text-sm flex-1\",children:['\"',$,'\"']}),c.jsx(\"button\",{onClick:()=>P($,`alt-${W}`),className:\"p-1 text-slate-500 hover:text-white flex-shrink-0\",children:x===`alt-${W}`?c.jsx(ba,{className:\"w-4 h-4 text-green-400\"}):c.jsx(Cf,{className:\"w-4 h-4\"})})]},W))})]}),f(i&&s?W(s):se(),()=>{ie()}),[]);const W=ee=>{console.log(\"[TwilioCall] Attaching to inbound call\"),X.current=ee,p(\"in-progress\"),Y.current=Date.now(),I();const ge=ee.parameters?.CallSid||null;console.log(\"[TwilioCall] Inbound call CallSid:\",ge),d?.(ge),ee.on(\"disconnect\",()=>{const Ee=Y.current?Math.floor((Date.now()-Y.current)/1e3):0;console.log(\"[TwilioCall] Inbound call disconnected, duration:\",Ee),p(\"ended\"),K(),$.current||($.current=!0,setTimeout(()=>{o?.(Ee)},500))}),ee.on(\"error\",Ee=>{console.error(\"[TwilioCall] Inbound call error:\",Ee),T(Ee.message),p(\"ended\"),K()})},se=async()=>{try{const{token:ee}=await nc.getToken(),ge=new Cb(ee,{logLevel:\"debug\",codecPreferences:[\"opus\",\"pcmu\"],enableRingingState:!0,edge:\"ashburn\"});ge.on(\"error\",Ee=>{console.error(\"Twilio Device error:\",Ee),T(Ee.message),p(\"ended\")}),z.current=ge,p(\"ready\"),O()}catch(ee){console.error(\"Failed to initialize Twilio:\",ee),T(ee.message),p(\"ended\")}},O=async()=>{if(z.current){if(!t?.phone){T(\"No phone number for this lead\"),p(\"ended\");return}try{p(\"connecting\");const ee=await z.current.connect({params:{To:t.phone,leadId:t?.id}});X.current=ee,ee.on(\"ringing\",()=>{p(\"ringing\")}),ee.on(\"accept\",()=>{p(\"in-progress\"),Y.current=Date.now(),I();const ge=ee.parameters?.CallSid||null;console.log(\"[TwilioCall] Call connected, CallSid:\",ge),d?.(ge)}),ee.on(\"disconnect\",()=>{const ge=Y.current?Math.floor((Date.now()-Y.current)/1e3):0;p(\"ended\"),K(),$.current||($.current=!0,setTimeout(()=>{o?.(ge)},500))}),ee.on(\"cancel\",()=>{p(\"ended\"),K(),$.current||($.current=!0,o?.(0))}),ee.on(\"error\",ge=>{console.error(\"Call error:\",ge),T(ge.message),p(\"ended\"),K()})}catch(ee){console.error(\"Failed to make call:\",ee),T(ee.message),p(\"ended\")}}},I=()=>{te.current=setInterval(()=>{Y.current&&x(Math.floor((Date.now()-Y.current)/1e3))},1e3)},K=()=>{te.current&&(clearInterval(te.current),te.current=null)},ie=()=>{K(),!i&&X.current&&X.current.disconnect(),!i&&z.current&&z.current.destroy()},oe=()=>{X.current?X.current.disconnect():l?.()},xe=()=>{X.current&&(g?X.current.mute(!1):X.current.mute(!0),w(!g))},Te=async()=>{if(!(D.length>0)){B(!0);try{const ee=await Mx.getRecordings();A(ee||[])}catch(ee){console.error(\"Failed to load VM recordings:\",ee)}finally{B(!1)}}},ae=async ee=>{const ge=X.current?.parameters?.CallSid;if(!ge){console.error(\"No CallSid available\");return}F(!0);try{await Mx.drop(ge,ee.id,t?.id),H(!0),R(!1)}catch(Ee){console.error(\"VM drop failed:\",Ee),T(\"Failed to drop voicemail\")}finally{F(!1)}},ce=ee=>{const ge=Math.floor(ee/60),Ee=ee%60;return`${ge}:${Ee.toString().padStart(2,\"0\")}`},ne=()=>{switch(m){case\"initializing\":return\"Setting up...\";case\"ready\":return\"Starting call...\";case\"connecting\":return\"Connecting...\";case\"ringing\":return\"Ringing...\";case\"in-progress\":return ce(y);case\"ended\":return\"Call ended\";default:return\"\"}},ue=()=>{switch(m){case\"ringing\":return\"text-amber-400\";case\"in-progress\":return\"text-green-400\";case\"ended\":return\"text-slate-400\";default:return\"text-blue-400\"}},de=`${t?.first_name||\"\"} ${t?.last_name||\"\"}`.trim()||\"Unknown\";return m===\"in-progress\"&&t?c.jsx(dE,{lead:t,duration:y,isMuted:g,onMute:xe,onHangUp:oe,onMarkHot:()=>{console.log(\"Marked hot during call\")}}):c.jsxs(Le.div,{initial:{y:100,opacity:0},animate:{y:0,opacity:1},exit:{y:100,opacity:0},className:\"fixed bottom-0 inset-x-0 z-[60] bg-gradient-to-t from-slate-900 via-slate-900 to-slate-900/95 rounded-t-3xl shadow-2xl pb-safe\",children:[c.jsxs(\"div\",{className:\"px-4 pt-4 pb-2 flex items-center gap-3\",children:[c.jsx(\"div\",{className:\"w-12 h-12 rounded-full bg-slate-700 flex items-center justify-center flex-shrink-0\",children:c.jsx(cr,{className:\"w-6 h-6 text-slate-400\"})}),c.jsxs(\"div\",{className:\"flex-1 min-w-0\",children:[c.jsx(\"h2\",{className:\"text-lg font-bold text-white truncate\",children:de}),c.jsxs(\"div\",{className:\"flex items-center gap-2\",children:[c.jsx(\"span\",{className:`text-sm font-medium ${ue()}`,children:ne()}),m===\"in-progress\"&&f&&c.jsxs(\"div\",{className:\"flex items-center gap-1\",children:[c.jsx(Yj,{className:\"w-3 h-3 text-emerald-400 animate-pulse\"}),c.jsx(\"span\",{className:\"text-xs text-emerald-400\",children:\"Recording\"})]})]})]}),m===\"ringing\"&&c.jsx(\"div\",{className:\"relative w-8 h-8\",children:c.jsx(Le.div,{className:\"absolute inset-0 rounded-full border-2 border-amber-400/50\",animate:{scale:[1,1.5],opacity:[.5,0]},transition:{duration:1.5,repeat:1/0}})})]}),S&&c.jsx(\"p\",{className:\"text-red-400 text-sm text-center px-4 pb-2\",children:S}),c.jsx(\"div\",{className:\"px-4 pb-6 pt-2\",children:m!==\"ended\"?c.jsxs(\"div\",{className:\"flex items-center justify-center gap-6\",children:[c.jsx(\"button\",{onClick:xe,disabled:m!==\"in-progress\",title:g?\"Unmute\":\"Mute\",className:`w-14 h-14 rounded-full flex items-center justify-center transition-colors ${g?\"bg-red-500 text-white\":\"bg-slate-700 text-white disabled:opacity-50\"}`,children:g?c.jsx(Tc,{className:\"w-6 h-6\"}):c.jsx(ti,{className:\"w-6 h-6\"})}),c.jsx(\"button\",{onClick:oe,title:\"End call\",className:\"w-16 h-16 rounded-full bg-red-500 text-white flex items-center justify-center shadow-lg shadow-red-500/30 active:scale-95 transition-transform\",children:c.jsx(ur,{className:\"w-8 h-8\"})}),c.jsx(\"button\",{onClick:()=>{R(!0),Te()},disabled:m===\"initializing\"||m===\"connecting\"||P,title:P?\"Voicemail dropped!\":\"Drop voicemail\",className:`w-14 h-14 rounded-full flex items-center justify-center transition-colors ${P?\"bg-green-600 text-white\":\"bg-amber-600 text-white disabled:opacity-50\"}`,children:P?c.jsx(ba,{className:\"w-6 h-6\"}):c.jsx(ey,{className:\"w-6 h-6\"})})]}):c.jsx(\"button\",{onClick:()=>{$.current||($.current=!0,o?.(y))},className:\"w-full py-4 bg-blue-600 text-white rounded-xl font-bold text-lg\",children:\"Continue\"})}),c.jsx(si,{children:N&&c.jsx(Le.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:\"fixed inset-0 z-[70] bg-black/60 flex items-end justify-center\",onClick:()=>R(!1),children:c.jsxs(Le.div,{initial:{y:\"100%\"},animate:{y:0},exit:{y:\"100%\"},className:\"w-full max-w-md bg-slate-800 rounded-t-2xl p-4 pb-8\",onClick:ee=>ee.stopPropagation(),children:[c.jsxs(\"div\",{className:\"flex items-center justify-between mb-4\",children:[c.jsx(\"h3\",{className:\"text-lg font-bold text-white\",children:\"Drop Voicemail\"}),c.jsx(\"button\",{onClick:()=>R(!1),className:\"w-8 h-8 rounded-full bg-slate-700 flex items-center justify-center\",children:c.jsx(Gt,{className:\"w-5 h-5 text-slate-400\"})})]}),C?c.jsx(\"div\",{className:\"flex items-center justify-center py-8\",children:c.jsx(_n,{className:\"w-6 h-6 text-blue-400 animate-spin\"})}):D.length===0?c.jsxs(\"div\",{className:\"text-center py-8 text-slate-400\",children:[\"No voicemail recordings yet.\",c.jsx(\"br\",{}),c.jsx(\"span\",{className:\"text-sm\",children:\"Add recordings in Settings → Voicemail\"})]}):c.jsx(\"div\",{className:\"space-y-2 max-h-64 overflow-y-auto\",children:D.map(ee=>c.jsxs(\"button\",{onClick:()=>ae(ee),disabled:_,className:\"w-full p-3 bg-slate-700/50 rounded-xl flex items-center gap-3 hover:bg-slate-700 transition-colors disabled:opacity-50\",children:[c.jsx(\"div\",{className:\"w-10 h-10 rounded-full bg-amber-600/20 flex items-center justify-center flex-shrink-0\",children:c.jsx(ey,{className:\"w-5 h-5 text-amber-400\"})}),c.jsxs(\"div\",{className:\"flex-1 text-left\",children:[c.jsx(\"p\",{className:\"text-white font-medium\",children:ee.name}),ee.description&&c.jsx(\"p\",{className:\"text-slate-400 text-sm truncate\",children:ee.description})]}),ee.is_default&&c.jsx(\"span\",{className:\"text-xs bg-blue-600/30 text-blue-400 px-2 py-0.5 rounded\",children:\"Default\"}),_&&c.jsx(_n,{className:\"w-4 h-4 text-blue-400 animate-spin\"})]},ee.id))}),c.jsx(\"p\",{className:\"text-xs text-slate-500 text-center mt-4\",children:\"Selecting a voicemail will play it to the recipient and end the call\"})]})})})]})}function hE({candidate:t,sourceLeadId:s,onAdd:i,onDismiss:l}){const{user:o}=br(),[d,f]=b.useState(!1),m=async()=>{f(!0);try{const x=await It.addContractorLead({sourceLeadId:s,companyName:t.company,projectName:t.project,userEmail:o?.email||\"unknown\"});x.success&&x.lead_id?i(x.lead_id,t):alert(\"Failed to create lead\")}catch(x){console.error(\"Add contractor error:\",x),alert(\"Failed to create lead: \"+x.message)}finally{f(!1)}},p=`${t.first_name||\"\"} ${t.last_name||\"\"}`.trim(),y=Math.round((t.confidence||.5)*100);return c.jsxs(\"div\",{className:\"fixed inset-0 z-50 flex items-center justify-center p-4\",children:[c.jsx(\"div\",{className:\"absolute inset-0 bg-black/60 backdrop-blur-sm\",onClick:l}),c.jsxs(\"div\",{className:\"relative w-full max-w-sm bg-white rounded-2xl shadow-2xl overflow-hidden animate-fade-in\",children:[c.jsx(\"div\",{className:\"bg-gradient-to-r from-amber-500 to-orange-500 px-5 py-4\",children:c.jsxs(\"div\",{className:\"flex items-center justify-between\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-3\",children:[c.jsx(\"div\",{className:\"w-10 h-10 bg-white/20 rounded-xl flex items-center justify-center\",children:c.jsx(nl,{className:\"w-5 h-5 text-white\"})}),c.jsxs(\"div\",{children:[c.jsx(\"h2\",{className:\"text-white font-bold text-lg\",children:\"Contractor Found!\"}),c.jsxs(\"p\",{className:\"text-white/80 text-sm\",children:[y,\"% confidence\"]})]})]}),c.jsx(\"button\",{onClick:l,className:\"w-8 h-8 bg-white/20 rounded-full flex items-center justify-center\",children:c.jsx(Gt,{className:\"w-4 h-4 text-white\"})})]})}),c.jsxs(\"div\",{className:\"p-5\",children:[c.jsxs(\"div\",{className:\"text-center mb-4\",children:[c.jsx(\"h3\",{className:\"text-xl font-bold text-slate-900\",children:p||\"Unknown\"}),t.job_title&&c.jsxs(\"div\",{className:\"flex items-center justify-center gap-2 mt-1 text-slate-600\",children:[c.jsx(Eb,{className:\"w-4 h-4\"}),c.jsx(\"span\",{children:t.job_title})]})]}),c.jsxs(\"div\",{className:\"bg-slate-50 rounded-xl p-4 mb-4 space-y-2\",children:[t.company&&c.jsxs(\"div\",{className:\"flex items-center gap-2 text-slate-700\",children:[c.jsx(Fj,{className:\"w-4 h-4 text-slate-400\"}),c.jsx(\"span\",{className:\"font-semibold\",children:t.company})]}),t.project&&c.jsxs(\"div\",{className:\"flex items-center gap-2 text-slate-600\",children:[c.jsx(ty,{className:\"w-4 h-4 text-slate-400\"}),c.jsxs(\"span\",{children:[t.project,\" Project\"]})]}),t.location&&c.jsxs(\"div\",{className:\"flex items-center gap-2 text-slate-500 text-sm\",children:[c.jsx(ty,{className:\"w-4 h-4 text-slate-400\"}),c.jsx(\"span\",{children:t.location})]})]}),t.linkedin_url&&c.jsxs(\"a\",{href:t.linkedin_url,target:\"_blank\",rel:\"noopener noreferrer\",className:\"flex items-center justify-center gap-2 mb-4 py-2 bg-[#0A66C2] text-white rounded-lg text-sm font-medium hover:bg-[#004182]\",children:[c.jsx(Xj,{className:\"w-4 h-4\"}),\"View LinkedIn Profile\"]}),t.source_worker&&c.jsx(\"div\",{className:\"bg-amber-50 rounded-lg p-3 mb-4 border border-amber-200\",children:c.jsxs(\"p\",{className:\"text-sm text-amber-800\",children:[c.jsx(\"span\",{className:\"font-semibold\",children:\"Source:\"}),\" Worker intel from \",t.source_worker]})}),c.jsxs(\"div\",{className:\"flex gap-3\",children:[c.jsx(\"button\",{onClick:l,className:\"flex-1 py-3 bg-slate-100 text-slate-700 rounded-xl font-semibold hover:bg-slate-200\",children:\"Dismiss\"}),c.jsxs(\"button\",{onClick:m,disabled:d,className:\"flex-1 py-3 bg-gradient-to-r from-green-500 to-emerald-500 text-white rounded-xl font-semibold flex items-center justify-center gap-2 hover:from-green-600 hover:to-emerald-600 disabled:opacity-50\",children:[d?c.jsx(_n,{className:\"w-5 h-5 animate-spin\"}):c.jsx(Af,{className:\"w-5 h-5\"}),\"Add as Lead\"]})]})]})]})]})}function mE(t){const s=Math.floor(t/60),i=t%60;return`${s}:${i.toString().padStart(2,\"0\")}`}const pE={opener:\"Opener\",discovery:\"Discovery\",value_prop:\"Value Props\",objections:\"Objections\",close:\"Close\"},_x=[\"opener\",\"discovery\",\"value_prop\",\"objections\",\"close\"];function gE({duration:t,leadName:s,isListening:i,onMinimize:l}){return c.jsxs(\"div\",{className:\"bg-slate-800 px-4 py-3 flex items-center justify-between safe-area-top\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-3\",children:[c.jsx(\"div\",{className:`w-2.5 h-2.5 rounded-full ${i?\"bg-red-500 animate-pulse\":\"bg-slate-500\"}`}),c.jsx(\"span\",{className:\"text-white font-mono text-lg font-bold tabular-nums\",children:mE(t)})]}),c.jsx(\"span\",{className:\"text-white font-medium truncate max-w-32\",children:s||\"Unknown\"}),c.jsx(\"button\",{onClick:l,className:\"p-2 -mr-2 text-slate-400 hover:text-white\",children:c.jsx(Kj,{className:\"w-5 h-5\"})})]})}function yE({intel:t}){const s=t?.personal_intel?.conversation_starters||t?.person?.conversation_starters||[],i=t?.personal_intel?.interest_news||t?.interest_news,l=[];return i?.items?.length>0&&i.items.slice(0,2).forEach(o=>{l.push({type:\"news\",text:o.talking_point||o.headline,source:o.topic||o.source,emoji:o.topic?.toLowerCase().includes(\"liverpool\")?\"⚽\":o.topic?.toLowerCase().includes(\"f1\")?\"🏎️\":o.topic?.toLowerCase().includes(\"gaa\")?\"🏐\":\"📰\"})}),s.slice(0,3-l.length).forEach(o=>{l.push({type:\"starter\",text:typeof o==\"string\"?o:o.text,source:typeof o==\"string\"?null:o.topic,emoji:\"💬\"})}),l.length===0?null:c.jsxs(\"div\",{className:\"bg-gradient-to-r from-blue-500/20 to-purple-500/20 border border-blue-500/30 rounded-2xl p-3\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-2 mb-2\",children:[c.jsx(\"span\",{className:\"text-sm\",children:\"🎯\"}),c.jsx(\"span\",{className:\"text-xs font-bold text-blue-300 uppercase tracking-wide\",children:\"Ice Breakers\"})]}),c.jsx(\"div\",{className:\"space-y-2\",children:l.map((o,d)=>c.jsxs(\"div\",{className:\"flex items-start gap-2\",children:[c.jsx(\"span\",{className:\"text-base flex-shrink-0\",children:o.emoji}),c.jsxs(\"div\",{className:\"flex-1 min-w-0\",children:[c.jsxs(\"p\",{className:\"text-white text-sm leading-snug\",children:['\"',o.text,'\"']}),o.source&&c.jsx(\"p\",{className:\"text-slate-400 text-xs mt-0.5\",children:o.source})]})]},d))})]})}function xE({stage:t,script:s,openingLine:i}){const[l,o]=b.useState(!1),d=_x.indexOf(t),m=(()=>{if(!s)return i||\"Hey, it's [your name] from RateRight. How's it going?\";switch(t){case\"opener\":return s.opening||i||\"Hey, it's [your name] from RateRight. How's it going?\";case\"discovery\":return s.discovery_questions?.[0]?.question||\"What's your biggest challenge finding workers right now?\";case\"value_prop\":return s.value_props?.[0]?.prop||\"We connect you with pre-vetted workers at just 9.9% - no lock-in contracts.\";case\"objections\":return\"Listen for concerns and address them directly.\";case\"close\":return s.closing_techniques?.[0]?.script||\"Let me get you set up - it takes about 2 minutes. What's your email?\";default:return s.opening||\"Start the conversation...\"}})(),p=async()=>{await navigator.clipboard.writeText(m),o(!0),setTimeout(()=>o(!1),500)};return c.jsxs(\"div\",{className:\"bg-slate-800/50 border border-slate-700 rounded-2xl p-4 relative\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-2 mb-3\",children:[c.jsx(\"span\",{className:\"text-xs font-bold text-violet-400 uppercase tracking-wide\",children:pE[t]||\"Script\"}),c.jsx(\"div\",{className:\"flex-1 h-px bg-slate-700\"}),c.jsxs(\"span\",{className:\"text-xs text-slate-500\",children:[d+1,\"/\",_x.length]})]}),c.jsxs(\"p\",{className:\"text-white text-base leading-relaxed pr-8\",children:['\"',m,'\"']}),c.jsx(\"button\",{onClick:p,className:\"absolute top-4 right-4 p-2 text-slate-400 hover:text-white transition-colors\",children:l?c.jsx(ba,{className:\"w-4 h-4 text-green-400\"}):c.jsx(Cf,{className:\"w-4 h-4\"})})]})}function bE({company:t,person:s,onExpand:i}){if(!t&&!s)return null;const l=[];return t?.name&&l.push(t.name),t?.industry&&l.push(t.industry),t?.size?l.push(t.size):s?.job_title&&l.push(s.job_title),l.length===0?null:c.jsxs(\"button\",{onClick:i,className:\"bg-slate-800/30 border border-slate-700/50 rounded-xl px-4 py-2.5 flex items-center gap-3 w-full text-left\",children:[c.jsx(jc,{className:\"w-4 h-4 text-blue-400 flex-shrink-0\"}),c.jsx(\"span\",{className:\"text-sm text-slate-300 truncate flex-1\",children:l.join(\" • \")}),c.jsx(Ab,{className:\"w-4 h-4 text-slate-500 flex-shrink-0\"})]})}function vE({type:t,trigger:s,suggestion:i,onDismiss:l}){const o=t===\"buying_signal\";return c.jsxs(Le.div,{initial:{y:100,opacity:0,scale:.95},animate:{y:0,opacity:1,scale:1},exit:{y:100,opacity:0,scale:.95},transition:{type:\"spring\",damping:25,stiffness:300},className:`w-full rounded-2xl overflow-hidden relative ${o?\"bg-gradient-to-br from-emerald-500/20 to-green-500/10 border border-emerald-500/50\":\"bg-gradient-to-br from-amber-500/20 to-orange-500/10 border border-amber-500/50\"}`,children:[c.jsxs(\"div\",{className:`px-4 py-2 flex items-center gap-2 ${o?\"bg-emerald-500/30\":\"bg-amber-500/30\"}`,children:[c.jsx(\"span\",{className:\"text-lg\",children:o?\"🔥\":\"⚠️\"}),c.jsx(\"span\",{className:`font-bold text-sm uppercase tracking-wide ${o?\"text-emerald-300\":\"text-amber-300\"}`,children:o?\"BUYING SIGNAL\":i?.objection_type===\"price\"?\"PRICE CONCERN\":i?.objection_type===\"timing\"?\"TIMING ISSUE\":i?.objection_type===\"trust\"?\"TRUST CONCERN\":\"OBJECTION\"})]}),c.jsx(\"div\",{className:\"px-4 pt-3 pb-2\",children:c.jsxs(\"p\",{className:\"text-slate-400 text-sm italic truncate\",children:['\"',s,'\"']})}),c.jsxs(\"div\",{className:\"px-4 pb-3\",children:[c.jsxs(\"p\",{className:\"text-white text-lg font-medium leading-snug\",children:['\"',i?.response||\"Handle this naturally...\",'\"']}),c.jsx(\"p\",{className:\"text-slate-500 text-xs italic mt-1\",children:\"Adapt in your own voice\"})]}),i?.key_point&&c.jsx(\"div\",{className:\"px-4 pb-2\",children:c.jsxs(\"div\",{className:`inline-flex items-center gap-1.5 rounded-full px-3 py-1 ${o?\"bg-emerald-500/20 border border-emerald-500/30\":\"bg-amber-500/20 border border-amber-500/30\"}`,children:[c.jsx(ac,{className:`w-3 h-3 ${o?\"text-emerald-400\":\"text-amber-400\"}`}),c.jsx(\"span\",{className:`text-xs font-medium ${o?\"text-emerald-300\":\"text-amber-300\"}`,children:i.key_point})]})}),i?.follow_up_question&&c.jsxs(\"div\",{className:\"px-4 pb-4 flex items-start gap-2\",children:[c.jsx(Qj,{className:`w-4 h-4 mt-0.5 flex-shrink-0 ${o?\"text-emerald-400\":\"text-amber-400\"}`}),c.jsxs(\"div\",{children:[c.jsx(\"span\",{className:`text-xs font-bold ${o?\"text-emerald-400\":\"text-amber-400\"}`,children:\"THEN ASK:\"}),c.jsxs(\"span\",{className:\"text-slate-300 text-sm ml-1\",children:['\"',i.follow_up_question,'\"']})]})]}),c.jsx(\"button\",{onClick:l,className:\"absolute top-2 right-2 p-2 text-slate-400 hover:text-white\",children:c.jsx(Gt,{className:\"w-4 h-4\"})})]})}function wE({isMuted:t,onMute:s,onMarkHot:i,onEndCall:l,markedHot:o}){return c.jsx(\"div\",{className:\"bg-slate-800 border-t border-slate-700 px-4 py-4 safe-area-bottom\",children:c.jsxs(\"div\",{className:\"flex items-center justify-center gap-4\",children:[c.jsx(\"button\",{onClick:s,className:`w-14 h-14 rounded-full flex items-center justify-center transition-colors ${t?\"bg-red-500 text-white\":\"bg-slate-700 text-slate-300\"}`,children:t?c.jsx(Tc,{className:\"w-6 h-6\"}):c.jsx(ti,{className:\"w-6 h-6\"})}),c.jsx(\"button\",{onClick:i,disabled:o,className:`w-14 h-14 rounded-full flex items-center justify-center transition-colors ${o?\"bg-amber-500 text-white\":\"bg-amber-500/20 border border-amber-500/50 text-amber-400\"}`,children:c.jsx(nl,{className:\"w-6 h-6\"})}),c.jsxs(\"button\",{onClick:l,className:\"px-8 py-4 rounded-full bg-red-500 text-white font-bold flex items-center gap-2 active:scale-95 transition-transform\",children:[c.jsx(ur,{className:\"w-5 h-5\"}),c.jsx(\"span\",{children:\"End\"})]})]})})}function SE({intel:t,leadName:s,onClose:i}){return t?c.jsx(Le.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:\"fixed inset-0 z-[60] bg-black/70 flex items-end\",onClick:i,children:c.jsx(Le.div,{initial:{y:\"100%\"},animate:{y:0},exit:{y:\"100%\"},transition:{type:\"spring\",damping:25,stiffness:300},className:\"bg-slate-800 rounded-t-3xl w-full max-h-[70vh] overflow-y-auto\",onClick:l=>l.stopPropagation(),children:c.jsxs(\"div\",{className:\"p-4\",children:[c.jsx(\"div\",{className:\"w-12 h-1 bg-slate-600 rounded-full mx-auto mb-4\"}),c.jsxs(\"h3\",{className:\"text-lg font-bold text-white mb-4\",children:[\"Intel: \",s]}),t.company&&c.jsxs(\"div\",{className:\"bg-slate-700/50 rounded-xl p-4 mb-3\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-2 mb-2\",children:[c.jsx(jc,{className:\"w-4 h-4 text-blue-400\"}),c.jsx(\"span\",{className:\"text-sm font-semibold text-white\",children:t.company.name})]}),c.jsxs(\"div\",{className:\"flex flex-wrap gap-2\",children:[t.company.industry&&c.jsx(\"span\",{className:\"px-2 py-1 bg-blue-500/20 text-blue-300 text-xs rounded\",children:t.company.industry}),t.company.size&&c.jsx(\"span\",{className:\"px-2 py-1 bg-slate-600 text-slate-300 text-xs rounded\",children:t.company.size}),t.company.location&&c.jsx(\"span\",{className:\"px-2 py-1 bg-slate-600 text-slate-300 text-xs rounded\",children:t.company.location})]}),t.company.sales_angle&&c.jsxs(\"div\",{className:\"mt-3 p-2 bg-emerald-500/10 border border-emerald-500/30 rounded-lg\",children:[c.jsx(\"span\",{className:\"text-xs text-emerald-400 font-semibold\",children:\"SALES ANGLE: \"}),c.jsx(\"span\",{className:\"text-sm text-slate-300\",children:t.company.sales_angle})]})]}),t.person?.job_title&&c.jsxs(\"div\",{className:\"bg-slate-700/50 rounded-xl p-4 mb-3\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-2 mb-1\",children:[c.jsx(\"span\",{className:\"text-lg\",children:\"👤\"}),c.jsx(\"span\",{className:\"text-sm font-semibold text-white\",children:s})]}),c.jsx(\"p\",{className:\"text-slate-400 text-sm\",children:t.person.job_title}),t.person.years_at_company&&c.jsxs(\"p\",{className:\"text-slate-500 text-xs mt-1\",children:[t.person.years_at_company,\" years at company\"]})]}),t.similar_wins?.length>0&&c.jsxs(\"div\",{className:\"bg-slate-700/50 rounded-xl p-4\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-2 mb-2\",children:[c.jsx(\"span\",{className:\"text-lg\",children:\"🏆\"}),c.jsx(\"span\",{className:\"text-sm font-semibold text-amber-400\",children:\"Similar Wins\"})]}),c.jsx(\"div\",{className:\"space-y-2\",children:t.similar_wins.slice(0,3).map((l,o)=>c.jsxs(\"div\",{className:\"text-sm\",children:[c.jsx(\"span\",{className:\"text-slate-300\",children:l.name}),l.key_factor&&c.jsxs(\"span\",{className:\"text-slate-500\",children:[' — \"',l.key_factor,'\"']})]},o))})]})]})})}):null}function jE({lead:t,duration:s,isListening:i,isMuted:l,script:o,scriptStage:d,intel:f,latestSuggestion:m,openingLine:p,error:y,onMinimize:x,onMute:g,onMarkHot:w,onEndCall:S,onDismissSuggestion:T}){const[N,R]=b.useState(!1),[D,A]=b.useState(!1),C=()=>{A(!0),w?.()};return c.jsxs(\"div\",{className:\"fixed inset-0 z-50 bg-slate-900 flex flex-col\",children:[c.jsx(gE,{duration:s,leadName:t?.first_name,isListening:i,onMinimize:x}),c.jsxs(\"div\",{className:\"flex-1 flex flex-col p-4 gap-3 overflow-hidden\",children:[c.jsx(yE,{intel:f}),c.jsx(xE,{stage:d,script:o,openingLine:p}),c.jsx(bE,{company:f?.company,person:f?.person,onExpand:()=>R(!0)}),y&&c.jsxs(\"div\",{className:\"bg-red-500/10 border border-red-500/30 rounded-xl px-4 py-2 flex items-center gap-2\",children:[c.jsx(Db,{className:\"w-4 h-4 text-red-400 flex-shrink-0\"}),c.jsx(\"span\",{className:\"text-red-400 text-sm\",children:y})]}),c.jsxs(\"div\",{className:\"flex-1 flex items-center justify-center px-2\",children:[c.jsx(si,{mode:\"wait\",children:m&&c.jsx(vE,{type:m.type,trigger:m.trigger,suggestion:m.suggestion,onDismiss:T},m.timestamp)}),!m&&i&&c.jsx(\"div\",{className:\"text-center\",children:c.jsxs(\"div\",{className:\"flex items-center justify-center gap-2 text-slate-500\",children:[c.jsx(\"div\",{className:\"w-2 h-2 bg-violet-500 rounded-full animate-pulse\"}),c.jsx(\"span\",{className:\"text-sm\",children:\"Listening for signals...\"})]})})]})]}),c.jsx(wE,{isMuted:l,onMute:g,onMarkHot:C,onEndCall:S,markedHot:D}),c.jsx(si,{children:N&&c.jsx(SE,{intel:f,leadName:t?.first_name,onClose:()=>R(!1)})})]})}const TE={discovery:[\"tell me about\",\"what do you\",\"how many\",\"when did\",\"how long\",\"what's your\",\"who is\"],value_prop:[\"we can help\",\"our platform\",\"rateright\",\"workers available\",\"save you\",\"percentage\"],objections:[\"price\",\"cost\",\"expensive\",\"not sure\",\"competitor\",\"think about\"],close:[\"next step\",\"sign up\",\"get started\",\"send you\",\"email\",\"ready to\"]},NE=[\"expensive\",\"cost\",\"price\",\"too much\",\"can't afford\",\"not sure\",\"think about\",\"need to check\",\"competitor\",\"already have\",\"not interested\",\"busy\",\"later\",\"call back\",\"happy with\",\"current provider\",\"contract\",\"locked in\"],CE=[/works?\\s+for\\s+(.+?)\\s+on\\s+(?:the\\s+)?(.+?)(?:\\s+project|\\s+site|\\s+job|[.!?]|$)/i,/(?:i|we)\\s+work\\s+for\\s+(.+?)(?:\\s+on|\\s+at|[.!?]|$)/i,/(?:my|the)\\s+boss\\s+(?:is\\s+)?(?:at\\s+)?(.+?)(?:[.!?]|$)/i,/working\\s+(?:for|with)\\s+(.+?)(?:\\s+on|\\s+at|[.!?]|$)/i],AE=[/^hey system[,:]?\\s*(.+)/i,/^command[,:]?\\s*(.+)/i,/^note[,:]?\\s*(.+)/i,/^mark\\s+(hot|warm|cold|engaged|converted|lost)/i,/^callback\\s+(.+)/i,/^skip$/i],EE=[\"when can you start\",\"when can we start\",\"how do i sign up\",\"how do we sign up\",\"what's the next step\",\"what is the next step\",\"next steps\",\"let's do it\",\"lets do it\",\"i'm ready\",\"we're ready\",\"sign me up\",\"sign us up\",\"send me the details\",\"send the details\",\"send me a quote\",\"need workers asap\",\"need someone today\",\"starting monday\",\"starting next week\",\"that's reasonable\",\"sounds fair\",\"cheaper than\",\"better than\",\"have a job starting\",\"got a project\",\"need workers\",\"how many workers\",\"do you have electricians\",\"do you have carpenters\"],Lx={\"next step\":{type:\"closing\",response:\"Great question! I can get you set up right now. I just need your email to send the signup link.\",followUp:\"What's the best email to send that to?\",keyPoint:\"They're ready to move forward!\"},sign:{type:\"closing\",response:\"Perfect! Let me get you started. The signup takes about 2 minutes.\",followUp:\"Do you have your ABN handy?\",keyPoint:\"Close the deal now!\"},\"when can\":{type:\"urgency\",response:\"We can have workers available within 24-48 hours once you're set up.\",followUp:\"What trade do you need first?\",keyPoint:\"Match their urgency!\"},\"need workers\":{type:\"qualification\",response:\"We've got a great pool of pre-vetted workers. Most contractors find someone within a day.\",followUp:\"How many workers are you looking for?\",keyPoint:\"Qualify the opportunity!\"},cheaper:{type:\"value\",response:\"Yes, at 9.9% we're typically 30-50% less than traditional agencies, with no lock-in contracts.\",followUp:\"Would you like me to calculate the savings based on your team size?\",keyPoint:\"Reinforce the value!\"},default:{type:\"interest\",response:\"I can hear you're interested! Let me show you how easy it is to get started.\",followUp:\"What's your biggest pain point with finding workers right now?\",keyPoint:\"Keep the momentum!\"}};function DE({lead:t,onClose:s,onEnd:i}){const{scriptSessionId:l,setScriptSessionId:o,preloadedIntel:d}=kc(),[f,m]=b.useState(!1),[p,y]=b.useState(\"\"),[x,g]=b.useState(\"\"),[w,S]=b.useState([]),[T,N]=b.useState(!1),[R,D]=b.useState(null),[A,C]=b.useState(0),[B,_]=b.useState(!1),[F,P]=b.useState(null),[H,z]=b.useState([]),[X,te]=b.useState(\"\"),[Y,$]=b.useState(!0),[W,se]=b.useState(!0),[O,I]=b.useState({}),[K,ie]=b.useState(null),[oe,xe]=b.useState(null),[Te,ae]=b.useState(null),[ce,ne]=b.useState(!1),ue=b.useRef(!1),[de,ee]=b.useState(null),[ge,Ee]=b.useState(!1),[wt,me]=b.useState(null),ze=b.useRef(null),[st,on]=b.useState(!0),[Wt,ms]=b.useState(null),[Yn,Yt]=b.useState(\"opener\"),[li,Ea]=b.useState([]),[Vt,Fn]=b.useState(null),[St,$s]=b.useState(null),[Xn,Da]=b.useState(d),[ps,ka]=b.useState(null),[Ln,ri]=b.useState(!1),cn=b.useRef(!1);b.useEffect(()=>{d&&!cn.current&&(console.log(\"[LiveCopilot] Syncing preloadedIntel from context:\",Object.keys(d)),Da(d),cn.current=!0)},[d]);const Ft=b.useRef(null),ft=b.useRef(null),Ut=b.useRef(null),Ct=b.useRef(null);b.useRef(!1);const Gs=b.useRef(null),Kn=b.useRef(\"\"),un=b.useRef([]),gs=b.useRef(0),Qn=b.useRef(!1),Pt=b.useRef(0),Xt=b.useRef(null),ve=b.useRef(null);b.useEffect(()=>{if(St){const re=setTimeout(()=>{$s(null)},5e3);return()=>clearTimeout(re)}},[St]),b.useEffect(()=>((async()=>(await Fe(),await ht(),await At(),await Zn(),console.log(\"[LiveCopilot] Starting real-time transcription\"),Rt()))(),()=>{xs(),Ut.current&&clearInterval(Ut.current)}),[]),b.useEffect(()=>{Ct.current?.scrollIntoView({behavior:\"smooth\"})},[w]),b.useEffect(()=>(Ut.current=setInterval(()=>{C(re=>(gs.current=re+1,re+1))},1e3),()=>clearInterval(Ut.current)),[]),b.useEffect(()=>{Kn.current=p},[p]),b.useEffect(()=>{un.current=w},[w]),b.useEffect(()=>()=>{!Qn.current&&t?.id&&Kn.current&&(console.log(\"[LiveCopilot] Saving session on unmount, transcript length:\",Kn.current.length),Qn.current=!0,It.saveCopilotSession({leadId:t.id,transcript:Kn.current,suggestions:un.current,duration:gs.current}).catch(re=>console.error(\"[LiveCopilot] Failed to save session on unmount:\",re)))},[t?.id]);const Fe=async()=>{try{const re=await It.getDeepgramCredentials();if(console.log(\"[LiveCopilot] Deepgram configured:\",re.configured),re.configured){const Ae=`wss://${window.location.host.includes(\"rateright.com.au\")?\"rateright-growth-production.up.railway.app\":window.location.host}/api/transcribe/ws`;console.log(\"[LiveCopilot] Using backend proxy:\",Ae),P({configured:!0,proxyUrl:Ae}),Gs.current={configured:!0,proxyUrl:Ae}}else console.log(\"[LiveCopilot] Deepgram not configured, will use Web Speech API fallback\"),Gs.current=null}catch(re){console.log(\"[LiveCopilot] Live transcription not available:\",re.message),Gs.current=null}},ht=async()=>{if(!t?.id){se(!1);return}try{if(t.ai_intel_brief?.talking_points){z(t.ai_intel_brief.talking_points||[]),te(t.ai_intel_brief.opening_line||\"\"),se(!1);return}const re=await It.getIntelBrief(t.id);re.brief&&(z(re.brief.talking_points||[]),te(re.brief.opening_line||\"\"));try{const je=await It.getSimilarWins(t.id);je?.wins?.length>0&&Fn(je.wins[0])}catch(je){console.log(\"Could not load similar wins:\",je)}}catch(re){console.log(\"Could not load intel brief:\",re)}finally{se(!1)}},At=async()=>{if(cn.current||Xn){console.log(\"[LiveCopilot] Intel already loaded, skipping API fetch\");return}if(d){console.log(\"[LiveCopilot] Preloaded intel exists, useEffect will sync\");return}if(t?.id)try{console.log(\"[LiveCopilot] No preloaded intel, fetching from API...\");const re=await It.getLiveIntel(t.id);re.success&&!cn.current&&Da(re)}catch(re){console.log(\"Could not load intel:\",re)}},Zn=async()=>{if(t?.id)try{const re=await hc.getForLead(t.id);if(re.recommendedScripts?.length>0){const je=await hc.get(re.recommendedScripts[0].id);ka(je.script),ms(je.script?.id)}}catch(re){console.log(\"Could not load script:\",re)}},Xe=b.useCallback(re=>{const je=re.toLowerCase();for(const[ye,Ae]of Object.entries(TE))for(const _e of Ae)if(je.includes(_e)){const et=[\"opener\",\"discovery\",\"value_prop\",\"objections\",\"close\"],Be=et.indexOf(Yn);if(et.indexOf(ye)>Be)return Ea(Bn=>[...new Set([...Bn,Yn])]),Yt(ye),!0}return!1},[Yn]),Ht=re=>{const je=Math.floor(re/60),ye=re%60;return`${je}:${ye.toString().padStart(2,\"0\")}`},Jn=b.useCallback(re=>{const je=re.toLowerCase();return NE.some(ye=>je.includes(ye))},[]),Dt=b.useCallback(re=>{const je=re.toLowerCase();for(const ye of EE)if(je.includes(ye)){if(ze.current===ye)return null;ze.current=ye;let Ae=Lx.default;for(const[_e,et]of Object.entries(Lx))if(_e!==\"default\"&&ye.includes(_e)){Ae=et;break}return{trigger:ye,...Ae}}return null},[]),kt=b.useCallback(re=>{me(re);const je={type:\"buying_signal\",trigger:re.trigger,suggestion:{signal_type:re.type,response:re.response,follow_up_question:re.followUp,key_point:re.keyPoint},timestamp:Date.now()};S(ye=>[...ye,je]),$s(je),setTimeout(()=>me(null),5e3)},[]),ys=async re=>{if(!T){N(!0);try{const je=await It.objectionResponse({objection:re,leadId:t?.id});if(je.success){const ye={type:\"objection\",trigger:re,suggestion:je.suggestion,timestamp:Date.now()};S(Ae=>[...Ae,ye]),$s(ye)}}catch(je){console.error(\"Failed to get objection response:\",je)}finally{N(!1)}}},qt=t?.metadata?.lead_type===\"worker\",oi=b.useCallback(re=>{if(!(!qt||ue.current||ce))for(const je of CE){const ye=re.match(je);if(ye){const Ae=ye[1]?.trim(),_e=ye[2]?.trim();if(Ae&&Ae.length>2){console.log(`[ContractorDetection] Found: ${Ae}, project: ${_e||\"N/A\"}`),Dr(Ae,_e);return}}}},[qt,ce]),Dr=async(re,je)=>{if(!(ue.current||ce)){ue.current=!0,ne(!0);try{const ye=await It.extractContractor({sourceLeadId:t?.id,companyName:re,projectName:je});ye.success&&ye.found&&ye.candidate&&ae(ye.candidate)}catch(ye){console.error(\"Contractor search error:\",ye)}finally{ne(!1)}}},Wn=(re,je)=>{ae(null),console.log(\"Contractor lead created:\",re,je)},mt=b.useCallback(async re=>{if(ge)return!1;const je=re.toLowerCase().trim();for(const ye of AE){const Ae=je.match(ye);if(Ae){let _e=Ae[1]||je;(ye.source.includes(\"mark\")||ye.source.includes(\"skip\"))&&(_e=je),console.log(\"[VoiceCommand] Detected:\",_e),Ee(!0);try{const et=await It.voiceCommand({transcript:_e,leadId:t?.id});et.success&&(ee({confirmation:et.parsed.confirmation,intent:et.parsed.intent}),setTimeout(()=>ee(null),3e3))}catch(et){console.error(\"Voice command error:\",et)}finally{Ee(!1)}return!0}}return!1},[t?.id,ge]),Rt=async()=>{try{console.log(\"[LiveCopilot] Requesting microphone access...\");const re=await navigator.mediaDevices.getUserMedia({audio:!0});ve.current=re,Pt.current=0,console.log(\"[LiveCopilot] Microphone access granted\");const je=Gs.current||F;if(console.log(\"[LiveCopilot] Using backend proxy:\",!!(je?.configured&&je?.proxyUrl)),je?.configured&&je?.proxyUrl){console.log(\"[LiveCopilot] Connecting to backend proxy...\"),console.log(\"[LiveCopilot] Proxy URL:\",je.proxyUrl),xe(\"deepgram\");const ye=new WebSocket(je.proxyUrl);console.log(\"[LiveCopilot] WebSocket created, readyState:\",ye.readyState);const Ae=setTimeout(()=>{console.error(\"[LiveCopilot] Connection timeout! readyState:\",ye.readyState),ye.readyState!==WebSocket.OPEN&&(D(\"Connection timeout - trying fallback...\"),ye.close())},1e4);ye.onopen=()=>{clearTimeout(Ae),console.log(\"[LiveCopilot] Connected to transcription proxy!\"),Pt.current=0,m(!0),D(null)},ye.onmessage=Qe=>{const Ke=JSON.parse(Qe.data);if(Ke.error){console.error(\"[LiveCopilot] Proxy error:\",Ke.error),D(Ke.error);return}if(Ke.type===\"Metadata\"&&console.log(\"[LiveCopilot] Transcription metadata:\",Ke),Ke.channel?.alternatives?.[0]?.transcript){console.log(\"[LiveCopilot] Transcript:\",Ke.channel.alternatives[0].transcript,\"is_final:\",Ke.is_final);const Kt=Ke.channel.alternatives[0].transcript;if(Ke.is_final){y(Fs=>Fs+\" \"+Kt),g(\"\"),mt(Kt),Xe(Kt);const Ys=Dt(Kt);Ys?kt(Ys):Jn(Kt)&&ys(Kt),qt&&oi(Kt)}else g(Kt)}},ye.onerror=Qe=>{clearTimeout(Ae),console.error(\"[LiveCopilot] Proxy WebSocket error:\",Qe),console.error(\"[LiveCopilot] Error type:\",Qe.type),console.error(\"[LiveCopilot] Socket readyState on error:\",ye.readyState),D(\"Transcription error - check console\")},ye.onclose=Qe=>{clearTimeout(Ae),console.log(\"[LiveCopilot] Proxy disconnected, code:\",Qe.code,\"reason:\",Qe.reason,\"wasClean:\",Qe.wasClean);const Ke=3;if(Pt.current{console.log(\"[LiveCopilot] Reconnecting WebSocket...\"),Rt()},Kt)}else m(!1),Pt.current>=Ke&&D(\"Transcription disconnected. Tap mic to restart.\")},Ft.current=ye;const _e=new AudioContext,et=_e.sampleRate;console.log(\"[LiveCopilot] AudioContext sample rate:\",et);const Be=`"}],"details":{"status":"completed","exitCode":0,"durationMs":267,"aggregated":"./public/assets/index-2HMepUD5.js:18: `),()=>{D.contains(R)&&D.removeChild(R)}},[s]),c.jsx(JA,{isPresent:s,childRef:d,sizeRef:f,children:b.cloneElement(t,{ref:y})})}const e2=({children:t,initial:s,isPresent:i,onExitComplete:l,custom:o,presenceAffectsLayout:d,mode:f,anchorX:m,root:p})=>{const y=bh(t2),x=b.useId();let g=!0,w=b.useMemo(()=>(g=!1,{id:x,initial:s,isPresent:i,custom:o,onExitComplete:S=>{y.set(S,!0);for(const T of y.values())if(!T)return;l&&l()},register:S=>(y.set(S,!1),()=>y.delete(S))}),[i,y,l]);return d&&g&&(w={...w}),b.useMemo(()=>{y.forEach((S,T)=>y.set(T,!1))},[i]),b.useEffect(()=>{!i&&!y.size&&l&&l()},[i]),f===\"popLayout\"&&(t=c.jsx(WA,{isPresent:i,anchorX:m,root:p,children:t})),c.jsx(Cc.Provider,{value:w,children:t})};function t2(){return new Map}function rw(t=!0){const s=b.useContext(Cc);if(s===null)return[!0,null];const{isPresent:i,onExitComplete:l,register:o}=s,d=b.useId();b.useEffect(()=>{if(t)return o(d)},[t]);const f=b.useCallback(()=>t&&l&&l(d),[d,l,t]);return!i&&l?[!1,f]:[!0]}const $o=t=>t.key||\"\";function yx(t){const s=[];return b.Children.forEach(t,i=>{b.isValidElement(i)&&s.push(i)}),s}const si=({children:t,custom:s,initial:i=!0,onExitComplete:l,presenceAffectsLayout:o=!0,mode:d=\"sync\",propagate:f=!1,anchorX:m=\"left\",root:p})=>{const[y,x]=rw(f),g=b.useMemo(()=>yx(t),[t]),w=f&&!y?[]:g.map($o),S=b.useRef(!0),T=b.useRef(g),N=bh(()=>new Map),R=b.useRef(new Set),[D,A]=b.useState(g),[C,B]=b.useState(g);Vb(()=>{S.current=!1,T.current=g;for(let P=0;P{const H=$o(P),z=f&&!y?!1:g===C||w.includes(H),X=()=>{if(R.current.has(H))return;if(R.current.add(H),N.has(H))N.set(H,!0);else return;let te=!0;N.forEach(Y=>{Y||(te=!1)}),te&&(F?.(),B(T.current),f&&x?.(),l&&l())};return c.jsx(e2,{isPresent:z,initial:!S.current||i?void 0:!1,custom:s,presenceAffectsLayout:o,mode:d,root:p,onExitComplete:z?void 0:X,anchorX:m,children:P},H)})})},ow=b.createContext({strict:!1}),xx={animation:[\"animate\",\"variants\",\"whileHover\",\"whileTap\",\"exit\",\"whileInView\",\"whileFocus\",\"whileDrag\"],exit:[\"exit\"],drag:[\"drag\",\"dragControls\"],focus:[\"whileFocus\"],hover:[\"whileHover\",\"onHoverStart\",\"onHoverEnd\"],tap:[\"whileTap\",\"onTap\",\"onTapStart\",\"onTapCancel\"],pan:[\"onPan\",\"onPanStart\",\"onPanSessionStart\",\"onPanEnd\"],inView:[\"whileInView\",\"onViewportEnter\",\"onViewportLeave\"],layout:[\"layout\",\"layoutId\"]};let bx=!1;function n2(){if(bx)return;const t={};for(const s in xx)t[s]={isEnabled:i=>xx[s].some(l=>!!i[l])};Bv(t),bx=!0}function cw(){return n2(),qC()}function s2(t){const s=cw();for(const i in t)s[i]={...s[i],...t[i]};Bv(s)}const a2=new Set([\"animate\",\"exit\",\"variants\",\"initial\",\"style\",\"values\",\"variants\",\"transition\",\"transformTemplate\",\"custom\",\"inherit\",\"onBeforeLayoutMeasure\",\"onAnimationStart\",\"onAnimationComplete\",\"onUpdate\",\"onDragStart\",\"onDrag\",\"onDragEnd\",\"onMeasureDragConstraints\",\"onDirectionLock\",\"onDragTransitionEnd\",\"_dragX\",\"_dragY\",\"onHoverStart\",\"onHoverEnd\",\"onViewportEnter\",\"onViewportLeave\",\"globalTapTarget\",\"ignoreStrict\",\"viewport\"]);function fc(t){return t.startsWith(\"while\")||t.startsWith(\"drag\")&&t!==\"draggable\"||t.startsWith(\"layout\")||t.startsWith(\"onTap\")||t.startsWith(\"onPan\")||t.startsWith(\"onLayout\")||a2.has(t)}let uw=t=>!fc(t);function i2(t){typeof t==\"function\"&&(uw=s=>s.startsWith(\"on\")?!fc(s):t(s))}try{i2(require(\"@emotion/is-prop-valid\").default)}catch{}function l2(t,s,i){const l={};for(const o in t)o===\"values\"&&typeof t.values==\"object\"||(uw(o)||i===!0&&fc(o)||!s&&!fc(o)||t.draggable&&o.startsWith(\"onDrag\"))&&(l[o]=t[o]);return l}const Dc=b.createContext({});function r2(t,s){if(Ec(t)){const{initial:i,animate:l}=t;return{initial:i===!1||mr(i)?i:void 0,animate:mr(l)?l:void 0}}return t.inherit!==!1?s:{}}function o2(t){const{initial:s,animate:i}=r2(t,b.useContext(Dc));return b.useMemo(()=>({initial:s,animate:i}),[vx(s),vx(i)])}function vx(t){return Array.isArray(t)?t.join(\" \"):t}const Xh=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function dw(t,s,i){for(const l in s)!$t(s[l])&&!$v(l,i)&&(t[l]=s[l])}function c2({transformTemplate:t},s){return b.useMemo(()=>{const i=Xh();return Gh(i,s,t),Object.assign({},i.vars,i.style)},[s])}function u2(t,s){const i=t.style||{},l={};return dw(l,i,t),Object.assign(l,c2(t,s)),l}function d2(t,s){const i={},l=u2(t,s);return t.drag&&t.dragListener!==!1&&(i.draggable=!1,l.userSelect=l.WebkitUserSelect=l.WebkitTouchCallout=\"none\",l.touchAction=t.drag===!0?\"none\":`pan-${t.drag===\"x\"?\"y\":\"x\"}`),t.tabIndex===void 0&&(t.onTap||t.onTapStart||t.whileTap)&&(i.tabIndex=0),i.style=l,i}const fw=()=>({...Xh(),attrs:{}});function f2(t,s,i,l){const o=b.useMemo(()=>{const d=fw();return Gv(d,s,Fv(l),t.transformTemplate,t.style),{...d.attrs,style:{...d.style}}},[s]);if(t.style){const d={};dw(d,t.style,t),o.style={...d,...o.style}}return o}const h2=[\"animate\",\"circle\",\"defs\",\"desc\",\"ellipse\",\"g\",\"image\",\"line\",\"filter\",\"marker\",\"mask\",\"metadata\",\"path\",\"pattern\",\"polygon\",\"polyline\",\"rect\",\"stop\",\"switch\",\"symbol\",\"svg\",\"text\",\"tspan\",\"use\",\"view\"];function Kh(t){return typeof t!=\"string\"||t.includes(\"-\")?!1:!!(h2.indexOf(t)>-1||/[A-Z]/u.test(t))}function m2(t,s,i,{latestValues:l},o,d=!1,f){const p=(f??Kh(t)?f2:d2)(s,l,o,t),y=l2(s,typeof t==\"string\",d),x=t!==b.Fragment?{...y,...p,ref:i}:{},{children:g}=s,w=b.useMemo(()=>$t(g)?g.get():g,[g]);return b.createElement(t,{...x,children:w})}function p2({scrapeMotionValuesFromProps:t,createRenderState:s},i,l,o){return{latestValues:g2(i,l,o,t),renderState:s()}}function g2(t,s,i,l){const o={},d=l(t,{});for(const w in d)o[w]=ec(d[w]);let{initial:f,animate:m}=t;const p=Ec(t),y=zv(t);s&&y&&!p&&t.inherit!==!1&&(f===void 0&&(f=s.initial),m===void 0&&(m=s.animate));let x=i?i.initial===!1:!1;x=x||f===!1;const g=x?m:f;if(g&&typeof g!=\"boolean\"&&!Ac(g)){const w=Array.isArray(g)?g:[g];for(let S=0;S(s,i)=>{const l=b.useContext(Dc),o=b.useContext(Cc),d=()=>p2(t,s,l,o);return i?d():bh(d)},y2=hw({scrapeMotionValuesFromProps:Yh,createRenderState:Xh}),x2=hw({scrapeMotionValuesFromProps:Xv,createRenderState:fw}),b2=Symbol.for(\"motionComponentSymbol\");function v2(t,s,i){const l=b.useRef(i);b.useInsertionEffect(()=>{l.current=i});const o=b.useRef(null);return b.useCallback(d=>{d&&t.onMount?.(d),s&&(d?s.mount(d):s.unmount());const f=l.current;if(typeof f==\"function\")if(d){const m=f(d);typeof m==\"function\"&&(o.current=m)}else o.current?(o.current(),o.current=null):f(d);else f&&(f.current=d)},[s])}const mw=b.createContext({});function sr(t){return t&&typeof t==\"object\"&&Object.prototype.hasOwnProperty.call(t,\"current\")}function w2(t,s,i,l,o,d){const{visualElement:f}=b.useContext(Dc),m=b.useContext(ow),p=b.useContext(Cc),y=b.useContext(Fh).reducedMotion,x=b.useRef(null);l=l||m.renderer,!x.current&&l&&(x.current=l(t,{visualState:s,parent:f,props:i,presenceContext:p,blockInitialAnimation:p?p.initial===!1:!1,reducedMotionConfig:y,isSVG:d}));const g=x.current,w=b.useContext(mw);g&&!g.projection&&o&&(g.type===\"html\"||g.type===\"svg\")&&S2(x.current,i,o,w);const S=b.useRef(!1);b.useInsertionEffect(()=>{g&&S.current&&g.update(i,p)});const T=i[wv],N=b.useRef(!!T&&!window.MotionHandoffIsComplete?.(T)&&window.MotionHasOptimisedAnimation?.(T));return Vb(()=>{g&&(S.current=!0,window.MotionIsMounted=!0,g.updateFeatures(),g.scheduleRenderMicrotask(),N.current&&g.animationState&&g.animationState.animateChanges())}),b.useEffect(()=>{g&&(!N.current&&g.animationState&&g.animationState.animateChanges(),N.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(T)}),N.current=!1),g.enteringChildren=void 0)}),g}function S2(t,s,i,l){const{layoutId:o,layout:d,drag:f,dragConstraints:m,layoutScroll:p,layoutRoot:y,layoutCrossfade:x}=s;t.projection=new i(t.latestValues,s[\"data-framer-portal-id\"]?void 0:pw(t.parent)),t.projection.setOptions({layoutId:o,layout:d,alwaysMeasureLayout:!!f||m&&sr(m),visualElement:t,animationType:typeof d==\"string\"?d:\"both\",initialPromotionConfig:l,crossfade:x,layoutScroll:p,layoutRoot:y})}function pw(t){if(t)return t.options.allowProjection!==!1?t.projection:pw(t.parent)}function ff(t,{forwardMotionProps:s=!1,type:i}={},l,o){l&&s2(l);const d=i?i===\"svg\":Kh(t),f=d?x2:y2;function m(y,x){let g;const w={...b.useContext(Fh),...y,layoutId:j2(y)},{isStatic:S}=w,T=o2(y),N=f(y,S);if(!S&&Bb){T2();const R=N2(w);g=R.MeasureLayout,T.visualElement=w2(t,N,w,o,R.ProjectionNode,d)}return c.jsxs(Dc.Provider,{value:T,children:[g&&T.visualElement?c.jsx(g,{visualElement:T.visualElement,...w}):null,m2(t,y,v2(N,T.visualElement,x),N,S,s,d)]})}m.displayName=`motion.${typeof t==\"string\"?t:`create(${t.displayName??t.name??\"\"})`}`;const p=b.forwardRef(m);return p[b2]=t,p}function j2({layoutId:t}){const s=b.useContext(xh).id;return s&&t!==void 0?s+\"-\"+t:t}function T2(t,s){b.useContext(ow).strict}function N2(t){const s=cw(),{drag:i,layout:l}=s;if(!i&&!l)return{};const o={...i,...l};return{MeasureLayout:i?.isEnabled(t)||l?.isEnabled(t)?o.MeasureLayout:void 0,ProjectionNode:o.ProjectionNode}}function C2(t,s){if(typeof Proxy>\"u\")return ff;const i=new Map,l=(d,f)=>ff(d,f,t,s),o=(d,f)=>l(d,f);return new Proxy(o,{get:(d,f)=>f===\"create\"?l:(i.has(f)||i.set(f,ff(f,void 0,t,s)),i.get(f))})}const A2=(t,s)=>s.isSVG??Kh(t)?new iA(s):new WC(s,{allowProjection:t!==b.Fragment});class E2 extends Na{constructor(s){super(s),s.animationState||(s.animationState=uA(s))}updateAnimationControlsSubscription(){const{animate:s}=this.node.getProps();Ac(s)&&(this.unmountControls=s.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:s}=this.node.getProps(),{animate:i}=this.node.prevProps||{};s!==i&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}}let D2=0;class k2 extends Na{constructor(){super(...arguments),this.id=D2++}update(){if(!this.node.presenceContext)return;const{isPresent:s,onExitComplete:i}=this.node.presenceContext,{isPresent:l}=this.node.prevPresenceContext||{};if(!this.node.animationState||s===l)return;const o=this.node.animationState.setActive(\"exit\",!s);i&&!s&&o.then(()=>{i(this.id)})}mount(){const{register:s,onExitComplete:i}=this.node.presenceContext||{};i&&i(this.id),s&&(this.unmount=s(this.id))}unmount(){}}const R2={animation:{Feature:E2},exit:{Feature:k2}};function jr(t){return{point:{x:t.pageX,y:t.pageY}}}const M2=t=>s=>qh(s)&&t(s,jr(s));function rr(t,s,i,l){return pr(t,s,M2(i),l)}const gw=({current:t})=>t?t.ownerDocument.defaultView:null,wx=(t,s)=>Math.abs(t-s);function O2(t,s){const i=wx(t.x,s.x),l=wx(t.y,s.y);return Math.sqrt(i**2+l**2)}const Sx=new Set([\"auto\",\"scroll\"]);class yw{constructor(s,i,{transformPagePoint:l,contextWindow:o=window,dragSnapToOrigin:d=!1,distanceThreshold:f=3,element:m}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=S=>{this.handleScroll(S.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const S=mf(this.lastMoveEventInfo,this.history),T=this.startEvent!==null,N=O2(S.offset,{x:0,y:0})>=this.distanceThreshold;if(!T&&!N)return;const{point:R}=S,{timestamp:D}=Bt;this.history.push({...R,timestamp:D});const{onStart:A,onMove:C}=this.handlers;T||(A&&A(this.lastMoveEvent,S),this.startEvent=this.lastMoveEvent),C&&C(this.lastMoveEvent,S)},this.handlePointerMove=(S,T)=>{this.lastMoveEvent=S,this.lastMoveEventInfo=hf(T,this.transformPagePoint),We.update(this.updatePoint,!0)},this.handlePointerUp=(S,T)=>{this.end();const{onEnd:N,onSessionEnd:R,resumeAnimation:D}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&D&&D(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const A=mf(S.type===\"pointercancel\"?this.lastMoveEventInfo:hf(T,this.transformPagePoint),this.history);this.startEvent&&N&&N(S,A),R&&R(S,A)},!qh(s))return;this.dragSnapToOrigin=d,this.handlers=i,this.transformPagePoint=l,this.distanceThreshold=f,this.contextWindow=o||window;const p=jr(s),y=hf(p,this.transformPagePoint),{point:x}=y,{timestamp:g}=Bt;this.history=[{...x,timestamp:g}];const{onSessionStart:w}=i;w&&w(s,mf(y,this.history)),this.removeListeners=vr(rr(this.contextWindow,\"pointermove\",this.handlePointerMove),rr(this.contextWindow,\"pointerup\",this.handlePointerUp),rr(this.contextWindow,\"pointercancel\",this.handlePointerUp)),m&&this.startScrollTracking(m)}startScrollTracking(s){let i=s.parentElement;for(;i;){const l=getComputedStyle(i);(Sx.has(l.overflowX)||Sx.has(l.overflowY))&&this.scrollPositions.set(i,{x:i.scrollLeft,y:i.scrollTop}),i=i.parentElement}this.scrollPositions.set(window,{x:window.scrollX,y:window.scrollY}),window.addEventListener(\"scroll\",this.onElementScroll,{capture:!0,passive:!0}),window.addEventListener(\"scroll\",this.onWindowScroll,{passive:!0}),this.removeScrollListeners=()=>{window.removeEventListener(\"scroll\",this.onElementScroll,{capture:!0}),window.removeEventListener(\"scroll\",this.onWindowScroll)}}handleScroll(s){const i=this.scrollPositions.get(s);if(!i)return;const l=s===window,o=l?{x:window.scrollX,y:window.scrollY}:{x:s.scrollLeft,y:s.scrollTop},d={x:o.x-i.x,y:o.y-i.y};d.x===0&&d.y===0||(l?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=d.x,this.lastMoveEventInfo.point.y+=d.y):this.history.length>0&&(this.history[0].x-=d.x,this.history[0].y-=d.y),this.scrollPositions.set(s,o),We.update(this.updatePoint,!0))}updateHandlers(s){this.handlers=s}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),va(this.updatePoint)}}function hf(t,s){return s?{point:s(t.point)}:t}function jx(t,s){return{x:t.x-s.x,y:t.y-s.y}}function mf({point:t},s){return{point:t,delta:jx(t,xw(s)),offset:jx(t,_2(s)),velocity:L2(s,.1)}}function _2(t){return t[0]}function xw(t){return t[t.length-1]}function L2(t,s){if(t.length<2)return{x:0,y:0};let i=t.length-1,l=null;const o=xw(t);for(;i>=0&&(l=t[i],!(o.timestamp-l.timestamp>Us(s)));)i--;if(!l)return{x:0,y:0};const d=Mn(o.timestamp-l.timestamp);if(d===0)return{x:0,y:0};const f={x:(o.x-l.x)/d,y:(o.y-l.y)/d};return f.x===1/0&&(f.x=0),f.y===1/0&&(f.y=0),f}function z2(t,{min:s,max:i},l){return s!==void 0&&ti&&(t=l?it(i,t,l.max):Math.min(t,i)),t}function Tx(t,s,i){return{min:s!==void 0?t.min+s:void 0,max:i!==void 0?t.max+i-(t.max-t.min):void 0}}function B2(t,{top:s,left:i,bottom:l,right:o}){return{x:Tx(t.x,i,o),y:Tx(t.y,s,l)}}function Nx(t,s){let i=s.min-t.min,l=s.max-t.max;return s.max-s.minl?i=dr(s.min,s.max-l,t.min):l>o&&(i=dr(t.min,t.max-o,s.min)),cs(0,1,i)}function P2(t,s){const i={};return s.min!==void 0&&(i.min=s.min-t.min),s.max!==void 0&&(i.max=s.max-t.min),i}const Xf=.35;function H2(t=Xf){return t===!1?t=0:t===!0&&(t=Xf),{x:Cx(t,\"left\",\"right\"),y:Cx(t,\"top\",\"bottom\")}}function Cx(t,s,i){return{min:Ax(t,s),max:Ax(t,i)}}function Ax(t,s){return typeof t==\"number\"?t:t[s]||0}const q2=new WeakMap;class I2{constructor(s){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=Tt(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=s}start(s,{snapToCursor:i=!1,distanceThreshold:l}={}){const{presenceContext:o}=this.visualElement;if(o&&o.isPresent===!1)return;const d=g=>{i?(this.stopAnimation(),this.snapToCursor(jr(g).point)):this.pauseAnimation()},f=(g,w)=>{this.stopAnimation();const{drag:S,dragPropagation:T,onDragStart:N}=this.getProps();if(S&&!T&&(this.openDragLock&&this.openDragLock(),this.openDragLock=kC(S),!this.openDragLock))return;this.latestPointerEvent=g,this.latestPanInfo=w,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Rn(D=>{let A=this.getAxisMotionValue(D).get()||0;if(rs.test(A)){const{projection:C}=this.visualElement;if(C&&C.layout){const B=C.layout.layoutBox[D];B&&(A=Jt(B)*(parseFloat(A)/100))}}this.originPoint[D]=A}),N&&We.postRender(()=>N(g,w)),Hf(this.visualElement,\"transform\");const{animationState:R}=this.visualElement;R&&R.setActive(\"whileDrag\",!0)},m=(g,w)=>{this.latestPointerEvent=g,this.latestPanInfo=w;const{dragPropagation:S,dragDirectionLock:T,onDirectionLock:N,onDrag:R}=this.getProps();if(!S&&!this.openDragLock)return;const{offset:D}=w;if(T&&this.currentDirection===null){this.currentDirection=$2(D),this.currentDirection!==null&&N&&N(this.currentDirection);return}this.updateAxis(\"x\",w.point,D),this.updateAxis(\"y\",w.point,D),this.visualElement.render(),R&&R(g,w)},p=(g,w)=>{this.latestPointerEvent=g,this.latestPanInfo=w,this.stop(g,w),this.latestPointerEvent=null,this.latestPanInfo=null},y=()=>Rn(g=>this.getAnimationState(g)===\"paused\"&&this.getAxisMotionValue(g).animation?.play()),{dragSnapToOrigin:x}=this.getProps();this.panSession=new yw(s,{onSessionStart:d,onStart:f,onMove:m,onSessionEnd:p,resumeAnimation:y},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:x,distanceThreshold:l,contextWindow:gw(this.visualElement),element:this.visualElement.current})}stop(s,i){const l=s||this.latestPointerEvent,o=i||this.latestPanInfo,d=this.isDragging;if(this.cancel(),!d||!o||!l)return;const{velocity:f}=o;this.startAnimation(f);const{onDragEnd:m}=this.getProps();m&&We.postRender(()=>m(l,o))}cancel(){this.isDragging=!1;const{projection:s,animationState:i}=this.visualElement;s&&(s.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:l}=this.getProps();!l&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),i&&i.setActive(\"whileDrag\",!1)}updateAxis(s,i,l){const{drag:o}=this.getProps();if(!l||!Go(s,o,this.currentDirection))return;const d=this.getAxisMotionValue(s);let f=this.originPoint[s]+l[s];this.constraints&&this.constraints[s]&&(f=z2(f,this.constraints[s],this.elastic[s])),d.set(f)}resolveConstraints(){const{dragConstraints:s,dragElastic:i}=this.getProps(),l=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,o=this.constraints;s&&sr(s)?this.constraints||(this.constraints=this.resolveRefConstraints()):s&&l?this.constraints=B2(l.layoutBox,s):this.constraints=!1,this.elastic=H2(i),o!==this.constraints&&l&&this.constraints&&!this.hasMutatedConstraints&&Rn(d=>{this.constraints!==!1&&this.getAxisMotionValue(d)&&(this.constraints[d]=P2(l.layoutBox[d],this.constraints[d]))})}resolveRefConstraints(){const{dragConstraints:s,onMeasureDragConstraints:i}=this.getProps();if(!s||!sr(s))return!1;const l=s.current,{projection:o}=this.visualElement;if(!o||!o.layout)return!1;const d=FC(l,o.root,this.visualElement.getTransformPagePoint());let f=V2(o.layout.layoutBox,d);if(i){const m=i($C(f));this.hasMutatedConstraints=!!m,m&&(f=Uv(m))}return f}startAnimation(s){const{drag:i,dragMomentum:l,dragElastic:o,dragTransition:d,dragSnapToOrigin:f,onDragTransitionEnd:m}=this.getProps(),p=this.constraints||{},y=Rn(x=>{if(!Go(x,i,this.currentDirection))return;let g=p&&p[x]||{};f&&(g={min:0,max:0});const w=o?200:1e6,S=o?40:1e7,T={type:\"inertia\",velocity:l?s[x]:0,bounceStiffness:w,bounceDamping:S,timeConstant:750,restDelta:1,restSpeed:10,...d,...g};return this.startAxisValueAnimation(x,T)});return Promise.all(y).then(m)}startAxisValueAnimation(s,i){const l=this.getAxisMotionValue(s);return Hf(this.visualElement,s),l.start(Bh(s,l,0,i,this.visualElement,!1))}stopAnimation(){Rn(s=>this.getAxisMotionValue(s).stop())}pauseAnimation(){Rn(s=>this.getAxisMotionValue(s).animation?.pause())}getAnimationState(s){return this.getAxisMotionValue(s).animation?.state}getAxisMotionValue(s){const i=`_drag${s.toUpperCase()}`,l=this.visualElement.getProps(),o=l[i];return o||this.visualElement.getValue(s,(l.initial?l.initial[s]:void 0)||0)}snapToCursor(s){Rn(i=>{const{drag:l}=this.getProps();if(!Go(i,l,this.currentDirection))return;const{projection:o}=this.visualElement,d=this.getAxisMotionValue(i);if(o&&o.layout){const{min:f,max:m}=o.layout.layoutBox[i],p=d.get()||0;d.set(s[i]-it(f,m,.5)+p)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:s,dragConstraints:i}=this.getProps(),{projection:l}=this.visualElement;if(!sr(i)||!l||!this.constraints)return;this.stopAnimation();const o={x:0,y:0};Rn(f=>{const m=this.getAxisMotionValue(f);if(m&&this.constraints!==!1){const p=m.get();o[f]=U2({min:p,max:p},this.constraints[f])}});const{transformTemplate:d}=this.visualElement.getProps();this.visualElement.current.style.transform=d?d({},\"\"):\"none\",l.root&&l.root.updateScroll(),l.updateLayout(),this.resolveConstraints(),Rn(f=>{if(!Go(f,s,null))return;const m=this.getAxisMotionValue(f),{min:p,max:y}=this.constraints[f];m.set(it(p,y,o[f]))})}addListeners(){if(!this.visualElement.current)return;q2.set(this.visualElement,this);const s=this.visualElement.current,i=rr(s,\"pointerdown\",p=>{const{drag:y,dragListener:x=!0}=this.getProps();y&&x&&!Ov(p.target)&&this.start(p)}),l=()=>{const{dragConstraints:p}=this.getProps();sr(p)&&p.current&&(this.constraints=this.resolveRefConstraints())},{projection:o}=this.visualElement,d=o.addEventListener(\"measure\",l);o&&!o.layout&&(o.root&&o.root.updateScroll(),o.updateLayout()),We.read(l);const f=pr(window,\"resize\",()=>this.scalePositionWithinConstraints()),m=o.addEventListener(\"didUpdate\",(({delta:p,hasLayoutChanged:y})=>{this.isDragging&&y&&(Rn(x=>{const g=this.getAxisMotionValue(x);g&&(this.originPoint[x]+=p[x].translate,g.set(g.get()+p[x].translate))}),this.visualElement.render())}));return()=>{f(),i(),d(),m&&m()}}getProps(){const s=this.visualElement.getProps(),{drag:i=!1,dragDirectionLock:l=!1,dragPropagation:o=!1,dragConstraints:d=!1,dragElastic:f=Xf,dragMomentum:m=!0}=s;return{...s,drag:i,dragDirectionLock:l,dragPropagation:o,dragConstraints:d,dragElastic:f,dragMomentum:m}}}function Go(t,s,i){return(s===!0||s===t)&&(i===null||i===t)}function $2(t,s=10){let i=null;return Math.abs(t.y)>s?i=\"y\":Math.abs(t.x)>s&&(i=\"x\"),i}class G2 extends Na{constructor(s){super(s),this.removeGroupControls=On,this.removeListeners=On,this.controls=new I2(s)}mount(){const{dragControls:s}=this.node.getProps();s&&(this.removeGroupControls=s.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||On}update(){const{dragControls:s}=this.node.getProps(),{dragControls:i}=this.node.prevProps||{};s!==i&&(this.removeGroupControls(),s&&(this.removeGroupControls=s.subscribe(this.controls)))}unmount(){this.removeGroupControls(),this.removeListeners()}}const Ex=t=>(s,i)=>{t&&We.postRender(()=>t(s,i))};class Y2 extends Na{constructor(){super(...arguments),this.removePointerDownListener=On}onPointerDown(s){this.session=new yw(s,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:gw(this.node)})}createPanHandlers(){const{onPanSessionStart:s,onPanStart:i,onPan:l,onPanEnd:o}=this.node.getProps();return{onSessionStart:Ex(s),onStart:Ex(i),onMove:l,onEnd:(d,f)=>{delete this.session,o&&We.postRender(()=>o(d,f))}}}mount(){this.removePointerDownListener=rr(this.node.current,\"pointerdown\",s=>this.onPointerDown(s))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}let pf=!1;class F2 extends b.Component{componentDidMount(){const{visualElement:s,layoutGroup:i,switchLayoutGroup:l,layoutId:o}=this.props,{projection:d}=s;d&&(i.group&&i.group.add(d),l&&l.register&&o&&l.register(d),pf&&d.root.didUpdate(),d.addEventListener(\"animationComplete\",()=>{this.safeToRemove()}),d.setOptions({...d.options,onExitComplete:()=>this.safeToRemove()})),tc.hasEverUpdated=!0}getSnapshotBeforeUpdate(s){const{layoutDependency:i,visualElement:l,drag:o,isPresent:d}=this.props,{projection:f}=l;return f&&(f.isPresent=d,pf=!0,o||s.layoutDependency!==i||i===void 0||s.isPresent!==d?f.willUpdate():this.safeToRemove(),s.isPresent!==d&&(d?f.promote():f.relegate()||We.postRender(()=>{const m=f.getStack();(!m||!m.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:s}=this.props.visualElement;s&&(s.root.didUpdate(),Hh.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:s,layoutGroup:i,switchLayoutGroup:l}=this.props,{projection:o}=s;pf=!0,o&&(o.scheduleCheckAfterUnmount(),i&&i.group&&i.group.remove(o),l&&l.deregister&&l.deregister(o))}safeToRemove(){const{safeToRemove:s}=this.props;s&&s()}render(){return null}}function bw(t){const[s,i]=rw(),l=b.useContext(xh);return c.jsx(F2,{...t,layoutGroup:l,switchLayoutGroup:b.useContext(mw),isPresent:s,safeToRemove:i})}const X2={pan:{Feature:Y2},drag:{Feature:G2,ProjectionNode:lw,MeasureLayout:bw}};function Dx(t,s,i){const{props:l}=t;t.animationState&&l.whileHover&&t.animationState.setActive(\"whileHover\",i===\"Start\");const o=\"onHover\"+i,d=l[o];d&&We.postRender(()=>d(s,jr(s)))}class K2 extends Na{mount(){const{current:s}=this.node;s&&(this.unmount=RC(s,(i,l)=>(Dx(this.node,l,\"Start\"),o=>Dx(this.node,o,\"End\"))))}unmount(){}}class Q2 extends Na{constructor(){super(...arguments),this.isActive=!1}onFocus(){let s=!1;try{s=this.node.current.matches(\":focus-visible\")}catch{s=!0}!s||!this.node.animationState||(this.node.animationState.setActive(\"whileFocus\",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive(\"whileFocus\",!1),this.isActive=!1)}mount(){this.unmount=vr(pr(this.node.current,\"focus\",()=>this.onFocus()),pr(this.node.current,\"blur\",()=>this.onBlur()))}unmount(){}}function kx(t,s,i){const{props:l}=t;if(t.current instanceof HTMLButtonElement&&t.current.disabled)return;t.animationState&&l.whileTap&&t.animationState.setActive(\"whileTap\",i===\"Start\");const o=\"onTap\"+(i===\"End\"?\"\":i),d=l[o];d&&We.postRender(()=>d(s,jr(s)))}class Z2 extends Na{mount(){const{current:s}=this.node;s&&(this.unmount=_C(s,(i,l)=>(kx(this.node,l,\"Start\"),(o,{success:d})=>kx(this.node,o,d?\"End\":\"Cancel\")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const Kf=new WeakMap,gf=new WeakMap,J2=t=>{const s=Kf.get(t.target);s&&s(t)},W2=t=>{t.forEach(J2)};function eE({root:t,...s}){const i=t||document;gf.has(i)||gf.set(i,{});const l=gf.get(i),o=JSON.stringify(s);return l[o]||(l[o]=new IntersectionObserver(W2,{root:t,...s})),l[o]}function tE(t,s,i){const l=eE(s);return Kf.set(t,i),l.observe(t),()=>{Kf.delete(t),l.unobserve(t)}}const nE={some:0,all:1};class sE extends Na{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:s={}}=this.node.getProps(),{root:i,margin:l,amount:o=\"some\",once:d}=s,f={root:i?i.current:void 0,rootMargin:l,threshold:typeof o==\"number\"?o:nE[o]},m=p=>{const{isIntersecting:y}=p;if(this.isInView===y||(this.isInView=y,d&&!y&&this.hasEnteredView))return;y&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive(\"whileInView\",y);const{onViewportEnter:x,onViewportLeave:g}=this.node.getProps(),w=y?x:g;w&&w(p)};return tE(this.node.current,f,m)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>\"u\")return;const{props:s,prevProps:i}=this.node;[\"amount\",\"margin\",\"root\"].some(aE(s,i))&&this.startObserver()}unmount(){}}function aE({viewport:t={}},{viewport:s={}}={}){return i=>t[i]!==s[i]}const iE={inView:{Feature:sE},tap:{Feature:Z2},focus:{Feature:Q2},hover:{Feature:K2}},lE={layout:{ProjectionNode:lw,MeasureLayout:bw}},rE={...R2,...iE,...X2,...lE},Le=C2(rE,A2),Qh=\"https://rateright-growth-production.up.railway.app\";async function Zh(){try{const{data:{session:t}}=await Nt.auth.getSession();return t?.access_token||null}catch{return null}}async function k(t,s={}){const i=`${Qh}${t}`,l=await Zh(),d={headers:{\"Content-Type\":\"application/json\",...l?{Authorization:`Bearer ${l}`}:{},...s.headers},...s},f=await fetch(i,d);if(!f.ok){const m=await f.json().catch(()=>({error:\"Request failed\"}));throw new Error(m.error||`HTTP ${f.status}`)}return f.status===204?null:f.json()}const Tr={list:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/leads${s?`?${s}`:\"\"}`)},get:t=>k(`/api/leads/${t}`),create:t=>k(\"/api/leads\",{method:\"POST\",body:JSON.stringify(t)}),update:(t,s)=>k(`/api/leads/${t}`,{method:\"PATCH\",body:JSON.stringify(s)}),updateLead:(t,s)=>k(`/api/leads/${t}`,{method:\"PATCH\",body:JSON.stringify(s)}),delete:t=>k(`/api/leads/${t}`,{method:\"DELETE\"}),archive:(t,s)=>k(`/api/leads/${t}/archive`,{method:\"POST\",body:JSON.stringify({reason:s})}),archiveLead:(t,s)=>k(`/api/leads/${t}/archive`,{method:\"POST\",body:JSON.stringify({reason:s})}),importFromSheet:()=>k(\"/api/leads/import-sheet\",{method:\"POST\"}),search:t=>k(`/api/leads/search?q=${encodeURIComponent(t)}`),claim:t=>k(`/api/leads/${t}/claim`,{method:\"POST\"}),release:t=>k(`/api/leads/${t}/release`,{method:\"POST\"}),assignments:()=>k(\"/api/leads/assignments\")},Jk={get:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/call-list${s?`?${s}`:\"\"}`)},stats:()=>k(\"/api/call-list/stats\"),activity:t=>k(`/api/call-list/activity${t?`?date=${t}`:\"\"}`)},Wk={send:t=>k(\"/api/sms/send\",{method:\"POST\",body:JSON.stringify(t)}),batch:t=>k(\"/api/sms/batch\",{method:\"POST\",body:JSON.stringify(t)}),preview:t=>k(\"/api/sms/preview\",{method:\"POST\",body:JSON.stringify(t)}),requestContact:t=>k(\"/api/sms/request-contact\",{method:\"POST\",body:JSON.stringify({leadId:t})}),getTemplates:t=>k(`/api/sms/templates${t?`?category=${t}`:\"\"}`),getTemplate:t=>k(`/api/sms/templates/${t}`),createTemplate:t=>k(\"/api/sms/templates\",{method:\"POST\",body:JSON.stringify(t)}),updateTemplate:(t,s)=>k(`/api/sms/templates/${t}`,{method:\"PUT\",body:JSON.stringify(s)}),deleteTemplate:t=>k(`/api/sms/templates/${t}`,{method:\"DELETE\"}),useTemplate:t=>k(`/api/sms/templates/${t}/use`,{method:\"POST\"}),getConversations:(t=\"all\")=>k(`/api/sms/conversations?filter=${t}`),getConversation:t=>k(`/api/sms/conversation/${t}`),markAsRead:t=>k(`/api/sms/conversation/${t}/read`,{method:\"PATCH\"}),handleConversation:(t,s=!0)=>k(`/api/sms/conversation/${t}/handle`,{method:\"PATCH\",body:JSON.stringify({handled:s})}),getPrioritized:(t=50)=>k(`/api/sms/conversations/prioritized?limit=${t}`),getAiSuggestion:(t,s)=>k(\"/api/sms/ai-suggest\",{method:\"POST\",body:JSON.stringify({leadId:t,lastMessage:s})}),getScheduled:t=>k(`/api/sms/scheduled${t?`?leadId=${t}`:\"\"}`),cancelScheduled:t=>k(`/api/sms/scheduled/${t}`,{method:\"DELETE\"}),getStats:(t=30)=>k(`/api/sms/stats?days=${t}`),sendBatch:t=>k(\"/api/sms/send-batch\",{method:\"POST\",body:JSON.stringify({messages:t})})},oE={log:t=>k(\"/api/calls/log\",{method:\"POST\",body:JSON.stringify(t)}),outcomes:()=>k(\"/api/calls/outcomes\"),getHistory:(t,s=1)=>k(`/api/calls/history/${t}?limit=${s}`)},eR={get:t=>k(`/api/dossier/${t}`),update:(t,s)=>k(`/api/dossier/${t}`,{method:\"PATCH\",body:JSON.stringify(s)}),addFact:(t,s,i=\"manual\")=>k(`/api/dossier/${t}/add-fact`,{method:\"POST\",body:JSON.stringify({fact:s,source:i})}),addCallSummary:(t,s)=>k(`/api/dossier/${t}/add-call-summary`,{method:\"POST\",body:JSON.stringify(s)}),addObjection:(t,s)=>k(`/api/dossier/${t}/add-objection`,{method:\"POST\",body:JSON.stringify(s)})},tR={getAll:()=>k(\"/api/dashboard/all\"),getStats:()=>k(\"/api/dashboard/stats\"),getWisdom:()=>k(\"/api/dashboard/wisdom\"),rateWisdom:(t,s)=>k(\"/api/dashboard/wisdom/rate\",{method:\"POST\",body:JSON.stringify({wisdomId:t,rating:s})}),getStrategy:()=>k(\"/api/dashboard/strategy\"),getPriorityAction:()=>k(\"/api/dashboard/priority-action\"),getSlipping:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/dashboard/slipping${s?`?${s}`:\"\"}`)}},nc={getToken:()=>k(\"/api/voice/token\"),status:()=>k(\"/api/voice/status\"),lookupCaller:t=>k(`/api/voice/lookup-caller?phone=${encodeURIComponent(t)}`)},cE={submit:t=>k(\"/api/bug-report\",{method:\"POST\",body:JSON.stringify(t)})},It={getIntelBrief:t=>k(`/api/ai/intel-brief/${t}`),getLiveIntel:t=>k(`/api/ai/live-intel/${t}`),postCallSummary:t=>k(\"/api/ai/post-call-summary\",{method:\"POST\",body:JSON.stringify(t)}),draftMessage:t=>k(\"/api/ai/draft-message\",{method:\"POST\",body:JSON.stringify(t)}),transcribe:async t=>{const s=new FormData;s.append(\"audio\",t,\"audio.webm\");const i=`${Qh}/api/ai/transcribe`,l=await Zh(),o=l?{Authorization:`Bearer ${l}`}:{},d=await fetch(i,{method:\"POST\",body:s,headers:o});if(!d.ok)throw new Error(\"Transcription failed\");return d.json()},voiceCommand:t=>k(\"/api/ai/voice-command\",{method:\"POST\",body:JSON.stringify(t)}),objectionResponse:t=>k(\"/api/ai/objection-response\",{method:\"POST\",body:JSON.stringify(t)}),getConversionProbability:t=>k(`/api/ai/conversion-probability/${t}`),weeklyInsights:()=>k(\"/api/ai/weekly-insights\",{method:\"POST\"}),cleanupNotes:t=>k(\"/api/ai/cleanup-notes\",{method:\"POST\",body:JSON.stringify(t)}),getInsights:()=>k(\"/api/ai/insights\"),getDeepgramCredentials:()=>k(\"/api/ai/deepgram-credentials\"),saveCopilotSession:t=>k(\"/api/ai/copilot-session\",{method:\"POST\",body:JSON.stringify(t)}),suggestionFeedback:t=>k(\"/api/ai/suggestion-feedback\",{method:\"POST\",body:JSON.stringify(t)}),getSimilarWins:t=>k(`/api/ai/similar-wins/${t}`),getEffectiveResponses:(t,s)=>{const i=s?`?trade=${encodeURIComponent(s)}`:\"\";return k(`/api/ai/effective-responses/${t}${i}`)},companyResearch:(t,s=!1)=>{const i=s?\"?refresh=true\":\"\";return k(`/api/ai/company-research/${encodeURIComponent(t)}${i}`)},personResearch:(t,s=!1)=>k(`/api/ai/person-research/${t}${s?\"?refresh=true\":\"\"}`),updateIntel:t=>k(\"/api/ai/update-intel\",{method:\"POST\",body:JSON.stringify(t)}),parseIntelVoiceNote:t=>k(\"/api/ai/parse-intel-voice\",{method:\"POST\",body:JSON.stringify(t)}),extractContractor:t=>k(\"/api/ai/extract-contractor\",{method:\"POST\",body:JSON.stringify(t)}),addContractorLead:t=>k(\"/api/ai/extract-contractor\",{method:\"POST\",body:JSON.stringify({...t,createLead:!0})}),extractLeadCorrections:t=>k(\"/api/ai/extract-lead-corrections\",{method:\"POST\",body:JSON.stringify(t)}),draftSimilar:t=>k(\"/api/ai/draft-similar\",{method:\"POST\",body:JSON.stringify(t)})},nR={status:()=>k(\"/api/sync/platform/status\"),stats:()=>k(\"/api/sync/platform/stats\"),syncAll:(t={})=>k(\"/api/sync/platform\",{method:\"POST\",body:JSON.stringify(t)}),syncRecent:()=>k(\"/api/sync/platform/recent\",{method:\"POST\"})},sR={getFunnel:()=>k(\"/api/activation/funnel\"),getLeadsAtStage:(t,s)=>{const i=new URLSearchParams({stage:t});return s&&i.append(\"type\",s),k(`/api/activation/leads-at-stage?${i}`)},getStuck:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/activation/stuck${s?`?${s}`:\"\"}`)},getRevenueAtRisk:()=>k(\"/api/activation/revenue-at-risk\"),getMetrics:(t=30)=>k(`/api/activation/metrics?days=${t}`),getTransitions:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/activation/stage-transitions${s?`?${s}`:\"\"}`)},analyze:()=>k(\"/api/activation/analyze\"),generateNudge:t=>k(\"/api/activation/nudge\",{method:\"POST\",body:JSON.stringify({leadId:t})}),bulkNudge:t=>k(\"/api/activation/bulk-nudge\",{method:\"POST\",body:JSON.stringify(t)}),addToCallList:t=>k(\"/api/activation/add-to-call-list\",{method:\"POST\",body:JSON.stringify(t)}),getActionScript:(t,s=\"contractor\")=>k(`/api/activation/action-script?stage=${t}&type=${s}`),getDropoffAnalysis:(t,s=\"contractor\")=>k(`/api/activation/dropoff-analysis?stage=${t}&type=${s}`),getNudgeTemplates:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/activation/nudge-templates${s?`?${s}`:\"\"}`)},createNudgeTemplate:t=>k(\"/api/activation/nudge-templates\",{method:\"POST\",body:JSON.stringify(t)}),updateNudgeTemplate:(t,s)=>k(`/api/activation/nudge-templates/${t}`,{method:\"PATCH\",body:JSON.stringify(s)}),deleteNudgeTemplate:t=>k(`/api/activation/nudge-templates/${t}`,{method:\"DELETE\"}),getJourney:t=>k(`/api/activation/journey/${t}`),getDiagnosis:t=>k(`/api/activation/diagnose/${t}`),getSimilarWins:(t,s=5)=>k(`/api/activation/similar-wins/${t}?limit=${s}`)},hc={list:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/scripts${s?`?${s}`:\"\"}`)},get:t=>k(`/api/scripts/${t}`),create:t=>k(\"/api/scripts\",{method:\"POST\",body:JSON.stringify(t)}),update:(t,s)=>k(`/api/scripts/${t}`,{method:\"PATCH\",body:JSON.stringify(s)}),delete:t=>k(`/api/scripts/${t}`,{method:\"DELETE\"}),startSession:(t,s)=>k(`/api/scripts/${t}/use`,{method:\"POST\",body:JSON.stringify({lead_id:s})}),endSession:(t,s)=>k(`/api/scripts/sessions/${t}`,{method:\"PATCH\",body:JSON.stringify(s)}),getForLead:t=>k(`/api/scripts/for-lead/${t}`),getAIRecommendation:t=>k(`/api/scripts/ai-recommend/${t}`),recordUsage:(t,s=!1)=>k(`/api/scripts/${t}/use`,{method:\"POST\",body:JSON.stringify({replied:s})}),getAnalytics:(t=30)=>k(`/api/scripts/analytics/overview?days=${t}`),getObjections:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/scripts/objections/list${s?`?${s}`:\"\"}`)},getObjection:t=>k(`/api/scripts/objections/${t}`),createObjection:t=>k(\"/api/scripts/objections\",{method:\"POST\",body:JSON.stringify(t)}),addObjectionResponse:(t,s)=>k(`/api/scripts/objections/${t}/response`,{method:\"POST\",body:JSON.stringify({response:s})}),getGuidelines:()=>k(\"/api/scripts/guidelines\"),updateGuidelines:t=>k(\"/api/scripts/guidelines\",{method:\"PUT\",body:JSON.stringify(t)}),getGuidelinesHistory:(t=20)=>k(`/api/scripts/guidelines/history?limit=${t}`),checkCompliance:(t,s={})=>k(\"/api/scripts/compliance/check\",{method:\"POST\",body:JSON.stringify({message:t,options:s})}),autoFix:t=>k(\"/api/scripts/compliance/auto-fix\",{method:\"POST\",body:JSON.stringify({message:t})}),validateScript:t=>k(`/api/scripts/compliance/validate/${t}`,{method:\"POST\"}),batchValidate:t=>k(\"/api/scripts/compliance/batch-validate\",{method:\"POST\",body:JSON.stringify({scriptIds:t})}),getComplianceStats:()=>k(\"/api/scripts/compliance/stats\"),getQueue:(t=\"pending\",s=20)=>k(`/api/scripts/compliance/queue?status=${t}&limit=${s}`),approveItem:t=>k(`/api/scripts/compliance/queue/${t}/approve`,{method:\"POST\"}),rejectItem:(t,s)=>k(`/api/scripts/compliance/queue/${t}/reject`,{method:\"POST\",body:JSON.stringify({reason:s})}),editItem:(t,s)=>k(`/api/scripts/compliance/queue/${t}/edit`,{method:\"POST\",body:JSON.stringify({final_content:s})})},aR={list:()=>k(\"/api/achievements\"),getUserAchievements:()=>k(\"/api/achievements/user\"),check:()=>k(\"/api/achievements/check\",{method:\"POST\"})},iR={getUser:()=>k(\"/api/xp/user\"),award:t=>k(\"/api/xp/award\",{method:\"POST\",body:JSON.stringify(t)}),getHistory:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/xp/history${s?`?${s}`:\"\"}`)},getLeaderboard:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/xp/leaderboard${s?`?${s}`:\"\"}`)}},Rx={list:t=>k(`/api/sequences${t?`?channel=${t}`:\"\"}`),get:t=>k(`/api/sequences/${t}`),enroll:(t,s)=>k(`/api/sequences/${t}/enroll`,{method:\"POST\",body:JSON.stringify({lead_ids:Array.isArray(s)?s:[s]})}),unenroll:(t,s)=>k(`/api/sequences/${t}/unenroll`,{method:\"POST\",body:JSON.stringify({lead_id:s})}),getActiveEnrollments:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/sequences/enrollments/active${s?`?${s}`:\"\"}`)},getLeadEnrollments:t=>k(`/api/sequences/enrollments/lead/${t}`),pauseEnrollment:(t,s)=>k(`/api/sequences/enrollments/${t}/pause`,{method:\"POST\",body:JSON.stringify({reason:s})}),resumeEnrollment:t=>k(`/api/sequences/enrollments/${t}/resume`,{method:\"POST\"}),skipStep:t=>k(`/api/sequences/enrollments/${t}/skip`,{method:\"POST\"}),sendNow:t=>k(`/api/sequences/enrollments/${t}/send-now`,{method:\"POST\"}),getOptOutStatus:t=>k(`/api/sequences/lead/${t}/opt-out`),setOptOut:(t,s)=>k(`/api/sequences/lead/${t}/opt-out`,{method:\"POST\",body:JSON.stringify({opted_out:s})}),bulkEnrollPreview:(t,s=100,i)=>{const l=new URLSearchParams({dry_run:\"true\",limit:s.toString()});return i&&l.set(\"source\",i),k(`/api/sequences/${t}/bulk-enroll?${l}`,{method:\"POST\"})},bulkEnroll:(t,s=100,i)=>{const l=new URLSearchParams({limit:s.toString()});return i&&l.set(\"source\",i),k(`/api/sequences/${t}/bulk-enroll?${l}`,{method:\"POST\"})}},lR={getScores:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/coaching/scores${s?`?${s}`:\"\"}`)},scoreCall:t=>k(\"/api/coaching/score\",{method:\"POST\",body:JSON.stringify(t)}),getTips:()=>k(\"/api/coaching/tips\"),getWeekly:()=>k(\"/api/coaching/weekly\"),getPatterns:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/coaching/patterns${s?`?${s}`:\"\"}`)}},rR={getTrends:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/analytics/trends${s?`?${s}`:\"\"}`)},getPatterns:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/analytics/patterns${s?`?${s}`:\"\"}`)},getFunnel:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/analytics/funnel${s?`?${s}`:\"\"}`)},getBestTimes:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/analytics/best-times${s?`?${s}`:\"\"}`)},getSources:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/analytics/sources${s?`?${s}`:\"\"}`)},savePattern:t=>k(\"/api/analytics/patterns\",{method:\"POST\",body:JSON.stringify(t)})},oR={list:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/ai-alerts${s?`?${s}`:\"\"}`)},create:t=>k(\"/api/ai-alerts\",{method:\"POST\",body:JSON.stringify(t)}),markRead:t=>k(`/api/ai-alerts/${t}/read`,{method:\"PATCH\"}),dismiss:t=>k(`/api/ai-alerts/${t}/dismiss`,{method:\"PATCH\"}),markAllRead:()=>k(\"/api/ai-alerts/read-all\",{method:\"POST\"}),generate:()=>k(\"/api/ai-alerts/generate\",{method:\"POST\"})},cR={getLeaderboard:(t=\"today\")=>k(`/api/battleground/leaderboard?period=${t}`),getUserStats:t=>k(`/api/battleground/leaderboard/${t}`),saveSnapshot:()=>k(\"/api/battleground/leaderboard/snapshot\",{method:\"POST\"}),getHallOfFame:()=>k(\"/api/battleground/hall-of-fame\"),checkRecord:(t,s,i,l,o)=>k(\"/api/battleground/hall-of-fame/check\",{method:\"POST\",body:JSON.stringify({recordType:t,userId:s,userName:i,value:l,details:o})}),getChallenges:()=>k(\"/api/battleground/challenges\"),updateChallengeProgress:(t,s=1)=>k(\"/api/battleground/challenges/progress\",{method:\"POST\",body:JSON.stringify({actionType:t,count:s})}),generateChallenges:()=>k(\"/api/battleground/challenges/generate\",{method:\"POST\"}),getTeamPulse:(t=20)=>k(`/api/battleground/pulse?limit=${t}`),createPulseEvent:t=>k(\"/api/battleground/pulse\",{method:\"POST\",body:JSON.stringify(t)}),getUserBadges:t=>k(`/api/battleground/badges/${t}`),getCurrentBadges:()=>k(\"/api/battleground/badges\"),awardWeeklyBadges:()=>k(\"/api/battleground/badges/award-weekly\",{method:\"POST\"}),updateStreakTier:(t,s)=>k(\"/api/battleground/streak/update\",{method:\"POST\",body:JSON.stringify({userId:t,streakDays:s})}),getActiveDuels:()=>k(\"/api/battleground/duels/active\"),getDuelHistory:(t=10)=>k(`/api/battleground/duels/history?limit=${t}`),getDuelOdds:(t,s)=>k(`/api/battleground/duels/odds?targetId=${t}&duelType=${s}`),createDuel:(t,s,i)=>k(\"/api/battleground/duels/challenge\",{method:\"POST\",body:JSON.stringify({targetId:t,duelType:s,stakeAmount:i})}),acceptDuel:t=>k(`/api/battleground/duels/${t}/accept`,{method:\"POST\"}),declineDuel:t=>k(`/api/battleground/duels/${t}/decline`,{method:\"POST\"}),getDuelScores:t=>k(`/api/battleground/duels/${t}/scores`),createChallenge:t=>k(\"/api/battleground/challenges\",{method:\"POST\",body:JSON.stringify(t)}),joinChallenge:t=>k(`/api/battleground/challenges/${t}/join`,{method:\"POST\"}),getChallengeDetails:t=>k(`/api/battleground/challenges/${t}`),getTeam:()=>k(\"/api/battleground/team\"),getCelebrations:(t=10)=>k(`/api/battleground/celebrations?limit=${t}`)},uR={getToday:()=>k(\"/api/playbook/today\"),send:(t,s,i)=>k(\"/api/playbook/send\",{method:\"POST\",body:JSON.stringify({leadId:t,messageId:s,messageText:i})}),getBulkPreview:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/playbook/bulk-preview${s?`?${s}`:\"\"}`)},bulkSend:(t,s,i={})=>k(\"/api/playbook/bulk-send\",{method:\"POST\",body:JSON.stringify({batchId:t,leadIds:s,edits:i})})},Mx={getRecordings:()=>k(\"/api/voicemail/recordings\"),createRecording:async t=>{const s=await Zh(),i=await fetch(`${Qh}/api/voicemail/recordings`,{method:\"POST\",headers:{Authorization:`Bearer ${s}`},body:t});if(!i.ok){const l=await i.json().catch(()=>({error:\"Upload failed\"}));throw new Error(l.error||\"Failed to upload\")}return i.json()},createRecordingFromUrl:t=>k(\"/api/voicemail/recordings\",{method:\"POST\",body:JSON.stringify(t)}),deleteRecording:t=>k(`/api/voicemail/recordings/${t}`,{method:\"DELETE\"}),setDefault:t=>k(`/api/voicemail/recordings/${t}/default`,{method:\"PATCH\"}),drop:(t,s,i)=>k(\"/api/voicemail/drop\",{method:\"POST\",body:JSON.stringify({callSid:t,recordingId:s,leadId:i})}),getStats:()=>k(\"/api/voicemail/drops/stats\")},dR={getDashboard:(t=\"week\")=>k(`/api/manager/dashboard?period=${t}`),getAnalytics:(t=\"week\")=>k(`/api/manager/analytics?period=${t}`),getRepDetail:(t,s=\"week\")=>k(`/api/manager/rep/${t}?period=${s}`)},fR={getDashboard:()=>k(\"/api/intelligence/dashboard\"),track:t=>k(\"/api/intelligence/track\",{method:\"POST\",body:JSON.stringify(t)}),trackBatch:t=>k(\"/api/intelligence/track-batch\",{method:\"POST\",body:JSON.stringify({events:t})}),getSuggestions:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/intelligence/suggestions${s?`?${s}`:\"\"}`)},updateSuggestionStatus:(t,s)=>k(`/api/intelligence/suggestions/${t}/status`,{method:\"PATCH\",body:JSON.stringify(s)}),getFriction:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/intelligence/friction${s?`?${s}`:\"\"}`)},getPageStats:(t=7)=>k(`/api/intelligence/page-stats?days=${t}`),getMetrics:(t,s,i)=>{const l=new URLSearchParams({start_date:t});return s&&l.append(\"end_date\",s),i&&l.append(\"metric_name\",i),k(`/api/intelligence/metrics?${l}`)}},Ox={getVapidKey:()=>k(\"/api/notifications/vapid-public-key\"),subscribe:t=>k(\"/api/notifications/subscribe\",{method:\"POST\",body:JSON.stringify({subscription:t})}),unsubscribe:(t=null)=>k(\"/api/notifications/unsubscribe\",{method:\"DELETE\",body:JSON.stringify({endpoint:t})}),getPreferences:()=>k(\"/api/notifications/preferences\"),updatePreferences:t=>k(\"/api/notifications/preferences\",{method:\"PUT\",body:JSON.stringify(t)}),test:()=>k(\"/api/notifications/test\",{method:\"POST\"}),getStatus:()=>k(\"/api/notifications/status\")},qn=[{id:\"opener\",label:\"Opener\",icon:\"👋\"},{id:\"discovery\",label:\"Discovery\",icon:\"🔍\"},{id:\"value_prop\",label:\"Value Prop\",icon:\"💎\"},{id:\"objections\",label:\"Objections\",icon:\"🛡️\"},{id:\"close\",label:\"Close\",icon:\"🎯\"}],uE={opener:{script:\"Hey, it's [your name] from RateRight. How's it going?\",tip:\"Be warm and conversational. Match their energy.\",alternatives:[\"Hi [name], this is [you] from RateRight - got a quick minute?\",\"G'day [name], [you] here from RateRight. How's business?\"]},discovery:{script:\"What's your biggest challenge finding workers right now?\",tip:\"Listen more than you talk. Take mental notes.\",alternatives:[\"How are you currently sourcing your workers?\",\"What trades are hardest to find good people for?\",\"How many workers do you typically need on a job?\"]},value_prop:{script:\"We connect you with pre-vetted workers at just 9.9% - no lock-in contracts.\",tip:\"Focus on their pain points. Make it about them.\",alternatives:[\"Most of our contractors find workers within 24 hours.\",\"You only pay when they work - no upfront fees.\",\"Every worker is vetted with references and qualifications checked.\"]},objections:{script:\"I hear you. What would need to change for this to make sense?\",tip:\"Don't argue. Acknowledge and redirect.\",alternatives:[\"That's a fair point. Here's how other contractors handle that...\",\"I understand. Can I ask what you're comparing us to?\",\"Makes sense. What if we could address that concern?\"]},close:{script:\"Let me get you set up - it takes about 2 minutes. What's your email?\",tip:\"Assume the sale. Be confident.\",alternatives:[\"When's your next job starting? Let's get you ready.\",\"I'll send you the link now - what email should I use?\",\"Want me to walk you through it while we're on the phone?\"]}};function dE({lead:t,duration:s,onHangUp:i,onMute:l,isMuted:o,onMarkHot:d}){const[f,m]=b.useState(0),[p,y]=b.useState(null),[x,g]=b.useState(null),[w,S]=b.useState(!1),[T,N]=b.useState([]),[R,D]=b.useState(null),[A,C]=b.useState([]);b.useEffect(()=>{t?.id&&(B(),_())},[t?.id]);const B=async()=>{try{const $=await hc.getRecommendation(t.id);$?.script&&y($.script)}catch{console.log(\"Using default scripts\")}},_=async()=>{try{const $=await It.getIntelBrief(t.id);if($){D($);const W=[];$.openingLine&&W.push({type:\"opener\",text:$.openingLine}),$.talkingPoints?.length&&$.talkingPoints.forEach(se=>W.push({type:\"point\",text:se})),$.similarWins?.length&&W.push({type:\"win\",text:`Similar win: ${$.similarWins[0].name} - \"${$.similarWins[0].whatWorked}\"`}),$.company?.sales_angle&&W.push({type:\"angle\",text:$.company.sales_angle}),C(W)}}catch{console.log(\"Intel not available\")}},F=$=>{const W=uE[$];if(!p)return W;switch($){case\"opener\":return{...W,script:p.opening||W.script};case\"discovery\":return{...W,script:p.discovery_questions?.[0]?.question||W.script,alternatives:p.discovery_questions?.slice(1,4).map(se=>se.question)||W.alternatives};case\"value_prop\":return{...W,script:p.value_props?.[0]?.prop||W.script,alternatives:p.value_props?.slice(1,4).map(se=>se.prop)||W.alternatives};case\"objections\":return W;case\"close\":return{...W,script:p.closing_techniques?.[0]?.script||W.script,alternatives:p.closing_techniques?.slice(1,4).map(se=>se.script)||W.alternatives};default:return W}},P=async($,W)=>{await navigator.clipboard.writeText($),g(W),setTimeout(()=>g(null),500)},H=()=>{f{m($)},X=()=>{S(!0),d?.()},te=$=>{const W=Math.floor($/60),se=$%60;return`${W}:${se.toString().padStart(2,\"0\")}`},Y=`${t?.first_name||\"\"} ${t?.last_name||\"\"}`.trim()||\"Unknown\";return c.jsxs(\"div\",{className:\"fixed inset-0 z-[60] bg-slate-900 flex flex-col\",children:[c.jsxs(\"div\",{className:\"bg-slate-800 px-4 py-3 flex items-center justify-between safe-area-top\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-3\",children:[c.jsx(\"div\",{className:\"w-10 h-10 rounded-full bg-slate-700 flex items-center justify-center\",children:c.jsx(cr,{className:\"w-5 h-5 text-slate-400\"})}),c.jsxs(\"div\",{children:[c.jsx(\"h2\",{className:\"font-bold text-white\",children:Y}),c.jsxs(\"div\",{className:\"flex items-center gap-2\",children:[c.jsx(\"div\",{className:\"w-2 h-2 rounded-full bg-green-500 animate-pulse\"}),c.jsx(\"span\",{className:\"text-green-400 font-mono text-sm\",children:te(s)})]})]})]}),c.jsx(\"button\",{onClick:X,disabled:w,className:`p-2 rounded-full ${w?\"bg-amber-500 text-white\":\"bg-slate-700 text-slate-400\"}`,children:c.jsx(nl,{className:\"w-5 h-5\"})})]}),c.jsx(\"div\",{className:\"bg-slate-800/50 px-4 py-3 flex items-center gap-2\",children:qn.map(($,W)=>c.jsxs(\"button\",{onClick:()=>z(W),className:`flex-1 py-2 rounded-lg text-center transition-all ${T.includes(W)?\"bg-emerald-600 text-white\":W===f?\"bg-violet-600 text-white ring-2 ring-violet-400\":\"bg-slate-700/50 text-slate-400\"}`,children:[c.jsx(\"span\",{className:\"text-lg\",children:$.icon}),c.jsx(\"p\",{className:\"text-[10px] font-bold mt-0.5\",children:T.includes(W)?\"✓\":$.label})]},$.id))}),c.jsx(\"div\",{className:\"flex-1 overflow-y-auto pb-40\",children:c.jsxs(\"div\",{className:\"p-4 space-y-4\",children:[A.length>0&&c.jsxs(\"div\",{className:\"bg-blue-500/10 border border-blue-500/20 rounded-xl p-3\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-2 mb-2\",children:[c.jsx(ac,{className:\"w-4 h-4 text-blue-400\"}),c.jsx(\"span\",{className:\"text-xs font-bold text-blue-400 uppercase\",children:\"Intel & Talking Points\"})]}),c.jsx(\"div\",{className:\"space-y-2\",children:A.slice(0,4).map(($,W)=>c.jsxs(\"div\",{className:\"flex items-start gap-2\",children:[c.jsx(\"span\",{className:\"text-blue-400 mt-0.5\",children:$.type===\"opener\"?\"💬\":$.type===\"win\"?\"🏆\":$.type===\"angle\"?\"🎯\":\"•\"}),c.jsx(\"p\",{className:\"text-blue-200/80 text-sm\",children:$.text})]},W))})]}),R?.company?.name&&c.jsxs(\"div\",{className:\"flex items-center gap-2 px-1\",children:[c.jsx(jc,{className:\"w-4 h-4 text-slate-500\"}),c.jsxs(\"span\",{className:\"text-slate-400 text-sm\",children:[R.company.name,R.company.industry&&` • ${R.company.industry}`,R.company.size&&` • ${R.company.size}`]})]}),c.jsxs(\"div\",{className:\"text-center py-2\",children:[c.jsx(\"span\",{className:\"text-3xl\",children:qn[f].icon}),c.jsx(\"h3\",{className:\"text-xl font-bold text-white mt-2\",children:qn[f].label}),c.jsxs(\"p\",{className:\"text-slate-400 text-sm\",children:[\"Stage \",f+1,\" of \",qn.length]})]}),c.jsxs(\"div\",{className:\"bg-gradient-to-br from-violet-600/20 to-purple-600/10 border border-violet-500/30 rounded-2xl p-4\",children:[c.jsxs(\"div\",{className:\"flex items-start justify-between mb-2\",children:[c.jsx(\"span\",{className:\"text-xs font-bold text-violet-400 uppercase\",children:\"Say This\"}),c.jsx(\"button\",{onClick:()=>P(F(qn[f].id).script,\"main\"),className:\"p-2 -m-2 text-slate-400 hover:text-white\",children:x===\"main\"?c.jsx(ba,{className:\"w-4 h-4 text-green-400\"}):c.jsx(Cf,{className:\"w-4 h-4\"})})]}),c.jsxs(\"p\",{className:\"text-white text-lg leading-relaxed\",children:['\"',F(qn[f].id).script,'\"']})]}),c.jsxs(\"div\",{className:\"bg-amber-500/10 border border-amber-500/20 rounded-xl px-4 py-3\",children:[c.jsx(\"span\",{className:\"text-xs font-bold text-amber-400 uppercase\",children:\"💡 Tip\"}),c.jsx(\"p\",{className:\"text-amber-200/80 text-sm mt-1\",children:F(qn[f].id).tip})]}),c.jsxs(\"div\",{children:[c.jsx(\"h4\",{className:\"text-sm font-bold text-slate-400 mb-2 px-1\",children:\"Or Try These:\"}),c.jsx(\"div\",{className:\"space-y-2\",children:F(qn[f].id).alternatives.map(($,W)=>c.jsxs(\"div\",{className:\"bg-slate-800/50 border border-slate-700 rounded-xl p-3 flex items-start gap-3\",children:[c.jsxs(\"p\",{className:\"text-slate-300 text-sm flex-1\",children:['\"',$,'\"']}),c.jsx(\"button\",{onClick:()=>P($,`alt-${W}`),className:\"p-1 text-slate-500 hover:text-white flex-shrink-0\",children:x===`alt-${W}`?c.jsx(ba,{className:\"w-4 h-4 text-green-400\"}):c.jsx(Cf,{className:\"w-4 h-4\"})})]},W))})]}),f(i&&s?W(s):se(),()=>{ie()}),[]);const W=ee=>{console.log(\"[TwilioCall] Attaching to inbound call\"),X.current=ee,p(\"in-progress\"),Y.current=Date.now(),I();const ge=ee.parameters?.CallSid||null;console.log(\"[TwilioCall] Inbound call CallSid:\",ge),d?.(ge),ee.on(\"disconnect\",()=>{const Ee=Y.current?Math.floor((Date.now()-Y.current)/1e3):0;console.log(\"[TwilioCall] Inbound call disconnected, duration:\",Ee),p(\"ended\"),K(),$.current||($.current=!0,setTimeout(()=>{o?.(Ee)},500))}),ee.on(\"error\",Ee=>{console.error(\"[TwilioCall] Inbound call error:\",Ee),T(Ee.message),p(\"ended\"),K()})},se=async()=>{try{const{token:ee}=await nc.getToken(),ge=new Cb(ee,{logLevel:\"debug\",codecPreferences:[\"opus\",\"pcmu\"],enableRingingState:!0,edge:\"ashburn\"});ge.on(\"error\",Ee=>{console.error(\"Twilio Device error:\",Ee),T(Ee.message),p(\"ended\")}),z.current=ge,p(\"ready\"),O()}catch(ee){console.error(\"Failed to initialize Twilio:\",ee),T(ee.message),p(\"ended\")}},O=async()=>{if(z.current){if(!t?.phone){T(\"No phone number for this lead\"),p(\"ended\");return}try{p(\"connecting\");const ee=await z.current.connect({params:{To:t.phone,leadId:t?.id}});X.current=ee,ee.on(\"ringing\",()=>{p(\"ringing\")}),ee.on(\"accept\",()=>{p(\"in-progress\"),Y.current=Date.now(),I();const ge=ee.parameters?.CallSid||null;console.log(\"[TwilioCall] Call connected, CallSid:\",ge),d?.(ge)}),ee.on(\"disconnect\",()=>{const ge=Y.current?Math.floor((Date.now()-Y.current)/1e3):0;p(\"ended\"),K(),$.current||($.current=!0,setTimeout(()=>{o?.(ge)},500))}),ee.on(\"cancel\",()=>{p(\"ended\"),K(),$.current||($.current=!0,o?.(0))}),ee.on(\"error\",ge=>{console.error(\"Call error:\",ge),T(ge.message),p(\"ended\"),K()})}catch(ee){console.error(\"Failed to make call:\",ee),T(ee.message),p(\"ended\")}}},I=()=>{te.current=setInterval(()=>{Y.current&&x(Math.floor((Date.now()-Y.current)/1e3))},1e3)},K=()=>{te.current&&(clearInterval(te.current),te.current=null)},ie=()=>{K(),!i&&X.current&&X.current.disconnect(),!i&&z.current&&z.current.destroy()},oe=()=>{X.current?X.current.disconnect():l?.()},xe=()=>{X.current&&(g?X.current.mute(!1):X.current.mute(!0),w(!g))},Te=async()=>{if(!(D.length>0)){B(!0);try{const ee=await Mx.getRecordings();A(ee||[])}catch(ee){console.error(\"Failed to load VM recordings:\",ee)}finally{B(!1)}}},ae=async ee=>{const ge=X.current?.parameters?.CallSid;if(!ge){console.error(\"No CallSid available\");return}F(!0);try{await Mx.drop(ge,ee.id,t?.id),H(!0),R(!1)}catch(Ee){console.error(\"VM drop failed:\",Ee),T(\"Failed to drop voicemail\")}finally{F(!1)}},ce=ee=>{const ge=Math.floor(ee/60),Ee=ee%60;return`${ge}:${Ee.toString().padStart(2,\"0\")}`},ne=()=>{switch(m){case\"initializing\":return\"Setting up...\";case\"ready\":return\"Starting call...\";case\"connecting\":return\"Connecting...\";case\"ringing\":return\"Ringing...\";case\"in-progress\":return ce(y);case\"ended\":return\"Call ended\";default:return\"\"}},ue=()=>{switch(m){case\"ringing\":return\"text-amber-400\";case\"in-progress\":return\"text-green-400\";case\"ended\":return\"text-slate-400\";default:return\"text-blue-400\"}},de=`${t?.first_name||\"\"} ${t?.last_name||\"\"}`.trim()||\"Unknown\";return m===\"in-progress\"&&t?c.jsx(dE,{lead:t,duration:y,isMuted:g,onMute:xe,onHangUp:oe,onMarkHot:()=>{console.log(\"Marked hot during call\")}}):c.jsxs(Le.div,{initial:{y:100,opacity:0},animate:{y:0,opacity:1},exit:{y:100,opacity:0},className:\"fixed bottom-0 inset-x-0 z-[60] bg-gradient-to-t from-slate-900 via-slate-900 to-slate-900/95 rounded-t-3xl shadow-2xl pb-safe\",children:[c.jsxs(\"div\",{className:\"px-4 pt-4 pb-2 flex items-center gap-3\",children:[c.jsx(\"div\",{className:\"w-12 h-12 rounded-full bg-slate-700 flex items-center justify-center flex-shrink-0\",children:c.jsx(cr,{className:\"w-6 h-6 text-slate-400\"})}),c.jsxs(\"div\",{className:\"flex-1 min-w-0\",children:[c.jsx(\"h2\",{className:\"text-lg font-bold text-white truncate\",children:de}),c.jsxs(\"div\",{className:\"flex items-center gap-2\",children:[c.jsx(\"span\",{className:`text-sm font-medium ${ue()}`,children:ne()}),m===\"in-progress\"&&f&&c.jsxs(\"div\",{className:\"flex items-center gap-1\",children:[c.jsx(Yj,{className:\"w-3 h-3 text-emerald-400 animate-pulse\"}),c.jsx(\"span\",{className:\"text-xs text-emerald-400\",children:\"Recording\"})]})]})]}),m===\"ringing\"&&c.jsx(\"div\",{className:\"relative w-8 h-8\",children:c.jsx(Le.div,{className:\"absolute inset-0 rounded-full border-2 border-amber-400/50\",animate:{scale:[1,1.5],opacity:[.5,0]},transition:{duration:1.5,repeat:1/0}})})]}),S&&c.jsx(\"p\",{className:\"text-red-400 text-sm text-center px-4 pb-2\",children:S}),c.jsx(\"div\",{className:\"px-4 pb-6 pt-2\",children:m!==\"ended\"?c.jsxs(\"div\",{className:\"flex items-center justify-center gap-6\",children:[c.jsx(\"button\",{onClick:xe,disabled:m!==\"in-progress\",title:g?\"Unmute\":\"Mute\",className:`w-14 h-14 rounded-full flex items-center justify-center transition-colors ${g?\"bg-red-500 text-white\":\"bg-slate-700 text-white disabled:opacity-50\"}`,children:g?c.jsx(Tc,{className:\"w-6 h-6\"}):c.jsx(ti,{className:\"w-6 h-6\"})}),c.jsx(\"button\",{onClick:oe,title:\"End call\",className:\"w-16 h-16 rounded-full bg-red-500 text-white flex items-center justify-center shadow-lg shadow-red-500/30 active:scale-95 transition-transform\",children:c.jsx(ur,{className:\"w-8 h-8\"})}),c.jsx(\"button\",{onClick:()=>{R(!0),Te()},disabled:m===\"initializing\"||m===\"connecting\"||P,title:P?\"Voicemail dropped!\":\"Drop voicemail\",className:`w-14 h-14 rounded-full flex items-center justify-center transition-colors ${P?\"bg-green-600 text-white\":\"bg-amber-600 text-white disabled:opacity-50\"}`,children:P?c.jsx(ba,{className:\"w-6 h-6\"}):c.jsx(ey,{className:\"w-6 h-6\"})})]}):c.jsx(\"button\",{onClick:()=>{$.current||($.current=!0,o?.(y))},className:\"w-full py-4 bg-blue-600 text-white rounded-xl font-bold text-lg\",children:\"Continue\"})}),c.jsx(si,{children:N&&c.jsx(Le.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:\"fixed inset-0 z-[70] bg-black/60 flex items-end justify-center\",onClick:()=>R(!1),children:c.jsxs(Le.div,{initial:{y:\"100%\"},animate:{y:0},exit:{y:\"100%\"},className:\"w-full max-w-md bg-slate-800 rounded-t-2xl p-4 pb-8\",onClick:ee=>ee.stopPropagation(),children:[c.jsxs(\"div\",{className:\"flex items-center justify-between mb-4\",children:[c.jsx(\"h3\",{className:\"text-lg font-bold text-white\",children:\"Drop Voicemail\"}),c.jsx(\"button\",{onClick:()=>R(!1),className:\"w-8 h-8 rounded-full bg-slate-700 flex items-center justify-center\",children:c.jsx(Gt,{className:\"w-5 h-5 text-slate-400\"})})]}),C?c.jsx(\"div\",{className:\"flex items-center justify-center py-8\",children:c.jsx(_n,{className:\"w-6 h-6 text-blue-400 animate-spin\"})}):D.length===0?c.jsxs(\"div\",{className:\"text-center py-8 text-slate-400\",children:[\"No voicemail recordings yet.\",c.jsx(\"br\",{}),c.jsx(\"span\",{className:\"text-sm\",children:\"Add recordings in Settings → Voicemail\"})]}):c.jsx(\"div\",{className:\"space-y-2 max-h-64 overflow-y-auto\",children:D.map(ee=>c.jsxs(\"button\",{onClick:()=>ae(ee),disabled:_,className:\"w-full p-3 bg-slate-700/50 rounded-xl flex items-center gap-3 hover:bg-slate-700 transition-colors disabled:opacity-50\",children:[c.jsx(\"div\",{className:\"w-10 h-10 rounded-full bg-amber-600/20 flex items-center justify-center flex-shrink-0\",children:c.jsx(ey,{className:\"w-5 h-5 text-amber-400\"})}),c.jsxs(\"div\",{className:\"flex-1 text-left\",children:[c.jsx(\"p\",{className:\"text-white font-medium\",children:ee.name}),ee.description&&c.jsx(\"p\",{className:\"text-slate-400 text-sm truncate\",children:ee.description})]}),ee.is_default&&c.jsx(\"span\",{className:\"text-xs bg-blue-600/30 text-blue-400 px-2 py-0.5 rounded\",children:\"Default\"}),_&&c.jsx(_n,{className:\"w-4 h-4 text-blue-400 animate-spin\"})]},ee.id))}),c.jsx(\"p\",{className:\"text-xs text-slate-500 text-center mt-4\",children:\"Selecting a voicemail will play it to the recipient and end the call\"})]})})})]})}function hE({candidate:t,sourceLeadId:s,onAdd:i,onDismiss:l}){const{user:o}=br(),[d,f]=b.useState(!1),m=async()=>{f(!0);try{const x=await It.addContractorLead({sourceLeadId:s,companyName:t.company,projectName:t.project,userEmail:o?.email||\"unknown\"});x.success&&x.lead_id?i(x.lead_id,t):alert(\"Failed to create lead\")}catch(x){console.error(\"Add contractor error:\",x),alert(\"Failed to create lead: \"+x.message)}finally{f(!1)}},p=`${t.first_name||\"\"} ${t.last_name||\"\"}`.trim(),y=Math.round((t.confidence||.5)*100);return c.jsxs(\"div\",{className:\"fixed inset-0 z-50 flex items-center justify-center p-4\",children:[c.jsx(\"div\",{className:\"absolute inset-0 bg-black/60 backdrop-blur-sm\",onClick:l}),c.jsxs(\"div\",{className:\"relative w-full max-w-sm bg-white rounded-2xl shadow-2xl overflow-hidden animate-fade-in\",children:[c.jsx(\"div\",{className:\"bg-gradient-to-r from-amber-500 to-orange-500 px-5 py-4\",children:c.jsxs(\"div\",{className:\"flex items-center justify-between\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-3\",children:[c.jsx(\"div\",{className:\"w-10 h-10 bg-white/20 rounded-xl flex items-center justify-center\",children:c.jsx(nl,{className:\"w-5 h-5 text-white\"})}),c.jsxs(\"div\",{children:[c.jsx(\"h2\",{className:\"text-white font-bold text-lg\",children:\"Contractor Found!\"}),c.jsxs(\"p\",{className:\"text-white/80 text-sm\",children:[y,\"% confidence\"]})]})]}),c.jsx(\"button\",{onClick:l,className:\"w-8 h-8 bg-white/20 rounded-full flex items-center justify-center\",children:c.jsx(Gt,{className:\"w-4 h-4 text-white\"})})]})}),c.jsxs(\"div\",{className:\"p-5\",children:[c.jsxs(\"div\",{className:\"text-center mb-4\",children:[c.jsx(\"h3\",{className:\"text-xl font-bold text-slate-900\",children:p||\"Unknown\"}),t.job_title&&c.jsxs(\"div\",{className:\"flex items-center justify-center gap-2 mt-1 text-slate-600\",children:[c.jsx(Eb,{className:\"w-4 h-4\"}),c.jsx(\"span\",{children:t.job_title})]})]}),c.jsxs(\"div\",{className:\"bg-slate-50 rounded-xl p-4 mb-4 space-y-2\",children:[t.company&&c.jsxs(\"div\",{className:\"flex items-center gap-2 text-slate-700\",children:[c.jsx(Fj,{className:\"w-4 h-4 text-slate-400\"}),c.jsx(\"span\",{className:\"font-semibold\",children:t.company})]}),t.project&&c.jsxs(\"div\",{className:\"flex items-center gap-2 text-slate-600\",children:[c.jsx(ty,{className:\"w-4 h-4 text-slate-400\"}),c.jsxs(\"span\",{children:[t.project,\" Project\"]})]}),t.location&&c.jsxs(\"div\",{className:\"flex items-center gap-2 text-slate-500 text-sm\",children:[c.jsx(ty,{className:\"w-4 h-4 text-slate-400\"}),c.jsx(\"span\",{children:t.location})]})]}),t.linkedin_url&&c.jsxs(\"a\",{href:t.linkedin_url,target:\"_blank\",rel:\"noopener noreferrer\",className:\"flex items-center justify-center gap-2 mb-4 py-2 bg-[#0A66C2] text-white rounded-lg text-sm font-medium hover:bg-[#004182]\",children:[c.jsx(Xj,{className:\"w-4 h-4\"}),\"View LinkedIn Profile\"]}),t.source_worker&&c.jsx(\"div\",{className:\"bg-amber-50 rounded-lg p-3 mb-4 border border-amber-200\",children:c.jsxs(\"p\",{className:\"text-sm text-amber-800\",children:[c.jsx(\"span\",{className:\"font-semibold\",children:\"Source:\"}),\" Worker intel from \",t.source_worker]})}),c.jsxs(\"div\",{className:\"flex gap-3\",children:[c.jsx(\"button\",{onClick:l,className:\"flex-1 py-3 bg-slate-100 text-slate-700 rounded-xl font-semibold hover:bg-slate-200\",children:\"Dismiss\"}),c.jsxs(\"button\",{onClick:m,disabled:d,className:\"flex-1 py-3 bg-gradient-to-r from-green-500 to-emerald-500 text-white rounded-xl font-semibold flex items-center justify-center gap-2 hover:from-green-600 hover:to-emerald-600 disabled:opacity-50\",children:[d?c.jsx(_n,{className:\"w-5 h-5 animate-spin\"}):c.jsx(Af,{className:\"w-5 h-5\"}),\"Add as Lead\"]})]})]})]})]})}function mE(t){const s=Math.floor(t/60),i=t%60;return`${s}:${i.toString().padStart(2,\"0\")}`}const pE={opener:\"Opener\",discovery:\"Discovery\",value_prop:\"Value Props\",objections:\"Objections\",close:\"Close\"},_x=[\"opener\",\"discovery\",\"value_prop\",\"objections\",\"close\"];function gE({duration:t,leadName:s,isListening:i,onMinimize:l}){return c.jsxs(\"div\",{className:\"bg-slate-800 px-4 py-3 flex items-center justify-between safe-area-top\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-3\",children:[c.jsx(\"div\",{className:`w-2.5 h-2.5 rounded-full ${i?\"bg-red-500 animate-pulse\":\"bg-slate-500\"}`}),c.jsx(\"span\",{className:\"text-white font-mono text-lg font-bold tabular-nums\",children:mE(t)})]}),c.jsx(\"span\",{className:\"text-white font-medium truncate max-w-32\",children:s||\"Unknown\"}),c.jsx(\"button\",{onClick:l,className:\"p-2 -mr-2 text-slate-400 hover:text-white\",children:c.jsx(Kj,{className:\"w-5 h-5\"})})]})}function yE({intel:t}){const s=t?.personal_intel?.conversation_starters||t?.person?.conversation_starters||[],i=t?.personal_intel?.interest_news||t?.interest_news,l=[];return i?.items?.length>0&&i.items.slice(0,2).forEach(o=>{l.push({type:\"news\",text:o.talking_point||o.headline,source:o.topic||o.source,emoji:o.topic?.toLowerCase().includes(\"liverpool\")?\"⚽\":o.topic?.toLowerCase().includes(\"f1\")?\"🏎️\":o.topic?.toLowerCase().includes(\"gaa\")?\"🏐\":\"📰\"})}),s.slice(0,3-l.length).forEach(o=>{l.push({type:\"starter\",text:typeof o==\"string\"?o:o.text,source:typeof o==\"string\"?null:o.topic,emoji:\"💬\"})}),l.length===0?null:c.jsxs(\"div\",{className:\"bg-gradient-to-r from-blue-500/20 to-purple-500/20 border border-blue-500/30 rounded-2xl p-3\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-2 mb-2\",children:[c.jsx(\"span\",{className:\"text-sm\",children:\"🎯\"}),c.jsx(\"span\",{className:\"text-xs font-bold text-blue-300 uppercase tracking-wide\",children:\"Ice Breakers\"})]}),c.jsx(\"div\",{className:\"space-y-2\",children:l.map((o,d)=>c.jsxs(\"div\",{className:\"flex items-start gap-2\",children:[c.jsx(\"span\",{className:\"text-base flex-shrink-0\",children:o.emoji}),c.jsxs(\"div\",{className:\"flex-1 min-w-0\",children:[c.jsxs(\"p\",{className:\"text-white text-sm leading-snug\",children:['\"',o.text,'\"']}),o.source&&c.jsx(\"p\",{className:\"text-slate-400 text-xs mt-0.5\",children:o.source})]})]},d))})]})}function xE({stage:t,script:s,openingLine:i}){const[l,o]=b.useState(!1),d=_x.indexOf(t),m=(()=>{if(!s)return i||\"Hey, it's [your name] from RateRight. How's it going?\";switch(t){case\"opener\":return s.opening||i||\"Hey, it's [your name] from RateRight. How's it going?\";case\"discovery\":return s.discovery_questions?.[0]?.question||\"What's your biggest challenge finding workers right now?\";case\"value_prop\":return s.value_props?.[0]?.prop||\"We connect you with pre-vetted workers at just 9.9% - no lock-in contracts.\";case\"objections\":return\"Listen for concerns and address them directly.\";case\"close\":return s.closing_techniques?.[0]?.script||\"Let me get you set up - it takes about 2 minutes. What's your email?\";default:return s.opening||\"Start the conversation...\"}})(),p=async()=>{await navigator.clipboard.writeText(m),o(!0),setTimeout(()=>o(!1),500)};return c.jsxs(\"div\",{className:\"bg-slate-800/50 border border-slate-700 rounded-2xl p-4 relative\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-2 mb-3\",children:[c.jsx(\"span\",{className:\"text-xs font-bold text-violet-400 uppercase tracking-wide\",children:pE[t]||\"Script\"}),c.jsx(\"div\",{className:\"flex-1 h-px bg-slate-700\"}),c.jsxs(\"span\",{className:\"text-xs text-slate-500\",children:[d+1,\"/\",_x.length]})]}),c.jsxs(\"p\",{className:\"text-white text-base leading-relaxed pr-8\",children:['\"',m,'\"']}),c.jsx(\"button\",{onClick:p,className:\"absolute top-4 right-4 p-2 text-slate-400 hover:text-white transition-colors\",children:l?c.jsx(ba,{className:\"w-4 h-4 text-green-400\"}):c.jsx(Cf,{className:\"w-4 h-4\"})})]})}function bE({company:t,person:s,onExpand:i}){if(!t&&!s)return null;const l=[];return t?.name&&l.push(t.name),t?.industry&&l.push(t.industry),t?.size?l.push(t.size):s?.job_title&&l.push(s.job_title),l.length===0?null:c.jsxs(\"button\",{onClick:i,className:\"bg-slate-800/30 border border-slate-700/50 rounded-xl px-4 py-2.5 flex items-center gap-3 w-full text-left\",children:[c.jsx(jc,{className:\"w-4 h-4 text-blue-400 flex-shrink-0\"}),c.jsx(\"span\",{className:\"text-sm text-slate-300 truncate flex-1\",children:l.join(\" • \")}),c.jsx(Ab,{className:\"w-4 h-4 text-slate-500 flex-shrink-0\"})]})}function vE({type:t,trigger:s,suggestion:i,onDismiss:l}){const o=t===\"buying_signal\";return c.jsxs(Le.div,{initial:{y:100,opacity:0,scale:.95},animate:{y:0,opacity:1,scale:1},exit:{y:100,opacity:0,scale:.95},transition:{type:\"spring\",damping:25,stiffness:300},className:`w-full rounded-2xl overflow-hidden relative ${o?\"bg-gradient-to-br from-emerald-500/20 to-green-500/10 border border-emerald-500/50\":\"bg-gradient-to-br from-amber-500/20 to-orange-500/10 border border-amber-500/50\"}`,children:[c.jsxs(\"div\",{className:`px-4 py-2 flex items-center gap-2 ${o?\"bg-emerald-500/30\":\"bg-amber-500/30\"}`,children:[c.jsx(\"span\",{className:\"text-lg\",children:o?\"🔥\":\"⚠️\"}),c.jsx(\"span\",{className:`font-bold text-sm uppercase tracking-wide ${o?\"text-emerald-300\":\"text-amber-300\"}`,children:o?\"BUYING SIGNAL\":i?.objection_type===\"price\"?\"PRICE CONCERN\":i?.objection_type===\"timing\"?\"TIMING ISSUE\":i?.objection_type===\"trust\"?\"TRUST CONCERN\":\"OBJECTION\"})]}),c.jsx(\"div\",{className:\"px-4 pt-3 pb-2\",children:c.jsxs(\"p\",{className:\"text-slate-400 text-sm italic truncate\",children:['\"',s,'\"']})}),c.jsxs(\"div\",{className:\"px-4 pb-3\",children:[c.jsxs(\"p\",{className:\"text-white text-lg font-medium leading-snug\",children:['\"',i?.response||\"Handle this naturally...\",'\"']}),c.jsx(\"p\",{className:\"text-slate-500 text-xs italic mt-1\",children:\"Adapt in your own voice\"})]}),i?.key_point&&c.jsx(\"div\",{className:\"px-4 pb-2\",children:c.jsxs(\"div\",{className:`inline-flex items-center gap-1.5 rounded-full px-3 py-1 ${o?\"bg-emerald-500/20 border border-emerald-500/30\":\"bg-amber-500/20 border border-amber-500/30\"}`,children:[c.jsx(ac,{className:`w-3 h-3 ${o?\"text-emerald-400\":\"text-amber-400\"}`}),c.jsx(\"span\",{className:`text-xs font-medium ${o?\"text-emerald-300\":\"text-amber-300\"}`,children:i.key_point})]})}),i?.follow_up_question&&c.jsxs(\"div\",{className:\"px-4 pb-4 flex items-start gap-2\",children:[c.jsx(Qj,{className:`w-4 h-4 mt-0.5 flex-shrink-0 ${o?\"text-emerald-400\":\"text-amber-400\"}`}),c.jsxs(\"div\",{children:[c.jsx(\"span\",{className:`text-xs font-bold ${o?\"text-emerald-400\":\"text-amber-400\"}`,children:\"THEN ASK:\"}),c.jsxs(\"span\",{className:\"text-slate-300 text-sm ml-1\",children:['\"',i.follow_up_question,'\"']})]})]}),c.jsx(\"button\",{onClick:l,className:\"absolute top-2 right-2 p-2 text-slate-400 hover:text-white\",children:c.jsx(Gt,{className:\"w-4 h-4\"})})]})}function wE({isMuted:t,onMute:s,onMarkHot:i,onEndCall:l,markedHot:o}){return c.jsx(\"div\",{className:\"bg-slate-800 border-t border-slate-700 px-4 py-4 safe-area-bottom\",children:c.jsxs(\"div\",{className:\"flex items-center justify-center gap-4\",children:[c.jsx(\"button\",{onClick:s,className:`w-14 h-14 rounded-full flex items-center justify-center transition-colors ${t?\"bg-red-500 text-white\":\"bg-slate-700 text-slate-300\"}`,children:t?c.jsx(Tc,{className:\"w-6 h-6\"}):c.jsx(ti,{className:\"w-6 h-6\"})}),c.jsx(\"button\",{onClick:i,disabled:o,className:`w-14 h-14 rounded-full flex items-center justify-center transition-colors ${o?\"bg-amber-500 text-white\":\"bg-amber-500/20 border border-amber-500/50 text-amber-400\"}`,children:c.jsx(nl,{className:\"w-6 h-6\"})}),c.jsxs(\"button\",{onClick:l,className:\"px-8 py-4 rounded-full bg-red-500 text-white font-bold flex items-center gap-2 active:scale-95 transition-transform\",children:[c.jsx(ur,{className:\"w-5 h-5\"}),c.jsx(\"span\",{children:\"End\"})]})]})})}function SE({intel:t,leadName:s,onClose:i}){return t?c.jsx(Le.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:\"fixed inset-0 z-[60] bg-black/70 flex items-end\",onClick:i,children:c.jsx(Le.div,{initial:{y:\"100%\"},animate:{y:0},exit:{y:\"100%\"},transition:{type:\"spring\",damping:25,stiffness:300},className:\"bg-slate-800 rounded-t-3xl w-full max-h-[70vh] overflow-y-auto\",onClick:l=>l.stopPropagation(),children:c.jsxs(\"div\",{className:\"p-4\",children:[c.jsx(\"div\",{className:\"w-12 h-1 bg-slate-600 rounded-full mx-auto mb-4\"}),c.jsxs(\"h3\",{className:\"text-lg font-bold text-white mb-4\",children:[\"Intel: \",s]}),t.company&&c.jsxs(\"div\",{className:\"bg-slate-700/50 rounded-xl p-4 mb-3\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-2 mb-2\",children:[c.jsx(jc,{className:\"w-4 h-4 text-blue-400\"}),c.jsx(\"span\",{className:\"text-sm font-semibold text-white\",children:t.company.name})]}),c.jsxs(\"div\",{className:\"flex flex-wrap gap-2\",children:[t.company.industry&&c.jsx(\"span\",{className:\"px-2 py-1 bg-blue-500/20 text-blue-300 text-xs rounded\",children:t.company.industry}),t.company.size&&c.jsx(\"span\",{className:\"px-2 py-1 bg-slate-600 text-slate-300 text-xs rounded\",children:t.company.size}),t.company.location&&c.jsx(\"span\",{className:\"px-2 py-1 bg-slate-600 text-slate-300 text-xs rounded\",children:t.company.location})]}),t.company.sales_angle&&c.jsxs(\"div\",{className:\"mt-3 p-2 bg-emerald-500/10 border border-emerald-500/30 rounded-lg\",children:[c.jsx(\"span\",{className:\"text-xs text-emerald-400 font-semibold\",children:\"SALES ANGLE: \"}),c.jsx(\"span\",{className:\"text-sm text-slate-300\",children:t.company.sales_angle})]})]}),t.person?.job_title&&c.jsxs(\"div\",{className:\"bg-slate-700/50 rounded-xl p-4 mb-3\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-2 mb-1\",children:[c.jsx(\"span\",{className:\"text-lg\",children:\"👤\"}),c.jsx(\"span\",{className:\"text-sm font-semibold text-white\",children:s})]}),c.jsx(\"p\",{className:\"text-slate-400 text-sm\",children:t.person.job_title}),t.person.years_at_company&&c.jsxs(\"p\",{className:\"text-slate-500 text-xs mt-1\",children:[t.person.years_at_company,\" years at company\"]})]}),t.similar_wins?.length>0&&c.jsxs(\"div\",{className:\"bg-slate-700/50 rounded-xl p-4\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-2 mb-2\",children:[c.jsx(\"span\",{className:\"text-lg\",children:\"🏆\"}),c.jsx(\"span\",{className:\"text-sm font-semibold text-amber-400\",children:\"Similar Wins\"})]}),c.jsx(\"div\",{className:\"space-y-2\",children:t.similar_wins.slice(0,3).map((l,o)=>c.jsxs(\"div\",{className:\"text-sm\",children:[c.jsx(\"span\",{className:\"text-slate-300\",children:l.name}),l.key_factor&&c.jsxs(\"span\",{className:\"text-slate-500\",children:[' — \"',l.key_factor,'\"']})]},o))})]})]})})}):null}function jE({lead:t,duration:s,isListening:i,isMuted:l,script:o,scriptStage:d,intel:f,latestSuggestion:m,openingLine:p,error:y,onMinimize:x,onMute:g,onMarkHot:w,onEndCall:S,onDismissSuggestion:T}){const[N,R]=b.useState(!1),[D,A]=b.useState(!1),C=()=>{A(!0),w?.()};return c.jsxs(\"div\",{className:\"fixed inset-0 z-50 bg-slate-900 flex flex-col\",children:[c.jsx(gE,{duration:s,leadName:t?.first_name,isListening:i,onMinimize:x}),c.jsxs(\"div\",{className:\"flex-1 flex flex-col p-4 gap-3 overflow-hidden\",children:[c.jsx(yE,{intel:f}),c.jsx(xE,{stage:d,script:o,openingLine:p}),c.jsx(bE,{company:f?.company,person:f?.person,onExpand:()=>R(!0)}),y&&c.jsxs(\"div\",{className:\"bg-red-500/10 border border-red-500/30 rounded-xl px-4 py-2 flex items-center gap-2\",children:[c.jsx(Db,{className:\"w-4 h-4 text-red-400 flex-shrink-0\"}),c.jsx(\"span\",{className:\"text-red-400 text-sm\",children:y})]}),c.jsxs(\"div\",{className:\"flex-1 flex items-center justify-center px-2\",children:[c.jsx(si,{mode:\"wait\",children:m&&c.jsx(vE,{type:m.type,trigger:m.trigger,suggestion:m.suggestion,onDismiss:T},m.timestamp)}),!m&&i&&c.jsx(\"div\",{className:\"text-center\",children:c.jsxs(\"div\",{className:\"flex items-center justify-center gap-2 text-slate-500\",children:[c.jsx(\"div\",{className:\"w-2 h-2 bg-violet-500 rounded-full animate-pulse\"}),c.jsx(\"span\",{className:\"text-sm\",children:\"Listening for signals...\"})]})})]})]}),c.jsx(wE,{isMuted:l,onMute:g,onMarkHot:C,onEndCall:S,markedHot:D}),c.jsx(si,{children:N&&c.jsx(SE,{intel:f,leadName:t?.first_name,onClose:()=>R(!1)})})]})}const TE={discovery:[\"tell me about\",\"what do you\",\"how many\",\"when did\",\"how long\",\"what's your\",\"who is\"],value_prop:[\"we can help\",\"our platform\",\"rateright\",\"workers available\",\"save you\",\"percentage\"],objections:[\"price\",\"cost\",\"expensive\",\"not sure\",\"competitor\",\"think about\"],close:[\"next step\",\"sign up\",\"get started\",\"send you\",\"email\",\"ready to\"]},NE=[\"expensive\",\"cost\",\"price\",\"too much\",\"can't afford\",\"not sure\",\"think about\",\"need to check\",\"competitor\",\"already have\",\"not interested\",\"busy\",\"later\",\"call back\",\"happy with\",\"current provider\",\"contract\",\"locked in\"],CE=[/works?\\s+for\\s+(.+?)\\s+on\\s+(?:the\\s+)?(.+?)(?:\\s+project|\\s+site|\\s+job|[.!?]|$)/i,/(?:i|we)\\s+work\\s+for\\s+(.+?)(?:\\s+on|\\s+at|[.!?]|$)/i,/(?:my|the)\\s+boss\\s+(?:is\\s+)?(?:at\\s+)?(.+?)(?:[.!?]|$)/i,/working\\s+(?:for|with)\\s+(.+?)(?:\\s+on|\\s+at|[.!?]|$)/i],AE=[/^hey system[,:]?\\s*(.+)/i,/^command[,:]?\\s*(.+)/i,/^note[,:]?\\s*(.+)/i,/^mark\\s+(hot|warm|cold|engaged|converted|lost)/i,/^callback\\s+(.+)/i,/^skip$/i],EE=[\"when can you start\",\"when can we start\",\"how do i sign up\",\"how do we sign up\",\"what's the next step\",\"what is the next step\",\"next steps\",\"let's do it\",\"lets do it\",\"i'm ready\",\"we're ready\",\"sign me up\",\"sign us up\",\"send me the details\",\"send the details\",\"send me a quote\",\"need workers asap\",\"need someone today\",\"starting monday\",\"starting next week\",\"that's reasonable\",\"sounds fair\",\"cheaper than\",\"better than\",\"have a job starting\",\"got a project\",\"need workers\",\"how many workers\",\"do you have electricians\",\"do you have carpenters\"],Lx={\"next step\":{type:\"closing\",response:\"Great question! I can get you set up right now. I just need your email to send the signup link.\",followUp:\"What's the best email to send that to?\",keyPoint:\"They're ready to move forward!\"},sign:{type:\"closing\",response:\"Perfect! Let me get you started. The signup takes about 2 minutes.\",followUp:\"Do you have your ABN handy?\",keyPoint:\"Close the deal now!\"},\"when can\":{type:\"urgency\",response:\"We can have workers available within 24-48 hours once you're set up.\",followUp:\"What trade do you need first?\",keyPoint:\"Match their urgency!\"},\"need workers\":{type:\"qualification\",response:\"We've got a great pool of pre-vetted workers. Most contractors find someone within a day.\",followUp:\"How many workers are you looking for?\",keyPoint:\"Qualify the opportunity!\"},cheaper:{type:\"value\",response:\"Yes, at 9.9% we're typically 30-50% less than traditional agencies, with no lock-in contracts.\",followUp:\"Would you like me to calculate the savings based on your team size?\",keyPoint:\"Reinforce the value!\"},default:{type:\"interest\",response:\"I can hear you're interested! Let me show you how easy it is to get started.\",followUp:\"What's your biggest pain point with finding workers right now?\",keyPoint:\"Keep the momentum!\"}};function DE({lead:t,onClose:s,onEnd:i}){const{scriptSessionId:l,setScriptSessionId:o,preloadedIntel:d}=kc(),[f,m]=b.useState(!1),[p,y]=b.useState(\"\"),[x,g]=b.useState(\"\"),[w,S]=b.useState([]),[T,N]=b.useState(!1),[R,D]=b.useState(null),[A,C]=b.useState(0),[B,_]=b.useState(!1),[F,P]=b.useState(null),[H,z]=b.useState([]),[X,te]=b.useState(\"\"),[Y,$]=b.useState(!0),[W,se]=b.useState(!0),[O,I]=b.useState({}),[K,ie]=b.useState(null),[oe,xe]=b.useState(null),[Te,ae]=b.useState(null),[ce,ne]=b.useState(!1),ue=b.useRef(!1),[de,ee]=b.useState(null),[ge,Ee]=b.useState(!1),[wt,me]=b.useState(null),ze=b.useRef(null),[st,on]=b.useState(!0),[Wt,ms]=b.useState(null),[Yn,Yt]=b.useState(\"opener\"),[li,Ea]=b.useState([]),[Vt,Fn]=b.useState(null),[St,$s]=b.useState(null),[Xn,Da]=b.useState(d),[ps,ka]=b.useState(null),[Ln,ri]=b.useState(!1),cn=b.useRef(!1);b.useEffect(()=>{d&&!cn.current&&(console.log(\"[LiveCopilot] Syncing preloadedIntel from context:\",Object.keys(d)),Da(d),cn.current=!0)},[d]);const Ft=b.useRef(null),ft=b.useRef(null),Ut=b.useRef(null),Ct=b.useRef(null);b.useRef(!1);const Gs=b.useRef(null),Kn=b.useRef(\"\"),un=b.useRef([]),gs=b.useRef(0),Qn=b.useRef(!1),Pt=b.useRef(0),Xt=b.useRef(null),ve=b.useRef(null);b.useEffect(()=>{if(St){const re=setTimeout(()=>{$s(null)},5e3);return()=>clearTimeout(re)}},[St]),b.useEffect(()=>((async()=>(await Fe(),await ht(),await At(),await Zn(),console.log(\"[LiveCopilot] Starting real-time transcription\"),Rt()))(),()=>{xs(),Ut.current&&clearInterval(Ut.current)}),[]),b.useEffect(()=>{Ct.current?.scrollIntoView({behavior:\"smooth\"})},[w]),b.useEffect(()=>(Ut.current=setInterval(()=>{C(re=>(gs.current=re+1,re+1))},1e3),()=>clearInterval(Ut.current)),[]),b.useEffect(()=>{Kn.current=p},[p]),b.useEffect(()=>{un.current=w},[w]),b.useEffect(()=>()=>{!Qn.current&&t?.id&&Kn.current&&(console.log(\"[LiveCopilot] Saving session on unmount, transcript length:\",Kn.current.length),Qn.current=!0,It.saveCopilotSession({leadId:t.id,transcript:Kn.current,suggestions:un.current,duration:gs.current}).catch(re=>console.error(\"[LiveCopilot] Failed to save session on unmount:\",re)))},[t?.id]);const Fe=async()=>{try{const re=await It.getDeepgramCredentials();if(console.log(\"[LiveCopilot] Deepgram configured:\",re.configured),re.configured){const Ae=`wss://${window.location.host.includes(\"rateright.com.au\")?\"rateright-growth-production.up.railway.app\":window.location.host}/api/transcribe/ws`;console.log(\"[LiveCopilot] Using backend proxy:\",Ae),P({configured:!0,proxyUrl:Ae}),Gs.current={configured:!0,proxyUrl:Ae}}else console.log(\"[LiveCopilot] Deepgram not configured, will use Web Speech API fallback\"),Gs.current=null}catch(re){console.log(\"[LiveCopilot] Live transcription not available:\",re.message),Gs.current=null}},ht=async()=>{if(!t?.id){se(!1);return}try{if(t.ai_intel_brief?.talking_points){z(t.ai_intel_brief.talking_points||[]),te(t.ai_intel_brief.opening_line||\"\"),se(!1);return}const re=await It.getIntelBrief(t.id);re.brief&&(z(re.brief.talking_points||[]),te(re.brief.opening_line||\"\"));try{const je=await It.getSimilarWins(t.id);je?.wins?.length>0&&Fn(je.wins[0])}catch(je){console.log(\"Could not load similar wins:\",je)}}catch(re){console.log(\"Could not load intel brief:\",re)}finally{se(!1)}},At=async()=>{if(cn.current||Xn){console.log(\"[LiveCopilot] Intel already loaded, skipping API fetch\");return}if(d){console.log(\"[LiveCopilot] Preloaded intel exists, useEffect will sync\");return}if(t?.id)try{console.log(\"[LiveCopilot] No preloaded intel, fetching from API...\");const re=await It.getLiveIntel(t.id);re.success&&!cn.current&&Da(re)}catch(re){console.log(\"Could not load intel:\",re)}},Zn=async()=>{if(t?.id)try{const re=await hc.getForLead(t.id);if(re.recommendedScripts?.length>0){const je=await hc.get(re.recommendedScripts[0].id);ka(je.script),ms(je.script?.id)}}catch(re){console.log(\"Could not load script:\",re)}},Xe=b.useCallback(re=>{const je=re.toLowerCase();for(const[ye,Ae]of Object.entries(TE))for(const _e of Ae)if(je.includes(_e)){const et=[\"opener\",\"discovery\",\"value_prop\",\"objections\",\"close\"],Be=et.indexOf(Yn);if(et.indexOf(ye)>Be)return Ea(Bn=>[...new Set([...Bn,Yn])]),Yt(ye),!0}return!1},[Yn]),Ht=re=>{const je=Math.floor(re/60),ye=re%60;return`${je}:${ye.toString().padStart(2,\"0\")}`},Jn=b.useCallback(re=>{const je=re.toLowerCase();return NE.some(ye=>je.includes(ye))},[]),Dt=b.useCallback(re=>{const je=re.toLowerCase();for(const ye of EE)if(je.includes(ye)){if(ze.current===ye)return null;ze.current=ye;let Ae=Lx.default;for(const[_e,et]of Object.entries(Lx))if(_e!==\"default\"&&ye.includes(_e)){Ae=et;break}return{trigger:ye,...Ae}}return null},[]),kt=b.useCallback(re=>{me(re);const je={type:\"buying_signal\",trigger:re.trigger,suggestion:{signal_type:re.type,response:re.response,follow_up_question:re.followUp,key_point:re.keyPoint},timestamp:Date.now()};S(ye=>[...ye,je]),$s(je),setTimeout(()=>me(null),5e3)},[]),ys=async re=>{if(!T){N(!0);try{const je=await It.objectionResponse({objection:re,leadId:t?.id});if(je.success){const ye={type:\"objection\",trigger:re,suggestion:je.suggestion,timestamp:Date.now()};S(Ae=>[...Ae,ye]),$s(ye)}}catch(je){console.error(\"Failed to get objection response:\",je)}finally{N(!1)}}},qt=t?.metadata?.lead_type===\"worker\",oi=b.useCallback(re=>{if(!(!qt||ue.current||ce))for(const je of CE){const ye=re.match(je);if(ye){const Ae=ye[1]?.trim(),_e=ye[2]?.trim();if(Ae&&Ae.length>2){console.log(`[ContractorDetection] Found: ${Ae}, project: ${_e||\"N/A\"}`),Dr(Ae,_e);return}}}},[qt,ce]),Dr=async(re,je)=>{if(!(ue.current||ce)){ue.current=!0,ne(!0);try{const ye=await It.extractContractor({sourceLeadId:t?.id,companyName:re,projectName:je});ye.success&&ye.found&&ye.candidate&&ae(ye.candidate)}catch(ye){console.error(\"Contractor search error:\",ye)}finally{ne(!1)}}},Wn=(re,je)=>{ae(null),console.log(\"Contractor lead created:\",re,je)},mt=b.useCallback(async re=>{if(ge)return!1;const je=re.toLowerCase().trim();for(const ye of AE){const Ae=je.match(ye);if(Ae){let _e=Ae[1]||je;(ye.source.includes(\"mark\")||ye.source.includes(\"skip\"))&&(_e=je),console.log(\"[VoiceCommand] Detected:\",_e),Ee(!0);try{const et=await It.voiceCommand({transcript:_e,leadId:t?.id});et.success&&(ee({confirmation:et.parsed.confirmation,intent:et.parsed.intent}),setTimeout(()=>ee(null),3e3))}catch(et){console.error(\"Voice command error:\",et)}finally{Ee(!1)}return!0}}return!1},[t?.id,ge]),Rt=async()=>{try{console.log(\"[LiveCopilot] Requesting microphone access...\");const re=await navigator.mediaDevices.getUserMedia({audio:!0});ve.current=re,Pt.current=0,console.log(\"[LiveCopilot] Microphone access granted\");const je=Gs.current||F;if(console.log(\"[LiveCopilot] Using backend proxy:\",!!(je?.configured&&je?.proxyUrl)),je?.configured&&je?.proxyUrl){console.log(\"[LiveCopilot] Connecting to backend proxy...\"),console.log(\"[LiveCopilot] Proxy URL:\",je.proxyUrl),xe(\"deepgram\");const ye=new WebSocket(je.proxyUrl);console.log(\"[LiveCopilot] WebSocket created, readyState:\",ye.readyState);const Ae=setTimeout(()=>{console.error(\"[LiveCopilot] Connection timeout! readyState:\",ye.readyState),ye.readyState!==WebSocket.OPEN&&(D(\"Connection timeout - trying fallback...\"),ye.close())},1e4);ye.onopen=()=>{clearTimeout(Ae),console.log(\"[LiveCopilot] Connected to transcription proxy!\"),Pt.current=0,m(!0),D(null)},ye.onmessage=Qe=>{const Ke=JSON.parse(Qe.data);if(Ke.error){console.error(\"[LiveCopilot] Proxy error:\",Ke.error),D(Ke.error);return}if(Ke.type===\"Metadata\"&&console.log(\"[LiveCopilot] Transcription metadata:\",Ke),Ke.channel?.alternatives?.[0]?.transcript){console.log(\"[LiveCopilot] Transcript:\",Ke.channel.alternatives[0].transcript,\"is_final:\",Ke.is_final);const Kt=Ke.channel.alternatives[0].transcript;if(Ke.is_final){y(Fs=>Fs+\" \"+Kt),g(\"\"),mt(Kt),Xe(Kt);const Ys=Dt(Kt);Ys?kt(Ys):Jn(Kt)&&ys(Kt),qt&&oi(Kt)}else g(Kt)}},ye.onerror=Qe=>{clearTimeout(Ae),console.error(\"[LiveCopilot] Proxy WebSocket error:\",Qe),console.error(\"[LiveCopilot] Error type:\",Qe.type),console.error(\"[LiveCopilot] Socket readyState on error:\",ye.readyState),D(\"Transcription error - check console\")},ye.onclose=Qe=>{clearTimeout(Ae),console.log(\"[LiveCopilot] Proxy disconnected, code:\",Qe.code,\"reason:\",Qe.reason,\"wasClean:\",Qe.wasClean);const Ke=3;if(Pt.current{console.log(\"[LiveCopilot] Reconnecting WebSocket...\"),Rt()},Kt)}else m(!1),Pt.current>=Ke&&D(\"Transcription disconnected. Tap mic to restart.\")},Ft.current=ye;const _e=new AudioContext,et=_e.sampleRate;console.log(\"[LiveCopilot] AudioContext sample rate:\",et);const Be=`\n./scripts/update-sms-sequences.js:196: console.log('- Removed old \"9.9%\" messaging');\n./scripts/update-all-sms-sequences.js:11: * - Remove \"9.9%\", \"FREE to use\" (for contractors), misleading fee language\n./scripts/update-all-sms-sequences.js:264: // FIX: Remove \"Rocky\", remove \"9.9%\"\n./scripts/update-all-sms-sequences.js:364: console.log(' ✓ 9.9% → $0 for workers');\n./admin/dist/assets/index-2HMepUD5.js:18: `),()=>{D.contains(R)&&D.removeChild(R)}},[s]),c.jsx(JA,{isPresent:s,childRef:d,sizeRef:f,children:b.cloneElement(t,{ref:y})})}const e2=({children:t,initial:s,isPresent:i,onExitComplete:l,custom:o,presenceAffectsLayout:d,mode:f,anchorX:m,root:p})=>{const y=bh(t2),x=b.useId();let g=!0,w=b.useMemo(()=>(g=!1,{id:x,initial:s,isPresent:i,custom:o,onExitComplete:S=>{y.set(S,!0);for(const T of y.values())if(!T)return;l&&l()},register:S=>(y.set(S,!1),()=>y.delete(S))}),[i,y,l]);return d&&g&&(w={...w}),b.useMemo(()=>{y.forEach((S,T)=>y.set(T,!1))},[i]),b.useEffect(()=>{!i&&!y.size&&l&&l()},[i]),f===\"popLayout\"&&(t=c.jsx(WA,{isPresent:i,anchorX:m,root:p,children:t})),c.jsx(Cc.Provider,{value:w,children:t})};function t2(){return new Map}function rw(t=!0){const s=b.useContext(Cc);if(s===null)return[!0,null];const{isPresent:i,onExitComplete:l,register:o}=s,d=b.useId();b.useEffect(()=>{if(t)return o(d)},[t]);const f=b.useCallback(()=>t&&l&&l(d),[d,l,t]);return!i&&l?[!1,f]:[!0]}const $o=t=>t.key||\"\";function yx(t){const s=[];return b.Children.forEach(t,i=>{b.isValidElement(i)&&s.push(i)}),s}const si=({children:t,custom:s,initial:i=!0,onExitComplete:l,presenceAffectsLayout:o=!0,mode:d=\"sync\",propagate:f=!1,anchorX:m=\"left\",root:p})=>{const[y,x]=rw(f),g=b.useMemo(()=>yx(t),[t]),w=f&&!y?[]:g.map($o),S=b.useRef(!0),T=b.useRef(g),N=bh(()=>new Map),R=b.useRef(new Set),[D,A]=b.useState(g),[C,B]=b.useState(g);Vb(()=>{S.current=!1,T.current=g;for(let P=0;P{const H=$o(P),z=f&&!y?!1:g===C||w.includes(H),X=()=>{if(R.current.has(H))return;if(R.current.add(H),N.has(H))N.set(H,!0);else return;let te=!0;N.forEach(Y=>{Y||(te=!1)}),te&&(F?.(),B(T.current),f&&x?.(),l&&l())};return c.jsx(e2,{isPresent:z,initial:!S.current||i?void 0:!1,custom:s,presenceAffectsLayout:o,mode:d,root:p,onExitComplete:z?void 0:X,anchorX:m,children:P},H)})})},ow=b.createContext({strict:!1}),xx={animation:[\"animate\",\"variants\",\"whileHover\",\"whileTap\",\"exit\",\"whileInView\",\"whileFocus\",\"whileDrag\"],exit:[\"exit\"],drag:[\"drag\",\"dragControls\"],focus:[\"whileFocus\"],hover:[\"whileHover\",\"onHoverStart\",\"onHoverEnd\"],tap:[\"whileTap\",\"onTap\",\"onTapStart\",\"onTapCancel\"],pan:[\"onPan\",\"onPanStart\",\"onPanSessionStart\",\"onPanEnd\"],inView:[\"whileInView\",\"onViewportEnter\",\"onViewportLeave\"],layout:[\"layout\",\"layoutId\"]};let bx=!1;function n2(){if(bx)return;const t={};for(const s in xx)t[s]={isEnabled:i=>xx[s].some(l=>!!i[l])};Bv(t),bx=!0}function cw(){return n2(),qC()}function s2(t){const s=cw();for(const i in t)s[i]={...s[i],...t[i]};Bv(s)}const a2=new Set([\"animate\",\"exit\",\"variants\",\"initial\",\"style\",\"values\",\"variants\",\"transition\",\"transformTemplate\",\"custom\",\"inherit\",\"onBeforeLayoutMeasure\",\"onAnimationStart\",\"onAnimationComplete\",\"onUpdate\",\"onDragStart\",\"onDrag\",\"onDragEnd\",\"onMeasureDragConstraints\",\"onDirectionLock\",\"onDragTransitionEnd\",\"_dragX\",\"_dragY\",\"onHoverStart\",\"onHoverEnd\",\"onViewportEnter\",\"onViewportLeave\",\"globalTapTarget\",\"ignoreStrict\",\"viewport\"]);function fc(t){return t.startsWith(\"while\")||t.startsWith(\"drag\")&&t!==\"draggable\"||t.startsWith(\"layout\")||t.startsWith(\"onTap\")||t.startsWith(\"onPan\")||t.startsWith(\"onLayout\")||a2.has(t)}let uw=t=>!fc(t);function i2(t){typeof t==\"function\"&&(uw=s=>s.startsWith(\"on\")?!fc(s):t(s))}try{i2(require(\"@emotion/is-prop-valid\").default)}catch{}function l2(t,s,i){const l={};for(const o in t)o===\"values\"&&typeof t.values==\"object\"||(uw(o)||i===!0&&fc(o)||!s&&!fc(o)||t.draggable&&o.startsWith(\"onDrag\"))&&(l[o]=t[o]);return l}const Dc=b.createContext({});function r2(t,s){if(Ec(t)){const{initial:i,animate:l}=t;return{initial:i===!1||mr(i)?i:void 0,animate:mr(l)?l:void 0}}return t.inherit!==!1?s:{}}function o2(t){const{initial:s,animate:i}=r2(t,b.useContext(Dc));return b.useMemo(()=>({initial:s,animate:i}),[vx(s),vx(i)])}function vx(t){return Array.isArray(t)?t.join(\" \"):t}const Xh=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function dw(t,s,i){for(const l in s)!$t(s[l])&&!$v(l,i)&&(t[l]=s[l])}function c2({transformTemplate:t},s){return b.useMemo(()=>{const i=Xh();return Gh(i,s,t),Object.assign({},i.vars,i.style)},[s])}function u2(t,s){const i=t.style||{},l={};return dw(l,i,t),Object.assign(l,c2(t,s)),l}function d2(t,s){const i={},l=u2(t,s);return t.drag&&t.dragListener!==!1&&(i.draggable=!1,l.userSelect=l.WebkitUserSelect=l.WebkitTouchCallout=\"none\",l.touchAction=t.drag===!0?\"none\":`pan-${t.drag===\"x\"?\"y\":\"x\"}`),t.tabIndex===void 0&&(t.onTap||t.onTapStart||t.whileTap)&&(i.tabIndex=0),i.style=l,i}const fw=()=>({...Xh(),attrs:{}});function f2(t,s,i,l){const o=b.useMemo(()=>{const d=fw();return Gv(d,s,Fv(l),t.transformTemplate,t.style),{...d.attrs,style:{...d.style}}},[s]);if(t.style){const d={};dw(d,t.style,t),o.style={...d,...o.style}}return o}const h2=[\"animate\",\"circle\",\"defs\",\"desc\",\"ellipse\",\"g\",\"image\",\"line\",\"filter\",\"marker\",\"mask\",\"metadata\",\"path\",\"pattern\",\"polygon\",\"polyline\",\"rect\",\"stop\",\"switch\",\"symbol\",\"svg\",\"text\",\"tspan\",\"use\",\"view\"];function Kh(t){return typeof t!=\"string\"||t.includes(\"-\")?!1:!!(h2.indexOf(t)>-1||/[A-Z]/u.test(t))}function m2(t,s,i,{latestValues:l},o,d=!1,f){const p=(f??Kh(t)?f2:d2)(s,l,o,t),y=l2(s,typeof t==\"string\",d),x=t!==b.Fragment?{...y,...p,ref:i}:{},{children:g}=s,w=b.useMemo(()=>$t(g)?g.get():g,[g]);return b.createElement(t,{...x,children:w})}function p2({scrapeMotionValuesFromProps:t,createRenderState:s},i,l,o){return{latestValues:g2(i,l,o,t),renderState:s()}}function g2(t,s,i,l){const o={},d=l(t,{});for(const w in d)o[w]=ec(d[w]);let{initial:f,animate:m}=t;const p=Ec(t),y=zv(t);s&&y&&!p&&t.inherit!==!1&&(f===void 0&&(f=s.initial),m===void 0&&(m=s.animate));let x=i?i.initial===!1:!1;x=x||f===!1;const g=x?m:f;if(g&&typeof g!=\"boolean\"&&!Ac(g)){const w=Array.isArray(g)?g:[g];for(let S=0;S(s,i)=>{const l=b.useContext(Dc),o=b.useContext(Cc),d=()=>p2(t,s,l,o);return i?d():bh(d)},y2=hw({scrapeMotionValuesFromProps:Yh,createRenderState:Xh}),x2=hw({scrapeMotionValuesFromProps:Xv,createRenderState:fw}),b2=Symbol.for(\"motionComponentSymbol\");function v2(t,s,i){const l=b.useRef(i);b.useInsertionEffect(()=>{l.current=i});const o=b.useRef(null);return b.useCallback(d=>{d&&t.onMount?.(d),s&&(d?s.mount(d):s.unmount());const f=l.current;if(typeof f==\"function\")if(d){const m=f(d);typeof m==\"function\"&&(o.current=m)}else o.current?(o.current(),o.current=null):f(d);else f&&(f.current=d)},[s])}const mw=b.createContext({});function sr(t){return t&&typeof t==\"object\"&&Object.prototype.hasOwnProperty.call(t,\"current\")}function w2(t,s,i,l,o,d){const{visualElement:f}=b.useContext(Dc),m=b.useContext(ow),p=b.useContext(Cc),y=b.useContext(Fh).reducedMotion,x=b.useRef(null);l=l||m.renderer,!x.current&&l&&(x.current=l(t,{visualState:s,parent:f,props:i,presenceContext:p,blockInitialAnimation:p?p.initial===!1:!1,reducedMotionConfig:y,isSVG:d}));const g=x.current,w=b.useContext(mw);g&&!g.projection&&o&&(g.type===\"html\"||g.type===\"svg\")&&S2(x.current,i,o,w);const S=b.useRef(!1);b.useInsertionEffect(()=>{g&&S.current&&g.update(i,p)});const T=i[wv],N=b.useRef(!!T&&!window.MotionHandoffIsComplete?.(T)&&window.MotionHasOptimisedAnimation?.(T));return Vb(()=>{g&&(S.current=!0,window.MotionIsMounted=!0,g.updateFeatures(),g.scheduleRenderMicrotask(),N.current&&g.animationState&&g.animationState.animateChanges())}),b.useEffect(()=>{g&&(!N.current&&g.animationState&&g.animationState.animateChanges(),N.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(T)}),N.current=!1),g.enteringChildren=void 0)}),g}function S2(t,s,i,l){const{layoutId:o,layout:d,drag:f,dragConstraints:m,layoutScroll:p,layoutRoot:y,layoutCrossfade:x}=s;t.projection=new i(t.latestValues,s[\"data-framer-portal-id\"]?void 0:pw(t.parent)),t.projection.setOptions({layoutId:o,layout:d,alwaysMeasureLayout:!!f||m&&sr(m),visualElement:t,animationType:typeof d==\"string\"?d:\"both\",initialPromotionConfig:l,crossfade:x,layoutScroll:p,layoutRoot:y})}function pw(t){if(t)return t.options.allowProjection!==!1?t.projection:pw(t.parent)}function ff(t,{forwardMotionProps:s=!1,type:i}={},l,o){l&&s2(l);const d=i?i===\"svg\":Kh(t),f=d?x2:y2;function m(y,x){let g;const w={...b.useContext(Fh),...y,layoutId:j2(y)},{isStatic:S}=w,T=o2(y),N=f(y,S);if(!S&&Bb){T2();const R=N2(w);g=R.MeasureLayout,T.visualElement=w2(t,N,w,o,R.ProjectionNode,d)}return c.jsxs(Dc.Provider,{value:T,children:[g&&T.visualElement?c.jsx(g,{visualElement:T.visualElement,...w}):null,m2(t,y,v2(N,T.visualElement,x),N,S,s,d)]})}m.displayName=`motion.${typeof t==\"string\"?t:`create(${t.displayName??t.name??\"\"})`}`;const p=b.forwardRef(m);return p[b2]=t,p}function j2({layoutId:t}){const s=b.useContext(xh).id;return s&&t!==void 0?s+\"-\"+t:t}function T2(t,s){b.useContext(ow).strict}function N2(t){const s=cw(),{drag:i,layout:l}=s;if(!i&&!l)return{};const o={...i,...l};return{MeasureLayout:i?.isEnabled(t)||l?.isEnabled(t)?o.MeasureLayout:void 0,ProjectionNode:o.ProjectionNode}}function C2(t,s){if(typeof Proxy>\"u\")return ff;const i=new Map,l=(d,f)=>ff(d,f,t,s),o=(d,f)=>l(d,f);return new Proxy(o,{get:(d,f)=>f===\"create\"?l:(i.has(f)||i.set(f,ff(f,void 0,t,s)),i.get(f))})}const A2=(t,s)=>s.isSVG??Kh(t)?new iA(s):new WC(s,{allowProjection:t!==b.Fragment});class E2 extends Na{constructor(s){super(s),s.animationState||(s.animationState=uA(s))}updateAnimationControlsSubscription(){const{animate:s}=this.node.getProps();Ac(s)&&(this.unmountControls=s.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:s}=this.node.getProps(),{animate:i}=this.node.prevProps||{};s!==i&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}}let D2=0;class k2 extends Na{constructor(){super(...arguments),this.id=D2++}update(){if(!this.node.presenceContext)return;const{isPresent:s,onExitComplete:i}=this.node.presenceContext,{isPresent:l}=this.node.prevPresenceContext||{};if(!this.node.animationState||s===l)return;const o=this.node.animationState.setActive(\"exit\",!s);i&&!s&&o.then(()=>{i(this.id)})}mount(){const{register:s,onExitComplete:i}=this.node.presenceContext||{};i&&i(this.id),s&&(this.unmount=s(this.id))}unmount(){}}const R2={animation:{Feature:E2},exit:{Feature:k2}};function jr(t){return{point:{x:t.pageX,y:t.pageY}}}const M2=t=>s=>qh(s)&&t(s,jr(s));function rr(t,s,i,l){return pr(t,s,M2(i),l)}const gw=({current:t})=>t?t.ownerDocument.defaultView:null,wx=(t,s)=>Math.abs(t-s);function O2(t,s){const i=wx(t.x,s.x),l=wx(t.y,s.y);return Math.sqrt(i**2+l**2)}const Sx=new Set([\"auto\",\"scroll\"]);class yw{constructor(s,i,{transformPagePoint:l,contextWindow:o=window,dragSnapToOrigin:d=!1,distanceThreshold:f=3,element:m}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=S=>{this.handleScroll(S.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const S=mf(this.lastMoveEventInfo,this.history),T=this.startEvent!==null,N=O2(S.offset,{x:0,y:0})>=this.distanceThreshold;if(!T&&!N)return;const{point:R}=S,{timestamp:D}=Bt;this.history.push({...R,timestamp:D});const{onStart:A,onMove:C}=this.handlers;T||(A&&A(this.lastMoveEvent,S),this.startEvent=this.lastMoveEvent),C&&C(this.lastMoveEvent,S)},this.handlePointerMove=(S,T)=>{this.lastMoveEvent=S,this.lastMoveEventInfo=hf(T,this.transformPagePoint),We.update(this.updatePoint,!0)},this.handlePointerUp=(S,T)=>{this.end();const{onEnd:N,onSessionEnd:R,resumeAnimation:D}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&D&&D(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const A=mf(S.type===\"pointercancel\"?this.lastMoveEventInfo:hf(T,this.transformPagePoint),this.history);this.startEvent&&N&&N(S,A),R&&R(S,A)},!qh(s))return;this.dragSnapToOrigin=d,this.handlers=i,this.transformPagePoint=l,this.distanceThreshold=f,this.contextWindow=o||window;const p=jr(s),y=hf(p,this.transformPagePoint),{point:x}=y,{timestamp:g}=Bt;this.history=[{...x,timestamp:g}];const{onSessionStart:w}=i;w&&w(s,mf(y,this.history)),this.removeListeners=vr(rr(this.contextWindow,\"pointermove\",this.handlePointerMove),rr(this.contextWindow,\"pointerup\",this.handlePointerUp),rr(this.contextWindow,\"pointercancel\",this.handlePointerUp)),m&&this.startScrollTracking(m)}startScrollTracking(s){let i=s.parentElement;for(;i;){const l=getComputedStyle(i);(Sx.has(l.overflowX)||Sx.has(l.overflowY))&&this.scrollPositions.set(i,{x:i.scrollLeft,y:i.scrollTop}),i=i.parentElement}this.scrollPositions.set(window,{x:window.scrollX,y:window.scrollY}),window.addEventListener(\"scroll\",this.onElementScroll,{capture:!0,passive:!0}),window.addEventListener(\"scroll\",this.onWindowScroll,{passive:!0}),this.removeScrollListeners=()=>{window.removeEventListener(\"scroll\",this.onElementScroll,{capture:!0}),window.removeEventListener(\"scroll\",this.onWindowScroll)}}handleScroll(s){const i=this.scrollPositions.get(s);if(!i)return;const l=s===window,o=l?{x:window.scrollX,y:window.scrollY}:{x:s.scrollLeft,y:s.scrollTop},d={x:o.x-i.x,y:o.y-i.y};d.x===0&&d.y===0||(l?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=d.x,this.lastMoveEventInfo.point.y+=d.y):this.history.length>0&&(this.history[0].x-=d.x,this.history[0].y-=d.y),this.scrollPositions.set(s,o),We.update(this.updatePoint,!0))}updateHandlers(s){this.handlers=s}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),va(this.updatePoint)}}function hf(t,s){return s?{point:s(t.point)}:t}function jx(t,s){return{x:t.x-s.x,y:t.y-s.y}}function mf({point:t},s){return{point:t,delta:jx(t,xw(s)),offset:jx(t,_2(s)),velocity:L2(s,.1)}}function _2(t){return t[0]}function xw(t){return t[t.length-1]}function L2(t,s){if(t.length<2)return{x:0,y:0};let i=t.length-1,l=null;const o=xw(t);for(;i>=0&&(l=t[i],!(o.timestamp-l.timestamp>Us(s)));)i--;if(!l)return{x:0,y:0};const d=Mn(o.timestamp-l.timestamp);if(d===0)return{x:0,y:0};const f={x:(o.x-l.x)/d,y:(o.y-l.y)/d};return f.x===1/0&&(f.x=0),f.y===1/0&&(f.y=0),f}function z2(t,{min:s,max:i},l){return s!==void 0&&ti&&(t=l?it(i,t,l.max):Math.min(t,i)),t}function Tx(t,s,i){return{min:s!==void 0?t.min+s:void 0,max:i!==void 0?t.max+i-(t.max-t.min):void 0}}function B2(t,{top:s,left:i,bottom:l,right:o}){return{x:Tx(t.x,i,o),y:Tx(t.y,s,l)}}function Nx(t,s){let i=s.min-t.min,l=s.max-t.max;return s.max-s.minl?i=dr(s.min,s.max-l,t.min):l>o&&(i=dr(t.min,t.max-o,s.min)),cs(0,1,i)}function P2(t,s){const i={};return s.min!==void 0&&(i.min=s.min-t.min),s.max!==void 0&&(i.max=s.max-t.min),i}const Xf=.35;function H2(t=Xf){return t===!1?t=0:t===!0&&(t=Xf),{x:Cx(t,\"left\",\"right\"),y:Cx(t,\"top\",\"bottom\")}}function Cx(t,s,i){return{min:Ax(t,s),max:Ax(t,i)}}function Ax(t,s){return typeof t==\"number\"?t:t[s]||0}const q2=new WeakMap;class I2{constructor(s){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=Tt(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=s}start(s,{snapToCursor:i=!1,distanceThreshold:l}={}){const{presenceContext:o}=this.visualElement;if(o&&o.isPresent===!1)return;const d=g=>{i?(this.stopAnimation(),this.snapToCursor(jr(g).point)):this.pauseAnimation()},f=(g,w)=>{this.stopAnimation();const{drag:S,dragPropagation:T,onDragStart:N}=this.getProps();if(S&&!T&&(this.openDragLock&&this.openDragLock(),this.openDragLock=kC(S),!this.openDragLock))return;this.latestPointerEvent=g,this.latestPanInfo=w,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Rn(D=>{let A=this.getAxisMotionValue(D).get()||0;if(rs.test(A)){const{projection:C}=this.visualElement;if(C&&C.layout){const B=C.layout.layoutBox[D];B&&(A=Jt(B)*(parseFloat(A)/100))}}this.originPoint[D]=A}),N&&We.postRender(()=>N(g,w)),Hf(this.visualElement,\"transform\");const{animationState:R}=this.visualElement;R&&R.setActive(\"whileDrag\",!0)},m=(g,w)=>{this.latestPointerEvent=g,this.latestPanInfo=w;const{dragPropagation:S,dragDirectionLock:T,onDirectionLock:N,onDrag:R}=this.getProps();if(!S&&!this.openDragLock)return;const{offset:D}=w;if(T&&this.currentDirection===null){this.currentDirection=$2(D),this.currentDirection!==null&&N&&N(this.currentDirection);return}this.updateAxis(\"x\",w.point,D),this.updateAxis(\"y\",w.point,D),this.visualElement.render(),R&&R(g,w)},p=(g,w)=>{this.latestPointerEvent=g,this.latestPanInfo=w,this.stop(g,w),this.latestPointerEvent=null,this.latestPanInfo=null},y=()=>Rn(g=>this.getAnimationState(g)===\"paused\"&&this.getAxisMotionValue(g).animation?.play()),{dragSnapToOrigin:x}=this.getProps();this.panSession=new yw(s,{onSessionStart:d,onStart:f,onMove:m,onSessionEnd:p,resumeAnimation:y},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:x,distanceThreshold:l,contextWindow:gw(this.visualElement),element:this.visualElement.current})}stop(s,i){const l=s||this.latestPointerEvent,o=i||this.latestPanInfo,d=this.isDragging;if(this.cancel(),!d||!o||!l)return;const{velocity:f}=o;this.startAnimation(f);const{onDragEnd:m}=this.getProps();m&&We.postRender(()=>m(l,o))}cancel(){this.isDragging=!1;const{projection:s,animationState:i}=this.visualElement;s&&(s.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:l}=this.getProps();!l&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),i&&i.setActive(\"whileDrag\",!1)}updateAxis(s,i,l){const{drag:o}=this.getProps();if(!l||!Go(s,o,this.currentDirection))return;const d=this.getAxisMotionValue(s);let f=this.originPoint[s]+l[s];this.constraints&&this.constraints[s]&&(f=z2(f,this.constraints[s],this.elastic[s])),d.set(f)}resolveConstraints(){const{dragConstraints:s,dragElastic:i}=this.getProps(),l=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,o=this.constraints;s&&sr(s)?this.constraints||(this.constraints=this.resolveRefConstraints()):s&&l?this.constraints=B2(l.layoutBox,s):this.constraints=!1,this.elastic=H2(i),o!==this.constraints&&l&&this.constraints&&!this.hasMutatedConstraints&&Rn(d=>{this.constraints!==!1&&this.getAxisMotionValue(d)&&(this.constraints[d]=P2(l.layoutBox[d],this.constraints[d]))})}resolveRefConstraints(){const{dragConstraints:s,onMeasureDragConstraints:i}=this.getProps();if(!s||!sr(s))return!1;const l=s.current,{projection:o}=this.visualElement;if(!o||!o.layout)return!1;const d=FC(l,o.root,this.visualElement.getTransformPagePoint());let f=V2(o.layout.layoutBox,d);if(i){const m=i($C(f));this.hasMutatedConstraints=!!m,m&&(f=Uv(m))}return f}startAnimation(s){const{drag:i,dragMomentum:l,dragElastic:o,dragTransition:d,dragSnapToOrigin:f,onDragTransitionEnd:m}=this.getProps(),p=this.constraints||{},y=Rn(x=>{if(!Go(x,i,this.currentDirection))return;let g=p&&p[x]||{};f&&(g={min:0,max:0});const w=o?200:1e6,S=o?40:1e7,T={type:\"inertia\",velocity:l?s[x]:0,bounceStiffness:w,bounceDamping:S,timeConstant:750,restDelta:1,restSpeed:10,...d,...g};return this.startAxisValueAnimation(x,T)});return Promise.all(y).then(m)}startAxisValueAnimation(s,i){const l=this.getAxisMotionValue(s);return Hf(this.visualElement,s),l.start(Bh(s,l,0,i,this.visualElement,!1))}stopAnimation(){Rn(s=>this.getAxisMotionValue(s).stop())}pauseAnimation(){Rn(s=>this.getAxisMotionValue(s).animation?.pause())}getAnimationState(s){return this.getAxisMotionValue(s).animation?.state}getAxisMotionValue(s){const i=`_drag${s.toUpperCase()}`,l=this.visualElement.getProps(),o=l[i];return o||this.visualElement.getValue(s,(l.initial?l.initial[s]:void 0)||0)}snapToCursor(s){Rn(i=>{const{drag:l}=this.getProps();if(!Go(i,l,this.currentDirection))return;const{projection:o}=this.visualElement,d=this.getAxisMotionValue(i);if(o&&o.layout){const{min:f,max:m}=o.layout.layoutBox[i],p=d.get()||0;d.set(s[i]-it(f,m,.5)+p)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:s,dragConstraints:i}=this.getProps(),{projection:l}=this.visualElement;if(!sr(i)||!l||!this.constraints)return;this.stopAnimation();const o={x:0,y:0};Rn(f=>{const m=this.getAxisMotionValue(f);if(m&&this.constraints!==!1){const p=m.get();o[f]=U2({min:p,max:p},this.constraints[f])}});const{transformTemplate:d}=this.visualElement.getProps();this.visualElement.current.style.transform=d?d({},\"\"):\"none\",l.root&&l.root.updateScroll(),l.updateLayout(),this.resolveConstraints(),Rn(f=>{if(!Go(f,s,null))return;const m=this.getAxisMotionValue(f),{min:p,max:y}=this.constraints[f];m.set(it(p,y,o[f]))})}addListeners(){if(!this.visualElement.current)return;q2.set(this.visualElement,this);const s=this.visualElement.current,i=rr(s,\"pointerdown\",p=>{const{drag:y,dragListener:x=!0}=this.getProps();y&&x&&!Ov(p.target)&&this.start(p)}),l=()=>{const{dragConstraints:p}=this.getProps();sr(p)&&p.current&&(this.constraints=this.resolveRefConstraints())},{projection:o}=this.visualElement,d=o.addEventListener(\"measure\",l);o&&!o.layout&&(o.root&&o.root.updateScroll(),o.updateLayout()),We.read(l);const f=pr(window,\"resize\",()=>this.scalePositionWithinConstraints()),m=o.addEventListener(\"didUpdate\",(({delta:p,hasLayoutChanged:y})=>{this.isDragging&&y&&(Rn(x=>{const g=this.getAxisMotionValue(x);g&&(this.originPoint[x]+=p[x].translate,g.set(g.get()+p[x].translate))}),this.visualElement.render())}));return()=>{f(),i(),d(),m&&m()}}getProps(){const s=this.visualElement.getProps(),{drag:i=!1,dragDirectionLock:l=!1,dragPropagation:o=!1,dragConstraints:d=!1,dragElastic:f=Xf,dragMomentum:m=!0}=s;return{...s,drag:i,dragDirectionLock:l,dragPropagation:o,dragConstraints:d,dragElastic:f,dragMomentum:m}}}function Go(t,s,i){return(s===!0||s===t)&&(i===null||i===t)}function $2(t,s=10){let i=null;return Math.abs(t.y)>s?i=\"y\":Math.abs(t.x)>s&&(i=\"x\"),i}class G2 extends Na{constructor(s){super(s),this.removeGroupControls=On,this.removeListeners=On,this.controls=new I2(s)}mount(){const{dragControls:s}=this.node.getProps();s&&(this.removeGroupControls=s.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||On}update(){const{dragControls:s}=this.node.getProps(),{dragControls:i}=this.node.prevProps||{};s!==i&&(this.removeGroupControls(),s&&(this.removeGroupControls=s.subscribe(this.controls)))}unmount(){this.removeGroupControls(),this.removeListeners()}}const Ex=t=>(s,i)=>{t&&We.postRender(()=>t(s,i))};class Y2 extends Na{constructor(){super(...arguments),this.removePointerDownListener=On}onPointerDown(s){this.session=new yw(s,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:gw(this.node)})}createPanHandlers(){const{onPanSessionStart:s,onPanStart:i,onPan:l,onPanEnd:o}=this.node.getProps();return{onSessionStart:Ex(s),onStart:Ex(i),onMove:l,onEnd:(d,f)=>{delete this.session,o&&We.postRender(()=>o(d,f))}}}mount(){this.removePointerDownListener=rr(this.node.current,\"pointerdown\",s=>this.onPointerDown(s))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}let pf=!1;class F2 extends b.Component{componentDidMount(){const{visualElement:s,layoutGroup:i,switchLayoutGroup:l,layoutId:o}=this.props,{projection:d}=s;d&&(i.group&&i.group.add(d),l&&l.register&&o&&l.register(d),pf&&d.root.didUpdate(),d.addEventListener(\"animationComplete\",()=>{this.safeToRemove()}),d.setOptions({...d.options,onExitComplete:()=>this.safeToRemove()})),tc.hasEverUpdated=!0}getSnapshotBeforeUpdate(s){const{layoutDependency:i,visualElement:l,drag:o,isPresent:d}=this.props,{projection:f}=l;return f&&(f.isPresent=d,pf=!0,o||s.layoutDependency!==i||i===void 0||s.isPresent!==d?f.willUpdate():this.safeToRemove(),s.isPresent!==d&&(d?f.promote():f.relegate()||We.postRender(()=>{const m=f.getStack();(!m||!m.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:s}=this.props.visualElement;s&&(s.root.didUpdate(),Hh.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:s,layoutGroup:i,switchLayoutGroup:l}=this.props,{projection:o}=s;pf=!0,o&&(o.scheduleCheckAfterUnmount(),i&&i.group&&i.group.remove(o),l&&l.deregister&&l.deregister(o))}safeToRemove(){const{safeToRemove:s}=this.props;s&&s()}render(){return null}}function bw(t){const[s,i]=rw(),l=b.useContext(xh);return c.jsx(F2,{...t,layoutGroup:l,switchLayoutGroup:b.useContext(mw),isPresent:s,safeToRemove:i})}const X2={pan:{Feature:Y2},drag:{Feature:G2,ProjectionNode:lw,MeasureLayout:bw}};function Dx(t,s,i){const{props:l}=t;t.animationState&&l.whileHover&&t.animationState.setActive(\"whileHover\",i===\"Start\");const o=\"onHover\"+i,d=l[o];d&&We.postRender(()=>d(s,jr(s)))}class K2 extends Na{mount(){const{current:s}=this.node;s&&(this.unmount=RC(s,(i,l)=>(Dx(this.node,l,\"Start\"),o=>Dx(this.node,o,\"End\"))))}unmount(){}}class Q2 extends Na{constructor(){super(...arguments),this.isActive=!1}onFocus(){let s=!1;try{s=this.node.current.matches(\":focus-visible\")}catch{s=!0}!s||!this.node.animationState||(this.node.animationState.setActive(\"whileFocus\",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive(\"whileFocus\",!1),this.isActive=!1)}mount(){this.unmount=vr(pr(this.node.current,\"focus\",()=>this.onFocus()),pr(this.node.current,\"blur\",()=>this.onBlur()))}unmount(){}}function kx(t,s,i){const{props:l}=t;if(t.current instanceof HTMLButtonElement&&t.current.disabled)return;t.animationState&&l.whileTap&&t.animationState.setActive(\"whileTap\",i===\"Start\");const o=\"onTap\"+(i===\"End\"?\"\":i),d=l[o];d&&We.postRender(()=>d(s,jr(s)))}class Z2 extends Na{mount(){const{current:s}=this.node;s&&(this.unmount=_C(s,(i,l)=>(kx(this.node,l,\"Start\"),(o,{success:d})=>kx(this.node,o,d?\"End\":\"Cancel\")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const Kf=new WeakMap,gf=new WeakMap,J2=t=>{const s=Kf.get(t.target);s&&s(t)},W2=t=>{t.forEach(J2)};function eE({root:t,...s}){const i=t||document;gf.has(i)||gf.set(i,{});const l=gf.get(i),o=JSON.stringify(s);return l[o]||(l[o]=new IntersectionObserver(W2,{root:t,...s})),l[o]}function tE(t,s,i){const l=eE(s);return Kf.set(t,i),l.observe(t),()=>{Kf.delete(t),l.unobserve(t)}}const nE={some:0,all:1};class sE extends Na{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:s={}}=this.node.getProps(),{root:i,margin:l,amount:o=\"some\",once:d}=s,f={root:i?i.current:void 0,rootMargin:l,threshold:typeof o==\"number\"?o:nE[o]},m=p=>{const{isIntersecting:y}=p;if(this.isInView===y||(this.isInView=y,d&&!y&&this.hasEnteredView))return;y&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive(\"whileInView\",y);const{onViewportEnter:x,onViewportLeave:g}=this.node.getProps(),w=y?x:g;w&&w(p)};return tE(this.node.current,f,m)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>\"u\")return;const{props:s,prevProps:i}=this.node;[\"amount\",\"margin\",\"root\"].some(aE(s,i))&&this.startObserver()}unmount(){}}function aE({viewport:t={}},{viewport:s={}}={}){return i=>t[i]!==s[i]}const iE={inView:{Feature:sE},tap:{Feature:Z2},focus:{Feature:Q2},hover:{Feature:K2}},lE={layout:{ProjectionNode:lw,MeasureLayout:bw}},rE={...R2,...iE,...X2,...lE},Le=C2(rE,A2),Qh=\"https://rateright-growth-production.up.railway.app\";async function Zh(){try{const{data:{session:t}}=await Nt.auth.getSession();return t?.access_token||null}catch{return null}}async function k(t,s={}){const i=`${Qh}${t}`,l=await Zh(),d={headers:{\"Content-Type\":\"application/json\",...l?{Authorization:`Bearer ${l}`}:{},...s.headers},...s},f=await fetch(i,d);if(!f.ok){const m=await f.json().catch(()=>({error:\"Request failed\"}));throw new Error(m.error||`HTTP ${f.status}`)}return f.status===204?null:f.json()}const Tr={list:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/leads${s?`?${s}`:\"\"}`)},get:t=>k(`/api/leads/${t}`),create:t=>k(\"/api/leads\",{method:\"POST\",body:JSON.stringify(t)}),update:(t,s)=>k(`/api/leads/${t}`,{method:\"PATCH\",body:JSON.stringify(s)}),updateLead:(t,s)=>k(`/api/leads/${t}`,{method:\"PATCH\",body:JSON.stringify(s)}),delete:t=>k(`/api/leads/${t}`,{method:\"DELETE\"}),archive:(t,s)=>k(`/api/leads/${t}/archive`,{method:\"POST\",body:JSON.stringify({reason:s})}),archiveLead:(t,s)=>k(`/api/leads/${t}/archive`,{method:\"POST\",body:JSON.stringify({reason:s})}),importFromSheet:()=>k(\"/api/leads/import-sheet\",{method:\"POST\"}),search:t=>k(`/api/leads/search?q=${encodeURIComponent(t)}`),claim:t=>k(`/api/leads/${t}/claim`,{method:\"POST\"}),release:t=>k(`/api/leads/${t}/release`,{method:\"POST\"}),assignments:()=>k(\"/api/leads/assignments\")},Jk={get:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/call-list${s?`?${s}`:\"\"}`)},stats:()=>k(\"/api/call-list/stats\"),activity:t=>k(`/api/call-list/activity${t?`?date=${t}`:\"\"}`)},Wk={send:t=>k(\"/api/sms/send\",{method:\"POST\",body:JSON.stringify(t)}),batch:t=>k(\"/api/sms/batch\",{method:\"POST\",body:JSON.stringify(t)}),preview:t=>k(\"/api/sms/preview\",{method:\"POST\",body:JSON.stringify(t)}),requestContact:t=>k(\"/api/sms/request-contact\",{method:\"POST\",body:JSON.stringify({leadId:t})}),getTemplates:t=>k(`/api/sms/templates${t?`?category=${t}`:\"\"}`),getTemplate:t=>k(`/api/sms/templates/${t}`),createTemplate:t=>k(\"/api/sms/templates\",{method:\"POST\",body:JSON.stringify(t)}),updateTemplate:(t,s)=>k(`/api/sms/templates/${t}`,{method:\"PUT\",body:JSON.stringify(s)}),deleteTemplate:t=>k(`/api/sms/templates/${t}`,{method:\"DELETE\"}),useTemplate:t=>k(`/api/sms/templates/${t}/use`,{method:\"POST\"}),getConversations:(t=\"all\")=>k(`/api/sms/conversations?filter=${t}`),getConversation:t=>k(`/api/sms/conversation/${t}`),markAsRead:t=>k(`/api/sms/conversation/${t}/read`,{method:\"PATCH\"}),handleConversation:(t,s=!0)=>k(`/api/sms/conversation/${t}/handle`,{method:\"PATCH\",body:JSON.stringify({handled:s})}),getPrioritized:(t=50)=>k(`/api/sms/conversations/prioritized?limit=${t}`),getAiSuggestion:(t,s)=>k(\"/api/sms/ai-suggest\",{method:\"POST\",body:JSON.stringify({leadId:t,lastMessage:s})}),getScheduled:t=>k(`/api/sms/scheduled${t?`?leadId=${t}`:\"\"}`),cancelScheduled:t=>k(`/api/sms/scheduled/${t}`,{method:\"DELETE\"}),getStats:(t=30)=>k(`/api/sms/stats?days=${t}`),sendBatch:t=>k(\"/api/sms/send-batch\",{method:\"POST\",body:JSON.stringify({messages:t})})},oE={log:t=>k(\"/api/calls/log\",{method:\"POST\",body:JSON.stringify(t)}),outcomes:()=>k(\"/api/calls/outcomes\"),getHistory:(t,s=1)=>k(`/api/calls/history/${t}?limit=${s}`)},eR={get:t=>k(`/api/dossier/${t}`),update:(t,s)=>k(`/api/dossier/${t}`,{method:\"PATCH\",body:JSON.stringify(s)}),addFact:(t,s,i=\"manual\")=>k(`/api/dossier/${t}/add-fact`,{method:\"POST\",body:JSON.stringify({fact:s,source:i})}),addCallSummary:(t,s)=>k(`/api/dossier/${t}/add-call-summary`,{method:\"POST\",body:JSON.stringify(s)}),addObjection:(t,s)=>k(`/api/dossier/${t}/add-objection`,{method:\"POST\",body:JSON.stringify(s)})},tR={getAll:()=>k(\"/api/dashboard/all\"),getStats:()=>k(\"/api/dashboard/stats\"),getWisdom:()=>k(\"/api/dashboard/wisdom\"),rateWisdom:(t,s)=>k(\"/api/dashboard/wisdom/rate\",{method:\"POST\",body:JSON.stringify({wisdomId:t,rating:s})}),getStrategy:()=>k(\"/api/dashboard/strategy\"),getPriorityAction:()=>k(\"/api/dashboard/priority-action\"),getSlipping:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/dashboard/slipping${s?`?${s}`:\"\"}`)}},nc={getToken:()=>k(\"/api/voice/token\"),status:()=>k(\"/api/voice/status\"),lookupCaller:t=>k(`/api/voice/lookup-caller?phone=${encodeURIComponent(t)}`)},cE={submit:t=>k(\"/api/bug-report\",{method:\"POST\",body:JSON.stringify(t)})},It={getIntelBrief:t=>k(`/api/ai/intel-brief/${t}`),getLiveIntel:t=>k(`/api/ai/live-intel/${t}`),postCallSummary:t=>k(\"/api/ai/post-call-summary\",{method:\"POST\",body:JSON.stringify(t)}),draftMessage:t=>k(\"/api/ai/draft-message\",{method:\"POST\",body:JSON.stringify(t)}),transcribe:async t=>{const s=new FormData;s.append(\"audio\",t,\"audio.webm\");const i=`${Qh}/api/ai/transcribe`,l=await Zh(),o=l?{Authorization:`Bearer ${l}`}:{},d=await fetch(i,{method:\"POST\",body:s,headers:o});if(!d.ok)throw new Error(\"Transcription failed\");return d.json()},voiceCommand:t=>k(\"/api/ai/voice-command\",{method:\"POST\",body:JSON.stringify(t)}),objectionResponse:t=>k(\"/api/ai/objection-response\",{method:\"POST\",body:JSON.stringify(t)}),getConversionProbability:t=>k(`/api/ai/conversion-probability/${t}`),weeklyInsights:()=>k(\"/api/ai/weekly-insights\",{method:\"POST\"}),cleanupNotes:t=>k(\"/api/ai/cleanup-notes\",{method:\"POST\",body:JSON.stringify(t)}),getInsights:()=>k(\"/api/ai/insights\"),getDeepgramCredentials:()=>k(\"/api/ai/deepgram-credentials\"),saveCopilotSession:t=>k(\"/api/ai/copilot-session\",{method:\"POST\",body:JSON.stringify(t)}),suggestionFeedback:t=>k(\"/api/ai/suggestion-feedback\",{method:\"POST\",body:JSON.stringify(t)}),getSimilarWins:t=>k(`/api/ai/similar-wins/${t}`),getEffectiveResponses:(t,s)=>{const i=s?`?trade=${encodeURIComponent(s)}`:\"\";return k(`/api/ai/effective-responses/${t}${i}`)},companyResearch:(t,s=!1)=>{const i=s?\"?refresh=true\":\"\";return k(`/api/ai/company-research/${encodeURIComponent(t)}${i}`)},personResearch:(t,s=!1)=>k(`/api/ai/person-research/${t}${s?\"?refresh=true\":\"\"}`),updateIntel:t=>k(\"/api/ai/update-intel\",{method:\"POST\",body:JSON.stringify(t)}),parseIntelVoiceNote:t=>k(\"/api/ai/parse-intel-voice\",{method:\"POST\",body:JSON.stringify(t)}),extractContractor:t=>k(\"/api/ai/extract-contractor\",{method:\"POST\",body:JSON.stringify(t)}),addContractorLead:t=>k(\"/api/ai/extract-contractor\",{method:\"POST\",body:JSON.stringify({...t,createLead:!0})}),extractLeadCorrections:t=>k(\"/api/ai/extract-lead-corrections\",{method:\"POST\",body:JSON.stringify(t)}),draftSimilar:t=>k(\"/api/ai/draft-similar\",{method:\"POST\",body:JSON.stringify(t)})},nR={status:()=>k(\"/api/sync/platform/status\"),stats:()=>k(\"/api/sync/platform/stats\"),syncAll:(t={})=>k(\"/api/sync/platform\",{method:\"POST\",body:JSON.stringify(t)}),syncRecent:()=>k(\"/api/sync/platform/recent\",{method:\"POST\"})},sR={getFunnel:()=>k(\"/api/activation/funnel\"),getLeadsAtStage:(t,s)=>{const i=new URLSearchParams({stage:t});return s&&i.append(\"type\",s),k(`/api/activation/leads-at-stage?${i}`)},getStuck:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/activation/stuck${s?`?${s}`:\"\"}`)},getRevenueAtRisk:()=>k(\"/api/activation/revenue-at-risk\"),getMetrics:(t=30)=>k(`/api/activation/metrics?days=${t}`),getTransitions:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/activation/stage-transitions${s?`?${s}`:\"\"}`)},analyze:()=>k(\"/api/activation/analyze\"),generateNudge:t=>k(\"/api/activation/nudge\",{method:\"POST\",body:JSON.stringify({leadId:t})}),bulkNudge:t=>k(\"/api/activation/bulk-nudge\",{method:\"POST\",body:JSON.stringify(t)}),addToCallList:t=>k(\"/api/activation/add-to-call-list\",{method:\"POST\",body:JSON.stringify(t)}),getActionScript:(t,s=\"contractor\")=>k(`/api/activation/action-script?stage=${t}&type=${s}`),getDropoffAnalysis:(t,s=\"contractor\")=>k(`/api/activation/dropoff-analysis?stage=${t}&type=${s}`),getNudgeTemplates:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/activation/nudge-templates${s?`?${s}`:\"\"}`)},createNudgeTemplate:t=>k(\"/api/activation/nudge-templates\",{method:\"POST\",body:JSON.stringify(t)}),updateNudgeTemplate:(t,s)=>k(`/api/activation/nudge-templates/${t}`,{method:\"PATCH\",body:JSON.stringify(s)}),deleteNudgeTemplate:t=>k(`/api/activation/nudge-templates/${t}`,{method:\"DELETE\"}),getJourney:t=>k(`/api/activation/journey/${t}`),getDiagnosis:t=>k(`/api/activation/diagnose/${t}`),getSimilarWins:(t,s=5)=>k(`/api/activation/similar-wins/${t}?limit=${s}`)},hc={list:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/scripts${s?`?${s}`:\"\"}`)},get:t=>k(`/api/scripts/${t}`),create:t=>k(\"/api/scripts\",{method:\"POST\",body:JSON.stringify(t)}),update:(t,s)=>k(`/api/scripts/${t}`,{method:\"PATCH\",body:JSON.stringify(s)}),delete:t=>k(`/api/scripts/${t}`,{method:\"DELETE\"}),startSession:(t,s)=>k(`/api/scripts/${t}/use`,{method:\"POST\",body:JSON.stringify({lead_id:s})}),endSession:(t,s)=>k(`/api/scripts/sessions/${t}`,{method:\"PATCH\",body:JSON.stringify(s)}),getForLead:t=>k(`/api/scripts/for-lead/${t}`),getAIRecommendation:t=>k(`/api/scripts/ai-recommend/${t}`),recordUsage:(t,s=!1)=>k(`/api/scripts/${t}/use`,{method:\"POST\",body:JSON.stringify({replied:s})}),getAnalytics:(t=30)=>k(`/api/scripts/analytics/overview?days=${t}`),getObjections:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/scripts/objections/list${s?`?${s}`:\"\"}`)},getObjection:t=>k(`/api/scripts/objections/${t}`),createObjection:t=>k(\"/api/scripts/objections\",{method:\"POST\",body:JSON.stringify(t)}),addObjectionResponse:(t,s)=>k(`/api/scripts/objections/${t}/response`,{method:\"POST\",body:JSON.stringify({response:s})}),getGuidelines:()=>k(\"/api/scripts/guidelines\"),updateGuidelines:t=>k(\"/api/scripts/guidelines\",{method:\"PUT\",body:JSON.stringify(t)}),getGuidelinesHistory:(t=20)=>k(`/api/scripts/guidelines/history?limit=${t}`),checkCompliance:(t,s={})=>k(\"/api/scripts/compliance/check\",{method:\"POST\",body:JSON.stringify({message:t,options:s})}),autoFix:t=>k(\"/api/scripts/compliance/auto-fix\",{method:\"POST\",body:JSON.stringify({message:t})}),validateScript:t=>k(`/api/scripts/compliance/validate/${t}`,{method:\"POST\"}),batchValidate:t=>k(\"/api/scripts/compliance/batch-validate\",{method:\"POST\",body:JSON.stringify({scriptIds:t})}),getComplianceStats:()=>k(\"/api/scripts/compliance/stats\"),getQueue:(t=\"pending\",s=20)=>k(`/api/scripts/compliance/queue?status=${t}&limit=${s}`),approveItem:t=>k(`/api/scripts/compliance/queue/${t}/approve`,{method:\"POST\"}),rejectItem:(t,s)=>k(`/api/scripts/compliance/queue/${t}/reject`,{method:\"POST\",body:JSON.stringify({reason:s})}),editItem:(t,s)=>k(`/api/scripts/compliance/queue/${t}/edit`,{method:\"POST\",body:JSON.stringify({final_content:s})})},aR={list:()=>k(\"/api/achievements\"),getUserAchievements:()=>k(\"/api/achievements/user\"),check:()=>k(\"/api/achievements/check\",{method:\"POST\"})},iR={getUser:()=>k(\"/api/xp/user\"),award:t=>k(\"/api/xp/award\",{method:\"POST\",body:JSON.stringify(t)}),getHistory:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/xp/history${s?`?${s}`:\"\"}`)},getLeaderboard:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/xp/leaderboard${s?`?${s}`:\"\"}`)}},Rx={list:t=>k(`/api/sequences${t?`?channel=${t}`:\"\"}`),get:t=>k(`/api/sequences/${t}`),enroll:(t,s)=>k(`/api/sequences/${t}/enroll`,{method:\"POST\",body:JSON.stringify({lead_ids:Array.isArray(s)?s:[s]})}),unenroll:(t,s)=>k(`/api/sequences/${t}/unenroll`,{method:\"POST\",body:JSON.stringify({lead_id:s})}),getActiveEnrollments:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/sequences/enrollments/active${s?`?${s}`:\"\"}`)},getLeadEnrollments:t=>k(`/api/sequences/enrollments/lead/${t}`),pauseEnrollment:(t,s)=>k(`/api/sequences/enrollments/${t}/pause`,{method:\"POST\",body:JSON.stringify({reason:s})}),resumeEnrollment:t=>k(`/api/sequences/enrollments/${t}/resume`,{method:\"POST\"}),skipStep:t=>k(`/api/sequences/enrollments/${t}/skip`,{method:\"POST\"}),sendNow:t=>k(`/api/sequences/enrollments/${t}/send-now`,{method:\"POST\"}),getOptOutStatus:t=>k(`/api/sequences/lead/${t}/opt-out`),setOptOut:(t,s)=>k(`/api/sequences/lead/${t}/opt-out`,{method:\"POST\",body:JSON.stringify({opted_out:s})}),bulkEnrollPreview:(t,s=100,i)=>{const l=new URLSearchParams({dry_run:\"true\",limit:s.toString()});return i&&l.set(\"source\",i),k(`/api/sequences/${t}/bulk-enroll?${l}`,{method:\"POST\"})},bulkEnroll:(t,s=100,i)=>{const l=new URLSearchParams({limit:s.toString()});return i&&l.set(\"source\",i),k(`/api/sequences/${t}/bulk-enroll?${l}`,{method:\"POST\"})}},lR={getScores:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/coaching/scores${s?`?${s}`:\"\"}`)},scoreCall:t=>k(\"/api/coaching/score\",{method:\"POST\",body:JSON.stringify(t)}),getTips:()=>k(\"/api/coaching/tips\"),getWeekly:()=>k(\"/api/coaching/weekly\"),getPatterns:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/coaching/patterns${s?`?${s}`:\"\"}`)}},rR={getTrends:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/analytics/trends${s?`?${s}`:\"\"}`)},getPatterns:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/analytics/patterns${s?`?${s}`:\"\"}`)},getFunnel:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/analytics/funnel${s?`?${s}`:\"\"}`)},getBestTimes:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/analytics/best-times${s?`?${s}`:\"\"}`)},getSources:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/analytics/sources${s?`?${s}`:\"\"}`)},savePattern:t=>k(\"/api/analytics/patterns\",{method:\"POST\",body:JSON.stringify(t)})},oR={list:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/ai-alerts${s?`?${s}`:\"\"}`)},create:t=>k(\"/api/ai-alerts\",{method:\"POST\",body:JSON.stringify(t)}),markRead:t=>k(`/api/ai-alerts/${t}/read`,{method:\"PATCH\"}),dismiss:t=>k(`/api/ai-alerts/${t}/dismiss`,{method:\"PATCH\"}),markAllRead:()=>k(\"/api/ai-alerts/read-all\",{method:\"POST\"}),generate:()=>k(\"/api/ai-alerts/generate\",{method:\"POST\"})},cR={getLeaderboard:(t=\"today\")=>k(`/api/battleground/leaderboard?period=${t}`),getUserStats:t=>k(`/api/battleground/leaderboard/${t}`),saveSnapshot:()=>k(\"/api/battleground/leaderboard/snapshot\",{method:\"POST\"}),getHallOfFame:()=>k(\"/api/battleground/hall-of-fame\"),checkRecord:(t,s,i,l,o)=>k(\"/api/battleground/hall-of-fame/check\",{method:\"POST\",body:JSON.stringify({recordType:t,userId:s,userName:i,value:l,details:o})}),getChallenges:()=>k(\"/api/battleground/challenges\"),updateChallengeProgress:(t,s=1)=>k(\"/api/battleground/challenges/progress\",{method:\"POST\",body:JSON.stringify({actionType:t,count:s})}),generateChallenges:()=>k(\"/api/battleground/challenges/generate\",{method:\"POST\"}),getTeamPulse:(t=20)=>k(`/api/battleground/pulse?limit=${t}`),createPulseEvent:t=>k(\"/api/battleground/pulse\",{method:\"POST\",body:JSON.stringify(t)}),getUserBadges:t=>k(`/api/battleground/badges/${t}`),getCurrentBadges:()=>k(\"/api/battleground/badges\"),awardWeeklyBadges:()=>k(\"/api/battleground/badges/award-weekly\",{method:\"POST\"}),updateStreakTier:(t,s)=>k(\"/api/battleground/streak/update\",{method:\"POST\",body:JSON.stringify({userId:t,streakDays:s})}),getActiveDuels:()=>k(\"/api/battleground/duels/active\"),getDuelHistory:(t=10)=>k(`/api/battleground/duels/history?limit=${t}`),getDuelOdds:(t,s)=>k(`/api/battleground/duels/odds?targetId=${t}&duelType=${s}`),createDuel:(t,s,i)=>k(\"/api/battleground/duels/challenge\",{method:\"POST\",body:JSON.stringify({targetId:t,duelType:s,stakeAmount:i})}),acceptDuel:t=>k(`/api/battleground/duels/${t}/accept`,{method:\"POST\"}),declineDuel:t=>k(`/api/battleground/duels/${t}/decline`,{method:\"POST\"}),getDuelScores:t=>k(`/api/battleground/duels/${t}/scores`),createChallenge:t=>k(\"/api/battleground/challenges\",{method:\"POST\",body:JSON.stringify(t)}),joinChallenge:t=>k(`/api/battleground/challenges/${t}/join`,{method:\"POST\"}),getChallengeDetails:t=>k(`/api/battleground/challenges/${t}`),getTeam:()=>k(\"/api/battleground/team\"),getCelebrations:(t=10)=>k(`/api/battleground/celebrations?limit=${t}`)},uR={getToday:()=>k(\"/api/playbook/today\"),send:(t,s,i)=>k(\"/api/playbook/send\",{method:\"POST\",body:JSON.stringify({leadId:t,messageId:s,messageText:i})}),getBulkPreview:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/playbook/bulk-preview${s?`?${s}`:\"\"}`)},bulkSend:(t,s,i={})=>k(\"/api/playbook/bulk-send\",{method:\"POST\",body:JSON.stringify({batchId:t,leadIds:s,edits:i})})},Mx={getRecordings:()=>k(\"/api/voicemail/recordings\"),createRecording:async t=>{const s=await Zh(),i=await fetch(`${Qh}/api/voicemail/recordings`,{method:\"POST\",headers:{Authorization:`Bearer ${s}`},body:t});if(!i.ok){const l=await i.json().catch(()=>({error:\"Upload failed\"}));throw new Error(l.error||\"Failed to upload\")}return i.json()},createRecordingFromUrl:t=>k(\"/api/voicemail/recordings\",{method:\"POST\",body:JSON.stringify(t)}),deleteRecording:t=>k(`/api/voicemail/recordings/${t}`,{method:\"DELETE\"}),setDefault:t=>k(`/api/voicemail/recordings/${t}/default`,{method:\"PATCH\"}),drop:(t,s,i)=>k(\"/api/voicemail/drop\",{method:\"POST\",body:JSON.stringify({callSid:t,recordingId:s,leadId:i})}),getStats:()=>k(\"/api/voicemail/drops/stats\")},dR={getDashboard:(t=\"week\")=>k(`/api/manager/dashboard?period=${t}`),getAnalytics:(t=\"week\")=>k(`/api/manager/analytics?period=${t}`),getRepDetail:(t,s=\"week\")=>k(`/api/manager/rep/${t}?period=${s}`)},fR={getDashboard:()=>k(\"/api/intelligence/dashboard\"),track:t=>k(\"/api/intelligence/track\",{method:\"POST\",body:JSON.stringify(t)}),trackBatch:t=>k(\"/api/intelligence/track-batch\",{method:\"POST\",body:JSON.stringify({events:t})}),getSuggestions:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/intelligence/suggestions${s?`?${s}`:\"\"}`)},updateSuggestionStatus:(t,s)=>k(`/api/intelligence/suggestions/${t}/status`,{method:\"PATCH\",body:JSON.stringify(s)}),getFriction:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/intelligence/friction${s?`?${s}`:\"\"}`)},getPageStats:(t=7)=>k(`/api/intelligence/page-stats?days=${t}`),getMetrics:(t,s,i)=>{const l=new URLSearchParams({start_date:t});return s&&l.append(\"end_date\",s),i&&l.append(\"metric_name\",i),k(`/api/intelligence/metrics?${l}`)}},Ox={getVapidKey:()=>k(\"/api/notifications/vapid-public-key\"),subscribe:t=>k(\"/api/notifications/subscribe\",{method:\"POST\",body:JSON.stringify({subscription:t})}),unsubscribe:(t=null)=>k(\"/api/notifications/unsubscribe\",{method:\"DELETE\",body:JSON.stringify({endpoint:t})}),getPreferences:()=>k(\"/api/notifications/preferences\"),updatePreferences:t=>k(\"/api/notifications/preferences\",{method:\"PUT\",body:JSON.stringify(t)}),test:()=>k(\"/api/notifications/test\",{method:\"POST\"}),getStatus:()=>k(\"/api/notifications/status\")},qn=[{id:\"opener\",label:\"Opener\",icon:\"👋\"},{id:\"discovery\",label:\"Discovery\",icon:\"🔍\"},{id:\"value_prop\",label:\"Value Prop\",icon:\"💎\"},{id:\"objections\",label:\"Objections\",icon:\"🛡️\"},{id:\"close\",label:\"Close\",icon:\"🎯\"}],uE={opener:{script:\"Hey, it's [your name] from RateRight. How's it going?\",tip:\"Be warm and conversational. Match their energy.\",alternatives:[\"Hi [name], this is [you] from RateRight - got a quick minute?\",\"G'day [name], [you] here from RateRight. How's business?\"]},discovery:{script:\"What's your biggest challenge finding workers right now?\",tip:\"Listen more than you talk. Take mental notes.\",alternatives:[\"How are you currently sourcing your workers?\",\"What trades are hardest to find good people for?\",\"How many workers do you typically need on a job?\"]},value_prop:{script:\"We connect you with pre-vetted workers at just 9.9% - no lock-in contracts.\",tip:\"Focus on their pain points. Make it about them.\",alternatives:[\"Most of our contractors find workers within 24 hours.\",\"You only pay when they work - no upfront fees.\",\"Every worker is vetted with references and qualifications checked.\"]},objections:{script:\"I hear you. What would need to change for this to make sense?\",tip:\"Don't argue. Acknowledge and redirect.\",alternatives:[\"That's a fair point. Here's how other contractors handle that...\",\"I understand. Can I ask what you're comparing us to?\",\"Makes sense. What if we could address that concern?\"]},close:{script:\"Let me get you set up - it takes about 2 minutes. What's your email?\",tip:\"Assume the sale. Be confident.\",alternatives:[\"When's your next job starting? Let's get you ready.\",\"I'll send you the link now - what email should I use?\",\"Want me to walk you through it while we're on the phone?\"]}};function dE({lead:t,duration:s,onHangUp:i,onMute:l,isMuted:o,onMarkHot:d}){const[f,m]=b.useState(0),[p,y]=b.useState(null),[x,g]=b.useState(null),[w,S]=b.useState(!1),[T,N]=b.useState([]),[R,D]=b.useState(null),[A,C]=b.useState([]);b.useEffect(()=>{t?.id&&(B(),_())},[t?.id]);const B=async()=>{try{const $=await hc.getRecommendation(t.id);$?.script&&y($.script)}catch{console.log(\"Using default scripts\")}},_=async()=>{try{const $=await It.getIntelBrief(t.id);if($){D($);const W=[];$.openingLine&&W.push({type:\"opener\",text:$.openingLine}),$.talkingPoints?.length&&$.talkingPoints.forEach(se=>W.push({type:\"point\",text:se})),$.similarWins?.length&&W.push({type:\"win\",text:`Similar win: ${$.similarWins[0].name} - \"${$.similarWins[0].whatWorked}\"`}),$.company?.sales_angle&&W.push({type:\"angle\",text:$.company.sales_angle}),C(W)}}catch{console.log(\"Intel not available\")}},F=$=>{const W=uE[$];if(!p)return W;switch($){case\"opener\":return{...W,script:p.opening||W.script};case\"discovery\":return{...W,script:p.discovery_questions?.[0]?.question||W.script,alternatives:p.discovery_questions?.slice(1,4).map(se=>se.question)||W.alternatives};case\"value_prop\":return{...W,script:p.value_props?.[0]?.prop||W.script,alternatives:p.value_props?.slice(1,4).map(se=>se.prop)||W.alternatives};case\"objections\":return W;case\"close\":return{...W,script:p.closing_techniques?.[0]?.script||W.script,alternatives:p.closing_techniques?.slice(1,4).map(se=>se.script)||W.alternatives};default:return W}},P=async($,W)=>{await navigator.clipboard.writeText($),g(W),setTimeout(()=>g(null),500)},H=()=>{f{m($)},X=()=>{S(!0),d?.()},te=$=>{const W=Math.floor($/60),se=$%60;return`${W}:${se.toString().padStart(2,\"0\")}`},Y=`${t?.first_name||\"\"} ${t?.last_name||\"\"}`.trim()||\"Unknown\";return c.jsxs(\"div\",{className:\"fixed inset-0 z-[60] bg-slate-900 flex flex-col\",children:[c.jsxs(\"div\",{className:\"bg-slate-800 px-4 py-3 flex items-center justify-between safe-area-top\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-3\",children:[c.jsx(\"div\",{className:\"w-10 h-10 rounded-full bg-slate-700 flex items-center justify-center\",children:c.jsx(cr,{className:\"w-5 h-5 text-slate-400\"})}),c.jsxs(\"div\",{children:[c.jsx(\"h2\",{className:\"font-bold text-white\",children:Y}),c.jsxs(\"div\",{className:\"flex items-center gap-2\",children:[c.jsx(\"div\",{className:\"w-2 h-2 rounded-full bg-green-500 animate-pulse\"}),c.jsx(\"span\",{className:\"text-green-400 font-mono text-sm\",children:te(s)})]})]})]}),c.jsx(\"button\",{onClick:X,disabled:w,className:`p-2 rounded-full ${w?\"bg-amber-500 text-white\":\"bg-slate-700 text-slate-400\"}`,children:c.jsx(nl,{className:\"w-5 h-5\"})})]}),c.jsx(\"div\",{className:\"bg-slate-800/50 px-4 py-3 flex items-center gap-2\",children:qn.map(($,W)=>c.jsxs(\"button\",{onClick:()=>z(W),className:`flex-1 py-2 rounded-lg text-center transition-all ${T.includes(W)?\"bg-emerald-600 text-white\":W===f?\"bg-violet-600 text-white ring-2 ring-violet-400\":\"bg-slate-700/50 text-slate-400\"}`,children:[c.jsx(\"span\",{className:\"text-lg\",children:$.icon}),c.jsx(\"p\",{className:\"text-[10px] font-bold mt-0.5\",children:T.includes(W)?\"✓\":$.label})]},$.id))}),c.jsx(\"div\",{className:\"flex-1 overflow-y-auto pb-40\",children:c.jsxs(\"div\",{className:\"p-4 space-y-4\",children:[A.length>0&&c.jsxs(\"div\",{className:\"bg-blue-500/10 border border-blue-500/20 rounded-xl p-3\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-2 mb-2\",children:[c.jsx(ac,{className:\"w-4 h-4 text-blue-400\"}),c.jsx(\"span\",{className:\"text-xs font-bold text-blue-400 uppercase\",children:\"Intel & Talking Points\"})]}),c.jsx(\"div\",{className:\"space-y-2\",children:A.slice(0,4).map(($,W)=>c.jsxs(\"div\",{className:\"flex items-start gap-2\",children:[c.jsx(\"span\",{className:\"text-blue-400 mt-0.5\",children:$.type===\"opener\"?\"💬\":$.type===\"win\"?\"🏆\":$.type===\"angle\"?\"🎯\":\"•\"}),c.jsx(\"p\",{className:\"text-blue-200/80 text-sm\",children:$.text})]},W))})]}),R?.company?.name&&c.jsxs(\"div\",{className:\"flex items-center gap-2 px-1\",children:[c.jsx(jc,{className:\"w-4 h-4 text-slate-500\"}),c.jsxs(\"span\",{className:\"text-slate-400 text-sm\",children:[R.company.name,R.company.industry&&` • ${R.company.industry}`,R.company.size&&` • ${R.company.size}`]})]}),c.jsxs(\"div\",{className:\"text-center py-2\",children:[c.jsx(\"span\",{className:\"text-3xl\",children:qn[f].icon}),c.jsx(\"h3\",{className:\"text-xl font-bold text-white mt-2\",children:qn[f].label}),c.jsxs(\"p\",{className:\"text-slate-400 text-sm\",children:[\"Stage \",f+1,\" of \",qn.length]})]}),c.jsxs(\"div\",{className:\"bg-gradient-to-br from-violet-600/20 to-purple-600/10 border border-violet-500/30 rounded-2xl p-4\",children:[c.jsxs(\"div\",{className:\"flex items-start justify-between mb-2\",children:[c.jsx(\"span\",{className:\"text-xs font-bold text-violet-400 uppercase\",children:\"Say This\"}),c.jsx(\"button\",{onClick:()=>P(F(qn[f].id).script,\"main\"),className:\"p-2 -m-2 text-slate-400 hover:text-white\",children:x===\"main\"?c.jsx(ba,{className:\"w-4 h-4 text-green-400\"}):c.jsx(Cf,{className:\"w-4 h-4\"})})]}),c.jsxs(\"p\",{className:\"text-white text-lg leading-relaxed\",children:['\"',F(qn[f].id).script,'\"']})]}),c.jsxs(\"div\",{className:\"bg-amber-500/10 border border-amber-500/20 rounded-xl px-4 py-3\",children:[c.jsx(\"span\",{className:\"text-xs font-bold text-amber-400 uppercase\",children:\"💡 Tip\"}),c.jsx(\"p\",{className:\"text-amber-200/80 text-sm mt-1\",children:F(qn[f].id).tip})]}),c.jsxs(\"div\",{children:[c.jsx(\"h4\",{className:\"text-sm font-bold text-slate-400 mb-2 px-1\",children:\"Or Try These:\"}),c.jsx(\"div\",{className:\"space-y-2\",children:F(qn[f].id).alternatives.map(($,W)=>c.jsxs(\"div\",{className:\"bg-slate-800/50 border border-slate-700 rounded-xl p-3 flex items-start gap-3\",children:[c.jsxs(\"p\",{className:\"text-slate-300 text-sm flex-1\",children:['\"',$,'\"']}),c.jsx(\"button\",{onClick:()=>P($,`alt-${W}`),className:\"p-1 text-slate-500 hover:text-white flex-shrink-0\",children:x===`alt-${W}`?c.jsx(ba,{className:\"w-4 h-4 text-green-400\"}):c.jsx(Cf,{className:\"w-4 h-4\"})})]},W))})]}),f(i&&s?W(s):se(),()=>{ie()}),[]);const W=ee=>{console.log(\"[TwilioCall] Attaching to inbound call\"),X.current=ee,p(\"in-progress\"),Y.current=Date.now(),I();const ge=ee.parameters?.CallSid||null;console.log(\"[TwilioCall] Inbound call CallSid:\",ge),d?.(ge),ee.on(\"disconnect\",()=>{const Ee=Y.current?Math.floor((Date.now()-Y.current)/1e3):0;console.log(\"[TwilioCall] Inbound call disconnected, duration:\",Ee),p(\"ended\"),K(),$.current||($.current=!0,setTimeout(()=>{o?.(Ee)},500))}),ee.on(\"error\",Ee=>{console.error(\"[TwilioCall] Inbound call error:\",Ee),T(Ee.message),p(\"ended\"),K()})},se=async()=>{try{const{token:ee}=await nc.getToken(),ge=new Cb(ee,{logLevel:\"debug\",codecPreferences:[\"opus\",\"pcmu\"],enableRingingState:!0,edge:\"ashburn\"});ge.on(\"error\",Ee=>{console.error(\"Twilio Device error:\",Ee),T(Ee.message),p(\"ended\")}),z.current=ge,p(\"ready\"),O()}catch(ee){console.error(\"Failed to initialize Twilio:\",ee),T(ee.message),p(\"ended\")}},O=async()=>{if(z.current){if(!t?.phone){T(\"No phone number for this lead\"),p(\"ended\");return}try{p(\"connecting\");const ee=await z.current.connect({params:{To:t.phone,leadId:t?.id}});X.current=ee,ee.on(\"ringing\",()=>{p(\"ringing\")}),ee.on(\"accept\",()=>{p(\"in-progress\"),Y.current=Date.now(),I();const ge=ee.parameters?.CallSid||null;console.log(\"[TwilioCall] Call connected, CallSid:\",ge),d?.(ge)}),ee.on(\"disconnect\",()=>{const ge=Y.current?Math.floor((Date.now()-Y.current)/1e3):0;p(\"ended\"),K(),$.current||($.current=!0,setTimeout(()=>{o?.(ge)},500))}),ee.on(\"cancel\",()=>{p(\"ended\"),K(),$.current||($.current=!0,o?.(0))}),ee.on(\"error\",ge=>{console.error(\"Call error:\",ge),T(ge.message),p(\"ended\"),K()})}catch(ee){console.error(\"Failed to make call:\",ee),T(ee.message),p(\"ended\")}}},I=()=>{te.current=setInterval(()=>{Y.current&&x(Math.floor((Date.now()-Y.current)/1e3))},1e3)},K=()=>{te.current&&(clearInterval(te.current),te.current=null)},ie=()=>{K(),!i&&X.current&&X.current.disconnect(),!i&&z.current&&z.current.destroy()},oe=()=>{X.current?X.current.disconnect():l?.()},xe=()=>{X.current&&(g?X.current.mute(!1):X.current.mute(!0),w(!g))},Te=async()=>{if(!(D.length>0)){B(!0);try{const ee=await Mx.getRecordings();A(ee||[])}catch(ee){console.error(\"Failed to load VM recordings:\",ee)}finally{B(!1)}}},ae=async ee=>{const ge=X.current?.parameters?.CallSid;if(!ge){console.error(\"No CallSid available\");return}F(!0);try{await Mx.drop(ge,ee.id,t?.id),H(!0),R(!1)}catch(Ee){console.error(\"VM drop failed:\",Ee),T(\"Failed to drop voicemail\")}finally{F(!1)}},ce=ee=>{const ge=Math.floor(ee/60),Ee=ee%60;return`${ge}:${Ee.toString().padStart(2,\"0\")}`},ne=()=>{switch(m){case\"initializing\":return\"Setting up...\";case\"ready\":return\"Starting call...\";case\"connecting\":return\"Connecting...\";case\"ringing\":return\"Ringing...\";case\"in-progress\":return ce(y);case\"ended\":return\"Call ended\";default:return\"\"}},ue=()=>{switch(m){case\"ringing\":return\"text-amber-400\";case\"in-progress\":return\"text-green-400\";case\"ended\":return\"text-slate-400\";default:return\"text-blue-400\"}},de=`${t?.first_name||\"\"} ${t?.last_name||\"\"}`.trim()||\"Unknown\";return m===\"in-progress\"&&t?c.jsx(dE,{lead:t,duration:y,isMuted:g,onMute:xe,onHangUp:oe,onMarkHot:()=>{console.log(\"Marked hot during call\")}}):c.jsxs(Le.div,{initial:{y:100,opacity:0},animate:{y:0,opacity:1},exit:{y:100,opacity:0},className:\"fixed bottom-0 inset-x-0 z-[60] bg-gradient-to-t from-slate-900 via-slate-900 to-slate-900/95 rounded-t-3xl shadow-2xl pb-safe\",children:[c.jsxs(\"div\",{className:\"px-4 pt-4 pb-2 flex items-center gap-3\",children:[c.jsx(\"div\",{className:\"w-12 h-12 rounded-full bg-slate-700 flex items-center justify-center flex-shrink-0\",children:c.jsx(cr,{className:\"w-6 h-6 text-slate-400\"})}),c.jsxs(\"div\",{className:\"flex-1 min-w-0\",children:[c.jsx(\"h2\",{className:\"text-lg font-bold text-white truncate\",children:de}),c.jsxs(\"div\",{className:\"flex items-center gap-2\",children:[c.jsx(\"span\",{className:`text-sm font-medium ${ue()}`,children:ne()}),m===\"in-progress\"&&f&&c.jsxs(\"div\",{className:\"flex items-center gap-1\",children:[c.jsx(Yj,{className:\"w-3 h-3 text-emerald-400 animate-pulse\"}),c.jsx(\"span\",{className:\"text-xs text-emerald-400\",children:\"Recording\"})]})]})]}),m===\"ringing\"&&c.jsx(\"div\",{className:\"relative w-8 h-8\",children:c.jsx(Le.div,{className:\"absolute inset-0 rounded-full border-2 border-amber-400/50\",animate:{scale:[1,1.5],opacity:[.5,0]},transition:{duration:1.5,repeat:1/0}})})]}),S&&c.jsx(\"p\",{className:\"text-red-400 text-sm text-center px-4 pb-2\",children:S}),c.jsx(\"div\",{className:\"px-4 pb-6 pt-2\",children:m!==\"ended\"?c.jsxs(\"div\",{className:\"flex items-center justify-center gap-6\",children:[c.jsx(\"button\",{onClick:xe,disabled:m!==\"in-progress\",title:g?\"Unmute\":\"Mute\",className:`w-14 h-14 rounded-full flex items-center justify-center transition-colors ${g?\"bg-red-500 text-white\":\"bg-slate-700 text-white disabled:opacity-50\"}`,children:g?c.jsx(Tc,{className:\"w-6 h-6\"}):c.jsx(ti,{className:\"w-6 h-6\"})}),c.jsx(\"button\",{onClick:oe,title:\"End call\",className:\"w-16 h-16 rounded-full bg-red-500 text-white flex items-center justify-center shadow-lg shadow-red-500/30 active:scale-95 transition-transform\",children:c.jsx(ur,{className:\"w-8 h-8\"})}),c.jsx(\"button\",{onClick:()=>{R(!0),Te()},disabled:m===\"initializing\"||m===\"connecting\"||P,title:P?\"Voicemail dropped!\":\"Drop voicemail\",className:`w-14 h-14 rounded-full flex items-center justify-center transition-colors ${P?\"bg-green-600 text-white\":\"bg-amber-600 text-white disabled:opacity-50\"}`,children:P?c.jsx(ba,{className:\"w-6 h-6\"}):c.jsx(ey,{className:\"w-6 h-6\"})})]}):c.jsx(\"button\",{onClick:()=>{$.current||($.current=!0,o?.(y))},className:\"w-full py-4 bg-blue-600 text-white rounded-xl font-bold text-lg\",children:\"Continue\"})}),c.jsx(si,{children:N&&c.jsx(Le.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:\"fixed inset-0 z-[70] bg-black/60 flex items-end justify-center\",onClick:()=>R(!1),children:c.jsxs(Le.div,{initial:{y:\"100%\"},animate:{y:0},exit:{y:\"100%\"},className:\"w-full max-w-md bg-slate-800 rounded-t-2xl p-4 pb-8\",onClick:ee=>ee.stopPropagation(),children:[c.jsxs(\"div\",{className:\"flex items-center justify-between mb-4\",children:[c.jsx(\"h3\",{className:\"text-lg font-bold text-white\",children:\"Drop Voicemail\"}),c.jsx(\"button\",{onClick:()=>R(!1),className:\"w-8 h-8 rounded-full bg-slate-700 flex items-center justify-center\",children:c.jsx(Gt,{className:\"w-5 h-5 text-slate-400\"})})]}),C?c.jsx(\"div\",{className:\"flex items-center justify-center py-8\",children:c.jsx(_n,{className:\"w-6 h-6 text-blue-400 animate-spin\"})}):D.length===0?c.jsxs(\"div\",{className:\"text-center py-8 text-slate-400\",children:[\"No voicemail recordings yet.\",c.jsx(\"br\",{}),c.jsx(\"span\",{className:\"text-sm\",children:\"Add recordings in Settings → Voicemail\"})]}):c.jsx(\"div\",{className:\"space-y-2 max-h-64 overflow-y-auto\",children:D.map(ee=>c.jsxs(\"button\",{onClick:()=>ae(ee),disabled:_,className:\"w-full p-3 bg-slate-700/50 rounded-xl flex items-center gap-3 hover:bg-slate-700 transition-colors disabled:opacity-50\",children:[c.jsx(\"div\",{className:\"w-10 h-10 rounded-full bg-amber-600/20 flex items-center justify-center flex-shrink-0\",children:c.jsx(ey,{className:\"w-5 h-5 text-amber-400\"})}),c.jsxs(\"div\",{className:\"flex-1 text-left\",children:[c.jsx(\"p\",{className:\"text-white font-medium\",children:ee.name}),ee.description&&c.jsx(\"p\",{className:\"text-slate-400 text-sm truncate\",children:ee.description})]}),ee.is_default&&c.jsx(\"span\",{className:\"text-xs bg-blue-600/30 text-blue-400 px-2 py-0.5 rounded\",children:\"Default\"}),_&&c.jsx(_n,{className:\"w-4 h-4 text-blue-400 animate-spin\"})]},ee.id))}),c.jsx(\"p\",{className:\"text-xs text-slate-500 text-center mt-4\",children:\"Selecting a voicemail will play it to the recipient and end the call\"})]})})})]})}function hE({candidate:t,sourceLeadId:s,onAdd:i,onDismiss:l}){const{user:o}=br(),[d,f]=b.useState(!1),m=async()=>{f(!0);try{const x=await It.addContractorLead({sourceLeadId:s,companyName:t.company,projectName:t.project,userEmail:o?.email||\"unknown\"});x.success&&x.lead_id?i(x.lead_id,t):alert(\"Failed to create lead\")}catch(x){console.error(\"Add contractor error:\",x),alert(\"Failed to create lead: \"+x.message)}finally{f(!1)}},p=`${t.first_name||\"\"} ${t.last_name||\"\"}`.trim(),y=Math.round((t.confidence||.5)*100);return c.jsxs(\"div\",{className:\"fixed inset-0 z-50 flex items-center justify-center p-4\",children:[c.jsx(\"div\",{className:\"absolute inset-0 bg-black/60 backdrop-blur-sm\",onClick:l}),c.jsxs(\"div\",{className:\"relative w-full max-w-sm bg-white rounded-2xl shadow-2xl overflow-hidden animate-fade-in\",children:[c.jsx(\"div\",{className:\"bg-gradient-to-r from-amber-500 to-orange-500 px-5 py-4\",children:c.jsxs(\"div\",{className:\"flex items-center justify-between\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-3\",children:[c.jsx(\"div\",{className:\"w-10 h-10 bg-white/20 rounded-xl flex items-center justify-center\",children:c.jsx(nl,{className:\"w-5 h-5 text-white\"})}),c.jsxs(\"div\",{children:[c.jsx(\"h2\",{className:\"text-white font-bold text-lg\",children:\"Contractor Found!\"}),c.jsxs(\"p\",{className:\"text-white/80 text-sm\",children:[y,\"% confidence\"]})]})]}),c.jsx(\"button\",{onClick:l,className:\"w-8 h-8 bg-white/20 rounded-full flex items-center justify-center\",children:c.jsx(Gt,{className:\"w-4 h-4 text-white\"})})]})}),c.jsxs(\"div\",{className:\"p-5\",children:[c.jsxs(\"div\",{className:\"text-center mb-4\",children:[c.jsx(\"h3\",{className:\"text-xl font-bold text-slate-900\",children:p||\"Unknown\"}),t.job_title&&c.jsxs(\"div\",{className:\"flex items-center justify-center gap-2 mt-1 text-slate-600\",children:[c.jsx(Eb,{className:\"w-4 h-4\"}),c.jsx(\"span\",{children:t.job_title})]})]}),c.jsxs(\"div\",{className:\"bg-slate-50 rounded-xl p-4 mb-4 space-y-2\",children:[t.company&&c.jsxs(\"div\",{className:\"flex items-center gap-2 text-slate-700\",children:[c.jsx(Fj,{className:\"w-4 h-4 text-slate-400\"}),c.jsx(\"span\",{className:\"font-semibold\",children:t.company})]}),t.project&&c.jsxs(\"div\",{className:\"flex items-center gap-2 text-slate-600\",children:[c.jsx(ty,{className:\"w-4 h-4 text-slate-400\"}),c.jsxs(\"span\",{children:[t.project,\" Project\"]})]}),t.location&&c.jsxs(\"div\",{className:\"flex items-center gap-2 text-slate-500 text-sm\",children:[c.jsx(ty,{className:\"w-4 h-4 text-slate-400\"}),c.jsx(\"span\",{children:t.location})]})]}),t.linkedin_url&&c.jsxs(\"a\",{href:t.linkedin_url,target:\"_blank\",rel:\"noopener noreferrer\",className:\"flex items-center justify-center gap-2 mb-4 py-2 bg-[#0A66C2] text-white rounded-lg text-sm font-medium hover:bg-[#004182]\",children:[c.jsx(Xj,{className:\"w-4 h-4\"}),\"View LinkedIn Profile\"]}),t.source_worker&&c.jsx(\"div\",{className:\"bg-amber-50 rounded-lg p-3 mb-4 border border-amber-200\",children:c.jsxs(\"p\",{className:\"text-sm text-amber-800\",children:[c.jsx(\"span\",{className:\"font-semibold\",children:\"Source:\"}),\" Worker intel from \",t.source_worker]})}),c.jsxs(\"div\",{className:\"flex gap-3\",children:[c.jsx(\"button\",{onClick:l,className:\"flex-1 py-3 bg-slate-100 text-slate-700 rounded-xl font-semibold hover:bg-slate-200\",children:\"Dismiss\"}),c.jsxs(\"button\",{onClick:m,disabled:d,className:\"flex-1 py-3 bg-gradient-to-r from-green-500 to-emerald-500 text-white rounded-xl font-semibold flex items-center justify-center gap-2 hover:from-green-600 hover:to-emerald-600 disabled:opacity-50\",children:[d?c.jsx(_n,{className:\"w-5 h-5 animate-spin\"}):c.jsx(Af,{className:\"w-5 h-5\"}),\"Add as Lead\"]})]})]})]})]})}function mE(t){const s=Math.floor(t/60),i=t%60;return`${s}:${i.toString().padStart(2,\"0\")}`}const pE={opener:\"Opener\",discovery:\"Discovery\",value_prop:\"Value Props\",objections:\"Objections\",close:\"Close\"},_x=[\"opener\",\"discovery\",\"value_prop\",\"objections\",\"close\"];function gE({duration:t,leadName:s,isListening:i,onMinimize:l}){return c.jsxs(\"div\",{className:\"bg-slate-800 px-4 py-3 flex items-center justify-between safe-area-top\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-3\",children:[c.jsx(\"div\",{className:`w-2.5 h-2.5 rounded-full ${i?\"bg-red-500 animate-pulse\":\"bg-slate-500\"}`}),c.jsx(\"span\",{className:\"text-white font-mono text-lg font-bold tabular-nums\",children:mE(t)})]}),c.jsx(\"span\",{className:\"text-white font-medium truncate max-w-32\",children:s||\"Unknown\"}),c.jsx(\"button\",{onClick:l,className:\"p-2 -mr-2 text-slate-400 hover:text-white\",children:c.jsx(Kj,{className:\"w-5 h-5\"})})]})}function yE({intel:t}){const s=t?.personal_intel?.conversation_starters||t?.person?.conversation_starters||[],i=t?.personal_intel?.interest_news||t?.interest_news,l=[];return i?.items?.length>0&&i.items.slice(0,2).forEach(o=>{l.push({type:\"news\",text:o.talking_point||o.headline,source:o.topic||o.source,emoji:o.topic?.toLowerCase().includes(\"liverpool\")?\"⚽\":o.topic?.toLowerCase().includes(\"f1\")?\"🏎️\":o.topic?.toLowerCase().includes(\"gaa\")?\"🏐\":\"📰\"})}),s.slice(0,3-l.length).forEach(o=>{l.push({type:\"starter\",text:typeof o==\"string\"?o:o.text,source:typeof o==\"string\"?null:o.topic,emoji:\"💬\"})}),l.length===0?null:c.jsxs(\"div\",{className:\"bg-gradient-to-r from-blue-500/20 to-purple-500/20 border border-blue-500/30 rounded-2xl p-3\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-2 mb-2\",children:[c.jsx(\"span\",{className:\"text-sm\",children:\"🎯\"}),c.jsx(\"span\",{className:\"text-xs font-bold text-blue-300 uppercase tracking-wide\",children:\"Ice Breakers\"})]}),c.jsx(\"div\",{className:\"space-y-2\",children:l.map((o,d)=>c.jsxs(\"div\",{className:\"flex items-start gap-2\",children:[c.jsx(\"span\",{className:\"text-base flex-shrink-0\",children:o.emoji}),c.jsxs(\"div\",{className:\"flex-1 min-w-0\",children:[c.jsxs(\"p\",{className:\"text-white text-sm leading-snug\",children:['\"',o.text,'\"']}),o.source&&c.jsx(\"p\",{className:\"text-slate-400 text-xs mt-0.5\",children:o.source})]})]},d))})]})}function xE({stage:t,script:s,openingLine:i}){const[l,o]=b.useState(!1),d=_x.indexOf(t),m=(()=>{if(!s)return i||\"Hey, it's [your name] from RateRight. How's it going?\";switch(t){case\"opener\":return s.opening||i||\"Hey, it's [your name] from RateRight. How's it going?\";case\"discovery\":return s.discovery_questions?.[0]?.question||\"What's your biggest challenge finding workers right now?\";case\"value_prop\":return s.value_props?.[0]?.prop||\"We connect you with pre-vetted workers at just 9.9% - no lock-in contracts.\";case\"objections\":return\"Listen for concerns and address them directly.\";case\"close\":return s.closing_techniques?.[0]?.script||\"Let me get you set up - it takes about 2 minutes. What's your email?\";default:return s.opening||\"Start the conversation...\"}})(),p=async()=>{await navigator.clipboard.writeText(m),o(!0),setTimeout(()=>o(!1),500)};return c.jsxs(\"div\",{className:\"bg-slate-800/50 border border-slate-700 rounded-2xl p-4 relative\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-2 mb-3\",children:[c.jsx(\"span\",{className:\"text-xs font-bold text-violet-400 uppercase tracking-wide\",children:pE[t]||\"Script\"}),c.jsx(\"div\",{className:\"flex-1 h-px bg-slate-700\"}),c.jsxs(\"span\",{className:\"text-xs text-slate-500\",children:[d+1,\"/\",_x.length]})]}),c.jsxs(\"p\",{className:\"text-white text-base leading-relaxed pr-8\",children:['\"',m,'\"']}),c.jsx(\"button\",{onClick:p,className:\"absolute top-4 right-4 p-2 text-slate-400 hover:text-white transition-colors\",children:l?c.jsx(ba,{className:\"w-4 h-4 text-green-400\"}):c.jsx(Cf,{className:\"w-4 h-4\"})})]})}function bE({company:t,person:s,onExpand:i}){if(!t&&!s)return null;const l=[];return t?.name&&l.push(t.name),t?.industry&&l.push(t.industry),t?.size?l.push(t.size):s?.job_title&&l.push(s.job_title),l.length===0?null:c.jsxs(\"button\",{onClick:i,className:\"bg-slate-800/30 border border-slate-700/50 rounded-xl px-4 py-2.5 flex items-center gap-3 w-full text-left\",children:[c.jsx(jc,{className:\"w-4 h-4 text-blue-400 flex-shrink-0\"}),c.jsx(\"span\",{className:\"text-sm text-slate-300 truncate flex-1\",children:l.join(\" • \")}),c.jsx(Ab,{className:\"w-4 h-4 text-slate-500 flex-shrink-0\"})]})}function vE({type:t,trigger:s,suggestion:i,onDismiss:l}){const o=t===\"buying_signal\";return c.jsxs(Le.div,{initial:{y:100,opacity:0,scale:.95},animate:{y:0,opacity:1,scale:1},exit:{y:100,opacity:0,scale:.95},transition:{type:\"spring\",damping:25,stiffness:300},className:`w-full rounded-2xl overflow-hidden relative ${o?\"bg-gradient-to-br from-emerald-500/20 to-green-500/10 border border-emerald-500/50\":\"bg-gradient-to-br from-amber-500/20 to-orange-500/10 border border-amber-500/50\"}`,children:[c.jsxs(\"div\",{className:`px-4 py-2 flex items-center gap-2 ${o?\"bg-emerald-500/30\":\"bg-amber-500/30\"}`,children:[c.jsx(\"span\",{className:\"text-lg\",children:o?\"🔥\":\"⚠️\"}),c.jsx(\"span\",{className:`font-bold text-sm uppercase tracking-wide ${o?\"text-emerald-300\":\"text-amber-300\"}`,children:o?\"BUYING SIGNAL\":i?.objection_type===\"price\"?\"PRICE CONCERN\":i?.objection_type===\"timing\"?\"TIMING ISSUE\":i?.objection_type===\"trust\"?\"TRUST CONCERN\":\"OBJECTION\"})]}),c.jsx(\"div\",{className:\"px-4 pt-3 pb-2\",children:c.jsxs(\"p\",{className:\"text-slate-400 text-sm italic truncate\",children:['\"',s,'\"']})}),c.jsxs(\"div\",{className:\"px-4 pb-3\",children:[c.jsxs(\"p\",{className:\"text-white text-lg font-medium leading-snug\",children:['\"',i?.response||\"Handle this naturally...\",'\"']}),c.jsx(\"p\",{className:\"text-slate-500 text-xs italic mt-1\",children:\"Adapt in your own voice\"})]}),i?.key_point&&c.jsx(\"div\",{className:\"px-4 pb-2\",children:c.jsxs(\"div\",{className:`inline-flex items-center gap-1.5 rounded-full px-3 py-1 ${o?\"bg-emerald-500/20 border border-emerald-500/30\":\"bg-amber-500/20 border border-amber-500/30\"}`,children:[c.jsx(ac,{className:`w-3 h-3 ${o?\"text-emerald-400\":\"text-amber-400\"}`}),c.jsx(\"span\",{className:`text-xs font-medium ${o?\"text-emerald-300\":\"text-amber-300\"}`,children:i.key_point})]})}),i?.follow_up_question&&c.jsxs(\"div\",{className:\"px-4 pb-4 flex items-start gap-2\",children:[c.jsx(Qj,{className:`w-4 h-4 mt-0.5 flex-shrink-0 ${o?\"text-emerald-400\":\"text-amber-400\"}`}),c.jsxs(\"div\",{children:[c.jsx(\"span\",{className:`text-xs font-bold ${o?\"text-emerald-400\":\"text-amber-400\"}`,children:\"THEN ASK:\"}),c.jsxs(\"span\",{className:\"text-slate-300 text-sm ml-1\",children:['\"',i.follow_up_question,'\"']})]})]}),c.jsx(\"button\",{onClick:l,className:\"absolute top-2 right-2 p-2 text-slate-400 hover:text-white\",children:c.jsx(Gt,{className:\"w-4 h-4\"})})]})}function wE({isMuted:t,onMute:s,onMarkHot:i,onEndCall:l,markedHot:o}){return c.jsx(\"div\",{className:\"bg-slate-800 border-t border-slate-700 px-4 py-4 safe-area-bottom\",children:c.jsxs(\"div\",{className:\"flex items-center justify-center gap-4\",children:[c.jsx(\"button\",{onClick:s,className:`w-14 h-14 rounded-full flex items-center justify-center transition-colors ${t?\"bg-red-500 text-white\":\"bg-slate-700 text-slate-300\"}`,children:t?c.jsx(Tc,{className:\"w-6 h-6\"}):c.jsx(ti,{className:\"w-6 h-6\"})}),c.jsx(\"button\",{onClick:i,disabled:o,className:`w-14 h-14 rounded-full flex items-center justify-center transition-colors ${o?\"bg-amber-500 text-white\":\"bg-amber-500/20 border border-amber-500/50 text-amber-400\"}`,children:c.jsx(nl,{className:\"w-6 h-6\"})}),c.jsxs(\"button\",{onClick:l,className:\"px-8 py-4 rounded-full bg-red-500 text-white font-bold flex items-center gap-2 active:scale-95 transition-transform\",children:[c.jsx(ur,{className:\"w-5 h-5\"}),c.jsx(\"span\",{children:\"End\"})]})]})})}function SE({intel:t,leadName:s,onClose:i}){return t?c.jsx(Le.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:\"fixed inset-0 z-[60] bg-black/70 flex items-end\",onClick:i,children:c.jsx(Le.div,{initial:{y:\"100%\"},animate:{y:0},exit:{y:\"100%\"},transition:{type:\"spring\",damping:25,stiffness:300},className:\"bg-slate-800 rounded-t-3xl w-full max-h-[70vh] overflow-y-auto\",onClick:l=>l.stopPropagation(),children:c.jsxs(\"div\",{className:\"p-4\",children:[c.jsx(\"div\",{className:\"w-12 h-1 bg-slate-600 rounded-full mx-auto mb-4\"}),c.jsxs(\"h3\",{className:\"text-lg font-bold text-white mb-4\",children:[\"Intel: \",s]}),t.company&&c.jsxs(\"div\",{className:\"bg-slate-700/50 rounded-xl p-4 mb-3\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-2 mb-2\",children:[c.jsx(jc,{className:\"w-4 h-4 text-blue-400\"}),c.jsx(\"span\",{className:\"text-sm font-semibold text-white\",children:t.company.name})]}),c.jsxs(\"div\",{className:\"flex flex-wrap gap-2\",children:[t.company.industry&&c.jsx(\"span\",{className:\"px-2 py-1 bg-blue-500/20 text-blue-300 text-xs rounded\",children:t.company.industry}),t.company.size&&c.jsx(\"span\",{className:\"px-2 py-1 bg-slate-600 text-slate-300 text-xs rounded\",children:t.company.size}),t.company.location&&c.jsx(\"span\",{className:\"px-2 py-1 bg-slate-600 text-slate-300 text-xs rounded\",children:t.company.location})]}),t.company.sales_angle&&c.jsxs(\"div\",{className:\"mt-3 p-2 bg-emerald-500/10 border border-emerald-500/30 rounded-lg\",children:[c.jsx(\"span\",{className:\"text-xs text-emerald-400 font-semibold\",children:\"SALES ANGLE: \"}),c.jsx(\"span\",{className:\"text-sm text-slate-300\",children:t.company.sales_angle})]})]}),t.person?.job_title&&c.jsxs(\"div\",{className:\"bg-slate-700/50 rounded-xl p-4 mb-3\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-2 mb-1\",children:[c.jsx(\"span\",{className:\"text-lg\",children:\"👤\"}),c.jsx(\"span\",{className:\"text-sm font-semibold text-white\",children:s})]}),c.jsx(\"p\",{className:\"text-slate-400 text-sm\",children:t.person.job_title}),t.person.years_at_company&&c.jsxs(\"p\",{className:\"text-slate-500 text-xs mt-1\",children:[t.person.years_at_company,\" years at company\"]})]}),t.similar_wins?.length>0&&c.jsxs(\"div\",{className:\"bg-slate-700/50 rounded-xl p-4\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-2 mb-2\",children:[c.jsx(\"span\",{className:\"text-lg\",children:\"🏆\"}),c.jsx(\"span\",{className:\"text-sm font-semibold text-amber-400\",children:\"Similar Wins\"})]}),c.jsx(\"div\",{className:\"space-y-2\",children:t.similar_wins.slice(0,3).map((l,o)=>c.jsxs(\"div\",{className:\"text-sm\",children:[c.jsx(\"span\",{className:\"text-slate-300\",children:l.name}),l.key_factor&&c.jsxs(\"span\",{className:\"text-slate-500\",children:[' — \"',l.key_factor,'\"']})]},o))})]})]})})}):null}function jE({lead:t,duration:s,isListening:i,isMuted:l,script:o,scriptStage:d,intel:f,latestSuggestion:m,openingLine:p,error:y,onMinimize:x,onMute:g,onMarkHot:w,onEndCall:S,onDismissSuggestion:T}){const[N,R]=b.useState(!1),[D,A]=b.useState(!1),C=()=>{A(!0),w?.()};return c.jsxs(\"div\",{className:\"fixed inset-0 z-50 bg-slate-900 flex flex-col\",children:[c.jsx(gE,{duration:s,leadName:t?.first_name,isListening:i,onMinimize:x}),c.jsxs(\"div\",{className:\"flex-1 flex flex-col p-4 gap-3 overflow-hidden\",children:[c.jsx(yE,{intel:f}),c.jsx(xE,{stage:d,script:o,openingLine:p}),c.jsx(bE,{company:f?.company,person:f?.person,onExpand:()=>R(!0)}),y&&c.jsxs(\"div\",{className:\"bg-red-500/10 border border-red-500/30 rounded-xl px-4 py-2 flex items-center gap-2\",children:[c.jsx(Db,{className:\"w-4 h-4 text-red-400 flex-shrink-0\"}),c.jsx(\"span\",{className:\"text-red-400 text-sm\",children:y})]}),c.jsxs(\"div\",{className:\"flex-1 flex items-center justify-center px-2\",children:[c.jsx(si,{mode:\"wait\",children:m&&c.jsx(vE,{type:m.type,trigger:m.trigger,suggestion:m.suggestion,onDismiss:T},m.timestamp)}),!m&&i&&c.jsx(\"div\",{className:\"text-center\",children:c.jsxs(\"div\",{className:\"flex items-center justify-center gap-2 text-slate-500\",children:[c.jsx(\"div\",{className:\"w-2 h-2 bg-violet-500 rounded-full animate-pulse\"}),c.jsx(\"span\",{className:\"text-sm\",children:\"Listening for signals...\"})]})})]})]}),c.jsx(wE,{isMuted:l,onMute:g,onMarkHot:C,onEndCall:S,markedHot:D}),c.jsx(si,{children:N&&c.jsx(SE,{intel:f,leadName:t?.first_name,onClose:()=>R(!1)})})]})}const TE={discovery:[\"tell me about\",\"what do you\",\"how many\",\"when did\",\"how long\",\"what's your\",\"who is\"],value_prop:[\"we can help\",\"our platform\",\"rateright\",\"workers available\",\"save you\",\"percentage\"],objections:[\"price\",\"cost\",\"expensive\",\"not sure\",\"competitor\",\"think about\"],close:[\"next step\",\"sign up\",\"get started\",\"send you\",\"email\",\"ready to\"]},NE=[\"expensive\",\"cost\",\"price\",\"too much\",\"can't afford\",\"not sure\",\"think about\",\"need to check\",\"competitor\",\"already have\",\"not interested\",\"busy\",\"later\",\"call back\",\"happy with\",\"current provider\",\"contract\",\"locked in\"],CE=[/works?\\s+for\\s+(.+?)\\s+on\\s+(?:the\\s+)?(.+?)(?:\\s+project|\\s+site|\\s+job|[.!?]|$)/i,/(?:i|we)\\s+work\\s+for\\s+(.+?)(?:\\s+on|\\s+at|[.!?]|$)/i,/(?:my|the)\\s+boss\\s+(?:is\\s+)?(?:at\\s+)?(.+?)(?:[.!?]|$)/i,/working\\s+(?:for|with)\\s+(.+?)(?:\\s+on|\\s+at|[.!?]|$)/i],AE=[/^hey system[,:]?\\s*(.+)/i,/^command[,:]?\\s*(.+)/i,/^note[,:]?\\s*(.+)/i,/^mark\\s+(hot|warm|cold|engaged|converted|lost)/i,/^callback\\s+(.+)/i,/^skip$/i],EE=[\"when can you start\",\"when can we start\",\"how do i sign up\",\"how do we sign up\",\"what's the next step\",\"what is the next step\",\"next steps\",\"let's do it\",\"lets do it\",\"i'm ready\",\"we're ready\",\"sign me up\",\"sign us up\",\"send me the details\",\"send the details\",\"send me a quote\",\"need workers asap\",\"need someone today\",\"starting monday\",\"starting next week\",\"that's reasonable\",\"sounds fair\",\"cheaper than\",\"better than\",\"have a job starting\",\"got a project\",\"need workers\",\"how many workers\",\"do you have electricians\",\"do you have carpenters\"],Lx={\"next step\":{type:\"closing\",response:\"Great question! I can get you set up right now. I just need your email to send the signup link.\",followUp:\"What's the best email to send that to?\",keyPoint:\"They're ready to move forward!\"},sign:{type:\"closing\",response:\"Perfect! Let me get you started. The signup takes about 2 minutes.\",followUp:\"Do you have your ABN handy?\",keyPoint:\"Close the deal now!\"},\"when can\":{type:\"urgency\",response:\"We can have workers available within 24-48 hours once you're set up.\",followUp:\"What trade do you need first?\",keyPoint:\"Match their urgency!\"},\"need workers\":{type:\"qualification\",response:\"We've got a great pool of pre-vetted workers. Most contractors find someone within a day.\",followUp:\"How many workers are you looking for?\",keyPoint:\"Qualify the opportunity!\"},cheaper:{type:\"value\",response:\"Yes, at 9.9% we're typically 30-50% less than traditional agencies, with no lock-in contracts.\",followUp:\"Would you like me to calculate the savings based on your team size?\",keyPoint:\"Reinforce the value!\"},default:{type:\"interest\",response:\"I can hear you're interested! Let me show you how easy it is to get started.\",followUp:\"What's your biggest pain point with finding workers right now?\",keyPoint:\"Keep the momentum!\"}};function DE({lead:t,onClose:s,onEnd:i}){const{scriptSessionId:l,setScriptSessionId:o,preloadedIntel:d}=kc(),[f,m]=b.useState(!1),[p,y]=b.useState(\"\"),[x,g]=b.useState(\"\"),[w,S]=b.useState([]),[T,N]=b.useState(!1),[R,D]=b.useState(null),[A,C]=b.useState(0),[B,_]=b.useState(!1),[F,P]=b.useState(null),[H,z]=b.useState([]),[X,te]=b.useState(\"\"),[Y,$]=b.useState(!0),[W,se]=b.useState(!0),[O,I]=b.useState({}),[K,ie]=b.useState(null),[oe,xe]=b.useState(null),[Te,ae]=b.useState(null),[ce,ne]=b.useState(!1),ue=b.useRef(!1),[de,ee]=b.useState(null),[ge,Ee]=b.useState(!1),[wt,me]=b.useState(null),ze=b.useRef(null),[st,on]=b.useState(!0),[Wt,ms]=b.useState(null),[Yn,Yt]=b.useState(\"opener\"),[li,Ea]=b.useState([]),[Vt,Fn]=b.useState(null),[St,$s]=b.useState(null),[Xn,Da]=b.useState(d),[ps,ka]=b.useState(null),[Ln,ri]=b.useState(!1),cn=b.useRef(!1);b.useEffect(()=>{d&&!cn.current&&(console.log(\"[LiveCopilot] Syncing preloadedIntel from context:\",Object.keys(d)),Da(d),cn.current=!0)},[d]);const Ft=b.useRef(null),ft=b.useRef(null),Ut=b.useRef(null),Ct=b.useRef(null);b.useRef(!1);const Gs=b.useRef(null),Kn=b.useRef(\"\"),un=b.useRef([]),gs=b.useRef(0),Qn=b.useRef(!1),Pt=b.useRef(0),Xt=b.useRef(null),ve=b.useRef(null);b.useEffect(()=>{if(St){const re=setTimeout(()=>{$s(null)},5e3);return()=>clearTimeout(re)}},[St]),b.useEffect(()=>((async()=>(await Fe(),await ht(),await At(),await Zn(),console.log(\"[LiveCopilot] Starting real-time transcription\"),Rt()))(),()=>{xs(),Ut.current&&clearInterval(Ut.current)}),[]),b.useEffect(()=>{Ct.current?.scrollIntoView({behavior:\"smooth\"})},[w]),b.useEffect(()=>(Ut.current=setInterval(()=>{C(re=>(gs.current=re+1,re+1))},1e3),()=>clearInterval(Ut.current)),[]),b.useEffect(()=>{Kn.current=p},[p]),b.useEffect(()=>{un.current=w},[w]),b.useEffect(()=>()=>{!Qn.current&&t?.id&&Kn.current&&(console.log(\"[LiveCopilot] Saving session on unmount, transcript length:\",Kn.current.length),Qn.current=!0,It.saveCopilotSession({leadId:t.id,transcript:Kn.current,suggestions:un.current,duration:gs.current}).catch(re=>console.error(\"[LiveCopilot] Failed to save session on unmount:\",re)))},[t?.id]);const Fe=async()=>{try{const re=await It.getDeepgramCredentials();if(console.log(\"[LiveCopilot] Deepgram configured:\",re.configured),re.configured){const Ae=`wss://${window.location.host.includes(\"rateright.com.au\")?\"rateright-growth-production.up.railway.app\":window.location.host}/api/transcribe/ws`;console.log(\"[LiveCopilot] Using backend proxy:\",Ae),P({configured:!0,proxyUrl:Ae}),Gs.current={configured:!0,proxyUrl:Ae}}else console.log(\"[LiveCopilot] Deepgram not configured, will use Web Speech API fallback\"),Gs.current=null}catch(re){console.log(\"[LiveCopilot] Live transcription not available:\",re.message),Gs.current=null}},ht=async()=>{if(!t?.id){se(!1);return}try{if(t.ai_intel_brief?.talking_points){z(t.ai_intel_brief.talking_points||[]),te(t.ai_intel_brief.opening_line||\"\"),se(!1);return}const re=await It.getIntelBrief(t.id);re.brief&&(z(re.brief.talking_points||[]),te(re.brief.opening_line||\"\"));try{const je=await It.getSimilarWins(t.id);je?.wins?.length>0&&Fn(je.wins[0])}catch(je){console.log(\"Could not load similar wins:\",je)}}catch(re){console.log(\"Could not load intel brief:\",re)}finally{se(!1)}},At=async()=>{if(cn.current||Xn){console.log(\"[LiveCopilot] Intel already loaded, skipping API fetch\");return}if(d){console.log(\"[LiveCopilot] Preloaded intel exists, useEffect will sync\");return}if(t?.id)try{console.log(\"[LiveCopilot] No preloaded intel, fetching from API...\");const re=await It.getLiveIntel(t.id);re.success&&!cn.current&&Da(re)}catch(re){console.log(\"Could not load intel:\",re)}},Zn=async()=>{if(t?.id)try{const re=await hc.getForLead(t.id);if(re.recommendedScripts?.length>0){const je=await hc.get(re.recommendedScripts[0].id);ka(je.script),ms(je.script?.id)}}catch(re){console.log(\"Could not load script:\",re)}},Xe=b.useCallback(re=>{const je=re.toLowerCase();for(const[ye,Ae]of Object.entries(TE))for(const _e of Ae)if(je.includes(_e)){const et=[\"opener\",\"discovery\",\"value_prop\",\"objections\",\"close\"],Be=et.indexOf(Yn);if(et.indexOf(ye)>Be)return Ea(Bn=>[...new Set([...Bn,Yn])]),Yt(ye),!0}return!1},[Yn]),Ht=re=>{const je=Math.floor(re/60),ye=re%60;return`${je}:${ye.toString().padStart(2,\"0\")}`},Jn=b.useCallback(re=>{const je=re.toLowerCase();return NE.some(ye=>je.includes(ye))},[]),Dt=b.useCallback(re=>{const je=re.toLowerCase();for(const ye of EE)if(je.includes(ye)){if(ze.current===ye)return null;ze.current=ye;let Ae=Lx.default;for(const[_e,et]of Object.entries(Lx))if(_e!==\"default\"&&ye.includes(_e)){Ae=et;break}return{trigger:ye,...Ae}}return null},[]),kt=b.useCallback(re=>{me(re);const je={type:\"buying_signal\",trigger:re.trigger,suggestion:{signal_type:re.type,response:re.response,follow_up_question:re.followUp,key_point:re.keyPoint},timestamp:Date.now()};S(ye=>[...ye,je]),$s(je),setTimeout(()=>me(null),5e3)},[]),ys=async re=>{if(!T){N(!0);try{const je=await It.objectionResponse({objection:re,leadId:t?.id});if(je.success){const ye={type:\"objection\",trigger:re,suggestion:je.suggestion,timestamp:Date.now()};S(Ae=>[...Ae,ye]),$s(ye)}}catch(je){console.error(\"Failed to get objection response:\",je)}finally{N(!1)}}},qt=t?.metadata?.lead_type===\"worker\",oi=b.useCallback(re=>{if(!(!qt||ue.current||ce))for(const je of CE){const ye=re.match(je);if(ye){const Ae=ye[1]?.trim(),_e=ye[2]?.trim();if(Ae&&Ae.length>2){console.log(`[ContractorDetection] Found: ${Ae}, project: ${_e||\"N/A\"}`),Dr(Ae,_e);return}}}},[qt,ce]),Dr=async(re,je)=>{if(!(ue.current||ce)){ue.current=!0,ne(!0);try{const ye=await It.extractContractor({sourceLeadId:t?.id,companyName:re,projectName:je});ye.success&&ye.found&&ye.candidate&&ae(ye.candidate)}catch(ye){console.error(\"Contractor search error:\",ye)}finally{ne(!1)}}},Wn=(re,je)=>{ae(null),console.log(\"Contractor lead created:\",re,je)},mt=b.useCallback(async re=>{if(ge)return!1;const je=re.toLowerCase().trim();for(const ye of AE){const Ae=je.match(ye);if(Ae){let _e=Ae[1]||je;(ye.source.includes(\"mark\")||ye.source.includes(\"skip\"))&&(_e=je),console.log(\"[VoiceCommand] Detected:\",_e),Ee(!0);try{const et=await It.voiceCommand({transcript:_e,leadId:t?.id});et.success&&(ee({confirmation:et.parsed.confirmation,intent:et.parsed.intent}),setTimeout(()=>ee(null),3e3))}catch(et){console.error(\"Voice command error:\",et)}finally{Ee(!1)}return!0}}return!1},[t?.id,ge]),Rt=async()=>{try{console.log(\"[LiveCopilot] Requesting microphone access...\");const re=await navigator.mediaDevices.getUserMedia({audio:!0});ve.current=re,Pt.current=0,console.log(\"[LiveCopilot] Microphone access granted\");const je=Gs.current||F;if(console.log(\"[LiveCopilot] Using backend proxy:\",!!(je?.configured&&je?.proxyUrl)),je?.configured&&je?.proxyUrl){console.log(\"[LiveCopilot] Connecting to backend proxy...\"),console.log(\"[LiveCopilot] Proxy URL:\",je.proxyUrl),xe(\"deepgram\");const ye=new WebSocket(je.proxyUrl);console.log(\"[LiveCopilot] WebSocket created, readyState:\",ye.readyState);const Ae=setTimeout(()=>{console.error(\"[LiveCopilot] Connection timeout! readyState:\",ye.readyState),ye.readyState!==WebSocket.OPEN&&(D(\"Connection timeout - trying fallback...\"),ye.close())},1e4);ye.onopen=()=>{clearTimeout(Ae),console.log(\"[LiveCopilot] Connected to transcription proxy!\"),Pt.current=0,m(!0),D(null)},ye.onmessage=Qe=>{const Ke=JSON.parse(Qe.data);if(Ke.error){console.error(\"[LiveCopilot] Proxy error:\",Ke.error),D(Ke.error);return}if(Ke.type===\"Metadata\"&&console.log(\"[LiveCopilot] Transcription metadata:\",Ke),Ke.channel?.alternatives?.[0]?.transcript){console.log(\"[LiveCopilot] Transcript:\",Ke.channel.alternatives[0].transcript,\"is_final:\",Ke.is_final);const Kt=Ke.channel.alternatives[0].transcript;if(Ke.is_final){y(Fs=>Fs+\" \"+Kt),g(\"\"),mt(Kt),Xe(Kt);const Ys=Dt(Kt);Ys?kt(Ys):Jn(Kt)&&ys(Kt),qt&&oi(Kt)}else g(Kt)}},ye.onerror=Qe=>{clearTimeout(Ae),console.error(\"[LiveCopilot] Proxy WebSocket error:\",Qe),console.error(\"[LiveCopilot] Error type:\",Qe.type),console.error(\"[LiveCopilot] Socket readyState on error:\",ye.readyState),D(\"Transcription error - check console\")},ye.onclose=Qe=>{clearTimeout(Ae),console.log(\"[LiveCopilot] Proxy disconnected, code:\",Qe.code,\"reason:\",Qe.reason,\"wasClean:\",Qe.wasClean);const Ke=3;if(Pt.current{console.log(\"[LiveCopilot] Reconnecting WebSocket...\"),Rt()},Kt)}else m(!1),Pt.current>=Ke&&D(\"Transcription disconnected. Tap mic to restart.\")},Ft.current=ye;const _e=new AudioContext,et=_e.sampleRate;console.log(\"[LiveCopilot] AudioContext sample rate:\",et);const Be=`","cwd":"/home/ccuser/the-50-dollar-app"},"isError":false,"timestamp":1771614158108}} {"type":"message","id":"fd1f0759","parentId":"1fdbf300","timestamp":"2026-02-20T19:02:45.443Z","message":{"role":"assistant","content":[{"type":"text","text":"I see there's also a `9.9%` reference in the built `admin/dist` bundle, and two more in the `LiveCopilot.jsx` component's `Lx` constant (the buying signal responses). Let me also check the admin dist for the hardcoded value_prop and fix the remaining source references:"},{"type":"toolCall","id":"toolu_01SS6qQkUANAohRy6fRiUKYS","name":"exec","arguments":{"command":"cd /home/ccuser/rateright-growth && grep -n \"9\\.9%\" admin/src/components/LiveCopilot.jsx"}}],"api":"anthropic-messages","provider":"anthropic","model":"claude-opus-4-6","usage":{"input":1,"output":158,"cacheRead":21919,"cacheWrite":73750,"totalTokens":95828,"cost":{"input":0.000005,"output":0.00395,"cacheRead":0.010959499999999999,"cacheWrite":0.4609375,"total":0.475852}},"stopReason":"toolUse","timestamp":1771614158120}} {"type":"message","id":"b02d024c","parentId":"fd1f0759","timestamp":"2026-02-20T19:02:45.464Z","message":{"role":"toolResult","toolCallId":"toolu_01SS6qQkUANAohRy6fRiUKYS","toolName":"exec","content":[{"type":"text","text":"{\n \"status\": \"error\",\n \"tool\": \"exec\",\n \"error\": \"Command exited with code 1\"\n}"}],"details":{"status":"error","tool":"exec","error":"Command exited with code 1"},"isError":false,"timestamp":1771614165461}} {"type":"message","id":"f462230f","parentId":"b02d024c","timestamp":"2026-02-20T19:02:49.550Z","message":{"role":"assistant","content":[{"type":"text","text":"Good — no more 9.9% in LiveCopilot source. Now let me verify all source files are clean:"},{"type":"toolCall","id":"toolu_014oATBQFEdNngMhfYD9uczG","name":"exec","arguments":{"command":"cd /home/ccuser/rateright-growth && grep -rn \"9\\.9%\" --include=\"*.js\" --include=\"*.jsx\" --include=\"*.ts\" --include=\"*.tsx\" . --exclude-dir=node_modules --exclude-dir=dist | grep -v \"scripts/update\""}}],"api":"anthropic-messages","provider":"anthropic","model":"claude-opus-4-6","usage":{"input":1,"output":148,"cacheRead":95669,"cacheWrite":201,"totalTokens":96019,"cost":{"input":0.000005,"output":0.0037,"cacheRead":0.047834499999999995,"cacheWrite":0.00125625,"total":0.052795749999999995}},"stopReason":"toolUse","timestamp":1771614165464}} {"type":"message","id":"cf241bfb","parentId":"f462230f","timestamp":"2026-02-20T19:02:49.642Z","message":{"role":"toolResult","toolCallId":"toolu_014oATBQFEdNngMhfYD9uczG","toolName":"exec","content":[{"type":"text","text":"./public/assets/index-2HMepUD5.js:18: `),()=>{D.contains(R)&&D.removeChild(R)}},[s]),c.jsx(JA,{isPresent:s,childRef:d,sizeRef:f,children:b.cloneElement(t,{ref:y})})}const e2=({children:t,initial:s,isPresent:i,onExitComplete:l,custom:o,presenceAffectsLayout:d,mode:f,anchorX:m,root:p})=>{const y=bh(t2),x=b.useId();let g=!0,w=b.useMemo(()=>(g=!1,{id:x,initial:s,isPresent:i,custom:o,onExitComplete:S=>{y.set(S,!0);for(const T of y.values())if(!T)return;l&&l()},register:S=>(y.set(S,!1),()=>y.delete(S))}),[i,y,l]);return d&&g&&(w={...w}),b.useMemo(()=>{y.forEach((S,T)=>y.set(T,!1))},[i]),b.useEffect(()=>{!i&&!y.size&&l&&l()},[i]),f===\"popLayout\"&&(t=c.jsx(WA,{isPresent:i,anchorX:m,root:p,children:t})),c.jsx(Cc.Provider,{value:w,children:t})};function t2(){return new Map}function rw(t=!0){const s=b.useContext(Cc);if(s===null)return[!0,null];const{isPresent:i,onExitComplete:l,register:o}=s,d=b.useId();b.useEffect(()=>{if(t)return o(d)},[t]);const f=b.useCallback(()=>t&&l&&l(d),[d,l,t]);return!i&&l?[!1,f]:[!0]}const $o=t=>t.key||\"\";function yx(t){const s=[];return b.Children.forEach(t,i=>{b.isValidElement(i)&&s.push(i)}),s}const si=({children:t,custom:s,initial:i=!0,onExitComplete:l,presenceAffectsLayout:o=!0,mode:d=\"sync\",propagate:f=!1,anchorX:m=\"left\",root:p})=>{const[y,x]=rw(f),g=b.useMemo(()=>yx(t),[t]),w=f&&!y?[]:g.map($o),S=b.useRef(!0),T=b.useRef(g),N=bh(()=>new Map),R=b.useRef(new Set),[D,A]=b.useState(g),[C,B]=b.useState(g);Vb(()=>{S.current=!1,T.current=g;for(let P=0;P{const H=$o(P),z=f&&!y?!1:g===C||w.includes(H),X=()=>{if(R.current.has(H))return;if(R.current.add(H),N.has(H))N.set(H,!0);else return;let te=!0;N.forEach(Y=>{Y||(te=!1)}),te&&(F?.(),B(T.current),f&&x?.(),l&&l())};return c.jsx(e2,{isPresent:z,initial:!S.current||i?void 0:!1,custom:s,presenceAffectsLayout:o,mode:d,root:p,onExitComplete:z?void 0:X,anchorX:m,children:P},H)})})},ow=b.createContext({strict:!1}),xx={animation:[\"animate\",\"variants\",\"whileHover\",\"whileTap\",\"exit\",\"whileInView\",\"whileFocus\",\"whileDrag\"],exit:[\"exit\"],drag:[\"drag\",\"dragControls\"],focus:[\"whileFocus\"],hover:[\"whileHover\",\"onHoverStart\",\"onHoverEnd\"],tap:[\"whileTap\",\"onTap\",\"onTapStart\",\"onTapCancel\"],pan:[\"onPan\",\"onPanStart\",\"onPanSessionStart\",\"onPanEnd\"],inView:[\"whileInView\",\"onViewportEnter\",\"onViewportLeave\"],layout:[\"layout\",\"layoutId\"]};let bx=!1;function n2(){if(bx)return;const t={};for(const s in xx)t[s]={isEnabled:i=>xx[s].some(l=>!!i[l])};Bv(t),bx=!0}function cw(){return n2(),qC()}function s2(t){const s=cw();for(const i in t)s[i]={...s[i],...t[i]};Bv(s)}const a2=new Set([\"animate\",\"exit\",\"variants\",\"initial\",\"style\",\"values\",\"variants\",\"transition\",\"transformTemplate\",\"custom\",\"inherit\",\"onBeforeLayoutMeasure\",\"onAnimationStart\",\"onAnimationComplete\",\"onUpdate\",\"onDragStart\",\"onDrag\",\"onDragEnd\",\"onMeasureDragConstraints\",\"onDirectionLock\",\"onDragTransitionEnd\",\"_dragX\",\"_dragY\",\"onHoverStart\",\"onHoverEnd\",\"onViewportEnter\",\"onViewportLeave\",\"globalTapTarget\",\"ignoreStrict\",\"viewport\"]);function fc(t){return t.startsWith(\"while\")||t.startsWith(\"drag\")&&t!==\"draggable\"||t.startsWith(\"layout\")||t.startsWith(\"onTap\")||t.startsWith(\"onPan\")||t.startsWith(\"onLayout\")||a2.has(t)}let uw=t=>!fc(t);function i2(t){typeof t==\"function\"&&(uw=s=>s.startsWith(\"on\")?!fc(s):t(s))}try{i2(require(\"@emotion/is-prop-valid\").default)}catch{}function l2(t,s,i){const l={};for(const o in t)o===\"values\"&&typeof t.values==\"object\"||(uw(o)||i===!0&&fc(o)||!s&&!fc(o)||t.draggable&&o.startsWith(\"onDrag\"))&&(l[o]=t[o]);return l}const Dc=b.createContext({});function r2(t,s){if(Ec(t)){const{initial:i,animate:l}=t;return{initial:i===!1||mr(i)?i:void 0,animate:mr(l)?l:void 0}}return t.inherit!==!1?s:{}}function o2(t){const{initial:s,animate:i}=r2(t,b.useContext(Dc));return b.useMemo(()=>({initial:s,animate:i}),[vx(s),vx(i)])}function vx(t){return Array.isArray(t)?t.join(\" \"):t}const Xh=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function dw(t,s,i){for(const l in s)!$t(s[l])&&!$v(l,i)&&(t[l]=s[l])}function c2({transformTemplate:t},s){return b.useMemo(()=>{const i=Xh();return Gh(i,s,t),Object.assign({},i.vars,i.style)},[s])}function u2(t,s){const i=t.style||{},l={};return dw(l,i,t),Object.assign(l,c2(t,s)),l}function d2(t,s){const i={},l=u2(t,s);return t.drag&&t.dragListener!==!1&&(i.draggable=!1,l.userSelect=l.WebkitUserSelect=l.WebkitTouchCallout=\"none\",l.touchAction=t.drag===!0?\"none\":`pan-${t.drag===\"x\"?\"y\":\"x\"}`),t.tabIndex===void 0&&(t.onTap||t.onTapStart||t.whileTap)&&(i.tabIndex=0),i.style=l,i}const fw=()=>({...Xh(),attrs:{}});function f2(t,s,i,l){const o=b.useMemo(()=>{const d=fw();return Gv(d,s,Fv(l),t.transformTemplate,t.style),{...d.attrs,style:{...d.style}}},[s]);if(t.style){const d={};dw(d,t.style,t),o.style={...d,...o.style}}return o}const h2=[\"animate\",\"circle\",\"defs\",\"desc\",\"ellipse\",\"g\",\"image\",\"line\",\"filter\",\"marker\",\"mask\",\"metadata\",\"path\",\"pattern\",\"polygon\",\"polyline\",\"rect\",\"stop\",\"switch\",\"symbol\",\"svg\",\"text\",\"tspan\",\"use\",\"view\"];function Kh(t){return typeof t!=\"string\"||t.includes(\"-\")?!1:!!(h2.indexOf(t)>-1||/[A-Z]/u.test(t))}function m2(t,s,i,{latestValues:l},o,d=!1,f){const p=(f??Kh(t)?f2:d2)(s,l,o,t),y=l2(s,typeof t==\"string\",d),x=t!==b.Fragment?{...y,...p,ref:i}:{},{children:g}=s,w=b.useMemo(()=>$t(g)?g.get():g,[g]);return b.createElement(t,{...x,children:w})}function p2({scrapeMotionValuesFromProps:t,createRenderState:s},i,l,o){return{latestValues:g2(i,l,o,t),renderState:s()}}function g2(t,s,i,l){const o={},d=l(t,{});for(const w in d)o[w]=ec(d[w]);let{initial:f,animate:m}=t;const p=Ec(t),y=zv(t);s&&y&&!p&&t.inherit!==!1&&(f===void 0&&(f=s.initial),m===void 0&&(m=s.animate));let x=i?i.initial===!1:!1;x=x||f===!1;const g=x?m:f;if(g&&typeof g!=\"boolean\"&&!Ac(g)){const w=Array.isArray(g)?g:[g];for(let S=0;S(s,i)=>{const l=b.useContext(Dc),o=b.useContext(Cc),d=()=>p2(t,s,l,o);return i?d():bh(d)},y2=hw({scrapeMotionValuesFromProps:Yh,createRenderState:Xh}),x2=hw({scrapeMotionValuesFromProps:Xv,createRenderState:fw}),b2=Symbol.for(\"motionComponentSymbol\");function v2(t,s,i){const l=b.useRef(i);b.useInsertionEffect(()=>{l.current=i});const o=b.useRef(null);return b.useCallback(d=>{d&&t.onMount?.(d),s&&(d?s.mount(d):s.unmount());const f=l.current;if(typeof f==\"function\")if(d){const m=f(d);typeof m==\"function\"&&(o.current=m)}else o.current?(o.current(),o.current=null):f(d);else f&&(f.current=d)},[s])}const mw=b.createContext({});function sr(t){return t&&typeof t==\"object\"&&Object.prototype.hasOwnProperty.call(t,\"current\")}function w2(t,s,i,l,o,d){const{visualElement:f}=b.useContext(Dc),m=b.useContext(ow),p=b.useContext(Cc),y=b.useContext(Fh).reducedMotion,x=b.useRef(null);l=l||m.renderer,!x.current&&l&&(x.current=l(t,{visualState:s,parent:f,props:i,presenceContext:p,blockInitialAnimation:p?p.initial===!1:!1,reducedMotionConfig:y,isSVG:d}));const g=x.current,w=b.useContext(mw);g&&!g.projection&&o&&(g.type===\"html\"||g.type===\"svg\")&&S2(x.current,i,o,w);const S=b.useRef(!1);b.useInsertionEffect(()=>{g&&S.current&&g.update(i,p)});const T=i[wv],N=b.useRef(!!T&&!window.MotionHandoffIsComplete?.(T)&&window.MotionHasOptimisedAnimation?.(T));return Vb(()=>{g&&(S.current=!0,window.MotionIsMounted=!0,g.updateFeatures(),g.scheduleRenderMicrotask(),N.current&&g.animationState&&g.animationState.animateChanges())}),b.useEffect(()=>{g&&(!N.current&&g.animationState&&g.animationState.animateChanges(),N.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(T)}),N.current=!1),g.enteringChildren=void 0)}),g}function S2(t,s,i,l){const{layoutId:o,layout:d,drag:f,dragConstraints:m,layoutScroll:p,layoutRoot:y,layoutCrossfade:x}=s;t.projection=new i(t.latestValues,s[\"data-framer-portal-id\"]?void 0:pw(t.parent)),t.projection.setOptions({layoutId:o,layout:d,alwaysMeasureLayout:!!f||m&&sr(m),visualElement:t,animationType:typeof d==\"string\"?d:\"both\",initialPromotionConfig:l,crossfade:x,layoutScroll:p,layoutRoot:y})}function pw(t){if(t)return t.options.allowProjection!==!1?t.projection:pw(t.parent)}function ff(t,{forwardMotionProps:s=!1,type:i}={},l,o){l&&s2(l);const d=i?i===\"svg\":Kh(t),f=d?x2:y2;function m(y,x){let g;const w={...b.useContext(Fh),...y,layoutId:j2(y)},{isStatic:S}=w,T=o2(y),N=f(y,S);if(!S&&Bb){T2();const R=N2(w);g=R.MeasureLayout,T.visualElement=w2(t,N,w,o,R.ProjectionNode,d)}return c.jsxs(Dc.Provider,{value:T,children:[g&&T.visualElement?c.jsx(g,{visualElement:T.visualElement,...w}):null,m2(t,y,v2(N,T.visualElement,x),N,S,s,d)]})}m.displayName=`motion.${typeof t==\"string\"?t:`create(${t.displayName??t.name??\"\"})`}`;const p=b.forwardRef(m);return p[b2]=t,p}function j2({layoutId:t}){const s=b.useContext(xh).id;return s&&t!==void 0?s+\"-\"+t:t}function T2(t,s){b.useContext(ow).strict}function N2(t){const s=cw(),{drag:i,layout:l}=s;if(!i&&!l)return{};const o={...i,...l};return{MeasureLayout:i?.isEnabled(t)||l?.isEnabled(t)?o.MeasureLayout:void 0,ProjectionNode:o.ProjectionNode}}function C2(t,s){if(typeof Proxy>\"u\")return ff;const i=new Map,l=(d,f)=>ff(d,f,t,s),o=(d,f)=>l(d,f);return new Proxy(o,{get:(d,f)=>f===\"create\"?l:(i.has(f)||i.set(f,ff(f,void 0,t,s)),i.get(f))})}const A2=(t,s)=>s.isSVG??Kh(t)?new iA(s):new WC(s,{allowProjection:t!==b.Fragment});class E2 extends Na{constructor(s){super(s),s.animationState||(s.animationState=uA(s))}updateAnimationControlsSubscription(){const{animate:s}=this.node.getProps();Ac(s)&&(this.unmountControls=s.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:s}=this.node.getProps(),{animate:i}=this.node.prevProps||{};s!==i&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}}let D2=0;class k2 extends Na{constructor(){super(...arguments),this.id=D2++}update(){if(!this.node.presenceContext)return;const{isPresent:s,onExitComplete:i}=this.node.presenceContext,{isPresent:l}=this.node.prevPresenceContext||{};if(!this.node.animationState||s===l)return;const o=this.node.animationState.setActive(\"exit\",!s);i&&!s&&o.then(()=>{i(this.id)})}mount(){const{register:s,onExitComplete:i}=this.node.presenceContext||{};i&&i(this.id),s&&(this.unmount=s(this.id))}unmount(){}}const R2={animation:{Feature:E2},exit:{Feature:k2}};function jr(t){return{point:{x:t.pageX,y:t.pageY}}}const M2=t=>s=>qh(s)&&t(s,jr(s));function rr(t,s,i,l){return pr(t,s,M2(i),l)}const gw=({current:t})=>t?t.ownerDocument.defaultView:null,wx=(t,s)=>Math.abs(t-s);function O2(t,s){const i=wx(t.x,s.x),l=wx(t.y,s.y);return Math.sqrt(i**2+l**2)}const Sx=new Set([\"auto\",\"scroll\"]);class yw{constructor(s,i,{transformPagePoint:l,contextWindow:o=window,dragSnapToOrigin:d=!1,distanceThreshold:f=3,element:m}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=S=>{this.handleScroll(S.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const S=mf(this.lastMoveEventInfo,this.history),T=this.startEvent!==null,N=O2(S.offset,{x:0,y:0})>=this.distanceThreshold;if(!T&&!N)return;const{point:R}=S,{timestamp:D}=Bt;this.history.push({...R,timestamp:D});const{onStart:A,onMove:C}=this.handlers;T||(A&&A(this.lastMoveEvent,S),this.startEvent=this.lastMoveEvent),C&&C(this.lastMoveEvent,S)},this.handlePointerMove=(S,T)=>{this.lastMoveEvent=S,this.lastMoveEventInfo=hf(T,this.transformPagePoint),We.update(this.updatePoint,!0)},this.handlePointerUp=(S,T)=>{this.end();const{onEnd:N,onSessionEnd:R,resumeAnimation:D}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&D&&D(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const A=mf(S.type===\"pointercancel\"?this.lastMoveEventInfo:hf(T,this.transformPagePoint),this.history);this.startEvent&&N&&N(S,A),R&&R(S,A)},!qh(s))return;this.dragSnapToOrigin=d,this.handlers=i,this.transformPagePoint=l,this.distanceThreshold=f,this.contextWindow=o||window;const p=jr(s),y=hf(p,this.transformPagePoint),{point:x}=y,{timestamp:g}=Bt;this.history=[{...x,timestamp:g}];const{onSessionStart:w}=i;w&&w(s,mf(y,this.history)),this.removeListeners=vr(rr(this.contextWindow,\"pointermove\",this.handlePointerMove),rr(this.contextWindow,\"pointerup\",this.handlePointerUp),rr(this.contextWindow,\"pointercancel\",this.handlePointerUp)),m&&this.startScrollTracking(m)}startScrollTracking(s){let i=s.parentElement;for(;i;){const l=getComputedStyle(i);(Sx.has(l.overflowX)||Sx.has(l.overflowY))&&this.scrollPositions.set(i,{x:i.scrollLeft,y:i.scrollTop}),i=i.parentElement}this.scrollPositions.set(window,{x:window.scrollX,y:window.scrollY}),window.addEventListener(\"scroll\",this.onElementScroll,{capture:!0,passive:!0}),window.addEventListener(\"scroll\",this.onWindowScroll,{passive:!0}),this.removeScrollListeners=()=>{window.removeEventListener(\"scroll\",this.onElementScroll,{capture:!0}),window.removeEventListener(\"scroll\",this.onWindowScroll)}}handleScroll(s){const i=this.scrollPositions.get(s);if(!i)return;const l=s===window,o=l?{x:window.scrollX,y:window.scrollY}:{x:s.scrollLeft,y:s.scrollTop},d={x:o.x-i.x,y:o.y-i.y};d.x===0&&d.y===0||(l?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=d.x,this.lastMoveEventInfo.point.y+=d.y):this.history.length>0&&(this.history[0].x-=d.x,this.history[0].y-=d.y),this.scrollPositions.set(s,o),We.update(this.updatePoint,!0))}updateHandlers(s){this.handlers=s}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),va(this.updatePoint)}}function hf(t,s){return s?{point:s(t.point)}:t}function jx(t,s){return{x:t.x-s.x,y:t.y-s.y}}function mf({point:t},s){return{point:t,delta:jx(t,xw(s)),offset:jx(t,_2(s)),velocity:L2(s,.1)}}function _2(t){return t[0]}function xw(t){return t[t.length-1]}function L2(t,s){if(t.length<2)return{x:0,y:0};let i=t.length-1,l=null;const o=xw(t);for(;i>=0&&(l=t[i],!(o.timestamp-l.timestamp>Us(s)));)i--;if(!l)return{x:0,y:0};const d=Mn(o.timestamp-l.timestamp);if(d===0)return{x:0,y:0};const f={x:(o.x-l.x)/d,y:(o.y-l.y)/d};return f.x===1/0&&(f.x=0),f.y===1/0&&(f.y=0),f}function z2(t,{min:s,max:i},l){return s!==void 0&&ti&&(t=l?it(i,t,l.max):Math.min(t,i)),t}function Tx(t,s,i){return{min:s!==void 0?t.min+s:void 0,max:i!==void 0?t.max+i-(t.max-t.min):void 0}}function B2(t,{top:s,left:i,bottom:l,right:o}){return{x:Tx(t.x,i,o),y:Tx(t.y,s,l)}}function Nx(t,s){let i=s.min-t.min,l=s.max-t.max;return s.max-s.minl?i=dr(s.min,s.max-l,t.min):l>o&&(i=dr(t.min,t.max-o,s.min)),cs(0,1,i)}function P2(t,s){const i={};return s.min!==void 0&&(i.min=s.min-t.min),s.max!==void 0&&(i.max=s.max-t.min),i}const Xf=.35;function H2(t=Xf){return t===!1?t=0:t===!0&&(t=Xf),{x:Cx(t,\"left\",\"right\"),y:Cx(t,\"top\",\"bottom\")}}function Cx(t,s,i){return{min:Ax(t,s),max:Ax(t,i)}}function Ax(t,s){return typeof t==\"number\"?t:t[s]||0}const q2=new WeakMap;class I2{constructor(s){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=Tt(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=s}start(s,{snapToCursor:i=!1,distanceThreshold:l}={}){const{presenceContext:o}=this.visualElement;if(o&&o.isPresent===!1)return;const d=g=>{i?(this.stopAnimation(),this.snapToCursor(jr(g).point)):this.pauseAnimation()},f=(g,w)=>{this.stopAnimation();const{drag:S,dragPropagation:T,onDragStart:N}=this.getProps();if(S&&!T&&(this.openDragLock&&this.openDragLock(),this.openDragLock=kC(S),!this.openDragLock))return;this.latestPointerEvent=g,this.latestPanInfo=w,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Rn(D=>{let A=this.getAxisMotionValue(D).get()||0;if(rs.test(A)){const{projection:C}=this.visualElement;if(C&&C.layout){const B=C.layout.layoutBox[D];B&&(A=Jt(B)*(parseFloat(A)/100))}}this.originPoint[D]=A}),N&&We.postRender(()=>N(g,w)),Hf(this.visualElement,\"transform\");const{animationState:R}=this.visualElement;R&&R.setActive(\"whileDrag\",!0)},m=(g,w)=>{this.latestPointerEvent=g,this.latestPanInfo=w;const{dragPropagation:S,dragDirectionLock:T,onDirectionLock:N,onDrag:R}=this.getProps();if(!S&&!this.openDragLock)return;const{offset:D}=w;if(T&&this.currentDirection===null){this.currentDirection=$2(D),this.currentDirection!==null&&N&&N(this.currentDirection);return}this.updateAxis(\"x\",w.point,D),this.updateAxis(\"y\",w.point,D),this.visualElement.render(),R&&R(g,w)},p=(g,w)=>{this.latestPointerEvent=g,this.latestPanInfo=w,this.stop(g,w),this.latestPointerEvent=null,this.latestPanInfo=null},y=()=>Rn(g=>this.getAnimationState(g)===\"paused\"&&this.getAxisMotionValue(g).animation?.play()),{dragSnapToOrigin:x}=this.getProps();this.panSession=new yw(s,{onSessionStart:d,onStart:f,onMove:m,onSessionEnd:p,resumeAnimation:y},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:x,distanceThreshold:l,contextWindow:gw(this.visualElement),element:this.visualElement.current})}stop(s,i){const l=s||this.latestPointerEvent,o=i||this.latestPanInfo,d=this.isDragging;if(this.cancel(),!d||!o||!l)return;const{velocity:f}=o;this.startAnimation(f);const{onDragEnd:m}=this.getProps();m&&We.postRender(()=>m(l,o))}cancel(){this.isDragging=!1;const{projection:s,animationState:i}=this.visualElement;s&&(s.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:l}=this.getProps();!l&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),i&&i.setActive(\"whileDrag\",!1)}updateAxis(s,i,l){const{drag:o}=this.getProps();if(!l||!Go(s,o,this.currentDirection))return;const d=this.getAxisMotionValue(s);let f=this.originPoint[s]+l[s];this.constraints&&this.constraints[s]&&(f=z2(f,this.constraints[s],this.elastic[s])),d.set(f)}resolveConstraints(){const{dragConstraints:s,dragElastic:i}=this.getProps(),l=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,o=this.constraints;s&&sr(s)?this.constraints||(this.constraints=this.resolveRefConstraints()):s&&l?this.constraints=B2(l.layoutBox,s):this.constraints=!1,this.elastic=H2(i),o!==this.constraints&&l&&this.constraints&&!this.hasMutatedConstraints&&Rn(d=>{this.constraints!==!1&&this.getAxisMotionValue(d)&&(this.constraints[d]=P2(l.layoutBox[d],this.constraints[d]))})}resolveRefConstraints(){const{dragConstraints:s,onMeasureDragConstraints:i}=this.getProps();if(!s||!sr(s))return!1;const l=s.current,{projection:o}=this.visualElement;if(!o||!o.layout)return!1;const d=FC(l,o.root,this.visualElement.getTransformPagePoint());let f=V2(o.layout.layoutBox,d);if(i){const m=i($C(f));this.hasMutatedConstraints=!!m,m&&(f=Uv(m))}return f}startAnimation(s){const{drag:i,dragMomentum:l,dragElastic:o,dragTransition:d,dragSnapToOrigin:f,onDragTransitionEnd:m}=this.getProps(),p=this.constraints||{},y=Rn(x=>{if(!Go(x,i,this.currentDirection))return;let g=p&&p[x]||{};f&&(g={min:0,max:0});const w=o?200:1e6,S=o?40:1e7,T={type:\"inertia\",velocity:l?s[x]:0,bounceStiffness:w,bounceDamping:S,timeConstant:750,restDelta:1,restSpeed:10,...d,...g};return this.startAxisValueAnimation(x,T)});return Promise.all(y).then(m)}startAxisValueAnimation(s,i){const l=this.getAxisMotionValue(s);return Hf(this.visualElement,s),l.start(Bh(s,l,0,i,this.visualElement,!1))}stopAnimation(){Rn(s=>this.getAxisMotionValue(s).stop())}pauseAnimation(){Rn(s=>this.getAxisMotionValue(s).animation?.pause())}getAnimationState(s){return this.getAxisMotionValue(s).animation?.state}getAxisMotionValue(s){const i=`_drag${s.toUpperCase()}`,l=this.visualElement.getProps(),o=l[i];return o||this.visualElement.getValue(s,(l.initial?l.initial[s]:void 0)||0)}snapToCursor(s){Rn(i=>{const{drag:l}=this.getProps();if(!Go(i,l,this.currentDirection))return;const{projection:o}=this.visualElement,d=this.getAxisMotionValue(i);if(o&&o.layout){const{min:f,max:m}=o.layout.layoutBox[i],p=d.get()||0;d.set(s[i]-it(f,m,.5)+p)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:s,dragConstraints:i}=this.getProps(),{projection:l}=this.visualElement;if(!sr(i)||!l||!this.constraints)return;this.stopAnimation();const o={x:0,y:0};Rn(f=>{const m=this.getAxisMotionValue(f);if(m&&this.constraints!==!1){const p=m.get();o[f]=U2({min:p,max:p},this.constraints[f])}});const{transformTemplate:d}=this.visualElement.getProps();this.visualElement.current.style.transform=d?d({},\"\"):\"none\",l.root&&l.root.updateScroll(),l.updateLayout(),this.resolveConstraints(),Rn(f=>{if(!Go(f,s,null))return;const m=this.getAxisMotionValue(f),{min:p,max:y}=this.constraints[f];m.set(it(p,y,o[f]))})}addListeners(){if(!this.visualElement.current)return;q2.set(this.visualElement,this);const s=this.visualElement.current,i=rr(s,\"pointerdown\",p=>{const{drag:y,dragListener:x=!0}=this.getProps();y&&x&&!Ov(p.target)&&this.start(p)}),l=()=>{const{dragConstraints:p}=this.getProps();sr(p)&&p.current&&(this.constraints=this.resolveRefConstraints())},{projection:o}=this.visualElement,d=o.addEventListener(\"measure\",l);o&&!o.layout&&(o.root&&o.root.updateScroll(),o.updateLayout()),We.read(l);const f=pr(window,\"resize\",()=>this.scalePositionWithinConstraints()),m=o.addEventListener(\"didUpdate\",(({delta:p,hasLayoutChanged:y})=>{this.isDragging&&y&&(Rn(x=>{const g=this.getAxisMotionValue(x);g&&(this.originPoint[x]+=p[x].translate,g.set(g.get()+p[x].translate))}),this.visualElement.render())}));return()=>{f(),i(),d(),m&&m()}}getProps(){const s=this.visualElement.getProps(),{drag:i=!1,dragDirectionLock:l=!1,dragPropagation:o=!1,dragConstraints:d=!1,dragElastic:f=Xf,dragMomentum:m=!0}=s;return{...s,drag:i,dragDirectionLock:l,dragPropagation:o,dragConstraints:d,dragElastic:f,dragMomentum:m}}}function Go(t,s,i){return(s===!0||s===t)&&(i===null||i===t)}function $2(t,s=10){let i=null;return Math.abs(t.y)>s?i=\"y\":Math.abs(t.x)>s&&(i=\"x\"),i}class G2 extends Na{constructor(s){super(s),this.removeGroupControls=On,this.removeListeners=On,this.controls=new I2(s)}mount(){const{dragControls:s}=this.node.getProps();s&&(this.removeGroupControls=s.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||On}update(){const{dragControls:s}=this.node.getProps(),{dragControls:i}=this.node.prevProps||{};s!==i&&(this.removeGroupControls(),s&&(this.removeGroupControls=s.subscribe(this.controls)))}unmount(){this.removeGroupControls(),this.removeListeners()}}const Ex=t=>(s,i)=>{t&&We.postRender(()=>t(s,i))};class Y2 extends Na{constructor(){super(...arguments),this.removePointerDownListener=On}onPointerDown(s){this.session=new yw(s,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:gw(this.node)})}createPanHandlers(){const{onPanSessionStart:s,onPanStart:i,onPan:l,onPanEnd:o}=this.node.getProps();return{onSessionStart:Ex(s),onStart:Ex(i),onMove:l,onEnd:(d,f)=>{delete this.session,o&&We.postRender(()=>o(d,f))}}}mount(){this.removePointerDownListener=rr(this.node.current,\"pointerdown\",s=>this.onPointerDown(s))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}let pf=!1;class F2 extends b.Component{componentDidMount(){const{visualElement:s,layoutGroup:i,switchLayoutGroup:l,layoutId:o}=this.props,{projection:d}=s;d&&(i.group&&i.group.add(d),l&&l.register&&o&&l.register(d),pf&&d.root.didUpdate(),d.addEventListener(\"animationComplete\",()=>{this.safeToRemove()}),d.setOptions({...d.options,onExitComplete:()=>this.safeToRemove()})),tc.hasEverUpdated=!0}getSnapshotBeforeUpdate(s){const{layoutDependency:i,visualElement:l,drag:o,isPresent:d}=this.props,{projection:f}=l;return f&&(f.isPresent=d,pf=!0,o||s.layoutDependency!==i||i===void 0||s.isPresent!==d?f.willUpdate():this.safeToRemove(),s.isPresent!==d&&(d?f.promote():f.relegate()||We.postRender(()=>{const m=f.getStack();(!m||!m.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:s}=this.props.visualElement;s&&(s.root.didUpdate(),Hh.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:s,layoutGroup:i,switchLayoutGroup:l}=this.props,{projection:o}=s;pf=!0,o&&(o.scheduleCheckAfterUnmount(),i&&i.group&&i.group.remove(o),l&&l.deregister&&l.deregister(o))}safeToRemove(){const{safeToRemove:s}=this.props;s&&s()}render(){return null}}function bw(t){const[s,i]=rw(),l=b.useContext(xh);return c.jsx(F2,{...t,layoutGroup:l,switchLayoutGroup:b.useContext(mw),isPresent:s,safeToRemove:i})}const X2={pan:{Feature:Y2},drag:{Feature:G2,ProjectionNode:lw,MeasureLayout:bw}};function Dx(t,s,i){const{props:l}=t;t.animationState&&l.whileHover&&t.animationState.setActive(\"whileHover\",i===\"Start\");const o=\"onHover\"+i,d=l[o];d&&We.postRender(()=>d(s,jr(s)))}class K2 extends Na{mount(){const{current:s}=this.node;s&&(this.unmount=RC(s,(i,l)=>(Dx(this.node,l,\"Start\"),o=>Dx(this.node,o,\"End\"))))}unmount(){}}class Q2 extends Na{constructor(){super(...arguments),this.isActive=!1}onFocus(){let s=!1;try{s=this.node.current.matches(\":focus-visible\")}catch{s=!0}!s||!this.node.animationState||(this.node.animationState.setActive(\"whileFocus\",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive(\"whileFocus\",!1),this.isActive=!1)}mount(){this.unmount=vr(pr(this.node.current,\"focus\",()=>this.onFocus()),pr(this.node.current,\"blur\",()=>this.onBlur()))}unmount(){}}function kx(t,s,i){const{props:l}=t;if(t.current instanceof HTMLButtonElement&&t.current.disabled)return;t.animationState&&l.whileTap&&t.animationState.setActive(\"whileTap\",i===\"Start\");const o=\"onTap\"+(i===\"End\"?\"\":i),d=l[o];d&&We.postRender(()=>d(s,jr(s)))}class Z2 extends Na{mount(){const{current:s}=this.node;s&&(this.unmount=_C(s,(i,l)=>(kx(this.node,l,\"Start\"),(o,{success:d})=>kx(this.node,o,d?\"End\":\"Cancel\")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const Kf=new WeakMap,gf=new WeakMap,J2=t=>{const s=Kf.get(t.target);s&&s(t)},W2=t=>{t.forEach(J2)};function eE({root:t,...s}){const i=t||document;gf.has(i)||gf.set(i,{});const l=gf.get(i),o=JSON.stringify(s);return l[o]||(l[o]=new IntersectionObserver(W2,{root:t,...s})),l[o]}function tE(t,s,i){const l=eE(s);return Kf.set(t,i),l.observe(t),()=>{Kf.delete(t),l.unobserve(t)}}const nE={some:0,all:1};class sE extends Na{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:s={}}=this.node.getProps(),{root:i,margin:l,amount:o=\"some\",once:d}=s,f={root:i?i.current:void 0,rootMargin:l,threshold:typeof o==\"number\"?o:nE[o]},m=p=>{const{isIntersecting:y}=p;if(this.isInView===y||(this.isInView=y,d&&!y&&this.hasEnteredView))return;y&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive(\"whileInView\",y);const{onViewportEnter:x,onViewportLeave:g}=this.node.getProps(),w=y?x:g;w&&w(p)};return tE(this.node.current,f,m)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>\"u\")return;const{props:s,prevProps:i}=this.node;[\"amount\",\"margin\",\"root\"].some(aE(s,i))&&this.startObserver()}unmount(){}}function aE({viewport:t={}},{viewport:s={}}={}){return i=>t[i]!==s[i]}const iE={inView:{Feature:sE},tap:{Feature:Z2},focus:{Feature:Q2},hover:{Feature:K2}},lE={layout:{ProjectionNode:lw,MeasureLayout:bw}},rE={...R2,...iE,...X2,...lE},Le=C2(rE,A2),Qh=\"https://rateright-growth-production.up.railway.app\";async function Zh(){try{const{data:{session:t}}=await Nt.auth.getSession();return t?.access_token||null}catch{return null}}async function k(t,s={}){const i=`${Qh}${t}`,l=await Zh(),d={headers:{\"Content-Type\":\"application/json\",...l?{Authorization:`Bearer ${l}`}:{},...s.headers},...s},f=await fetch(i,d);if(!f.ok){const m=await f.json().catch(()=>({error:\"Request failed\"}));throw new Error(m.error||`HTTP ${f.status}`)}return f.status===204?null:f.json()}const Tr={list:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/leads${s?`?${s}`:\"\"}`)},get:t=>k(`/api/leads/${t}`),create:t=>k(\"/api/leads\",{method:\"POST\",body:JSON.stringify(t)}),update:(t,s)=>k(`/api/leads/${t}`,{method:\"PATCH\",body:JSON.stringify(s)}),updateLead:(t,s)=>k(`/api/leads/${t}`,{method:\"PATCH\",body:JSON.stringify(s)}),delete:t=>k(`/api/leads/${t}`,{method:\"DELETE\"}),archive:(t,s)=>k(`/api/leads/${t}/archive`,{method:\"POST\",body:JSON.stringify({reason:s})}),archiveLead:(t,s)=>k(`/api/leads/${t}/archive`,{method:\"POST\",body:JSON.stringify({reason:s})}),importFromSheet:()=>k(\"/api/leads/import-sheet\",{method:\"POST\"}),search:t=>k(`/api/leads/search?q=${encodeURIComponent(t)}`),claim:t=>k(`/api/leads/${t}/claim`,{method:\"POST\"}),release:t=>k(`/api/leads/${t}/release`,{method:\"POST\"}),assignments:()=>k(\"/api/leads/assignments\")},Jk={get:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/call-list${s?`?${s}`:\"\"}`)},stats:()=>k(\"/api/call-list/stats\"),activity:t=>k(`/api/call-list/activity${t?`?date=${t}`:\"\"}`)},Wk={send:t=>k(\"/api/sms/send\",{method:\"POST\",body:JSON.stringify(t)}),batch:t=>k(\"/api/sms/batch\",{method:\"POST\",body:JSON.stringify(t)}),preview:t=>k(\"/api/sms/preview\",{method:\"POST\",body:JSON.stringify(t)}),requestContact:t=>k(\"/api/sms/request-contact\",{method:\"POST\",body:JSON.stringify({leadId:t})}),getTemplates:t=>k(`/api/sms/templates${t?`?category=${t}`:\"\"}`),getTemplate:t=>k(`/api/sms/templates/${t}`),createTemplate:t=>k(\"/api/sms/templates\",{method:\"POST\",body:JSON.stringify(t)}),updateTemplate:(t,s)=>k(`/api/sms/templates/${t}`,{method:\"PUT\",body:JSON.stringify(s)}),deleteTemplate:t=>k(`/api/sms/templates/${t}`,{method:\"DELETE\"}),useTemplate:t=>k(`/api/sms/templates/${t}/use`,{method:\"POST\"}),getConversations:(t=\"all\")=>k(`/api/sms/conversations?filter=${t}`),getConversation:t=>k(`/api/sms/conversation/${t}`),markAsRead:t=>k(`/api/sms/conversation/${t}/read`,{method:\"PATCH\"}),handleConversation:(t,s=!0)=>k(`/api/sms/conversation/${t}/handle`,{method:\"PATCH\",body:JSON.stringify({handled:s})}),getPrioritized:(t=50)=>k(`/api/sms/conversations/prioritized?limit=${t}`),getAiSuggestion:(t,s)=>k(\"/api/sms/ai-suggest\",{method:\"POST\",body:JSON.stringify({leadId:t,lastMessage:s})}),getScheduled:t=>k(`/api/sms/scheduled${t?`?leadId=${t}`:\"\"}`),cancelScheduled:t=>k(`/api/sms/scheduled/${t}`,{method:\"DELETE\"}),getStats:(t=30)=>k(`/api/sms/stats?days=${t}`),sendBatch:t=>k(\"/api/sms/send-batch\",{method:\"POST\",body:JSON.stringify({messages:t})})},oE={log:t=>k(\"/api/calls/log\",{method:\"POST\",body:JSON.stringify(t)}),outcomes:()=>k(\"/api/calls/outcomes\"),getHistory:(t,s=1)=>k(`/api/calls/history/${t}?limit=${s}`)},eR={get:t=>k(`/api/dossier/${t}`),update:(t,s)=>k(`/api/dossier/${t}`,{method:\"PATCH\",body:JSON.stringify(s)}),addFact:(t,s,i=\"manual\")=>k(`/api/dossier/${t}/add-fact`,{method:\"POST\",body:JSON.stringify({fact:s,source:i})}),addCallSummary:(t,s)=>k(`/api/dossier/${t}/add-call-summary`,{method:\"POST\",body:JSON.stringify(s)}),addObjection:(t,s)=>k(`/api/dossier/${t}/add-objection`,{method:\"POST\",body:JSON.stringify(s)})},tR={getAll:()=>k(\"/api/dashboard/all\"),getStats:()=>k(\"/api/dashboard/stats\"),getWisdom:()=>k(\"/api/dashboard/wisdom\"),rateWisdom:(t,s)=>k(\"/api/dashboard/wisdom/rate\",{method:\"POST\",body:JSON.stringify({wisdomId:t,rating:s})}),getStrategy:()=>k(\"/api/dashboard/strategy\"),getPriorityAction:()=>k(\"/api/dashboard/priority-action\"),getSlipping:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/dashboard/slipping${s?`?${s}`:\"\"}`)}},nc={getToken:()=>k(\"/api/voice/token\"),status:()=>k(\"/api/voice/status\"),lookupCaller:t=>k(`/api/voice/lookup-caller?phone=${encodeURIComponent(t)}`)},cE={submit:t=>k(\"/api/bug-report\",{method:\"POST\",body:JSON.stringify(t)})},It={getIntelBrief:t=>k(`/api/ai/intel-brief/${t}`),getLiveIntel:t=>k(`/api/ai/live-intel/${t}`),postCallSummary:t=>k(\"/api/ai/post-call-summary\",{method:\"POST\",body:JSON.stringify(t)}),draftMessage:t=>k(\"/api/ai/draft-message\",{method:\"POST\",body:JSON.stringify(t)}),transcribe:async t=>{const s=new FormData;s.append(\"audio\",t,\"audio.webm\");const i=`${Qh}/api/ai/transcribe`,l=await Zh(),o=l?{Authorization:`Bearer ${l}`}:{},d=await fetch(i,{method:\"POST\",body:s,headers:o});if(!d.ok)throw new Error(\"Transcription failed\");return d.json()},voiceCommand:t=>k(\"/api/ai/voice-command\",{method:\"POST\",body:JSON.stringify(t)}),objectionResponse:t=>k(\"/api/ai/objection-response\",{method:\"POST\",body:JSON.stringify(t)}),getConversionProbability:t=>k(`/api/ai/conversion-probability/${t}`),weeklyInsights:()=>k(\"/api/ai/weekly-insights\",{method:\"POST\"}),cleanupNotes:t=>k(\"/api/ai/cleanup-notes\",{method:\"POST\",body:JSON.stringify(t)}),getInsights:()=>k(\"/api/ai/insights\"),getDeepgramCredentials:()=>k(\"/api/ai/deepgram-credentials\"),saveCopilotSession:t=>k(\"/api/ai/copilot-session\",{method:\"POST\",body:JSON.stringify(t)}),suggestionFeedback:t=>k(\"/api/ai/suggestion-feedback\",{method:\"POST\",body:JSON.stringify(t)}),getSimilarWins:t=>k(`/api/ai/similar-wins/${t}`),getEffectiveResponses:(t,s)=>{const i=s?`?trade=${encodeURIComponent(s)}`:\"\";return k(`/api/ai/effective-responses/${t}${i}`)},companyResearch:(t,s=!1)=>{const i=s?\"?refresh=true\":\"\";return k(`/api/ai/company-research/${encodeURIComponent(t)}${i}`)},personResearch:(t,s=!1)=>k(`/api/ai/person-research/${t}${s?\"?refresh=true\":\"\"}`),updateIntel:t=>k(\"/api/ai/update-intel\",{method:\"POST\",body:JSON.stringify(t)}),parseIntelVoiceNote:t=>k(\"/api/ai/parse-intel-voice\",{method:\"POST\",body:JSON.stringify(t)}),extractContractor:t=>k(\"/api/ai/extract-contractor\",{method:\"POST\",body:JSON.stringify(t)}),addContractorLead:t=>k(\"/api/ai/extract-contractor\",{method:\"POST\",body:JSON.stringify({...t,createLead:!0})}),extractLeadCorrections:t=>k(\"/api/ai/extract-lead-corrections\",{method:\"POST\",body:JSON.stringify(t)}),draftSimilar:t=>k(\"/api/ai/draft-similar\",{method:\"POST\",body:JSON.stringify(t)})},nR={status:()=>k(\"/api/sync/platform/status\"),stats:()=>k(\"/api/sync/platform/stats\"),syncAll:(t={})=>k(\"/api/sync/platform\",{method:\"POST\",body:JSON.stringify(t)}),syncRecent:()=>k(\"/api/sync/platform/recent\",{method:\"POST\"})},sR={getFunnel:()=>k(\"/api/activation/funnel\"),getLeadsAtStage:(t,s)=>{const i=new URLSearchParams({stage:t});return s&&i.append(\"type\",s),k(`/api/activation/leads-at-stage?${i}`)},getStuck:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/activation/stuck${s?`?${s}`:\"\"}`)},getRevenueAtRisk:()=>k(\"/api/activation/revenue-at-risk\"),getMetrics:(t=30)=>k(`/api/activation/metrics?days=${t}`),getTransitions:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/activation/stage-transitions${s?`?${s}`:\"\"}`)},analyze:()=>k(\"/api/activation/analyze\"),generateNudge:t=>k(\"/api/activation/nudge\",{method:\"POST\",body:JSON.stringify({leadId:t})}),bulkNudge:t=>k(\"/api/activation/bulk-nudge\",{method:\"POST\",body:JSON.stringify(t)}),addToCallList:t=>k(\"/api/activation/add-to-call-list\",{method:\"POST\",body:JSON.stringify(t)}),getActionScript:(t,s=\"contractor\")=>k(`/api/activation/action-script?stage=${t}&type=${s}`),getDropoffAnalysis:(t,s=\"contractor\")=>k(`/api/activation/dropoff-analysis?stage=${t}&type=${s}`),getNudgeTemplates:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/activation/nudge-templates${s?`?${s}`:\"\"}`)},createNudgeTemplate:t=>k(\"/api/activation/nudge-templates\",{method:\"POST\",body:JSON.stringify(t)}),updateNudgeTemplate:(t,s)=>k(`/api/activation/nudge-templates/${t}`,{method:\"PATCH\",body:JSON.stringify(s)}),deleteNudgeTemplate:t=>k(`/api/activation/nudge-templates/${t}`,{method:\"DELETE\"}),getJourney:t=>k(`/api/activation/journey/${t}`),getDiagnosis:t=>k(`/api/activation/diagnose/${t}`),getSimilarWins:(t,s=5)=>k(`/api/activation/similar-wins/${t}?limit=${s}`)},hc={list:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/scripts${s?`?${s}`:\"\"}`)},get:t=>k(`/api/scripts/${t}`),create:t=>k(\"/api/scripts\",{method:\"POST\",body:JSON.stringify(t)}),update:(t,s)=>k(`/api/scripts/${t}`,{method:\"PATCH\",body:JSON.stringify(s)}),delete:t=>k(`/api/scripts/${t}`,{method:\"DELETE\"}),startSession:(t,s)=>k(`/api/scripts/${t}/use`,{method:\"POST\",body:JSON.stringify({lead_id:s})}),endSession:(t,s)=>k(`/api/scripts/sessions/${t}`,{method:\"PATCH\",body:JSON.stringify(s)}),getForLead:t=>k(`/api/scripts/for-lead/${t}`),getAIRecommendation:t=>k(`/api/scripts/ai-recommend/${t}`),recordUsage:(t,s=!1)=>k(`/api/scripts/${t}/use`,{method:\"POST\",body:JSON.stringify({replied:s})}),getAnalytics:(t=30)=>k(`/api/scripts/analytics/overview?days=${t}`),getObjections:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/scripts/objections/list${s?`?${s}`:\"\"}`)},getObjection:t=>k(`/api/scripts/objections/${t}`),createObjection:t=>k(\"/api/scripts/objections\",{method:\"POST\",body:JSON.stringify(t)}),addObjectionResponse:(t,s)=>k(`/api/scripts/objections/${t}/response`,{method:\"POST\",body:JSON.stringify({response:s})}),getGuidelines:()=>k(\"/api/scripts/guidelines\"),updateGuidelines:t=>k(\"/api/scripts/guidelines\",{method:\"PUT\",body:JSON.stringify(t)}),getGuidelinesHistory:(t=20)=>k(`/api/scripts/guidelines/history?limit=${t}`),checkCompliance:(t,s={})=>k(\"/api/scripts/compliance/check\",{method:\"POST\",body:JSON.stringify({message:t,options:s})}),autoFix:t=>k(\"/api/scripts/compliance/auto-fix\",{method:\"POST\",body:JSON.stringify({message:t})}),validateScript:t=>k(`/api/scripts/compliance/validate/${t}`,{method:\"POST\"}),batchValidate:t=>k(\"/api/scripts/compliance/batch-validate\",{method:\"POST\",body:JSON.stringify({scriptIds:t})}),getComplianceStats:()=>k(\"/api/scripts/compliance/stats\"),getQueue:(t=\"pending\",s=20)=>k(`/api/scripts/compliance/queue?status=${t}&limit=${s}`),approveItem:t=>k(`/api/scripts/compliance/queue/${t}/approve`,{method:\"POST\"}),rejectItem:(t,s)=>k(`/api/scripts/compliance/queue/${t}/reject`,{method:\"POST\",body:JSON.stringify({reason:s})}),editItem:(t,s)=>k(`/api/scripts/compliance/queue/${t}/edit`,{method:\"POST\",body:JSON.stringify({final_content:s})})},aR={list:()=>k(\"/api/achievements\"),getUserAchievements:()=>k(\"/api/achievements/user\"),check:()=>k(\"/api/achievements/check\",{method:\"POST\"})},iR={getUser:()=>k(\"/api/xp/user\"),award:t=>k(\"/api/xp/award\",{method:\"POST\",body:JSON.stringify(t)}),getHistory:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/xp/history${s?`?${s}`:\"\"}`)},getLeaderboard:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/xp/leaderboard${s?`?${s}`:\"\"}`)}},Rx={list:t=>k(`/api/sequences${t?`?channel=${t}`:\"\"}`),get:t=>k(`/api/sequences/${t}`),enroll:(t,s)=>k(`/api/sequences/${t}/enroll`,{method:\"POST\",body:JSON.stringify({lead_ids:Array.isArray(s)?s:[s]})}),unenroll:(t,s)=>k(`/api/sequences/${t}/unenroll`,{method:\"POST\",body:JSON.stringify({lead_id:s})}),getActiveEnrollments:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/sequences/enrollments/active${s?`?${s}`:\"\"}`)},getLeadEnrollments:t=>k(`/api/sequences/enrollments/lead/${t}`),pauseEnrollment:(t,s)=>k(`/api/sequences/enrollments/${t}/pause`,{method:\"POST\",body:JSON.stringify({reason:s})}),resumeEnrollment:t=>k(`/api/sequences/enrollments/${t}/resume`,{method:\"POST\"}),skipStep:t=>k(`/api/sequences/enrollments/${t}/skip`,{method:\"POST\"}),sendNow:t=>k(`/api/sequences/enrollments/${t}/send-now`,{method:\"POST\"}),getOptOutStatus:t=>k(`/api/sequences/lead/${t}/opt-out`),setOptOut:(t,s)=>k(`/api/sequences/lead/${t}/opt-out`,{method:\"POST\",body:JSON.stringify({opted_out:s})}),bulkEnrollPreview:(t,s=100,i)=>{const l=new URLSearchParams({dry_run:\"true\",limit:s.toString()});return i&&l.set(\"source\",i),k(`/api/sequences/${t}/bulk-enroll?${l}`,{method:\"POST\"})},bulkEnroll:(t,s=100,i)=>{const l=new URLSearchParams({limit:s.toString()});return i&&l.set(\"source\",i),k(`/api/sequences/${t}/bulk-enroll?${l}`,{method:\"POST\"})}},lR={getScores:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/coaching/scores${s?`?${s}`:\"\"}`)},scoreCall:t=>k(\"/api/coaching/score\",{method:\"POST\",body:JSON.stringify(t)}),getTips:()=>k(\"/api/coaching/tips\"),getWeekly:()=>k(\"/api/coaching/weekly\"),getPatterns:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/coaching/patterns${s?`?${s}`:\"\"}`)}},rR={getTrends:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/analytics/trends${s?`?${s}`:\"\"}`)},getPatterns:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/analytics/patterns${s?`?${s}`:\"\"}`)},getFunnel:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/analytics/funnel${s?`?${s}`:\"\"}`)},getBestTimes:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/analytics/best-times${s?`?${s}`:\"\"}`)},getSources:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/analytics/sources${s?`?${s}`:\"\"}`)},savePattern:t=>k(\"/api/analytics/patterns\",{method:\"POST\",body:JSON.stringify(t)})},oR={list:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/ai-alerts${s?`?${s}`:\"\"}`)},create:t=>k(\"/api/ai-alerts\",{method:\"POST\",body:JSON.stringify(t)}),markRead:t=>k(`/api/ai-alerts/${t}/read`,{method:\"PATCH\"}),dismiss:t=>k(`/api/ai-alerts/${t}/dismiss`,{method:\"PATCH\"}),markAllRead:()=>k(\"/api/ai-alerts/read-all\",{method:\"POST\"}),generate:()=>k(\"/api/ai-alerts/generate\",{method:\"POST\"})},cR={getLeaderboard:(t=\"today\")=>k(`/api/battleground/leaderboard?period=${t}`),getUserStats:t=>k(`/api/battleground/leaderboard/${t}`),saveSnapshot:()=>k(\"/api/battleground/leaderboard/snapshot\",{method:\"POST\"}),getHallOfFame:()=>k(\"/api/battleground/hall-of-fame\"),checkRecord:(t,s,i,l,o)=>k(\"/api/battleground/hall-of-fame/check\",{method:\"POST\",body:JSON.stringify({recordType:t,userId:s,userName:i,value:l,details:o})}),getChallenges:()=>k(\"/api/battleground/challenges\"),updateChallengeProgress:(t,s=1)=>k(\"/api/battleground/challenges/progress\",{method:\"POST\",body:JSON.stringify({actionType:t,count:s})}),generateChallenges:()=>k(\"/api/battleground/challenges/generate\",{method:\"POST\"}),getTeamPulse:(t=20)=>k(`/api/battleground/pulse?limit=${t}`),createPulseEvent:t=>k(\"/api/battleground/pulse\",{method:\"POST\",body:JSON.stringify(t)}),getUserBadges:t=>k(`/api/battleground/badges/${t}`),getCurrentBadges:()=>k(\"/api/battleground/badges\"),awardWeeklyBadges:()=>k(\"/api/battleground/badges/award-weekly\",{method:\"POST\"}),updateStreakTier:(t,s)=>k(\"/api/battleground/streak/update\",{method:\"POST\",body:JSON.stringify({userId:t,streakDays:s})}),getActiveDuels:()=>k(\"/api/battleground/duels/active\"),getDuelHistory:(t=10)=>k(`/api/battleground/duels/history?limit=${t}`),getDuelOdds:(t,s)=>k(`/api/battleground/duels/odds?targetId=${t}&duelType=${s}`),createDuel:(t,s,i)=>k(\"/api/battleground/duels/challenge\",{method:\"POST\",body:JSON.stringify({targetId:t,duelType:s,stakeAmount:i})}),acceptDuel:t=>k(`/api/battleground/duels/${t}/accept`,{method:\"POST\"}),declineDuel:t=>k(`/api/battleground/duels/${t}/decline`,{method:\"POST\"}),getDuelScores:t=>k(`/api/battleground/duels/${t}/scores`),createChallenge:t=>k(\"/api/battleground/challenges\",{method:\"POST\",body:JSON.stringify(t)}),joinChallenge:t=>k(`/api/battleground/challenges/${t}/join`,{method:\"POST\"}),getChallengeDetails:t=>k(`/api/battleground/challenges/${t}`),getTeam:()=>k(\"/api/battleground/team\"),getCelebrations:(t=10)=>k(`/api/battleground/celebrations?limit=${t}`)},uR={getToday:()=>k(\"/api/playbook/today\"),send:(t,s,i)=>k(\"/api/playbook/send\",{method:\"POST\",body:JSON.stringify({leadId:t,messageId:s,messageText:i})}),getBulkPreview:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/playbook/bulk-preview${s?`?${s}`:\"\"}`)},bulkSend:(t,s,i={})=>k(\"/api/playbook/bulk-send\",{method:\"POST\",body:JSON.stringify({batchId:t,leadIds:s,edits:i})})},Mx={getRecordings:()=>k(\"/api/voicemail/recordings\"),createRecording:async t=>{const s=await Zh(),i=await fetch(`${Qh}/api/voicemail/recordings`,{method:\"POST\",headers:{Authorization:`Bearer ${s}`},body:t});if(!i.ok){const l=await i.json().catch(()=>({error:\"Upload failed\"}));throw new Error(l.error||\"Failed to upload\")}return i.json()},createRecordingFromUrl:t=>k(\"/api/voicemail/recordings\",{method:\"POST\",body:JSON.stringify(t)}),deleteRecording:t=>k(`/api/voicemail/recordings/${t}`,{method:\"DELETE\"}),setDefault:t=>k(`/api/voicemail/recordings/${t}/default`,{method:\"PATCH\"}),drop:(t,s,i)=>k(\"/api/voicemail/drop\",{method:\"POST\",body:JSON.stringify({callSid:t,recordingId:s,leadId:i})}),getStats:()=>k(\"/api/voicemail/drops/stats\")},dR={getDashboard:(t=\"week\")=>k(`/api/manager/dashboard?period=${t}`),getAnalytics:(t=\"week\")=>k(`/api/manager/analytics?period=${t}`),getRepDetail:(t,s=\"week\")=>k(`/api/manager/rep/${t}?period=${s}`)},fR={getDashboard:()=>k(\"/api/intelligence/dashboard\"),track:t=>k(\"/api/intelligence/track\",{method:\"POST\",body:JSON.stringify(t)}),trackBatch:t=>k(\"/api/intelligence/track-batch\",{method:\"POST\",body:JSON.stringify({events:t})}),getSuggestions:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/intelligence/suggestions${s?`?${s}`:\"\"}`)},updateSuggestionStatus:(t,s)=>k(`/api/intelligence/suggestions/${t}/status`,{method:\"PATCH\",body:JSON.stringify(s)}),getFriction:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/intelligence/friction${s?`?${s}`:\"\"}`)},getPageStats:(t=7)=>k(`/api/intelligence/page-stats?days=${t}`),getMetrics:(t,s,i)=>{const l=new URLSearchParams({start_date:t});return s&&l.append(\"end_date\",s),i&&l.append(\"metric_name\",i),k(`/api/intelligence/metrics?${l}`)}},Ox={getVapidKey:()=>k(\"/api/notifications/vapid-public-key\"),subscribe:t=>k(\"/api/notifications/subscribe\",{method:\"POST\",body:JSON.stringify({subscription:t})}),unsubscribe:(t=null)=>k(\"/api/notifications/unsubscribe\",{method:\"DELETE\",body:JSON.stringify({endpoint:t})}),getPreferences:()=>k(\"/api/notifications/preferences\"),updatePreferences:t=>k(\"/api/notifications/preferences\",{method:\"PUT\",body:JSON.stringify(t)}),test:()=>k(\"/api/notifications/test\",{method:\"POST\"}),getStatus:()=>k(\"/api/notifications/status\")},qn=[{id:\"opener\",label:\"Opener\",icon:\"👋\"},{id:\"discovery\",label:\"Discovery\",icon:\"🔍\"},{id:\"value_prop\",label:\"Value Prop\",icon:\"💎\"},{id:\"objections\",label:\"Objections\",icon:\"🛡️\"},{id:\"close\",label:\"Close\",icon:\"🎯\"}],uE={opener:{script:\"Hey, it's [your name] from RateRight. How's it going?\",tip:\"Be warm and conversational. Match their energy.\",alternatives:[\"Hi [name], this is [you] from RateRight - got a quick minute?\",\"G'day [name], [you] here from RateRight. How's business?\"]},discovery:{script:\"What's your biggest challenge finding workers right now?\",tip:\"Listen more than you talk. Take mental notes.\",alternatives:[\"How are you currently sourcing your workers?\",\"What trades are hardest to find good people for?\",\"How many workers do you typically need on a job?\"]},value_prop:{script:\"We connect you with pre-vetted workers at just 9.9% - no lock-in contracts.\",tip:\"Focus on their pain points. Make it about them.\",alternatives:[\"Most of our contractors find workers within 24 hours.\",\"You only pay when they work - no upfront fees.\",\"Every worker is vetted with references and qualifications checked.\"]},objections:{script:\"I hear you. What would need to change for this to make sense?\",tip:\"Don't argue. Acknowledge and redirect.\",alternatives:[\"That's a fair point. Here's how other contractors handle that...\",\"I understand. Can I ask what you're comparing us to?\",\"Makes sense. What if we could address that concern?\"]},close:{script:\"Let me get you set up - it takes about 2 minutes. What's your email?\",tip:\"Assume the sale. Be confident.\",alternatives:[\"When's your next job starting? Let's get you ready.\",\"I'll send you the link now - what email should I use?\",\"Want me to walk you through it while we're on the phone?\"]}};function dE({lead:t,duration:s,onHangUp:i,onMute:l,isMuted:o,onMarkHot:d}){const[f,m]=b.useState(0),[p,y]=b.useState(null),[x,g]=b.useState(null),[w,S]=b.useState(!1),[T,N]=b.useState([]),[R,D]=b.useState(null),[A,C]=b.useState([]);b.useEffect(()=>{t?.id&&(B(),_())},[t?.id]);const B=async()=>{try{const $=await hc.getRecommendation(t.id);$?.script&&y($.script)}catch{console.log(\"Using default scripts\")}},_=async()=>{try{const $=await It.getIntelBrief(t.id);if($){D($);const W=[];$.openingLine&&W.push({type:\"opener\",text:$.openingLine}),$.talkingPoints?.length&&$.talkingPoints.forEach(se=>W.push({type:\"point\",text:se})),$.similarWins?.length&&W.push({type:\"win\",text:`Similar win: ${$.similarWins[0].name} - \"${$.similarWins[0].whatWorked}\"`}),$.company?.sales_angle&&W.push({type:\"angle\",text:$.company.sales_angle}),C(W)}}catch{console.log(\"Intel not available\")}},F=$=>{const W=uE[$];if(!p)return W;switch($){case\"opener\":return{...W,script:p.opening||W.script};case\"discovery\":return{...W,script:p.discovery_questions?.[0]?.question||W.script,alternatives:p.discovery_questions?.slice(1,4).map(se=>se.question)||W.alternatives};case\"value_prop\":return{...W,script:p.value_props?.[0]?.prop||W.script,alternatives:p.value_props?.slice(1,4).map(se=>se.prop)||W.alternatives};case\"objections\":return W;case\"close\":return{...W,script:p.closing_techniques?.[0]?.script||W.script,alternatives:p.closing_techniques?.slice(1,4).map(se=>se.script)||W.alternatives};default:return W}},P=async($,W)=>{await navigator.clipboard.writeText($),g(W),setTimeout(()=>g(null),500)},H=()=>{f{m($)},X=()=>{S(!0),d?.()},te=$=>{const W=Math.floor($/60),se=$%60;return`${W}:${se.toString().padStart(2,\"0\")}`},Y=`${t?.first_name||\"\"} ${t?.last_name||\"\"}`.trim()||\"Unknown\";return c.jsxs(\"div\",{className:\"fixed inset-0 z-[60] bg-slate-900 flex flex-col\",children:[c.jsxs(\"div\",{className:\"bg-slate-800 px-4 py-3 flex items-center justify-between safe-area-top\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-3\",children:[c.jsx(\"div\",{className:\"w-10 h-10 rounded-full bg-slate-700 flex items-center justify-center\",children:c.jsx(cr,{className:\"w-5 h-5 text-slate-400\"})}),c.jsxs(\"div\",{children:[c.jsx(\"h2\",{className:\"font-bold text-white\",children:Y}),c.jsxs(\"div\",{className:\"flex items-center gap-2\",children:[c.jsx(\"div\",{className:\"w-2 h-2 rounded-full bg-green-500 animate-pulse\"}),c.jsx(\"span\",{className:\"text-green-400 font-mono text-sm\",children:te(s)})]})]})]}),c.jsx(\"button\",{onClick:X,disabled:w,className:`p-2 rounded-full ${w?\"bg-amber-500 text-white\":\"bg-slate-700 text-slate-400\"}`,children:c.jsx(nl,{className:\"w-5 h-5\"})})]}),c.jsx(\"div\",{className:\"bg-slate-800/50 px-4 py-3 flex items-center gap-2\",children:qn.map(($,W)=>c.jsxs(\"button\",{onClick:()=>z(W),className:`flex-1 py-2 rounded-lg text-center transition-all ${T.includes(W)?\"bg-emerald-600 text-white\":W===f?\"bg-violet-600 text-white ring-2 ring-violet-400\":\"bg-slate-700/50 text-slate-400\"}`,children:[c.jsx(\"span\",{className:\"text-lg\",children:$.icon}),c.jsx(\"p\",{className:\"text-[10px] font-bold mt-0.5\",children:T.includes(W)?\"✓\":$.label})]},$.id))}),c.jsx(\"div\",{className:\"flex-1 overflow-y-auto pb-40\",children:c.jsxs(\"div\",{className:\"p-4 space-y-4\",children:[A.length>0&&c.jsxs(\"div\",{className:\"bg-blue-500/10 border border-blue-500/20 rounded-xl p-3\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-2 mb-2\",children:[c.jsx(ac,{className:\"w-4 h-4 text-blue-400\"}),c.jsx(\"span\",{className:\"text-xs font-bold text-blue-400 uppercase\",children:\"Intel & Talking Points\"})]}),c.jsx(\"div\",{className:\"space-y-2\",children:A.slice(0,4).map(($,W)=>c.jsxs(\"div\",{className:\"flex items-start gap-2\",children:[c.jsx(\"span\",{className:\"text-blue-400 mt-0.5\",children:$.type===\"opener\"?\"💬\":$.type===\"win\"?\"🏆\":$.type===\"angle\"?\"🎯\":\"•\"}),c.jsx(\"p\",{className:\"text-blue-200/80 text-sm\",children:$.text})]},W))})]}),R?.company?.name&&c.jsxs(\"div\",{className:\"flex items-center gap-2 px-1\",children:[c.jsx(jc,{className:\"w-4 h-4 text-slate-500\"}),c.jsxs(\"span\",{className:\"text-slate-400 text-sm\",children:[R.company.name,R.company.industry&&` • ${R.company.industry}`,R.company.size&&` • ${R.company.size}`]})]}),c.jsxs(\"div\",{className:\"text-center py-2\",children:[c.jsx(\"span\",{className:\"text-3xl\",children:qn[f].icon}),c.jsx(\"h3\",{className:\"text-xl font-bold text-white mt-2\",children:qn[f].label}),c.jsxs(\"p\",{className:\"text-slate-400 text-sm\",children:[\"Stage \",f+1,\" of \",qn.length]})]}),c.jsxs(\"div\",{className:\"bg-gradient-to-br from-violet-600/20 to-purple-600/10 border border-violet-500/30 rounded-2xl p-4\",children:[c.jsxs(\"div\",{className:\"flex items-start justify-between mb-2\",children:[c.jsx(\"span\",{className:\"text-xs font-bold text-violet-400 uppercase\",children:\"Say This\"}),c.jsx(\"button\",{onClick:()=>P(F(qn[f].id).script,\"main\"),className:\"p-2 -m-2 text-slate-400 hover:text-white\",children:x===\"main\"?c.jsx(ba,{className:\"w-4 h-4 text-green-400\"}):c.jsx(Cf,{className:\"w-4 h-4\"})})]}),c.jsxs(\"p\",{className:\"text-white text-lg leading-relaxed\",children:['\"',F(qn[f].id).script,'\"']})]}),c.jsxs(\"div\",{className:\"bg-amber-500/10 border border-amber-500/20 rounded-xl px-4 py-3\",children:[c.jsx(\"span\",{className:\"text-xs font-bold text-amber-400 uppercase\",children:\"💡 Tip\"}),c.jsx(\"p\",{className:\"text-amber-200/80 text-sm mt-1\",children:F(qn[f].id).tip})]}),c.jsxs(\"div\",{children:[c.jsx(\"h4\",{className:\"text-sm font-bold text-slate-400 mb-2 px-1\",children:\"Or Try These:\"}),c.jsx(\"div\",{className:\"space-y-2\",children:F(qn[f].id).alternatives.map(($,W)=>c.jsxs(\"div\",{className:\"bg-slate-800/50 border border-slate-700 rounded-xl p-3 flex items-start gap-3\",children:[c.jsxs(\"p\",{className:\"text-slate-300 text-sm flex-1\",children:['\"',$,'\"']}),c.jsx(\"button\",{onClick:()=>P($,`alt-${W}`),className:\"p-1 text-slate-500 hover:text-white flex-shrink-0\",children:x===`alt-${W}`?c.jsx(ba,{className:\"w-4 h-4 text-green-400\"}):c.jsx(Cf,{className:\"w-4 h-4\"})})]},W))})]}),f(i&&s?W(s):se(),()=>{ie()}),[]);const W=ee=>{console.log(\"[TwilioCall] Attaching to inbound call\"),X.current=ee,p(\"in-progress\"),Y.current=Date.now(),I();const ge=ee.parameters?.CallSid||null;console.log(\"[TwilioCall] Inbound call CallSid:\",ge),d?.(ge),ee.on(\"disconnect\",()=>{const Ee=Y.current?Math.floor((Date.now()-Y.current)/1e3):0;console.log(\"[TwilioCall] Inbound call disconnected, duration:\",Ee),p(\"ended\"),K(),$.current||($.current=!0,setTimeout(()=>{o?.(Ee)},500))}),ee.on(\"error\",Ee=>{console.error(\"[TwilioCall] Inbound call error:\",Ee),T(Ee.message),p(\"ended\"),K()})},se=async()=>{try{const{token:ee}=await nc.getToken(),ge=new Cb(ee,{logLevel:\"debug\",codecPreferences:[\"opus\",\"pcmu\"],enableRingingState:!0,edge:\"ashburn\"});ge.on(\"error\",Ee=>{console.error(\"Twilio Device error:\",Ee),T(Ee.message),p(\"ended\")}),z.current=ge,p(\"ready\"),O()}catch(ee){console.error(\"Failed to initialize Twilio:\",ee),T(ee.message),p(\"ended\")}},O=async()=>{if(z.current){if(!t?.phone){T(\"No phone number for this lead\"),p(\"ended\");return}try{p(\"connecting\");const ee=await z.current.connect({params:{To:t.phone,leadId:t?.id}});X.current=ee,ee.on(\"ringing\",()=>{p(\"ringing\")}),ee.on(\"accept\",()=>{p(\"in-progress\"),Y.current=Date.now(),I();const ge=ee.parameters?.CallSid||null;console.log(\"[TwilioCall] Call connected, CallSid:\",ge),d?.(ge)}),ee.on(\"disconnect\",()=>{const ge=Y.current?Math.floor((Date.now()-Y.current)/1e3):0;p(\"ended\"),K(),$.current||($.current=!0,setTimeout(()=>{o?.(ge)},500))}),ee.on(\"cancel\",()=>{p(\"ended\"),K(),$.current||($.current=!0,o?.(0))}),ee.on(\"error\",ge=>{console.error(\"Call error:\",ge),T(ge.message),p(\"ended\"),K()})}catch(ee){console.error(\"Failed to make call:\",ee),T(ee.message),p(\"ended\")}}},I=()=>{te.current=setInterval(()=>{Y.current&&x(Math.floor((Date.now()-Y.current)/1e3))},1e3)},K=()=>{te.current&&(clearInterval(te.current),te.current=null)},ie=()=>{K(),!i&&X.current&&X.current.disconnect(),!i&&z.current&&z.current.destroy()},oe=()=>{X.current?X.current.disconnect():l?.()},xe=()=>{X.current&&(g?X.current.mute(!1):X.current.mute(!0),w(!g))},Te=async()=>{if(!(D.length>0)){B(!0);try{const ee=await Mx.getRecordings();A(ee||[])}catch(ee){console.error(\"Failed to load VM recordings:\",ee)}finally{B(!1)}}},ae=async ee=>{const ge=X.current?.parameters?.CallSid;if(!ge){console.error(\"No CallSid available\");return}F(!0);try{await Mx.drop(ge,ee.id,t?.id),H(!0),R(!1)}catch(Ee){console.error(\"VM drop failed:\",Ee),T(\"Failed to drop voicemail\")}finally{F(!1)}},ce=ee=>{const ge=Math.floor(ee/60),Ee=ee%60;return`${ge}:${Ee.toString().padStart(2,\"0\")}`},ne=()=>{switch(m){case\"initializing\":return\"Setting up...\";case\"ready\":return\"Starting call...\";case\"connecting\":return\"Connecting...\";case\"ringing\":return\"Ringing...\";case\"in-progress\":return ce(y);case\"ended\":return\"Call ended\";default:return\"\"}},ue=()=>{switch(m){case\"ringing\":return\"text-amber-400\";case\"in-progress\":return\"text-green-400\";case\"ended\":return\"text-slate-400\";default:return\"text-blue-400\"}},de=`${t?.first_name||\"\"} ${t?.last_name||\"\"}`.trim()||\"Unknown\";return m===\"in-progress\"&&t?c.jsx(dE,{lead:t,duration:y,isMuted:g,onMute:xe,onHangUp:oe,onMarkHot:()=>{console.log(\"Marked hot during call\")}}):c.jsxs(Le.div,{initial:{y:100,opacity:0},animate:{y:0,opacity:1},exit:{y:100,opacity:0},className:\"fixed bottom-0 inset-x-0 z-[60] bg-gradient-to-t from-slate-900 via-slate-900 to-slate-900/95 rounded-t-3xl shadow-2xl pb-safe\",children:[c.jsxs(\"div\",{className:\"px-4 pt-4 pb-2 flex items-center gap-3\",children:[c.jsx(\"div\",{className:\"w-12 h-12 rounded-full bg-slate-700 flex items-center justify-center flex-shrink-0\",children:c.jsx(cr,{className:\"w-6 h-6 text-slate-400\"})}),c.jsxs(\"div\",{className:\"flex-1 min-w-0\",children:[c.jsx(\"h2\",{className:\"text-lg font-bold text-white truncate\",children:de}),c.jsxs(\"div\",{className:\"flex items-center gap-2\",children:[c.jsx(\"span\",{className:`text-sm font-medium ${ue()}`,children:ne()}),m===\"in-progress\"&&f&&c.jsxs(\"div\",{className:\"flex items-center gap-1\",children:[c.jsx(Yj,{className:\"w-3 h-3 text-emerald-400 animate-pulse\"}),c.jsx(\"span\",{className:\"text-xs text-emerald-400\",children:\"Recording\"})]})]})]}),m===\"ringing\"&&c.jsx(\"div\",{className:\"relative w-8 h-8\",children:c.jsx(Le.div,{className:\"absolute inset-0 rounded-full border-2 border-amber-400/50\",animate:{scale:[1,1.5],opacity:[.5,0]},transition:{duration:1.5,repeat:1/0}})})]}),S&&c.jsx(\"p\",{className:\"text-red-400 text-sm text-center px-4 pb-2\",children:S}),c.jsx(\"div\",{className:\"px-4 pb-6 pt-2\",children:m!==\"ended\"?c.jsxs(\"div\",{className:\"flex items-center justify-center gap-6\",children:[c.jsx(\"button\",{onClick:xe,disabled:m!==\"in-progress\",title:g?\"Unmute\":\"Mute\",className:`w-14 h-14 rounded-full flex items-center justify-center transition-colors ${g?\"bg-red-500 text-white\":\"bg-slate-700 text-white disabled:opacity-50\"}`,children:g?c.jsx(Tc,{className:\"w-6 h-6\"}):c.jsx(ti,{className:\"w-6 h-6\"})}),c.jsx(\"button\",{onClick:oe,title:\"End call\",className:\"w-16 h-16 rounded-full bg-red-500 text-white flex items-center justify-center shadow-lg shadow-red-500/30 active:scale-95 transition-transform\",children:c.jsx(ur,{className:\"w-8 h-8\"})}),c.jsx(\"button\",{onClick:()=>{R(!0),Te()},disabled:m===\"initializing\"||m===\"connecting\"||P,title:P?\"Voicemail dropped!\":\"Drop voicemail\",className:`w-14 h-14 rounded-full flex items-center justify-center transition-colors ${P?\"bg-green-600 text-white\":\"bg-amber-600 text-white disabled:opacity-50\"}`,children:P?c.jsx(ba,{className:\"w-6 h-6\"}):c.jsx(ey,{className:\"w-6 h-6\"})})]}):c.jsx(\"button\",{onClick:()=>{$.current||($.current=!0,o?.(y))},className:\"w-full py-4 bg-blue-600 text-white rounded-xl font-bold text-lg\",children:\"Continue\"})}),c.jsx(si,{children:N&&c.jsx(Le.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:\"fixed inset-0 z-[70] bg-black/60 flex items-end justify-center\",onClick:()=>R(!1),children:c.jsxs(Le.div,{initial:{y:\"100%\"},animate:{y:0},exit:{y:\"100%\"},className:\"w-full max-w-md bg-slate-800 rounded-t-2xl p-4 pb-8\",onClick:ee=>ee.stopPropagation(),children:[c.jsxs(\"div\",{className:\"flex items-center justify-between mb-4\",children:[c.jsx(\"h3\",{className:\"text-lg font-bold text-white\",children:\"Drop Voicemail\"}),c.jsx(\"button\",{onClick:()=>R(!1),className:\"w-8 h-8 rounded-full bg-slate-700 flex items-center justify-center\",children:c.jsx(Gt,{className:\"w-5 h-5 text-slate-400\"})})]}),C?c.jsx(\"div\",{className:\"flex items-center justify-center py-8\",children:c.jsx(_n,{className:\"w-6 h-6 text-blue-400 animate-spin\"})}):D.length===0?c.jsxs(\"div\",{className:\"text-center py-8 text-slate-400\",children:[\"No voicemail recordings yet.\",c.jsx(\"br\",{}),c.jsx(\"span\",{className:\"text-sm\",children:\"Add recordings in Settings → Voicemail\"})]}):c.jsx(\"div\",{className:\"space-y-2 max-h-64 overflow-y-auto\",children:D.map(ee=>c.jsxs(\"button\",{onClick:()=>ae(ee),disabled:_,className:\"w-full p-3 bg-slate-700/50 rounded-xl flex items-center gap-3 hover:bg-slate-700 transition-colors disabled:opacity-50\",children:[c.jsx(\"div\",{className:\"w-10 h-10 rounded-full bg-amber-600/20 flex items-center justify-center flex-shrink-0\",children:c.jsx(ey,{className:\"w-5 h-5 text-amber-400\"})}),c.jsxs(\"div\",{className:\"flex-1 text-left\",children:[c.jsx(\"p\",{className:\"text-white font-medium\",children:ee.name}),ee.description&&c.jsx(\"p\",{className:\"text-slate-400 text-sm truncate\",children:ee.description})]}),ee.is_default&&c.jsx(\"span\",{className:\"text-xs bg-blue-600/30 text-blue-400 px-2 py-0.5 rounded\",children:\"Default\"}),_&&c.jsx(_n,{className:\"w-4 h-4 text-blue-400 animate-spin\"})]},ee.id))}),c.jsx(\"p\",{className:\"text-xs text-slate-500 text-center mt-4\",children:\"Selecting a voicemail will play it to the recipient and end the call\"})]})})})]})}function hE({candidate:t,sourceLeadId:s,onAdd:i,onDismiss:l}){const{user:o}=br(),[d,f]=b.useState(!1),m=async()=>{f(!0);try{const x=await It.addContractorLead({sourceLeadId:s,companyName:t.company,projectName:t.project,userEmail:o?.email||\"unknown\"});x.success&&x.lead_id?i(x.lead_id,t):alert(\"Failed to create lead\")}catch(x){console.error(\"Add contractor error:\",x),alert(\"Failed to create lead: \"+x.message)}finally{f(!1)}},p=`${t.first_name||\"\"} ${t.last_name||\"\"}`.trim(),y=Math.round((t.confidence||.5)*100);return c.jsxs(\"div\",{className:\"fixed inset-0 z-50 flex items-center justify-center p-4\",children:[c.jsx(\"div\",{className:\"absolute inset-0 bg-black/60 backdrop-blur-sm\",onClick:l}),c.jsxs(\"div\",{className:\"relative w-full max-w-sm bg-white rounded-2xl shadow-2xl overflow-hidden animate-fade-in\",children:[c.jsx(\"div\",{className:\"bg-gradient-to-r from-amber-500 to-orange-500 px-5 py-4\",children:c.jsxs(\"div\",{className:\"flex items-center justify-between\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-3\",children:[c.jsx(\"div\",{className:\"w-10 h-10 bg-white/20 rounded-xl flex items-center justify-center\",children:c.jsx(nl,{className:\"w-5 h-5 text-white\"})}),c.jsxs(\"div\",{children:[c.jsx(\"h2\",{className:\"text-white font-bold text-lg\",children:\"Contractor Found!\"}),c.jsxs(\"p\",{className:\"text-white/80 text-sm\",children:[y,\"% confidence\"]})]})]}),c.jsx(\"button\",{onClick:l,className:\"w-8 h-8 bg-white/20 rounded-full flex items-center justify-center\",children:c.jsx(Gt,{className:\"w-4 h-4 text-white\"})})]})}),c.jsxs(\"div\",{className:\"p-5\",children:[c.jsxs(\"div\",{className:\"text-center mb-4\",children:[c.jsx(\"h3\",{className:\"text-xl font-bold text-slate-900\",children:p||\"Unknown\"}),t.job_title&&c.jsxs(\"div\",{className:\"flex items-center justify-center gap-2 mt-1 text-slate-600\",children:[c.jsx(Eb,{className:\"w-4 h-4\"}),c.jsx(\"span\",{children:t.job_title})]})]}),c.jsxs(\"div\",{className:\"bg-slate-50 rounded-xl p-4 mb-4 space-y-2\",children:[t.company&&c.jsxs(\"div\",{className:\"flex items-center gap-2 text-slate-700\",children:[c.jsx(Fj,{className:\"w-4 h-4 text-slate-400\"}),c.jsx(\"span\",{className:\"font-semibold\",children:t.company})]}),t.project&&c.jsxs(\"div\",{className:\"flex items-center gap-2 text-slate-600\",children:[c.jsx(ty,{className:\"w-4 h-4 text-slate-400\"}),c.jsxs(\"span\",{children:[t.project,\" Project\"]})]}),t.location&&c.jsxs(\"div\",{className:\"flex items-center gap-2 text-slate-500 text-sm\",children:[c.jsx(ty,{className:\"w-4 h-4 text-slate-400\"}),c.jsx(\"span\",{children:t.location})]})]}),t.linkedin_url&&c.jsxs(\"a\",{href:t.linkedin_url,target:\"_blank\",rel:\"noopener noreferrer\",className:\"flex items-center justify-center gap-2 mb-4 py-2 bg-[#0A66C2] text-white rounded-lg text-sm font-medium hover:bg-[#004182]\",children:[c.jsx(Xj,{className:\"w-4 h-4\"}),\"View LinkedIn Profile\"]}),t.source_worker&&c.jsx(\"div\",{className:\"bg-amber-50 rounded-lg p-3 mb-4 border border-amber-200\",children:c.jsxs(\"p\",{className:\"text-sm text-amber-800\",children:[c.jsx(\"span\",{className:\"font-semibold\",children:\"Source:\"}),\" Worker intel from \",t.source_worker]})}),c.jsxs(\"div\",{className:\"flex gap-3\",children:[c.jsx(\"button\",{onClick:l,className:\"flex-1 py-3 bg-slate-100 text-slate-700 rounded-xl font-semibold hover:bg-slate-200\",children:\"Dismiss\"}),c.jsxs(\"button\",{onClick:m,disabled:d,className:\"flex-1 py-3 bg-gradient-to-r from-green-500 to-emerald-500 text-white rounded-xl font-semibold flex items-center justify-center gap-2 hover:from-green-600 hover:to-emerald-600 disabled:opacity-50\",children:[d?c.jsx(_n,{className:\"w-5 h-5 animate-spin\"}):c.jsx(Af,{className:\"w-5 h-5\"}),\"Add as Lead\"]})]})]})]})]})}function mE(t){const s=Math.floor(t/60),i=t%60;return`${s}:${i.toString().padStart(2,\"0\")}`}const pE={opener:\"Opener\",discovery:\"Discovery\",value_prop:\"Value Props\",objections:\"Objections\",close:\"Close\"},_x=[\"opener\",\"discovery\",\"value_prop\",\"objections\",\"close\"];function gE({duration:t,leadName:s,isListening:i,onMinimize:l}){return c.jsxs(\"div\",{className:\"bg-slate-800 px-4 py-3 flex items-center justify-between safe-area-top\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-3\",children:[c.jsx(\"div\",{className:`w-2.5 h-2.5 rounded-full ${i?\"bg-red-500 animate-pulse\":\"bg-slate-500\"}`}),c.jsx(\"span\",{className:\"text-white font-mono text-lg font-bold tabular-nums\",children:mE(t)})]}),c.jsx(\"span\",{className:\"text-white font-medium truncate max-w-32\",children:s||\"Unknown\"}),c.jsx(\"button\",{onClick:l,className:\"p-2 -mr-2 text-slate-400 hover:text-white\",children:c.jsx(Kj,{className:\"w-5 h-5\"})})]})}function yE({intel:t}){const s=t?.personal_intel?.conversation_starters||t?.person?.conversation_starters||[],i=t?.personal_intel?.interest_news||t?.interest_news,l=[];return i?.items?.length>0&&i.items.slice(0,2).forEach(o=>{l.push({type:\"news\",text:o.talking_point||o.headline,source:o.topic||o.source,emoji:o.topic?.toLowerCase().includes(\"liverpool\")?\"⚽\":o.topic?.toLowerCase().includes(\"f1\")?\"🏎️\":o.topic?.toLowerCase().includes(\"gaa\")?\"🏐\":\"📰\"})}),s.slice(0,3-l.length).forEach(o=>{l.push({type:\"starter\",text:typeof o==\"string\"?o:o.text,source:typeof o==\"string\"?null:o.topic,emoji:\"💬\"})}),l.length===0?null:c.jsxs(\"div\",{className:\"bg-gradient-to-r from-blue-500/20 to-purple-500/20 border border-blue-500/30 rounded-2xl p-3\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-2 mb-2\",children:[c.jsx(\"span\",{className:\"text-sm\",children:\"🎯\"}),c.jsx(\"span\",{className:\"text-xs font-bold text-blue-300 uppercase tracking-wide\",children:\"Ice Breakers\"})]}),c.jsx(\"div\",{className:\"space-y-2\",children:l.map((o,d)=>c.jsxs(\"div\",{className:\"flex items-start gap-2\",children:[c.jsx(\"span\",{className:\"text-base flex-shrink-0\",children:o.emoji}),c.jsxs(\"div\",{className:\"flex-1 min-w-0\",children:[c.jsxs(\"p\",{className:\"text-white text-sm leading-snug\",children:['\"',o.text,'\"']}),o.source&&c.jsx(\"p\",{className:\"text-slate-400 text-xs mt-0.5\",children:o.source})]})]},d))})]})}function xE({stage:t,script:s,openingLine:i}){const[l,o]=b.useState(!1),d=_x.indexOf(t),m=(()=>{if(!s)return i||\"Hey, it's [your name] from RateRight. How's it going?\";switch(t){case\"opener\":return s.opening||i||\"Hey, it's [your name] from RateRight. How's it going?\";case\"discovery\":return s.discovery_questions?.[0]?.question||\"What's your biggest challenge finding workers right now?\";case\"value_prop\":return s.value_props?.[0]?.prop||\"We connect you with pre-vetted workers at just 9.9% - no lock-in contracts.\";case\"objections\":return\"Listen for concerns and address them directly.\";case\"close\":return s.closing_techniques?.[0]?.script||\"Let me get you set up - it takes about 2 minutes. What's your email?\";default:return s.opening||\"Start the conversation...\"}})(),p=async()=>{await navigator.clipboard.writeText(m),o(!0),setTimeout(()=>o(!1),500)};return c.jsxs(\"div\",{className:\"bg-slate-800/50 border border-slate-700 rounded-2xl p-4 relative\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-2 mb-3\",children:[c.jsx(\"span\",{className:\"text-xs font-bold text-violet-400 uppercase tracking-wide\",children:pE[t]||\"Script\"}),c.jsx(\"div\",{className:\"flex-1 h-px bg-slate-700\"}),c.jsxs(\"span\",{className:\"text-xs text-slate-500\",children:[d+1,\"/\",_x.length]})]}),c.jsxs(\"p\",{className:\"text-white text-base leading-relaxed pr-8\",children:['\"',m,'\"']}),c.jsx(\"button\",{onClick:p,className:\"absolute top-4 right-4 p-2 text-slate-400 hover:text-white transition-colors\",children:l?c.jsx(ba,{className:\"w-4 h-4 text-green-400\"}):c.jsx(Cf,{className:\"w-4 h-4\"})})]})}function bE({company:t,person:s,onExpand:i}){if(!t&&!s)return null;const l=[];return t?.name&&l.push(t.name),t?.industry&&l.push(t.industry),t?.size?l.push(t.size):s?.job_title&&l.push(s.job_title),l.length===0?null:c.jsxs(\"button\",{onClick:i,className:\"bg-slate-800/30 border border-slate-700/50 rounded-xl px-4 py-2.5 flex items-center gap-3 w-full text-left\",children:[c.jsx(jc,{className:\"w-4 h-4 text-blue-400 flex-shrink-0\"}),c.jsx(\"span\",{className:\"text-sm text-slate-300 truncate flex-1\",children:l.join(\" • \")}),c.jsx(Ab,{className:\"w-4 h-4 text-slate-500 flex-shrink-0\"})]})}function vE({type:t,trigger:s,suggestion:i,onDismiss:l}){const o=t===\"buying_signal\";return c.jsxs(Le.div,{initial:{y:100,opacity:0,scale:.95},animate:{y:0,opacity:1,scale:1},exit:{y:100,opacity:0,scale:.95},transition:{type:\"spring\",damping:25,stiffness:300},className:`w-full rounded-2xl overflow-hidden relative ${o?\"bg-gradient-to-br from-emerald-500/20 to-green-500/10 border border-emerald-500/50\":\"bg-gradient-to-br from-amber-500/20 to-orange-500/10 border border-amber-500/50\"}`,children:[c.jsxs(\"div\",{className:`px-4 py-2 flex items-center gap-2 ${o?\"bg-emerald-500/30\":\"bg-amber-500/30\"}`,children:[c.jsx(\"span\",{className:\"text-lg\",children:o?\"🔥\":\"⚠️\"}),c.jsx(\"span\",{className:`font-bold text-sm uppercase tracking-wide ${o?\"text-emerald-300\":\"text-amber-300\"}`,children:o?\"BUYING SIGNAL\":i?.objection_type===\"price\"?\"PRICE CONCERN\":i?.objection_type===\"timing\"?\"TIMING ISSUE\":i?.objection_type===\"trust\"?\"TRUST CONCERN\":\"OBJECTION\"})]}),c.jsx(\"div\",{className:\"px-4 pt-3 pb-2\",children:c.jsxs(\"p\",{className:\"text-slate-400 text-sm italic truncate\",children:['\"',s,'\"']})}),c.jsxs(\"div\",{className:\"px-4 pb-3\",children:[c.jsxs(\"p\",{className:\"text-white text-lg font-medium leading-snug\",children:['\"',i?.response||\"Handle this naturally...\",'\"']}),c.jsx(\"p\",{className:\"text-slate-500 text-xs italic mt-1\",children:\"Adapt in your own voice\"})]}),i?.key_point&&c.jsx(\"div\",{className:\"px-4 pb-2\",children:c.jsxs(\"div\",{className:`inline-flex items-center gap-1.5 rounded-full px-3 py-1 ${o?\"bg-emerald-500/20 border border-emerald-500/30\":\"bg-amber-500/20 border border-amber-500/30\"}`,children:[c.jsx(ac,{className:`w-3 h-3 ${o?\"text-emerald-400\":\"text-amber-400\"}`}),c.jsx(\"span\",{className:`text-xs font-medium ${o?\"text-emerald-300\":\"text-amber-300\"}`,children:i.key_point})]})}),i?.follow_up_question&&c.jsxs(\"div\",{className:\"px-4 pb-4 flex items-start gap-2\",children:[c.jsx(Qj,{className:`w-4 h-4 mt-0.5 flex-shrink-0 ${o?\"text-emerald-400\":\"text-amber-400\"}`}),c.jsxs(\"div\",{children:[c.jsx(\"span\",{className:`text-xs font-bold ${o?\"text-emerald-400\":\"text-amber-400\"}`,children:\"THEN ASK:\"}),c.jsxs(\"span\",{className:\"text-slate-300 text-sm ml-1\",children:['\"',i.follow_up_question,'\"']})]})]}),c.jsx(\"button\",{onClick:l,className:\"absolute top-2 right-2 p-2 text-slate-400 hover:text-white\",children:c.jsx(Gt,{className:\"w-4 h-4\"})})]})}function wE({isMuted:t,onMute:s,onMarkHot:i,onEndCall:l,markedHot:o}){return c.jsx(\"div\",{className:\"bg-slate-800 border-t border-slate-700 px-4 py-4 safe-area-bottom\",children:c.jsxs(\"div\",{className:\"flex items-center justify-center gap-4\",children:[c.jsx(\"button\",{onClick:s,className:`w-14 h-14 rounded-full flex items-center justify-center transition-colors ${t?\"bg-red-500 text-white\":\"bg-slate-700 text-slate-300\"}`,children:t?c.jsx(Tc,{className:\"w-6 h-6\"}):c.jsx(ti,{className:\"w-6 h-6\"})}),c.jsx(\"button\",{onClick:i,disabled:o,className:`w-14 h-14 rounded-full flex items-center justify-center transition-colors ${o?\"bg-amber-500 text-white\":\"bg-amber-500/20 border border-amber-500/50 text-amber-400\"}`,children:c.jsx(nl,{className:\"w-6 h-6\"})}),c.jsxs(\"button\",{onClick:l,className:\"px-8 py-4 rounded-full bg-red-500 text-white font-bold flex items-center gap-2 active:scale-95 transition-transform\",children:[c.jsx(ur,{className:\"w-5 h-5\"}),c.jsx(\"span\",{children:\"End\"})]})]})})}function SE({intel:t,leadName:s,onClose:i}){return t?c.jsx(Le.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:\"fixed inset-0 z-[60] bg-black/70 flex items-end\",onClick:i,children:c.jsx(Le.div,{initial:{y:\"100%\"},animate:{y:0},exit:{y:\"100%\"},transition:{type:\"spring\",damping:25,stiffness:300},className:\"bg-slate-800 rounded-t-3xl w-full max-h-[70vh] overflow-y-auto\",onClick:l=>l.stopPropagation(),children:c.jsxs(\"div\",{className:\"p-4\",children:[c.jsx(\"div\",{className:\"w-12 h-1 bg-slate-600 rounded-full mx-auto mb-4\"}),c.jsxs(\"h3\",{className:\"text-lg font-bold text-white mb-4\",children:[\"Intel: \",s]}),t.company&&c.jsxs(\"div\",{className:\"bg-slate-700/50 rounded-xl p-4 mb-3\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-2 mb-2\",children:[c.jsx(jc,{className:\"w-4 h-4 text-blue-400\"}),c.jsx(\"span\",{className:\"text-sm font-semibold text-white\",children:t.company.name})]}),c.jsxs(\"div\",{className:\"flex flex-wrap gap-2\",children:[t.company.industry&&c.jsx(\"span\",{className:\"px-2 py-1 bg-blue-500/20 text-blue-300 text-xs rounded\",children:t.company.industry}),t.company.size&&c.jsx(\"span\",{className:\"px-2 py-1 bg-slate-600 text-slate-300 text-xs rounded\",children:t.company.size}),t.company.location&&c.jsx(\"span\",{className:\"px-2 py-1 bg-slate-600 text-slate-300 text-xs rounded\",children:t.company.location})]}),t.company.sales_angle&&c.jsxs(\"div\",{className:\"mt-3 p-2 bg-emerald-500/10 border border-emerald-500/30 rounded-lg\",children:[c.jsx(\"span\",{className:\"text-xs text-emerald-400 font-semibold\",children:\"SALES ANGLE: \"}),c.jsx(\"span\",{className:\"text-sm text-slate-300\",children:t.company.sales_angle})]})]}),t.person?.job_title&&c.jsxs(\"div\",{className:\"bg-slate-700/50 rounded-xl p-4 mb-3\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-2 mb-1\",children:[c.jsx(\"span\",{className:\"text-lg\",children:\"👤\"}),c.jsx(\"span\",{className:\"text-sm font-semibold text-white\",children:s})]}),c.jsx(\"p\",{className:\"text-slate-400 text-sm\",children:t.person.job_title}),t.person.years_at_company&&c.jsxs(\"p\",{className:\"text-slate-500 text-xs mt-1\",children:[t.person.years_at_company,\" years at company\"]})]}),t.similar_wins?.length>0&&c.jsxs(\"div\",{className:\"bg-slate-700/50 rounded-xl p-4\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-2 mb-2\",children:[c.jsx(\"span\",{className:\"text-lg\",children:\"🏆\"}),c.jsx(\"span\",{className:\"text-sm font-semibold text-amber-400\",children:\"Similar Wins\"})]}),c.jsx(\"div\",{className:\"space-y-2\",children:t.similar_wins.slice(0,3).map((l,o)=>c.jsxs(\"div\",{className:\"text-sm\",children:[c.jsx(\"span\",{className:\"text-slate-300\",children:l.name}),l.key_factor&&c.jsxs(\"span\",{className:\"text-slate-500\",children:[' — \"',l.key_factor,'\"']})]},o))})]})]})})}):null}function jE({lead:t,duration:s,isListening:i,isMuted:l,script:o,scriptStage:d,intel:f,latestSuggestion:m,openingLine:p,error:y,onMinimize:x,onMute:g,onMarkHot:w,onEndCall:S,onDismissSuggestion:T}){const[N,R]=b.useState(!1),[D,A]=b.useState(!1),C=()=>{A(!0),w?.()};return c.jsxs(\"div\",{className:\"fixed inset-0 z-50 bg-slate-900 flex flex-col\",children:[c.jsx(gE,{duration:s,leadName:t?.first_name,isListening:i,onMinimize:x}),c.jsxs(\"div\",{className:\"flex-1 flex flex-col p-4 gap-3 overflow-hidden\",children:[c.jsx(yE,{intel:f}),c.jsx(xE,{stage:d,script:o,openingLine:p}),c.jsx(bE,{company:f?.company,person:f?.person,onExpand:()=>R(!0)}),y&&c.jsxs(\"div\",{className:\"bg-red-500/10 border border-red-500/30 rounded-xl px-4 py-2 flex items-center gap-2\",children:[c.jsx(Db,{className:\"w-4 h-4 text-red-400 flex-shrink-0\"}),c.jsx(\"span\",{className:\"text-red-400 text-sm\",children:y})]}),c.jsxs(\"div\",{className:\"flex-1 flex items-center justify-center px-2\",children:[c.jsx(si,{mode:\"wait\",children:m&&c.jsx(vE,{type:m.type,trigger:m.trigger,suggestion:m.suggestion,onDismiss:T},m.timestamp)}),!m&&i&&c.jsx(\"div\",{className:\"text-center\",children:c.jsxs(\"div\",{className:\"flex items-center justify-center gap-2 text-slate-500\",children:[c.jsx(\"div\",{className:\"w-2 h-2 bg-violet-500 rounded-full animate-pulse\"}),c.jsx(\"span\",{className:\"text-sm\",children:\"Listening for signals...\"})]})})]})]}),c.jsx(wE,{isMuted:l,onMute:g,onMarkHot:C,onEndCall:S,markedHot:D}),c.jsx(si,{children:N&&c.jsx(SE,{intel:f,leadName:t?.first_name,onClose:()=>R(!1)})})]})}const TE={discovery:[\"tell me about\",\"what do you\",\"how many\",\"when did\",\"how long\",\"what's your\",\"who is\"],value_prop:[\"we can help\",\"our platform\",\"rateright\",\"workers available\",\"save you\",\"percentage\"],objections:[\"price\",\"cost\",\"expensive\",\"not sure\",\"competitor\",\"think about\"],close:[\"next step\",\"sign up\",\"get started\",\"send you\",\"email\",\"ready to\"]},NE=[\"expensive\",\"cost\",\"price\",\"too much\",\"can't afford\",\"not sure\",\"think about\",\"need to check\",\"competitor\",\"already have\",\"not interested\",\"busy\",\"later\",\"call back\",\"happy with\",\"current provider\",\"contract\",\"locked in\"],CE=[/works?\\s+for\\s+(.+?)\\s+on\\s+(?:the\\s+)?(.+?)(?:\\s+project|\\s+site|\\s+job|[.!?]|$)/i,/(?:i|we)\\s+work\\s+for\\s+(.+?)(?:\\s+on|\\s+at|[.!?]|$)/i,/(?:my|the)\\s+boss\\s+(?:is\\s+)?(?:at\\s+)?(.+?)(?:[.!?]|$)/i,/working\\s+(?:for|with)\\s+(.+?)(?:\\s+on|\\s+at|[.!?]|$)/i],AE=[/^hey system[,:]?\\s*(.+)/i,/^command[,:]?\\s*(.+)/i,/^note[,:]?\\s*(.+)/i,/^mark\\s+(hot|warm|cold|engaged|converted|lost)/i,/^callback\\s+(.+)/i,/^skip$/i],EE=[\"when can you start\",\"when can we start\",\"how do i sign up\",\"how do we sign up\",\"what's the next step\",\"what is the next step\",\"next steps\",\"let's do it\",\"lets do it\",\"i'm ready\",\"we're ready\",\"sign me up\",\"sign us up\",\"send me the details\",\"send the details\",\"send me a quote\",\"need workers asap\",\"need someone today\",\"starting monday\",\"starting next week\",\"that's reasonable\",\"sounds fair\",\"cheaper than\",\"better than\",\"have a job starting\",\"got a project\",\"need workers\",\"how many workers\",\"do you have electricians\",\"do you have carpenters\"],Lx={\"next step\":{type:\"closing\",response:\"Great question! I can get you set up right now. I just need your email to send the signup link.\",followUp:\"What's the best email to send that to?\",keyPoint:\"They're ready to move forward!\"},sign:{type:\"closing\",response:\"Perfect! Let me get you started. The signup takes about 2 minutes.\",followUp:\"Do you have your ABN handy?\",keyPoint:\"Close the deal now!\"},\"when can\":{type:\"urgency\",response:\"We can have workers available within 24-48 hours once you're set up.\",followUp:\"What trade do you need first?\",keyPoint:\"Match their urgency!\"},\"need workers\":{type:\"qualification\",response:\"We've got a great pool of pre-vetted workers. Most contractors find someone within a day.\",followUp:\"How many workers are you looking for?\",keyPoint:\"Qualify the opportunity!\"},cheaper:{type:\"value\",response:\"Yes, at 9.9% we're typically 30-50% less than traditional agencies, with no lock-in contracts.\",followUp:\"Would you like me to calculate the savings based on your team size?\",keyPoint:\"Reinforce the value!\"},default:{type:\"interest\",response:\"I can hear you're interested! Let me show you how easy it is to get started.\",followUp:\"What's your biggest pain point with finding workers right now?\",keyPoint:\"Keep the momentum!\"}};function DE({lead:t,onClose:s,onEnd:i}){const{scriptSessionId:l,setScriptSessionId:o,preloadedIntel:d}=kc(),[f,m]=b.useState(!1),[p,y]=b.useState(\"\"),[x,g]=b.useState(\"\"),[w,S]=b.useState([]),[T,N]=b.useState(!1),[R,D]=b.useState(null),[A,C]=b.useState(0),[B,_]=b.useState(!1),[F,P]=b.useState(null),[H,z]=b.useState([]),[X,te]=b.useState(\"\"),[Y,$]=b.useState(!0),[W,se]=b.useState(!0),[O,I]=b.useState({}),[K,ie]=b.useState(null),[oe,xe]=b.useState(null),[Te,ae]=b.useState(null),[ce,ne]=b.useState(!1),ue=b.useRef(!1),[de,ee]=b.useState(null),[ge,Ee]=b.useState(!1),[wt,me]=b.useState(null),ze=b.useRef(null),[st,on]=b.useState(!0),[Wt,ms]=b.useState(null),[Yn,Yt]=b.useState(\"opener\"),[li,Ea]=b.useState([]),[Vt,Fn]=b.useState(null),[St,$s]=b.useState(null),[Xn,Da]=b.useState(d),[ps,ka]=b.useState(null),[Ln,ri]=b.useState(!1),cn=b.useRef(!1);b.useEffect(()=>{d&&!cn.current&&(console.log(\"[LiveCopilot] Syncing preloadedIntel from context:\",Object.keys(d)),Da(d),cn.current=!0)},[d]);const Ft=b.useRef(null),ft=b.useRef(null),Ut=b.useRef(null),Ct=b.useRef(null);b.useRef(!1);const Gs=b.useRef(null),Kn=b.useRef(\"\"),un=b.useRef([]),gs=b.useRef(0),Qn=b.useRef(!1),Pt=b.useRef(0),Xt=b.useRef(null),ve=b.useRef(null);b.useEffect(()=>{if(St){const re=setTimeout(()=>{$s(null)},5e3);return()=>clearTimeout(re)}},[St]),b.useEffect(()=>((async()=>(await Fe(),await ht(),await At(),await Zn(),console.log(\"[LiveCopilot] Starting real-time transcription\"),Rt()))(),()=>{xs(),Ut.current&&clearInterval(Ut.current)}),[]),b.useEffect(()=>{Ct.current?.scrollIntoView({behavior:\"smooth\"})},[w]),b.useEffect(()=>(Ut.current=setInterval(()=>{C(re=>(gs.current=re+1,re+1))},1e3),()=>clearInterval(Ut.current)),[]),b.useEffect(()=>{Kn.current=p},[p]),b.useEffect(()=>{un.current=w},[w]),b.useEffect(()=>()=>{!Qn.current&&t?.id&&Kn.current&&(console.log(\"[LiveCopilot] Saving session on unmount, transcript length:\",Kn.current.length),Qn.current=!0,It.saveCopilotSession({leadId:t.id,transcript:Kn.current,suggestions:un.current,duration:gs.current}).catch(re=>console.error(\"[LiveCopilot] Failed to save session on unmount:\",re)))},[t?.id]);const Fe=async()=>{try{const re=await It.getDeepgramCredentials();if(console.log(\"[LiveCopilot] Deepgram configured:\",re.configured),re.configured){const Ae=`wss://${window.location.host.includes(\"rateright.com.au\")?\"rateright-growth-production.up.railway.app\":window.location.host}/api/transcribe/ws`;console.log(\"[LiveCopilot] Using backend proxy:\",Ae),P({configured:!0,proxyUrl:Ae}),Gs.current={configured:!0,proxyUrl:Ae}}else console.log(\"[LiveCopilot] Deepgram not configured, will use Web Speech API fallback\"),Gs.current=null}catch(re){console.log(\"[LiveCopilot] Live transcription not available:\",re.message),Gs.current=null}},ht=async()=>{if(!t?.id){se(!1);return}try{if(t.ai_intel_brief?.talking_points){z(t.ai_intel_brief.talking_points||[]),te(t.ai_intel_brief.opening_line||\"\"),se(!1);return}const re=await It.getIntelBrief(t.id);re.brief&&(z(re.brief.talking_points||[]),te(re.brief.opening_line||\"\"));try{const je=await It.getSimilarWins(t.id);je?.wins?.length>0&&Fn(je.wins[0])}catch(je){console.log(\"Could not load similar wins:\",je)}}catch(re){console.log(\"Could not load intel brief:\",re)}finally{se(!1)}},At=async()=>{if(cn.current||Xn){console.log(\"[LiveCopilot] Intel already loaded, skipping API fetch\");return}if(d){console.log(\"[LiveCopilot] Preloaded intel exists, useEffect will sync\");return}if(t?.id)try{console.log(\"[LiveCopilot] No preloaded intel, fetching from API...\");const re=await It.getLiveIntel(t.id);re.success&&!cn.current&&Da(re)}catch(re){console.log(\"Could not load intel:\",re)}},Zn=async()=>{if(t?.id)try{const re=await hc.getForLead(t.id);if(re.recommendedScripts?.length>0){const je=await hc.get(re.recommendedScripts[0].id);ka(je.script),ms(je.script?.id)}}catch(re){console.log(\"Could not load script:\",re)}},Xe=b.useCallback(re=>{const je=re.toLowerCase();for(const[ye,Ae]of Object.entries(TE))for(const _e of Ae)if(je.includes(_e)){const et=[\"opener\",\"discovery\",\"value_prop\",\"objections\",\"close\"],Be=et.indexOf(Yn);if(et.indexOf(ye)>Be)return Ea(Bn=>[...new Set([...Bn,Yn])]),Yt(ye),!0}return!1},[Yn]),Ht=re=>{const je=Math.floor(re/60),ye=re%60;return`${je}:${ye.toString().padStart(2,\"0\")}`},Jn=b.useCallback(re=>{const je=re.toLowerCase();return NE.some(ye=>je.includes(ye))},[]),Dt=b.useCallback(re=>{const je=re.toLowerCase();for(const ye of EE)if(je.includes(ye)){if(ze.current===ye)return null;ze.current=ye;let Ae=Lx.default;for(const[_e,et]of Object.entries(Lx))if(_e!==\"default\"&&ye.includes(_e)){Ae=et;break}return{trigger:ye,...Ae}}return null},[]),kt=b.useCallback(re=>{me(re);const je={type:\"buying_signal\",trigger:re.trigger,suggestion:{signal_type:re.type,response:re.response,follow_up_question:re.followUp,key_point:re.keyPoint},timestamp:Date.now()};S(ye=>[...ye,je]),$s(je),setTimeout(()=>me(null),5e3)},[]),ys=async re=>{if(!T){N(!0);try{const je=await It.objectionResponse({objection:re,leadId:t?.id});if(je.success){const ye={type:\"objection\",trigger:re,suggestion:je.suggestion,timestamp:Date.now()};S(Ae=>[...Ae,ye]),$s(ye)}}catch(je){console.error(\"Failed to get objection response:\",je)}finally{N(!1)}}},qt=t?.metadata?.lead_type===\"worker\",oi=b.useCallback(re=>{if(!(!qt||ue.current||ce))for(const je of CE){const ye=re.match(je);if(ye){const Ae=ye[1]?.trim(),_e=ye[2]?.trim();if(Ae&&Ae.length>2){console.log(`[ContractorDetection] Found: ${Ae}, project: ${_e||\"N/A\"}`),Dr(Ae,_e);return}}}},[qt,ce]),Dr=async(re,je)=>{if(!(ue.current||ce)){ue.current=!0,ne(!0);try{const ye=await It.extractContractor({sourceLeadId:t?.id,companyName:re,projectName:je});ye.success&&ye.found&&ye.candidate&&ae(ye.candidate)}catch(ye){console.error(\"Contractor search error:\",ye)}finally{ne(!1)}}},Wn=(re,je)=>{ae(null),console.log(\"Contractor lead created:\",re,je)},mt=b.useCallback(async re=>{if(ge)return!1;const je=re.toLowerCase().trim();for(const ye of AE){const Ae=je.match(ye);if(Ae){let _e=Ae[1]||je;(ye.source.includes(\"mark\")||ye.source.includes(\"skip\"))&&(_e=je),console.log(\"[VoiceCommand] Detected:\",_e),Ee(!0);try{const et=await It.voiceCommand({transcript:_e,leadId:t?.id});et.success&&(ee({confirmation:et.parsed.confirmation,intent:et.parsed.intent}),setTimeout(()=>ee(null),3e3))}catch(et){console.error(\"Voice command error:\",et)}finally{Ee(!1)}return!0}}return!1},[t?.id,ge]),Rt=async()=>{try{console.log(\"[LiveCopilot] Requesting microphone access...\");const re=await navigator.mediaDevices.getUserMedia({audio:!0});ve.current=re,Pt.current=0,console.log(\"[LiveCopilot] Microphone access granted\");const je=Gs.current||F;if(console.log(\"[LiveCopilot] Using backend proxy:\",!!(je?.configured&&je?.proxyUrl)),je?.configured&&je?.proxyUrl){console.log(\"[LiveCopilot] Connecting to backend proxy...\"),console.log(\"[LiveCopilot] Proxy URL:\",je.proxyUrl),xe(\"deepgram\");const ye=new WebSocket(je.proxyUrl);console.log(\"[LiveCopilot] WebSocket created, readyState:\",ye.readyState);const Ae=setTimeout(()=>{console.error(\"[LiveCopilot] Connection timeout! readyState:\",ye.readyState),ye.readyState!==WebSocket.OPEN&&(D(\"Connection timeout - trying fallback...\"),ye.close())},1e4);ye.onopen=()=>{clearTimeout(Ae),console.log(\"[LiveCopilot] Connected to transcription proxy!\"),Pt.current=0,m(!0),D(null)},ye.onmessage=Qe=>{const Ke=JSON.parse(Qe.data);if(Ke.error){console.error(\"[LiveCopilot] Proxy error:\",Ke.error),D(Ke.error);return}if(Ke.type===\"Metadata\"&&console.log(\"[LiveCopilot] Transcription metadata:\",Ke),Ke.channel?.alternatives?.[0]?.transcript){console.log(\"[LiveCopilot] Transcript:\",Ke.channel.alternatives[0].transcript,\"is_final:\",Ke.is_final);const Kt=Ke.channel.alternatives[0].transcript;if(Ke.is_final){y(Fs=>Fs+\" \"+Kt),g(\"\"),mt(Kt),Xe(Kt);const Ys=Dt(Kt);Ys?kt(Ys):Jn(Kt)&&ys(Kt),qt&&oi(Kt)}else g(Kt)}},ye.onerror=Qe=>{clearTimeout(Ae),console.error(\"[LiveCopilot] Proxy WebSocket error:\",Qe),console.error(\"[LiveCopilot] Error type:\",Qe.type),console.error(\"[LiveCopilot] Socket readyState on error:\",ye.readyState),D(\"Transcription error - check console\")},ye.onclose=Qe=>{clearTimeout(Ae),console.log(\"[LiveCopilot] Proxy disconnected, code:\",Qe.code,\"reason:\",Qe.reason,\"wasClean:\",Qe.wasClean);const Ke=3;if(Pt.current{console.log(\"[LiveCopilot] Reconnecting WebSocket...\"),Rt()},Kt)}else m(!1),Pt.current>=Ke&&D(\"Transcription disconnected. Tap mic to restart.\")},Ft.current=ye;const _e=new AudioContext,et=_e.sampleRate;console.log(\"[LiveCopilot] AudioContext sample rate:\",et);const Be=`"}],"details":{"status":"completed","exitCode":0,"durationMs":96,"aggregated":"./public/assets/index-2HMepUD5.js:18: `),()=>{D.contains(R)&&D.removeChild(R)}},[s]),c.jsx(JA,{isPresent:s,childRef:d,sizeRef:f,children:b.cloneElement(t,{ref:y})})}const e2=({children:t,initial:s,isPresent:i,onExitComplete:l,custom:o,presenceAffectsLayout:d,mode:f,anchorX:m,root:p})=>{const y=bh(t2),x=b.useId();let g=!0,w=b.useMemo(()=>(g=!1,{id:x,initial:s,isPresent:i,custom:o,onExitComplete:S=>{y.set(S,!0);for(const T of y.values())if(!T)return;l&&l()},register:S=>(y.set(S,!1),()=>y.delete(S))}),[i,y,l]);return d&&g&&(w={...w}),b.useMemo(()=>{y.forEach((S,T)=>y.set(T,!1))},[i]),b.useEffect(()=>{!i&&!y.size&&l&&l()},[i]),f===\"popLayout\"&&(t=c.jsx(WA,{isPresent:i,anchorX:m,root:p,children:t})),c.jsx(Cc.Provider,{value:w,children:t})};function t2(){return new Map}function rw(t=!0){const s=b.useContext(Cc);if(s===null)return[!0,null];const{isPresent:i,onExitComplete:l,register:o}=s,d=b.useId();b.useEffect(()=>{if(t)return o(d)},[t]);const f=b.useCallback(()=>t&&l&&l(d),[d,l,t]);return!i&&l?[!1,f]:[!0]}const $o=t=>t.key||\"\";function yx(t){const s=[];return b.Children.forEach(t,i=>{b.isValidElement(i)&&s.push(i)}),s}const si=({children:t,custom:s,initial:i=!0,onExitComplete:l,presenceAffectsLayout:o=!0,mode:d=\"sync\",propagate:f=!1,anchorX:m=\"left\",root:p})=>{const[y,x]=rw(f),g=b.useMemo(()=>yx(t),[t]),w=f&&!y?[]:g.map($o),S=b.useRef(!0),T=b.useRef(g),N=bh(()=>new Map),R=b.useRef(new Set),[D,A]=b.useState(g),[C,B]=b.useState(g);Vb(()=>{S.current=!1,T.current=g;for(let P=0;P{const H=$o(P),z=f&&!y?!1:g===C||w.includes(H),X=()=>{if(R.current.has(H))return;if(R.current.add(H),N.has(H))N.set(H,!0);else return;let te=!0;N.forEach(Y=>{Y||(te=!1)}),te&&(F?.(),B(T.current),f&&x?.(),l&&l())};return c.jsx(e2,{isPresent:z,initial:!S.current||i?void 0:!1,custom:s,presenceAffectsLayout:o,mode:d,root:p,onExitComplete:z?void 0:X,anchorX:m,children:P},H)})})},ow=b.createContext({strict:!1}),xx={animation:[\"animate\",\"variants\",\"whileHover\",\"whileTap\",\"exit\",\"whileInView\",\"whileFocus\",\"whileDrag\"],exit:[\"exit\"],drag:[\"drag\",\"dragControls\"],focus:[\"whileFocus\"],hover:[\"whileHover\",\"onHoverStart\",\"onHoverEnd\"],tap:[\"whileTap\",\"onTap\",\"onTapStart\",\"onTapCancel\"],pan:[\"onPan\",\"onPanStart\",\"onPanSessionStart\",\"onPanEnd\"],inView:[\"whileInView\",\"onViewportEnter\",\"onViewportLeave\"],layout:[\"layout\",\"layoutId\"]};let bx=!1;function n2(){if(bx)return;const t={};for(const s in xx)t[s]={isEnabled:i=>xx[s].some(l=>!!i[l])};Bv(t),bx=!0}function cw(){return n2(),qC()}function s2(t){const s=cw();for(const i in t)s[i]={...s[i],...t[i]};Bv(s)}const a2=new Set([\"animate\",\"exit\",\"variants\",\"initial\",\"style\",\"values\",\"variants\",\"transition\",\"transformTemplate\",\"custom\",\"inherit\",\"onBeforeLayoutMeasure\",\"onAnimationStart\",\"onAnimationComplete\",\"onUpdate\",\"onDragStart\",\"onDrag\",\"onDragEnd\",\"onMeasureDragConstraints\",\"onDirectionLock\",\"onDragTransitionEnd\",\"_dragX\",\"_dragY\",\"onHoverStart\",\"onHoverEnd\",\"onViewportEnter\",\"onViewportLeave\",\"globalTapTarget\",\"ignoreStrict\",\"viewport\"]);function fc(t){return t.startsWith(\"while\")||t.startsWith(\"drag\")&&t!==\"draggable\"||t.startsWith(\"layout\")||t.startsWith(\"onTap\")||t.startsWith(\"onPan\")||t.startsWith(\"onLayout\")||a2.has(t)}let uw=t=>!fc(t);function i2(t){typeof t==\"function\"&&(uw=s=>s.startsWith(\"on\")?!fc(s):t(s))}try{i2(require(\"@emotion/is-prop-valid\").default)}catch{}function l2(t,s,i){const l={};for(const o in t)o===\"values\"&&typeof t.values==\"object\"||(uw(o)||i===!0&&fc(o)||!s&&!fc(o)||t.draggable&&o.startsWith(\"onDrag\"))&&(l[o]=t[o]);return l}const Dc=b.createContext({});function r2(t,s){if(Ec(t)){const{initial:i,animate:l}=t;return{initial:i===!1||mr(i)?i:void 0,animate:mr(l)?l:void 0}}return t.inherit!==!1?s:{}}function o2(t){const{initial:s,animate:i}=r2(t,b.useContext(Dc));return b.useMemo(()=>({initial:s,animate:i}),[vx(s),vx(i)])}function vx(t){return Array.isArray(t)?t.join(\" \"):t}const Xh=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function dw(t,s,i){for(const l in s)!$t(s[l])&&!$v(l,i)&&(t[l]=s[l])}function c2({transformTemplate:t},s){return b.useMemo(()=>{const i=Xh();return Gh(i,s,t),Object.assign({},i.vars,i.style)},[s])}function u2(t,s){const i=t.style||{},l={};return dw(l,i,t),Object.assign(l,c2(t,s)),l}function d2(t,s){const i={},l=u2(t,s);return t.drag&&t.dragListener!==!1&&(i.draggable=!1,l.userSelect=l.WebkitUserSelect=l.WebkitTouchCallout=\"none\",l.touchAction=t.drag===!0?\"none\":`pan-${t.drag===\"x\"?\"y\":\"x\"}`),t.tabIndex===void 0&&(t.onTap||t.onTapStart||t.whileTap)&&(i.tabIndex=0),i.style=l,i}const fw=()=>({...Xh(),attrs:{}});function f2(t,s,i,l){const o=b.useMemo(()=>{const d=fw();return Gv(d,s,Fv(l),t.transformTemplate,t.style),{...d.attrs,style:{...d.style}}},[s]);if(t.style){const d={};dw(d,t.style,t),o.style={...d,...o.style}}return o}const h2=[\"animate\",\"circle\",\"defs\",\"desc\",\"ellipse\",\"g\",\"image\",\"line\",\"filter\",\"marker\",\"mask\",\"metadata\",\"path\",\"pattern\",\"polygon\",\"polyline\",\"rect\",\"stop\",\"switch\",\"symbol\",\"svg\",\"text\",\"tspan\",\"use\",\"view\"];function Kh(t){return typeof t!=\"string\"||t.includes(\"-\")?!1:!!(h2.indexOf(t)>-1||/[A-Z]/u.test(t))}function m2(t,s,i,{latestValues:l},o,d=!1,f){const p=(f??Kh(t)?f2:d2)(s,l,o,t),y=l2(s,typeof t==\"string\",d),x=t!==b.Fragment?{...y,...p,ref:i}:{},{children:g}=s,w=b.useMemo(()=>$t(g)?g.get():g,[g]);return b.createElement(t,{...x,children:w})}function p2({scrapeMotionValuesFromProps:t,createRenderState:s},i,l,o){return{latestValues:g2(i,l,o,t),renderState:s()}}function g2(t,s,i,l){const o={},d=l(t,{});for(const w in d)o[w]=ec(d[w]);let{initial:f,animate:m}=t;const p=Ec(t),y=zv(t);s&&y&&!p&&t.inherit!==!1&&(f===void 0&&(f=s.initial),m===void 0&&(m=s.animate));let x=i?i.initial===!1:!1;x=x||f===!1;const g=x?m:f;if(g&&typeof g!=\"boolean\"&&!Ac(g)){const w=Array.isArray(g)?g:[g];for(let S=0;S(s,i)=>{const l=b.useContext(Dc),o=b.useContext(Cc),d=()=>p2(t,s,l,o);return i?d():bh(d)},y2=hw({scrapeMotionValuesFromProps:Yh,createRenderState:Xh}),x2=hw({scrapeMotionValuesFromProps:Xv,createRenderState:fw}),b2=Symbol.for(\"motionComponentSymbol\");function v2(t,s,i){const l=b.useRef(i);b.useInsertionEffect(()=>{l.current=i});const o=b.useRef(null);return b.useCallback(d=>{d&&t.onMount?.(d),s&&(d?s.mount(d):s.unmount());const f=l.current;if(typeof f==\"function\")if(d){const m=f(d);typeof m==\"function\"&&(o.current=m)}else o.current?(o.current(),o.current=null):f(d);else f&&(f.current=d)},[s])}const mw=b.createContext({});function sr(t){return t&&typeof t==\"object\"&&Object.prototype.hasOwnProperty.call(t,\"current\")}function w2(t,s,i,l,o,d){const{visualElement:f}=b.useContext(Dc),m=b.useContext(ow),p=b.useContext(Cc),y=b.useContext(Fh).reducedMotion,x=b.useRef(null);l=l||m.renderer,!x.current&&l&&(x.current=l(t,{visualState:s,parent:f,props:i,presenceContext:p,blockInitialAnimation:p?p.initial===!1:!1,reducedMotionConfig:y,isSVG:d}));const g=x.current,w=b.useContext(mw);g&&!g.projection&&o&&(g.type===\"html\"||g.type===\"svg\")&&S2(x.current,i,o,w);const S=b.useRef(!1);b.useInsertionEffect(()=>{g&&S.current&&g.update(i,p)});const T=i[wv],N=b.useRef(!!T&&!window.MotionHandoffIsComplete?.(T)&&window.MotionHasOptimisedAnimation?.(T));return Vb(()=>{g&&(S.current=!0,window.MotionIsMounted=!0,g.updateFeatures(),g.scheduleRenderMicrotask(),N.current&&g.animationState&&g.animationState.animateChanges())}),b.useEffect(()=>{g&&(!N.current&&g.animationState&&g.animationState.animateChanges(),N.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(T)}),N.current=!1),g.enteringChildren=void 0)}),g}function S2(t,s,i,l){const{layoutId:o,layout:d,drag:f,dragConstraints:m,layoutScroll:p,layoutRoot:y,layoutCrossfade:x}=s;t.projection=new i(t.latestValues,s[\"data-framer-portal-id\"]?void 0:pw(t.parent)),t.projection.setOptions({layoutId:o,layout:d,alwaysMeasureLayout:!!f||m&&sr(m),visualElement:t,animationType:typeof d==\"string\"?d:\"both\",initialPromotionConfig:l,crossfade:x,layoutScroll:p,layoutRoot:y})}function pw(t){if(t)return t.options.allowProjection!==!1?t.projection:pw(t.parent)}function ff(t,{forwardMotionProps:s=!1,type:i}={},l,o){l&&s2(l);const d=i?i===\"svg\":Kh(t),f=d?x2:y2;function m(y,x){let g;const w={...b.useContext(Fh),...y,layoutId:j2(y)},{isStatic:S}=w,T=o2(y),N=f(y,S);if(!S&&Bb){T2();const R=N2(w);g=R.MeasureLayout,T.visualElement=w2(t,N,w,o,R.ProjectionNode,d)}return c.jsxs(Dc.Provider,{value:T,children:[g&&T.visualElement?c.jsx(g,{visualElement:T.visualElement,...w}):null,m2(t,y,v2(N,T.visualElement,x),N,S,s,d)]})}m.displayName=`motion.${typeof t==\"string\"?t:`create(${t.displayName??t.name??\"\"})`}`;const p=b.forwardRef(m);return p[b2]=t,p}function j2({layoutId:t}){const s=b.useContext(xh).id;return s&&t!==void 0?s+\"-\"+t:t}function T2(t,s){b.useContext(ow).strict}function N2(t){const s=cw(),{drag:i,layout:l}=s;if(!i&&!l)return{};const o={...i,...l};return{MeasureLayout:i?.isEnabled(t)||l?.isEnabled(t)?o.MeasureLayout:void 0,ProjectionNode:o.ProjectionNode}}function C2(t,s){if(typeof Proxy>\"u\")return ff;const i=new Map,l=(d,f)=>ff(d,f,t,s),o=(d,f)=>l(d,f);return new Proxy(o,{get:(d,f)=>f===\"create\"?l:(i.has(f)||i.set(f,ff(f,void 0,t,s)),i.get(f))})}const A2=(t,s)=>s.isSVG??Kh(t)?new iA(s):new WC(s,{allowProjection:t!==b.Fragment});class E2 extends Na{constructor(s){super(s),s.animationState||(s.animationState=uA(s))}updateAnimationControlsSubscription(){const{animate:s}=this.node.getProps();Ac(s)&&(this.unmountControls=s.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:s}=this.node.getProps(),{animate:i}=this.node.prevProps||{};s!==i&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}}let D2=0;class k2 extends Na{constructor(){super(...arguments),this.id=D2++}update(){if(!this.node.presenceContext)return;const{isPresent:s,onExitComplete:i}=this.node.presenceContext,{isPresent:l}=this.node.prevPresenceContext||{};if(!this.node.animationState||s===l)return;const o=this.node.animationState.setActive(\"exit\",!s);i&&!s&&o.then(()=>{i(this.id)})}mount(){const{register:s,onExitComplete:i}=this.node.presenceContext||{};i&&i(this.id),s&&(this.unmount=s(this.id))}unmount(){}}const R2={animation:{Feature:E2},exit:{Feature:k2}};function jr(t){return{point:{x:t.pageX,y:t.pageY}}}const M2=t=>s=>qh(s)&&t(s,jr(s));function rr(t,s,i,l){return pr(t,s,M2(i),l)}const gw=({current:t})=>t?t.ownerDocument.defaultView:null,wx=(t,s)=>Math.abs(t-s);function O2(t,s){const i=wx(t.x,s.x),l=wx(t.y,s.y);return Math.sqrt(i**2+l**2)}const Sx=new Set([\"auto\",\"scroll\"]);class yw{constructor(s,i,{transformPagePoint:l,contextWindow:o=window,dragSnapToOrigin:d=!1,distanceThreshold:f=3,element:m}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=S=>{this.handleScroll(S.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const S=mf(this.lastMoveEventInfo,this.history),T=this.startEvent!==null,N=O2(S.offset,{x:0,y:0})>=this.distanceThreshold;if(!T&&!N)return;const{point:R}=S,{timestamp:D}=Bt;this.history.push({...R,timestamp:D});const{onStart:A,onMove:C}=this.handlers;T||(A&&A(this.lastMoveEvent,S),this.startEvent=this.lastMoveEvent),C&&C(this.lastMoveEvent,S)},this.handlePointerMove=(S,T)=>{this.lastMoveEvent=S,this.lastMoveEventInfo=hf(T,this.transformPagePoint),We.update(this.updatePoint,!0)},this.handlePointerUp=(S,T)=>{this.end();const{onEnd:N,onSessionEnd:R,resumeAnimation:D}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&D&&D(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const A=mf(S.type===\"pointercancel\"?this.lastMoveEventInfo:hf(T,this.transformPagePoint),this.history);this.startEvent&&N&&N(S,A),R&&R(S,A)},!qh(s))return;this.dragSnapToOrigin=d,this.handlers=i,this.transformPagePoint=l,this.distanceThreshold=f,this.contextWindow=o||window;const p=jr(s),y=hf(p,this.transformPagePoint),{point:x}=y,{timestamp:g}=Bt;this.history=[{...x,timestamp:g}];const{onSessionStart:w}=i;w&&w(s,mf(y,this.history)),this.removeListeners=vr(rr(this.contextWindow,\"pointermove\",this.handlePointerMove),rr(this.contextWindow,\"pointerup\",this.handlePointerUp),rr(this.contextWindow,\"pointercancel\",this.handlePointerUp)),m&&this.startScrollTracking(m)}startScrollTracking(s){let i=s.parentElement;for(;i;){const l=getComputedStyle(i);(Sx.has(l.overflowX)||Sx.has(l.overflowY))&&this.scrollPositions.set(i,{x:i.scrollLeft,y:i.scrollTop}),i=i.parentElement}this.scrollPositions.set(window,{x:window.scrollX,y:window.scrollY}),window.addEventListener(\"scroll\",this.onElementScroll,{capture:!0,passive:!0}),window.addEventListener(\"scroll\",this.onWindowScroll,{passive:!0}),this.removeScrollListeners=()=>{window.removeEventListener(\"scroll\",this.onElementScroll,{capture:!0}),window.removeEventListener(\"scroll\",this.onWindowScroll)}}handleScroll(s){const i=this.scrollPositions.get(s);if(!i)return;const l=s===window,o=l?{x:window.scrollX,y:window.scrollY}:{x:s.scrollLeft,y:s.scrollTop},d={x:o.x-i.x,y:o.y-i.y};d.x===0&&d.y===0||(l?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=d.x,this.lastMoveEventInfo.point.y+=d.y):this.history.length>0&&(this.history[0].x-=d.x,this.history[0].y-=d.y),this.scrollPositions.set(s,o),We.update(this.updatePoint,!0))}updateHandlers(s){this.handlers=s}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),va(this.updatePoint)}}function hf(t,s){return s?{point:s(t.point)}:t}function jx(t,s){return{x:t.x-s.x,y:t.y-s.y}}function mf({point:t},s){return{point:t,delta:jx(t,xw(s)),offset:jx(t,_2(s)),velocity:L2(s,.1)}}function _2(t){return t[0]}function xw(t){return t[t.length-1]}function L2(t,s){if(t.length<2)return{x:0,y:0};let i=t.length-1,l=null;const o=xw(t);for(;i>=0&&(l=t[i],!(o.timestamp-l.timestamp>Us(s)));)i--;if(!l)return{x:0,y:0};const d=Mn(o.timestamp-l.timestamp);if(d===0)return{x:0,y:0};const f={x:(o.x-l.x)/d,y:(o.y-l.y)/d};return f.x===1/0&&(f.x=0),f.y===1/0&&(f.y=0),f}function z2(t,{min:s,max:i},l){return s!==void 0&&ti&&(t=l?it(i,t,l.max):Math.min(t,i)),t}function Tx(t,s,i){return{min:s!==void 0?t.min+s:void 0,max:i!==void 0?t.max+i-(t.max-t.min):void 0}}function B2(t,{top:s,left:i,bottom:l,right:o}){return{x:Tx(t.x,i,o),y:Tx(t.y,s,l)}}function Nx(t,s){let i=s.min-t.min,l=s.max-t.max;return s.max-s.minl?i=dr(s.min,s.max-l,t.min):l>o&&(i=dr(t.min,t.max-o,s.min)),cs(0,1,i)}function P2(t,s){const i={};return s.min!==void 0&&(i.min=s.min-t.min),s.max!==void 0&&(i.max=s.max-t.min),i}const Xf=.35;function H2(t=Xf){return t===!1?t=0:t===!0&&(t=Xf),{x:Cx(t,\"left\",\"right\"),y:Cx(t,\"top\",\"bottom\")}}function Cx(t,s,i){return{min:Ax(t,s),max:Ax(t,i)}}function Ax(t,s){return typeof t==\"number\"?t:t[s]||0}const q2=new WeakMap;class I2{constructor(s){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=Tt(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=s}start(s,{snapToCursor:i=!1,distanceThreshold:l}={}){const{presenceContext:o}=this.visualElement;if(o&&o.isPresent===!1)return;const d=g=>{i?(this.stopAnimation(),this.snapToCursor(jr(g).point)):this.pauseAnimation()},f=(g,w)=>{this.stopAnimation();const{drag:S,dragPropagation:T,onDragStart:N}=this.getProps();if(S&&!T&&(this.openDragLock&&this.openDragLock(),this.openDragLock=kC(S),!this.openDragLock))return;this.latestPointerEvent=g,this.latestPanInfo=w,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Rn(D=>{let A=this.getAxisMotionValue(D).get()||0;if(rs.test(A)){const{projection:C}=this.visualElement;if(C&&C.layout){const B=C.layout.layoutBox[D];B&&(A=Jt(B)*(parseFloat(A)/100))}}this.originPoint[D]=A}),N&&We.postRender(()=>N(g,w)),Hf(this.visualElement,\"transform\");const{animationState:R}=this.visualElement;R&&R.setActive(\"whileDrag\",!0)},m=(g,w)=>{this.latestPointerEvent=g,this.latestPanInfo=w;const{dragPropagation:S,dragDirectionLock:T,onDirectionLock:N,onDrag:R}=this.getProps();if(!S&&!this.openDragLock)return;const{offset:D}=w;if(T&&this.currentDirection===null){this.currentDirection=$2(D),this.currentDirection!==null&&N&&N(this.currentDirection);return}this.updateAxis(\"x\",w.point,D),this.updateAxis(\"y\",w.point,D),this.visualElement.render(),R&&R(g,w)},p=(g,w)=>{this.latestPointerEvent=g,this.latestPanInfo=w,this.stop(g,w),this.latestPointerEvent=null,this.latestPanInfo=null},y=()=>Rn(g=>this.getAnimationState(g)===\"paused\"&&this.getAxisMotionValue(g).animation?.play()),{dragSnapToOrigin:x}=this.getProps();this.panSession=new yw(s,{onSessionStart:d,onStart:f,onMove:m,onSessionEnd:p,resumeAnimation:y},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:x,distanceThreshold:l,contextWindow:gw(this.visualElement),element:this.visualElement.current})}stop(s,i){const l=s||this.latestPointerEvent,o=i||this.latestPanInfo,d=this.isDragging;if(this.cancel(),!d||!o||!l)return;const{velocity:f}=o;this.startAnimation(f);const{onDragEnd:m}=this.getProps();m&&We.postRender(()=>m(l,o))}cancel(){this.isDragging=!1;const{projection:s,animationState:i}=this.visualElement;s&&(s.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:l}=this.getProps();!l&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),i&&i.setActive(\"whileDrag\",!1)}updateAxis(s,i,l){const{drag:o}=this.getProps();if(!l||!Go(s,o,this.currentDirection))return;const d=this.getAxisMotionValue(s);let f=this.originPoint[s]+l[s];this.constraints&&this.constraints[s]&&(f=z2(f,this.constraints[s],this.elastic[s])),d.set(f)}resolveConstraints(){const{dragConstraints:s,dragElastic:i}=this.getProps(),l=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,o=this.constraints;s&&sr(s)?this.constraints||(this.constraints=this.resolveRefConstraints()):s&&l?this.constraints=B2(l.layoutBox,s):this.constraints=!1,this.elastic=H2(i),o!==this.constraints&&l&&this.constraints&&!this.hasMutatedConstraints&&Rn(d=>{this.constraints!==!1&&this.getAxisMotionValue(d)&&(this.constraints[d]=P2(l.layoutBox[d],this.constraints[d]))})}resolveRefConstraints(){const{dragConstraints:s,onMeasureDragConstraints:i}=this.getProps();if(!s||!sr(s))return!1;const l=s.current,{projection:o}=this.visualElement;if(!o||!o.layout)return!1;const d=FC(l,o.root,this.visualElement.getTransformPagePoint());let f=V2(o.layout.layoutBox,d);if(i){const m=i($C(f));this.hasMutatedConstraints=!!m,m&&(f=Uv(m))}return f}startAnimation(s){const{drag:i,dragMomentum:l,dragElastic:o,dragTransition:d,dragSnapToOrigin:f,onDragTransitionEnd:m}=this.getProps(),p=this.constraints||{},y=Rn(x=>{if(!Go(x,i,this.currentDirection))return;let g=p&&p[x]||{};f&&(g={min:0,max:0});const w=o?200:1e6,S=o?40:1e7,T={type:\"inertia\",velocity:l?s[x]:0,bounceStiffness:w,bounceDamping:S,timeConstant:750,restDelta:1,restSpeed:10,...d,...g};return this.startAxisValueAnimation(x,T)});return Promise.all(y).then(m)}startAxisValueAnimation(s,i){const l=this.getAxisMotionValue(s);return Hf(this.visualElement,s),l.start(Bh(s,l,0,i,this.visualElement,!1))}stopAnimation(){Rn(s=>this.getAxisMotionValue(s).stop())}pauseAnimation(){Rn(s=>this.getAxisMotionValue(s).animation?.pause())}getAnimationState(s){return this.getAxisMotionValue(s).animation?.state}getAxisMotionValue(s){const i=`_drag${s.toUpperCase()}`,l=this.visualElement.getProps(),o=l[i];return o||this.visualElement.getValue(s,(l.initial?l.initial[s]:void 0)||0)}snapToCursor(s){Rn(i=>{const{drag:l}=this.getProps();if(!Go(i,l,this.currentDirection))return;const{projection:o}=this.visualElement,d=this.getAxisMotionValue(i);if(o&&o.layout){const{min:f,max:m}=o.layout.layoutBox[i],p=d.get()||0;d.set(s[i]-it(f,m,.5)+p)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:s,dragConstraints:i}=this.getProps(),{projection:l}=this.visualElement;if(!sr(i)||!l||!this.constraints)return;this.stopAnimation();const o={x:0,y:0};Rn(f=>{const m=this.getAxisMotionValue(f);if(m&&this.constraints!==!1){const p=m.get();o[f]=U2({min:p,max:p},this.constraints[f])}});const{transformTemplate:d}=this.visualElement.getProps();this.visualElement.current.style.transform=d?d({},\"\"):\"none\",l.root&&l.root.updateScroll(),l.updateLayout(),this.resolveConstraints(),Rn(f=>{if(!Go(f,s,null))return;const m=this.getAxisMotionValue(f),{min:p,max:y}=this.constraints[f];m.set(it(p,y,o[f]))})}addListeners(){if(!this.visualElement.current)return;q2.set(this.visualElement,this);const s=this.visualElement.current,i=rr(s,\"pointerdown\",p=>{const{drag:y,dragListener:x=!0}=this.getProps();y&&x&&!Ov(p.target)&&this.start(p)}),l=()=>{const{dragConstraints:p}=this.getProps();sr(p)&&p.current&&(this.constraints=this.resolveRefConstraints())},{projection:o}=this.visualElement,d=o.addEventListener(\"measure\",l);o&&!o.layout&&(o.root&&o.root.updateScroll(),o.updateLayout()),We.read(l);const f=pr(window,\"resize\",()=>this.scalePositionWithinConstraints()),m=o.addEventListener(\"didUpdate\",(({delta:p,hasLayoutChanged:y})=>{this.isDragging&&y&&(Rn(x=>{const g=this.getAxisMotionValue(x);g&&(this.originPoint[x]+=p[x].translate,g.set(g.get()+p[x].translate))}),this.visualElement.render())}));return()=>{f(),i(),d(),m&&m()}}getProps(){const s=this.visualElement.getProps(),{drag:i=!1,dragDirectionLock:l=!1,dragPropagation:o=!1,dragConstraints:d=!1,dragElastic:f=Xf,dragMomentum:m=!0}=s;return{...s,drag:i,dragDirectionLock:l,dragPropagation:o,dragConstraints:d,dragElastic:f,dragMomentum:m}}}function Go(t,s,i){return(s===!0||s===t)&&(i===null||i===t)}function $2(t,s=10){let i=null;return Math.abs(t.y)>s?i=\"y\":Math.abs(t.x)>s&&(i=\"x\"),i}class G2 extends Na{constructor(s){super(s),this.removeGroupControls=On,this.removeListeners=On,this.controls=new I2(s)}mount(){const{dragControls:s}=this.node.getProps();s&&(this.removeGroupControls=s.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||On}update(){const{dragControls:s}=this.node.getProps(),{dragControls:i}=this.node.prevProps||{};s!==i&&(this.removeGroupControls(),s&&(this.removeGroupControls=s.subscribe(this.controls)))}unmount(){this.removeGroupControls(),this.removeListeners()}}const Ex=t=>(s,i)=>{t&&We.postRender(()=>t(s,i))};class Y2 extends Na{constructor(){super(...arguments),this.removePointerDownListener=On}onPointerDown(s){this.session=new yw(s,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:gw(this.node)})}createPanHandlers(){const{onPanSessionStart:s,onPanStart:i,onPan:l,onPanEnd:o}=this.node.getProps();return{onSessionStart:Ex(s),onStart:Ex(i),onMove:l,onEnd:(d,f)=>{delete this.session,o&&We.postRender(()=>o(d,f))}}}mount(){this.removePointerDownListener=rr(this.node.current,\"pointerdown\",s=>this.onPointerDown(s))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}let pf=!1;class F2 extends b.Component{componentDidMount(){const{visualElement:s,layoutGroup:i,switchLayoutGroup:l,layoutId:o}=this.props,{projection:d}=s;d&&(i.group&&i.group.add(d),l&&l.register&&o&&l.register(d),pf&&d.root.didUpdate(),d.addEventListener(\"animationComplete\",()=>{this.safeToRemove()}),d.setOptions({...d.options,onExitComplete:()=>this.safeToRemove()})),tc.hasEverUpdated=!0}getSnapshotBeforeUpdate(s){const{layoutDependency:i,visualElement:l,drag:o,isPresent:d}=this.props,{projection:f}=l;return f&&(f.isPresent=d,pf=!0,o||s.layoutDependency!==i||i===void 0||s.isPresent!==d?f.willUpdate():this.safeToRemove(),s.isPresent!==d&&(d?f.promote():f.relegate()||We.postRender(()=>{const m=f.getStack();(!m||!m.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:s}=this.props.visualElement;s&&(s.root.didUpdate(),Hh.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:s,layoutGroup:i,switchLayoutGroup:l}=this.props,{projection:o}=s;pf=!0,o&&(o.scheduleCheckAfterUnmount(),i&&i.group&&i.group.remove(o),l&&l.deregister&&l.deregister(o))}safeToRemove(){const{safeToRemove:s}=this.props;s&&s()}render(){return null}}function bw(t){const[s,i]=rw(),l=b.useContext(xh);return c.jsx(F2,{...t,layoutGroup:l,switchLayoutGroup:b.useContext(mw),isPresent:s,safeToRemove:i})}const X2={pan:{Feature:Y2},drag:{Feature:G2,ProjectionNode:lw,MeasureLayout:bw}};function Dx(t,s,i){const{props:l}=t;t.animationState&&l.whileHover&&t.animationState.setActive(\"whileHover\",i===\"Start\");const o=\"onHover\"+i,d=l[o];d&&We.postRender(()=>d(s,jr(s)))}class K2 extends Na{mount(){const{current:s}=this.node;s&&(this.unmount=RC(s,(i,l)=>(Dx(this.node,l,\"Start\"),o=>Dx(this.node,o,\"End\"))))}unmount(){}}class Q2 extends Na{constructor(){super(...arguments),this.isActive=!1}onFocus(){let s=!1;try{s=this.node.current.matches(\":focus-visible\")}catch{s=!0}!s||!this.node.animationState||(this.node.animationState.setActive(\"whileFocus\",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive(\"whileFocus\",!1),this.isActive=!1)}mount(){this.unmount=vr(pr(this.node.current,\"focus\",()=>this.onFocus()),pr(this.node.current,\"blur\",()=>this.onBlur()))}unmount(){}}function kx(t,s,i){const{props:l}=t;if(t.current instanceof HTMLButtonElement&&t.current.disabled)return;t.animationState&&l.whileTap&&t.animationState.setActive(\"whileTap\",i===\"Start\");const o=\"onTap\"+(i===\"End\"?\"\":i),d=l[o];d&&We.postRender(()=>d(s,jr(s)))}class Z2 extends Na{mount(){const{current:s}=this.node;s&&(this.unmount=_C(s,(i,l)=>(kx(this.node,l,\"Start\"),(o,{success:d})=>kx(this.node,o,d?\"End\":\"Cancel\")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const Kf=new WeakMap,gf=new WeakMap,J2=t=>{const s=Kf.get(t.target);s&&s(t)},W2=t=>{t.forEach(J2)};function eE({root:t,...s}){const i=t||document;gf.has(i)||gf.set(i,{});const l=gf.get(i),o=JSON.stringify(s);return l[o]||(l[o]=new IntersectionObserver(W2,{root:t,...s})),l[o]}function tE(t,s,i){const l=eE(s);return Kf.set(t,i),l.observe(t),()=>{Kf.delete(t),l.unobserve(t)}}const nE={some:0,all:1};class sE extends Na{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:s={}}=this.node.getProps(),{root:i,margin:l,amount:o=\"some\",once:d}=s,f={root:i?i.current:void 0,rootMargin:l,threshold:typeof o==\"number\"?o:nE[o]},m=p=>{const{isIntersecting:y}=p;if(this.isInView===y||(this.isInView=y,d&&!y&&this.hasEnteredView))return;y&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive(\"whileInView\",y);const{onViewportEnter:x,onViewportLeave:g}=this.node.getProps(),w=y?x:g;w&&w(p)};return tE(this.node.current,f,m)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>\"u\")return;const{props:s,prevProps:i}=this.node;[\"amount\",\"margin\",\"root\"].some(aE(s,i))&&this.startObserver()}unmount(){}}function aE({viewport:t={}},{viewport:s={}}={}){return i=>t[i]!==s[i]}const iE={inView:{Feature:sE},tap:{Feature:Z2},focus:{Feature:Q2},hover:{Feature:K2}},lE={layout:{ProjectionNode:lw,MeasureLayout:bw}},rE={...R2,...iE,...X2,...lE},Le=C2(rE,A2),Qh=\"https://rateright-growth-production.up.railway.app\";async function Zh(){try{const{data:{session:t}}=await Nt.auth.getSession();return t?.access_token||null}catch{return null}}async function k(t,s={}){const i=`${Qh}${t}`,l=await Zh(),d={headers:{\"Content-Type\":\"application/json\",...l?{Authorization:`Bearer ${l}`}:{},...s.headers},...s},f=await fetch(i,d);if(!f.ok){const m=await f.json().catch(()=>({error:\"Request failed\"}));throw new Error(m.error||`HTTP ${f.status}`)}return f.status===204?null:f.json()}const Tr={list:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/leads${s?`?${s}`:\"\"}`)},get:t=>k(`/api/leads/${t}`),create:t=>k(\"/api/leads\",{method:\"POST\",body:JSON.stringify(t)}),update:(t,s)=>k(`/api/leads/${t}`,{method:\"PATCH\",body:JSON.stringify(s)}),updateLead:(t,s)=>k(`/api/leads/${t}`,{method:\"PATCH\",body:JSON.stringify(s)}),delete:t=>k(`/api/leads/${t}`,{method:\"DELETE\"}),archive:(t,s)=>k(`/api/leads/${t}/archive`,{method:\"POST\",body:JSON.stringify({reason:s})}),archiveLead:(t,s)=>k(`/api/leads/${t}/archive`,{method:\"POST\",body:JSON.stringify({reason:s})}),importFromSheet:()=>k(\"/api/leads/import-sheet\",{method:\"POST\"}),search:t=>k(`/api/leads/search?q=${encodeURIComponent(t)}`),claim:t=>k(`/api/leads/${t}/claim`,{method:\"POST\"}),release:t=>k(`/api/leads/${t}/release`,{method:\"POST\"}),assignments:()=>k(\"/api/leads/assignments\")},Jk={get:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/call-list${s?`?${s}`:\"\"}`)},stats:()=>k(\"/api/call-list/stats\"),activity:t=>k(`/api/call-list/activity${t?`?date=${t}`:\"\"}`)},Wk={send:t=>k(\"/api/sms/send\",{method:\"POST\",body:JSON.stringify(t)}),batch:t=>k(\"/api/sms/batch\",{method:\"POST\",body:JSON.stringify(t)}),preview:t=>k(\"/api/sms/preview\",{method:\"POST\",body:JSON.stringify(t)}),requestContact:t=>k(\"/api/sms/request-contact\",{method:\"POST\",body:JSON.stringify({leadId:t})}),getTemplates:t=>k(`/api/sms/templates${t?`?category=${t}`:\"\"}`),getTemplate:t=>k(`/api/sms/templates/${t}`),createTemplate:t=>k(\"/api/sms/templates\",{method:\"POST\",body:JSON.stringify(t)}),updateTemplate:(t,s)=>k(`/api/sms/templates/${t}`,{method:\"PUT\",body:JSON.stringify(s)}),deleteTemplate:t=>k(`/api/sms/templates/${t}`,{method:\"DELETE\"}),useTemplate:t=>k(`/api/sms/templates/${t}/use`,{method:\"POST\"}),getConversations:(t=\"all\")=>k(`/api/sms/conversations?filter=${t}`),getConversation:t=>k(`/api/sms/conversation/${t}`),markAsRead:t=>k(`/api/sms/conversation/${t}/read`,{method:\"PATCH\"}),handleConversation:(t,s=!0)=>k(`/api/sms/conversation/${t}/handle`,{method:\"PATCH\",body:JSON.stringify({handled:s})}),getPrioritized:(t=50)=>k(`/api/sms/conversations/prioritized?limit=${t}`),getAiSuggestion:(t,s)=>k(\"/api/sms/ai-suggest\",{method:\"POST\",body:JSON.stringify({leadId:t,lastMessage:s})}),getScheduled:t=>k(`/api/sms/scheduled${t?`?leadId=${t}`:\"\"}`),cancelScheduled:t=>k(`/api/sms/scheduled/${t}`,{method:\"DELETE\"}),getStats:(t=30)=>k(`/api/sms/stats?days=${t}`),sendBatch:t=>k(\"/api/sms/send-batch\",{method:\"POST\",body:JSON.stringify({messages:t})})},oE={log:t=>k(\"/api/calls/log\",{method:\"POST\",body:JSON.stringify(t)}),outcomes:()=>k(\"/api/calls/outcomes\"),getHistory:(t,s=1)=>k(`/api/calls/history/${t}?limit=${s}`)},eR={get:t=>k(`/api/dossier/${t}`),update:(t,s)=>k(`/api/dossier/${t}`,{method:\"PATCH\",body:JSON.stringify(s)}),addFact:(t,s,i=\"manual\")=>k(`/api/dossier/${t}/add-fact`,{method:\"POST\",body:JSON.stringify({fact:s,source:i})}),addCallSummary:(t,s)=>k(`/api/dossier/${t}/add-call-summary`,{method:\"POST\",body:JSON.stringify(s)}),addObjection:(t,s)=>k(`/api/dossier/${t}/add-objection`,{method:\"POST\",body:JSON.stringify(s)})},tR={getAll:()=>k(\"/api/dashboard/all\"),getStats:()=>k(\"/api/dashboard/stats\"),getWisdom:()=>k(\"/api/dashboard/wisdom\"),rateWisdom:(t,s)=>k(\"/api/dashboard/wisdom/rate\",{method:\"POST\",body:JSON.stringify({wisdomId:t,rating:s})}),getStrategy:()=>k(\"/api/dashboard/strategy\"),getPriorityAction:()=>k(\"/api/dashboard/priority-action\"),getSlipping:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/dashboard/slipping${s?`?${s}`:\"\"}`)}},nc={getToken:()=>k(\"/api/voice/token\"),status:()=>k(\"/api/voice/status\"),lookupCaller:t=>k(`/api/voice/lookup-caller?phone=${encodeURIComponent(t)}`)},cE={submit:t=>k(\"/api/bug-report\",{method:\"POST\",body:JSON.stringify(t)})},It={getIntelBrief:t=>k(`/api/ai/intel-brief/${t}`),getLiveIntel:t=>k(`/api/ai/live-intel/${t}`),postCallSummary:t=>k(\"/api/ai/post-call-summary\",{method:\"POST\",body:JSON.stringify(t)}),draftMessage:t=>k(\"/api/ai/draft-message\",{method:\"POST\",body:JSON.stringify(t)}),transcribe:async t=>{const s=new FormData;s.append(\"audio\",t,\"audio.webm\");const i=`${Qh}/api/ai/transcribe`,l=await Zh(),o=l?{Authorization:`Bearer ${l}`}:{},d=await fetch(i,{method:\"POST\",body:s,headers:o});if(!d.ok)throw new Error(\"Transcription failed\");return d.json()},voiceCommand:t=>k(\"/api/ai/voice-command\",{method:\"POST\",body:JSON.stringify(t)}),objectionResponse:t=>k(\"/api/ai/objection-response\",{method:\"POST\",body:JSON.stringify(t)}),getConversionProbability:t=>k(`/api/ai/conversion-probability/${t}`),weeklyInsights:()=>k(\"/api/ai/weekly-insights\",{method:\"POST\"}),cleanupNotes:t=>k(\"/api/ai/cleanup-notes\",{method:\"POST\",body:JSON.stringify(t)}),getInsights:()=>k(\"/api/ai/insights\"),getDeepgramCredentials:()=>k(\"/api/ai/deepgram-credentials\"),saveCopilotSession:t=>k(\"/api/ai/copilot-session\",{method:\"POST\",body:JSON.stringify(t)}),suggestionFeedback:t=>k(\"/api/ai/suggestion-feedback\",{method:\"POST\",body:JSON.stringify(t)}),getSimilarWins:t=>k(`/api/ai/similar-wins/${t}`),getEffectiveResponses:(t,s)=>{const i=s?`?trade=${encodeURIComponent(s)}`:\"\";return k(`/api/ai/effective-responses/${t}${i}`)},companyResearch:(t,s=!1)=>{const i=s?\"?refresh=true\":\"\";return k(`/api/ai/company-research/${encodeURIComponent(t)}${i}`)},personResearch:(t,s=!1)=>k(`/api/ai/person-research/${t}${s?\"?refresh=true\":\"\"}`),updateIntel:t=>k(\"/api/ai/update-intel\",{method:\"POST\",body:JSON.stringify(t)}),parseIntelVoiceNote:t=>k(\"/api/ai/parse-intel-voice\",{method:\"POST\",body:JSON.stringify(t)}),extractContractor:t=>k(\"/api/ai/extract-contractor\",{method:\"POST\",body:JSON.stringify(t)}),addContractorLead:t=>k(\"/api/ai/extract-contractor\",{method:\"POST\",body:JSON.stringify({...t,createLead:!0})}),extractLeadCorrections:t=>k(\"/api/ai/extract-lead-corrections\",{method:\"POST\",body:JSON.stringify(t)}),draftSimilar:t=>k(\"/api/ai/draft-similar\",{method:\"POST\",body:JSON.stringify(t)})},nR={status:()=>k(\"/api/sync/platform/status\"),stats:()=>k(\"/api/sync/platform/stats\"),syncAll:(t={})=>k(\"/api/sync/platform\",{method:\"POST\",body:JSON.stringify(t)}),syncRecent:()=>k(\"/api/sync/platform/recent\",{method:\"POST\"})},sR={getFunnel:()=>k(\"/api/activation/funnel\"),getLeadsAtStage:(t,s)=>{const i=new URLSearchParams({stage:t});return s&&i.append(\"type\",s),k(`/api/activation/leads-at-stage?${i}`)},getStuck:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/activation/stuck${s?`?${s}`:\"\"}`)},getRevenueAtRisk:()=>k(\"/api/activation/revenue-at-risk\"),getMetrics:(t=30)=>k(`/api/activation/metrics?days=${t}`),getTransitions:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/activation/stage-transitions${s?`?${s}`:\"\"}`)},analyze:()=>k(\"/api/activation/analyze\"),generateNudge:t=>k(\"/api/activation/nudge\",{method:\"POST\",body:JSON.stringify({leadId:t})}),bulkNudge:t=>k(\"/api/activation/bulk-nudge\",{method:\"POST\",body:JSON.stringify(t)}),addToCallList:t=>k(\"/api/activation/add-to-call-list\",{method:\"POST\",body:JSON.stringify(t)}),getActionScript:(t,s=\"contractor\")=>k(`/api/activation/action-script?stage=${t}&type=${s}`),getDropoffAnalysis:(t,s=\"contractor\")=>k(`/api/activation/dropoff-analysis?stage=${t}&type=${s}`),getNudgeTemplates:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/activation/nudge-templates${s?`?${s}`:\"\"}`)},createNudgeTemplate:t=>k(\"/api/activation/nudge-templates\",{method:\"POST\",body:JSON.stringify(t)}),updateNudgeTemplate:(t,s)=>k(`/api/activation/nudge-templates/${t}`,{method:\"PATCH\",body:JSON.stringify(s)}),deleteNudgeTemplate:t=>k(`/api/activation/nudge-templates/${t}`,{method:\"DELETE\"}),getJourney:t=>k(`/api/activation/journey/${t}`),getDiagnosis:t=>k(`/api/activation/diagnose/${t}`),getSimilarWins:(t,s=5)=>k(`/api/activation/similar-wins/${t}?limit=${s}`)},hc={list:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/scripts${s?`?${s}`:\"\"}`)},get:t=>k(`/api/scripts/${t}`),create:t=>k(\"/api/scripts\",{method:\"POST\",body:JSON.stringify(t)}),update:(t,s)=>k(`/api/scripts/${t}`,{method:\"PATCH\",body:JSON.stringify(s)}),delete:t=>k(`/api/scripts/${t}`,{method:\"DELETE\"}),startSession:(t,s)=>k(`/api/scripts/${t}/use`,{method:\"POST\",body:JSON.stringify({lead_id:s})}),endSession:(t,s)=>k(`/api/scripts/sessions/${t}`,{method:\"PATCH\",body:JSON.stringify(s)}),getForLead:t=>k(`/api/scripts/for-lead/${t}`),getAIRecommendation:t=>k(`/api/scripts/ai-recommend/${t}`),recordUsage:(t,s=!1)=>k(`/api/scripts/${t}/use`,{method:\"POST\",body:JSON.stringify({replied:s})}),getAnalytics:(t=30)=>k(`/api/scripts/analytics/overview?days=${t}`),getObjections:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/scripts/objections/list${s?`?${s}`:\"\"}`)},getObjection:t=>k(`/api/scripts/objections/${t}`),createObjection:t=>k(\"/api/scripts/objections\",{method:\"POST\",body:JSON.stringify(t)}),addObjectionResponse:(t,s)=>k(`/api/scripts/objections/${t}/response`,{method:\"POST\",body:JSON.stringify({response:s})}),getGuidelines:()=>k(\"/api/scripts/guidelines\"),updateGuidelines:t=>k(\"/api/scripts/guidelines\",{method:\"PUT\",body:JSON.stringify(t)}),getGuidelinesHistory:(t=20)=>k(`/api/scripts/guidelines/history?limit=${t}`),checkCompliance:(t,s={})=>k(\"/api/scripts/compliance/check\",{method:\"POST\",body:JSON.stringify({message:t,options:s})}),autoFix:t=>k(\"/api/scripts/compliance/auto-fix\",{method:\"POST\",body:JSON.stringify({message:t})}),validateScript:t=>k(`/api/scripts/compliance/validate/${t}`,{method:\"POST\"}),batchValidate:t=>k(\"/api/scripts/compliance/batch-validate\",{method:\"POST\",body:JSON.stringify({scriptIds:t})}),getComplianceStats:()=>k(\"/api/scripts/compliance/stats\"),getQueue:(t=\"pending\",s=20)=>k(`/api/scripts/compliance/queue?status=${t}&limit=${s}`),approveItem:t=>k(`/api/scripts/compliance/queue/${t}/approve`,{method:\"POST\"}),rejectItem:(t,s)=>k(`/api/scripts/compliance/queue/${t}/reject`,{method:\"POST\",body:JSON.stringify({reason:s})}),editItem:(t,s)=>k(`/api/scripts/compliance/queue/${t}/edit`,{method:\"POST\",body:JSON.stringify({final_content:s})})},aR={list:()=>k(\"/api/achievements\"),getUserAchievements:()=>k(\"/api/achievements/user\"),check:()=>k(\"/api/achievements/check\",{method:\"POST\"})},iR={getUser:()=>k(\"/api/xp/user\"),award:t=>k(\"/api/xp/award\",{method:\"POST\",body:JSON.stringify(t)}),getHistory:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/xp/history${s?`?${s}`:\"\"}`)},getLeaderboard:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/xp/leaderboard${s?`?${s}`:\"\"}`)}},Rx={list:t=>k(`/api/sequences${t?`?channel=${t}`:\"\"}`),get:t=>k(`/api/sequences/${t}`),enroll:(t,s)=>k(`/api/sequences/${t}/enroll`,{method:\"POST\",body:JSON.stringify({lead_ids:Array.isArray(s)?s:[s]})}),unenroll:(t,s)=>k(`/api/sequences/${t}/unenroll`,{method:\"POST\",body:JSON.stringify({lead_id:s})}),getActiveEnrollments:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/sequences/enrollments/active${s?`?${s}`:\"\"}`)},getLeadEnrollments:t=>k(`/api/sequences/enrollments/lead/${t}`),pauseEnrollment:(t,s)=>k(`/api/sequences/enrollments/${t}/pause`,{method:\"POST\",body:JSON.stringify({reason:s})}),resumeEnrollment:t=>k(`/api/sequences/enrollments/${t}/resume`,{method:\"POST\"}),skipStep:t=>k(`/api/sequences/enrollments/${t}/skip`,{method:\"POST\"}),sendNow:t=>k(`/api/sequences/enrollments/${t}/send-now`,{method:\"POST\"}),getOptOutStatus:t=>k(`/api/sequences/lead/${t}/opt-out`),setOptOut:(t,s)=>k(`/api/sequences/lead/${t}/opt-out`,{method:\"POST\",body:JSON.stringify({opted_out:s})}),bulkEnrollPreview:(t,s=100,i)=>{const l=new URLSearchParams({dry_run:\"true\",limit:s.toString()});return i&&l.set(\"source\",i),k(`/api/sequences/${t}/bulk-enroll?${l}`,{method:\"POST\"})},bulkEnroll:(t,s=100,i)=>{const l=new URLSearchParams({limit:s.toString()});return i&&l.set(\"source\",i),k(`/api/sequences/${t}/bulk-enroll?${l}`,{method:\"POST\"})}},lR={getScores:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/coaching/scores${s?`?${s}`:\"\"}`)},scoreCall:t=>k(\"/api/coaching/score\",{method:\"POST\",body:JSON.stringify(t)}),getTips:()=>k(\"/api/coaching/tips\"),getWeekly:()=>k(\"/api/coaching/weekly\"),getPatterns:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/coaching/patterns${s?`?${s}`:\"\"}`)}},rR={getTrends:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/analytics/trends${s?`?${s}`:\"\"}`)},getPatterns:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/analytics/patterns${s?`?${s}`:\"\"}`)},getFunnel:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/analytics/funnel${s?`?${s}`:\"\"}`)},getBestTimes:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/analytics/best-times${s?`?${s}`:\"\"}`)},getSources:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/analytics/sources${s?`?${s}`:\"\"}`)},savePattern:t=>k(\"/api/analytics/patterns\",{method:\"POST\",body:JSON.stringify(t)})},oR={list:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/ai-alerts${s?`?${s}`:\"\"}`)},create:t=>k(\"/api/ai-alerts\",{method:\"POST\",body:JSON.stringify(t)}),markRead:t=>k(`/api/ai-alerts/${t}/read`,{method:\"PATCH\"}),dismiss:t=>k(`/api/ai-alerts/${t}/dismiss`,{method:\"PATCH\"}),markAllRead:()=>k(\"/api/ai-alerts/read-all\",{method:\"POST\"}),generate:()=>k(\"/api/ai-alerts/generate\",{method:\"POST\"})},cR={getLeaderboard:(t=\"today\")=>k(`/api/battleground/leaderboard?period=${t}`),getUserStats:t=>k(`/api/battleground/leaderboard/${t}`),saveSnapshot:()=>k(\"/api/battleground/leaderboard/snapshot\",{method:\"POST\"}),getHallOfFame:()=>k(\"/api/battleground/hall-of-fame\"),checkRecord:(t,s,i,l,o)=>k(\"/api/battleground/hall-of-fame/check\",{method:\"POST\",body:JSON.stringify({recordType:t,userId:s,userName:i,value:l,details:o})}),getChallenges:()=>k(\"/api/battleground/challenges\"),updateChallengeProgress:(t,s=1)=>k(\"/api/battleground/challenges/progress\",{method:\"POST\",body:JSON.stringify({actionType:t,count:s})}),generateChallenges:()=>k(\"/api/battleground/challenges/generate\",{method:\"POST\"}),getTeamPulse:(t=20)=>k(`/api/battleground/pulse?limit=${t}`),createPulseEvent:t=>k(\"/api/battleground/pulse\",{method:\"POST\",body:JSON.stringify(t)}),getUserBadges:t=>k(`/api/battleground/badges/${t}`),getCurrentBadges:()=>k(\"/api/battleground/badges\"),awardWeeklyBadges:()=>k(\"/api/battleground/badges/award-weekly\",{method:\"POST\"}),updateStreakTier:(t,s)=>k(\"/api/battleground/streak/update\",{method:\"POST\",body:JSON.stringify({userId:t,streakDays:s})}),getActiveDuels:()=>k(\"/api/battleground/duels/active\"),getDuelHistory:(t=10)=>k(`/api/battleground/duels/history?limit=${t}`),getDuelOdds:(t,s)=>k(`/api/battleground/duels/odds?targetId=${t}&duelType=${s}`),createDuel:(t,s,i)=>k(\"/api/battleground/duels/challenge\",{method:\"POST\",body:JSON.stringify({targetId:t,duelType:s,stakeAmount:i})}),acceptDuel:t=>k(`/api/battleground/duels/${t}/accept`,{method:\"POST\"}),declineDuel:t=>k(`/api/battleground/duels/${t}/decline`,{method:\"POST\"}),getDuelScores:t=>k(`/api/battleground/duels/${t}/scores`),createChallenge:t=>k(\"/api/battleground/challenges\",{method:\"POST\",body:JSON.stringify(t)}),joinChallenge:t=>k(`/api/battleground/challenges/${t}/join`,{method:\"POST\"}),getChallengeDetails:t=>k(`/api/battleground/challenges/${t}`),getTeam:()=>k(\"/api/battleground/team\"),getCelebrations:(t=10)=>k(`/api/battleground/celebrations?limit=${t}`)},uR={getToday:()=>k(\"/api/playbook/today\"),send:(t,s,i)=>k(\"/api/playbook/send\",{method:\"POST\",body:JSON.stringify({leadId:t,messageId:s,messageText:i})}),getBulkPreview:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/playbook/bulk-preview${s?`?${s}`:\"\"}`)},bulkSend:(t,s,i={})=>k(\"/api/playbook/bulk-send\",{method:\"POST\",body:JSON.stringify({batchId:t,leadIds:s,edits:i})})},Mx={getRecordings:()=>k(\"/api/voicemail/recordings\"),createRecording:async t=>{const s=await Zh(),i=await fetch(`${Qh}/api/voicemail/recordings`,{method:\"POST\",headers:{Authorization:`Bearer ${s}`},body:t});if(!i.ok){const l=await i.json().catch(()=>({error:\"Upload failed\"}));throw new Error(l.error||\"Failed to upload\")}return i.json()},createRecordingFromUrl:t=>k(\"/api/voicemail/recordings\",{method:\"POST\",body:JSON.stringify(t)}),deleteRecording:t=>k(`/api/voicemail/recordings/${t}`,{method:\"DELETE\"}),setDefault:t=>k(`/api/voicemail/recordings/${t}/default`,{method:\"PATCH\"}),drop:(t,s,i)=>k(\"/api/voicemail/drop\",{method:\"POST\",body:JSON.stringify({callSid:t,recordingId:s,leadId:i})}),getStats:()=>k(\"/api/voicemail/drops/stats\")},dR={getDashboard:(t=\"week\")=>k(`/api/manager/dashboard?period=${t}`),getAnalytics:(t=\"week\")=>k(`/api/manager/analytics?period=${t}`),getRepDetail:(t,s=\"week\")=>k(`/api/manager/rep/${t}?period=${s}`)},fR={getDashboard:()=>k(\"/api/intelligence/dashboard\"),track:t=>k(\"/api/intelligence/track\",{method:\"POST\",body:JSON.stringify(t)}),trackBatch:t=>k(\"/api/intelligence/track-batch\",{method:\"POST\",body:JSON.stringify({events:t})}),getSuggestions:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/intelligence/suggestions${s?`?${s}`:\"\"}`)},updateSuggestionStatus:(t,s)=>k(`/api/intelligence/suggestions/${t}/status`,{method:\"PATCH\",body:JSON.stringify(s)}),getFriction:(t={})=>{const s=new URLSearchParams(t).toString();return k(`/api/intelligence/friction${s?`?${s}`:\"\"}`)},getPageStats:(t=7)=>k(`/api/intelligence/page-stats?days=${t}`),getMetrics:(t,s,i)=>{const l=new URLSearchParams({start_date:t});return s&&l.append(\"end_date\",s),i&&l.append(\"metric_name\",i),k(`/api/intelligence/metrics?${l}`)}},Ox={getVapidKey:()=>k(\"/api/notifications/vapid-public-key\"),subscribe:t=>k(\"/api/notifications/subscribe\",{method:\"POST\",body:JSON.stringify({subscription:t})}),unsubscribe:(t=null)=>k(\"/api/notifications/unsubscribe\",{method:\"DELETE\",body:JSON.stringify({endpoint:t})}),getPreferences:()=>k(\"/api/notifications/preferences\"),updatePreferences:t=>k(\"/api/notifications/preferences\",{method:\"PUT\",body:JSON.stringify(t)}),test:()=>k(\"/api/notifications/test\",{method:\"POST\"}),getStatus:()=>k(\"/api/notifications/status\")},qn=[{id:\"opener\",label:\"Opener\",icon:\"👋\"},{id:\"discovery\",label:\"Discovery\",icon:\"🔍\"},{id:\"value_prop\",label:\"Value Prop\",icon:\"💎\"},{id:\"objections\",label:\"Objections\",icon:\"🛡️\"},{id:\"close\",label:\"Close\",icon:\"🎯\"}],uE={opener:{script:\"Hey, it's [your name] from RateRight. How's it going?\",tip:\"Be warm and conversational. Match their energy.\",alternatives:[\"Hi [name], this is [you] from RateRight - got a quick minute?\",\"G'day [name], [you] here from RateRight. How's business?\"]},discovery:{script:\"What's your biggest challenge finding workers right now?\",tip:\"Listen more than you talk. Take mental notes.\",alternatives:[\"How are you currently sourcing your workers?\",\"What trades are hardest to find good people for?\",\"How many workers do you typically need on a job?\"]},value_prop:{script:\"We connect you with pre-vetted workers at just 9.9% - no lock-in contracts.\",tip:\"Focus on their pain points. Make it about them.\",alternatives:[\"Most of our contractors find workers within 24 hours.\",\"You only pay when they work - no upfront fees.\",\"Every worker is vetted with references and qualifications checked.\"]},objections:{script:\"I hear you. What would need to change for this to make sense?\",tip:\"Don't argue. Acknowledge and redirect.\",alternatives:[\"That's a fair point. Here's how other contractors handle that...\",\"I understand. Can I ask what you're comparing us to?\",\"Makes sense. What if we could address that concern?\"]},close:{script:\"Let me get you set up - it takes about 2 minutes. What's your email?\",tip:\"Assume the sale. Be confident.\",alternatives:[\"When's your next job starting? Let's get you ready.\",\"I'll send you the link now - what email should I use?\",\"Want me to walk you through it while we're on the phone?\"]}};function dE({lead:t,duration:s,onHangUp:i,onMute:l,isMuted:o,onMarkHot:d}){const[f,m]=b.useState(0),[p,y]=b.useState(null),[x,g]=b.useState(null),[w,S]=b.useState(!1),[T,N]=b.useState([]),[R,D]=b.useState(null),[A,C]=b.useState([]);b.useEffect(()=>{t?.id&&(B(),_())},[t?.id]);const B=async()=>{try{const $=await hc.getRecommendation(t.id);$?.script&&y($.script)}catch{console.log(\"Using default scripts\")}},_=async()=>{try{const $=await It.getIntelBrief(t.id);if($){D($);const W=[];$.openingLine&&W.push({type:\"opener\",text:$.openingLine}),$.talkingPoints?.length&&$.talkingPoints.forEach(se=>W.push({type:\"point\",text:se})),$.similarWins?.length&&W.push({type:\"win\",text:`Similar win: ${$.similarWins[0].name} - \"${$.similarWins[0].whatWorked}\"`}),$.company?.sales_angle&&W.push({type:\"angle\",text:$.company.sales_angle}),C(W)}}catch{console.log(\"Intel not available\")}},F=$=>{const W=uE[$];if(!p)return W;switch($){case\"opener\":return{...W,script:p.opening||W.script};case\"discovery\":return{...W,script:p.discovery_questions?.[0]?.question||W.script,alternatives:p.discovery_questions?.slice(1,4).map(se=>se.question)||W.alternatives};case\"value_prop\":return{...W,script:p.value_props?.[0]?.prop||W.script,alternatives:p.value_props?.slice(1,4).map(se=>se.prop)||W.alternatives};case\"objections\":return W;case\"close\":return{...W,script:p.closing_techniques?.[0]?.script||W.script,alternatives:p.closing_techniques?.slice(1,4).map(se=>se.script)||W.alternatives};default:return W}},P=async($,W)=>{await navigator.clipboard.writeText($),g(W),setTimeout(()=>g(null),500)},H=()=>{f{m($)},X=()=>{S(!0),d?.()},te=$=>{const W=Math.floor($/60),se=$%60;return`${W}:${se.toString().padStart(2,\"0\")}`},Y=`${t?.first_name||\"\"} ${t?.last_name||\"\"}`.trim()||\"Unknown\";return c.jsxs(\"div\",{className:\"fixed inset-0 z-[60] bg-slate-900 flex flex-col\",children:[c.jsxs(\"div\",{className:\"bg-slate-800 px-4 py-3 flex items-center justify-between safe-area-top\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-3\",children:[c.jsx(\"div\",{className:\"w-10 h-10 rounded-full bg-slate-700 flex items-center justify-center\",children:c.jsx(cr,{className:\"w-5 h-5 text-slate-400\"})}),c.jsxs(\"div\",{children:[c.jsx(\"h2\",{className:\"font-bold text-white\",children:Y}),c.jsxs(\"div\",{className:\"flex items-center gap-2\",children:[c.jsx(\"div\",{className:\"w-2 h-2 rounded-full bg-green-500 animate-pulse\"}),c.jsx(\"span\",{className:\"text-green-400 font-mono text-sm\",children:te(s)})]})]})]}),c.jsx(\"button\",{onClick:X,disabled:w,className:`p-2 rounded-full ${w?\"bg-amber-500 text-white\":\"bg-slate-700 text-slate-400\"}`,children:c.jsx(nl,{className:\"w-5 h-5\"})})]}),c.jsx(\"div\",{className:\"bg-slate-800/50 px-4 py-3 flex items-center gap-2\",children:qn.map(($,W)=>c.jsxs(\"button\",{onClick:()=>z(W),className:`flex-1 py-2 rounded-lg text-center transition-all ${T.includes(W)?\"bg-emerald-600 text-white\":W===f?\"bg-violet-600 text-white ring-2 ring-violet-400\":\"bg-slate-700/50 text-slate-400\"}`,children:[c.jsx(\"span\",{className:\"text-lg\",children:$.icon}),c.jsx(\"p\",{className:\"text-[10px] font-bold mt-0.5\",children:T.includes(W)?\"✓\":$.label})]},$.id))}),c.jsx(\"div\",{className:\"flex-1 overflow-y-auto pb-40\",children:c.jsxs(\"div\",{className:\"p-4 space-y-4\",children:[A.length>0&&c.jsxs(\"div\",{className:\"bg-blue-500/10 border border-blue-500/20 rounded-xl p-3\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-2 mb-2\",children:[c.jsx(ac,{className:\"w-4 h-4 text-blue-400\"}),c.jsx(\"span\",{className:\"text-xs font-bold text-blue-400 uppercase\",children:\"Intel & Talking Points\"})]}),c.jsx(\"div\",{className:\"space-y-2\",children:A.slice(0,4).map(($,W)=>c.jsxs(\"div\",{className:\"flex items-start gap-2\",children:[c.jsx(\"span\",{className:\"text-blue-400 mt-0.5\",children:$.type===\"opener\"?\"💬\":$.type===\"win\"?\"🏆\":$.type===\"angle\"?\"🎯\":\"•\"}),c.jsx(\"p\",{className:\"text-blue-200/80 text-sm\",children:$.text})]},W))})]}),R?.company?.name&&c.jsxs(\"div\",{className:\"flex items-center gap-2 px-1\",children:[c.jsx(jc,{className:\"w-4 h-4 text-slate-500\"}),c.jsxs(\"span\",{className:\"text-slate-400 text-sm\",children:[R.company.name,R.company.industry&&` • ${R.company.industry}`,R.company.size&&` • ${R.company.size}`]})]}),c.jsxs(\"div\",{className:\"text-center py-2\",children:[c.jsx(\"span\",{className:\"text-3xl\",children:qn[f].icon}),c.jsx(\"h3\",{className:\"text-xl font-bold text-white mt-2\",children:qn[f].label}),c.jsxs(\"p\",{className:\"text-slate-400 text-sm\",children:[\"Stage \",f+1,\" of \",qn.length]})]}),c.jsxs(\"div\",{className:\"bg-gradient-to-br from-violet-600/20 to-purple-600/10 border border-violet-500/30 rounded-2xl p-4\",children:[c.jsxs(\"div\",{className:\"flex items-start justify-between mb-2\",children:[c.jsx(\"span\",{className:\"text-xs font-bold text-violet-400 uppercase\",children:\"Say This\"}),c.jsx(\"button\",{onClick:()=>P(F(qn[f].id).script,\"main\"),className:\"p-2 -m-2 text-slate-400 hover:text-white\",children:x===\"main\"?c.jsx(ba,{className:\"w-4 h-4 text-green-400\"}):c.jsx(Cf,{className:\"w-4 h-4\"})})]}),c.jsxs(\"p\",{className:\"text-white text-lg leading-relaxed\",children:['\"',F(qn[f].id).script,'\"']})]}),c.jsxs(\"div\",{className:\"bg-amber-500/10 border border-amber-500/20 rounded-xl px-4 py-3\",children:[c.jsx(\"span\",{className:\"text-xs font-bold text-amber-400 uppercase\",children:\"💡 Tip\"}),c.jsx(\"p\",{className:\"text-amber-200/80 text-sm mt-1\",children:F(qn[f].id).tip})]}),c.jsxs(\"div\",{children:[c.jsx(\"h4\",{className:\"text-sm font-bold text-slate-400 mb-2 px-1\",children:\"Or Try These:\"}),c.jsx(\"div\",{className:\"space-y-2\",children:F(qn[f].id).alternatives.map(($,W)=>c.jsxs(\"div\",{className:\"bg-slate-800/50 border border-slate-700 rounded-xl p-3 flex items-start gap-3\",children:[c.jsxs(\"p\",{className:\"text-slate-300 text-sm flex-1\",children:['\"',$,'\"']}),c.jsx(\"button\",{onClick:()=>P($,`alt-${W}`),className:\"p-1 text-slate-500 hover:text-white flex-shrink-0\",children:x===`alt-${W}`?c.jsx(ba,{className:\"w-4 h-4 text-green-400\"}):c.jsx(Cf,{className:\"w-4 h-4\"})})]},W))})]}),f(i&&s?W(s):se(),()=>{ie()}),[]);const W=ee=>{console.log(\"[TwilioCall] Attaching to inbound call\"),X.current=ee,p(\"in-progress\"),Y.current=Date.now(),I();const ge=ee.parameters?.CallSid||null;console.log(\"[TwilioCall] Inbound call CallSid:\",ge),d?.(ge),ee.on(\"disconnect\",()=>{const Ee=Y.current?Math.floor((Date.now()-Y.current)/1e3):0;console.log(\"[TwilioCall] Inbound call disconnected, duration:\",Ee),p(\"ended\"),K(),$.current||($.current=!0,setTimeout(()=>{o?.(Ee)},500))}),ee.on(\"error\",Ee=>{console.error(\"[TwilioCall] Inbound call error:\",Ee),T(Ee.message),p(\"ended\"),K()})},se=async()=>{try{const{token:ee}=await nc.getToken(),ge=new Cb(ee,{logLevel:\"debug\",codecPreferences:[\"opus\",\"pcmu\"],enableRingingState:!0,edge:\"ashburn\"});ge.on(\"error\",Ee=>{console.error(\"Twilio Device error:\",Ee),T(Ee.message),p(\"ended\")}),z.current=ge,p(\"ready\"),O()}catch(ee){console.error(\"Failed to initialize Twilio:\",ee),T(ee.message),p(\"ended\")}},O=async()=>{if(z.current){if(!t?.phone){T(\"No phone number for this lead\"),p(\"ended\");return}try{p(\"connecting\");const ee=await z.current.connect({params:{To:t.phone,leadId:t?.id}});X.current=ee,ee.on(\"ringing\",()=>{p(\"ringing\")}),ee.on(\"accept\",()=>{p(\"in-progress\"),Y.current=Date.now(),I();const ge=ee.parameters?.CallSid||null;console.log(\"[TwilioCall] Call connected, CallSid:\",ge),d?.(ge)}),ee.on(\"disconnect\",()=>{const ge=Y.current?Math.floor((Date.now()-Y.current)/1e3):0;p(\"ended\"),K(),$.current||($.current=!0,setTimeout(()=>{o?.(ge)},500))}),ee.on(\"cancel\",()=>{p(\"ended\"),K(),$.current||($.current=!0,o?.(0))}),ee.on(\"error\",ge=>{console.error(\"Call error:\",ge),T(ge.message),p(\"ended\"),K()})}catch(ee){console.error(\"Failed to make call:\",ee),T(ee.message),p(\"ended\")}}},I=()=>{te.current=setInterval(()=>{Y.current&&x(Math.floor((Date.now()-Y.current)/1e3))},1e3)},K=()=>{te.current&&(clearInterval(te.current),te.current=null)},ie=()=>{K(),!i&&X.current&&X.current.disconnect(),!i&&z.current&&z.current.destroy()},oe=()=>{X.current?X.current.disconnect():l?.()},xe=()=>{X.current&&(g?X.current.mute(!1):X.current.mute(!0),w(!g))},Te=async()=>{if(!(D.length>0)){B(!0);try{const ee=await Mx.getRecordings();A(ee||[])}catch(ee){console.error(\"Failed to load VM recordings:\",ee)}finally{B(!1)}}},ae=async ee=>{const ge=X.current?.parameters?.CallSid;if(!ge){console.error(\"No CallSid available\");return}F(!0);try{await Mx.drop(ge,ee.id,t?.id),H(!0),R(!1)}catch(Ee){console.error(\"VM drop failed:\",Ee),T(\"Failed to drop voicemail\")}finally{F(!1)}},ce=ee=>{const ge=Math.floor(ee/60),Ee=ee%60;return`${ge}:${Ee.toString().padStart(2,\"0\")}`},ne=()=>{switch(m){case\"initializing\":return\"Setting up...\";case\"ready\":return\"Starting call...\";case\"connecting\":return\"Connecting...\";case\"ringing\":return\"Ringing...\";case\"in-progress\":return ce(y);case\"ended\":return\"Call ended\";default:return\"\"}},ue=()=>{switch(m){case\"ringing\":return\"text-amber-400\";case\"in-progress\":return\"text-green-400\";case\"ended\":return\"text-slate-400\";default:return\"text-blue-400\"}},de=`${t?.first_name||\"\"} ${t?.last_name||\"\"}`.trim()||\"Unknown\";return m===\"in-progress\"&&t?c.jsx(dE,{lead:t,duration:y,isMuted:g,onMute:xe,onHangUp:oe,onMarkHot:()=>{console.log(\"Marked hot during call\")}}):c.jsxs(Le.div,{initial:{y:100,opacity:0},animate:{y:0,opacity:1},exit:{y:100,opacity:0},className:\"fixed bottom-0 inset-x-0 z-[60] bg-gradient-to-t from-slate-900 via-slate-900 to-slate-900/95 rounded-t-3xl shadow-2xl pb-safe\",children:[c.jsxs(\"div\",{className:\"px-4 pt-4 pb-2 flex items-center gap-3\",children:[c.jsx(\"div\",{className:\"w-12 h-12 rounded-full bg-slate-700 flex items-center justify-center flex-shrink-0\",children:c.jsx(cr,{className:\"w-6 h-6 text-slate-400\"})}),c.jsxs(\"div\",{className:\"flex-1 min-w-0\",children:[c.jsx(\"h2\",{className:\"text-lg font-bold text-white truncate\",children:de}),c.jsxs(\"div\",{className:\"flex items-center gap-2\",children:[c.jsx(\"span\",{className:`text-sm font-medium ${ue()}`,children:ne()}),m===\"in-progress\"&&f&&c.jsxs(\"div\",{className:\"flex items-center gap-1\",children:[c.jsx(Yj,{className:\"w-3 h-3 text-emerald-400 animate-pulse\"}),c.jsx(\"span\",{className:\"text-xs text-emerald-400\",children:\"Recording\"})]})]})]}),m===\"ringing\"&&c.jsx(\"div\",{className:\"relative w-8 h-8\",children:c.jsx(Le.div,{className:\"absolute inset-0 rounded-full border-2 border-amber-400/50\",animate:{scale:[1,1.5],opacity:[.5,0]},transition:{duration:1.5,repeat:1/0}})})]}),S&&c.jsx(\"p\",{className:\"text-red-400 text-sm text-center px-4 pb-2\",children:S}),c.jsx(\"div\",{className:\"px-4 pb-6 pt-2\",children:m!==\"ended\"?c.jsxs(\"div\",{className:\"flex items-center justify-center gap-6\",children:[c.jsx(\"button\",{onClick:xe,disabled:m!==\"in-progress\",title:g?\"Unmute\":\"Mute\",className:`w-14 h-14 rounded-full flex items-center justify-center transition-colors ${g?\"bg-red-500 text-white\":\"bg-slate-700 text-white disabled:opacity-50\"}`,children:g?c.jsx(Tc,{className:\"w-6 h-6\"}):c.jsx(ti,{className:\"w-6 h-6\"})}),c.jsx(\"button\",{onClick:oe,title:\"End call\",className:\"w-16 h-16 rounded-full bg-red-500 text-white flex items-center justify-center shadow-lg shadow-red-500/30 active:scale-95 transition-transform\",children:c.jsx(ur,{className:\"w-8 h-8\"})}),c.jsx(\"button\",{onClick:()=>{R(!0),Te()},disabled:m===\"initializing\"||m===\"connecting\"||P,title:P?\"Voicemail dropped!\":\"Drop voicemail\",className:`w-14 h-14 rounded-full flex items-center justify-center transition-colors ${P?\"bg-green-600 text-white\":\"bg-amber-600 text-white disabled:opacity-50\"}`,children:P?c.jsx(ba,{className:\"w-6 h-6\"}):c.jsx(ey,{className:\"w-6 h-6\"})})]}):c.jsx(\"button\",{onClick:()=>{$.current||($.current=!0,o?.(y))},className:\"w-full py-4 bg-blue-600 text-white rounded-xl font-bold text-lg\",children:\"Continue\"})}),c.jsx(si,{children:N&&c.jsx(Le.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:\"fixed inset-0 z-[70] bg-black/60 flex items-end justify-center\",onClick:()=>R(!1),children:c.jsxs(Le.div,{initial:{y:\"100%\"},animate:{y:0},exit:{y:\"100%\"},className:\"w-full max-w-md bg-slate-800 rounded-t-2xl p-4 pb-8\",onClick:ee=>ee.stopPropagation(),children:[c.jsxs(\"div\",{className:\"flex items-center justify-between mb-4\",children:[c.jsx(\"h3\",{className:\"text-lg font-bold text-white\",children:\"Drop Voicemail\"}),c.jsx(\"button\",{onClick:()=>R(!1),className:\"w-8 h-8 rounded-full bg-slate-700 flex items-center justify-center\",children:c.jsx(Gt,{className:\"w-5 h-5 text-slate-400\"})})]}),C?c.jsx(\"div\",{className:\"flex items-center justify-center py-8\",children:c.jsx(_n,{className:\"w-6 h-6 text-blue-400 animate-spin\"})}):D.length===0?c.jsxs(\"div\",{className:\"text-center py-8 text-slate-400\",children:[\"No voicemail recordings yet.\",c.jsx(\"br\",{}),c.jsx(\"span\",{className:\"text-sm\",children:\"Add recordings in Settings → Voicemail\"})]}):c.jsx(\"div\",{className:\"space-y-2 max-h-64 overflow-y-auto\",children:D.map(ee=>c.jsxs(\"button\",{onClick:()=>ae(ee),disabled:_,className:\"w-full p-3 bg-slate-700/50 rounded-xl flex items-center gap-3 hover:bg-slate-700 transition-colors disabled:opacity-50\",children:[c.jsx(\"div\",{className:\"w-10 h-10 rounded-full bg-amber-600/20 flex items-center justify-center flex-shrink-0\",children:c.jsx(ey,{className:\"w-5 h-5 text-amber-400\"})}),c.jsxs(\"div\",{className:\"flex-1 text-left\",children:[c.jsx(\"p\",{className:\"text-white font-medium\",children:ee.name}),ee.description&&c.jsx(\"p\",{className:\"text-slate-400 text-sm truncate\",children:ee.description})]}),ee.is_default&&c.jsx(\"span\",{className:\"text-xs bg-blue-600/30 text-blue-400 px-2 py-0.5 rounded\",children:\"Default\"}),_&&c.jsx(_n,{className:\"w-4 h-4 text-blue-400 animate-spin\"})]},ee.id))}),c.jsx(\"p\",{className:\"text-xs text-slate-500 text-center mt-4\",children:\"Selecting a voicemail will play it to the recipient and end the call\"})]})})})]})}function hE({candidate:t,sourceLeadId:s,onAdd:i,onDismiss:l}){const{user:o}=br(),[d,f]=b.useState(!1),m=async()=>{f(!0);try{const x=await It.addContractorLead({sourceLeadId:s,companyName:t.company,projectName:t.project,userEmail:o?.email||\"unknown\"});x.success&&x.lead_id?i(x.lead_id,t):alert(\"Failed to create lead\")}catch(x){console.error(\"Add contractor error:\",x),alert(\"Failed to create lead: \"+x.message)}finally{f(!1)}},p=`${t.first_name||\"\"} ${t.last_name||\"\"}`.trim(),y=Math.round((t.confidence||.5)*100);return c.jsxs(\"div\",{className:\"fixed inset-0 z-50 flex items-center justify-center p-4\",children:[c.jsx(\"div\",{className:\"absolute inset-0 bg-black/60 backdrop-blur-sm\",onClick:l}),c.jsxs(\"div\",{className:\"relative w-full max-w-sm bg-white rounded-2xl shadow-2xl overflow-hidden animate-fade-in\",children:[c.jsx(\"div\",{className:\"bg-gradient-to-r from-amber-500 to-orange-500 px-5 py-4\",children:c.jsxs(\"div\",{className:\"flex items-center justify-between\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-3\",children:[c.jsx(\"div\",{className:\"w-10 h-10 bg-white/20 rounded-xl flex items-center justify-center\",children:c.jsx(nl,{className:\"w-5 h-5 text-white\"})}),c.jsxs(\"div\",{children:[c.jsx(\"h2\",{className:\"text-white font-bold text-lg\",children:\"Contractor Found!\"}),c.jsxs(\"p\",{className:\"text-white/80 text-sm\",children:[y,\"% confidence\"]})]})]}),c.jsx(\"button\",{onClick:l,className:\"w-8 h-8 bg-white/20 rounded-full flex items-center justify-center\",children:c.jsx(Gt,{className:\"w-4 h-4 text-white\"})})]})}),c.jsxs(\"div\",{className:\"p-5\",children:[c.jsxs(\"div\",{className:\"text-center mb-4\",children:[c.jsx(\"h3\",{className:\"text-xl font-bold text-slate-900\",children:p||\"Unknown\"}),t.job_title&&c.jsxs(\"div\",{className:\"flex items-center justify-center gap-2 mt-1 text-slate-600\",children:[c.jsx(Eb,{className:\"w-4 h-4\"}),c.jsx(\"span\",{children:t.job_title})]})]}),c.jsxs(\"div\",{className:\"bg-slate-50 rounded-xl p-4 mb-4 space-y-2\",children:[t.company&&c.jsxs(\"div\",{className:\"flex items-center gap-2 text-slate-700\",children:[c.jsx(Fj,{className:\"w-4 h-4 text-slate-400\"}),c.jsx(\"span\",{className:\"font-semibold\",children:t.company})]}),t.project&&c.jsxs(\"div\",{className:\"flex items-center gap-2 text-slate-600\",children:[c.jsx(ty,{className:\"w-4 h-4 text-slate-400\"}),c.jsxs(\"span\",{children:[t.project,\" Project\"]})]}),t.location&&c.jsxs(\"div\",{className:\"flex items-center gap-2 text-slate-500 text-sm\",children:[c.jsx(ty,{className:\"w-4 h-4 text-slate-400\"}),c.jsx(\"span\",{children:t.location})]})]}),t.linkedin_url&&c.jsxs(\"a\",{href:t.linkedin_url,target:\"_blank\",rel:\"noopener noreferrer\",className:\"flex items-center justify-center gap-2 mb-4 py-2 bg-[#0A66C2] text-white rounded-lg text-sm font-medium hover:bg-[#004182]\",children:[c.jsx(Xj,{className:\"w-4 h-4\"}),\"View LinkedIn Profile\"]}),t.source_worker&&c.jsx(\"div\",{className:\"bg-amber-50 rounded-lg p-3 mb-4 border border-amber-200\",children:c.jsxs(\"p\",{className:\"text-sm text-amber-800\",children:[c.jsx(\"span\",{className:\"font-semibold\",children:\"Source:\"}),\" Worker intel from \",t.source_worker]})}),c.jsxs(\"div\",{className:\"flex gap-3\",children:[c.jsx(\"button\",{onClick:l,className:\"flex-1 py-3 bg-slate-100 text-slate-700 rounded-xl font-semibold hover:bg-slate-200\",children:\"Dismiss\"}),c.jsxs(\"button\",{onClick:m,disabled:d,className:\"flex-1 py-3 bg-gradient-to-r from-green-500 to-emerald-500 text-white rounded-xl font-semibold flex items-center justify-center gap-2 hover:from-green-600 hover:to-emerald-600 disabled:opacity-50\",children:[d?c.jsx(_n,{className:\"w-5 h-5 animate-spin\"}):c.jsx(Af,{className:\"w-5 h-5\"}),\"Add as Lead\"]})]})]})]})]})}function mE(t){const s=Math.floor(t/60),i=t%60;return`${s}:${i.toString().padStart(2,\"0\")}`}const pE={opener:\"Opener\",discovery:\"Discovery\",value_prop:\"Value Props\",objections:\"Objections\",close:\"Close\"},_x=[\"opener\",\"discovery\",\"value_prop\",\"objections\",\"close\"];function gE({duration:t,leadName:s,isListening:i,onMinimize:l}){return c.jsxs(\"div\",{className:\"bg-slate-800 px-4 py-3 flex items-center justify-between safe-area-top\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-3\",children:[c.jsx(\"div\",{className:`w-2.5 h-2.5 rounded-full ${i?\"bg-red-500 animate-pulse\":\"bg-slate-500\"}`}),c.jsx(\"span\",{className:\"text-white font-mono text-lg font-bold tabular-nums\",children:mE(t)})]}),c.jsx(\"span\",{className:\"text-white font-medium truncate max-w-32\",children:s||\"Unknown\"}),c.jsx(\"button\",{onClick:l,className:\"p-2 -mr-2 text-slate-400 hover:text-white\",children:c.jsx(Kj,{className:\"w-5 h-5\"})})]})}function yE({intel:t}){const s=t?.personal_intel?.conversation_starters||t?.person?.conversation_starters||[],i=t?.personal_intel?.interest_news||t?.interest_news,l=[];return i?.items?.length>0&&i.items.slice(0,2).forEach(o=>{l.push({type:\"news\",text:o.talking_point||o.headline,source:o.topic||o.source,emoji:o.topic?.toLowerCase().includes(\"liverpool\")?\"⚽\":o.topic?.toLowerCase().includes(\"f1\")?\"🏎️\":o.topic?.toLowerCase().includes(\"gaa\")?\"🏐\":\"📰\"})}),s.slice(0,3-l.length).forEach(o=>{l.push({type:\"starter\",text:typeof o==\"string\"?o:o.text,source:typeof o==\"string\"?null:o.topic,emoji:\"💬\"})}),l.length===0?null:c.jsxs(\"div\",{className:\"bg-gradient-to-r from-blue-500/20 to-purple-500/20 border border-blue-500/30 rounded-2xl p-3\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-2 mb-2\",children:[c.jsx(\"span\",{className:\"text-sm\",children:\"🎯\"}),c.jsx(\"span\",{className:\"text-xs font-bold text-blue-300 uppercase tracking-wide\",children:\"Ice Breakers\"})]}),c.jsx(\"div\",{className:\"space-y-2\",children:l.map((o,d)=>c.jsxs(\"div\",{className:\"flex items-start gap-2\",children:[c.jsx(\"span\",{className:\"text-base flex-shrink-0\",children:o.emoji}),c.jsxs(\"div\",{className:\"flex-1 min-w-0\",children:[c.jsxs(\"p\",{className:\"text-white text-sm leading-snug\",children:['\"',o.text,'\"']}),o.source&&c.jsx(\"p\",{className:\"text-slate-400 text-xs mt-0.5\",children:o.source})]})]},d))})]})}function xE({stage:t,script:s,openingLine:i}){const[l,o]=b.useState(!1),d=_x.indexOf(t),m=(()=>{if(!s)return i||\"Hey, it's [your name] from RateRight. How's it going?\";switch(t){case\"opener\":return s.opening||i||\"Hey, it's [your name] from RateRight. How's it going?\";case\"discovery\":return s.discovery_questions?.[0]?.question||\"What's your biggest challenge finding workers right now?\";case\"value_prop\":return s.value_props?.[0]?.prop||\"We connect you with pre-vetted workers at just 9.9% - no lock-in contracts.\";case\"objections\":return\"Listen for concerns and address them directly.\";case\"close\":return s.closing_techniques?.[0]?.script||\"Let me get you set up - it takes about 2 minutes. What's your email?\";default:return s.opening||\"Start the conversation...\"}})(),p=async()=>{await navigator.clipboard.writeText(m),o(!0),setTimeout(()=>o(!1),500)};return c.jsxs(\"div\",{className:\"bg-slate-800/50 border border-slate-700 rounded-2xl p-4 relative\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-2 mb-3\",children:[c.jsx(\"span\",{className:\"text-xs font-bold text-violet-400 uppercase tracking-wide\",children:pE[t]||\"Script\"}),c.jsx(\"div\",{className:\"flex-1 h-px bg-slate-700\"}),c.jsxs(\"span\",{className:\"text-xs text-slate-500\",children:[d+1,\"/\",_x.length]})]}),c.jsxs(\"p\",{className:\"text-white text-base leading-relaxed pr-8\",children:['\"',m,'\"']}),c.jsx(\"button\",{onClick:p,className:\"absolute top-4 right-4 p-2 text-slate-400 hover:text-white transition-colors\",children:l?c.jsx(ba,{className:\"w-4 h-4 text-green-400\"}):c.jsx(Cf,{className:\"w-4 h-4\"})})]})}function bE({company:t,person:s,onExpand:i}){if(!t&&!s)return null;const l=[];return t?.name&&l.push(t.name),t?.industry&&l.push(t.industry),t?.size?l.push(t.size):s?.job_title&&l.push(s.job_title),l.length===0?null:c.jsxs(\"button\",{onClick:i,className:\"bg-slate-800/30 border border-slate-700/50 rounded-xl px-4 py-2.5 flex items-center gap-3 w-full text-left\",children:[c.jsx(jc,{className:\"w-4 h-4 text-blue-400 flex-shrink-0\"}),c.jsx(\"span\",{className:\"text-sm text-slate-300 truncate flex-1\",children:l.join(\" • \")}),c.jsx(Ab,{className:\"w-4 h-4 text-slate-500 flex-shrink-0\"})]})}function vE({type:t,trigger:s,suggestion:i,onDismiss:l}){const o=t===\"buying_signal\";return c.jsxs(Le.div,{initial:{y:100,opacity:0,scale:.95},animate:{y:0,opacity:1,scale:1},exit:{y:100,opacity:0,scale:.95},transition:{type:\"spring\",damping:25,stiffness:300},className:`w-full rounded-2xl overflow-hidden relative ${o?\"bg-gradient-to-br from-emerald-500/20 to-green-500/10 border border-emerald-500/50\":\"bg-gradient-to-br from-amber-500/20 to-orange-500/10 border border-amber-500/50\"}`,children:[c.jsxs(\"div\",{className:`px-4 py-2 flex items-center gap-2 ${o?\"bg-emerald-500/30\":\"bg-amber-500/30\"}`,children:[c.jsx(\"span\",{className:\"text-lg\",children:o?\"🔥\":\"⚠️\"}),c.jsx(\"span\",{className:`font-bold text-sm uppercase tracking-wide ${o?\"text-emerald-300\":\"text-amber-300\"}`,children:o?\"BUYING SIGNAL\":i?.objection_type===\"price\"?\"PRICE CONCERN\":i?.objection_type===\"timing\"?\"TIMING ISSUE\":i?.objection_type===\"trust\"?\"TRUST CONCERN\":\"OBJECTION\"})]}),c.jsx(\"div\",{className:\"px-4 pt-3 pb-2\",children:c.jsxs(\"p\",{className:\"text-slate-400 text-sm italic truncate\",children:['\"',s,'\"']})}),c.jsxs(\"div\",{className:\"px-4 pb-3\",children:[c.jsxs(\"p\",{className:\"text-white text-lg font-medium leading-snug\",children:['\"',i?.response||\"Handle this naturally...\",'\"']}),c.jsx(\"p\",{className:\"text-slate-500 text-xs italic mt-1\",children:\"Adapt in your own voice\"})]}),i?.key_point&&c.jsx(\"div\",{className:\"px-4 pb-2\",children:c.jsxs(\"div\",{className:`inline-flex items-center gap-1.5 rounded-full px-3 py-1 ${o?\"bg-emerald-500/20 border border-emerald-500/30\":\"bg-amber-500/20 border border-amber-500/30\"}`,children:[c.jsx(ac,{className:`w-3 h-3 ${o?\"text-emerald-400\":\"text-amber-400\"}`}),c.jsx(\"span\",{className:`text-xs font-medium ${o?\"text-emerald-300\":\"text-amber-300\"}`,children:i.key_point})]})}),i?.follow_up_question&&c.jsxs(\"div\",{className:\"px-4 pb-4 flex items-start gap-2\",children:[c.jsx(Qj,{className:`w-4 h-4 mt-0.5 flex-shrink-0 ${o?\"text-emerald-400\":\"text-amber-400\"}`}),c.jsxs(\"div\",{children:[c.jsx(\"span\",{className:`text-xs font-bold ${o?\"text-emerald-400\":\"text-amber-400\"}`,children:\"THEN ASK:\"}),c.jsxs(\"span\",{className:\"text-slate-300 text-sm ml-1\",children:['\"',i.follow_up_question,'\"']})]})]}),c.jsx(\"button\",{onClick:l,className:\"absolute top-2 right-2 p-2 text-slate-400 hover:text-white\",children:c.jsx(Gt,{className:\"w-4 h-4\"})})]})}function wE({isMuted:t,onMute:s,onMarkHot:i,onEndCall:l,markedHot:o}){return c.jsx(\"div\",{className:\"bg-slate-800 border-t border-slate-700 px-4 py-4 safe-area-bottom\",children:c.jsxs(\"div\",{className:\"flex items-center justify-center gap-4\",children:[c.jsx(\"button\",{onClick:s,className:`w-14 h-14 rounded-full flex items-center justify-center transition-colors ${t?\"bg-red-500 text-white\":\"bg-slate-700 text-slate-300\"}`,children:t?c.jsx(Tc,{className:\"w-6 h-6\"}):c.jsx(ti,{className:\"w-6 h-6\"})}),c.jsx(\"button\",{onClick:i,disabled:o,className:`w-14 h-14 rounded-full flex items-center justify-center transition-colors ${o?\"bg-amber-500 text-white\":\"bg-amber-500/20 border border-amber-500/50 text-amber-400\"}`,children:c.jsx(nl,{className:\"w-6 h-6\"})}),c.jsxs(\"button\",{onClick:l,className:\"px-8 py-4 rounded-full bg-red-500 text-white font-bold flex items-center gap-2 active:scale-95 transition-transform\",children:[c.jsx(ur,{className:\"w-5 h-5\"}),c.jsx(\"span\",{children:\"End\"})]})]})})}function SE({intel:t,leadName:s,onClose:i}){return t?c.jsx(Le.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:\"fixed inset-0 z-[60] bg-black/70 flex items-end\",onClick:i,children:c.jsx(Le.div,{initial:{y:\"100%\"},animate:{y:0},exit:{y:\"100%\"},transition:{type:\"spring\",damping:25,stiffness:300},className:\"bg-slate-800 rounded-t-3xl w-full max-h-[70vh] overflow-y-auto\",onClick:l=>l.stopPropagation(),children:c.jsxs(\"div\",{className:\"p-4\",children:[c.jsx(\"div\",{className:\"w-12 h-1 bg-slate-600 rounded-full mx-auto mb-4\"}),c.jsxs(\"h3\",{className:\"text-lg font-bold text-white mb-4\",children:[\"Intel: \",s]}),t.company&&c.jsxs(\"div\",{className:\"bg-slate-700/50 rounded-xl p-4 mb-3\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-2 mb-2\",children:[c.jsx(jc,{className:\"w-4 h-4 text-blue-400\"}),c.jsx(\"span\",{className:\"text-sm font-semibold text-white\",children:t.company.name})]}),c.jsxs(\"div\",{className:\"flex flex-wrap gap-2\",children:[t.company.industry&&c.jsx(\"span\",{className:\"px-2 py-1 bg-blue-500/20 text-blue-300 text-xs rounded\",children:t.company.industry}),t.company.size&&c.jsx(\"span\",{className:\"px-2 py-1 bg-slate-600 text-slate-300 text-xs rounded\",children:t.company.size}),t.company.location&&c.jsx(\"span\",{className:\"px-2 py-1 bg-slate-600 text-slate-300 text-xs rounded\",children:t.company.location})]}),t.company.sales_angle&&c.jsxs(\"div\",{className:\"mt-3 p-2 bg-emerald-500/10 border border-emerald-500/30 rounded-lg\",children:[c.jsx(\"span\",{className:\"text-xs text-emerald-400 font-semibold\",children:\"SALES ANGLE: \"}),c.jsx(\"span\",{className:\"text-sm text-slate-300\",children:t.company.sales_angle})]})]}),t.person?.job_title&&c.jsxs(\"div\",{className:\"bg-slate-700/50 rounded-xl p-4 mb-3\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-2 mb-1\",children:[c.jsx(\"span\",{className:\"text-lg\",children:\"👤\"}),c.jsx(\"span\",{className:\"text-sm font-semibold text-white\",children:s})]}),c.jsx(\"p\",{className:\"text-slate-400 text-sm\",children:t.person.job_title}),t.person.years_at_company&&c.jsxs(\"p\",{className:\"text-slate-500 text-xs mt-1\",children:[t.person.years_at_company,\" years at company\"]})]}),t.similar_wins?.length>0&&c.jsxs(\"div\",{className:\"bg-slate-700/50 rounded-xl p-4\",children:[c.jsxs(\"div\",{className:\"flex items-center gap-2 mb-2\",children:[c.jsx(\"span\",{className:\"text-lg\",children:\"🏆\"}),c.jsx(\"span\",{className:\"text-sm font-semibold text-amber-400\",children:\"Similar Wins\"})]}),c.jsx(\"div\",{className:\"space-y-2\",children:t.similar_wins.slice(0,3).map((l,o)=>c.jsxs(\"div\",{className:\"text-sm\",children:[c.jsx(\"span\",{className:\"text-slate-300\",children:l.name}),l.key_factor&&c.jsxs(\"span\",{className:\"text-slate-500\",children:[' — \"',l.key_factor,'\"']})]},o))})]})]})})}):null}function jE({lead:t,duration:s,isListening:i,isMuted:l,script:o,scriptStage:d,intel:f,latestSuggestion:m,openingLine:p,error:y,onMinimize:x,onMute:g,onMarkHot:w,onEndCall:S,onDismissSuggestion:T}){const[N,R]=b.useState(!1),[D,A]=b.useState(!1),C=()=>{A(!0),w?.()};return c.jsxs(\"div\",{className:\"fixed inset-0 z-50 bg-slate-900 flex flex-col\",children:[c.jsx(gE,{duration:s,leadName:t?.first_name,isListening:i,onMinimize:x}),c.jsxs(\"div\",{className:\"flex-1 flex flex-col p-4 gap-3 overflow-hidden\",children:[c.jsx(yE,{intel:f}),c.jsx(xE,{stage:d,script:o,openingLine:p}),c.jsx(bE,{company:f?.company,person:f?.person,onExpand:()=>R(!0)}),y&&c.jsxs(\"div\",{className:\"bg-red-500/10 border border-red-500/30 rounded-xl px-4 py-2 flex items-center gap-2\",children:[c.jsx(Db,{className:\"w-4 h-4 text-red-400 flex-shrink-0\"}),c.jsx(\"span\",{className:\"text-red-400 text-sm\",children:y})]}),c.jsxs(\"div\",{className:\"flex-1 flex items-center justify-center px-2\",children:[c.jsx(si,{mode:\"wait\",children:m&&c.jsx(vE,{type:m.type,trigger:m.trigger,suggestion:m.suggestion,onDismiss:T},m.timestamp)}),!m&&i&&c.jsx(\"div\",{className:\"text-center\",children:c.jsxs(\"div\",{className:\"flex items-center justify-center gap-2 text-slate-500\",children:[c.jsx(\"div\",{className:\"w-2 h-2 bg-violet-500 rounded-full animate-pulse\"}),c.jsx(\"span\",{className:\"text-sm\",children:\"Listening for signals...\"})]})})]})]}),c.jsx(wE,{isMuted:l,onMute:g,onMarkHot:C,onEndCall:S,markedHot:D}),c.jsx(si,{children:N&&c.jsx(SE,{intel:f,leadName:t?.first_name,onClose:()=>R(!1)})})]})}const TE={discovery:[\"tell me about\",\"what do you\",\"how many\",\"when did\",\"how long\",\"what's your\",\"who is\"],value_prop:[\"we can help\",\"our platform\",\"rateright\",\"workers available\",\"save you\",\"percentage\"],objections:[\"price\",\"cost\",\"expensive\",\"not sure\",\"competitor\",\"think about\"],close:[\"next step\",\"sign up\",\"get started\",\"send you\",\"email\",\"ready to\"]},NE=[\"expensive\",\"cost\",\"price\",\"too much\",\"can't afford\",\"not sure\",\"think about\",\"need to check\",\"competitor\",\"already have\",\"not interested\",\"busy\",\"later\",\"call back\",\"happy with\",\"current provider\",\"contract\",\"locked in\"],CE=[/works?\\s+for\\s+(.+?)\\s+on\\s+(?:the\\s+)?(.+?)(?:\\s+project|\\s+site|\\s+job|[.!?]|$)/i,/(?:i|we)\\s+work\\s+for\\s+(.+?)(?:\\s+on|\\s+at|[.!?]|$)/i,/(?:my|the)\\s+boss\\s+(?:is\\s+)?(?:at\\s+)?(.+?)(?:[.!?]|$)/i,/working\\s+(?:for|with)\\s+(.+?)(?:\\s+on|\\s+at|[.!?]|$)/i],AE=[/^hey system[,:]?\\s*(.+)/i,/^command[,:]?\\s*(.+)/i,/^note[,:]?\\s*(.+)/i,/^mark\\s+(hot|warm|cold|engaged|converted|lost)/i,/^callback\\s+(.+)/i,/^skip$/i],EE=[\"when can you start\",\"when can we start\",\"how do i sign up\",\"how do we sign up\",\"what's the next step\",\"what is the next step\",\"next steps\",\"let's do it\",\"lets do it\",\"i'm ready\",\"we're ready\",\"sign me up\",\"sign us up\",\"send me the details\",\"send the details\",\"send me a quote\",\"need workers asap\",\"need someone today\",\"starting monday\",\"starting next week\",\"that's reasonable\",\"sounds fair\",\"cheaper than\",\"better than\",\"have a job starting\",\"got a project\",\"need workers\",\"how many workers\",\"do you have electricians\",\"do you have carpenters\"],Lx={\"next step\":{type:\"closing\",response:\"Great question! I can get you set up right now. I just need your email to send the signup link.\",followUp:\"What's the best email to send that to?\",keyPoint:\"They're ready to move forward!\"},sign:{type:\"closing\",response:\"Perfect! Let me get you started. The signup takes about 2 minutes.\",followUp:\"Do you have your ABN handy?\",keyPoint:\"Close the deal now!\"},\"when can\":{type:\"urgency\",response:\"We can have workers available within 24-48 hours once you're set up.\",followUp:\"What trade do you need first?\",keyPoint:\"Match their urgency!\"},\"need workers\":{type:\"qualification\",response:\"We've got a great pool of pre-vetted workers. Most contractors find someone within a day.\",followUp:\"How many workers are you looking for?\",keyPoint:\"Qualify the opportunity!\"},cheaper:{type:\"value\",response:\"Yes, at 9.9% we're typically 30-50% less than traditional agencies, with no lock-in contracts.\",followUp:\"Would you like me to calculate the savings based on your team size?\",keyPoint:\"Reinforce the value!\"},default:{type:\"interest\",response:\"I can hear you're interested! Let me show you how easy it is to get started.\",followUp:\"What's your biggest pain point with finding workers right now?\",keyPoint:\"Keep the momentum!\"}};function DE({lead:t,onClose:s,onEnd:i}){const{scriptSessionId:l,setScriptSessionId:o,preloadedIntel:d}=kc(),[f,m]=b.useState(!1),[p,y]=b.useState(\"\"),[x,g]=b.useState(\"\"),[w,S]=b.useState([]),[T,N]=b.useState(!1),[R,D]=b.useState(null),[A,C]=b.useState(0),[B,_]=b.useState(!1),[F,P]=b.useState(null),[H,z]=b.useState([]),[X,te]=b.useState(\"\"),[Y,$]=b.useState(!0),[W,se]=b.useState(!0),[O,I]=b.useState({}),[K,ie]=b.useState(null),[oe,xe]=b.useState(null),[Te,ae]=b.useState(null),[ce,ne]=b.useState(!1),ue=b.useRef(!1),[de,ee]=b.useState(null),[ge,Ee]=b.useState(!1),[wt,me]=b.useState(null),ze=b.useRef(null),[st,on]=b.useState(!0),[Wt,ms]=b.useState(null),[Yn,Yt]=b.useState(\"opener\"),[li,Ea]=b.useState([]),[Vt,Fn]=b.useState(null),[St,$s]=b.useState(null),[Xn,Da]=b.useState(d),[ps,ka]=b.useState(null),[Ln,ri]=b.useState(!1),cn=b.useRef(!1);b.useEffect(()=>{d&&!cn.current&&(console.log(\"[LiveCopilot] Syncing preloadedIntel from context:\",Object.keys(d)),Da(d),cn.current=!0)},[d]);const Ft=b.useRef(null),ft=b.useRef(null),Ut=b.useRef(null),Ct=b.useRef(null);b.useRef(!1);const Gs=b.useRef(null),Kn=b.useRef(\"\"),un=b.useRef([]),gs=b.useRef(0),Qn=b.useRef(!1),Pt=b.useRef(0),Xt=b.useRef(null),ve=b.useRef(null);b.useEffect(()=>{if(St){const re=setTimeout(()=>{$s(null)},5e3);return()=>clearTimeout(re)}},[St]),b.useEffect(()=>((async()=>(await Fe(),await ht(),await At(),await Zn(),console.log(\"[LiveCopilot] Starting real-time transcription\"),Rt()))(),()=>{xs(),Ut.current&&clearInterval(Ut.current)}),[]),b.useEffect(()=>{Ct.current?.scrollIntoView({behavior:\"smooth\"})},[w]),b.useEffect(()=>(Ut.current=setInterval(()=>{C(re=>(gs.current=re+1,re+1))},1e3),()=>clearInterval(Ut.current)),[]),b.useEffect(()=>{Kn.current=p},[p]),b.useEffect(()=>{un.current=w},[w]),b.useEffect(()=>()=>{!Qn.current&&t?.id&&Kn.current&&(console.log(\"[LiveCopilot] Saving session on unmount, transcript length:\",Kn.current.length),Qn.current=!0,It.saveCopilotSession({leadId:t.id,transcript:Kn.current,suggestions:un.current,duration:gs.current}).catch(re=>console.error(\"[LiveCopilot] Failed to save session on unmount:\",re)))},[t?.id]);const Fe=async()=>{try{const re=await It.getDeepgramCredentials();if(console.log(\"[LiveCopilot] Deepgram configured:\",re.configured),re.configured){const Ae=`wss://${window.location.host.includes(\"rateright.com.au\")?\"rateright-growth-production.up.railway.app\":window.location.host}/api/transcribe/ws`;console.log(\"[LiveCopilot] Using backend proxy:\",Ae),P({configured:!0,proxyUrl:Ae}),Gs.current={configured:!0,proxyUrl:Ae}}else console.log(\"[LiveCopilot] Deepgram not configured, will use Web Speech API fallback\"),Gs.current=null}catch(re){console.log(\"[LiveCopilot] Live transcription not available:\",re.message),Gs.current=null}},ht=async()=>{if(!t?.id){se(!1);return}try{if(t.ai_intel_brief?.talking_points){z(t.ai_intel_brief.talking_points||[]),te(t.ai_intel_brief.opening_line||\"\"),se(!1);return}const re=await It.getIntelBrief(t.id);re.brief&&(z(re.brief.talking_points||[]),te(re.brief.opening_line||\"\"));try{const je=await It.getSimilarWins(t.id);je?.wins?.length>0&&Fn(je.wins[0])}catch(je){console.log(\"Could not load similar wins:\",je)}}catch(re){console.log(\"Could not load intel brief:\",re)}finally{se(!1)}},At=async()=>{if(cn.current||Xn){console.log(\"[LiveCopilot] Intel already loaded, skipping API fetch\");return}if(d){console.log(\"[LiveCopilot] Preloaded intel exists, useEffect will sync\");return}if(t?.id)try{console.log(\"[LiveCopilot] No preloaded intel, fetching from API...\");const re=await It.getLiveIntel(t.id);re.success&&!cn.current&&Da(re)}catch(re){console.log(\"Could not load intel:\",re)}},Zn=async()=>{if(t?.id)try{const re=await hc.getForLead(t.id);if(re.recommendedScripts?.length>0){const je=await hc.get(re.recommendedScripts[0].id);ka(je.script),ms(je.script?.id)}}catch(re){console.log(\"Could not load script:\",re)}},Xe=b.useCallback(re=>{const je=re.toLowerCase();for(const[ye,Ae]of Object.entries(TE))for(const _e of Ae)if(je.includes(_e)){const et=[\"opener\",\"discovery\",\"value_prop\",\"objections\",\"close\"],Be=et.indexOf(Yn);if(et.indexOf(ye)>Be)return Ea(Bn=>[...new Set([...Bn,Yn])]),Yt(ye),!0}return!1},[Yn]),Ht=re=>{const je=Math.floor(re/60),ye=re%60;return`${je}:${ye.toString().padStart(2,\"0\")}`},Jn=b.useCallback(re=>{const je=re.toLowerCase();return NE.some(ye=>je.includes(ye))},[]),Dt=b.useCallback(re=>{const je=re.toLowerCase();for(const ye of EE)if(je.includes(ye)){if(ze.current===ye)return null;ze.current=ye;let Ae=Lx.default;for(const[_e,et]of Object.entries(Lx))if(_e!==\"default\"&&ye.includes(_e)){Ae=et;break}return{trigger:ye,...Ae}}return null},[]),kt=b.useCallback(re=>{me(re);const je={type:\"buying_signal\",trigger:re.trigger,suggestion:{signal_type:re.type,response:re.response,follow_up_question:re.followUp,key_point:re.keyPoint},timestamp:Date.now()};S(ye=>[...ye,je]),$s(je),setTimeout(()=>me(null),5e3)},[]),ys=async re=>{if(!T){N(!0);try{const je=await It.objectionResponse({objection:re,leadId:t?.id});if(je.success){const ye={type:\"objection\",trigger:re,suggestion:je.suggestion,timestamp:Date.now()};S(Ae=>[...Ae,ye]),$s(ye)}}catch(je){console.error(\"Failed to get objection response:\",je)}finally{N(!1)}}},qt=t?.metadata?.lead_type===\"worker\",oi=b.useCallback(re=>{if(!(!qt||ue.current||ce))for(const je of CE){const ye=re.match(je);if(ye){const Ae=ye[1]?.trim(),_e=ye[2]?.trim();if(Ae&&Ae.length>2){console.log(`[ContractorDetection] Found: ${Ae}, project: ${_e||\"N/A\"}`),Dr(Ae,_e);return}}}},[qt,ce]),Dr=async(re,je)=>{if(!(ue.current||ce)){ue.current=!0,ne(!0);try{const ye=await It.extractContractor({sourceLeadId:t?.id,companyName:re,projectName:je});ye.success&&ye.found&&ye.candidate&&ae(ye.candidate)}catch(ye){console.error(\"Contractor search error:\",ye)}finally{ne(!1)}}},Wn=(re,je)=>{ae(null),console.log(\"Contractor lead created:\",re,je)},mt=b.useCallback(async re=>{if(ge)return!1;const je=re.toLowerCase().trim();for(const ye of AE){const Ae=je.match(ye);if(Ae){let _e=Ae[1]||je;(ye.source.includes(\"mark\")||ye.source.includes(\"skip\"))&&(_e=je),console.log(\"[VoiceCommand] Detected:\",_e),Ee(!0);try{const et=await It.voiceCommand({transcript:_e,leadId:t?.id});et.success&&(ee({confirmation:et.parsed.confirmation,intent:et.parsed.intent}),setTimeout(()=>ee(null),3e3))}catch(et){console.error(\"Voice command error:\",et)}finally{Ee(!1)}return!0}}return!1},[t?.id,ge]),Rt=async()=>{try{console.log(\"[LiveCopilot] Requesting microphone access...\");const re=await navigator.mediaDevices.getUserMedia({audio:!0});ve.current=re,Pt.current=0,console.log(\"[LiveCopilot] Microphone access granted\");const je=Gs.current||F;if(console.log(\"[LiveCopilot] Using backend proxy:\",!!(je?.configured&&je?.proxyUrl)),je?.configured&&je?.proxyUrl){console.log(\"[LiveCopilot] Connecting to backend proxy...\"),console.log(\"[LiveCopilot] Proxy URL:\",je.proxyUrl),xe(\"deepgram\");const ye=new WebSocket(je.proxyUrl);console.log(\"[LiveCopilot] WebSocket created, readyState:\",ye.readyState);const Ae=setTimeout(()=>{console.error(\"[LiveCopilot] Connection timeout! readyState:\",ye.readyState),ye.readyState!==WebSocket.OPEN&&(D(\"Connection timeout - trying fallback...\"),ye.close())},1e4);ye.onopen=()=>{clearTimeout(Ae),console.log(\"[LiveCopilot] Connected to transcription proxy!\"),Pt.current=0,m(!0),D(null)},ye.onmessage=Qe=>{const Ke=JSON.parse(Qe.data);if(Ke.error){console.error(\"[LiveCopilot] Proxy error:\",Ke.error),D(Ke.error);return}if(Ke.type===\"Metadata\"&&console.log(\"[LiveCopilot] Transcription metadata:\",Ke),Ke.channel?.alternatives?.[0]?.transcript){console.log(\"[LiveCopilot] Transcript:\",Ke.channel.alternatives[0].transcript,\"is_final:\",Ke.is_final);const Kt=Ke.channel.alternatives[0].transcript;if(Ke.is_final){y(Fs=>Fs+\" \"+Kt),g(\"\"),mt(Kt),Xe(Kt);const Ys=Dt(Kt);Ys?kt(Ys):Jn(Kt)&&ys(Kt),qt&&oi(Kt)}else g(Kt)}},ye.onerror=Qe=>{clearTimeout(Ae),console.error(\"[LiveCopilot] Proxy WebSocket error:\",Qe),console.error(\"[LiveCopilot] Error type:\",Qe.type),console.error(\"[LiveCopilot] Socket readyState on error:\",ye.readyState),D(\"Transcription error - check console\")},ye.onclose=Qe=>{clearTimeout(Ae),console.log(\"[LiveCopilot] Proxy disconnected, code:\",Qe.code,\"reason:\",Qe.reason,\"wasClean:\",Qe.wasClean);const Ke=3;if(Pt.current{console.log(\"[LiveCopilot] Reconnecting WebSocket...\"),Rt()},Kt)}else m(!1),Pt.current>=Ke&&D(\"Transcription disconnected. Tap mic to restart.\")},Ft.current=ye;const _e=new AudioContext,et=_e.sampleRate;console.log(\"[LiveCopilot] AudioContext sample rate:\",et);const Be=`","cwd":"/home/ccuser/the-50-dollar-app"},"isError":false,"timestamp":1771614169637}} {"type":"message","id":"8d6a839d","parentId":"cf241bfb","timestamp":"2026-02-20T19:02:55.429Z","message":{"role":"assistant","content":[{"type":"text","text":"The only remaining references are in the built bundle (`public/assets/index-2HMepUD5.js` and `admin/dist/`). These will be regenerated by the build. Now let me run the build and commit:"},{"type":"toolCall","id":"toolu_01MuxfJWZ6VU6LMpoGYaaUFx","name":"exec","arguments":{"command":"cd /home/ccuser/rateright-growth && npm run build 2>&1 | tail -20","timeout":120}}],"api":"anthropic-messages","provider":"anthropic","model":"claude-opus-4-6","usage":{"input":1,"output":144,"cacheRead":95870,"cacheWrite":36891,"totalTokens":132906,"cost":{"input":0.000005,"output":0.0036000000000000003,"cacheRead":0.047935,"cacheWrite":0.23056875000000002,"total":0.28210875}},"stopReason":"toolUse","timestamp":1771614169643}} {"type":"message","id":"6442bfef","parentId":"8d6a839d","timestamp":"2026-02-20T19:02:56.748Z","message":{"role":"toolResult","toolCallId":"toolu_01MuxfJWZ6VU6LMpoGYaaUFx","toolName":"exec","content":[{"type":"text","text":"> rateright-growth@1.0.0 build\n> cd admin && npm install && npm run build && cp -r dist/* ../public/\n\n\nup to date, audited 70 packages in 914ms\n\n5 packages are looking for funding\n run `npm fund` for details\n\nfound 0 vulnerabilities\n\n> admin@0.0.0 build\n> vite build && node -e \"const fs=require('fs'); const sw=fs.readFileSync('dist/sw.js','utf8'); const push=fs.readFileSync('public/sw-push-handlers.js','utf8'); fs.writeFileSync('dist/sw.js', sw + '\\n' + push);\"\n\nsh: 1: vite: not found"}],"details":{"status":"completed","exitCode":0,"durationMs":1319,"aggregated":"> rateright-growth@1.0.0 build\n> cd admin && npm install && npm run build && cp -r dist/* ../public/\n\n\nup to date, audited 70 packages in 914ms\n\n5 packages are looking for funding\n run `npm fund` for details\n\nfound 0 vulnerabilities\n\n> admin@0.0.0 build\n> vite build && node -e \"const fs=require('fs'); const sw=fs.readFileSync('dist/sw.js','utf8'); const push=fs.readFileSync('public/sw-push-handlers.js','utf8'); fs.writeFileSync('dist/sw.js', sw + '\\n' + push);\"\n\nsh: 1: vite: not found","cwd":"/home/ccuser/the-50-dollar-app"},"isError":false,"timestamp":1771614176740}} {"type":"message","id":"39c937fd","parentId":"6442bfef","timestamp":"2026-02-20T19:03:00.384Z","message":{"role":"assistant","content":[{"type":"text","text":"Vite isn't globally installed. Let me check:"},{"type":"toolCall","id":"toolu_014isQL3SG9V5Djk2prkngWN","name":"exec","arguments":{"command":"cd /home/ccuser/rateright-growth/admin && npx vite build 2>&1 | tail -20","timeout":120}}],"api":"anthropic-messages","provider":"anthropic","model":"claude-opus-4-6","usage":{"input":1,"output":109,"cacheRead":132761,"cacheWrite":328,"totalTokens":133199,"cost":{"input":0.000005,"output":0.002725,"cacheRead":0.0663805,"cacheWrite":0.00205,"total":0.07116049999999999}},"stopReason":"toolUse","timestamp":1771614176749}} {"type":"message","id":"bfcf906e","parentId":"39c937fd","timestamp":"2026-02-20T19:03:06.376Z","message":{"role":"toolResult","toolCallId":"toolu_014isQL3SG9V5Djk2prkngWN","toolName":"exec","content":[{"type":"text","text":"npm warn exec The following package was not found and will be installed: vite@7.3.1\nfailed to load config from /home/ccuser/rateright-growth/admin/vite.config.js\nerror during build:\nError [ERR_MODULE_NOT_FOUND]: Cannot find package 'vite' imported from /home/ccuser/rateright-growth/admin/node_modules/.vite-temp/vite.config.js.timestamp-1771614186328-e56d3f06f3932.mjs\n at Object.getPackageJSONURL (node:internal/modules/package_json_reader:314:9)\n at packageResolve (node:internal/modules/esm/resolve:767:81)\n at moduleResolve (node:internal/modules/esm/resolve:853:18)\n at defaultResolve (node:internal/modules/esm/resolve:983:11)\n at #cachedDefaultResolve (node:internal/modules/esm/loader:731:20)\n at ModuleLoader.resolve (node:internal/modules/esm/loader:708:38)\n at ModuleLoader.getModuleJobForImport (node:internal/modules/esm/loader:310:38)\n at ModuleJob._link (node:internal/modules/esm/module_job:182:49)"}],"details":{"status":"completed","exitCode":0,"durationMs":5993,"aggregated":"npm warn exec The following package was not found and will be installed: vite@7.3.1\nfailed to load config from /home/ccuser/rateright-growth/admin/vite.config.js\nerror during build:\nError [ERR_MODULE_NOT_FOUND]: Cannot find package 'vite' imported from /home/ccuser/rateright-growth/admin/node_modules/.vite-temp/vite.config.js.timestamp-1771614186328-e56d3f06f3932.mjs\n at Object.getPackageJSONURL (node:internal/modules/package_json_reader:314:9)\n at packageResolve (node:internal/modules/esm/resolve:767:81)\n at moduleResolve (node:internal/modules/esm/resolve:853:18)\n at defaultResolve (node:internal/modules/esm/resolve:983:11)\n at #cachedDefaultResolve (node:internal/modules/esm/loader:731:20)\n at ModuleLoader.resolve (node:internal/modules/esm/loader:708:38)\n at ModuleLoader.getModuleJobForImport (node:internal/modules/esm/loader:310:38)\n at ModuleJob._link (node:internal/modules/esm/module_job:182:49)","cwd":"/home/ccuser/the-50-dollar-app"},"isError":false,"timestamp":1771614186367}} {"type":"message","id":"04f0d6f4","parentId":"bfcf906e","timestamp":"2026-02-20T19:03:10.175Z","message":{"role":"assistant","content":[{"type":"toolCall","id":"toolu_01ApBc5KiXUgaUTtRnSnoYvp","name":"exec","arguments":{"command":"cd /home/ccuser/rateright-growth/admin && ls node_modules/.bin/vite 2>/dev/null && ./node_modules/.bin/vite build 2>&1 | tail -20 || echo \"vite not in local node_modules\"","timeout":120}}],"api":"anthropic-messages","provider":"anthropic","model":"claude-opus-4-6","usage":{"input":1,"output":130,"cacheRead":133089,"cacheWrite":449,"totalTokens":133669,"cost":{"input":0.000005,"output":0.0032500000000000003,"cacheRead":0.06654449999999999,"cacheWrite":0.00280625,"total":0.07260574999999998}},"stopReason":"toolUse","timestamp":1771614186376}} {"type":"message","id":"6bf9cb3f","parentId":"04f0d6f4","timestamp":"2026-02-20T19:03:10.202Z","message":{"role":"toolResult","toolCallId":"toolu_01ApBc5KiXUgaUTtRnSnoYvp","toolName":"exec","content":[{"type":"text","text":"vite not in local node_modules"}],"details":{"status":"completed","exitCode":0,"durationMs":30,"aggregated":"vite not in local node_modules","cwd":"/home/ccuser/the-50-dollar-app"},"isError":false,"timestamp":1771614190195}} {"type":"message","id":"57044ef5","parentId":"6bf9cb3f","timestamp":"2026-02-20T19:03:13.804Z","message":{"role":"assistant","content":[{"type":"toolCall","id":"toolu_01MVcCRZAgaK1L83thM5nvSs","name":"exec","arguments":{"command":"cd /home/ccuser/rateright-growth/admin && npm install vite --save-dev 2>&1 | tail -5 && npx vite build 2>&1 | tail -20","timeout":180}}],"api":"anthropic-messages","provider":"anthropic","model":"claude-opus-4-6","usage":{"input":1,"output":115,"cacheRead":133538,"cacheWrite":150,"totalTokens":133804,"cost":{"input":0.000005,"output":0.002875,"cacheRead":0.066769,"cacheWrite":0.0009375000000000001,"total":0.07058649999999998}},"stopReason":"toolUse","timestamp":1771614190202}} {"type":"message","id":"8e682815","parentId":"57044ef5","timestamp":"2026-02-20T19:03:17.043Z","message":{"role":"toolResult","toolCallId":"toolu_01MVcCRZAgaK1L83thM5nvSs","toolName":"exec","content":[{"type":"text","text":"5 packages are looking for funding\n run `npm fund` for details\n\nfound 0 vulnerabilities\nfailed to load config from /home/ccuser/rateright-growth/admin/vite.config.js\nerror during build:\nError [ERR_MODULE_NOT_FOUND]: Cannot find package 'vite' imported from /home/ccuser/rateright-growth/admin/node_modules/.vite-temp/vite.config.js.timestamp-1771614197001-827f1ec51bf7f.mjs\n at Object.getPackageJSONURL (node:internal/modules/package_json_reader:314:9)\n at packageResolve (node:internal/modules/esm/resolve:767:81)\n at moduleResolve (node:internal/modules/esm/resolve:853:18)\n at defaultResolve (node:internal/modules/esm/resolve:983:11)\n at #cachedDefaultResolve (node:internal/modules/esm/loader:731:20)\n at ModuleLoader.resolve (node:internal/modules/esm/loader:708:38)\n at ModuleLoader.getModuleJobForImport (node:internal/modules/esm/loader:310:38)\n at ModuleJob._link (node:internal/modules/esm/module_job:182:49)"}],"details":{"status":"completed","exitCode":0,"durationMs":3240,"aggregated":"5 packages are looking for funding\n run `npm fund` for details\n\nfound 0 vulnerabilities\nfailed to load config from /home/ccuser/rateright-growth/admin/vite.config.js\nerror during build:\nError [ERR_MODULE_NOT_FOUND]: Cannot find package 'vite' imported from /home/ccuser/rateright-growth/admin/node_modules/.vite-temp/vite.config.js.timestamp-1771614197001-827f1ec51bf7f.mjs\n at Object.getPackageJSONURL (node:internal/modules/package_json_reader:314:9)\n at packageResolve (node:internal/modules/esm/resolve:767:81)\n at moduleResolve (node:internal/modules/esm/resolve:853:18)\n at defaultResolve (node:internal/modules/esm/resolve:983:11)\n at #cachedDefaultResolve (node:internal/modules/esm/loader:731:20)\n at ModuleLoader.resolve (node:internal/modules/esm/loader:708:38)\n at ModuleLoader.getModuleJobForImport (node:internal/modules/esm/loader:310:38)\n at ModuleJob._link (node:internal/modules/esm/module_job:182:49)","cwd":"/home/ccuser/the-50-dollar-app"},"isError":false,"timestamp":1771614197037}} {"type":"message","id":"dced3fde","parentId":"8e682815","timestamp":"2026-02-20T19:03:21.769Z","message":{"role":"assistant","content":[{"type":"text","text":"The admin build has a pre-existing dependency issue (vite not properly resolved). This isn't caused by my changes — the source files are all correct. Let me just commit the source changes since the build system has an existing problem:"},{"type":"toolCall","id":"toolu_01SHuhYodiYAGsXBvDgb9f3o","name":"exec","arguments":{"command":"cd /home/ccuser/rateright-growth && git diff --stat"}}],"api":"anthropic-messages","provider":"anthropic","model":"claude-opus-4-6","usage":{"input":1,"output":116,"cacheRead":133688,"cacheWrite":455,"totalTokens":134260,"cost":{"input":0.000005,"output":0.0029000000000000002,"cacheRead":0.066844,"cacheWrite":0.00284375,"total":0.07259275000000001}},"stopReason":"toolUse","timestamp":1771614197044}} {"type":"message","id":"290bda65","parentId":"dced3fde","timestamp":"2026-02-20T19:03:21.799Z","message":{"role":"toolResult","toolCallId":"toolu_01SHuhYodiYAGsXBvDgb9f3o","toolName":"exec","content":[{"type":"text","text":"admin/package-lock.json | 2 +-\n admin/package.json | 2 +-\n admin/src/components/CallSalesFunnel.jsx | 2 +-\n admin/src/components/EliteCallUI.jsx | 2 +-\n admin/src/components/LiveCopilot.jsx | 2 +-\n rivet/BUILDER-INBOX.md | 140 ++++++-\n rivet/HEARTBEAT.md | 40 +-\n rivet/IDENTITY.md | 18 +-\n rivet/MEMORY.md | 45 ++-\n rivet/TOOLS.md | 1 +\n rivet/USER.md | 4 +-\n rivet/agents/topic-6-construction.md | 22 +-\n rivet/knowledge/COMPLETE-KNOWLEDGE.md | 8 +-\n rivet/knowledge/competitive-intel-labour-hire.md | 6 +-\n rivet/knowledge/contractor-hitlist-final.md | 4 +-\n rivet/knowledge/mae-vena-playbook-complete.md | 12 +-\n rivet/knowledge/worker-hitlist-final.md | 4 +-\n rivet/memory/2026-02-20.md | 250 +++++++++++-\n rivet/memory/2026-02-20.md.backup | 177 +++++----\n rivet/memory/calendar-summary.md | 16 +-\n rivet/memory/fresh-leads.json | 430 ++++++++++++++++++---\n rivet/memory/gmail-summary.md | 15 +-\n rivet/memory/morning-strategic-brief.md | 26 +-\n rivet/memory/nightly-scan.md | 253 +++++++++---\n rivet/memory/todays-hard-questions.md | 57 +--\n rivet/memory/topics/business.md | 29 +-\n rivet/memory/topics/michael.md | 17 +-\n rivet/memory/topics/personal.md | 14 +-\n rivet/memory/topics/technical.md | 6 +-\n rivet/memory/training/lessons-log.md | 4 +-\n rivet/memory/voice-brief-data.json | 27 +-\n rivet/memory/watchdog-log.md | 28 +-\n .../memory/work-log/sites/parramatta-powerhouse.md | 282 ++++++++++----\n rivet/status.json | 13 +-\n src/routes/playbook.js | 4 +-\n src/services/ai.js | 24 +-\n src/services/compliance.js | 2 +-\n src/services/perplexity.js | 4 +-\n src/services/stageDiagnosis.js | 2 +-\n 39 files changed, 1534 insertions(+), 460 deletions(-)"}],"details":{"status":"completed","exitCode":0,"durationMs":33,"aggregated":"admin/package-lock.json | 2 +-\n admin/package.json | 2 +-\n admin/src/components/CallSalesFunnel.jsx | 2 +-\n admin/src/components/EliteCallUI.jsx | 2 +-\n admin/src/components/LiveCopilot.jsx | 2 +-\n rivet/BUILDER-INBOX.md | 140 ++++++-\n rivet/HEARTBEAT.md | 40 +-\n rivet/IDENTITY.md | 18 +-\n rivet/MEMORY.md | 45 ++-\n rivet/TOOLS.md | 1 +\n rivet/USER.md | 4 +-\n rivet/agents/topic-6-construction.md | 22 +-\n rivet/knowledge/COMPLETE-KNOWLEDGE.md | 8 +-\n rivet/knowledge/competitive-intel-labour-hire.md | 6 +-\n rivet/knowledge/contractor-hitlist-final.md | 4 +-\n rivet/knowledge/mae-vena-playbook-complete.md | 12 +-\n rivet/knowledge/worker-hitlist-final.md | 4 +-\n rivet/memory/2026-02-20.md | 250 +++++++++++-\n rivet/memory/2026-02-20.md.backup | 177 +++++----\n rivet/memory/calendar-summary.md | 16 +-\n rivet/memory/fresh-leads.json | 430 ++++++++++++++++++---\n rivet/memory/gmail-summary.md | 15 +-\n rivet/memory/morning-strategic-brief.md | 26 +-\n rivet/memory/nightly-scan.md | 253 +++++++++---\n rivet/memory/todays-hard-questions.md | 57 +--\n rivet/memory/topics/business.md | 29 +-\n rivet/memory/topics/michael.md | 17 +-\n rivet/memory/topics/personal.md | 14 +-\n rivet/memory/topics/technical.md | 6 +-\n rivet/memory/training/lessons-log.md | 4 +-\n rivet/memory/voice-brief-data.json | 27 +-\n rivet/memory/watchdog-log.md | 28 +-\n .../memory/work-log/sites/parramatta-powerhouse.md | 282 ++++++++++----\n rivet/status.json | 13 +-\n src/routes/playbook.js | 4 +-\n src/services/ai.js | 24 +-\n src/services/compliance.js | 2 +-\n src/services/perplexity.js | 4 +-\n src/services/stageDiagnosis.js | 2 +-\n 39 files changed, 1534 insertions(+), 460 deletions(-)","cwd":"/home/ccuser/the-50-dollar-app"},"isError":false,"timestamp":1771614201794}} {"type":"message","id":"50a9b158","parentId":"290bda65","timestamp":"2026-02-20T19:03:27.278Z","message":{"role":"assistant","content":[{"type":"text","text":"There's a bunch of other rivet changes mixed in. Let me commit only the pricing-related files:"},{"type":"toolCall","id":"toolu_0179neqh3i9CRdRypZBhbuJs","name":"exec","arguments":{"command":"cd /home/ccuser/rateright-growth && git add \\\n src/services/ai.js \\\n src/services/perplexity.js \\\n src/services/compliance.js \\\n src/services/stageDiagnosis.js \\\n src/routes/playbook.js \\\n admin/src/components/LiveCopilot.jsx \\\n admin/src/components/CallSalesFunnel.jsx \\\n admin/src/components/EliteCallUI.jsx \\\n && git commit -m \"fix: purge all 9.9% pricing refs — now \\$50 flat fee per hire\""}}],"api":"anthropic-messages","provider":"anthropic","model":"claude-opus-4-6","usage":{"input":1,"output":226,"cacheRead":134143,"cacheWrite":960,"totalTokens":135330,"cost":{"input":0.000005,"output":0.0056500000000000005,"cacheRead":0.06707149999999999,"cacheWrite":0.006,"total":0.0787265}},"stopReason":"toolUse","timestamp":1771614201799}} {"type":"message","id":"0f84b5d0","parentId":"50a9b158","timestamp":"2026-02-20T19:03:27.318Z","message":{"role":"toolResult","toolCallId":"toolu_0179neqh3i9CRdRypZBhbuJs","toolName":"exec","content":[{"type":"text","text":"[main 9c9ec39c] fix: purge all 9.9% pricing refs — now $50 flat fee per hire\n 8 files changed, 21 insertions(+), 21 deletions(-)"}],"details":{"status":"completed","exitCode":0,"durationMs":41,"aggregated":"[main 9c9ec39c] fix: purge all 9.9% pricing refs — now $50 flat fee per hire\n 8 files changed, 21 insertions(+), 21 deletions(-)","cwd":"/home/ccuser/the-50-dollar-app"},"isError":false,"timestamp":1771614207312}} {"type":"message","id":"4e0472cd","parentId":"0f84b5d0","timestamp":"2026-02-20T19:03:32.029Z","message":{"role":"assistant","content":[{"type":"text","text":"Done. Final verification — no more 9.9% in source files (excluding migration scripts and built bundles):"},{"type":"toolCall","id":"toolu_015BZraN2iLYWj1fjKNDD7WQ","name":"exec","arguments":{"command":"cd /home/ccuser/rateright-growth && grep -rn \"9\\.9%\" --include=\"*.js\" --include=\"*.jsx\" --include=\"*.ts\" --include=\"*.tsx\" . --exclude-dir=node_modules --exclude-dir=dist --exclude-dir=public | grep -v \"scripts/update\""}}],"api":"anthropic-messages","provider":"anthropic","model":"claude-opus-4-6","usage":{"input":1,"output":151,"cacheRead":135103,"cacheWrite":289,"totalTokens":135544,"cost":{"input":0.000005,"output":0.003775,"cacheRead":0.0675515,"cacheWrite":0.0018062500000000001,"total":0.07313775}},"stopReason":"toolUse","timestamp":1771614207318}} {"type":"message","id":"207111d4","parentId":"4e0472cd","timestamp":"2026-02-20T19:03:32.119Z","message":{"role":"toolResult","toolCallId":"toolu_015BZraN2iLYWj1fjKNDD7WQ","toolName":"exec","content":[{"type":"text","text":"{\n \"status\": \"error\",\n \"tool\": \"exec\",\n \"error\": \"Command exited with code 1\"\n}"}],"details":{"status":"error","tool":"exec","error":"Command exited with code 1"},"isError":false,"timestamp":1771614212114}} {"type":"message","id":"97b43b93","parentId":"207111d4","timestamp":"2026-02-20T19:03:44.170Z","message":{"role":"assistant","content":[{"type":"text","text":"Zero matches — all clean.\n\n## Summary of Changes\n\n**Committed as `9c9ec39c`** — `fix: purge all 9.9% pricing refs — now $50 flat fee per hire`\n\n**8 files changed, 21 insertions, 21 deletions:**\n\n| File | What Changed |\n|------|-------------|\n| **src/services/ai.js** | 10 edits — All \"9.9% fee\" → \"$50 flat fee per hire\", \"workers pay 9.9%\" → \"workers pay nothing\", competitive comparisons updated, objection playbook rewritten |\n| **src/services/perplexity.js** | 2 edits — AI sales angle and talking points prompts updated |\n| **src/services/compliance.js** | 1 edit — `'free'` compliance guidance now says \"$50 flat fee per hire\" for contractors, \"you pay nothing\" for workers |\n| **src/services/stageDiagnosis.js** | 1 edit — Value prop comparison updated |\n| **src/routes/playbook.js** | 2 edits — Worker SMS messaging now says \"Workers pay nothing — keep 100%\" |\n| **admin/src/components/LiveCopilot.jsx** | 1 edit — \"cheaper\" objection handler updated |\n| **admin/src/components/CallSalesFunnel.jsx** | 1 edit — Value prop script updated |\n| **admin/src/components/EliteCallUI.jsx** | 1 edit — Fallback value prop updated |\n\n**Skipped (intentionally):**\n- `scripts/update-sms-sequences.js` and `scripts/update-all-sms-sequences.js` — These are migration scripts that already fix 9.9% → $50 in the database. References are only in comments/logs describing what they changed.\n- `public/assets/index-*.js` and `admin/dist/` — Built bundles containing old 9.9% refs. The admin build has a pre-existing vite dependency issue preventing rebuild. Source files are all correct and will produce clean bundles when the build environment is fixed."}],"api":"anthropic-messages","provider":"anthropic","model":"claude-opus-4-6","usage":{"input":1,"output":507,"cacheRead":135392,"cacheWrite":194,"totalTokens":136094,"cost":{"input":0.000005,"output":0.012675,"cacheRead":0.06769599999999999,"cacheWrite":0.0012125,"total":0.0815885}},"stopReason":"stop","timestamp":1771614212120}}