1import{j as e}from"./vendor-radix-BnNg3BH5.js";import{r as n,h as zs,L as fa}from"./vendor-react-67mgcWXU.js";import{C as R,d as O,a as J,b as Z,c as ae}from"./card-DpKBVi42.js";import{d as gs,u as re,B as y,C as Ce,b as ne,s as b,D as _e,e as Se,L as E,f as ke,g as Ae,h as Ee,a3 as $s,G as Ue,U as js,V as fs,W as ve,Y as ue,v as B,I as se,a4 as As,n as Bs,a0 as ut,a7 as Kt,T as Ke,l as $e,m as Ye,a as jt,w as ie,x as ce,y as le,z as oe,A as V,af as ya,ag as va,F as Us,E as Is,X as $t,S as wa,a9 as ft,q as de,ah as Na,Z as kt,aa as ba,ai as _a,i as Sa}from"./index-Epr9psQo.js";import{S as ye}from"./switch-ZTMCvIb3.js";import{S as me}from"./separator-C2IB9E9R.js";import{g as Ca,L as ka,s as Aa}from"./landingPage-DE2QF79r.js";import{B as U}from"./badge-Cl7apleB.js";import{A as Ne,b as be}from"./alert-BbCCz1lQ.js";import{C as Ws}from"./calendar-Ce69BthR.js";import{G as hs}from"./globe-DQzIP_ik.js";import{C as pe}from"./circle-alert-CFN03ksH.js";import{E as ns}from"./external-link-DnfaRxEP.js";import{u as Pa}from"./useIsAdmin-Ctpj3Dh2.js";import{P as ys}from"./progress-OXAVVpg3.js";import{S as Ds}from"./scroll-area-OnGFamwr.js";import{GlobalWorkerOptions as Yt,getDocument as Jt,version as Ta}from"./pdf-DxqAUlXS.js";import Ia from"./pdf.worker.min-D8eRykn8.js";import{Z as Da,a as Ea}from"./zoom-out-B0h_yV9L.js";import{D as Ys}from"./download-CDzT20jl.js";import{l as La}from"./index-DWK1yKUm.js";import{U as At}from"./upload-2-rh2XwF.js";import{S as xs}from"./sparkles-BcySMUTB.js";import{S as rt}from"./save-B2-eOoIe.js";import{S as Pt}from"./scroll-text-cs_ud9J6.js";import{S as Fa}from"./square-pen-Cweehhnk.js";import{D as qa,C as Ma,P as Ra}from"./dnd.esm-BsK0xBzW.js";import{F as Tt}from"./file-pen-line-D9G_viQN.js";import{U as Be}from"./users-uAR6_Qvs.js";import{B as We}from"./building-2-DODpaxwc.js";import{G as Oa}from"./grip-vertical-eNKORDT2.js";import{T as Le}from"./trash-2-EIFrPvgK.js";import{C as Je}from"./copy-C-Qie2rJ.js";import{M as Xe}from"./mail-BWzQtSAz.js";import{T as za}from"./trending-up-CXZcoU_y.js";import{T as De}from"./triangle-alert-C6ISfBPd.js";import{u as He,a as Oe,c as we}from"./vendor-query-PMAhJHCS.js";import{U as Ba}from"./user-plus-Cz5haDJC.js";import{f as es}from"./formatDistanceToNow--Gw1Xv78.js";import{P as Vs,M as Ga,m as Ha,u as Ua,a as Wa}from"./microsoft-logo-yPpbPnud.js";import{I as Js,S as Va}from"./SalesforceWizard-Brg_KVn5.js";import{C as Zt,a as Xt,b as ea}from"./collapsible-CKRfPF8i.js";import{C as he}from"./circle-check-Cv8aCTuA.js";import{A as Zs,m as qe}from"./vendor-motion-CSzk-Fqg.js";import{C as Es}from"./chevron-left-D3yfuHpM.js";import{C as Ls}from"./chevron-right-DQtszqux.js";import{A as Xs}from"./arrow-right-LjC5fuTq.js";import{K as Qa}from"./key-CGXcwh1g.js";import{C as ms}from"./checkbox-CaPhqoy3.js";import{R as ht,a as xt}from"./radio-group-CfZiOVDj.js";import{C as Ge}from"./clock-BYWbH6MV.js";import{D as Fs}from"./database-C-966MCo.js";import{T as yt}from"./target-CyHaUH9t.js";import{M as Hs}from"./mic-eFw98pWv.js";import{S as Ve}from"./shield-BI9NGrnO.js";import{u as Ka,a as sa}from"./useUserGoogleToken-DAyK-34U.js";import{L as ss}from"./link-D3nquTTi.js";import{H as Re}from"./hash-C8fDZTIR.js";import{S as et}from"./search-BnpyGpZl.js";import{L as Ps}from"./lock-Nw6CqB2t.js";import{M as ta}from"./message-square-7cL_4-It.js";import{C as $a}from"./circle-user-CauPGfW5.js";import{E as Qs}from"./eye-off-DPaUcPgH.js";import{F as Ya}from"./folder-open-CP9JKzSm.js";import{T as vt,a as wt,b as ps,c as Pe,d as Nt,e as Te}from"./table-023rHGnC.js";import{R as ts}from"./refresh-cw-j1umLsSM.js";import{A as Ja}from"./arrow-left-BKCvbsa9.js";import{C as bt}from"./chart-column-6WlVTHnt.js";import{P as aa}from"./pause-BywH4XAI.js";import{P as _t}from"./play-CCgxmdCK.js";import{C as qs}from"./circle-x-HEsvXgN2.js";import{f as as}from"./format-Bw8okCdv.js";import{A as vs,a as ws,b as Ns,c as bs,d as _s,e as Ss,f as Cs,g as st,h as St}from"./alert-dialog-D6zmf4Qa.js";import{u as Za,a as Xa,b as en,c as sn}from"./useTeamworkSync-CLV1A5y_.js";import{T as tn}from"./TeamworkUserMapping-Dib2yhEO.js";import{L as Ms}from"./link-2-Bu8oQt2W.js";import{S as Rs}from"./settings-2-rw5RGAbH.js";import{I as us}from"./info-DuvYtGx9.js";import{W as It}from"./wand-sparkles-CP9Guegx.js";import{U as tt}from"./unlink-BIn62xtc.js";import{C as an}from"./calendar-clock-Dgofoxff.js";import{M as Ie}from"./metric-DK0Tcl4m.js";import{u as nn}from"./useSubscription-FuoKqSQZ.js";import{C as Ks}from"./credit-card-rF6FfvWR.js";import{C as Dt}from"./crown-BKEU7eeR.js";import{K as rn,F as cn,C as ln}
1from"./ContradictionScanner-CLoalyjc.js";import{R as it}from"./refresh-ccw-Dxc3RwEl.js";import{B as na}from"./brain-BAvvPRM1.js";import{F as on}from"./filter-idQrjp7H.js";import{u as dn}from"./useWikiPages-DutED1-m.js";import{u as mn}from"./usePerformanceSettings-wF77WMxB.js";import{P as Ts}from"./plus-DRTmwF2W.js";import{I as Et,a as Lt,b as Me}from"./input-otp-CP0Ge4Pu.js";import{S as un}from"./shield-check-D18Fa-7Q.js";import{S as hn}from"./shield-off-D1uDtxif.js";import{S as xn}from"./smartphone-CQCDmUAV.js";import{u as pn,t as gn}from"./zod-JuGaLNur.js";import{u as jn}from"./useAuditVertical-CvZDU-Ht.js";import{S as ra}from"./scale-Cc_B3FHe.js";import{B as fn}from"./briefcase-DJg8wfqE.js";import{C as yn}from"./calculator-4oGLHdIn.js";import{C as vn}from"./clipboard-check-DG2jkXce.js";import{B as Os}from"./bell-BSliH8iT.js";import{D as ia}from"./dollar-sign-CC-jyV1q.js";import{T as ca}from"./trending-down-CFwiQb3W.js";import{S as ct}from"./skeleton-CXDkv5zX.js";import{a as wn,N as Nn,u as bn,S as _n}from"./useNotificationPreferences-B-iV4BWC.js";import{A as Sn}from"./activity-DehK1-wv.js";import{u as la}from"./useTranslation-DUpvmwV_.js";import{u as Cn}from"./useICPConfig-B1jX8Ign.js";import{R as Ft}from"./rocket-C5i7F51i.js";import{u as kn}from"./useFeatureGate-Bya5cmwc.js";import{U as oa}from"./user-BG8cpmCD.js";import{P as da}from"./palette-BS3PZByh.js";import{L as An}from"./layout-grid-ShDyZi0i.js";import{B as Pn}from"./book-open-CDTjHrJx.js";import{W as Tn}from"./wrench-Vigg387C.js";import"./vendor-supabase-CTlrDMdV.js";import"./vendor-charts-Dck3qfzI.js";import"./jszip.min-C-g80qGt.js";import"./_commonjs-dynamic-modules-TDtrdbi3.js";import"./constructNow-LutmP3uJ.js";import"./en-US-DJiZ5LCQ.js";import"./differenceInMonths-ODK8TVL-.js";import"./differenceInCalendarMonths-CBq9QhqA.js";import"./endOfDay-CV7hhp0x.js";import"./endOfMonth-BJH_LSY0.js";import"./differenceInMilliseconds-BS2m-4UB.js";import"./dateUtils-Cc1QGD5W.js";import"./FunctionalRoleContext-BWioCyPQ.js";import"./zap-DC4LlnWT.js";import"./index-Jdtl9AIN.js";import"./circle-CPv7M1K7.js";import"./rotate-ccw-C8K84F0R.js";import"./AIKnowledgeGenerator-DK1KL-vt.js";import"./trophy-DDLL3U1f.js";import"./package-DW7ssg6N.js";import"./avatar-DkXZyfFy.js";import"./vendor-editor-CEJKB4cc.js";import"./FreshnessBadge-Bkkuqg1E.js";import"./file-warning-BppkjwTD.js";/** 2 * @license lucide-react v0.462.0 - ISC 3 * 4 * This source code is licensed under the ISC license. 5 * See the LICENSE file in the root directory of this source tree. 6 */const In=gs("ArrowLeftRight",[["path",{d:"M8 3 4 7l4 4",key:"9rb6wj"}],["path",{d:"M4 7h16",key:"6tx8e3"}],["path",{d:"m16 21 4-4-4-4",key:"siv7j2"}],["path",{d:"M20 17H4",key:"h6l3hr"}]]);/** 7 * @license lucide-react v0.462.0 - ISC 8 * 9 * This source code is licensed under the ISC license. 10 * See the LICENSE file in the root directory of this source tree. 11 */const pt=gs("FileJson",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10 12a1 1 0 0 0-1 1v1a1 1 0 0 1-1 1 1 1 0 0 1 1 1v1a1 1 0 0 0 1 1",key:"1oajmo"}],["path",{d:"M14 18a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1 1 1 0 0 1-1-1v-1a1 1 0 0 0-1-1",key:"mpwhp6"}]]);/** 12 * @license lucide-react v0.462.0 - ISC 13 * 14 * This source code is licensed under the ISC license. 15 * See the LICENSE file in the root directory of this source tree. 16 */const Dn=gs("FolderSearch",[["path",{d:"M10.7 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v4.1",key:"1bw5m7"}],["path",{d:"m21 21-1.9-1.9",key:"1g2n9r"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}]]);/** 17 * @license lucide-react v0.462.0 - ISC 18 * 19 * This source code is licensed under the ISC license. 20 * See the LICENSE file in the root directory of this source tree. 21 */const ma=gs("HeartPulse",[["path",{d:"M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z",key:"c3ymky"}],["path",{d:"M3.22 12H9.5l.5-1 2 4.5 2-7 1.5 3.5h5.27",key:"1uw2ng"}]]);/** 22 * @license lucide-react v0.462.0 - ISC 23 * 24 * This source code is licensed under the ISC license. 25 * See the LICENSE file in the root directory of this source tree. 26 */const En=gs("KeyRound",[["path",{d:"M2.586 17.414A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814a6.5 6.5 0 1 0-4-4z",key:"1s6t7t"}],["circle",{cx:"16.5",cy:"7.5",r:".5",fill:"currentColor",key:"w0ekpg"}]]);/** 27 * @license lucide-react v0.462.0 - ISC 28 * 29 * This source code is licensed under the ISC license. 30 * See the LICENSE file in the root directory of this source tree. 31 */const Ln=gs("Moon",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}
31]]),qt=`# Connect Google Workspace to CommandOS â Super-Admin Setup Guide 32 33> **Send this to your Google Workspace super-admin.** This is the **recommended** way to connect Google Workspace org-wide. It replaces the per-user OAuth flow so every teammate's calendar shows up in CommandOS automatically â no individual sign-ins. 34 35You're receiving this because your team uses CommandOS and we want to connect Google Workspace **once for the whole organization** so every teammate's calendar (and, optionally, mail) is available to them inside CommandOS â without each person having to authorize their own Google account. 36 37This requires a **Google Workspace super-admin** (you). It takes about 10 minutes. 38 39--- 40 41## Why a Service Account (and not OAuth)? 42 43- **OAuth** = each person must connect their own Google account. Calendars only show up after they personally authorize. 44- **Service Account + Domain-Wide Delegation (DWD)** = CommandOS impersonates each user server-side using credentials you authorize once. No per-user click-through. This is the same model Microsoft 365 uses by default and is the recommended path for any organization with more than a couple of users. 45 46--- 47 48## Step 1 â Create a Google Cloud project 49 501. Open https://console.cloud.google.com/projectcreate 512. Name it something like \`CommandOS Workspace Integration\` 523. Pick your organization (not "No organization") so the project lives under your Workspace tenant. 534. Click **Create**. Wait for the project to finish provisioning, then make sure it's selected in the top bar. 54 55## Step 2 â Enable the required APIs 56 57In the same project, enable each of these (click the link, then click **Enable**): 58 591. Google Calendar API â https://console.cloud.google.com/apis/library/calendar-json.googleapis.com 602. Admin SDK API (used for directory sync) â https://console.cloud.google.com/apis/library/admin.googleapis.com 613. *(Optional, only if you want CommandOS to read/send Gmail on behalf of users)* Gmail API â https://console.cloud.google.com/apis/library/gmail.googleapis.com 62 63## Step 3 â Create the Service Account 64 651. Open https://console.cloud.google.com/iam-admin/serviceaccounts/create 662. **Service account name**: \`commandos-workspace\` 673. **Service account ID**: leave the auto-generated value 684. **Description**: \`Used by CommandOS to read calendars and directory on behalf of users via Domain-Wide Delegation.\` 695. Click **Create and Continue**. 706. **Skip** the "Grant this service account access to project" step (click **Continue**). 717. **Skip** the "Grant users access" step (click **Done**). 72 73You should now see the service account in the list. **Click into it** and copy its **Unique ID (Client ID)** â it's a ~21-digit number. You'll need it in step 5. 74 75## Step 4 â Generate a JSON key 76 771. Inside the service account, go to the **Keys** tab. 782. Click **Add Key â Create new key**. 793. Choose **JSON** and click **Create**. A \`.json\` file will download. 804. **Keep this file safe** â it's the credential that lets CommandOS act as your Workspace. Anyone with it can read calendars across your domain. Treat it like a password. 81 82## Step 5 â Authorize Domain-Wide Delegation 83 84This is the step that requires super-admin rights. 85 861. Open https://admin.google.com/ac/owl/domainwidedelegation 872. Click **Add new**. 883. **Client ID**: paste the 21-digit Unique ID from step 3. 894. **OAuth scopes** (comma-separated, paste exactly): 90 91\`\`\` 92https://www.googleapis.com/auth/calendar.readonly, 93https://www.googleapis.com/auth/gmail.readonly, 94https://www.googleapis.com/auth/admin.directory.user.readonly, 95https://www.googleapis.com/auth/admin.directory.group.readonly 96\`\`\` 97 98 *(Add \`https://www.googleapis.com/auth/gmail.readonly\` and \`https://www.googleapis.com/auth/gmail.send\` only if you also enabled the Gmail API in step 2 and want CommandOS to handle mail.)* 99 1005. Click **Authorize**. 101 102## Step 6 â Hand off to your CommandOS admin 103 104Send the **JSON key file** from step 4 to whoever runs CommandOS for your team (this is probably the person who sent you this guide). They will: 105
1061. Open **Settings â Integrations â Google Workspace** in CommandOS. 1072. Choose the **Service Account** tab. 1083. Paste the entire JSON file contents. 1094. Click **Test connection**, then **Complete setup**. 110 111Once they do that, every user on your domain will see their own calendar in CommandOS automatically â no individual OAuth clicks required. 112 113--- 114 115## Security notes 116 117- The JSON key is the only sensitive item here. CommandOS stores it encrypted. If you ever rotate or revoke it in the Google Cloud console (Service Account â Keys â Delete), the integration stops working immediately. 118- DWD only grants the scopes you authorized in step 5. CommandOS cannot read mail unless you explicitly added Gmail scopes. It cannot modify calendars unless you grant a write scope (we don't request one by default). 119- To revoke entirely: in Admin Console â Security â API Controls â Domain-Wide Delegation, delete the row with the Client ID from step 5. 120 121## Troubleshooting 122 123- **"unauthorized_client"** when CommandOS tests the connection â the Client ID in step 5 doesn't match the JSON key, or the scopes don't match. Double-check both. 124- **"access_denied" reading a specific user's calendar** â that user's Workspace account is suspended or the scope wasn't authorized. Re-check step 5. 125- **Directory sync returns 0 users** â the Admin SDK API (step 2) isn't enabled, or the directory scopes weren't added in step 5. 126 127If you hit something not covered here, send a screenshot to your CommandOS admin and they'll loop in support. 128`;function Fn(){const{toast:s}=re(),[t,r]=n.useState(!1),d=async()=>{await navigator.clipboard.writeText(qt),r(!0),s({title:"Guide copied",description:"Paste it into an email or doc to send to your Google Workspace super-admin."}),setTimeout(()=>r(!1),2500)},c=()=>{const i=new Blob([qt],{type:"text/markdown"}),o=URL.createObjectURL(i),g=document.createElement("a");g.href=o,g.download="commandos-google-workspace-setup.md",document.body.appendChild(g),g.click(),document.body.removeChild(g),URL.revokeObjectURL(o)};return e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-md bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(pt,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium leading-tight",children:"Have a Google Workspace super-admin? Set this up org-wide instead."}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"A Service Account with Domain-Wide Delegation lets CommandOS read every teammate's calendar without each person having to OAuth. This is the recommended path for any team larger than a couple of people."})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(y,{size:"sm",variant:"default",onClick:d,children:[t?e.jsx(Ce,{className:"h-3.5 w-3.5 mr-1.5"}):e.jsx(Je,{className:"h-3.5 w-3.5 mr-1.5"}),t?"Copied":"Copy guide for your admin"]}),e.jsxs(y,{size:"sm",variant:"outline",onClick:c,children:[e.jsx(Ys,{className:"h-3.5 w-3.5 mr-1.5"}),"Download as .md"]})]})]})}const cs=[{id:"intro",title:"Overview"},{id:"setup",title:"Google Cloud Setup"},{id:"credentials",title:"Enter Credentials"},{id:"validate",title:"Test & Connect"}],Mt="https://vgdtukgdfjsvjjcvcuxk.supabase.co/functions/v1/google-oauth-callback";function ls({href:s,label:t,copyKey:r,onCopy:d,copyId:c}){return e.jsxs("div",{className:"flex items-stretch gap-1",children:[e.jsx(y,{variant:"outline",asChild:!0,className:"flex-1 justify-between h-9",children:e.jsxs("a",{href:s,target:"_blank",rel:"noopener noreferrer",onClick:i=>{window.open(s,"_blank","noopener,noreferrer")&&i.preventDefault()},children:[e.jsx("span",{className:"text-xs truncate",children:t}),e.jsx(ns,{className:"h-3.5 w-3.5 shrink-0"})]})}),e.jsx(y,{variant:"outline",size:"sm",className:"h-9 w-9 p-0 shrink-0",title:"Copy URL (paste into a
128new tab if the link is blocked)",onClick:()=>d(s),children:r===c?e.jsx(Ce,{className:"h-3.5 w-3.5"}):e.jsx(Je,{className:"h-3.5 w-3.5"})})]})}function qn({open:s,onOpenChange:t,onSuccess:r}){const{currentTenant:d}=ne(),{toast:c}=re(),[i,o]=zs(),[g,f]=n.useState(0),[h,p]=n.useState("service_account"),[u,l]=n.useState(""),[x,w]=n.useState(""),[v,N]=n.useState(""),[S,_]=n.useState(!1),[P,G]=n.useState(!1),[a,j]=n.useState(null),[M,W]=n.useState(!1),[K,T]=n.useState(null),[L,m]=n.useState(null),[k,q]=n.useState(!0),[A,ee]=n.useState(null),D=(g+1)/cs.length*100;n.useEffect(()=>{if(!s){f(0),p("service_account"),l(""),w(""),N(""),G(!1),j(null),m(null),ee(null),q(!0);return}d?.id&&(async()=>{q(!0);const{data:z}=await b.from("tenant_integrations").select("credentials, updated_at, is_active").eq("tenant_id",d.id).eq("integration_type","google_workspace").eq("is_active",!0).maybeSingle();if(z){const te=z.credentials;ee({auth_method:te?.type==="service_account"?"service_account":"oauth",updated_at:z.updated_at})}q(!1)})()},[s,d?.id]),n.useEffect(()=>{const z=te=>{te.data?.type==="google_oauth_callback"&&(te.data.success?(G(!0),j(null),c({title:"Google Workspace connected successfully!"})):j(te.data.error_description||te.data.error||"OAuth failed"))};return window.addEventListener("message",z),()=>window.removeEventListener("message",z)},[c]),n.useEffect(()=>{if(!s)return;const z=i.get("google_success"),te=i.get("google_error_desc")||i.get("google_error");
128if(z==="true"){G(!0),j(null),_(!1),c({title:"Google Workspace connected successfully!"}),o(ge=>{const je=new URLSearchParams(ge);return je.delete("google_success"),je.delete("google_error"),je.delete("google_error_desc"),je},{replace:!0});return}te&&(G(!1),_(!1),j(te),o(ge=>{const je=new URLSearchParams(ge);return je.delete("google_success"),je.delete("google_error"),je.delete("google_error_desc"),je},{replace:!0}))},[s,i,o,c]);const H=async(z,te)=>{await navigator.clipboard.writeText(z),T(te),setTimeout(()=>T(null),2e3)},Y=async()=>{if(d){_(!0),j(null);try{const{data:{session:z}}=await b.auth.getSession();if(!z)throw new Error("Not authenticated");if(h==="service_account"){const{data:te,error:ge}=await b.functions.invoke("google-integration-setup",{headers:{Authorization:`Bearer ${z.access_token}`},body:{action:"validate_service_account",tenant_id:d.id,service_account_json:v}});if(ge)throw new Error(ge.message);if(te?.valid)G(!0),m(te.client_id||null);else throw new Error(te?.error||"Validation failed")}else{if(!u||!x)throw new Error("Client ID and Secret are required");const{error:te}=await b.functions.invoke("google-integration-setup",{headers:{Authorization:`Bearer ${z.access_token}`},body:{action:"save_oauth_credentials",tenant_id:d.id,client_id:u,client_secret:x}});if(te)throw new Error(te.message);const{data:ge,error:je}=await b.functions.invoke("google-integration-setup",{headers:{Authorization:`Bearer ${z.access_token}`},body:{action:"get_auth_url",tenant_id:d.id,client_id:u,redirect_uri:window.location.origin}});if(je)throw new Error(je.message);if(!ge?.auth_url)throw new Error("Failed to get authorization URL");const rs=600,Fe=700,Qe=window.screenX+(window.innerWidth-rs)/2,Ze=window.screenY+(window.innerHeight-Fe)/2;window.open(ge.auth_url,"google_oauth",`width=${rs},height=${Fe},left=${Qe},top=${Ze}`)}}catch(z){console.error("Validation error:",z),j(z.message||"Failed to validate credentials")}finally{_(!1)}}},xe=async()=>{if(!(!d||!P)){W(!0);try{const{data:{session:z}}=await b.auth.getSession();if(!z)throw new Error("Not authenticated");if(h==="service_account"){const{error:je}=await b.functions.invoke("google-integration-setup",{headers:{Authorization:`Bearer ${z.access_token}`},body:{action:"save_service_account",tenant_id:d.id,service_account_json:v}});if(je)throw new Error(je.message)}c({title:"Google Workspace connected",description:"Service Account + Domain-Wide Delegation is active. Teammates will see their own calendar and mail without per-user OAuth."});const ge=(z.user?.email||"").split("@")[1]||"";ge&&b.functions.invoke("sync-google-directory-users",{headers:{Authorization:`Bearer ${z.access_token}`},body:{tenant_id:d.id,domain:ge,sync_photos:!1}}).catch(je=>ut.warn("Google directory warm-up failed:",je)),b.functions.invoke("fetch-calendar",{headers:{Authorization:`Bearer ${z.access_token}`},body:{tenant_id:d.id}}).catch(je=>ut.warn("fetch-calendar warm-up failed:",je)),r?.(),t(!1)}catch(z){c({title:"Failed to save integration",description:z.message,variant:"destructive"})}finally{W(!1)}}},F=()=>{ee(null),f(0)},X=()=>{switch(g){case 2:return h==="oauth"?u.length>10&&x.length>10:v.length>100;case 3:return P;default:return!0}},I=()=>{g<cs.length-1&&X()&&f(g+1)},C=()=>{g>0&&(f(g-1),g===3&&(G(!1),j(null)))};if(s&&k)return e.jsx(_e,{open:s,onOpenChange:t,children:e.jsx(Se,{className:"sm:max-w-md",children:e.jsxs("div",{className:"py-12 text-center space-y-4",children:[e.jsx(E,{className:"h-8 w-8 animate-spin mx-auto text-primary"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Checking existing connectionâ¦"})]})})});if(s&&A)return e.jsx(_e,{open:s,onOpenChange:t,children:e.jsxs(Se,{className:"sm:max-w-md",children:[e.jsxs(ke,{children:[e.jsxs(Ae,{className:"flex items-center gap-2",children:[e.jsx(he,{className:"h-5 w-5 text-success"}),"Google Workspace Connected"]}),e.jsxs(Ee,{children:["This workspace is connected via"," ",e.jsx("strong",{children:A.auth_method==="service_account"?"Service Account":"OAuth"}),". Last updated"," ",new Date(A.updated_at).toLocaleDateString(),"."]})]}),e.jsxs("div",{className:"flex flex-col gap-2 pt-2",children:[e.jsx(y,{onClick:F,variant:"outline",className:"w-full",children:"Reconfigure connection"}),e.jsx(y,{onClick:()=>t(!1),className:"w-full",children:"Close"})]})]})});const $=()=>{switch(g){case 0:return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Js,{name:"Google Worksp
128ace",whatItDoes:["Sync every teammate's calendar org-wide for attendee matching and meeting briefs","Identify client meetings automatically for time tracking","Sync your Workspace directory (users + groups) for team rosters","Optionally read & send email on behalf of users (only if Gmail scopes are added)"],permissions:[{label:"calendar.readonly",description:"Read calendar events for every user in the domain"},{label:"admin.directory.user.readonly",description:"List users in your Workspace directory"},{label:"admin.directory.group.readonly",description:"List groups & memberships"},{label:"gmail.send (optional)",description:"Send mail on behalf of users â only if you add it"},{label:"gmail.readonly (optional)",description:"Read mail on behalf of users â only if you add it"}],dataFlow:"One-way read from Google â CommandOS via Service Account impersonation. Calendars polled every 15 minutes; directory daily.",helpHref:"/docs/integrations/google"}),e.jsx(Fn,{}),e.jsxs(Ne,{children:[e.jsx(pe,{className:"h-4 w-4"}),e.jsxs(be,{className:"text-xs",children:[e.jsx("strong",{children:"Recommended (org-wide): Service Account + Domain-Wide Delegation."})," ",`One setup by a Google Workspace super-admin enables every teammate's calendar automatically â no per-user clicks. Use "Copy guide for your admin" above to send the step-by-step instructions.`,e.jsx("br",{}),e.jsx("br",{}),e.jsx("strong",{children:"Fallback (single user / no super-admin): OAuth."})," Only connects the person who runs the wizard. Every other teammate must also OAuth their own Google account from Settings â Integrations. Choose this only if you can't get super-admin help."]})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Service Account setup takes ~10 min (super-admin required). OAuth takes ~5 min per person."})]});case 1:return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Ne,{children:[e.jsx(pe,{className:"h-4 w-4"}),e.jsxs(be,{className:"text-xs",children:[e.jsx("strong",{children:"Heads up:"}),' Google Console links open in a new tab. If clicking does nothing, your browser is blocking the popup from this preview â right-click â "Open in new tab", or copy the URL.']})]}),e.jsxs("div",{className:"rounded-lg border-2 border-primary/30 bg-primary/5 p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pt,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"font-semibold text-sm",children:"Recommended: Service Account (org-wide)"}),e.jsx(U,{variant:"default",className:"text-caption uppercase",children:"Super-admin"})]}),e.jsx("p",{className:"text-xs text-muted-foreground -mt-2",children:"Hand the guide on the previous step to your Google Workspace super-admin. They'll do steps 1â5 and send you back a JSON key, which you'll paste in the next step."}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium",children:"1. Create a Google Cloud project"}),e.jsx(ls,{href:"https://console.cloud.google.com/projectcreate",label:"Open project creator",copyKey:K,onCopy:z=>H(z,"url-project"),copyId:"url-project"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium",children:"2. Enable required APIs (Calendar + Admin SDK)"}),e.jsx(ls,{href:"https://console.cloud.google.com/apis/library/calendar-json.googleapis.com",label:"Enable Calendar API",copyKey:K,onCopy:z=>H(z,"url-cal"),copyId:"url-cal"}),e.jsx(ls,{href:"https://console.cloud.google.com/apis/library/admin.googleapis.com",label:"Enable Admin SDK API",copyKey:K,onCopy:z=>H(z,"url-admin"),copyId:"url-admin"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium",children:"3. Create the service account & download JSON key"}),e.jsx(ls,{href:"https://console.cloud.google.com/iam-admin/serviceaccounts/create",label:"Create service account",copyKey:K,onCopy:z=>H(z,"url-sa"),copyId:"url-sa"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium",children:"4. Authorize Domain-Wide Delegation in Admin Console"}),e.jsx(ls,{href:"https://admin.google.com/ac/owl/domainwidedelegation",label:"Open Domain-Wide Delegation",copyKey:K,onCopy:z=>H(z,"url-dwd"),copyId:"url-dwd"}),e.jsxs("div",{className:"bg-background rounded-md p-2 space-y-1",children:[e.jsx("p",{className:"text-caption font-medium",children:"Paste these scopes (comma-separated):"}),e.jsxs("div",{className:"flex items-start gap-2 bg-muted rounded px-2 py-1.5",children:[e.jsx("code",{className:"text-caption flex-1 break-all leading-relaxed",children:"https://www.googleapis.com/auth/calendar.readonly,https://www.googleapis.com/auth/gmail.readonly,https://www.googleapis.com/auth/admin.directory.user.readonly,https://www.googleapis.com/auth/admin.directory.group.readonly"}),e.jsx(y,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 shrink-0",onClick:()=>H("https://www.googleapis.com/auth/calendar.readonly,https://www.googleapis.com/auth/gmail.readonly,https://www.googleapis.com/auth/admin.directory.user.readonly,https://www.googleapis.com/auth/admin.directory.group.readonly","scopes"),children:K==="scopes"?e.jsx(Ce,{className:"h-3 w-3"}):e.jsx(Je,{className:"h-3 w-3"})})]})]})]})]}),e.jsxs(Zt,{children:[e.jsx(Xt,{asChild:!0,children:e.jsxs(y,{variant:"ghost",size:"sm",className:"w-full justify-between",children:[e.jsx("span",{className:"text-xs",children:"Fallback: OAuth (single-user, no super-admin needed)"}),e.jsx(Bs,{className:"h-4 w-4"})]})}),e.jsxs(ea,{className:"pt-3 space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connects only the person running the wizard. Each other teammate must OAuth their own account from Settings â Integrations afterward."}),e.jsx(ls,{href:"https://console.cloud.google.com/apis/credentials/oauthclient",label:"Create OAuth client",copyKey:K,onCopy:z=>H(z,"url-oauth"),copyId:"url-oauth"}),e.jsxs("div",{className:"bg-muted rounded-lg p-3 space-y-2 text-xs",children:[e.jsx("p",{className:"font-medium",children:"Use these settings:"}),e.jsxs("ul",{className:"space-y-1 ml-4",children:[e.jsxs("li",{children:["⢠Application type: ",e.jsx("strong",{children:"Web application"})]}),e.jsx("li",{children:"⢠Authorized redirect URI:"})]}),e.jsxs("div",{className:"flex items-center gap-2 bg-background rounded px-2 py-1",children:[e.jsx("code",{className:"text-xs flex-1 overflow-hidden text-ellipsis",children:Mt}),e.jsx(y,{variant:"ghost",size:"sm",onClick:()=>H(Mt,"uri"),children:K==="uri"?e.jsx(Ce,{className:"h-4 w-4"}):e.jsx(Je,{className:"h-4 w-4"})})]})]})]})]})]});case 2:return e.jsx("div",{className:"space-y-4",children:e.jsxs(js,{value:h,onValueChange:z=>p(z),children:[e.jsxs(fs,{className:"grid w-full grid-cols-2",children:[e.jsxs(ve,{value:"service_account",className:"gap-2",children:[e.jsx(pt,{className:"h-4 w-4"}),"Service Account (recommended)"]}),e.jsxs(ve,{value:"oauth",className:"gap-2",children:[e.jsx(Qa,{className:"h-4 w-4"}),"OAuth (per-user)"]})]}
128),e.jsxs(ue,{value:"oauth",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{htmlFor:"clientId",children:"Client ID"}),e.jsx(se,{id:"clientId",placeholder:"xxxxxxxxxxxx-xxxxxxxxxxxxxxxx.apps.googleusercontent.com",value:u,onChange:z=>l(z.target.value.trim())})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{htmlFor:"clientSecret",children:"Client Secret"}),e.jsx(se,{id:"clientSecret",type:"password",placeholder:"GOCSPX-...",value:x,onChange:z=>w(z.target.value)})]})]}),e.jsxs(ue,{value:"service_account",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{htmlFor:"serviceAccount",children:"Service Account JSON"}),e.jsx(As,{id:"serviceAccount",placeholder:"Paste the entire JSON file contents here...",value:v,onChange:z=>N(z.target.value),rows:8,className:"font-mono text-xs"})]}),e.jsxs(Ne,{children:[e.jsx(pe,{className:"h-4 w-4"}),e.jsxs(be,{className:"text-xs",children:["Requires ",e.jsx("strong",{children:"domain-wide delegation"})," enabled in Google Admin Console."]})]})]})]})});case 3:return e.jsxs("div",{className:"space-y-6",children:[!P&&!S&&!a&&e.jsxs("div",{className:"text-center py-8 space-y-4",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-muted mx-auto flex items-center justify-center",children:e.jsx(he,{className:"h-8 w-8 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium",children:"Ready to connect"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:h==="oauth"?"We'll open a Google authorization popup.":"We'll verify your service account credentials."})]}),e.jsxs(y,{onClick:Y,size:"lg",children:[h==="oauth"?"Connect with Google":"Test connection",e.jsx(Xs,{className:"ml-2 h-4 w-4"})]})]}),S&&e.jsxs("div",{className:"text-center py-8 space-y-4",children:[e.jsx(E,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:h==="oauth"?"Complete the authorization in the popup window.":"Validating credentialsâ¦"})]}),a&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Ne,{variant:"destructive",children:[e.jsx(pe,{className:"h-4 w-4"}),e.jsx(be,{children:a})]}),e.jsx("div",{className:"text-center",children:e.jsx(y,{onClick:Y,variant:"outline",children:"Try again"})})]}),P&&e.jsxs("div",{className:"text-center py-8 space-y-4",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-success-soft mx-auto flex items-center justify-center",children:e.jsx(he,{className:"h-8 w-8 text-success"})}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium text-success",children:"Connection successful"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Your Google Workspace is connected."}),L&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["DWD Client ID: ",e.jsx("code",{className:"rounded bg-muted px-1 py-0.5",children:L})]})]}),e.jsx(y,{onClick:xe,size:"lg",disabled:M,children:M?e.jsxs(e.Fragment,{children:[e.jsx(E,{className:"mr-2 h-4 w-4 animate-spin"}),"Savingâ¦"]}):"Complete setup"})]})]});default:return null}};return e.jsx(_e,{open:s,onOpenChange:t,children:e.jsxs(Se,{className:"sm:max-w-2xl",children:[e.jsxs(ke,{children:[e.jsxs(Ae,{className:"flex items-center gap-2",children:[e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 48 48",className:"h-6 w-6 shrink-0","aria-label":"Google",role:"img",children:[e.jsx("path",{fill:"#FFC107",d:"M43.611 20.083H42V20H24v8h11.303c-1.649 4.657-6.08 8-11.303 8-6.627 0-12-5.373-12-12s5.373-12 12-12c3.059 0 5.842 1.154 7.961 3.039l5.657-5.657C34.046 6.053 29.268 4 24 4 12.955 4 4 12.955 4 24s8.955 20 20 20 20-8.955 20-20c0-1.341-.138-2.65-.389-3.917z"}),e.jsx("path",{fill:"#FF3D00",d:"M6.306 14.691l6.571 4.819C14.655 15.108 18.961 12 24 12c3.059 0 5.842 1.154 7.961 3.039l5.657-5.657C34.046 6.053 29.268 4 24 4 16.318 4 9.656 8.337 6.306 14.691z"}),e.jsx("path",{fill:"#4CAF50",d:"M24 44c5.166 0 9.86-1.977 13.409-5.192l-6.19-5.238C29.211 35.091 26.715 36 24 36c-5.202 0-9.619-3.317-11.283-7.946l-6.522 5.025C9.505 39.556 16.227 44 24 44z"}),e.jsx("path",{fill:"#1976D2",d:"M43.611 20.083H42V20H24v8h11.303c-.792 2.237-2.231 4.166-4.087 5.571.001-.001.002-.001.003-.002l6.19 5.238C36.971 39.205 44 34 44 24c0-1.341-.138-2.65-.389-3.917z"})]}
128),"Connect Google Workspace"]}),e.jsxs(Ee,{children:["Step ",g+1," of ",cs.length,": ",cs[g].title]})]}),e.jsxs("div",{className:"space-y-2 shrink-0",children:[e.jsx(ys,{value:D,className:"h-2"}),e.jsx("div",{className:"flex justify-between",children:cs.map((z,te)=>e.jsx("div",{className:`text-xs ${te<=g?"text-primary":"text-muted-foreground"}`,children:te<g?e.jsx(Ce,{className:"h-4 w-4"}):e.jsx("span",{className:te===g?"font-medium":"",children:te+1})},z.id))})]}),e.jsx($s,{children:e.jsx(Zs,{mode:"wait",children:e.jsx(qe.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.2},children:$()},g)})}),e.jsxs(Ue,{className:"border-t pt-4 sm:justify-between",children:[e.jsxs(y,{variant:"outline",onClick:C,disabled:g===0,children:[e.jsx(Es,{className:"mr-2 h-4 w-4"}),"Back"]}),g<cs.length-1&&e.jsxs(y,{onClick:I,disabled:!X(),children:["Next",e.jsx(Ls,{className:"ml-2 h-4 w-4"})]})]})]})})}const os=[{id:"intro",title:"Overview"},{id:"token",title:"Enter Bot Token"},{id:"validate",title:"Test Connection"}],Mn=["channels:manage","channels:read","channels:history","chat:write","users:read","users:read.email"];function Rn({open:s,onOpenChange:t,onSuccess:r}){const{currentTenant:d}=ne(),{toast:c}=re(),[i,o]=n.useState(0),[g,f]=n.useState(""),[h,p]=n.useState(!1),[u,l]=n.useState(!1),[x,w]=n.useState(null),[v,N]=n.useState(null),[S,_]=n.useState(!1),P=(i+1)/os.length*100;n.useEffect(()=>{s||(o(0),f(""),l(!1),w(null),N(null))},[s]);const G=async()=>{if(!(!d||!g)){p(!0),w(null);try{const{data:{session:T}}=await b.auth.getSession();if(!T)throw new Error("Not authenticated");const{data:L,error:m}=await b.functions.invoke("slack-integration-setup",{headers:{Authorization:`Bearer ${T.access_token}`},body:{action:"validate_token",tenant_id:d.id,bot_token:g}});if(m)throw new Error(m.message);if(L?.valid)l(!0),N(L.workspace_name||null);else throw new Error(L?.error||"Token validation failed")}catch(T){console.error("Validation error:",T),w(T.message||"Failed to validate token. Please check your Bot Token.")}finally{p(!1)}}},a=async()=>{if(!(!d||!u)){_(!0);try{const{data:{session:T}}=await b.auth.getSession();if(!T)throw new Error("Not authenticated");const{data:L,error:m}=await b.functions.invoke("slack-integration-setup",{headers:{Authorization:`Bearer ${T.access_token}`},body:{action:"save_integration",tenant_id:d.id,bot_token:g,workspace_name:v,scopes:Mn}});if(m)throw new Error(m.message);c({title:"Slack connected successfully!"}),r?.(),t(!1)}catch(T){c({title:"Failed to save integration",description:T.message,variant:"destructive"})}finally{_(!1)}}},j=()=>{switch(i){case 1:return g.startsWith("xoxb-")&&g.length>20;case 2:return u;default:return!0}},M=()=>{i<os.length-1&&j()&&o(i+1)},W=()=>{i>0&&(o(i-1),i===2&&(l(!1),w(null),N(null)))},K=()=>{switch(i){case 0:return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Js,{name:"Slack",whatItDoes:["Auto-create internal project channels at kickoff","Post status updates when milestones and deliverables ship","Resolve Slack users to CommandOS team members"],permissions:[{label:"channels:manage",description:"Create project channels"},{label:"chat:write",description:"Post status updates"},{label:"users:read",description:"Resolve Slack users"}],dataFlow:"One-way write from CommandOS â Slack, real-time on events.",helpHref:"/docs/integrations/slack"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Setup takes ~5 minutes and requires Slack workspace admin access."})]});case 1:return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h4",{className:"font-medium flex items-center gap-2",children:[e.jsx("span",{className:"flex items-center justify-center w-6 h-6 rounded-full bg-primary text-primary-foreground text-xs font-bold",children:"1"}),"Go to Your Slack App"]}),e.jsx(y,{variant:"outline",asChild:!0,className:"w-full justify-between",children:e.jsxs("a",{href:"https://api.slack.com/apps",target:"_blank",rel:"noopener noreferrer",children:["Open Slack App Dashboard",e.jsx(ns,{className:"h-4 w-4"})]})})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h4",{className:"font-medium flex items-center gap-2",children:[e.jsx("span",{className:"flex items-center justify-center w-6 h-6 rounded-full bg-primary text-primary-foreground text-xs font-bold",children:"2"}),"Copy Your Bot Token"]}),e.jsxs("div",{className:"bg-muted rounded-lg p-4 space-y-2 text-sm",children:[e.jsxs("p",{children:["Navigate to ",e.jsx("strong",{children:"OAuth & Permissions"})]}),e.jsxs("p",{children:["Copy the ",e.jsx("strong",{children:"Bot User OAuth Token"})," (starts with ",e.jsx("code",{children:"xoxb-"}),")"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{htmlFor:"botToken",children:"Bot User OAuth Token"}),e.jsx(se,{id:"botToken",type:"password",placeholder:"xoxb-xxxx-xxxx-xxxx",value:g,onChange:T=>f(T.target.value.trim())}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Found in OAuth & Permissions â Bot User OAuth Token"})]}),!g.startsWith("xoxb-")&&g.length>0&&e.jsxs(Ne,{variant:"destructive",children:[e.jsx(pe,{className:"h-4 w-4"}),e.jsxs(be,{children:["Bot tokens should start with ",e.jsx("code",{children:"xoxb-"}),". Make sure you're using the Bot User OAuth Token, not a User token."]})]})]});case 2:return e.jsxs("div",{className:"space-y-6",children:[!u&&!h&&!x&&e.jsxs("div",{className:"text-center py-8 space-y-4",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-muted mx-auto flex items-center justify-center",children:e.jsx(he,{className:"h-8 w-8 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium",children:"Ready to Test"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"We'll verify your bot token by connecting to the Slack API."})]}),e.jsxs(y,{onClick:G,size:"lg",children:["Test Connection",e.jsx(Xs,{className:"ml-2 h-4 w-4"})]})]}),h&&e.jsxs("div",{className:"text-center py-8 space-y-4",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-muted mx-auto flex items-center justify-center",children:e.jsx(E,{className:"h-8 w-8 animate-spin text-primary"})}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium",children:"Validating..."}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Connecting to Slack API..."})]})]}),x&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Ne,{variant:"destructive",children:[e.jsx(pe,{className:"h-4 w-4"}),e.jsx(be,{children:x})]}),e.jsx("div",{className:"text-center",children:e.jsx(y,{onClick:G,variant:"outline",children:"Try Again"})})]}),u&&e.jsxs("div",{className:"text-center py-8 space-y-4",children:[e.jsx(qe.div,{initial:{scale:0},animate:{scale:1},className:"w-16 h-16 rounded-full bg-success-soft mx-auto flex items-center justify-center",children:e.jsx(he,{className:"h-8 w-8 text-success"})}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium text-success",children:"Connection Successful!"}),v&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["Connected to workspace: ",e.jsx("strong",{children:v})]})]}),e.jsx(y,{onClick:a,disabled:S,size:"lg",children:S?e.jsxs(e.Fragment,{children:[e.jsx(E,{className:"mr-2 h-4 w-4 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:["Save & Connect",e.jsx(Ce,{className:"ml-2 h-4 w-4"})]})})]})]});default:return null}};return e.jsx(_e,{open:s,onOpenChange:t,children:e.jsxs(Se,{className:"sm:max-w-lg",children:[e.jsxs(ke,{children:[e.jsx(Ae,{className:"flex items-center gap-2",children:"Slack Integration Setup"}),e.jsx(Ee,{children:os[i].title})]}),e.jsxs("div",{className:"space-y-1 shrink-0",children:[e.jsx(ys,{value:P,className:"h-1"}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Step ",i+1," of ",os.length]}),e.jsx("span",{children:os[i].title})]})]}),e.jsx($s,{children:e.jsx(Zs,{mode:"wait",children:e.jsx(qe.div,{initial:{opacity:0,x:20}
128,animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.2},children:K()},i)})}),e.jsxs(Ue,{className:"border-t pt-4 sm:justify-between",children:[e.jsxs(y,{variant:"ghost",onClick:W,disabled:i===0,children:[e.jsx(Es,{className:"mr-2 h-4 w-4"}),"Back"]}),i<os.length-1&&e.jsxs(y,{onClick:M,disabled:!j(),children:["Next",e.jsx(Ls,{className:"ml-2 h-4 w-4"})]})]})]})})}const ds=[{id:"intro",title:"Overview"},{id:"auth",title:"Authentication"},{id:"objects",title:"Object Selection"},{id:"import",title:"Historical Import"},{id:"schedule",title:"Sync Schedule"},{id:"validate",title:"Test & Connect"}],On=[{id:"companies",label:"Companies",icon:We,description:"Sync with Clients"},{id:"contacts",label:"Contacts",icon:Be,description:"Sync with Client Contacts"},{id:"deals",label:"Deals",icon:yt,description:"Sync with Proposals"}],Rt=[{id:"full",label:"Full Import",description:"Import all historical records",recommended:!1},{id:"90days",label:"Last 90 Days",description:"Import records from the last 3 months",recommended:!0},{id:"30days",label:"Last 30 Days",description:"Import records from the last month",recommended:!1},{id:"skip",label:"Skip Import",description:"Only sync new and updated records",recommended:!1}],Ot=[{id:"15",label:"Every 15 minutes",description:"Most frequent sync"},{id:"30",label:"Every 30 minutes",description:"Recommended"},{id:"60",label:"Every hour",description:"Less frequent sync"},{id:"manual",label:"Manual only",description:"Sync on-demand"}];function zn({open:s,onOpenChange:t,onSuccess:r}){const{currentTenant:d}=ne(),{toast:c}=re(),[i,o]=n.useState(0),[g,f]=n.useState(""),[h,p]=n.useState(["companies","contacts","deals"]),[u,l]=n.useState("90days"),[x,w]=n.useState({}),[v,N]=n.useState(!1),[S,_]=n.useState("30"),[P,G]=n.useState(!1),[a,j]=n.useState(!1),[M,W]=n.useState(null),[K,T]=n.useState(null),[L,m]=n.useState(!1),k=(i+1)/ds.length*100;n.useEffect(()=>{s||q()},[s]);const q=()=>{o(0),f(""),p(["companies","contacts","deals"]),l("90days"),w({}),_("30"),j(!1),W(null),T(null)},A=async()=>{if(!(!d||!g)){G(!0),W(null);try{const{data:{session:C}}=await b.auth.getSession();if(!C)throw new Error("Not authenticated");const{data:$,error:z}=await b.functions.invoke("hubspot-integration-setup",{headers:{Authorization:`Bearer ${C.access_token}`},body:{action:"validate_credentials",tenant_id:d.id,access_token:g}});if(z)throw new Error(z.message);if($?.valid)j(!0),T($.portal_name||null),$.record_counts&&w($.record_counts);else throw new Error($?.error||"Credential validation failed")}catch(C){console.error("Validation error:",C),W(C.message||"Failed to validate credentials")}finally{G(!1)}}},ee=async()=>{if(!(!d||!a)){N(!0);try{const{data:{session:C}}=await b.auth.getSession();if(!C)throw new Error("Not authenticated");const{data:$,error:z}=await b.functions.invoke("hubspot-integration-setup",{headers:{Authorization:`Bearer ${C.access_token}`},body:{action:"fetch_record_counts",tenant_id:d.id,objects:h}});if(z)throw z;$?.counts&&w($.counts)}catch(C){console.error("Failed to fetch record counts:",C)}finally{N(!1)}}},D=async()=>{if(!(!d||!a)){m(!0);try{const{data:{session:C}}=await b.auth.getSession();if(!C)throw new Error("Not authenticated");const{data:$,error:z}=await b.functions.invoke("hubspot-integration-setup",{headers:{Authorization:`Bearer ${C.access_token}`},body:{action:"save_integration",tenant_id:d.id,access_token:g,portal_name:K,selected_objects:h,import_option:u,sync_schedule:S}});if(z)throw new Error(z.message);if(c({title:"HubSpot connected successfully!"}),u&&u!=="skip")try{const te=u==="full"?"full":"historical";await b.functions.invoke("hubspot-sync",{headers:{Authorization:`Bearer ${C.access_token}`},body:{tenant_id:d.id,sync_type:te,objects:h}}),c({title:"Initial sync started",description:"Your HubSpot data is being imported."})}catch(te){console.error("Initial sync trigger failed:",te),c({title:"Initial sync will need to be triggered manually",variant:"destructive"})}r?.(),t(!1)}catch(C){c({title:"Failed to save integration",description:C.message,variant:"destructive"})}finally{m(!1)}}},H=C=>{p($=>$.includes(C)?$.filter(z=>z!==C):[...$,C])},Y=()=>{switch(i){case 1:return g.length>10;case 2:return h.length>0;case 3:return u!=="";case 4:return S!=="";case 5:return a;default:return!0}},xe=()=>{i<ds.length-1&&Y()&&(o(i+1),i===2&&a&&Object.keys(x).length===0&&ee())},F=()=>{i>0&&(o(i-1),i===5&&(j(!1),W(null)))},X=()=>Object.values(x).reduce((C,$)=>C+$,0),I=()=>{switch(i){case 0:return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Js,{name:"HubSpot
128CRM",whatItDoes:["Sync Companies â Clients, Contacts â Client Contacts","Sync Deals â Proposals with stage mapping","Bring CRM context into proposals and revenue intel"],permissions:[{label:"crm.objects.companies",description:"Read/write companies"},{label:"crm.objects.contacts",description:"Read/write contacts"},{label:"crm.objects.deals",description:"Read/write deals"}],dataFlow:"Two-way sync, configurable cadence (15/30/60 minutes or manual).",helpHref:"/docs/integrations/hubspot"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uses HubSpot Private Apps (Personal Access Token). No OAuth dance required."})]});case 1:return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h4",{className:"font-medium flex items-center gap-2",children:[e.jsx("span",{className:"flex items-center justify-center w-6 h-6 rounded-full bg-primary text-primary-foreground text-xs font-bold",children:"1"}),"Create a Private App"]}),e.jsx(y,{variant:"outline",asChild:!0,className:"w-full justify-between",children:e.jsxs("a",{href:"https://app.hubspot.com/",target:"_blank",rel:"noopener noreferrer",children:["Open HubSpot",e.jsx(ns,{className:"h-4 w-4"})]})}),e.jsxs("div",{className:"bg-muted rounded-lg p-3 text-sm space-y-1",children:[e.jsxs("p",{children:["⢠Go to ",e.jsx("strong",{children:"Settings"})," (gear icon) â ",e.jsx("strong",{children:"Integrations"})," â ",e.jsx("strong",{children:"Private Apps"})]}),e.jsxs("p",{children:["⢠Click ",e.jsx("strong",{children:"Create a private app"})]}),e.jsxs("p",{children:["⢠Under Scopes, add: ",e.jsx("code",{children:"crm.objects.companies"}),", ",e.jsx("code",{children:"crm.objects.contacts"}),", ",e.jsx("code",{children:"crm.objects.deals"})]}),e.jsxs("p",{children:["⢠Click ",e.jsx("strong",{children:"Create app"})," and copy the Access Token"]})]})]}),e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{htmlFor:"accessToken",children:"Private App Access Token"}),e.jsx(se,{id:"accessToken",type:"password",placeholder:"pat-na1-...",value:g,onChange:C=>f(C.target.value.trim())}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Your token starts with "pat-" and contains your portal region.'})]})})]});case 2:return e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select which HubSpot objects to sync with CommandOS:"}),e.jsx("div",{className:"space-y-3",children:On.map(C=>{const $=C.icon,z=h.includes(C.id);return e.jsxs("div",{className:`flex items-center gap-3 p-3 rounded-lg border cursor-pointer transition-colors ${z?"border-primary bg-primary/5":"border-border hover:border-muted-foreground/30"}`,onClick:()=>H(C.id),children:[e.jsx(ms,{checked:z}),e.jsx($,{className:`h-5 w-5 ${z?"text-primary":"text-muted-foreground"}`}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium text-sm",children:C.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:C.description})]})]},C.id)})})]});case 3:return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Choose how much historical data to import:"}),v&&e.jsx(E,{className:"h-4 w-4 animate-spin"})]}),Object.keys(x).length>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Fs,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium",children:"HubSpot Records"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 text-sm",children:Object.entries(x).map(([C,$])=>e.jsxs("div",{className:"flex justify-between",children:[e.jsxs("span",{className:"text-muted-foreground capitalize",children:[C,":"]}),e.jsx("span",{className:"font-medium",children:$.toLocaleString()})]},C))}),e.jsxs("div",{className:"mt-2 pt-2 border-t flex justify-between text-sm font-medium",children:[e.jsx("span",{children:"Total:"}
128),e.jsxs("span",{children:[X().toLocaleString()," records"]})]})]}),e.jsx(ht,{value:u,onValueChange:l,children:Rt.map(C=>e.jsxs("div",{className:`flex items-center gap-3 p-3 rounded-lg border cursor-pointer ${u===C.id?"border-primary bg-primary/5":"border-border"}`,onClick:()=>l(C.id),children:[e.jsx(xt,{value:C.id}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm",children:C.label}),C.recommended&&e.jsx(U,{variant:"secondary",className:"text-xs bg-secondary text-secondary-foreground",children:"Recommended"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:C.description})]})]},C.id))})]});case 4:return e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"How often should we sync data between systems?"}),e.jsx(ht,{value:S,onValueChange:_,children:Ot.map(C=>e.jsxs("div",{className:`flex items-center gap-3 p-3 rounded-lg border cursor-pointer ${S===C.id?"border-primary bg-primary/5":"border-border"}`,onClick:()=>_(C.id),children:[e.jsx(xt,{value:C.id}),e.jsx(Ge,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium text-sm",children:C.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:C.description})]})]},C.id))})]});case 5:return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-medium",children:"Configuration Summary"}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 space-y-3 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Objects:"}),e.jsx("span",{children:h.join(", ")})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Import:"}),e.jsx("span",{children:Rt.find(C=>C.id===u)?.label})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Schedule:"}),e.jsx("span",{children:Ot.find(C=>C.id===S)?.label})]})]})]}),!a&&!P&&!M&&e.jsx(y,{onClick:A,className:"w-full",children:"Test Connection"}),P&&e.jsxs("div",{className:"flex items-center justify-center gap-2 py-4",children:[e.jsx(E,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{children:"Validating connection..."})]}),M&&e.jsxs(Ne,{variant:"destructive",children:[e.jsx(pe,{className:"h-4 w-4"}),e.jsx(be,{children:M})]}),a&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Ne,{className:"border-success/30 bg-success/5",children:[e.jsx(he,{className:"h-4 w-4 text-success"}),e.jsxs(be,{className:"text-success",children:["Successfully connected to ",K||"HubSpot"]})]}),e.jsx(y,{onClick:D,className:"w-full",disabled:L,children:L?e.jsxs(e.Fragment,{children:[e.jsx(E,{className:"h-4 w-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ce,{className:"h-4 w-4 mr-2"}),"Save & Enable Sync"]})})]}),M&&e.jsx(y,{variant:"outline",onClick:A,className:"w-full",children:"Retry Connection"})]});default:return null}};return e.jsx(_e,{open:s,onOpenChange:t,children:e.jsxs(Se,{className:"sm:max-w-2xl",children:[e.jsxs(ke,{children:[e.jsxs(Ae,{className:"flex items-center gap-2",children:[e.jsx("svg",{viewBox:"0 0 32 32",className:"h-5 w-5 shrink-0",role:"img","aria-label":"HubSpot",children:e.jsx("path",{fill:"#FF7A59",d:"M22.4 12.6V9.4a2.5 2.5 0 1 0-2 0v3.2a7 7 0 0 0-3.3 1.4l-9-7 .4-1.5a2 2 0 1 0-2.7-1.5L7.5 5.6l9.5 7.4a7 7 0 1 0 5.4-.4Zm-1 10.6a3.6 3.6 0 1 1 0-7.2 3.6 3.6 0 0 1 0 7.2Z"})}),"Connect HubSpot"]}),e.jsxs(Ee,{children:["Step ",i+1," of ",ds.length,": ",ds[i].title]})]}),e.jsxs("div",{className:"shrink-0 space-y-2",children:[e.jsx(ys,{value:k,className:"h-1.5"}),e.jsx("div",{className:"flex gap-1",children:ds.map((C,$)=>e.jsx("div",{className:`flex-1 h-1 rounded-full transition-colors ${$<=i?"bg-primary":"bg-muted"}`},C.id))})]}),e.jsx($s,{children:e.jsx(Zs,{mode:"wait",children:e.jsx(qe.div,{initial:{opacity:0,x:20}
128,animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.2},children:I()},i)})}),e.jsxs(Ue,{className:"border-t pt-4 sm:justify-between",children:[e.jsxs(y,{variant:"outline",onClick:F,disabled:i===0,children:[e.jsx(Es,{className:"h-4 w-4 mr-1"}),"Back"]}),i<ds.length-1?e.jsxs(y,{onClick:xe,disabled:!Y(),children:["Next",e.jsx(Ls,{className:"h-4 w-4 ml-1"})]}):e.jsx(y,{onClick:()=>t(!1),variant:"ghost",children:"Close"})]})]})})}function Bn(){const{toast:s}=re(),[t,r]=zs(),{graphToken:d,isLoading:c,isConnected:i,isExpired:o,hasMailSendScope:g,connectGraph:f,disconnectGraph:h,isConnecting:p,isDisconnecting:u,refetch:l}=Ka();return n.useEffect(()=>{const x=t.get("graph_connected"),w=t.get("graph_error");x==="true"&&(s({title:"Microsoft 365 connected",description:"You can now send emails from your account"}),l(),t.delete("graph_connected"),r(t)),w&&(s({title:"Connection failed",description:decodeURIComponent(w),variant:"destructive"}),t.delete("graph_error"),r(t))},[t,s,l,r]),n.useEffect(()=>{const x=w=>{w.data?.type==="graph_connected"&&w.data?.success?(s({title:"Microsoft 365 connected",description:"You can now send emails from your account"}),l()):w.data?.type==="graph_error"&&s({title:"Connection failed",description:w.data?.error||"Unknown error",variant:"destructive"})};return window.addEventListener("message",x),()=>window.removeEventListener("message",x)},[s,l]),c?e.jsx(R,{children:e.jsx(O,{className:"py-8 flex justify-center",children:e.jsx(E,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):e.jsx(qe.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},children:e.jsxs(R,{children:[e.jsxs(J,{children:[e.jsxs(Z,{className:"flex items-center gap-2",children:[e.jsx(Xe,{className:"h-5 w-5"}),"Personal Email Connection"]}),e.jsx(ae,{children:"Connect your Microsoft 365 account to send emails as yourself"})]}),e.jsx(O,{className:"space-y-4",children:i?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between p-4 bg-success-soft rounded-lg border border-success/30",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(he,{className:"h-5 w-5 text-success"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-success",children:"Connected"}),e.jsxs("p",{className:"text-sm text-success",children:["Connected ",d?.created_at&&as(new Date(d.created_at),"MMM d, yyyy")]})]})]}),e.jsx(U,{variant:"outline",className:"bg-background",children:o?"Expired":"Active"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Ve,{className:"h-4 w-4"}),"Granted Permissions"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:d?.scopes?.map(x=>e.jsx(U,{variant:"secondary",children:x},x))})]}),o&&e.jsxs(Ne,{className:"border-warning/30 bg-warning-soft",children:[e.jsx(pe,{className:"h-4 w-4 text-warning"}),e.jsx(be,{className:"text-warning",children:"Your connection has expired. Please reconnect to continue sending emails."})]}),!g&&!o&&e.jsxs(Ne,{className:"border-warning/30 bg-warning-soft",children:[e.jsx(pe,{className:"h-4 w-4 text-warning"}),e.jsx(be,{className:"text-warning",children:"Mail.Send permission not granted. Reconnect to enable sending emails."})]}),e.jsxs("div",{className:"flex gap-2",children:[(o||!g)&&e.jsxs(y,{onClick:()=>f(void 0),disabled:p,className:"flex-1",children:[p?e.jsx(E,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ss,{className:"h-4 w-4 mr-2"}),"Reconnect"]}),e.jsxs(y,{variant:"outline",onClick:()=>h(),disabled:u,className:o||!g?"":"flex-1",children:[u?e.jsx(E,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(tt,{className:"h-4 w-4 mr-2"}),"Disconnect"]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"p-4 bg-muted/50 rounded-lg space-y-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"When connected, emails sent from this platform (proposals, reminders, notifications) will appear to come from your Microsoft 365 email address."}),e.jsxs("div",{className:"text-sm space-y-1",children:[e.jsx("p",{className:"font-medium",children:"Permissions requested:"}),e.jsxs("ul",{className:"list-disc list-inside text-muted-foreground",children:[e.jsx("li",{children:"Send email on your behalf"}),e.jsx("li",{children:"Read your basic profile"})]})]})]}),e.jsxs(y,{onClick:()=>f(void 0),disabled:p,className:"w-full",children:[p?e.jsx(E,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ss,{className:"h-4 w-4 mr-2"}),"Connect Microsoft 365"]})]})})]})})}function Gn(){const{toast:s}=re(),[t,r]=zs(),{googleToken:d,isLoading:c,isConnected:i,isExpired:o,hasGmailSendScope:g,connectGoogle:f,disconnectGoogle:h,isConnecting:p,isDisconnecting:u,refetch:l}=sa();return n.useEffect(()=>{const x=t.get("google_user_connected"),w=t.get("google_user_error");x==="true"&&(s({title:"Google connected",description:"You can now send emails from your Google account"}),l(),t.delete("google_user_connected"),r(t)),w&&(s({title:"Connection failed",description:decodeURIComponent(w),variant:"destructive"}),t.delete("google_user_error"),r(t))},[t,s,l,r]),c?e.jsx(R,{children:e.jsx(O,{className:"py-8 flex justify-center",children:e.jsx(E,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):e.jsx(qe.div,{initial:{opacity:0,y:10}
128,animate:{opacity:1,y:0},children:e.jsxs(R,{children:[e.jsxs(J,{children:[e.jsxs(Z,{className:"flex items-center gap-2",children:[e.jsx(Xe,{className:"h-5 w-5"}),"Personal Email Connection (Google)"]}),e.jsx(ae,{children:"Connect your Google account to send emails as yourself"})]}),e.jsx(O,{className:"space-y-4",children:i?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between p-4 bg-success-soft rounded-lg border border-success/30",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(he,{className:"h-5 w-5 text-success"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-success",children:"Connected"}),e.jsxs("p",{className:"text-sm text-success",children:["Connected ",d?.created_at&&as(new Date(d.created_at),"MMM d, yyyy")]})]})]}),e.jsx(U,{variant:"outline",className:"bg-background",children:o?"Expired":"Active"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Ve,{className:"h-4 w-4"}),"Granted Permissions"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:d?.scopes?.map(x=>e.jsx(U,{variant:"secondary",className:"text-xs",children:x.split("/").pop()},x))})]}),o&&e.jsxs(Ne,{className:"border-warning/30 bg-warning-soft",children:[e.jsx(pe,{className:"h-4 w-4 text-warning"}),e.jsx(be,{className:"text-warning",children:"Your connection has expired. Please reconnect to continue sending emails."})]}),!g&&!o&&e.jsxs(Ne,{className:"border-warning/30 bg-warning-soft",children:[e.jsx(pe,{className:"h-4 w-4 text-warning"}),e.jsx(be,{className:"text-warning",children:"Gmail send permission not granted. Reconnect to enable sending emails."})]}),e.jsxs("div",{className:"flex gap-2",children:[(o||!g)&&e.jsxs(y,{onClick:()=>f(void 0),disabled:p,className:"flex-1",children:[p?e.jsx(E,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ss,{className:"h-4 w-4 mr-2"}),"Reconnect"]}),e.jsxs(y,{variant:"outline",onClick:()=>h(),disabled:u,className:o||!g?"":"flex-1",children:[u?e.jsx(E,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(tt,{className:"h-4 w-4 mr-2"}),"Disconnect"]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"p-4 bg-muted/50 rounded-lg space-y-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"When connected, emails sent from this platform (proposals, reminders, notifications) will appear to come from your Google email address."}),e.jsxs("div",{className:"text-sm space-y-1",children:[e.jsx("p",{className:"font-medium",children:"Permissions requested:"}),e.jsxs("ul",{className:"list-disc list-inside text-muted-foreground",children:[e.jsx("li",{children:"Send email on your behalf"}),e.jsx("li",{children:"Read your basic profile"})]})]})]}),e.jsxs(y,{onClick:()=>f(void 0),disabled:p,className:"w-full",children:[p?e.jsx(E,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ss,{className:"h-4 w-4 mr-2"}),"Connect Google"]})]})})]})})}function Hn({open:s,onOpenChange:t,onSuccess:r}){const{currentTenant:d}=ne(),{toast:c}=re(),[i,o]=n.useState(1),[g,f]=n.useState(!1),h=async()=>{if(d){f(!0);try{const{data:l}=await b.auth.getSession();if(!l.session)throw new Error("Not authenticated");const{data:x,error:w}=await b.functions.invoke("granola-oauth-start",{body:{tenant_id:d.id,app_origin:window.location.origin}});if(w)throw w;if(x.error)throw new Error(x.error);if(!x.authorization_url)throw new Error("No authorization URL returned");const v=window.open(x.authorization_url,"granola_oauth","width=600,height=700,scrollbars=yes"),N=_=>{_.data?.type==="granola_oauth_callback"&&(window.removeEventListener("message",N),_.data.success?(o(3),p(),c({title:"Granola connected successfully!"})):c({title:"Connection failed",description:_.data.error||"Please try again",variant:"destructive"}),f(!1))};window.addEventListener("message",N);const S=setInterval(async()=>{if(v?.closed){clearInterval(S),window.removeEventListener("message",N),await new Promise(_=>setTimeout(_,1e3));try{const{data:_}=await b.from("user_granola_tokens").select("id").eq("tenant_id",d.id).maybeSingle();_&&(o(3),p(),c({title:"Granola connected successfully!"}))}catch{}f(!1)}},1e3)}catch(l){console.error("Granola connect error:",l),c({title:"Connection failed",description:l.message||"Could not start OAuth flow",variant:"destructive"}),f(!1)}}},p=async()=>
128{if(d)try{await b.from("tenant_integrations").upsert({tenant_id:d.id,integration_type:"granola",is_active:!0,connected_at:new Date().toISOString(),scopes:["list_meetings","get_meetings","get_meeting_transcript","query_granola_meetings"]},{onConflict:"tenant_id,integration_type"})}catch(l){console.error("Failed to register tenant integration:",l)}},u=()=>{i===3&&r(),o(1),t(!1)};return e.jsx(_e,{open:s,onOpenChange:u,children:e.jsxs(Se,{className:"max-w-lg",children:[e.jsxs(ke,{children:[e.jsxs(Ae,{className:"flex items-center gap-2",children:[e.jsx(Hs,{className:"h-5 w-5"}),"Connect Granola"]}),e.jsx(Ee,{children:"Import meeting notes and transcripts from Granola into CommandOS"})]}),e.jsxs($s,{children:[i===1&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Js,{name:"Granola",whatItDoes:["Browse and import AI meeting notes into projects","Pull full transcripts for sentiment & action item extraction","Link meetings to clients, prospects, or projects"],permissions:[{label:"list_meetings",description:"List your meetings"},{label:"get_meetings",description:"Read meeting notes"},{label:"get_meeting_transcript",description:"Pull transcripts"},{label:"query_granola_meetings",description:"Search meeting history"}],dataFlow:"On-demand pull from Granola â CommandOS, per-user OAuth.",helpHref:"/docs/integrations/granola"}),e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-primary/5 rounded-lg text-sm",children:[e.jsx(Ve,{className:"h-4 w-4 text-primary shrink-0"}),e.jsx("span",{className:"text-muted-foreground",children:"Each team member connects their own Granola account. No API key required."})]}),e.jsxs(y,{onClick:()=>o(2),className:"w-full",children:["Continue",e.jsx(Xs,{className:"h-4 w-4 ml-2"})]})]}),i===2&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"p-6 border-2 border-dashed rounded-lg text-center space-y-4",children:[e.jsx(Hs,{className:"h-12 w-12 text-muted-foreground mx-auto"}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-1",children:"Sign in with Granola"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"You'll be redirected to Granola to authorize access to your meeting notes."})]}),e.jsxs(y,{onClick:h,disabled:g,size:"lg",className:"w-full",children:[g?e.jsx(E,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Hs,{className:"h-4 w-4 mr-2"}),g?"Connecting...":"Sign in with Granola"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(U,{variant:"secondary",children:"list_meetings"}),e.jsx(U,{variant:"secondary",children:"get_meetings"}),e.jsx(U,{variant:"secondary",children:"get_meeting_transcript"}),e.jsx(U,{variant:"secondary",children:"query_granola_meetings"})]})]}),i===3&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"p-6 text-center space-y-3",children:[e.jsx(he,{className:"h-12 w-12 text-success mx-auto"}),e.jsx("h4",{className:"font-semibold text-lg",children:"Granola Connected!"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your Granola account is now linked. You can browse and import meeting notes from the project transcripts tab or the meeting browser."})]}),e.jsx(y,{onClick:u,className:"w-full",children:"Done"})]})]})]})})}function Un(){const{toast:s}=re(),{currentTenant:t}=ne(),r=He(),[d,c]=zs(),[i,o]=n.useState(!1),[g,f]=n.useState(!1),{data:h,isLoading:p,refetch:u}=Oe({queryKey:["granola-token",t?.id],queryFn:async()=>{if(!t)return null;const{data:N}=await b.from("user_granola_tokens").select("id, connected_at, granola_email, token_expires_at, created_at").eq("tenant_id",t.id).maybeSingle();return N},enabled:!!t}),l=!!h,x=h?.token_expires_at?new Date(h.token_expires_at)<new Date:!1;n.useEffect(()=>{const N=d.get("granola_connected"),S=d.get("granola_error");N==="true"&&(s({title:"Granola connected",description:"Your Granola account is now linked"}),u(),d.delete("granola_connected"),c(d)),S&&(s({title:"Connection failed",description:decodeURIComponent(S),variant:"destructive"}),d.delete("granola_error"),c(d))},[d,s,u,c]),n.useEffect(()=>{const N=S=>{S.data?.type==="granola_oauth_callback"&&(S.data.success?(s({title:"Granola connected"}),u()):s({title:"Connection failed",description:S.data.error,variant:"destructive"}),o(!1))};return window.addEventListener("message",N),()=>window.removeEventListener("message",N)},[s,u]);const w=n.useCallback(async()=>
128{if(t){o(!0);try{const{data:N,error:S}=await b.functions.invoke("granola-oauth-start",{body:{tenant_id:t.id,app_origin:window.location.origin}});if(S)throw S;if(N.error)throw new Error(N.error);const _=window.open(N.authorization_url,"granola_oauth","width=600,height=700,scrollbars=yes"),P=setInterval(async()=>{_?.closed&&(clearInterval(P),await new Promise(G=>setTimeout(G,1e3)),u(),o(!1))},1e3)}catch(N){s({title:"Connection failed",description:N.message,variant:"destructive"}),o(!1)}}},[t,s]),v=n.useCallback(async()=>{if(h){f(!0);try{const{error:N}=await b.from("user_granola_tokens").delete().eq("id",h.id);if(N)throw N;s({title:"Granola disconnected"}),r.invalidateQueries({queryKey:["granola-token"]})}catch(N){s({title:"Failed to disconnect",description:N.message,variant:"destructive"})}finally{f(!1)}}},[h,s,r]);return p?e.jsx(R,{children:e.jsx(O,{className:"py-8 flex justify-center",children:e.jsx(E,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):e.jsx(qe.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},children:e.jsxs(R,{children:[e.jsxs(J,{children:[e.jsxs(Z,{className:"flex items-center gap-2",children:[e.jsx(Hs,{className:"h-5 w-5"}),"Granola Meeting Notes"]}),e.jsx(ae,{children:"Connect your Granola account to import meeting notes and transcripts"})]}),e.jsx(O,{className:"space-y-4",children:l?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between p-4 bg-success-soft rounded-lg border border-success/30",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(he,{className:"h-5 w-5 text-success"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-success",children:"Connected"}),e.jsx("p",{className:"text-sm text-success",children:h.granola_email?h.granola_email:`Connected ${h.connected_at?as(new Date(h.connected_at),"MMM d, yyyy"):""}`})]})]}),e.jsx(U,{variant:"outline",className:"bg-background",children:x?"Expired":"Active"})]}),e.jsxs("div",{className:"flex gap-2 items-center",children:[x&&e.jsxs(y,{onClick:w,disabled:i,className:"flex-1",children:[i?e.jsx(E,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ss,{className:"h-4 w-4 mr-2"}),"Reconnect"]}),e.jsxs(y,{variant:"outline",onClick:v,disabled:g,className:x?"":"flex-1",children:[g?e.jsx(E,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(tt,{className:"h-4 w-4 mr-2"}),"Disconnect"]}),e.jsx(Kt,{children:e.jsxs(Ke,{children:[e.jsx($e,{asChild:!0,children:e.jsx(y,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0","aria-label":"Information",children:e.jsx(us,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsxs(Ye,{side:"top",className:"max-w-xs text-sm",children:[e.jsx("p",{className:"font-medium mb-1",children:"Where is this used?"}),e.jsxs("ul",{className:"list-disc pl-4 space-y-0.5 text-muted-foreground",children:[e.jsx("li",{children:"Project Transcripts â import meeting notes"}),e.jsx("li",{children:"Client & Prospect pages â pull related meetings"}),e.jsx("li",{children:"Meeting Notes dialog â import directly from Granola"})]})]})]})})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"p-4 bg-muted/50 rounded-lg space-y-3",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Connect your Granola account to import meeting notes, transcripts, and AI-enhanced summaries directly into your projects and client records."})}),e.jsxs(y,{onClick:w,disabled:i,className:"w-full",children:[i?e.jsx(E,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ss,{className:"h-4 w-4 mr-2"}),"Connect Granola"]})]})})]})})}const ua=[{group:"United States",options:[{value:"America/New_York",label:"Eastern Time (ET)"},{value:"America/Chicago",label:"Central Time (CT)"},{value:"America/Denver",label:"Mountain Time (MT)"},{value:"America/Los_Angeles",label:"Pacific Time (PT)"},{value:"America/Anchorage",label:"Alaska Time (AKT)"},{value:"Pacific/Honolulu",label:"Hawaii Time (HT)"}]},{group:"Canada",options:[{value:"America/Toronto",label:"Toronto (ET)"},{value:"America/Vancouver",label:"Vancouver (PT)"},{value:"America/Edmonton",label:"Edmonton (MT)"}]},{group:"Europe",options:[{value:"Europe/London",label:"London (GMT/BST)"},{value:"Europe/Paris",label:"Paris (CET)"},{value:"Europe/Berlin",label:"Berlin (CET)"},{value:"Europe/Amsterdam",label:"Amsterdam (CET)"},{value:"Europe/Madrid",label:"Madrid (CET)"},{value:"Europe/Rome",label:"Rome (CET)"},{value:"Europe/Zurich",label:"Zurich (CET)"}
128]},{group:"Asia Pacific",options:[{value:"Asia/Tokyo",label:"Tokyo (JST)"},{value:"Asia/Singapore",label:"Singapore (SGT)"},{value:"Asia/Hong_Kong",label:"Hong Kong (HKT)"},{value:"Asia/Shanghai",label:"Shanghai (CST)"},{value:"Asia/Seoul",label:"Seoul (KST)"},{value:"Asia/Mumbai",label:"Mumbai (IST)"},{value:"Asia/Dubai",label:"Dubai (GST)"},{value:"Australia/Sydney",label:"Sydney (AEDT)"},{value:"Australia/Melbourne",label:"Melbourne (AEDT)"},{value:"Pacific/Auckland",label:"Auckland (NZDT)"}]},{group:"Latin America",options:[{value:"America/Mexico_City",label:"Mexico City (CST)"},{value:"America/Sao_Paulo",label:"São Paulo (BRT)"},{value:"America/Argentina/Buenos_Aires",label:"Buenos Aires (ART)"},{value:"America/Bogota",label:"Bogota (COT)"},{value:"America/Lima",label:"Lima (PET)"}]}],Wn=ua.flatMap(s=>s.options);function zt(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"America/New_York"}}function Vn(s){return s==="auto"?"Auto-detect":Wn.find(r=>r.value===s)?.label||s}function Qn(){const[s,t]=n.useState(""),[r,d]=n.useState("auto"),[c,i]=n.useState(!1),[o,g]=n.useState(!1),{user:f}=jt(),{toast:h}=re();n.useEffect(()=>{(async()=>{if(f){i(!0);try{const{data:x}=await b.from("profiles").select("calendar_url, timezone").eq("user_id",f.id).single();x?.calendar_url&&t(x.calendar_url),x?.timezone&&d(x.timezone)}catch(x){console.error("Error loading calendar settings:",x)}finally{i(!1)}}})()},[f]);const p=async()=>{if(f){g(!0);try{const l=r==="auto"?zt():r,{error:x}=await b.from("profiles").update({calendar_url:s||null,timezone:l}).eq("user_id",f.id);if(x)throw x;h({title:"Settings saved",description:s?`Calendar will display times in ${Vn(l)}.`:"Calendar integration removed."})}catch(l){console.error("Error saving calendar settings:",l),h({title:"Save failed",description:"Could not save settings. Please try again.",variant:"destructive"})}finally{g(!1)}}};if(c)return e.jsx(R,{children:e.jsx(O,{className:"flex items-center justify-center py-8",children:e.jsx(E,{className:"h-6 w-6 animate-spin text-muted-foreground"})})});const u=zt();return e.jsxs(R,{children:[e.jsx(J,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10",children:e.jsx(Ws,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Z,{children:"Calendar Integration"}),e.jsx(ae,{children:"Connect your calendar to include events in AI briefings"})]})]})}),e.jsxs(O,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(B,{htmlFor:"timezone",className:"flex items-center gap-2",children:[e.jsx(hs,{className:"h-4 w-4"}),"Timezone"]}),e.jsxs(ie,{value:r,onValueChange:d,children:[e.jsx(ce,{id:"timezone",className:"w-full",children:e.jsx(le,{placeholder:"Select timezone"})}),e.jsxs(oe,{className:"max-h-[300px]",children:[e.jsxs(V,{value:"auto",children:["Auto-detect (",u.split("/").pop()?.replace("_"," "),")"]}),ua.map(l=>e.jsxs(ya,{children:[e.jsx(va,{children:l.group}),l.options.map(x=>e.jsx(V,{value:x.value,children:x.label},x.value))]},l.group))]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Calendar times will be displayed in this timezone"})]}),e.jsxs("div",{className:"border-t pt-4 space-y-4",children:[e.jsxs(Ne,{children:[e.jsx(pe,{className:"h-4 w-4"}),e.jsx(be,{children:"Paste your public iCal/ICS URL. This works with Google Calendar, Outlook, Apple Calendar, and most calendar apps."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{htmlFor:"calendar-url",children:"iCal URL"}),e.jsx(se,{id:"calendar-url",type:"url",placeholder:"https://calendar.google.com/calendar/ical/...",value:s,onChange:l=>t(l.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Find this in your calendar settings under "Share" or "Export"'})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(y,{onClick:p,disabled:o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(E,{className:"mr-2 h-4 w-4 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ce,{className:"mr-2 h-4 w-4"}),"Save Settings"]})}),s&&e.jsx(y,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:s,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(ns,{className:"mr-2 h-4 w-4"}),"Test URL"]})})]}),e.jsxs("div",{className:"rounded-lg border bg-muted/50 p-4 space-y-2",children:[e.jsx("h4",{className:"font-medium text-sm",children:"How to get your calendar URL:"}),e.jsxs("ul",{className:"text-sm text-muted-foreground space-y-1",children:[e.jsxs("li",{children:[e.jsx("strong",{children:"Google Calendar:"})," Settings â Calendar settings â Integrate calendar â Secret address in iCal format"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Outlook:"})," Calendar â Share â Publish â ICS link"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Apple Calendar:"})," Right-click calendar â Share Calendar â Public Calendar"]})]})]})]})]})]})}function Kn({open:s,onOpenChange:t,pdfUrl:r,pdfName:d,extractedSettings:c}){const[i,o]=n.useState([]),[g,f]=n.useState(!1),[h,p]=n.useState(1),[u,l]=n.useState(0);n.useEffect(()=>{s&&r&&x()},[s,r]);const x=async()=>
128{if(r){f(!0);try{Yt.workerSrc=Ia;const S=await(await fetch(r)).arrayBuffer(),_=await Jt({data:S}).promise,P=[],G=Math.min(_.numPages,20);for(let a=1;a<=G;a++){const j=await _.getPage(a),M=j.getViewport({scale:1.5}),W=document.createElement("canvas");W.width=M.width,W.height=M.height;const K=W.getContext("2d");await j.render({canvasContext:K,viewport:M}).promise,P.push(W.toDataURL("image/jpeg",.85))}o(P)}catch(N){console.error("Error loading PDF:",N)}finally{f(!1)}}},w=c?[{label:"Legal Name",value:c.company_legal_name},{label:"Entity Type",value:c.entity_type},{label:"State of Formation",value:c.state_of_formation},{label:"Governing Law",value:c.governing_law_state},{label:"Payment Terms",value:`Net ${c.payment_terms_days} days`},{label:"Warranty Period",value:`${c.warranty_period_days} days`},{label:"Cure Period",value:`${c.cure_period_days} days`},{label:"Non-Solicitation",value:`${c.non_solicit_months} months`},{label:"Acceptance Period",value:`${c.acceptance_period_days} days`}]:[],v=c?[{label:"IP Section",enabled:c.include_ip_section},{label:"Confidentiality",enabled:c.include_confidentiality},{label:"Data Protection",enabled:c.include_data_protection},{label:"Penetration Testing",enabled:c.include_penetration_testing},{label:"Non-Solicitation",enabled:c.include_non_solicitation},{label:"Limitation of Liability",enabled:c.include_limitation_of_liability}]:[];return e.jsx(_e,{open:s,onOpenChange:t,children:e.jsxs(Se,{className:"max-w-6xl h-[85vh] flex flex-col p-0",children:[e.jsx(ke,{className:"px-6 py-4 border-b shrink-0",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Us,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx(Ae,{children:"MSA Comparison"}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-0.5",children:[d||"Uploaded Document"," vs Extracted Fields"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(y,{variant:"outline",size:"icon",onClick:()=>p(Math.max(.5,h-.25)),"aria-label":"Zoom out",children:e.jsx(Da,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-sm text-muted-foreground w-12 text-center",children:[Math.round(h*100),"%"]}),e.jsx(y,{variant:"outline",size:"icon",onClick:()=>p(Math.min(2,h+.25)),"aria-label":"Zoom in",children:e.jsx(Ea,{className:"h-4 w-4"})}),r&&e.jsx(y,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:r,download:d,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Download"]})})]})]})}),e.jsxs("div",{className:"flex-1 grid grid-cols-2 gap-0 overflow-hidden",children:[e.jsxs("div",{className:"border-r flex flex-col",children:[e.jsxs("div",{className:"px-4 py-2 bg-muted/50 border-b shrink-0",children:[e.jsx("h3",{className:"font-medium text-sm",children:"Original Document"}),i.length>0&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Page ",u+1," of ",i.length]})]}),e.jsx(Ds,{className:"flex-1",children:e.jsx("div",{className:"p-4",children:g?e.jsx("div",{className:"flex items-center justify-center h-96",children:e.jsx(E,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):i.length>0?e.jsx("div",{className:"space-y-4",children:i.map((N,S)=>e.jsx("div",{className:"border rounded-lg overflow-hidden shadow-sm",style:{transform:`scale(${h})`,transformOrigin:"top left"},children:e.jsx("img",{src:N,alt:`Page ${S+1}`,className:"w-full",onMouseEnter:()=>l(S)})},S))}):e.jsxs("div",{className:"flex flex-col items-center justify-center h-96 text-muted-foreground",children:[e.jsx(Us,{className:"h-12 w-12 mb-4 opacity-30"}),e.jsx("p",{children:"No document uploaded"})]})})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"px-4 py-2 bg-muted/50 border-b shrink-0",children:[e.jsx("h3",{className:"font-medium text-sm",children:"Extracted Terms"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"AI-parsed contract details"})]}),e.jsx(Ds,{className:"flex-1",children:e.jsxs("div",{className:"p-4 space-y-6",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold mb-3 text-muted-foreground uppercase tracking-wide",children:"Entity Information"}),e.jsx("div",{className:"space-y-3",children:w.slice(0,4).map(N=>e.jsxs("div",{className:"flex justify-between items-start border-b pb-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:N.label}),e.jsx("span",{className:"text-sm font-medium text-right max-w-[60%]",children:N.value||e.jsx("span",{className:"text-muted-foreground
128/50",children:"Not found"})})]},N.label))})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold mb-3 text-muted-foreground uppercase tracking-wide",children:"Commercial Terms"}),e.jsx("div",{className:"space-y-3",children:w.slice(4).map(N=>e.jsxs("div",{className:"flex justify-between items-start border-b pb-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:N.label}),e.jsx("span",{className:"text-sm font-medium",children:N.value||e.jsx("span",{className:"text-muted-foreground/50",children:"Not found"})})]},N.label))})]}),e.jsx(me,{}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold mb-3 text-muted-foreground uppercase tracking-wide",children:"Detected Sections"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:v.map(N=>e.jsx(U,{variant:N.enabled?"default":"outline",className:N.enabled?"":"opacity-50",children:N.label},N.label))})]}),c?.arbitration_rules&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold mb-2 text-muted-foreground uppercase tracking-wide",children:"Arbitration Rules"}),e.jsx("p",{className:"text-sm bg-muted/50 p-3 rounded-lg",children:c.arbitration_rules})]}),c?.company_address&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold mb-2 text-muted-foreground uppercase tracking-wide",children:"Company Address"}),e.jsx("p",{className:"text-sm bg-muted/50 p-3 rounded-lg whitespace-pre-line",children:c.company_address})]})]})})]})]})]})})}Yt.workerSrc=`//cdnjs.cloudflare.com/ajax/libs/pdf.js/${Ta}/pdf.worker.min.js`;const Bt=s=>{const t=s.match(/^(\d+)\./);return t?parseInt(t[1],10):999},$n=s=>[...s].sort((t,r)=>Bt(t.title)-Bt(r.title)),Gt={company_legal_name:"",entity_type:"LLC",state_of_formation:"",company_address:"",payment_terms_days:30,warranty_period_days:30,cure_period_days:30,non_solicit_months:18,governing_law_state:"Delaware",arbitration_rules:"American Arbitration Association Commercial Arbitration Rules",acceptance_period_days:10,include_ip_section:!0,include_confidentiality:!0,include_data_protection:!0,include_penetration_testing:!1,include_non_solicitation:!0,include_limitation_of_liability:!0,custom_msa_text:""},Yn=["LLC","Corporation","S-Corporation","Partnership","Sole Proprietorship","LLP"],Ht=["Alabama","Alaska","Arizona","Arkansas","California","Colorado","Connecticut","Delaware","Florida","Georgia","Hawaii","Idaho","Illinois","Indiana","Iowa","Kansas","Kentucky","Louisiana","Maine","Maryland","Massachusetts","Michigan","Minnesota","Mississippi","Missouri","Montana","Nebraska","Nevada","New Hampshire","New Jersey","New Mexico","New York","North Carolina","North Dakota","Ohio","Oklahoma","Oregon","Pennsylvania","Rhode Island","South Carolina","South Dakota","Tennessee","Texas","Utah","Vermont","Virginia","Washington","West Virginia","Wisconsin","Wyoming"];function Jn(){const[s,t]=n.useState(Gt),[r,d]=n.useState(!0),[c,i]=n.useState(!1),[o,g]=n.useState(!1),[f,h]=n.useState(0),[p,u]=n.useState(""),[l,x]=n.useState([]),[w,v]=n.useState(null),[N,S]=n.useState(!1),[_,P]=n.useState(null),G=n.useRef(null),{toast:a}=re(),{currentTenant:j}=ne();n.useEffect(()=>{j?.id&&M()},[j?.id]);const M=async()=>{if(j?.id){d(!0);try{const{data:m}=await b.from("msa_settings").select("*").eq("tenant_id",j.id).limit(1).maybeSingle();if(m){const k={...m,msa_sections:Array.isArray(m.msa_sections)?m.msa_sections:void 0};t(k)}else t(Gt)}catch(m){console.error("Error loading MSA settings:",m)}finally{d(!1)}}},W=async m=>{const k=m.target.files?.[0];if(k){if(!k.type.includes("pdf")&&!k.type.includes("word")){a({title:"Unsupported file type",description:"Please upload a PDF or Word document",variant:"destructive"});return}g(!0),v(null),h(10),u("Reading document...");try{let q="",A=[];if(k.type==="application/pdf"){h(15),u("Uploading document to storage...");const Y=`${j?.id||"default"}/${Date.now()}-${k.name}`,{data:xe,error:F}=await b.storage.from("msa-documents").upload(Y,k,{contentType:k.type,upsert:!0});F&&console.error("Upload error:",F);let X,I;if(xe){const{data:te}=b.storage.from("msa-documents").getPublicUrl(xe.path);X=te.publicUrl,I=k.name}h(20),u("Extracting PDF content...");const C=await k.arrayBuffer(),$=await Jt({data:C}).promise,z=Math.min($.numPages,30);for(let te=1;te<=z;te++){h(20+te/z*30),u(`Processing page ${te} of ${z}...`);const ge=await $.getPage(te),rs=(await ge.getTextContent()).items.map(nt=>nt.str).join(" ");
128q+=rs+` 129 130`;const Fe=ge.getViewport({scale:1.5}),Qe=document.createElement("canvas");Qe.width=Fe.width,Qe.height=Fe.height;const Ze=Qe.getContext("2d");await ge.render({canvasContext:Ze,viewport:Fe}).promise;const at=Qe.toDataURL("image/jpeg",.8).split(",")[1];A.push(at)}X&&s.id&&(await b.from("msa_settings").update({source_pdf_url:X,source_pdf_name:I}).eq("id",s.id),t(te=>({...te,source_pdf_url:X,source_pdf_name:I})))}else{h(20),u("Extracting Word document content...");const Y=await k.arrayBuffer(),xe=await La.extractRawText({arrayBuffer:Y});q=xe.value,xe.messages&&xe.messages.length>0&&ut.info("Mammoth warnings:",xe.messages),h(50),u("Document text extracted...")}h(60),u("Analyzing with AI...");const{data:ee,error:D}=await b.functions.invoke("parse-msa",{body:{text_content:q,page_images:A.length>0?A:void 0,file_type:"image/jpeg"}});if(D)throw D;if(!ee.success)throw new Error(ee.error);h(90),u("Applying extracted data...");const H=ee.data;t(Y=>({...Y,company_legal_name:H.company_legal_name||Y.company_legal_name,entity_type:H.entity_type||Y.entity_type,state_of_formation:H.state_of_formation||Y.state_of_formation,company_address:H.company_address||Y.company_address,payment_terms_days:H.payment_terms_days||Y.payment_terms_days,warranty_period_days:H.warranty_period_days||Y.warranty_period_days,cure_period_days:H.cure_period_days||Y.cure_period_days,non_solicit_months:H.non_solicit_months||Y.non_solicit_months,acceptance_period_days:H.acceptance_period_days||Y.acceptance_period_days,governing_law_state:H.governing_law_state||Y.governing_law_state,arbitration_rules:H.arbitration_rules||Y.arbitration_rules,include_ip_section:H.include_ip_section??Y.include_ip_section,include_confidentiality:H.include_confidentiality??Y.include_confidentiality,include_data_protection:H.include_data_protection??Y.include_data_protection,include_penetration_testing:H.include_penetration_testing??Y.include_penetration_testing,include_non_solicitation:H.include_non_solicitation??Y.include_non_solicitation,include_limitation_of_liability:H.include_limitation_of_liability??Y.include_limitation_of_liability,msa_sections:H.msa_sections&&H.msa_sections.length>0?H.msa_sections:Y.msa_sections})),H.notable_clauses&&H.notable_clauses.length>0&&x(H.notable_clauses),h(100),u("Complete!"),a({title:"MSA parsed successfully",description:"Review the extracted terms and save when ready"})}catch(q){console.error("MSA parse error:",q),v(q.message||"Failed to parse document"),a({title:"Failed to parse MSA",description:q.message,variant:"destructive"})}finally{setTimeout(()=>{g(!1),h(0),u("")},1500),G.current&&(G.current.value="")}}},K=(m,k)=>{t(q=>({...q,msa_sections:q.msa_sections?.map(A=>A.id===m?{...A,content:k}:A)}))},T=(m,k)=>{t(q=>({...q,msa_sections:q.msa_sections?.map(A=>A.id===m?{...A,enabled:k}:A)}))},L=async()=>{if(!j?.id){a({title:"Error saving MSA settings",description:"No tenant selected",variant:"destructive"});return}i(!0);try{const{id:m,organization_id:k,tenant_id:q,...A}=s;if(m){const{error:ee}=await b.from("msa_settings").update({...A,msa_sections:A.msa_sections}).eq("id",m);if(ee)throw ee}else{const{error:ee}=await b.from("msa_settings").insert({...A,tenant_id:j.id,msa_sections:A.msa_sections});if(ee)throw ee}a({title:"MSA settings saved successfully"}),M()}catch(m){a({title:"Error saving MSA settings",description:m.message,variant:"destructive"})}finally{i(!1)}};return r?e.jsx(R,{children:e.jsx(O,{className:"flex items-center justify-center py-12",children:e.jsx(E,{className:"h-8 w-8 animate-spin text-muted-foreground"})})}):e.jsxs(e.Fragment,{children:[e.jsxs(R,{children:[e.jsxs(J,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10",children:e.jsx(Us,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Z,{children:"Master Service Agreement"}),e.jsx(ae,{children:"Configure your company information and standard contract terms"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[s.source_pdf_url&&e.jsxs(y,{variant:"outline",size:"sm",onClick:()=>S(!0),className:"gap-2",children:[e.jsx(Is,{className:"h-4 w-4"}),"Compare"]}),e.jsx("input",{ref:G,type:"file",accept:".pdf,.docx,.doc",onChange:W,className:"hidden",id:"msa-upload"}),e.jsx(y,{variant:"outline",onClick:()=>G.current?.click(),disabled:o,className:"gap-2",children:o?e.jsxs(e.Fragment,{children:[e.jsx(E,{className:"h-4 w-4 animate-spin"}),"Parsing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(At,{className:"h-4 w-4"}),"Upload MSA"]})})]})]}),s.source_pdf_name&&e.jsxs("div",{className:"mt-3 flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Us,{className:"h-4 w-4"}),e.jsxs("span",{children:["Source: ",s.source_pdf_name]}),s.source_pdf_url&&e.jsx("a",{href:s.source_pdf_url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline",children:e.jsx(Ys,{className:"h-4 w-4"})})]}),o&&e.jsxs("div",{className:"mt-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(xs,{className:"h-4 w-4 text-primary animate-pulse"}),p]}),e.jsxs("span",{className:"text-muted-foreground",children:[f,"%"]})]}),e.jsx(ys,{value:f,className:"h-2"})]}),w&&e.jsxs(Ne,{variant:"destructive",className:"mt-4",children:[e.jsx(pe,{className:"h-4 w-4"}),e.jsx(be,{children:w})]}),l.length>0&&e.jsxs("div",{className:"mt-4 p-4 bg-warning-soft border border-warning/30 rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(xs,{className:"h-4 w-4 text-warning"}),e.jsx("span",{className:"font-medium text-warning",children:"Notable Clauses Detected"})]}),e.jsx("ul",{className:"text-sm text-warning space-y-1",children:l.map((m,k)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx(Ce,{className:"h-3 w-3 mt-1 flex-shrink-0"}),e.jsx("span",{children:m})]},k))}),e.jsx(y,{variant:"ghost",size:"sm",className:"mt-2 text-warning",onClick:()=>x([]),children:"Dismiss"})]})]}),e.jsx(O,{children:e.jsxs(js,{defaultValue:"company",className:"space-y-6",children:[e.jsxs(fs,{className:"grid w-full grid-cols-3",children:[e.jsx(ve,{value:"company",children:"Company Info"}),e.jsx(ve,{value:"terms",children:"Contract Terms"}),e.jsx(ve,{value:"agreement",children:"Your Agreement"})]}),e.jsxs(ue,{value:"company",className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{children:"Legal Company Name"}),e.jsx(se,{value:s.company_legal_name,onChange:m=>t({...s,company_legal_name:m.target.value}),placeholder:"e.g., BD Emerson LLC"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{children:"Entity Type"}),e.jsxs(ie,{value:s.entity_type,onValueChange:m=>t({...s,entity_type:m}),children:[e.jsx(ce,{children:e.jsx(le,{})}),e.jsx(oe,{children:Yn.map(m=>e.jsx(V,{value:m,children:m},m))})]})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{children:"State of Formation"}),e.jsxs(ie,{value:s.state_of_formation,onValueChange:m=>t({...s,state_of_formation:m}),children:[e.jsx(ce,{children:e.jsx(le,{placeholder:"Select state"})}),e.jsx(oe,{children:Ht.map(m=>e.jsx(V,{value:m,children:m},m))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{children:"Governing Law State"}),e.jsxs(ie,{value:s.governing_law_state,onValueChange:m=>t({...s,governing_law_state:m}),children:[e.jsx(ce,{children:e.jsx(le,{})}),e.jsx(oe,{children:Ht.map(m=>e.jsx(V,{value:m,children:m},m))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{children:"Company Address"}),e.jsx(As,{value:s.company_address,onChange:m=>t({...s,company_address:m.target.value}),placeholder:"9702 Gayton Road, Suite 303, Richmond VA 23238",rows:2})]}
130),e.jsxs(y,{onClick:L,disabled:c,children:[c?e.jsx(E,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(rt,{className:"h-4 w-4 mr-2"}),"Save Company Info"]})]}),e.jsxs(ue,{value:"terms",className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{children:"Payment Terms (days)"}),e.jsx(se,{type:"number",value:s.payment_terms_days,onChange:m=>t({...s,payment_terms_days:parseInt(m.target.value)||30})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{children:"Warranty Period (days)"}),e.jsx(se,{type:"number",value:s.warranty_period_days,onChange:m=>t({...s,warranty_period_days:parseInt(m.target.value)||30})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{children:"Cure Period (days)"}),e.jsx(se,{type:"number",value:s.cure_period_days,onChange:m=>t({...s,cure_period_days:parseInt(m.target.value)||30})})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{children:"Non-Solicitation (months)"}),e.jsx(se,{type:"number",value:s.non_solicit_months,onChange:m=>t({...s,non_solicit_months:parseInt(m.target.value)||18})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{children:"Acceptance Period (days)"}),e.jsx(se,{type:"number",value:s.acceptance_period_days,onChange:m=>t({...s,acceptance_period_days:parseInt(m.target.value)||10})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{children:"Arbitration Rules"}),e.jsx(As,{value:s.arbitration_rules,onChange:m=>t({...s,arbitration_rules:m.target.value}),rows:2})]}),e.jsx(me,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-medium",children:"Contract Sections to Include"}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:[{key:"include_ip_section",label:"Intellectual Property",desc:"IP ownership and licensing terms"},{key:"include_confidentiality",label:"Confidentiality",desc:"NDA and data protection clauses"},{key:"include_data_protection",label:"Data Protection",desc:"GDPR/CCPA compliance terms"},{key:"include_penetration_testing",label:"Penetration Testing",desc:"Security testing liability waiver"},{key:"include_non_solicitation",label:"Non-Solicitation",desc:"Employee hiring restrictions"},{key:"include_limitation_of_liability",label:"Limitation of Liability",desc:"Damage caps and exclusions"}].map(({key:m,label:k,desc:q})=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:k}),e.jsx("p",{className:"text-sm text-muted-foreground",children:q})]}),e.jsx(ye,{checked:s[m],onCheckedChange:A=>t({...s,[m]:A})})]},m))})]}),e.jsxs(y,{onClick:L,disabled:c,children:[c?e.jsx(E,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(rt,{className:"h-4 w-4 mr-2"}),"Save Contract Terms"]})]}),e.jsxs(ue,{value:"agreement",className:"space-y-6",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium",children:"Your Agreement Sections"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"These sections were extracted from your uploaded MSA and will be used in proposals"})]})}),s.msa_sections&&s.msa_sections.length>0?e.jsxs("div",{className:"space-y-4",children:[$n(s.msa_sections).map(m=>e.jsxs("div",{className:`border rounded-lg transition-colors ${m.enabled?"border-border":"border-muted bg-muted/30"}`,children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Pt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:m.title}),!m.enabled&&e.jsx(U,{variant:"secondary",className:"text-xs",children:"Disabled"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{checked:m.enabled,onCheckedChange:k=>T(m.id,k)}),_===m.id?e.jsx(y,{variant:"ghost",size:"sm",onClick:()=>P(null),children:e.jsx(Ce,{className:"h-4 w-4"})}):e.jsx(y,{variant:"ghost",size:"sm",onClick:()=>P(m.id),children:e.jsx(Fa,{className:"h-4 w-4"})})]})]}),e.jsx("div",{className:"p-4",children:_===m.id?e.jsx(As,{value:m.content,onChange:k=>K(m.id,k.target.value),rows:8,className:"font-mono text-sm"}):e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap line-clamp-4",children:m.content})})]}
130,m.id)),e.jsxs(y,{onClick:L,disabled:c,children:[c?e.jsx(E,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(rt,{className:"h-4 w-4 mr-2"}),"Save Agreement"]})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-12 text-center",children:[e.jsx(Pt,{className:"h-12 w-12 mx-auto text-muted-foreground/30 mb-4"}),e.jsx("p",{className:"text-muted-foreground mb-2",children:"No agreement sections found"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Upload your MSA document to extract and manage your contract sections"}),e.jsxs(y,{variant:"outline",onClick:()=>G.current?.click(),disabled:o,children:[e.jsx(At,{className:"h-4 w-4 mr-2"}),"Upload MSA Document"]})]}),e.jsxs(Ne,{children:[e.jsx(pe,{className:"h-4 w-4"}),e.jsx(be,{children:"These sections will be included in proposals. You can enable/disable or edit individual sections here."})]})]})]})})]}),e.jsx(Kn,{open:N,onOpenChange:S,pdfUrl:s.source_pdf_url||null,pdfName:s.source_pdf_name||null,extractedSettings:s})]})}function Zn(){const{toast:s}=re(),{currentTenant:t}=ne(),[r,d]=n.useState(!0),[c,i]=n.useState(!1),[o,g]=n.useState([]),[f,h]=n.useState([]),[p,u]=n.useState([]),[l,x]=n.useState(!0),[w,v]=n.useState(!0);n.useEffect(()=>{N(),S()},[t]);const N=async()=>{if(t)try{const{data:m,error:k}=await b.from("signing_workflow_settings").select("*").eq("tenant_id",t.id).single();if(k&&k.code!=="PGRST116")throw k;if(m){const q=m;g(Array.isArray(q.default_signers)?q.default_signers:[]),h(Array.isArray(q.cc_recipients)?q.cc_recipients:[]),x(q.require_internal_approval??!0),v(q.send_executed_copy??!0)}}catch(m){console.error("Error loading signing workflow settings:",m)}finally{d(!1)}},S=async()=>{if(t)try{const{data:m,error:k}=await b.from("tenant_members").select("user_id").eq("tenant_id",t.id);if(k)throw k;const q=(m||[]).map(D=>D.user_id);if(q.length===0){u([]);return}const{data:A,error:ee}=await b.from("profiles").select("user_id, full_name, email, title").in("user_id",q).order("full_name");if(ee)throw ee;u((A||[]).map(D=>({id:D.user_id,full_name:D.full_name||"Unknown",email:D.email||"",title:D.title})))}catch(m){console.error("Error loading team members:",m),u([])}},_=m=>{const k=o.length+1;g([...o,{id:crypto.randomUUID(),signer_type:m,signer_name:m==="client"?"[Client Signatory]":"",signer_email:m==="client"?"[From Proposal]":"",signer_title:m==="client"?"[From Proposal]":"",signer_role:"signer",signing_order:k,is_required:!0}])},P=(m,k,q)=>{g(o.map(A=>A.id===m?{...A,[k]:q}:A))},G=m=>{const k=o.filter(q=>q.id!==m).map((q,A)=>({...q,signing_order:A+1}));g(k)},a=n.useCallback(m=>{if(!m.destination)return;const k=m.source.index,q=m.destination.index;if(k===q)return;const A=[...o].sort((D,H)=>D.signing_order-H.signing_order),[ee]=A.splice(k,1);A.splice(q,0,ee),g(A.map((D,H)=>({...D,signing_order:H+1})))}
130,[o]),j=(m,k)=>{const q=p.find(A=>A.id===k);q&&g(o.map(A=>A.id===m?{...A,profile_id:k,signer_name:q.full_name,signer_email:q.email,signer_title:q.title||""}:A))},M=m=>{h([...f,{id:crypto.randomUUID(),name:"",email:""}])},W=(m,k,q)=>{h(f.map(A=>A.id===m?{...A,[k]:q}:A))},K=(m,k)=>{const q=p.find(A=>A.id===k);q&&h(f.map(A=>A.id===m?{...A,profile_id:k,name:q.full_name,email:q.email}:A))},T=m=>{h(f.filter(k=>k.id!==m))},L=async()=>{if(t){i(!0);try{const{error:m}=await b.from("signing_workflow_settings").upsert({tenant_id:t.id,default_signers:o,cc_recipients:f,require_internal_approval:l,send_executed_copy:w,updated_at:new Date().toISOString()},{onConflict:"tenant_id"});if(m)throw m;s({title:"Signing workflow settings saved"})}catch(m){s({title:"Error saving settings",description:m.message,variant:"destructive"})}finally{i(!1)}}};return r?e.jsx(R,{children:e.jsx(O,{className:"py-12 flex justify-center",children:e.jsx(E,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):e.jsxs(R,{children:[e.jsxs(J,{children:[e.jsxs(Z,{className:"flex items-center gap-2",children:[e.jsx(Tt,{className:"h-5 w-5"}),"Signing Workflow"]}),e.jsx(ae,{children:"Configure default signers and approval workflow for proposals"})]}),e.jsxs(O,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Require Internal Approval"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Proposals must be signed internally before sending to client"})]}),e.jsx(ye,{checked:l,onCheckedChange:x})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Send Executed Copy"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Email the signed PDF to all parties once fully executed"})]}),e.jsx(ye,{checked:w,onCheckedChange:v})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(B,{className:"text-base font-medium",children:"Default Signing Order"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(y,{variant:"outline",size:"sm",onClick:()=>_("internal"),children:[e.jsx(Be,{className:"h-4 w-4 mr-1"}),"Add Internal"]}),e.jsxs(y,{variant:"outline",size:"sm",onClick:()=>_("client"),children:[e.jsx(We,{className:"h-4 w-4 mr-1"}),"Add Client"]})]})]}),o.length===0?e.jsxs("div",{className:"text-center py-8 border border-dashed rounded-lg",children:[e.jsx(Tt,{className:"h-8 w-8 text-muted-foreground/30 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No default signers configured. Add internal approvers or client signatories."})]}):e.jsx(qa,{onDragEnd:a,children:e.jsx(Ma,{droppableId:"signers",children:m=>e.jsxs("div",{className:"space-y-2",ref:m.innerRef,...m.droppableProps,children:[o.sort((k,q)=>k.signing_order-q.signing_order).map((k,q)=>e.jsx(Ra,{draggableId:k.id,index:q,children:(A,ee)=>e.jsxs("div",{ref:A.innerRef,...A.draggableProps,className:`flex items-center gap-3 p-3 bg-muted/50 rounded-lg border ${ee.isDragging?"shadow-lg ring-2 ring-primary/20":""}`,children:[e.jsx("div",{...A.dragHandleProps,children:e.jsx(Oa,{className:"h-4 w-4 text-muted-foreground cursor-grab"})}),e.jsx("div",{className:"h-8 w-8 rounded-full bg-primary/10 flex items-center justify-center text-sm font-bold text-primary",children:q+1}),e.jsxs(U,{variant:k.signer_type==="internal"?"secondary":"outline",className:"shrink-0",children:[k.signer_type==="internal"?e.jsx(Be,{className:"h-3 w-3 mr-1"}):e.jsx(We,{className:"h-3 w-3 mr-1"}),k.signer_type==="internal"?"Internal":"Client"]}),k.signer_type==="internal"?e.jsxs(ie,{value:k.profile_id||"",onValueChange:D=>j(k.id,D),children:[e.jsx(ce,{className:"w-[200px]",children:e.jsx(le,{placeholder:"Select team member"})}),e.jsx(oe,{children:p.map(D=>e.jsx(V,{value:D.id,children:D.full_name},D.id))})]}):e.jsx("span",{className:"text-sm text-muted-foreground italic",children:"Uses client signatory from proposal"}),e.jsx("div",{className:"flex-1"}),e.jsxs(ie,{value:k.signer_role,onValueChange:D=>P(k.id,"signer_role",D),children:[e.jsx(ce,{className:"w-[120px]",children:e.jsx(le,{})}),e.jsxs(oe,{children:[e.jsx(V,{value:"signer",children:"Signer"}),e.jsx(V,{value:"reviewer",children:"Reviewer"}),e.jsx(V,{value:"approver",children:"Approver"})]})]}),e.jsx(y,{variant:"ghost",size:"icon",onClick:()=>G(k.id),className:"text-destructive hover:text-destructive","aria-label":"Delete",children:e.jsx(Le,{className:"h-4 w-4"})})]})},k.id)),m.placeholder]})})})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(B,{className:"text-base font-medium",children:"CC Recipients"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"These people will receive a copy of the signed agreement"})]}),e.jsxs(y,{variant:"outline",size:"sm",onClick:()=>M(),children:[e.jsx(Je,{className:"h-4 w-4 mr-1"}),"Add CC"]})]}),f.length===0?e.jsxs("div",{className:"text-center py-6 border border-dashed rounded-lg",children:[e.jsx(Xe,{className:"h-6 w-6 text-muted-foreground
130/30 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No CC recipients configured"})]}):e.jsx("div",{className:"space-y-2",children:f.map(m=>e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted/30 rounded-lg border",children:[e.jsxs(U,{variant:"outline",className:"shrink-0",children:[e.jsx(Xe,{className:"h-3 w-3 mr-1"}),"CC"]}),e.jsxs(ie,{value:m.profile_id||"manual",onValueChange:k=>{k==="manual"?(W(m.id,"profile_id",""),W(m.id,"name",""),W(m.id,"email","")):K(m.id,k)},children:[e.jsx(ce,{className:"w-[200px]",children:e.jsx(le,{placeholder:"Select or enter manually"})}),e.jsxs(oe,{children:[e.jsx(V,{value:"manual",children:e.jsx("span",{className:"text-muted-foreground",children:"Enter manually..."})}),p.map(k=>e.jsx(V,{value:k.id,children:k.full_name},k.id))]})]}),!m.profile_id&&e.jsxs(e.Fragment,{children:[e.jsx(se,{placeholder:"Name",value:m.name,onChange:k=>W(m.id,"name",k.target.value),className:"w-[150px]"}),e.jsx(se,{placeholder:"Email",type:"email",value:m.email,onChange:k=>W(m.id,"email",k.target.value),className:"w-[200px]"})]}),m.profile_id&&e.jsx("span",{className:"text-sm text-muted-foreground",children:m.email}),e.jsx("div",{className:"flex-1"}),e.jsx(y,{variant:"ghost",size:"icon",onClick:()=>T(m.id),className:"text-destructive hover:text-destructive","aria-label":"Delete",children:e.jsx(Le,{className:"h-4 w-4"})})]},m.id))})]}),e.jsxs(y,{onClick:L,disabled:c,children:[c&&e.jsx(E,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Workflow Settings"]})]})]})}function Xn(){const{currentTenant:s}=ne(),{toast:t}=re(),[r,d]=n.useState(!1),[c,i]=n.useState(!1),[o,g]=n.useState(""),[f,h]=n.useState("");n.useEffect(()=>{s?.id&&p()},[s?.id]);const p=async()=>{if(s?.id){d(!0);try{const{data:l,error:x}=await b.from("tenants").select("target_margin_percent, margin_alert_threshold").eq("id",s.id).single();if(x)throw x;g(l?.target_margin_percent?.toString()||"35"),h(l?.margin_alert_threshold?.toString()||"10")}catch(l){console.error("Failed to load margin settings:",l)}finally{d(!1)}}},u=async()=>{if(s?.id){i(!0);try{const{error:l}=await b.from("tenants").update({target_margin_percent:parseFloat(o)||35,margin_alert_threshold:parseFloat(f)||10}).eq("id",s.id);if(l)throw l;t({title:"Settings saved",description:"Organization margin settings have been updated."})}catch(l){console.error("Failed to save margin settings:",l),t({title:"Save failed",description:l.message,variant:"destructive"})}finally{i(!1)}}};return r?e.jsx(R,{children:e.jsx(O,{className:"flex items-center justify-center py-8",children:e.jsx(E,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):e.jsxs(R,{children:[e.jsxs(J,{children:[e.jsxs(Z,{className:"flex items-center gap-2",children:[e.jsx(za,{className:"h-5 w-5"}),"Profitability Settings"]}),e.jsx(ae,{children:"Configure default target margins and alert thresholds for your organization"})]}),e.jsxs(O,{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{htmlFor:"targetMargin",children:"Default Target Margin (%)"}),e.jsx(se,{id:"targetMargin",type:"number",min:"0",max:"100",step:"1",value:o,onChange:l=>g(l.target.value),placeholder:"35"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This is the default margin target for projects unless overridden at project or practice level"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{htmlFor:"alertThreshold",children:"Alert Threshold (%)"}),e.jsxs("div",{className:"relative",children:[e.jsx(se,{id:"alertThreshold",type:"number",min:"0",max:"50",step:"1",value:f,onChange:l=>h(l.target.value),placeholder:"10",className:"pr-10"}),e.jsx(De,{className:"absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Notify managers when a project margin falls more than this percentage below target"})]})]}),e.jsxs("div",{className:"p-4 rounded-lg bg-muted/50 border border-border",children:[e.jsx("h4",{className:"text-sm font-medium mb-2",children:"Margin Hierarchy"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Margin targets cascade: ",e.jsx("strong",{children:"Project"})," â ",e.jsx("strong",{children:"Practice"})," â ",e.jsx("strong",{children:"Organization"}),". If a project has no target set, it inherits from its practice. If the practice has no target, the organization default is used."]})]}
130),e.jsxs(y,{onClick:u,disabled:c,children:[c&&e.jsx(E,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Settings"]})]})]})}const er=new Set(["gmail.com","yahoo.com","hotmail.com","outlook.com","aol.com","icloud.com","proton.me","protonmail.com","live.com","msn.com"]);function sr(){const{currentTenant:s}=ne(),{toast:t}=re(),r=He(),[d,c]=n.useState(""),i=s?.id,{data:o,isLoading:g}=Oe({queryKey:["tenant-domains",i],enabled:!!i,queryFn:async()=>{const{data:v,error:N}=await b.from("tenant_domains").select("*").eq("tenant_id",i).order("created_at");if(N)throw N;return v}}),{data:f,isLoading:h}=Oe({queryKey:["tenant-join-requests",i],enabled:!!i,queryFn:async()=>{const{data:v,error:N}=await b.from("tenant_join_requests").select("*").eq("tenant_id",i).eq("status","pending").order("requested_at",{ascending:!1});if(N)throw N;return v}}),p=we({mutationFn:async v=>{const{error:N}=await b.from("tenant_domains").insert({tenant_id:i,domain:v.toLowerCase()});if(N)throw N},onSuccess:()=>{c(""),r.invalidateQueries({queryKey:["tenant-domains",i]}),t({title:"Domain added",description:"New signups with this email domain can now request to join."})},onError:v=>{t({title:"Failed to add domain",description:v.message,variant:"destructive"})}}),u=we({mutationFn:async v=>{const{error:N}=await b.from("tenant_domains").delete().eq("id",v);if(N)throw N},onSuccess:()=>r.invalidateQueries({queryKey:["tenant-domains",i]}),onError:v=>{t({title:"Failed to remove domain",description:v.message,variant:"destructive"})}}),l=we({mutationFn:async({id:v,autoJoin:N})=>{const{error:S}=await b.from("tenant_domains").update({auto_join:N}).eq("id",v);if(S)throw S},onSuccess:()=>r.invalidateQueries({queryKey:["tenant-domains",i]}),onError:v=>{t({title:"Failed to update domain",description:v.message,variant:"destructive"})}}),x=we({mutationFn:async({requestId:v,approve:N})=>{const{error:S}=await b.rpc("resolve_tenant_join_request",{_request_id:v,_approve:N});if(S)throw S;return N},onSuccess:v=>{r.invalidateQueries({queryKey:["tenant-join-requests",i]}),t({title:v?"Request approved":"Request rejected",description:v?"The user has been added to your organization.":"The request has been rejected."})},onError:v=>{t({title:"Failed to resolve request",description:v.message,variant:"destructive"})}}),w=()=>{const v=d.trim().toLowerCase().replace(/^@/,"");if(!v||!/^[a-z0-9.-]+\.[a-z]{2,}$/.test(v)){t({title:"Invalid domain",description:"Enter a valid domain like acme.com",variant:"destructive"});return}if(er.has(v)){t({title:"Personal email domain",description:"Free email providers cannot be claimed as organization domains.",variant:"destructive"});return}p.mutate(v)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(R,{children:[e.jsxs(J,{children:[e.jsxs(Z,{className:"flex items-center gap-2",children:[e.jsx(hs,{className:"h-5 w-5"}),"Email Domains"]}),e.jsx(ae,{children:"Claim your company email domains so new teammates who sign up are routed to this organization instead of getting their own workspace. Enable auto-join to add them automatically, or leave it off to approve each request."})]}),e.jsxs(O,{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(se,{placeholder:"acme.com",value:d,onChange:v=>c(v.target.value),onKeyDown:v=>v.key==="Enter"&&w()}),e.jsx(y,{onClick:w,disabled:p.isPending,children:p.isPending?e.jsx(E,{className:"h-4 w-4 animate-spin"}):"Add Domain"})]}),g?e.jsx("div",{className:"flex justify-center py-4",children:e.jsx(E,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):(o||[]).length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-2",children:"No domains claimed yet. New signups from your company will create separate workspaces."}):e.jsx("div",{className:"space-y-2",children:(o||[]).map(v=>e.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("span",{className:"font-medium",children:["@",v.domain]})}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Auto-join"}),e.jsx(ye,{checked:v.auto_join,onCheckedChange:N=>l.mutate({id:v.id,autoJoin:N}),"aria-label":`Auto-join for ${v.domain}`})]}),e.jsx(y,{variant:"ghost",size:"icon",onClick:()=>u.mutate(v.id),"aria-label":`Remove ${v.domain}`,children:e.jsx(Le,{className:"h-4 w-4 text-muted-foreground"})})]})]},v.id))})]})]}),e.jsxs(R,{children:[e.jsxs(J,{children:[e.jsxs(Z,{className:"flex items-center gap-2",children:[e.jsx(Ba,{className:"h-5 w-5"}),"Join Requests",(f||[]).length>0&&e.jsx(U,{variant:"secondary",children:(f||[]).length})]}),e.jsx(ae,{children:"People who signed up with one of your claimed domains and are waiting for approval."})]}),e.jsx(O,{children:h?e.jsx("div",{className:"flex justify-center py-4",children:e.jsx(E,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):(f||[]).length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-2",children:"No pending join requests."}):e.jsx("div",{className:"space-y-2",children:(f||[]).map(v=>e.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:v.full_name||v.email}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[v.email," · requested ",es(new Date(v.requested_at),{addSuffix:!0})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(y,{size:"sm",onClick:()=>x.mutate({requestId:v.id,approve:!0}),disabled:x.isPending,children:[e.jsx(Ce,{className:"h-4 w-4 mr-1"}),"Approve"]}),e.jsxs(y,{size:"sm",variant:"outline",onClick:()=>x.mutate({requestId:v.id,approve:!1}),disabled:x.isPending,children:[e.jsx($t,{className:"h-4 w-4 mr-1"}),"Reject"]})]})]},v.id))})})]})]})}function tr(){const{isLoading:s,isConnected:t,isExpired:r,hasTenantServiceAccount:d,connectGoogle:c,isConnecting:i}=sa();if(s||d||t&&!r)return null;const o=t&&r;return e.jsxs(qe.div,{initial:{opacity:0,y:6}
130,animate:{opacity:1,y:0},className:"mx-4 mb-4 rounded-lg border border-primary/20 bg-primary/5 p-3 flex items-center gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-md bg-primary/10 flex items-center justify-center shrink-0",children:o?e.jsx(pe,{className:"h-4 w-4 text-primary"}):e.jsx(Ws,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium leading-tight",children:o?"Your Google calendar connection expired":"Connect your Google calendar"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-2",children:o?"Reconnect to keep syncing your personal events to My Day and Meeting Briefs.":"This workspace uses per-user OAuth, so connect your Google account to show your personal events in My Day and Meeting Briefs."})]}),e.jsxs(y,{size:"sm",onClick:()=>c(void 0),disabled:i,className:"shrink-0",children:[i?e.jsx(E,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(ss,{className:"h-3.5 w-3.5 mr-1.5"}),o?"Reconnect":"Connect"]})]})}function ar({open:s,onOpenChange:t,channels:r,loading:d,onSelectChannel:c,selectable:i=!1}){const[o,g]=n.useState(""),f=r.filter(u=>u.name.toLowerCase().includes(o.toLowerCase())||u.topic?.toLowerCase().includes(o.toLowerCase())||u.purpose?.toLowerCase().includes(o.toLowerCase())),h=f.filter(u=>!u.is_archived),p=f.filter(u=>u.is_archived);return e.jsx(_e,{open:s,onOpenChange:t,children:e.jsxs(Se,{className:"max-w-lg",children:[e.jsxs(ke,{children:[e.jsxs(Ae,{className:"flex items-center gap-2",children:[e.jsx(Re,{className:"h-5 w-5"}),"Slack Channels"]}),e.jsx(Ee,{children:i?"Select a channel to use":`Found ${r.length} channels in your workspace`})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(et,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(se,{placeholder:"Search channels...",value:o,onChange:u=>g(u.target.value),className:"pl-9"})]}),d?e.jsxs("div",{className:"flex items-center justify-center py-8",children:[e.jsx(E,{className:"h-6 w-6 animate-spin text-muted-foreground"}),e.jsx("span",{className:"ml-2 text-muted-foreground",children:"Loading channels..."})]}):e.jsx(Ds,{className:"h-[300px]",children:e.jsx("div",{className:"space-y-1",children:h.length===0&&p.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No channels found"}):e.jsxs(e.Fragment,{children:[h.map(u=>e.jsx(Ut,{channel:u,selectable:i,onSelect:c},u.id)),p.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"pt-4 pb-2",children:e.jsx("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Archived"})}),p.map(u=>e.jsx(Ut,{channel:u,selectable:!1,onSelect:c},u.id))]})]})})})]})]})})}function Ut({channel:s,selectable:t,onSelect:r}){return e.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-md ${t&&!s.is_archived?"cursor-pointer hover:bg-muted":s.is_archived?"opacity-50":""}`,onClick:()=>{t&&!s.is_archived&&r&&r(s)},children:[e.jsx("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:s.is_private?e.jsx(Ps,{className:"h-4 w-4"}):e.jsx(Re,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium truncate",children:s.name}),s.is_archived&&e.jsx(U,{variant:"secondary",className:"text-xs",children:"Archived"})]}),(s.purpose||s.topic)&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:s.purpose||s.topic})]}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Be,{className:"h-3 w-3"}),s.member_count]})]})}function nr({open:s,onOpenChange:t,channels:r,channelsLoading:d}){const{currentTenant:c}=ne(),{toast:i}=re(),[o,g]=n.useState(""),[f,h]=n.useState("ð Hello from CommandOS! This is a test message to verify Slack integration is working."),[p,u]=n.useState(!1),l=r.filter(w=>!w.is_archived),x=async()=>{if(!(!c||!o||!f.trim())){u(!0);try{const{data:w,error:v}=await b.functions.invoke("slack-send-message",{body:{tenant_id:c.id,channel_id:o,text:f.trim()}});if(v)throw v;if(w.error)throw new Error(w.error);const N=l.find(S=>S.id===o)?.name;i({title:"Message sent!",description:`Successfully posted to #${N}`}),t(!1),g(""),h("ð Hello from CommandOS! This is a test message to verify Slack integration is working.")}catch(w){console.error("Failed to send message:",w),i({title:"Failed to send message",description:w.message||"Please check the Slack integration settings",variant:"destructive"})}finally{u(!1)}}};return e.jsx(_e,{open:s,onOpenChange:t,children:e.jsxs(Se,{className:"max-w-md",children:[e.jsxs(ke,{children:[e.jsxs(Ae,{className:"flex items-center gap-2",children:[e.jsx(ta,{className:"h-5 w-5"}),"Send Test Message"]}),e.jsx(Ee,{children:"Send a test message to verify your Slack integration is working"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{htmlFor:"channel",children:"Channel"}),d?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-2",children:[e.jsx(E,{className:"h-4 w-4 animate-spin"}),"Loading channels..."]}):e.jsxs(ie,{value:o,onValueChange:g,children:[e.jsx(ce,{children:e.jsx(le,{placeholder:"Select a channel"})}),e.jsx(oe,{children:l.map(w=>e.jsx(V,{value:w.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Re,{className:"h-3 w-3"}),w.name]})},w.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{htmlFor:"message",children:"Message"}),e.jsx(As,{id:"message",value:f,onChange:w=>h(w.target.value),placeholder:"Enter your message...",rows:3})]})]}),e.jsxs(Ue,{children:[e.jsx(y,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(y,{onClick:x,disabled:!o||!f.trim()||p,children:p?e.jsxs(e.Fragment,{children:[e.jsx(E,{className:"h-4 w-4 animate-spin mr-2"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(wa,{className:"h-4 w-4 mr-2"}),"Send Message"]})})]})]})})}const Gs=[{id:"load",title:"Load Channels"},{id:"map",title:"Map Channels"},{id:"confirm",title:"Confirm & Save"}],Wt={client:{label:"Client",icon:We,color:"text-info-soft-foreground bg-info-soft"},internal:{label:"Internal",icon:Be,color:"text-warning-soft-foreground bg-warning-soft"}
130,personal:{label:"Personal",icon:$a,color:"text-accent-purple-soft-foreground bg-accent-purple-soft"},ignore:{label:"Ignore",icon:Qs,color:"text-muted-foreground bg-muted"}};function rr({open:s,onOpenChange:t,onSuccess:r}){const{currentTenant:d}=ne(),{toast:c}=re(),[i,o]=n.useState(0),[g,f]=n.useState([]),[h,p]=n.useState([]),[u,l]=n.useState({}),[x,w]=n.useState(!1),[v,N]=n.useState(!1),[S,_]=n.useState(""),P=(i+1)/Gs.length*100;n.useEffect(()=>{s||(o(0),f([]),l({}),_(""))},[s]);const G=n.useCallback(async()=>{if(d){w(!0);try{const[T,L,m]=await Promise.all([b.functions.invoke("slack-list-channels",{body:{tenant_id:d.id}}),b.from("clients").select("id, name").eq("tenant_id",d.id).order("name"),b.from("slack_channel_mappings").select("*").eq("tenant_id",d.id)]);if(T.error)throw new Error(T.error.message);if(T.data?.error)throw new Error(T.data.error);const k=(T.data?.channels||[]).filter(A=>!A.is_archived);f(k),p(L.data||[]);const q={};if(m.data)for(const A of m.data)q[A.slack_channel_id]={slack_channel_id:A.slack_channel_id,slack_channel_name:A.slack_channel_name,category:A.category,client_id:A.client_id};for(const A of k)q[A.id]||(q[A.id]={slack_channel_id:A.id,slack_channel_name:A.name,category:"ignore",client_id:null});l(q),o(1)}catch(T){c({title:"Failed to load channels",description:T.message,variant:"destructive"})}finally{w(!1)}}},[d,c]),a=(T,L,m)=>{l(k=>({...k,[T]:{...k[T],category:L,client_id:L==="client"?m??k[T]?.client_id??null:null}}))},j=async()=>{if(d){N(!0);try{const T=Object.values(u).filter(q=>q.category!=="ignore"),L=Object.values(u),{data:m,error:k}=await b.functions.invoke("slack-save-channel-mappings",{body:{tenant_id:d.id,mappings:L}});if(k)throw new Error(k.message);if(m?.error)throw new Error(m.error);c({title:"Channel mappings saved!",description:`${m.saved_count} channels mapped.`}),r?.(),t(!1)}catch(T){c({title:"Failed to save mappings",description:T.message,variant:"destructive"})}finally{N(!1)}}},M=g.filter(T=>T.name.toLowerCase().includes(S.toLowerCase())||T.purpose?.toLowerCase().includes(S.toLowerCase())),W=Object.values(u).reduce((T,L)=>(T[L.category]=(T[L.category]||0)+1,T),{}),K=()=>{switch(i){case 0:return e.jsx("div",{className:"flex flex-col items-center justify-center py-12 space-y-4",children:x?e.jsxs(e.Fragment,{children:[e.jsx(E,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading channels & clients..."})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-muted flex items-center justify-center",children:e.jsx(Re,{className:"h-8 w-8 text-muted-foreground"})}),e.jsxs("div",{className:"text-center space-y-1",children:[e.jsx("h4",{className:"font-medium",children:"Map Slack Channels to Clients"}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-sm",children:"Categorize your channels as Client, Internal, Personal, or Ignore. Client channels will be linked to projects for AI extraction."})]}),e.jsxs(y,{onClick:G,size:"lg",children:["Load Channels",e.jsx(Ls,{className:"ml-2 h-4 w-4"})]})]})});case 1:return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(et,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(se,{placeholder:"Search channels...",value:S,onChange:T=>_(T.target.value),className:"pl-9"})]}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:Object.entries(Wt).map(([T,L])=>e.jsxs(U,{variant:"secondary",className:`text-xs ${L.color}`,children:[L.label,": ",W[T]||0]},T))}),e.jsx(Ds,{className:"h-[340px]",children:e.jsx("div",{className:"space-y-1.5 pr-2",children:M.map(T=>{const L=u[T.id];return e.jsxs("div",{className:"flex items-center gap-2 p-2.5 rounded-lg border bg-card hover:bg-muted/50 transition-colors",children:[e.jsx("div",{className:"flex items-center gap-1.5 text-muted-foreground shrink-0",children:T.is_private?e.jsx(Ps,{className:"h-3.5 w-3.5"}):e.jsx(Re,{className:"h-3.5 w-3.5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm font-medium truncate block",children:T.name}),T.purpose&&e.jsx("span",{className:"text-xs text-muted-foreground truncate block",children:T.purpose})]}),e.jsxs(ie,{value:L?.category||"ignore",onValueChange:m=>a(T.id,m),children:[e.jsx(ce,{className:"w-[110px] h-8 text-xs",children:e.jsx(le,{})}),e.jsxs(oe,{children:[e.jsx(V,{value:"client",children:"ð¢ Client"}),e.jsx(V,{value:"internal",children:"ð¥ Internal"}),e.jsx(V,{value:"personal",children:"ð¤ Personal"}),e.jsx(V,{value:"ignore",children:"ð« Ignore"})]})]}),L?.category==="client"&&e.jsxs(ie,{value:L.client_id||"",onValueChange:m=>a(T.id,"client",m||null),children:[e.jsx(ce,{className:"w-[140px] h-8 text-xs",children:e.jsx(le,{placeholder:"Select client"})}),e.jsx(oe,{children:h.map(m=>e.jsx(V,{value:m.id,children:m.name},m.id))})]})]},T.id)})})})]});case 2:return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(he,{className:"h-10 w-10 text-success mx-auto"}),e.jsx("h4",{className:"font-medium",children:"Ready to Save"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Review your channel mapping summary below."})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:Object.entries(Wt).map(([T,
130L])=>{const m=W[T]||0,k=L.icon;return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-card",children:[e.jsx("div",{className:`p-2 rounded-md ${L.color}`,children:e.jsx(k,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:L.label}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[m," channels"]})]})]},T)})}),(W.client||0)>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h5",{className:"text-sm font-medium",children:"Client Channel Mappings"}),e.jsx("div",{className:"space-y-1",children:Object.values(u).filter(T=>T.category==="client").map(T=>{const L=h.find(m=>m.id===T.client_id);return e.jsxs("div",{className:"flex items-center justify-between text-sm p-2 rounded bg-muted/50",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Re,{className:"h-3.5 w-3.5 text-muted-foreground"}),T.slack_channel_name]}),e.jsxs("span",{className:"text-muted-foreground",children:["â ",L?.name||"No client selected"]})]},T.slack_channel_id)})})]}),e.jsx(y,{onClick:j,disabled:v,className:"w-full",size:"lg",children:v?e.jsxs(e.Fragment,{children:[e.jsx(E,{className:"mr-2 h-4 w-4 animate-spin"}),"Saving..."]}):"Save Mappings"})]})}};return e.jsx(_e,{open:s,onOpenChange:t,children:e.jsxs(Se,{className:"sm:max-w-2xl",children:[e.jsxs(ke,{children:[e.jsxs(Ae,{className:"flex items-center gap-2",children:[e.jsx(Re,{className:"h-5 w-5"}),"Channel Mapping Wizard"]}),e.jsx(Ee,{children:Gs[i].title})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ys,{value:P,className:"h-1"}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Step ",i+1," of ",Gs.length]}),e.jsx("span",{children:Gs[i].title})]})]}),e.jsx(Zs,{mode:"wait",children:e.jsx(qe.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.2},className:"min-h-[300px]",children:K()},i)}),i>0&&i<2&&e.jsxs("div",{className:"flex justify-between pt-2 border-t",children:[e.jsxs(y,{variant:"ghost",onClick:()=>o(T=>T-1),children:[e.jsx(Es,{className:"mr-2 h-4 w-4"}),"Back"]}),e.jsxs(y,{onClick:()=>o(T=>T+1),children:["Next",e.jsx(Ls,{className:"ml-2 h-4 w-4"})]})]}),i===2&&e.jsx("div",{className:"flex justify-start pt-2 border-t",children:e.jsxs(y,{variant:"ghost",onClick:()=>o(1),children:[e.jsx(Es,{className:"mr-2 h-4 w-4"}),"Back to Mapping"]})})]})})}function ir({open:s,onOpenChange:t,channels:r,channelsLoading:d,onSuccess:c}){const{currentTenant:i}=ne(),{toast:o}=re(),[g,f]=n.useState(""),[h,p]=n.useState(""),[u,l]=n.useState(""),[x,w]=n.useState([]),[v,N]=n.useState([]),[S,_]=n.useState([]),[P,G]=n.useState(!1),[a,j]=n.useState(!1);n.useEffect(()=>{s&&i&&M()},[s,i]),n.useEffect(()=>{h&&i?W(h):(N([]),l(""))},[h,i]);const M=async()=>{if(i){G(!0);try{const{data:L}=await b.from("clients").select("id, name").eq("tenant_id",i.id).order("name");w(L||[]);const{data:m}=await b.from("project_slack_channels").select("slack_channel_id").eq("tenant_id",i.id);_((m||[]).map(k=>k.slack_channel_id))}catch(L){console.error("Error fetching data:",L)}finally{G(!1)}}},W=async L=>{if(i)try{const{data:m}=await b.from("projects").select("id, name, client_id").eq("tenant_id",i.id).eq("client_id",L).order("name");N(m||[])}catch(m){console.error("Error fetching projects:",m)}},K=async()=>{if(!i||!g||!h)return;const L=r.find(m=>m.id===g);if(L){j(!0);try{const{error:m}=await b.from("project_slack_channels").insert({tenant_id:i.id,slack_channel_id:L.id,slack_channel_name:L.name,client_id:h,project_id:u||null});if(m)throw m;o({title:"Channel linked",description:`#${L.name} is now linked for customer intelligence.`}),f(""),p(""),l(""),t(!1),c()}catch(m){console.error("Error linking channel:",m),o({title:"Failed to link channel",description:m instanceof Error?m.message:"An error occurred",variant:"destructive"})}finally{j(!1)}}},T=r.filter(L=>!S.includes(L.id));return e.jsx(_e,{open:s,onOpenChange:t,children:e.jsxs(Se,{className:"sm:max-w-[425px]",children:[e.jsxs(ke,{children:[e.jsxs(Ae,{className:"flex items-center gap-2",children:[e.jsx(Re,{className:"h-5 w-5"}),"Link Slack Channel"]}),e.jsx(Ee,{children:"Associate a Slack channel with a client to enable customer intelligence analysis."})]}),P||d?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(E,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"grid gap-4 py-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx(B,{htmlFor:"channel",children:"Slack Channel"}),e.jsxs(ie,{value:g,onValueChange:f,children:[e.jsx(ce,{id:"channel",children:e.jsx(le,{placeholder:"Select a channel"})}),e.jsx(oe,{children:T.length===0?e.jsx("div",{className:"px-2 py-4 text-sm text-muted-foreground text-center",children:"No available channels to link"}):T.map(L=>e.jsx(V,{value:L.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Re,{className:"h-4 w-4 text-muted-foreground"}),L.name,L.is_private&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(private)"})]})},L.id))})]})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(B,{htmlFor:"client",children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(We,{className:"h-4 w-4"}),"Client"]})}),e.jsxs(ie,{value:h,onValueChange:p,children:[e.jsx(ce,{id:"client",children:e.jsx(le,{placeholder:"Select a client"})}),e.jsx(oe,{children:x.length===0?e.jsx("div",{className:"px-2 py-4 text-sm text-muted-foreground text-center",children:"No clients found"}):x.map(L=>e.jsx(V,{value:L.id,children:L.name},L.id))})]})]}),v.length>0&&e.jsxs("div",{className:"grid gap-2",children:[e.jsx(B,{htmlFor:"project",children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Ya,{className:"h-4 w-4"}),"Project (optional)"]})}),e.jsxs(ie,{value:u||"none",onValueChange:L=>l(L==="none"?"":L),children:[e.jsx(ce,{id:"project",children:e.jsx(le,{placeholder:"Select a project (optional)"})}),e.jsxs(oe,{children:[e.jsx(V,{value:"none",children:"No specific project"}),v.map(L=>e.jsx(V,{value:L.id,children:L.name},L.id))]})]})]})]}),e.jsxs(Ue,{children:[e.jsx(y,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(y,{onClick:K,disabled:!g||!h||a,children:a?e.jsxs(e.Fragment,{children:[e.jsx(E,{className:"h-4 w-4 animate-spin mr-2"}),"Linking..."]}):"Link Channel"})]})]})})}
130function cr(){const[s,t]=n.useState(!1),[r,d]=n.useState(null),[c,i]=n.useState(null),{toast:o}=re();return{syncNow:n.useCallback(async f=>{if(s)return o({title:"Sync already in progress",description:"Please wait for the current sync to complete.",variant:"default"}),null;t(!0);try{const{data:h,error:p}=await b.functions.invoke("sync-customer-intelligence",{body:{tenant_id:f}});if(p)throw new Error(p.message||"Failed to sync customer intelligence");if(!h.success&&h.error)throw new Error(h.error);const u={channels_processed:h.channels_processed||0,messages_ingested:h.messages_ingested||0,messages_analyzed:h.messages_analyzed||0,signals_detected:h.signals_detected||0,errors:h.errors};if(i(u),d(new Date().toISOString()),u.channels_processed===0&&!h.message)o({title:"No channels to sync",description:"Link Slack channels to clients first to enable intelligence sync.",variant:"default"});else if(h.message)o({title:"Sync completed",description:h.message});else{const l=[];u.channels_processed>0&&l.push(`${u.channels_processed} channel${u.channels_processed!==1?"s":""}`),u.messages_ingested>0&&l.push(`${u.messages_ingested} message${u.messages_ingested!==1?"s":""} ingested`),u.signals_detected>0&&l.push(`${u.signals_detected} signal${u.signals_detected!==1?"s":""} detected`),o({title:"Intelligence synced successfully",description:l.join(" ⢠")||"No new data found"})}return u}catch(h){return console.error("Customer intelligence sync error:",h),o({title:"Sync failed",description:h instanceof Error?h.message:"An unexpected error occurred",variant:"destructive"}),null}finally{t(!1)}},[s,o]),isSyncing:s,lastSynced:r,lastResult:c}}const lr=[{value:"inbound",label:"HubSpot â InCommand",icon:Xs,description:"Import only"},{value:"bidirectional",label:"Bidirectional",icon:In,description:"Two-way sync"},{value:"outbound",label:"InCommand â HubSpot",icon:Ja,description:"Export only"}],or=[{value:"all",label:"All time",description:"Import everything"},{value:"90days",label:"Last 90 days",description:"Recommended"},{value:"30days",label:"Last 30 days",description:"Recent only"},{value:"new_only",label:"New records only",description:"Going forward"}],dr=[{value:"lead",label:"Lead"},{value:"qualified",label:"Qualified"},{value:"proposal",label:"Proposal"},{value:"negotiation",label:"Negotiation"},{value:"won",label:"Won"},{value:"lost",label:"Lost"}];function mr(){const{currentTenant:s}=ne(),{toast:t}=re(),[r,d]=n.useState(null),[c,i]=n.useState([]),[o,g]=n.useState([]),[f,h]=n.useState(!0),[p,u]=n.useState(!1),[l,x]=n.useState(!1),[w,v]=n.useState(!1);n.useEffect(()=>{s&&N()},[s]);const N=async()=>{if(s){h(!0);try{const{data:a,error:j}=await b.from("crm_sync_settings").select("*").eq("tenant_id",s.id).eq("integration_type","hubspot").single();if(j&&j.code!=="PGRST116")throw j;a&&d({id:a.id,sync_clients:a.sync_clients??!0,sync_contacts:a.sync_contacts??!0,sync_prospects:a.sync_prospects??!0,sync_direction_companies:a.sync_direction_companies||"bidirectional",sync_direction_contacts:a.sync_direction_contacts||"bidirectional",sync_direction_deals:a.sync_direction_deals||"bidirectional",import_scope:a.import_scope||"90days",last_successful_sync:a.last_successful_sync});const{data:M}=await b.from("crm_sync_log").select("*").eq("tenant_id",s.id).eq("integration_type","hubspot").order("started_at",{ascending:!1}).limit(5);i(M||[]);const{data:W}=await b.from("hubspot_stage_mappings").select("*").eq("tenant_id",s.id).order("hubspot_stage_label",{ascending:!0});W&&W.length>0&&g(W.map(K=>({hubspot_stage:K.hubspot_stage,hubspot_stage_label:K.hubspot_stage_label||K.hubspot_stage,pipeline_label:"",incommand_stage:K.incommand_stage,is_mapped:!0})))}catch(a){console.error("Failed to load sync settings:",a)}finally{h(!1)}}},S=async()=>{if(!(!r||!s)){u(!0);try{const a=[];r.sync_clients&&a.push("companies"),r.sync_contacts&&a.push("contacts"),r.sync_prospects&&a.push("deals");const{error:j}=await b.from("crm_sync_settings").update({sync_clients:r.sync_clients,sync_contacts:r.sync_contacts,sync_prospects:r.sync_prospects,sync_objects:a,sync_direction_companies:r.sync_direction_companies,sync_direction_contacts:r.sync_direction_contacts,sync_direction_deals:r.sync_direction_deals,import_scope:r.import_scope}).eq("id",r.id);if(j)throw j;t({title:"Sync settings saved"})}catch(a){t({title:"Failed to save settings",description:a.message,variant:"destructive"})}finally{u(!1)}}},_=async()=>
130{if(s){x(!0);try{const{data:a,error:j}=await b.functions.invoke("hubspot-sync",{body:{tenant_id:s.id,sync_type:"full"}});if(j)throw j;a?.error?t({title:"Sync failed",description:a.error,variant:"destructive"}):(t({title:"Sync complete",description:`${a.records_created||0} created, ${a.records_updated||0} updated`}),N())}catch(a){t({title:"Sync failed",description:a.message,variant:"destructive"})}finally{x(!1)}}},P=async()=>{if(s){v(!0);try{const{data:a,error:j}=await b.functions.invoke("hubspot-integration-setup",{body:{action:"fetch_pipeline_stages",tenant_id:s.id}});if(j)throw j;a?.error?t({title:"Failed to fetch stages",description:a.error,variant:"destructive"}):a?.stages&&(g(a.stages),t({title:"Pipeline stages loaded",description:`${a.stages.length} stages found`}))}catch(a){t({title:"Failed to fetch stages",description:a.message,variant:"destructive"})}finally{v(!1)}}},G=async(a,j)=>{if(s){g(M=>M.map(W=>W.hubspot_stage===a?{...W,incommand_stage:j,is_mapped:!0}:W));try{const{error:M}=await b.from("hubspot_stage_mappings").upsert({tenant_id:s.id,hubspot_stage:a,hubspot_stage_label:o.find(W=>W.hubspot_stage===a)?.hubspot_stage_label||a,incommand_stage:j},{onConflict:"tenant_id,hubspot_stage"});if(M)throw M}catch(M){t({title:"Failed to save mapping",description:M.message,variant:"destructive"})}}};return f?e.jsx(R,{children:e.jsx(O,{className:"flex justify-center py-8",children:e.jsx(E,{className:"h-5 w-5 animate-spin text-muted-foreground"})})}):r?e.jsxs(R,{children:[e.jsxs(J,{children:[e.jsxs(Z,{className:"flex items-center gap-2 text-lg",children:[e.jsx("img",{src:"https://www.hubspot.com/favicon.ico",alt:"HubSpot",className:"w-5 h-5"}),"HubSpot Sync Configuration"]}),e.jsx(ae,{children:"Control what gets synced, in which direction, and how far back to import."})]}),e.jsxs(O,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(B,{className:"text-sm font-semibold",children:"Sync Objects"}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3 rounded-lg border p-3",children:[e.jsx(ms,{id:"sync-companies",checked:r.sync_clients,onCheckedChange:a=>d({...r,sync_clients:!!a})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(B,{htmlFor:"sync-companies",className:"font-medium cursor-pointer",children:"Companies"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"HubSpot Companies (Customers only) â Clients"})]}),r.sync_clients&&e.jsx(lt,{value:r.sync_direction_companies,onChange:a=>d({...r,sync_direction_companies:a})})]}),e.jsxs("div",{className:"flex items-center gap-3 rounded-lg border p-3",children:[e.jsx(ms,{id:"sync-contacts",checked:r.sync_contacts,onCheckedChange:a=>d({...r,sync_contacts:!!a})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(B,{htmlFor:"sync-contacts",className:"font-medium cursor-pointer",children:"Contacts"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"HubSpot Contacts (Customer companies only) â Client Contacts"})]}),r.sync_contacts&&e.jsx(lt,{value:r.sync_direction_contacts,onChange:a=>d({...r,sync_direction_contacts:a})})]}),e.jsxs("div",{className:"flex items-center gap-3 rounded-lg border p-3",children:[e.jsx(ms,{id:"sync-deals",checked:r.sync_prospects,onCheckedChange:a=>d({...r,sync_prospects:!!a})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(B,{htmlFor:"sync-deals",className:"font-medium cursor-pointer",children:"Deals"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"HubSpot Deals â Prospects (closed-won auto-creates Clients)"})]}),r.sync_prospects&&e.jsx(lt,{value:r.sync_direction_deals,onChange:a=>d({...r,sync_direction_deals:a})})]})]})]}),e.jsx(me,{}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(B,{className:"text-sm font-semibold",children:"Import Scope"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Choose how far back to pull historical records from HubSpot."}),e.jsx(ht,{value:r.import_scope,onValueChange:a=>d({...r,import_scope:a}),className:"grid grid-cols-2 gap-2",children:or.map(a=>e.jsxs("label",{className:`flex items-center gap-2 rounded-lg border p-3 cursor-pointer transition-colors ${r.import_scope===a.value?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsx(xt,{value:a.value}),e.jsxs("div",{children:[e.jsx("span",{className:"text-sm font-medium",children:a.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:a.description})]})]},a.value))})]}),e.jsx(me,{}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(B,{className:"text-sm font-semibold",children:"Deal Stage Mapping"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Map HubSpot deal stages to InCommand pipeline stages."})]}),e.jsxs(y,{variant:"outline",size:"sm",onClick:P,disabled:w,children:[w?e.jsx(E,{className:"h-3.5 w-3.5 animate-spin mr-1.5"}):e.jsx(Ys,{className:"h-3.5 w-3.5 mr-1.5"}),w?"Fetching...":"Fetch Stages"]})]}),o.length>0?e.jsx("div",{className:"rounded-md border",children:e.jsxs(vt,{children:[e.jsx(wt,{children:e.jsxs(ps,{children:[e.jsx(Pe,{children:"HubSpot Stage"}),e.jsx(Pe,{children:"InCommand Stage"})]})}),e.jsx(Nt,{children:o.map(a=>e.jsxs(ps,{children:[e.jsx(Te,{children:e.jsxs("div",{children:[e.jsx("span",{className:"text-sm font-medium",children:a.hubspot_stage_label}),a.pipeline_label&&e.jsx("p",{className:"text-xs text-muted-foreground",children:a.pipeline_label})]})}),e.jsx(Te,{children:e.jsxs(ie,{value:a.incommand_stage,onValueChange:j=>G(a.hubspot_stage,j),children:[e.jsx(ce,{className:"w-[160px]",children:e.jsx(le,{})}),e.jsx(oe,{children:dr.map(j=>e.jsx(V,{value:j.value,children:j.label},j.value))})]})})]},a.hubspot_stage))})]})}):e.jsx("div",{className:"rounded-lg border border-dashed p-4 text-center",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:'No stage mappings configured. Click "Fetch Stages" to pull your HubSpot pipeline stages.'})})]}),e.jsx(me,{}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(y,{onClick:S,disabled:p,children:[p?e.jsx(E,{className:"h-4 w-4 animate-spin mr-2"}):null,p?"Saving...":"Save Settings"]}),e.jsxs(y,{variant:"outline",onClick:_,disabled:l,children:[l?e.jsx(E,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(ts,{className:"h-4 w-4 mr-2"}),l?"Syncing...":"Sync Now"]})]}),(r.last_successful_sync||c.length>0)&&e.jsxs(e.Fragment,{children:[e.jsx(me,{}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(B,{className:"text-sm font-semibold",children:"Recent Sync Activity"}),r.last_successful_sync&&e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Ge,{className:"h-3 w-3"}),"Last successful sync: ",new Date(r.last_successful_sync).toLocaleStr
130ing()]}),c.length>0&&e.jsx("div",{className:"space-y-1.5",children:c.map(a=>e.jsxs("div",{className:"flex items-center gap-2 text-xs rounded-md bg-muted/50 px-3 py-2",children:[a.status==="completed"?e.jsx(he,{className:"h-3.5 w-3.5 text-success shrink-0"}):a.status==="failed"?e.jsx(pe,{className:"h-3.5 w-3.5 text-destructive shrink-0"}):a.status==="running"?e.jsx(E,{className:"h-3.5 w-3.5 animate-spin text-primary shrink-0"}):e.jsx(pe,{className:"h-3.5 w-3.5 text-warning shrink-0"}),e.jsx("span",{className:"text-muted-foreground",children:new Date(a.started_at).toLocaleString()}),e.jsx(U,{variant:a.status==="completed"?"default":a.status==="failed"?"destructive":"secondary",className:"text-caption px-1.5 py-0",children:a.status}),a.records_created!=null&&e.jsxs("span",{className:"text-muted-foreground ml-auto",children:["+",a.records_created," created, ~",a.records_updated||0," updated",(a.records_failed||0)>0&&e.jsxs("span",{className:"text-destructive",children:[" · ",a.records_failed," failed"]})]})]},a.id))})]})]})]})]}):null}function lt({value:s,onChange:t}){return e.jsx("div",{className:"flex items-center gap-1",children:lr.map(r=>{const d=r.icon,c=r.value===s;return e.jsx("button",{type:"button",onClick:()=>t(r.value),className:`p-1.5 rounded-md transition-colors ${c?"bg-primary text-primary-foreground":"text-muted-foreground hover:bg-muted"}`,title:r.label,children:e.jsx(d,{className:"h-3.5 w-3.5"})},r.value)})})}function ha(s,t){const{toast:r}=re(),[d,c]=n.useState([]),[i,o]=n.useState(null),[g,f]=n.useState(!0),[h,p]=n.useState(!1),u=n.useCallback(async()=>{if(s)try{let N=b.from("crm_sync_log").select("*").eq("tenant_id",s).order("started_at",{ascending:!1}).limit(20);t&&(N=N.eq("integration_type",t));const{data:S,error:_}=await N;if(_)throw _;c(S||[])}catch(N){console.error("Failed to fetch sync logs:",N)}},[s,t]),l=n.useCallback(async()=>{if(!(!s||!t))try{const{data:N,error:S}=await b.from("crm_sync_settings").select("*").eq("tenant_id",s).eq("integration_type",t).single();if(S&&S.code!=="PGRST116")throw S;o(N||null)}catch(N){console.error("Failed to fetch sync settings:",N)}},[s,t]);return n.useEffect(()=>{s&&(async()=>{f(!0),await Promise.all([u(),l()]),f(!1)})()},[s,u,l]),{syncLogs:d,settings:i,isLoading:g,isSyncing:h,triggerSync:async N=>{if(s){p(!0);try{const{data:{session:S}}=await b.auth.getSession();if(!S)throw new Error("Not authenticated");const _=N==="salesforce"?"salesforce-sync":"hubspot-sync",{data:P,error:G}=await b.functions.invoke(_,{headers:{Authorization:`Bearer ${S.access_token}`},body:{tenant_id:s,sync_type:"full"}});if(G)throw G;r({title:"Sync started",description:`${N.charAt(0).toUpperCase()+N.slice(1)} sync is in progress.`}),setTimeout(u,2e3)}
130catch(S){console.error("Sync error:",S),r({title:"Sync failed",description:S.message||"Failed to start sync",variant:"destructive"})}finally{p(!1)}}},cancelRunningSyncs:async N=>{if(s)try{const{error:S}=await b.from("crm_sync_log").update({status:"failed",completed_at:new Date().toISOString(),error_details:{error:"Sync manually canceled after becoming stuck",canceled_at:new Date().toISOString(),canceled_reason:"Canceled from integration settings"}}).eq("tenant_id",s).eq("integration_type",N).in("status",["running","pending","in_progress","syncing"]);if(S)throw S;await u(),r({title:"Sync canceled",description:`${N.charAt(0).toUpperCase()+N.slice(1)} running syncs were stopped.`})}catch(S){console.error("Cancel sync error:",S),r({title:"Failed to cancel sync",description:S.message||"Could not cancel running syncs",variant:"destructive"})}},updateSettings:async N=>{if(!(!s||!t||!i))try{const S={...N,updated_at:new Date().toISOString()},{error:_}=await b.from("crm_sync_settings").update(S).eq("id",i.id);if(_)throw _;o({...i,...N}),r({title:"Settings updated"})}catch(S){r({title:"Failed to update settings",description:S.message,variant:"destructive"})}},refreshLogs:u}}function ur(){const{currentTenant:s}=ne(),{syncLogs:t,settings:r,isLoading:d,isSyncing:c,triggerSync:i,cancelRunningSyncs:o,updateSettings:g,refreshLogs:f}=ha(s?.id,"hubspot"),[h,p]=n.useState(!1),[u,l]=n.useState(!1),[x,w]=n.useState(!1);if(d)return e.jsx(R,{children:e.jsx(O,{className:"flex justify-center py-8",children:e.jsx(E,{className:"h-5 w-5 animate-spin text-muted-foreground"})})});const v=t[0],N=x?t:t.slice(0,5),S=t.some(j=>["running","pending","in_progress","syncing"].includes(j.status)),_=j=>{switch(j){case"completed":return e.jsx(he,{className:"h-4 w-4 text-success"});case"completed_with_errors":return e.jsx(De,{className:"h-4 w-4 text-warning"});case"failed":return e.jsx(qs,{className:"h-4 w-4 text-destructive"});case"running":return e.jsx(E,{className:"h-4 w-4 animate-spin text-primary"});default:return e.jsx(Ge,{className:"h-4 w-4 text-muted-foreground"})}},P=j=>{const M={completed:"bg-success/10 text-success border-success/20",completed_with_errors:"bg-warning/10 text-warning border-warning/20",failed:"bg-destructive/10 text-destructive border-destructive/20",running:"bg-primary/10 text-primary border-primary/20"};return e.jsxs(U,{variant:"outline",className:`text-xs ${M[j]||""}`,children:[_(j),e.jsx("span",{className:"ml-1 capitalize",children:j.replace(/_/g," ")})]})},G=j=>{const M=j.error_details;return M&&typeof M=="object"&&M.object_details?M.object_details:null},a=j=>{const M=j.error_details;return M?Array.isArray(M.errors)?M.errors:typeof M.error=="string"?[M.error]:[]:[]};return e.jsxs(R,{children:[e.jsx(J,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Z,{className:"flex items-center gap-2 text-lg",children:[e.jsx(bt,{className:"h-5 w-5"}),"HubSpot Sync Status"]}),e.jsx(ae,{children:"Monitor sync activity and trigger manual syncs"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&e.jsxs(y,{variant:r.is_enabled?"destructive":"outline",size:"sm",disabled:h,onClick:async()=>{p(!0),await g({is_enabled:!r.is_enabled}),p(!1)},children:[h?e.jsx(E,{className:"h-3.5 w-3.5 animate-spin mr-1.5"}):r.is_enabled?e.jsx(aa,{className:"h-3.5 w-3.5 mr-1.5"}):e.jsx(_t,{className:"h-3.5 w-3.5 mr-1.5"}),r.is_enabled?"Pause Sync":"Resume Sync"]}),e.jsxs(y,{variant:"outline",size:"sm",onClick:f,disabled:d,children:[e.jsx(ts,{className:"h-3.5 w-3.5 mr-1.5"}),"Refresh"]}),e.jsxs(y,{size:"sm",onClick:()=>i("hubspot"),disabled:c||S,children:[c?e.jsx(E,{className:"h-3.5 w-3.5 animate-spin mr-1.5"}):e.jsx(ts,{className:"h-3.5 w-3.5 mr-1.5"}),"Sync Now"]}),S&&e.jsxs(y,{variant:"destructive",size:"sm",onClick:async()=>{l(!0),await o("hubspot"),l(!1)},disabled:u,children:[u?e.jsx(E,{className:"h-3.5 w-3.5 animate-spin mr-1.5"}):e.jsx(qs,{className:"h-3.5 w-3.5 mr-1.5"}),"Cancel Sync"]})]})]})}),e.jsxs(O,{className:"space-y-4",children:[v&&e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"rounded-lg border bg-card p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last Sync"}
130),e.jsx("p",{className:"text-sm font-medium mt-1",children:v.completed_at?es(new Date(v.completed_at),{addSuffix:!0}):"In progress"})]}),e.jsxs("div",{className:"rounded-lg border bg-card p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Status"}),e.jsx("div",{className:"mt-1",children:P(v.status)})]}),e.jsxs("div",{className:"rounded-lg border bg-card p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Records Synced"}),e.jsxs("p",{className:"text-sm font-medium mt-1",children:[e.jsxs("span",{className:"text-success",children:[v.records_created," new"]})," · ",e.jsxs("span",{className:"text-info",children:[v.records_updated," updated"]})]})]}),e.jsxs("div",{className:"rounded-lg border bg-card p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Failures"}),e.jsxs("p",{className:`text-sm font-medium mt-1 ${v.records_failed>0?"text-destructive":"text-muted-foreground"}`,children:[v.records_failed," failed"]})]})]}),v&&(()=>{const j=G(v);return j?e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-2",children:"Last Sync Breakdown"}),e.jsx("div",{className:"grid grid-cols-3 gap-2 text-xs",children:Object.entries(j).map(([M,W])=>e.jsxs("div",{className:"flex items-center justify-between bg-muted/50 rounded px-2 py-1.5",children:[e.jsx("span",{className:"capitalize font-medium",children:M}),e.jsxs("span",{className:"text-muted-foreground",children:[W.created,"â ",W.updated,"â» ",W.failed>0?e.jsxs("span",{className:"text-destructive",children:[W.failed,"â"]}):null]})]},M))})]}):null})(),v&&(()=>{const j=a(v);return j.length===0?null:e.jsxs("div",{className:"rounded-lg border border-destructive/20 bg-destructive/5 p-3",children:[e.jsx("p",{className:"text-xs font-medium text-destructive mb-1",children:"Errors"}),e.jsxs("ul",{className:"text-xs text-muted-foreground space-y-0.5 max-h-24 overflow-y-auto",children:[j.slice(0,5).map((M,W)=>e.jsxs("li",{className:"truncate",children:["⢠",M]},W)),j.length>5&&e.jsxs("li",{className:"text-destructive",children:["...and ",j.length-5," more"]})]})]})})(),t.length>0?e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-2",children:"Sync History"}),e.jsxs(vt,{children:[e.jsx(wt,{children:e.jsxs(ps,{children:[e.jsx(Pe,{className:"text-xs",children:"Time"}),e.jsx(Pe,{className:"text-xs",children:"Type"}),e.jsx(Pe,{className:"text-xs",children:"Status"}),e.jsx(Pe,{className:"text-xs text-right",children:"Created"}),e.jsx(Pe,{className:"text-xs text-right",children:"Updated"}),e.jsx(Pe,{className:"text-xs text-right",children:"Failed"})]})}),e.jsx(Nt,{children:N.map(j=>e.jsxs(ps,{children:[e.jsx(Te,{className:"text-xs text-muted-foreground",children:as(new Date(j.started_at),"MMM d, HH:mm")}),e.jsx(Te,{className:"text-xs capitalize",children:j.sync_type}),e.jsx(Te,{children:P(j.status)}),e.jsx(Te,{className:"text-xs text-right text-success",children:j.records_created}),e.jsx(Te,{className:"text-xs text-right text-info",children:j.records_updated}),e.jsx(Te,{className:`text-xs text-right ${j.records_failed>0?"text-destructive":"text-muted-foreground"}`,children:j.records_failed})]},j.id))})]}),t.length>5&&e.jsx(y,{variant:"ghost",size:"sm",onClick:()=>w(!x),className:"w-full mt-1 text-xs",children:x?e.jsxs(e.Fragment,{children:[e.jsx(ft,{className:"h-3 w-3 mr-1"})," Show less"]}):e.jsxs(e.Fragment,{children:[e.jsx(Bs,{className:"h-3 w-3 mr-1"})," Show all ",t.length," entries"]})})]}):e.jsx("div",{className:"text-center py-6 text-sm text-muted-foreground",children:'No sync history yet. Click "Sync Now" to start your first sync.'}),r&&e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Auto-sync:"})," ",r.is_enabled?e.jsxs(e.Fragment,{children:["Every ",r.sync_interval_minutes," minutes · Objects: ",r.sync_objects?.join(", ")||"all"]}):"Disabled",r.last_successful_sync&&e.jsxs(e.Fragment,{children:[" · Last success: ",es(new Date(r.last_successful_sync),{addSuffix:!0})]})]})]})]})}function hr(){const{currentTenant:s}=ne(),{syncLogs:t,settings:r,isLoading:d,isSyncing:c,triggerSync:i,updateSettings:o,refreshLogs:g}=ha(s?.id,"salesforce"),[f,h]=n.useState(!1),[p,u]=n.useState(!1),[l,x]=n.useState(!1);if(d)return e.jsx(R,{children:e.jsx(O,{className:"flex justify-center py-8",children:e.jsx(E,{className:"h-5 w-5 animate-spin text-muted-foreground"})})});const w=t[0],v=p?t:t.slice(0,5),N=l||w?.status==="failed"&&w?.error_details&&typeof w.error_details=="object"&&w.error_details.reconnect_required===!0,S=a=>{switch(a){case"completed":return e.jsx(he,{className:"h-4 w-4 text-success"});case"completed_with_errors":return e.jsx(De,{className:"h-4 w-4 text-warning"});case"failed":return e.jsx(qs,{className:"h-4 w-4 text-destructive"});case"running":return e.jsx(E,{className:"h-4 w-4 animate-spin text-primary"});default:return e.jsx(Ge,{className:"h-4 w-4 text-muted-foreground"})}},_=a=>{const j={completed:"bg-success/10 text-success border-success/20",completed_with_errors:"bg-warning/10 text-warning border-warning/20",failed:"bg-destructive/10 text-destructive border-destructive/20",running:"bg-primary/10 text-primary border-primary/20"};return e.jsxs(U,{variant:"outline",className:`text-xs ${j[a]||""}`,children:[S(a),e.jsx("span",{className:"ml-1 capitalize",children:a.replace(/_/g," ")})]})},P=a=>{const j=a.error_details;return j?Array.isArray(j.errors)?j.errors:typeof j.error=="string"?[j.error]:[]:[]},G=async()=>{try{await i("salesforce"),x(!1)}catch{}};return e.jsxs(R,{children:[e.jsx(J,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Z,{className:"flex items-center gap-2 text-lg",children:[e.jsx(bt,{className:"h-5 w-5"}),"Salesforce Sync Status"]}),e.jsx(ae,{children:"Monitor sync activity and trigger manual syncs"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&e.jsxs(y,{variant:r.is_enabled?"destructive":"outline",size:"sm",disabled:f,onClick:async()=>{h(!0),await o({is_enabled:!r.is_enabled}),h(!1)},children:[f?e.jsx(E,{className:"h-3.5 w-3.5 animate-spin mr-1.5"}):r.is_enabled?e.jsx(aa,{className:"h-3.5 w-3.5 mr-1.5"}):e.jsx(_t,{className:"h-3.5 w-3.5 mr-1.5"}),r.is_enabled?"Pause Sync":"Resume Sync"]}),e.jsxs(y,{variant:"outline",size:"sm",onClick:g,disabled:d,children:[e.jsx(ts,{className:"h-3.5 w-3.5 mr-1.5"}),"Refresh"]}
130),e.jsxs(y,{size:"sm",onClick:G,disabled:c,children:[c?e.jsx(E,{className:"h-3.5 w-3.5 animate-spin mr-1.5"}):e.jsx(ts,{className:"h-3.5 w-3.5 mr-1.5"}),"Sync Now"]})]})]})}),e.jsxs(O,{className:"space-y-4",children:[N&&e.jsxs(Ne,{variant:"destructive",children:[e.jsx(pe,{className:"h-4 w-4"}),e.jsxs(be,{children:["Your Salesforce connection needs to be re-authorized. The refresh token has expired or been revoked. Go to ",e.jsx("strong",{children:"Settings â Integrations"})," and reconnect Salesforce."]})]}),w&&e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"rounded-lg border bg-card p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last Sync"}),e.jsx("p",{className:"text-sm font-medium mt-1",children:w.completed_at?es(new Date(w.completed_at),{addSuffix:!0}):"In progress"})]}),e.jsxs("div",{className:"rounded-lg border bg-card p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Status"}),e.jsx("div",{className:"mt-1",children:_(w.status)})]}),e.jsxs("div",{className:"rounded-lg border bg-card p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Records Synced"}),e.jsxs("p",{className:"text-sm font-medium mt-1",children:[e.jsxs("span",{className:"text-success",children:[w.records_created," new"]})," · ",e.jsxs("span",{className:"text-info",children:[w.records_updated," updated"]})]})]}),e.jsxs("div",{className:"rounded-lg border bg-card p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Failures"}),e.jsxs("p",{className:`text-sm font-medium mt-1 ${w.records_failed>0?"text-destructive":"text-muted-foreground"}`,children:[w.records_failed," failed"]})]})]}),w?.error_details&&typeof w.error_details=="object"&&w.error_details.api_limit&&(()=>{const a=w.error_details.api_limit;return e.jsxs("div",{className:`rounded-lg border p-3 ${a.pct>80?"border-warning/30 bg-warning/5":""}`,children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Salesforce API Usage"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex-1 h-2 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full ${a.pct>80?"bg-warning":"bg-primary"}`,style:{width:`${Math.min(a.pct,100)}%`}})}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[a.used.toLocaleString()," / ",a.total.toLocaleString()," (",a.pct.toFixed(1),"%)"]})]})]})})(),w&&(()=>{const j=P(w).filter(M=>!M.startsWith("[INFO]")&&!M.startsWith("[WARN]"));return j.length===0?null:e.jsxs("div",{className:"rounded-lg border border-destructive/20 bg-destructive/5 p-3",children:[e.jsx("p",{className:"text-xs font-medium text-destructive mb-1",children:"Errors"}),e.jsxs("ul",{className:"text-xs text-muted-foreground space-y-0.5 max-h-24 overflow-y-auto",children:[j.slice(0,5).map((M,W)=>e.jsxs("li",{className:"truncate",children:["⢠",M]},W)),j.length>5&&e.jsxs("li",{className:"text-destructive",children:["...and ",j.length-5," more"]})]})]})})(),t.length>0?e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-2",children:"Sync History"}),e.jsxs(vt,{children:[e.jsx(wt,{children:e.jsxs(ps,{children:[e.jsx(Pe,{className:"text-xs",children:"Time"}),e.jsx(Pe,{className:"text-xs",children:"Type"}),e.jsx(Pe,{className:"text-xs",children:"Status"}),e.jsx(Pe,{className:"text-xs text-right",children:"Created"}),e.jsx(Pe,{className:"text-xs text-right",children:"Updated"}),e.jsx(Pe,{className:"text-xs text-right",children:"Failed"})]})}),e.jsx(Nt,{children:v.map(a=>e.jsxs(ps,{children:[e.jsx(Te,{className:"text-xs text-muted-foreground",children:as(new Date(a.started_at),"MMM d, HH:mm")}),e.jsx(Te,{className:"text-xs capitalize",children:a.sync_type}),e.jsx(Te,{children:_(a.status)}),e.jsx(Te,{className:"text-xs text-right",children:a.records_created}),e.jsx(Te,{className:"text-xs text-right",children:a.records_updated}),e.jsx(Te,{className:`text-xs text-right ${a.records_failed>0?"text-destructive":""}`,children:a.records_failed})]},a.id))})]}),t.length>5&&e.jsx(y,{variant:"ghost",size:"sm",className:"w-full mt-2 text-xs",onClick:()=>u(!p),children:p?e.jsxs(e.Fragment,{children:[e.jsx(ft,{className:"h-3.5 w-3.5 mr-1"})," Show Less"]}):e.jsxs(e.Fragment,{children:[e.jsx(Bs,{className:"h-3.5 w-3.5 mr-1"})," Show All (",t.length,")"]})})]}):e.jsx("div",{className:"text-center py-6 text-sm text-muted-foreground",children:'No sync history yet. Click "Sync Now" to start.'})]})]})}function xr(){const{currentTenant:s}=ne(),{data:t,isLoading:r}=Za(),d=Xa(),c=en(),{data:i}=sn(t?.id),o=He(),[g,f]=n.useState(""),[h,p]=n.useState(""),[u,l]=n.useState({tasks:!0,time_entries:!0,projects:!0,clients:!0,billing:!0}),[x,w]=n.useState(!1),[v,N]=n.useState(null),[S,_]=n.useState([]),[P,G]=n.useState([]),[a,j]=n.useState([]),[M,W]=n.useState([]),[K,T]=n.useState([]),[L,m]=n.useState(!1);n.useEffect(()=>{if(t){f(t.site_name),p(t.api_token);const F=t.sync_config||{};l({tasks:F.tasks??!0,time_entries:F.time_entries??!0,projects:F.projects??!0,clients:F.clients??!0,billing:F.billing??!0}),j(t.sync_scope||[]);const X=t.user_mappings;Array.isArray(X)&&X.length>0&&T(X)}},[t]),n.useEffect(()=>{s?.id&&b.from("projects").select("id, name, is_program").eq("tenant_id",s.id).eq("status","active").order("name").then(({data:F})=>W(F||[]))},[s?.id]),n.useEffect(()=>{if(!t?.is_active||!t.site_name||!t.api_token||P.length>0)return;async function F(){try{const X=await fetch(`https://${t.site_name}.teamwork.com/projects/api/v3/people.json?pageSize=200`,{headers:{Authorization:`Basic ${btoa(t.api_token+":xxx")}`}});if(X.ok){const I=await X.json(),C=I?.people||I?.persons||[];G(C)}}catch(X){console.error("Failed to auto-fetch Teamwork users:",X)}}F()},[t?.is_active,t?.site_name,t?.api_token,P.length]);const k=async()=>
130{if(!g||!h){de.error("Enter site name and API token");return}w(!0),N(null);try{const[F,X]=await Promise.all([fetch(`https://${g}.teamwork.com/projects/api/v3/projects.json?pageSize=100`,{headers:{Authorization:`Basic ${btoa(h+":xxx")}`}}),fetch(`https://${g}.teamwork.com/projects/api/v3/people.json?pageSize=200`,{headers:{Authorization:`Basic ${btoa(h+":xxx")}`}})]);if(!F.ok)throw new Error(`HTTP ${F.status}`);const C=(await F.json())?.projects||[];if(_(C.map($=>({id:String($.id),name:$.name}))),X.ok){const $=await X.json(),z=$?.people||$?.persons||[];G(z)}N(!0),de.success(`Connected! Found ${C.length} projects`)}catch(F){N(!1),de.error(`Connection failed: ${F.message}`)}finally{w(!1)}},q=async()=>{if(u.time_entries&&K.filter(X=>X.platformProfileId).length===0&&de.warning("No user mappings set. Time entries require at least one mapped user."),a.filter(X=>M.find(C=>C.id===X.platformProjectId)?.is_program).length>0){de.error("Cannot map to a program. Please select an actual project, not a program.");return}d.mutate({site_name:g,api_token:h,sync_scope:a,sync_config:u},{onSuccess:async X=>{(X?.id||t?.id)&&await b.from("teamwork_connections").update({user_mappings:K}).eq("id",X?.id||t.id)}})},A=async()=>{t?.id&&(await b.from("teamwork_connections").update({is_active:!1}).eq("id",t.id),o.invalidateQueries({queryKey:["teamwork-connection"]}),de.success("Teamwork disconnected"),m(!1))},ee=F=>{const X=S.find(I=>I.id===F);X&&(a.some(I=>I.teamworkProjectId===F)||j(I=>[...I,{teamworkProjectId:F,teamworkProjectName:X.name,platformProjectId:null,platformProjectName:null}]))},D=(F,X)=>{const I=M.find(C=>C.id===X);if(I?.is_program){de.error("Cannot map to a program. Select an actual project instead.");return}j(C=>C.map($=>$.teamworkProjectId===F?{...$,platformProjectId:X,platformProjectName:I?.name||null}:$))},H=F=>{j(X=>X.filter(I=>I.teamworkProjectId!==F))},Y=n.useCallback(F=>{T(F)},[]),xe=M.filter(F=>!F.is_program);return r?e.jsx(R,{children:e.jsx(O,{className:"flex items-center justify-center py-8",children:e.jsx(E,{className:"h-5 w-5 animate-spin text-muted-foreground"})})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs(R,{children:[e.jsx(J,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-lg bg-primary/10",children:e.jsx(Vs,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Z,{className:"text-lg",children:"Teamwork Integration"}),e.jsx(ae,{children:"Bidirectional sync for tasks, time entries, and project data"})]})]}),t?.is_active&&e.jsxs(U,{variant:"default",className:"bg-success/15 text-success border-success/30",children:[e.jsx(Ce,{className:"h-3 w-3 mr-1"}),"Connected"]})]})}),e.jsxs(O,{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{htmlFor:"tw-site",children:"Teamwork Site Name"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(se,{id:"tw-site",placeholder:"mycompany",value:g,onChange:F=>f(F.target.value)}),e.jsx("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:".teamwork.com"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{htmlFor:"tw-token",children:"API Token"}),e.jsx(se,{id:"tw-token",type:"password",placeholder:"Enter your Teamwork API token",value:h,onChange:F=>p(F.target.value)})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(y,{variant:"outline",onClick:k,disabled:x||!g||!h,children:[x?e.jsx(E,{className:"h-4 w-4 mr-2 animate-spin"}):v===!0?e.jsx(Ce,{className:"h-4 w-4 mr-2 text-success"}):v===!1?e.jsx(pe,{className:"h-4 w-4 mr-2 text-destructive"}):e.jsx(Ms,{className:"h-4 w-4 mr-2"}),"Test Connection"]}),t?.is_active&&e.jsx(y,{variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>m(!0),children:"Disconnect"})]}),e.jsx(me,{}),e.jsxs("div",{children:[e.jsxs("h3",{className:"font-medium mb-3 flex items-center gap-2",children:[e.jsx(Rs,{className:"h-4 w-4"}),"Sync Settings"]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-3",children:[{key:"clients",label:"Clients (Companies)"},{key:"tasks",label:"Tasks"},{key:"time_entries",label:"Time Entries"},{key:"projects",label:"Project Metadata"},{key:"billing",label:"Billing (Invoices & Expenses)"}].map(({key:F,label:X})=>e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-card",children:[e.jsx(B,{htmlFor:`sync-${F}`,className:"cursor-pointer text-sm",children:X}),e.jsx(ye,{id:`sync-${F}`,checked:u[F]??!0,onCheckedChange:I=>l(C=>({...C,[F]:I}))})]},F))})]}),e.jsx(me,{}),e.jsxs("div",{children:[e.jsxs("h3",{className:"font-medium mb-3 flex items-center gap-2",children:[e.jsx(Ms,{className:"h-4 w-4"}),"Project Mappings"]}),e.jsxs("p",{className:"text-sm text-muted-foreground mb-4",children:["Map Teamwork projects to actual projects (not programs) for bidirectional sync.",S.length===0&&" Test connection first to load Teamwork projects."]}),S.length>0&&e.jsx("div",{className:"mb-4",children:e.jsxs(ie,{onValueChange:ee,children:[e.jsx(ce,{className:"w-full sm:w-80",children:e.jsx(le,{placeholder:"Add a Teamwork project to sync..."})}),e.jsx(oe,{children:S.filter(F=>!a.some(X=>X.teamworkProjectId===F.id)).map(F=>e.jsx(V,{value:F.id,children:F.name},F.id))})]})}),a.length>0&&e.jsx("div",{className:"space-y-2",children:a.map(F=>{const I=M.find(C=>C.id===F.platformProjectId)?.is_program;return e.jsxs("div",{className:`flex items-center gap-3 p-3 rounded-lg border bg-card ${I?"border-destructive":""}`,children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:F.teamworkProjectName}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Teamwork ID: ",F.teamworkProjectId]})]}),e.jsx("span",{className:"text-muted-foreground",children:"â"}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs(ie,{value:F.platformProjectId||"",onValueChange:C=>D(F.teamworkProjectId,C),children:[e.jsx(ce,{className:"w-48",children:e.jsx(le,{placeholder:"Map to project..."})}),e.jsx(oe,{children:xe.map(C=>e.jsx(V,{value:C.id,children:C.name},C.id))})]}),I&&e.jsx("p",{className:"text-xs text-destructive",children:"â This is a program, not a project. Please re-map."})]}),e.jsx(y,{variant:"ghost",size:"icon",className:"shrink-0",onClick:()=>H(F.teamworkProjectId),"aria-label":"Delete",children:e.jsx(Le,{className:"h-4 w-4 text-muted-foreground"})})]},F.teamworkProjectId)})})]}),e.jsx(me,{}),s?.id&&P.length>0&&e.jsx(tn,{teamworkUsers:P,tenantId:s.id,mapping:K,onMappingChange:Y}),s?.id&&P.length===0&&K.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Be,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"text-sm font-medium",children:"User Mappings"}),e.jsxs(U,{variant:"secondary",className:"text-xs",children:[K.filter(F=>F.platformProfileId).length," mapped"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Test the connection to refresh and update user mappings."})]}),e.jsxs("div",{className:"flex items-center gap-3 pt-2",children:[e.jsxs(y,{onClick:q,disabled:d.isPending||!g||!h,children:[d.isPending?e.jsx(E,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Save Connection"]}),t?.is_active&&e.jsxs(y,{variant:"outline",onClick:()=>c.mutate(t.id),disabled:c.isPending,children:[c.isPending?e.jsx(E,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ts,{className:"h-4 w-4 mr-2"}),"Sync Now"]})]})]})]}),i&&i.length>0&&e.jsxs(R,{children:[e.jsx(J,{children:e.jsx(Z,{className:"text-base",children:"Sync History"})}),e.jsx(O,{children:e.jsx("div",{className:"space-y-2",children:i.slice(0,10).map(F=>e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border text-sm",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(U,{variant:F.status==="completed"?"default":F.status==="partial"?"secondary":F.status==="failed"?"destructive":"outline",className:"text-xs",children:F.status}),e.jsxs("span",{className:"text-muted-foreground capitalize",children:[F.sync_type," · ",F.direction]})]}),e.jsxs("div",{className:"flex items-center gap-4 text-muted-foreground",children:[e.jsxs("span",{children:[F.entities_processed," synced"]}),F.entities_errored>0&&e.jsxs("span",{className:"text-destructive",children:[F.entities_errored," errors"]}),e.jsx("span",{children:es(new Date(F.started_at),{addSuffix:!0})})]})]},F.id))})})]}),e.jsx(vs,{open:L,onOpenChange:m,children:e.jsxs(ws,{children:[e.jsxs(Ns,{children:[e.jsx(bs,{children:"Disconnect Teamwork?"}),e.jsx(_s,{children:"This will stop syncing data between Teamwork and Commandos. Existing imported data will remain."})]}),e.jsxs(Ss,{children:[e.jsx(Cs,{children:"Cancel"}),e.jsx(st,{onClick:A,children:"Disconnect"})]})]})})]})}function pr({tenantId:s,integrationType:t}){const[r,d]=n.useState(!0),[c,i]=n.useState(null);if(n.useEffect(()=>{let g=!1;return(async()=>{d(!0);try{if(t==="salesforce"||t==="hubspot"){const[{data:p},{data:u}
130]=await Promise.all([b.from("crm_sync_settings").select("sync_interval_minutes, is_enabled, last_successful_sync").eq("tenant_id",s).eq("integration_type",t).maybeSingle(),b.from("crm_sync_log").select("status, completed_at, started_at, error_details, records_processed, records_created, records_updated").eq("tenant_id",s).eq("integration_type",t).order("started_at",{ascending:!1}).limit(1)]),l=u?.[0],x=l?.status==="running"?"running":l?.status==="failed"?"failed":l?.status==="completed"?"ok":"idle";let w=null;if(l?.status==="failed"&&l.error_details){const v=l.error_details;w=v.message||v.error||JSON.stringify(v).slice(0,120)}g||i({lastSuccessAt:p?.last_successful_sync??l?.completed_at??null,lastError:w,intervalMinutes:p?.sync_interval_minutes??null,isEnabled:p?.is_enabled??!1,recentRowsProcessed:l?.records_processed??0,recentRowsCreated:l?.records_created??0,recentRowsUpdated:l?.records_updated??0,status:x})}else{const{data:p}=await b.from("tenant_integrations").select("last_sync_at, sync_error").eq("tenant_id",s).eq("integration_type",t).maybeSingle();g||i({lastSuccessAt:p?.last_sync_at??null,lastError:p?.sync_error??null,intervalMinutes:null,isEnabled:!0,recentRowsProcessed:0,recentRowsCreated:0,recentRowsUpdated:0,status:p?.sync_error?"failed":"ok"})}}catch(h){console.error("IntegrationLiveStatus load failed",h)}finally{g||d(!1)}})(),()=>{g=!0}},[s,t]),r)return e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(E,{className:"h-3 w-3 animate-spin"}),e.jsx("span",{children:"Checking sync statusâ¦"})]});if(!c)return null;const o=c.intervalMinutes&&c.isEnabled&&c.lastSuccessAt?new Date(new Date(c.lastSuccessAt).getTime()+c.intervalMinutes*6e4):null;return e.jsxs("div",{className:"mt-3 pt-3 border-t border-border/50 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:[c.status==="running"&&e.jsxs(U,{variant:"secondary",className:"gap-1",children:[e.jsx(E,{className:"h-3 w-3 animate-spin"})," Syncing now"]}),c.status==="ok"&&e.jsxs(U,{variant:"secondary",className:"gap-1 bg-success/10 text-success border-success/20",children:[e.jsx(he,{className:"h-3 w-3"})," Healthy"]}),c.status==="failed"&&e.jsxs(U,{variant:"destructive",className:"gap-1",children:[e.jsx(pe,{className:"h-3 w-3"})," Last sync failed"]}),c.status==="idle"&&e.jsx(U,{variant:"outline",className:"gap-1",children:"Awaiting first sync"}),c.lastSuccessAt&&e.jsxs("span",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Ge,{className:"h-3 w-3"}),"Last sync ",es(new Date(c.lastSuccessAt),{addSuffix:!0})]}),o&&e.jsxs("span",{className:"flex items-center gap-1 text-muted-foreground",children:["⢠Next ",es(o,{addSuffix:!0})]})]}),c.recentRowsProcessed>0&&e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Fs,{className:"h-3 w-3"}),c.recentRowsProcessed.toLocaleString()," processed"]}),c.recentRowsCreated>0&&e.jsxs("span",{children:[c.recentRowsCreated.toLocaleString()," created"]}),c.recentRowsUpdated>0&&e.jsxs("span",{children:[c.recentRowsUpdated.toLocaleString()," updated"]})]}),c.lastError&&e.jsx("p",{className:"text-xs text-destructive line-clamp-2",children:c.lastError})]})}const gr="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAANK0lEQVR42uxdCXRU1Rm+mI1QqLYFy1aQipVFlsybNwkBnJk3CUulhckkBWorIK2V0yJ6sLi0nlSzQJCiKKB4jrKZFVqMCEgCcnqACgXbni6AWGWTZJawzUJIkNz+P63OkIWQyZv37sy93znfgXOiMHO///733+6FxBpoTk6cy5wy2KMYf+BWjI87FeMKtyJvdlvlvU6bfMypyDVum+yD3zcCm5xW+Rr87IrTJnndNskJPz8KP98P/8878OurLsW0yK2Ycmqt8nAqSQlEgC3UmU393VZpJooFPAAiXoZfaSQIRnIV/vx/we/f8ijSL5w2wwgioPUOH5bossmTUHCnVTqOwuhLyelSjMUem/zg+QzpdiKgPtD1wmJPwYVGV40LzyLxWIFj530w0Fm1mSO/RgQ6B4/VeK/LZlwG57EbFzjK6APvsNaTIRuJQMfgspom4E7CIA0XM+qpGD/EQJLmktuIQOughHSB3e6AqPyvuGixSMwwXFbjTzFTIQJBuDLkiUHheeD1TGIK4R11immY22bciYvCI8Hj7a7LSB1KeMPZKVI3COyWYtTMo/AtMwe58ITZ3JXwAGeGbIPCzWe8C9+cEBscqVMkE4lVnE5LS4YvupJ3oW9GKGx9ARlDbsxlC1hHRwvnXeAOxAYfuCca+sRGhG8zPQTNlgDvooaRMtY4M0xp0d2Vs8kv8S5kZ4hdSpciz46+XW8e1h2i223cC6gSYSP9LnqifCX121jU4V20CBjB84R11FhTBmKLlnexInAUfAqt5gFsR/qZpkHwYU9yLxaP4uMHdFnlU9yLxefOH3OncPscih+M9o2HuReLR/ExzxepHqfiI6BAsZx7sXgVH2btf8K9WLyKX5tpvC9aavuQmTQA/4JdSCikzMfLIjjL78lI6Ysj3DhtjJ2345MGJ9VMGt0Lh1A9VpMCQyoP47wCDqu4rNI5IX5IS9dlk/7N+twdigeLej/eIVBjVvG60SjyQhhJ/xPeJOJSfAT0ql9h031KdXgFDMrQIyM/xpbWD2YYn4a5vhNcie9RTFbWxrRRBNjxj6ILJxoDjw6XImW7FelvMS8+zvCxNcYl1eI5Tc3meBbG2cEzzsBKaEyKj4DFLmJogHKpJz29B4ubBNcJx7piSnwcW2Zhevd/wacxhfksyWJIRZFjQnwEuP4dDOz+V6NpbBpTTEg7K6NefKciZep81tfjTGG0XnUDj7UkOsUPGsAhHQ3AEwtz8m7FNDcqxb+yKXmqZ+bwi/oEe9LnGHsQAf1wdVfCoatVifTSM3dpLf4ZnC4iAjqKXxVnAwOgXzKwshf1TJYiLj7W3fHCKBHQFw3VCdtQ+FA2lPegdT8aEdGAD9LNMURAX9TvTrq7oSqhCUVvzsbtSfTiL++J1OXIOUSABfefUIRi34z+wr7UPcGonviK9AYR0B90D4mH3V+LIrfH+vV30LqpKWqUd49hm5kIsBD5x01GcW+VDZXd6Pk5Q8MWH3vr4txnCI3V8RtQ2A6xOpF6nx0Y7nWnl4gAG6AVJLFhV8JFFDUcBlb1hFTR0KFK3wXzqDuIADO5/0QUsjNsqOhOz00fcauB36+IAFOVvxVA2lk27oBUcf7g9s7+0+LlbfYCwKMooFr0L+nTdqqoGBcQAXbQtIP0QdHUZv0GSBXto1sMcOL0DBFgB19UJ0xHwSLBhq3J9PzcIaGR/8tEILrP/7BSxd8OoO4MLPmaRhEB5gzgz0AaaQZWf+MjwhjMuTSeJ7Y63w75f0ALA2jcFf8UYQxKgZ/yRGth4IckFPV7kgajOFqwYXfCcGEA+tKa73/mRvdfHTdFC/HBy9QQgDAAvQ3Au46EAtzy4xq5/3JhAAwwz7+vmQdIeFkjA1goDEB/Wgq8nzf3AJu1MAA4ajKEATBhANcwGwj1APu0MICmXcn9hAGwQfOSQP/QLuAxDQLAK5SSLsIAGGG+30C+BIyAOSN+/lfHnSAAYQBs0JbnCx7HsDv9GhwBh4QBsERvdqgHuBppA4C/4wNhAEwdAbNDDaBJgxjgfWEADDE/8KgwAI4NwFrgmy+OAI4NwJLve0wEgVx7AO+8UA9QG/E0sCr+pDAApjj3hmFQDWKABlEIYqol/JD2peA9yf2FATBzBGSRLwHueZM2AyFxmcIAWKHPqn07eHf8k8IA2KB1sX9UaDt4gSYGUB1fIQyADU7Iu/yd0G7gA1oYAGYbwgAYnAfAJ2FQII2MYIQwAJYmgoJj4X6NjoGnhQHoTd+Hrb0LtF8LA9i7vd8+whgsed4rTLDA26BNCuh/mwA0HQy9siuRLqscTY1lDmoozx5BBFogI887TiMv8GzLy6G7E3MiJb6zqgf92R8sKP51SqUO8SxMK4AO3RMatYLtrb0O1jsS4h/a0ZtOrHgAhf+KhlJHnfTuFHE9vBmUfF+lFgaQ8cKle9p6IOKImuKv3zqEppZloegtaChxPEYEvkJOLk2ECxteDS6FnCeUdiGAiMUBl6qT6aIt6Sh0mzSUOU5Lax4RT8T8H9ZC//c1mgVsezAHa/WdFf+Tnd+kjk0TUeR2KZVmiUeigqloiTZdQN/zpC3QwyQBCjUXwhV/+7a76Pjyqe0KHxoLjNoylftn4sy53p6YBmo0Dm4hNwH2BdZ1+B2g6iS6tDIFRQ2DWSsI54De/HMaVQADGGuo+lZgTVV3+vBmK4oZJu3XpLKssYRTpBd5eljy/HV6n/+hr4XGgRc4eyviH9zRh06omIJCdopSmeN4Wnl2Mp9nv+8FjSeB2weIu7g98dduHUpNwRSv0zSU2t8knCEzr36Qkue9rM2bAN6m4IXQdlC/M2kQNIeutSb8xepudOGWsSia6pTLHT8nnABzcSXfu1O7DqDvYEdfDX+3ufgfQ4pn3zQJxYoMSxxXpIqccYQD4Fy+xhdBniAdAL4bZAkV/71tg+i4smkoVGRZ6rgQ680iS2EgNdj508T9N44r8PYiHcXF6q7/xBRvcaUBxdGSZw2l0+6OyZQv7/JAiPqdGvf/3yHhoGpb/zmzNysoiB6sgRTxvpgK+nJ9d4L4H+twE3gyCRfG0qyD+hgANozs5+Ty7DEx0esvCvSFQYwjOrwIdjTY/AkDIIKih/ihgaGxLHtOdOf63mHAkzpfAw8fIMR7mgvfsnG0CotF0Sd+YJqlwH9Jp1dAatJ+39T5NZNLp33PWGJvQCF05lG5xGEkUQA0Vkvh2dW6XwFXC1CvL2DAAHCQ5Co0kJZDveB2wiigyzkBPut/5A3zrllePK6T+N6zMPvfVVWLBi/wCYrACF0QoD7C0lAJZi1gnFtvqG6W/piOX7FbhxfB/XMiYdnjIShrYsgIKBjlKRwsMa+d1VU34Usd6bA2m2+2NulrXgdhLmkU+HkPByN/lYHulw3xW1YQ4ZhaCSKkEA0gV+T0xrlGqcTx91v9jKnrnqLWojMRb/pAlTFy7fXB2yclBb80m8T2MhqqoSzLqpZnGFaRk4g1CfA2v4GjZy/OMYTz2UzFc+j9yw9FcuTrdRJpSMVZQ8D1+vALsU97I3iFj0C014AL4E7C1JQSx0iIafrhONr1GCI39zY0FPmP075lLM76rqHMniaV2LPhv/81tqmlMvshrEeo95ly6NhVZViiVdv1n5mUW/d1jc69rOn4ZQTDZ9qbBXBP36Oe68/3T9Q6+CniXcTO0rRxHjUvO6bG7n+RaA10nTDfX8m7iJ2lXAKp4itVnRr2kNZQfdJhvOKFDSPeRVSD6W+sgvz9Ykd3fi3U+/sRPSEVz+wJX+AI7wKqwdT1i6il6NQtiY93Ccz5gTRWat/9oHP4Ge8CqkG5eBakigfaDfogi5hBWALU5wdATPAp7wKqQbksm45dXdx2qpjvY/NanWmjvb84DtTjmLfyqHWJu/krn88RloExgQgM1aPp7XnUsuxI6L/6yT4wOxApoo
130oszWk0L9//JIkmYJ1AFIvUGYvDyiuJVsBM3wzsHXAvZBgEL+qMicsyxvLse8GK/8G7oB2j/QCm1yRWgK1kfCEMByeEuDchrk+pYxm2oEksAozAgjNz3Avduss/A63oTBLrwBlDMIRCnDbmXfTgrs96zbTxQfX7+ezHBo5tXO/6Esd/27tCFoSBKHzBaBejf2E6bS4oCMIEt2lQsJgM/gebQQSjYBAR3FYNRtcNNoPJaFVQrH4fmkXEyTbvg2PL9969d+/e991twqSA8otrWORE/JHhSV07pB2rJfiWksQDSAmVqDsC70hUbKMj70l8qUYyC+TYk3wZHcNXt2jyNDVPiwmJ90CSJiavj1bzMaSbuytC/ZREUyHxObhqQPMuZRbGjBqAoB/dosJZIsw3UMvHhcR3wdzJWhkra8TWc2C0CLYxRtrS5U3oPwZVOthN1+gQT9HGxW8VElb5GkqkgeqadWVeTQqJ4IBlVda1UjBQGaKOLow2hHM4cAwPkWPH0zZUGyfk5Rs3mRz8xziz+YKxJ58BKWeF7wThvAdFUFt1jHxuoSdExHAH0IC61Hl4s2wAAAAASUVORK5CYII=",jr="/assets/slack-logo-CwwBgl4G.png",fr=[{id:"microsoft_graph",name:"Microsoft 365",description:"Connect to Microsoft Graph API to sync calendar events and attendee information automatically.",icon:Ha,scopes:["Calendars.Read","User.Read.All"],type:"microsoft_graph"},{id:"google_workspace",name:"Google Workspace",description:"Org-wide calendar + directory sync via Service Account (recommended). OAuth fallback available.",icon:gr,scopes:["calendar.readonly","admin.directory.user.readonly","admin.directory.group.readonly"],type:"google_workspace"}
130,{id:"slack",name:"Slack",description:"Create internal project channels and post automated updates for deliverables and milestones.",icon:jr,scopes:["channels:manage","chat:write","users:read"],type:"slack"},{id:"salesforce",name:"Salesforce",description:"Two-way sync of Accounts, Contacts, Leads and Opportunities via a Salesforce Connected App. Production or Sandbox.",icon:"https://www.salesforce.com/favicon.ico",scopes:["api","refresh_token","offline_access"],type:"salesforce"},{id:"hubspot",name:"HubSpot",description:"Sync companies, contacts, and deals bidirectionally with your HubSpot CRM.",icon:"https://www.hubspot.com/favicon.ico",scopes:["crm.objects.companies","crm.objects.contacts","crm.objects.deals"],type:"hubspot"},{id:"granola",name:"Granola",description:"Import meeting notes and transcripts. AI analyzes calls for sentiment, action items, and decisions.",icon:"/images/granola-icon.png",scopes:["list_meetings","get_meetings","get_meeting_transcript"],type:"granola"}];function yr(){const{currentTenant:s,currentMembership:t}=ne(),r=t?.role==="owner"||t?.role==="admin",{toast:d}=re(),[c,i]=n.useState([]),[o,g]=n.useState(!0),[f,h]=n.useState(null),[p,u]=n.useState(null),[l,x]=n.useState(!1),[w,v]=n.useState(!1),[N,S]=n.useState(!1),[_,P]=n.useState(!1),[G,a]=n.useState(!1),[j,M]=n.useState(!1),[W,K]=n.useState(null),[T,L]=n.useState(!1),[m,k]=n.useState(!1),[q,A]=n.useState(!1),[ee,D]=n.useState(!1),[H,Y]=n.useState([]),[xe,F]=n.useState(!1),[X,I]=n.useState(0),{syncNow:C,isSyncing:$}=cr(),[z,te]=n.useState(!1);n.useEffect(()=>{s&&ge()},[s]);const ge=async()=>{if(s)try{const{data:Q,error:fe}=await b.from("tenant_integrations").select("*").eq("tenant_id",s.id);if(fe)throw fe;i(Q||[]);const{count:ze}=await b.from("project_slack_channels").select("*",{count:"exact",head:!0}).eq("tenant_id",s.id).eq("is_active",!0);I(ze||0)}catch(Q){console.error("Failed to fetch integrations:",Q)}finally{g(!1)}},je=Q=>{K(null),Q.type==="microsoft_graph"?x(!0):Q.type==="google_workspace"?v(!0):Q.type==="slack"?S(!0):Q.type==="salesforce"?P(!0):Q.type==="hubspot"?a(!0):Q.type==="granola"&&M(!0)},rs=Q=>{K(Q),Q==="microsoft_graph"?x(!0):Q==="google_workspace"&&v(!0)},Fe=()=>{x(!1),v(!1),S(!1),P(!1),a(!1),M(!1),K(null),ge()},Qe=async Q=>{if(s){h(Q),u(null);try{if(Q==="salesforce"){const{data:ze}=await b.from("tenant_integrations").select("credentials").eq("tenant_id",s.id).eq("integration_type","salesforce").maybeSingle(),is=ze?.credentials;if(is?.access_token&&is?.instance_url)try{await fetch(`${is.instance_url}/services/oauth2/revoke`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({token:is.access_token})})}catch{}}const{error:fe}=await b.from("tenant_integrations").delete().eq("tenant_id",s.id).eq("integration_type",Q);if(fe)throw fe;d({title:"Integration disconnected"}),ge()}catch(fe){d({title:"Failed to disconnect",description:fe.message,variant:"destructive"})}finally{h(null)}}},Ze=async()=>{if(s){F(!0);try{const{data:Q,error:fe}=await b.functions.invoke("slack-list-channels",{body:{tenant_id:s.id}});if(fe)throw fe;if(Q.error)throw new Error(Q.error);Y(Q.channels||[])}catch(Q){console.error("Failed to fetch Slack channels:",Q),d({title:"Failed to fetch channels",description:Q.message||"Please check the Slack integration settings",variant:"destructive"})}finally{F(!1)}}},at=()=>{L(!0),Ze()},nt=()=>{k(!0),H.length===0&&Ze()},pa=()=>{A(!0),H.length===0&&Ze()},ga=async()=>{s&&await C(s.id)},ja=()=>{ge()},ks=Q=>c.find(fe=>fe.integration_type===Q);return o?e.jsxs(R,{children:[e.jsx(J,{children:e.jsxs(Z,{className:"flex items-center gap-2",children:[e.jsx(Vs,{className:"h-5 w-5"}),"Integrations"]})}),e.jsx(O,{className:"flex justify-center py-8",children:e.jsx(E,{className:"h-6 w-6 animate-spin text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(R,{children:[e.jsxs(J,{children:[e.jsxs(Z,{className:"flex items-center gap-2",children:[e.jsx(Vs,{className:"h-5 w-5"}),"Integrations"]}),e.jsx(ae,{children:"Connect external services to enhance your workflow. Integrations are configured at the organization level."})]}),e.jsxs(O,{className:"space-y-3",children:[e.jsx(Kt,{children:fr.map(Q=>{const fe=ks(Q.type),ze=fe?.is_active,is=fe?.scopes||Q.scopes;return e.jsxs(qe.div,{initial:{opacity:0,y:10}
130,animate:{opacity:1,y:0},className:`relative overflow-hidden rounded-xl border transition-all duration-200 ${ze?"border-success/30 bg-gradient-to-br from-success/5 to-transparent":"border-border hover:border-primary/30 hover:bg-muted/30"}`,children:[e.jsxs("div",{className:"flex items-center gap-4 p-4",children:[e.jsx("div",{className:`w-11 h-11 rounded-lg flex items-center justify-center p-2 ${ze?"bg-success/10":"bg-muted"}`,children:e.jsx("img",{src:Q.icon,alt:Q.name,className:"w-7 h-7 object-contain"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h4",{className:"font-semibold text-base",children:Q.name}),ze&&e.jsxs(U,{className:"bg-success text-white text-xs px-2 py-0.5",children:[e.jsx(Ce,{className:"h-3 w-3 mr-1"}),"Connected"]}),fe?.sync_error&&e.jsxs(U,{variant:"destructive",className:"text-xs",children:[e.jsx(pe,{className:"h-3 w-3 mr-1"}),"Error"]})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5 line-clamp-1",children:Q.description})]}),e.jsx("div",{className:"flex items-center gap-2",children:ze?e.jsxs(e.Fragment,{children:[(Q.type==="microsoft_graph"||Q.type==="google_workspace")&&e.jsxs(Ke,{children:[e.jsx($e,{asChild:!0,children:e.jsx(y,{variant:"ghost",size:"icon",className:"h-9 w-9",onClick:()=>rs(Q.type),"aria-label":"Settings",children:e.jsx(Rs,{className:"h-4 w-4"})})}),e.jsx(Ye,{children:"Edit scopes & settings"})]}),Q.type==="granola"&&e.jsxs(Ke,{children:[e.jsx($e,{asChild:!0,children:e.jsx(y,{variant:"ghost",size:"icon",className:"h-9 w-9","aria-label":"Information",children:e.jsx(us,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsxs(Ye,{side:"top",className:"max-w-xs text-sm",children:[e.jsx("p",{className:"font-medium mb-1",children:"Where is this used?"}),e.jsxs("ul",{className:"list-disc pl-4 space-y-0.5 text-muted-foreground",children:[e.jsx("li",{children:"Project Transcripts â import meeting notes"}),e.jsx("li",{children:"Client & Prospect pages â pull related meetings"}),e.jsx("li",{children:"Meeting Notes dialog â import directly from Granola"})]})]})]}),e.jsxs(Ke,{children:[e.jsx($e,{asChild:!0,children:e.jsx(y,{variant:"ghost",size:"icon",className:"h-9 w-9 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>u(Q.type),disabled:f===Q.type||!r,children:f===Q.type?e.jsx(E,{className:"h-4 w-4 animate-spin"}):e.jsx(Le,{className:"h-4 w-4"})})}),e.jsx(Ye,{children:r?"Disconnect":"Admins only"})]})]}):r?e.jsxs(y,{onClick:()=>je(Q),size:"sm",children:[e.jsx(It,{className:"h-4 w-4 mr-2"}),"Setup"]}):e.jsxs(Ke,{children:[e.jsx($e,{asChild:!0,children:e.jsx("span",{children:e.jsxs(y,{size:"sm",disabled:!0,children:[e.jsx(It,{className:"h-4 w-4 mr-2"}),"Setup"]})})}),e.jsx(Ye,{side:"top",className:"max-w-xs",children:"Only tenant admins can connect this integration. Ask an admin (owner or admin role) on your workspace to set it up â once they do, calendars and CRM data flow automatically for everyone."})]})})]}),ze&&e.jsxs("div",{className:"px-4 pb-4 pt-0",children:[e.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:is.map(Ct=>e.jsx(U,{variant:"secondary",className:"text-xs font-medium bg-background/50 border border-border/50",children:Ct},Ct))}),fe?.connected_at&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Connected ",new Date(fe.connected_at).toLocaleDateString(),fe.last_sync_at&&e.jsxs(e.Fragment,{children:[" · Last synced ",new Date(fe.last_sync_at).toLocaleString()]})]}),fe?.sync_error&&e.jsx("p",{className:"text-xs text-destructive mt-1",children:fe.sync_error}),s&&(Q.type==="salesforce"||Q.type==="hubspot"||Q.type==="google_workspace"||Q.type==="microsoft_graph")&&e.jsx(pr,{tenantId:s.id,integrationType:Q.type}),Q.type==="hubspot"&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-3 pt-3 border-t border-border/50",children:e.jsxs(y,{variant:"outline",size:"sm",onClick:()=>te(!z),className:"h-8 text-xs",children:[e.jsx(Rs,{className:"h-3.5 w-3.5 mr-1.5"}),z?"Hide Sync Settings":"Configure Sync"]})}),Q.type==="slack"&&e.jsxs("div",{className:"flex flex-wrap gap-2 mt-3 pt-3 border-t border-border/50",children:[e.jsxs(y,{variant:"outline",size:"sm",onClick:()=>D(!0),className:"h-8 text-xs",children:[e.jsx(Re,{className:"h-3.5 w-3.5 mr-1.5"}),"Map Channels"]}),e.jsxs(y,{variant:"outline",size:"sm",onClick:pa,disabled:xe,className:"h-8 text-xs",children:[e.jsx(Ms,{className:"h-3.5 w-3.5 mr-1.5"}),"Link Channel",X>0&&e.jsx(U,{variant:"secondary",className:"ml-1.5 h-4 px-1 text-caption",children:X})]}),e.jsxs(y,{variant:"outline",size:"sm",onClick:ga,disabled:$,className:"h-8 text-xs",children:[$?e.jsx(E,{className:"h-3.5 w-3.5 animate-spin mr-1.5"}):e.jsx(ts,{className:"h-3.5 w-3.5 mr-1.5"}),"Sync Intelligence"]}),e.jsxs(y,{variant:"outline",size:"sm",onClick:at,disabled:xe,className:"h-8 text-xs",children:[xe?e.jsx(E,{className:"h-3.5 w-3.5 animate-spin mr-1.5"}):e.jsx(Re,{className:"h-3.5 w-3.5 mr-1.5"}),"List Channels"]}),e.jsxs(y,{variant:"outline",size:"sm",onClick:nt,className:"h-8 text-xs",children:[e.jsx(ta,{className:"h-3.5 w-3.5 mr-1.5"}),"Test Message"]})]})]}),ze&&Q.type==="google_workspace"&&e.jsx(tr,{})]},Q.id)})}),e.jsx("div",{className:"pt-4 border-t",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("strong",{children:"Note:"})," Each integration requires admin access to the respective platform. The setup wizard will guide you through the configuration process."]})})]})]}),z&&ks("hubspot")?.is_active&&e.jsx(mr,{}),ks("hubspot")?.is_active&&e.jsx(ur,{}),ks("salesforce")?.is_active&&e.jsx(hr,{}),e.jsx(xr,{}),e.jsx(Ga,{open:l,onOpenChange:Q=>{x(Q),Q||K(null)},onSuccess:Fe,existingIntegration:W==="microsoft_graph"?ks("microsoft_graph"):void 0}),e.jsx(qn,{open:w,onOpenChange:Q=>{v(Q),Q||K(null)},onSuccess:Fe}),e.jsx(Rn,{open:N,onOpenChange:S,onSuccess:Fe}),e.jsx(Va,{open:_,onOpenChange:P,onSuccess:Fe}),e.jsx(zn,{open:G,onOpenChange:a,onSuccess:Fe}),e.jsx(Hn,{open:j,onOpenChange:M,onSuccess:Fe}),e.jsx(vs,{open:!!p,onOpenChange:()=>u(null),children:e.jsxs(ws,{children:[e.jsxs(Ns,{children:[e.jsx(bs,{children:"Disconnect Integration?"}),e.jsx(_s,{children:"This will remove the connection and stop syncing data from this service. You can reconnect at any time."})]}),e.jsxs(Ss,{children:[e.jsx(Cs,{children:"Cancel"}),e.jsx(st,{onClick:()=>p&&Qe(p),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})}),e.jsx(ar,{open:T,onOpenChange:L,channels:H,loading:xe}),e.jsx(nr,{open:m,onOpenChange:k,channels:H,channelsLoading:xe}),e.jsx(ir,{open:q,onOpenChange:A,channels:H,channelsLoading:xe,onSuccess:ja}),e.jsx(rr,{open:ee,onOpenChange:D,onSuccess:()=>{D(!1),ge()}})]})}const vr=[{id:"perplexity",label:"Perplexity",description:"Web research for most OSINT layers"},{id:"firecrawl",label:"Firecrawl",description:"Site crawling and structured scraping"},{id:"apollo",label:"Apollo",description:"Org charts and people enrichment"},{id:"sam_gov",label:"SAM.gov",description:"Federal entity registration and exclusion checks (free key)"}];function wr(){const{currentTenant:s}=ne(),{toast:t}=re(),r=He(),d=s?.id,[c,i]=n.useState({}),{data:o,isLoading:g}=Oe({queryKey:["tenant-api-keys",d],enabled:!!d,queryFn:async()=>{const{data:x,error:w}=await b.from("tenant_api_keys").select("id, provider, updated_at").eq("tenant_id",d);if(w)throw w;return x||[]}}),{data:f}=Oe({queryKey:["osint-usage",d],enabled:!!d,queryFn:async()=>{const x=new Date(Date.now()-2592e6).toISOString(),{data:w,error:v}=await b.from("osint_usage_events").select("provider, calls, estimated_cost_usd").eq("tenant_id",d).gte("created_at",x).limit(5e3);if(v)throw v;return w||[]}}),h=n.useMemo(()=>{const x=new Map;
130for(const w of f||[]){const v=x.get(w.provider)||{calls:0,cost:0};v.calls+=w.calls||0,v.cost+=Number(w.estimated_cost_usd)||0,x.set(w.provider,v)}return x},[f]),p=we({mutationFn:async({provider:x,apiKey:w})=>{const{error:v}=await b.from("tenant_api_keys").upsert({tenant_id:d,provider:x,api_key:w,updated_at:new Date().toISOString()},{onConflict:"tenant_id,provider"});if(v)throw v},onSuccess:(x,{provider:w})=>{i(v=>({...v,[w]:""})),r.invalidateQueries({queryKey:["tenant-api-keys",d]}),t({title:"Provider key saved"})},onError:x=>t({title:"Failed to save key",description:x.message,variant:"destructive"})}),u=we({mutationFn:async x=>{const{error:w}=await b.from("tenant_api_keys").delete().eq("tenant_id",d).eq("provider",x);if(w)throw w},onSuccess:()=>{r.invalidateQueries({queryKey:["tenant-api-keys",d]}),t({title:"Provider key removed",description:"OSINT runs fall back to the platform key."})},onError:x=>t({title:"Failed to remove key",description:x.message,variant:"destructive"})}),l=new Set((o||[]).map(x=>x.provider));return e.jsxs(R,{children:[e.jsxs(J,{children:[e.jsxs(Z,{className:"flex items-center gap-2 text-base",children:[e.jsx(En,{className:"h-4 w-4 text-primary"}),"Intelligence Providers"]}),e.jsx(ae,{children:"Bring your own API keys for OSINT research. Your keys take precedence; without one, runs use the platform key. Keys are stored per organization and never shown after saving."})]}),e.jsx(O,{className:"space-y-4",children:g?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(E,{className:"h-4 w-4 animate-spin"})," Loadingâ¦"]}):vr.map(x=>{const w=h.get(x.id);return e.jsxs("div",{className:"flex flex-col gap-2 rounded-md border p-3 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:x.label}),l.has(x.id)?e.jsx(U,{variant:"secondary",className:"text-xs",children:"Your key"}):e.jsx(U,{variant:"outline",className:"text-xs",children:"Platform key"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:x.description}),w&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:["Last 30 days: ",w.calls," calls",w.cost>0?` · ~$${w.cost.toFixed(2)} est.`:""]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(se,{type:"password",placeholder:l.has(x.id)?"Replace keyâ¦":"Paste API keyâ¦",value:c[x.id]||"",onChange:v=>i(N=>({...N,[x.id]:v.target.value})),className:"h-8 w-48 text-xs",autoComplete:"off"}),e.jsx(y,{size:"sm",className:"h-8",disabled:!(c[x.id]||"").trim()||p.isPending,onClick:()=>p.mutate({provider:x.id,apiKey:c[x.id].trim()}),children:"Save"}),l.has(x.id)&&e.jsx(y,{size:"sm",variant:"ghost",className:"h-8 px-2","aria-label":`Remove ${x.label} key`,disabled:u.isPending,onClick:()=>u.mutate(x.id),children:e.jsx(Le,{className:"h-3.5 w-3.5"})})]})]},x.id)})})]})}function Nr(){const{currentTenant:s}=ne(),t=He(),[r,d]=zs(),[c,i]=n.useState(""),[o,g]=n.useState(""),[f,h]=n.useState(!1);n.useEffect(()=>{r.get("qbo_connected")==="true"&&(de.success("QuickBooks Online connected successfully!"),t.invalidateQueries({queryKey:["qbo-integration"]}),r.delete("qbo_connected"),d(r,{replace:!0}));const P=r.get("qbo_error");if(P){const G={missing_params:"OAuth callback missing required parameters",invalid_state:"Invalid OAuth state â please try again",no_integration:"No QuickBooks integration found for this tenant",missing_credentials:"Client credentials not found â please re-enter",token_exchange_failed:"Failed to exchange authorization code for tokens",
130save_failed:"Connected but failed to save credentials",unexpected:"An unexpected error occurred during connection"};de.error(G[P]||`QuickBooks error: ${P}`),r.delete("qbo_error"),d(r,{replace:!0})}},[r]);const{data:p,isLoading:u}=Oe({queryKey:["qbo-integration",s?.id],queryFn:async()=>{const{data:P}=await b.from("tenant_integrations").select("*").eq("tenant_id",s.id).eq("integration_type","quickbooks").maybeSingle();return P},enabled:!!s?.id}),l=we({mutationFn:async()=>{if(!p?.id)throw new Error("No integration to disconnect");const{error:P}=await b.from("tenant_integrations").update({is_active:!1}).eq("id",p.id);if(P)throw P},onSuccess:()=>{t.invalidateQueries({queryKey:["qbo-integration"]}),de.success("QuickBooks disconnected")},onError:P=>de.error(P.message)}),x=we({mutationFn:async()=>{if(!c.trim()||!o.trim())throw new Error("Client ID and Client Secret are required");const{data:{session:P}}=await b.auth.getSession();if(!P)throw new Error("Not authenticated");const{data:G,error:a}=await b.functions.invoke("qbo-oauth-start",{body:{tenant_id:s.id,client_id:c.trim(),client_secret:o.trim()}});if(a)throw a;if(G?.error)throw new Error(G.error);if(!G?.authorize_url)throw new Error("No authorization URL returned");window.location.href=G.authorize_url},onError:P=>de.error(P.message)}),w=p?.is_active,N=p?.credentials?.realm_id,S=p?.last_sync_at,_=p?.sync_error;return u?e.jsx(R,{children:e.jsx(O,{className:"py-8 flex items-center justify-center",children:e.jsx(E,{className:"h-5 w-5 animate-spin text-muted-foreground"})})}):e.jsxs(R,{children:[e.jsx(J,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Z,{className:"text-base flex items-center gap-2",children:[e.jsx("img",{src:"https://upload.wikimedia.org/wikipedia/commons/thumb/a/ae/Intuit_QuickBooks_logo.svg/200px-Intuit_QuickBooks_logo.svg.png",alt:"QuickBooks",className:"h-5",onError:P=>{P.target.style.display="none"}}),"QuickBooks Online"]}),e.jsx(ae,{children:"Push approved invoices to QuickBooks for accounting and AR tracking"})]}),e.jsx(U,{variant:w?"default":"secondary",className:"text-xs",children:w?e.jsxs(e.Fragment,{children:[e.jsx(he,{className:"h-3 w-3 mr-1"})," Connected"]}):"Not Connected"})]})}),e.jsx(O,{className:"space-y-4",children:w?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground text-xs",children:"Company ID"}),e.jsx("p",{className:"font-mono text-xs",children:N||"â"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground text-xs",children:"Last Sync"}),e.jsx("p",{className:"text-xs",children:S?new Date(S).toLocaleString():"Never"})]})]}),_&&e.jsxs("div",{className:"p-2 rounded bg-destructive/10 text-destructive text-xs flex items-start gap-2",children:[e.jsx(pe,{className:"h-3.5 w-3.5 mt-0.5 shrink-0"}),e.jsx("span",{children:_})]}),e.jsx(me,{}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Data Flows"}),e.jsxs("div",{className:"grid grid-cols-1 gap-1.5 text-xs",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(he,{className:"h-3 w-3 text-primary"}),e.jsx("span",{children:"Invoice Push â Approved drafts â QBO Invoices"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(he,{className:"h-3 w-3 text-primary"}),e.jsx("span",{children:"AR Sync â Payment status synced back hourly"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(he,{className:"h-3 w-3 text-primary"}),e.jsx("span",{children:"Client Sync â Bidirectional customer matching"})]})]})]}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(y,{variant:"outline",size:"sm",className:"text-xs",onClick:()=>l.mutate(),disabled:l.isPending,children:[e.jsx(tt,{className:"h-3 w-3 mr-1"}),"Disconnect"]})})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Connect your QuickBooks Online account to automatically push approved invoices and sync payment status. You can also export invoices as CSV for manual import."}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"What gets synced:"}),e.jsxs("ul",{className:"text-xs text-muted-foreground space-y-1 list-disc pl-4",children:[e.jsx("li",{children:"Approved invoice drafts â QBO Invoices with line items"}),e.jsx("li",{children:"Payment status and AR aging synced back"}),e.jsx("li",{children:"Client â Customer matching"})]})]}),f?e.jsxs("div",{className:"space-y-3 border rounded-lg p-3 bg-muted/30",children:[e.jsx("p",{className:"text-xs font-medium",children:"Enter your QuickBooks OAuth App credentials"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Create an app at"," ",e.jsx("a",{href:"https://developer.intuit.com/app/developer/dashboard",target:"_blank",rel:"noopener noreferrer",className:"text-primary underline",children:"developer.intuit.com"})," ","with the Accounting scope, then copy the Client ID and Secret here."]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{children:[e.jsx(B,{htmlFor:"qbo-client-id",className:"text-xs",children:"Client ID"}),e.jsx(se,{id:"qbo-client-id",value:c,onChange:P=>i(P.target.value),placeholder:"ABcDeFgHiJkLmNoPqRsTuV...",className:"text-xs h-8"})]}),e.jsxs("div",{children:[e.jsx(B,{htmlFor:"qbo-client-secret",className:"text-xs",children:"Client Secret"}),e.jsx(se,{id:"qbo-client-secret",type:"password",value:o,onChange:P=>g(P.target.value),placeholder:"â¢â¢â¢â¢â¢â¢â¢â¢â¢â¢â¢â¢â¢â¢â¢â¢",className:"text-xs h-8"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(y,{size:"sm",className:"text-xs",onClick:()=>x.mutate(),disabled:x.isPending||!c.trim()||!o.trim(),children:[x.isPending?e.jsx(E,{className:"h-3 w-3 mr-1 animate-spin"}):e.jsx(Ms,{className:"h-3.5 w-3.5 mr-1"}),"Authorize with QuickBooks"]}),e.jsx(y,{variant:"ghost",size:"sm",className:"text-xs",onClick:()=>{h(!1),i(""),g("")},children:"Cancel"})]})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(y,{size:"sm",className:"text-xs",onClick:()=>h(!0),children:[e.jsx(Ms,{className:"h-3.5 w-3.5 mr-1"}),"Connect QuickBooks"]}),e.jsxs(y,{variant:"outline",size:"sm",className:"text-xs",onClick:()=>de.info("CSV export available on each billing run's review page"),children:[e.jsx(ns,{className:"h-3.5 w-3.5 mr-1"}),"Use CSV Export Instead"]})]})]})})]})}function br(){const{toast:s}=re(),{currentTenant:t}=ne(),[r,d]=n.useState({billing_increment_minutes:15,max_task_hours_ai:2,meetings_use_calendar_duration:!0,communication_billing_enabled:!1,communication_billing_max_daily_minutes:30,timesheet_cadence:"weekly"}),[c,i]=n.useState(!0),[o,g]=n.useState(!1),f=n.useCallback(async()=>
130{if(!t?.id){i(!1);return}i(!0);try{const{data:p,error:u}=await b.from("tenants").select("billing_increment_minutes, max_task_hours_ai, meetings_use_calendar_duration, communication_billing_enabled, communication_billing_max_daily_minutes, timesheet_cadence").eq("id",t.id).single();if(u)throw u;p&&d({billing_increment_minutes:p.billing_increment_minutes||15,max_task_hours_ai:Number(p.max_task_hours_ai)||2,meetings_use_calendar_duration:p.meetings_use_calendar_duration??!0,communication_billing_enabled:p.communication_billing_enabled??!1,communication_billing_max_daily_minutes:p.communication_billing_max_daily_minutes??30,timesheet_cadence:p.timesheet_cadence||"weekly"})}catch(p){console.error("Error loading billing settings:",p)}finally{i(!1)}},[t?.id]);n.useEffect(()=>{f()},[f]);const h=async()=>{if(t?.id){g(!0);try{const{error:p}=await b.from("tenants").update({billing_increment_minutes:r.billing_increment_minutes,max_task_hours_ai:r.max_task_hours_ai,meetings_use_calendar_duration:r.meetings_use_calendar_duration,communication_billing_enabled:r.communication_billing_enabled,communication_billing_max_daily_minutes:r.communication_billing_max_daily_minutes,timesheet_cadence:r.timesheet_cadence}).eq("id",t.id);if(p)throw p;s({title:"Billing settings saved"})}catch(p){console.error("Error saving billing settings:",p),s({title:"Failed to save settings",variant:"destructive"})}finally{g(!1)}}};return c?e.jsxs(R,{children:[e.jsx(J,{children:e.jsxs(Z,{className:"flex items-center gap-2",children:[e.jsx(Ge,{className:"h-5 w-5"}),"Time & Billing Settings"]})}),e.jsx(O,{children:e.jsxs("div",{className:"animate-pulse space-y-4",children:[e.jsx("div",{className:"h-10 bg-muted rounded"}),e.jsx("div",{className:"h-10 bg-muted rounded"})]})})]}):e.jsxs(R,{children:[e.jsxs(J,{children:[e.jsxs(Z,{className:"flex items-center gap-2",children:[e.jsx(Ge,{className:"h-5 w-5"}),"Time & Billing Settings"]}),e.jsx(ae,{children:"Configure AI time estimation rules and billing increments for your organization"})]}),e.jsxs(O,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{htmlFor:"billing-increment",className:"text-base font-medium",children:"Default Billing Increment"}),e.jsxs(Ke,{children:[e.jsx($e,{children:e.jsx(us,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(Ye,{side:"right",className:"max-w-xs",children:e.jsx("p",{children:"All time entries will be rounded up to this increment. Standard is quarter-hour (15 minutes)."})})]})]}),e.jsxs(ie,{value:String(r.billing_increment_minutes),onValueChange:p=>d({...r,billing_increment_minutes:parseInt(p)}),children:[e.jsx(ce,{id:"billing-increment",className:"w-48",children:e.jsx(le,{})}),e.jsxs(oe,{children:[e.jsx(V,{value:"6",children:"6 minutes (0.1h)"}),e.jsx(V,{value:"15",children:"15 minutes (0.25h)"}),e.jsx(V,{value:"30",children:"30 minutes (0.5h)"})]})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Time entries will be rounded up to the nearest ",r.billing_increment_minutes," minutes"]})]}),e.jsx(me,{}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{htmlFor:"timesheet-cadence",className:"text-base font-medium",children:"Timesheet Period"}),e.jsxs(Ke,{children:[e.jsx($e,{children:e.jsx(us,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(Ye,{side:"right",className:"max-w-xs",children:e.jsx("p",{children:"Sets how often timesheet periods reset. The timesheet counter resets at the start of each new period."})})]})]}),e.jsxs(ie,{value:r.timesheet_cadence,onValueChange:p=>d({...r,timesheet_cadence:p}),children:[e.jsx(ce,{id:"timesheet-cadence",className:"w-48",children:e.jsx(le,{})}),e.jsxs(oe,{children:[e.jsx(V,{value:"daily",children:"Daily"}),e.jsx(V,{value:"weekly",children:"Weekly"}),e.jsx(V,{value:"biweekly",children:"Bi-weekly (2 weeks)"}),e.jsx(V,{value:"monthly",children:"Monthly"})]})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[r.timesheet_cadence==="daily"&&"Timesheets reset each day",r.timesheet_cadence==="weekly"&&"Timesheets reset each Monday",r.timesheet_cadence==="biweekly"&&"Timesheets reset every two weeks",r.timesheet_cadence==="monthly"&&"Timesheets reset on the 1st of each month"]})]}),e.jsx(me,{}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{htmlFor:"max-task-hours",className:"text-base font-medium",children:"Maximum AI Suggestion per Task"}),e.jsxs(Ke,{children:[e.jsx($e,{children:e.jsx(us,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(Ye,{side:"right",className:"max-w-xs",children:e.jsx("p",{children:"Limits the maximum hours AI can suggest for a single task. Forces breakdown into smaller increments."})})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(se,{id:"max-task-hours",type:"number",min:.5,max:8,step:.5,value:r.max_task_hours_ai,onChange:p=>d({...r,max_task_hours_ai:parseFloat(p.target.value)||2}),className:"w-24"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"hours maximum"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["AI will not suggest more than ",r.max_task_hours_ai," hours for any single task"]})]}),e.jsx(me,{}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(an,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:"Use Calendar Duration for Meetings"})]}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-md",children:"When enabled, AI uses the actual scheduled meeting duration from your calendar instead of estimating time"})]}),e.jsx(ye,{checked:r.meetings_use_calendar_duration,onCheckedChange:p=>d({...r,meetings_use_calendar_duration:p})})]}),e.jsx(me,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xe,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:"Communication Billing Intelligence"})]}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-md",children:"Detect emails and Slack messages with clients and suggest billable time in 5-minute increments (daily digest)"})]}),e.jsx(ye,{checked:r.communication_billing_enabled,onCheckedChange:p=>d({...r,communication_billing_enabled:p})})]}),r.communication_billing_enabled&&e.jsxs("div",{className:"ml-6 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(B,{htmlFor:"comm-max-daily",className:"text-sm",children:"Daily cap per client:"}),e.jsxs(ie,{value:String(r.communication_billing_max_daily_minutes||30),onValueChange:p=>d({...r,communication_billing_max_daily_minutes:parseInt(p)}),children:[e.jsx(ce,{id:"comm-max-daily",className:"w-32",children:e.jsx(le,{})}),e.jsxs(oe,{children:[e.jsx(V,{value:"15",children:"15 minutes"}),e.jsx(V,{value:"30",children:"30 minutes"}),e.jsx(V,{value:"45",children:"45 minutes"}),e.jsx(V,{value:"60",children:"60 minutes"})]})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Maximum billable time from communications per user, per client, per day"})]})]}),e.jsx(me,{}),e.jsx("div",{className:"flex justify-end",children:e.jsx(y,{onClick:h,disabled:o,children:o?"Saving...":"Save Billing Settings"})})]})]})}function _r(){const{currentTenant:s}=ne(),[t,r]=n.useState(!1),[d,c]=n.useState(!0);n.useEffect(()=>{s?.id&&i()},[s?.id]);const i=async()=>
130{if(!s?.id)return;const{data:f}=await b.from("tenants").select("compliance_mode").eq("id",s.id).single();r(f?.compliance_mode==="dcaa"),c(!1)},o=async f=>{if(!s?.id)return;const h=f?"dcaa":"off",{error:p}=await b.from("tenants").update({compliance_mode:h}).eq("id",s.id);if(p){de.error("Failed to update compliance mode");return}r(f),de.success(f?"DCAA compliance mode enabled":"Compliance mode disabled")},g=["Time entries cannot be edited after period lock without a correction workflow","Every edit creates an immutable audit log with required reason",'"Work performed" narrative field is required on all entries',"Time must be submitted daily â no end-of-week deferrals","Approving manager cannot be the same person as the submitter","Time codes must map to approved charge categories"];return d?null:e.jsxs(R,{className:t?"border-warning/30":"",children:[e.jsxs(J,{children:[e.jsxs(Z,{className:"flex items-center gap-2",children:[e.jsx(Ve,{className:"h-5 w-5"}),"DCAA Compliance Mode",t&&e.jsx(U,{variant:"secondary",className:"text-xs",children:"Active"})]}),e.jsx(ae,{children:"Enable stricter time tracking standards for government contracts. This enforces audit-grade controls across all time entries."})]}),e.jsxs(O,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(B,{className:"font-medium",children:"Enable DCAA Mode"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Applies to all team members in this organization"})]}),e.jsx(ye,{checked:t,onCheckedChange:o})]}),t&&e.jsxs(e.Fragment,{children:[e.jsx(me,{}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium flex items-center gap-1.5",children:[e.jsx(De,{className:"h-3.5 w-3.5 text-warning"}),"Active Enforcement Rules"]}),e.jsx("ul",{className:"space-y-1.5",children:g.map((f,h)=>e.jsxs("li",{className:"flex items-start gap-2 text-xs text-muted-foreground",children:[e.jsx(Ce,{className:"h-3 w-3 mt-0.5 text-success shrink-0"}),f]},h))})]})]})]})]})}const Sr={starter:{name:"Starter",price:29,color:"bg-info"},pro:{name:"Pro",price:49,color:"bg-primary"},enterprise:{name:"Enterprise",price:null,color:"bg-accent-purple"}};function Cr(){const{toast:s}=re(),{subscription:t,loading:r,isActive:d,isTrialing:c,isNFR:i,plan:o,monthlyTotal:g,trialDaysLeft:f,refetch:h}=nn(),[p,u]=n.useState(!1),[l,x]=n.useState(null),w=async()=>{u(!0);try{const{data:_,error:P}=await b.functions.invoke("customer-portal");if(P)throw P;if(_?.url)window.open(_.url,"_blank");else throw new Error("No portal URL returned")}catch(_){console.error("Error opening customer portal:",_),s({title:"Failed to open subscription management",description:_.message||"Please try again later",variant:"destructive"})}finally{u(!1)}},v=async _=>{x(_);try{const{data:P,error:G}=await b.functions.invoke("create-checkout-session",{body:{plan:_,seatCount:t?.seat_count||1}});if(G)throw G;if(P?.url)window.open(P.url,"_blank");else throw new Error("No checkout URL returned")}catch(P){console.error("Error creating checkout:",P),s({title:"Failed to start checkout",description:P.message||"Please try again later",variant:"destructive"})}finally{x(null)}},N=()=>i?e.jsx(U,{variant:"outline",className:"bg-success/10 text-success border-success/30",children:"NFR Partner"}):t?.status==="manually_approved"?e.jsx(U,{variant:"outline",className:"bg-accent-purple/10 text-accent-purple border-accent-purple/30",children:"Approved"}):d?e.jsx(U,{variant:"outline",className:"bg-success/10 text-success border-success/30",children:"Active"}):c?e.jsxs(U,{variant:"outline",className:"bg-warning/10 text-warning border-warning/30",children:["Trial (",f," days left)"]}):t?.status==="past_due"?e.jsx(U,{variant:"destructive",children:"Payment Past Due"}):t?.status==="canceled"?e.jsx(U,{variant:"secondary",children:"Canceled"}):e.jsx(U,{variant:"secondary",children:"No subscription"});if(r)return e.jsxs(R,{children:[e.jsx(J,{children:e.jsxs(Z,{className:"flex items-center gap-2",children:[e.jsx(Ks,{className:"h-5 w-5"}),"Subscription"]})}),e.jsx(O,{children:e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(E,{className:"h-6 w-6 animate-spin text-muted-foreground"})})})]});const S=o?Sr[o]:null;return e.jsxs(R,{children:[e.jsxs(J,{children:[e.jsxs(Z,{className:"flex items-center gap-2",children:[e.jsx(Ks,{className:"h-5 w-5"}),"Subscription"]}),e.jsx(ae,{children:"Manage your subscription and billing"})]}),e.jsxs(O,{className:"space-y-6",children:[e.jsx("div",{className:"flex items-start justify-between p-4 rounded-lg border bg-muted/30",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Dt,{className:`h-5 w-5 ${S?.color?"text-primary":"text-muted-foreground"}`}),e.jsx("span",{className:"text-lg font-semibold",children:S?.name||"No Plan"}),N()]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Be,{className:"h-4 w-4"}),e.jsxs("span",{children:[t?.seat_count||1," seat",(t?.seat_count||1)>1?"s":""]})]}),t?.current_period_end&&d&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ws,{className:"h-4 w-4"}),e.jsxs("span",{children:["Renews ",as(new Date(t.current_period_end),"MMM d, yyyy")]})]}),t?.trial_ends_at&&c&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ws,{className:"h-4 w-4"}),e.jsxs("span",{children:["Trial ends ",as(new Date(t.trial_ends_at),"MMM d, yyyy")]})]})]}),!i&&g>0&&e.jsxs("p",{className:"text-sm",children:[e.jsxs(Ie,{size:"md",children:["$",g]}),e.jsx("span",{className:"text-muted-foreground",children:"/month"})]}),i&&e.jsx("p",{className:"text-sm text-success font-medium",children:"Partner account â no charge"}),t?.cancel_at_period_end&&e.jsx("p",{className:"text-sm text-warning font-medium",children:"Will cancel at end of billing period"})]})}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[t?.stripe_subscription_id&&e.jsxs(y,{variant:"outline",onClick:w,disabled:p,children:[p?e.jsx(E,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ns,{className:"h-4 w-4 mr-2"}),"Manage Subscription"]}),(c||!d&&!i)&&e.jsxs(e.Fragment,{children:[e.jsxs(y,{variant:o==="starter"?"outline":"default",onClick:()=>v("starter"),disabled:l!==null,children:[l==="starter"?e.jsx(E,{className:"h-4 w-4 mr-2 animate-spin"}):null,c?"Subscribe to Starter â $29/mo":"Start with Starter"]}),e.jsxs(y,{variant:"default",onClick:()=>v("pro"),disabled:l!==null,children:[l==="pro"?e.jsx(E,{className:"h-4 w-4 mr-2 animate-spin"}):null,c?"Subscribe to Pro â $49/mo":"Start with Pro"]})]}),d&&o==="starter"&&t?.stripe_subscription_id&&e.jsxs(y,{onClick:w,disabled:p,children:[p?e.jsx(E,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Dt,{className:"h-4 w-4 mr-2"}),"Upgrade to Pro"]})]}),t?.status==="past_due"&&e.jsxs("div",{className:"p-4 rounded-lg border border-destructive/50 bg-destructive/10",children:[e.jsx("p",{className:"text-sm font-medium text-destructive",children:"Your payment is past due. Please update your payment method to avoid service interruption."}),e.jsxs(y,{variant:"destructive",size:"sm",className:"mt-2",onClick:w,disabled:p,children:[p?e.jsx(E,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Update Payment Method"]})]})]})]})}function kr(){const{currentTenant:s}=ne(),t=s?.id;return Oe({queryKey:["embedding-quality-stats",t],queryFn:async()=>
130{if(!t)throw new Error("No tenant");const{data:r,error:d}=await b.from("embedding_quality_stats").select("*").eq("tenant_id",t).order("stat_date",{ascending:!1}).limit(50);if(d)throw d;const c=new Map;for(const l of r||[])c.has(l.source_type)||c.set(l.source_type,l);const i=Array.from(c.values()),o=i.reduce((l,x)=>l+x.total_count,0),g=i.filter(l=>l.avg_quality_score!==null).map(l=>({score:l.avg_quality_score,count:l.total_count})),f=g.length>0?g.reduce((l,x)=>l+x.score*x.count,0)/g.reduce((l,x)=>l+x.count,0):0,h=i.reduce((l,x)=>l+x.needs_review_count,0),p=i.reduce((l,x)=>l+x.duplicate_detected_count,0),u=i.reduce((l,x)=>l+x.stale_count,0);return{totalEmbeddings:o,avgQualityScore:f,pendingReviewCount:h,duplicateCount:p,staleCount:u,bySourceType:i}},enabled:!!t,staleTime:6e4})}function Ar(){const{currentTenant:s}=ne(),t=s?.id;return Oe({queryKey:["embedding-review-queue",t],queryFn:async()=>{if(!t)throw new Error("No tenant");const{data:r,error:d}=await b.from("embedding_review_queue").select("*").eq("tenant_id",t).is("reviewed_at",null).order("created_at",{ascending:!1}).limit(100);if(d)throw d;return r||[]},enabled:!!t})}function Pr(){const s=He();return ne(),we({mutationFn:async({itemId:t,decision:r,notes:d})=>{const{data:{user:c}}=await b.auth.getUser();if(!c)throw new Error("Not authenticated");const{error:i}=await b.from("embedding_review_queue").update({review_decision:r,review_notes:d,reviewed_by:c.id,reviewed_at:new Date().toISOString()}).eq("id",t);if(i)throw i;if(r==="approved"){const{data:o}=await b.from("embedding_review_queue").select("source_type, source_id").eq("id",t).single();o&&await b.from("content_embeddings").update({review_status:"approved"}).eq("source_type",o.source_type).eq("source_id",o.source_id)}return{success:!0}},onSuccess:()=>{de.success("Review submitted"),s.invalidateQueries({queryKey:["embedding-review-queue"]}),s.invalidateQueries({queryKey:["embedding-quality-stats"]})},onError:t=>{de.error("Failed to submit review: "+t.message)}})}function Tr(){const s=He();return we({mutationFn:async({itemIds:t,decision:r})=>{const{data:{user:d}}=await b.auth.getUser();if(!d)throw new Error("Not authenticated");const{error:c}=await b.from("embedding_review_queue").update({review_decision:r,review_notes:`Bulk ${r}`,reviewed_by:d.id,reviewed_at:new Date().toISOString()}).in("id",t);if(c)throw c;if(r==="approved"){const{data:i}=await b.from("embedding_review_queue").select("source_type, source_id").in("id",t);for(const o of i||[])await b.from("content_embeddings").update({review_status:"approved"}).eq("source_type",o.source_type).eq("source_id",o.source_id)}return{count:t.length}},onSuccess:t=>{de.success(`${t.count} items reviewed`),s.invalidateQueries({queryKey:["embedding-review-queue"]}),s.invalidateQueries({queryKey:["embedding-quality-stats"]})},onError:t=>{de.error("Bulk review failed: "+t.message)}})}function Ir(){const{currentTenant:s}=ne();return we({mutationFn:async({sourceTypes:t})=>{if(!s?.id)throw new Error("No tenant");const{data:r,error:d}=await b.functions.invoke("batch-embed",{body:{tenant_id:s.id,source_types:t,force:!0}});if(d)throw d;return r},onSuccess:t=>{de.success(`Re-indexed ${t?.summary?.total_embedded||0} items`)},onError:t=>{de.error("Re-indexing failed: "+t.message)}})}function Dr(){const s=He(),{currentTenant:t}=ne();return we({mutationFn:async({maxQualityScore:r})=>{if(!t?.id)throw new Error("No tenant");const{count:d,error:c}=await b.from("content_embeddings").delete().eq("tenant_id",t.id).lt("data_quality_score",r);if(c)throw c;return{purged:d||0}},onSuccess:r=>{de.success(`Purged ${r.purged} low-quality embeddings`),s.invalidateQueries({queryKey:["embedding-quality-stats"]})},onError:r=>{de.error("Purge failed: "+r.message)}})}const gt={wiki_page:"Wiki Pages",battlecard:"Battlecards",proposal:"Proposals",case_study:"Case Studies",service:"Services",project_lesson:"Project Lessons",deal_outcome:"Deal Outcomes",deliverable_blueprint:"Deliverables",decision_point:"Decisions",redline_resolution:"Redlines",task_completion:"Task Completions",historical_project:"Historical Projects",service_document:"Service Docs",certification:"Certifications",customer_signal:"Customer Signals",communication_insight:"Communications",pricing_insight:"Pricing Insights",billing_pattern:"Billing Patterns"};function xa({score:s}){if(s===null)return e.jsx(U,{variant:"outline",children:"N/A"});const t=s>=80?"bg-success":s>=60?"bg-warning":"bg-destructive";return e.jsx(U,{className:`${t} text-white`,children:s.toFixed(0)})}function Er({reason:s}){const t={duplicate_detected:{label:"Duplicate",variant:"destructive"}
130,quality_threshold:{label:"Quality Review",variant:"secondary"},stale:{label:"Stale",variant:"outline"}},{label:r,variant:d}=t[s]||{label:s,variant:"outline"};return e.jsx(U,{variant:d,children:r})}function Lr(){const{data:s,isLoading:t}=kr(),{data:r,isLoading:d}=Ar(),c=Pr(),i=Tr(),o=Ir(),g=Dr(),[f,h]=n.useState(new Set),[p,u]=n.useState("all"),[l,x]=n.useState(!0),w=r?.filter(_=>p==="all"||_.source_type===p)||[],v=(_,P)=>{const G=new Set(f);P?G.add(_):G.delete(_),h(G)},N=_=>{h(_?new Set(w.map(P=>P.id)):new Set)},S=_=>{f.size!==0&&(i.mutate({itemIds:Array.from(f),decision:_}),h(new Set))};return t?e.jsx("div",{className:"flex items-center justify-center p-8",children:e.jsx(it,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4",children:[e.jsx(R,{children:e.jsxs(O,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(na,{className:"h-4 w-4 text-primary"}),e.jsx(Ie,{size:"md",children:s?.totalEmbeddings||0})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Embeddings"})]})}),e.jsx(R,{children:e.jsxs(O,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(he,{className:"h-4 w-4 text-success"}),e.jsx(Ie,{size:"md",children:s?.avgQualityScore?.toFixed(0)||0})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Avg Quality Score"})]})}),e.jsx(R,{children:e.jsxs(O,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(De,{className:"h-4 w-4 text-warning"}),e.jsx(Ie,{size:"md",children:s?.pendingReviewCount||0})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pending Review"})]})}),e.jsx(R,{children:e.jsxs(O,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Je,{className:"h-4 w-4 text-warning"}),e.jsx(Ie,{size:"md",children:s?.duplicateCount||0})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Duplicates"})]})}),e.jsx(R,{children:e.jsxs(O,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ge,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Ie,{size:"md",children:s?.staleCount||0})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Stale Content"})]})})]}),e.jsx(Zt,{open:l,onOpenChange:x,children:e.jsxs(R,{children:[e.jsx(Xt,{asChild:!0,children:e.jsx(J,{className:"cursor-pointer hover:bg-muted/50 transition-colors",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Z,{className:"text-base",children:"Quality by Source Type"}),e.jsx(ae,{children:"Embedding distribution and quality metrics"})]}),e.jsx(Bs,{className:`h-4 w-4 transition-transform ${l?"rotate-180":""}`})]})})}),e.jsx(ea,{children:e.jsx(O,{children:e.jsx("div",{className:"space-y-3",children:s?.bySourceType.map(_=>e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"w-32 text-sm font-medium truncate",children:gt[_.source_type]||_.source_type}),e.jsx("div",{className:"flex-1",children:e.jsx(ys,{value:_.total_count/(s.totalEmbeddings||1)*100,className:"h-2"})}),e.jsx("div",{className:"w-12 text-right text-sm text-muted-foreground",children:_.total_count}),e.jsx(xa,{score:_.avg_quality_score}),_.needs_review_count>0&&e.jsxs(U,{variant:"outline",className:"text-warning",children:[_.needs_review_count," review"]})]},_.source_type))})})})]})}),e.jsxs(R,{children:[e.jsx(J,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Z,{className:"text-base",children:"Review Queue"}),e.jsx(ae,{children:"Items requiring human review"})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(ie,{value:p,onValueChange:u,children:[e.jsxs(ce,{className:"w-40",children:[e.jsx(on,{className:"h-4 w-4 mr-2"}),e.jsx(le,{})]}),e.jsxs(oe,{children:[e.jsx(V,{value:"all",children:"All Types"}),Object.entries(gt).map(([_,P])=>e.jsx(V,{value:_,children:P},_))]})]})})]})}),e.jsxs(O,{children:[f.size>0&&e.jsxs("div",{className:"flex items-center gap-2 mb-4 p-2 bg-muted rounded-md",children:[e.jsxs("span",{className:"text-sm",children:[f.size," selected"]}),e.jsxs(y,{size:"sm",variant:"outline",onClick:()=>S("approved"),disabled:i.isPending,children:[e.jsx(he,{className:"h-4 w-4 mr-1"}),"Approve All"]}),e.jsxs(y,{size:"sm",variant:"outline",onClick:()=>S("rejected"),disabled:i.isPending,children:[e.jsx(Le,{className:"h-4 w-4 mr-1"}),"Reject All"]})]}),d?e.jsx("div",{className:"flex justify-center p-4",children:e.jsx(it,{className:"h-5 w-5 animate-spin"})}):w.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(he,{className:"h-8 w-8 mx-auto mb-2 text-success"}),e.jsx("p",{children:"No items pending review"})]}):e.jsx(Ds,{className:"h-[400px]",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 p-2 text-sm font-medium text-muted-foreground border-b",children:[e.jsx(ms,{checked:f.size===w.length&&w.length>0,onCheckedChange:N}),e.jsx("span",{className:"w-32",children:"Type"}),e.jsx("span",{className:"flex-1",children:"Preview"}),e.jsx("span",{className:"w-20",children:"Quality"}),e.jsx("span",{className:"w-24",children:"Reason"}),e.jsx("span",{className:"w-32",children:"Actions"})]}),w.map(_=>e.jsx(Fr,{item:_,isSelected:f.has(_.id),onSelect:v,onReview:P=>c.mutate({itemId:_.id,decision:P}),isReviewing:c.isPending},_.id))]})})]})]}),e.jsxs(R,{children:[e.jsxs(J,{children:[e.jsx(Z,{className:"text-base",children:"Manual Controls"}),e.jsx(ae,{children:"Force re-indexing and maintenance operations"})]}),e.jsx(O,{children:e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsxs(y,{variant:"outline",onClick:()=>o.mutate({}),disabled:o.isPending,children:[e.jsx(it,{className:`h-4 w-4 mr-2 ${o.isPending?"animate-spin":""}`}),"Re-index All Content"]}),e.jsxs(vs,{children:[e.jsx(St,{asChild:!0,children:e.jsxs(y,{variant:"outline",className:"text-destructive",children:[e.jsx(Le,{className:"h-4 w-4 mr-2"}),"Purge Low Quality"]})}),e.jsxs(ws,{children:[e.jsxs(Ns,{children:[e.jsx(bs,{children:"Purge Low Quality Embeddings?"}),e.jsx(_s,{children:"This will permanently delete all embeddings with a quality score below 50. This action cannot be undone."})]}),e.jsxs(Ss,{children:[e.jsx(Cs,{children:"Cancel"}),e.jsx(st,{onClick:()=>g.mutate({maxQualityScore:50}),className:"bg-destructive hover:bg-destructive/90",children:"Purge"})]})]})]})]})})]})]})}function Fr({item:s,isSelected:t,onSelect:r,onReview:d,isReviewing:c}){return e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded-md",children:[e.jsx(ms,{checked:t,onCheckedChange:i=>r(s.id,!!i)}),e.jsx("span",{className:"w-32 text-sm truncate",children:gt[s.source_type]||s.source_type}),e.jsx("span",{className:"flex-1 text-sm text-muted-foreground truncate",children:s.content_preview?.slice(0,100)||"No preview"}),e.jsx(xa,{score:s.data_quality_score}),e.jsx(Er,{reason:s.review_reason}),e.jsxs("div",{className:"w-32 flex gap-1",children:[e.jsx(y,{size:"sm",variant:"ghost",className:"h-7 px-2 text-success",onClick:()=>
130d("approved"),disabled:c,children:e.jsx(he,{className:"h-4 w-4"})}),e.jsx(y,{size:"sm",variant:"ghost",className:"h-7 px-2 text-destructive",onClick:()=>d("rejected"),disabled:c,children:e.jsx(Le,{className:"h-4 w-4"})}),s.review_reason==="duplicate_detected"&&e.jsx(y,{size:"sm",variant:"ghost",className:"h-7 px-2 text-info",onClick:()=>d("merged"),disabled:c,children:e.jsx(Je,{className:"h-4 w-4"})})]})]})}function qr(){const{data:s}=dn(),[t,r]=n.useState(!1),d={totalPages:s?.length||0,published:s?.filter(c=>c.status==="published").length||0,drafts:s?.filter(c=>c.status==="draft").length||0,needsReview:s?.filter(c=>{const i=c.last_reviewed_at?new Date(c.last_reviewed_at):new Date(c.updated_at);return Math.floor((Date.now()-i.getTime())/(1e3*60*60*24))>(c.review_reminder_days||90)}).length||0};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-medium",children:"Knowledge Hub Settings"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Configure your organization's knowledge management system"})]}),e.jsx(me,{}),e.jsxs(js,{defaultValue:"overview",className:"space-y-4",children:[e.jsxs(fs,{children:[e.jsx(ve,{value:"overview",children:"Overview"}),e.jsx(ve,{value:"freshness",children:"Freshness & Review"}),e.jsx(ve,{value:"quality",children:"Quality Checks"}),e.jsxs(ve,{value:"embeddings",className:"flex items-center gap-1",children:[e.jsx(na,{className:"h-3 w-3"}),"Embedding Health"]}),e.jsx(ve,{value:"policies",children:"Policies"})]}),e.jsxs(ue,{value:"overview",className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(R,{children:e.jsxs(O,{className:"pt-4",children:[e.jsx(Ie,{size:"md",children:d.totalPages}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Pages"})]})}),e.jsx(R,{children:e.jsxs(O,{className:"pt-4",children:[e.jsx(Ie,{size:"md",className:"text-success",children:d.published}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Published"})]})}),e.jsx(R,{children:e.jsxs(O,{className:"pt-4",children:[e.jsx(Ie,{size:"md",className:"text-warning",children:d.drafts}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Drafts"})]})}),e.jsx(R,{children:e.jsxs(O,{className:"pt-4",children:[e.jsx(Ie,{size:"md",className:"text-destructive",children:d.needsReview}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Needs Review"})]})})]}),e.jsxs(R,{children:[e.jsxs(J,{children:[e.jsxs(Z,{className:"flex items-center gap-2",children:[e.jsx(xs,{className:"h-5 w-5"}),"Knowledge Bootstrapper"]}),e.jsx(ae,{children:"Generate knowledge pages based on your services, projects, team, and best practices"})]}),e.jsx(O,{children:t?e.jsx(rn,{variant:"wizard",onComplete:()=>r(!1)}):e.jsxs(y,{onClick:()=>r(!0),variant:"outline",className:"w-full",children:[e.jsx(xs,{className:"h-4 w-4 mr-2"}),"Launch Knowledge Bootstrapper"]})})]})]}),e.jsx(ue,{value:"freshness",children:e.jsx(cn,{})}),e.jsx(ue,{value:"quality",className:"space-y-6",children:e.jsx(ln,{})}),e.jsx(ue,{value:"embeddings",className:"space-y-6",children:e.jsx(Lr,{})}),e.jsx(ue,{value:"policies",className:"space-y-6",children:e.jsxs(R,{children:[e.jsx(J,{children:e.jsxs(Z,{className:"flex items-center gap-2",children:[e.jsx(Rs,{className:"h-5 w-5"}),"Content Policies"]})}),e.jsxs(O,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(B,{children:"Auto-versioning"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Automatically create versions when pages are edited"})]}),e.jsx(ye,{defaultChecked:!0})]}),e.jsx(me,{}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(B,{children:"Review Reminders"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Default review cycle for knowledge pages (90 days)"})]}),e.jsx(ye,{defaultChecked:!0})]}),e.jsx(me,{}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(B,{children:"AI Context Injection"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Include knowledge in AI-generated content (proposals, deliverables)"})]}),e.jsx(ye,{defaultChecked:!0})]})]})]})})]})]})}function Mr(){const{settings:s,isLoading:t,updateSettings:r}=mn(),[d,c]=n.useState("quarterly"),[i,o]=n.useState(7),[g,f]=n.useState(7),[h,p]=n.useState([]),[u,l]=n.useState(""),[x,w]=n.useState(!1);n.useEffect(()=>{s&&(c(s.review_cycle_frequency),o(s.review_reminder_days_before),f(s.review_escalation_days_after),p(s.default_competencies))},[s]);const v=()=>{u.trim()&&!h.includes(u.trim())&&(p([...h,u.trim()]),l(""),w(!0))},N=_=>{p(h.filter(P=>P!==_)),w(!0)},S=()=>{r.mutate({review_cycle_frequency:d,review_reminder_days_before:i,review_escalation_days_after:g,default_competencies:h},{onSuccess:()=>w(!1)})};return t?e.jsx(R,{children:e.jsx(O,{className:"flex items-center justify-center py-8",children:e.jsx(E,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):e.jsxs(R,{children:[e.jsxs(J,{children:[e.jsxs(Z,{className:"flex items-center gap-2",children:[e.jsx(bt,{className:"h-5 w-5"}),"Performance Management"]}),e.jsx(ae,{children:"Configure review cycles, reminders, and competency frameworks"})]}),e.jsxs(O,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{children:"Review Frequency"}),e.jsxs(ie,{value:d,onValueChange:_=>{c(_),w(!0)},children:[e.jsx(ce,{className:"w-full md:w-[200px]",children:e.jsx(le,{})}),e.jsxs(oe,{children:[e.jsx(V,{value:"monthly",children:"Monthly"}),e.jsx(V,{value:"quarterly",children:"Quarterly"}),e.jsx(V,{value:"semi_annual",children:"Semi-Annual"}),e.jsx(V,{value:"annual",children:"Annual"})]})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"How often performance reviews are conducted"})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{htmlFor:"reminder-days",children:"Reminder Days Before"}),e.jsx(se,{id:"reminder-days",type:"number",min:1,max:30,value:i,onChange:_=>{o(parseInt(_.target.value)||7),w(!0)},className:"w-full md:w-[120px]"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Days before due date to send reminder"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{htmlFor:"escalation-days",children:"Escalation Days After"}),e.jsx(se,{id:"escalation-days",type:"number",min:1,max:30,value:g,onChange:_=>{f(parseInt(_.target.value)||7),w(!0)},className:"w-full md:w-[120px]"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Days after due date to escalate to admin"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(B,{children:"Default Competencies"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"These competencies will be used in performance review templates"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:h.map(_=>e.jsxs(U,{variant:"secondary",className:"flex items-center gap-1 pr-1",children:[_,e.jsx("button",{onClick:()=>N(_),className:"ml-1 rounded-full p-0.5 hover:bg-muted",children:e.jsx($t,{className:"h-3 w-3"})})]},_))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(se,{placeholder:"Add competency...",value:u,onChange:_=>l(_.target.value),onKeyDown:_=>{_.key==="Enter"&&(_.preventDefault(),v())},className:"max-w-[250px]"}),e.jsx(y,{variant:"outline",size:"icon",onClick:v,disabled:!u.trim(),"aria-label":"Add",children:e.jsx(Ts,{className:"h-4 w-4"})})]})]}),e.jsx(y,{onClick:S,disabled:!x||r.isPending,children:r.isPending?e.jsxs(e.Fragment,{children:[e.jsx(E,{className:"mr-2 h-4 w-4 animate-spin"}),"Saving..."]}):"Save Settings"})]})]})}function Rr(){const{toast:s}=re(),[t,r]=n.useState(!0),[d,c]=n.useState([]),[i,o]=n.useState(!1),[g,f]=n.useState(!1),[h,p]=n.useState(!1),[u,l]=n.useState(null),[x,w]=n.useState(null),[v,N]=n.useState(null),[S,_]=n.useState(""),[P,G]=n.useState(!1),[a,j]=n.useState(!1),[M,W]=n.useState(""),K=async()=>{try{const{data:A,error:ee}=await b.auth.mfa.listFactors();if(ee)throw ee;const D=A.totp.filter(H=>H.status==="verified");c(D)}catch(A){console.error("Error fetching MFA factors:",A)}finally{r(!1)}};n.useEffect(()=>{K()},[]);const T=async()=>{p(!0),l(null),w(null),_("");try{const{data:A,error:ee}=await b.auth.mfa.enroll({factorType:"totp",friendlyName:"Authenticator App"});if(ee)throw ee;l(A.totp.qr_code),w(A.totp.secret),N(A.id),o(!0)}catch(A){s({title:"Failed to start enrollment",description:A.message,variant:"destructive"})}finally{p(!1)}},L=async()=>
130{if(!(!v||S.length!==6)){G(!0);try{const{data:A,error:ee}=await b.auth.mfa.challenge({factorId:v});if(ee)throw ee;const{error:D}=await b.auth.mfa.verify({factorId:v,challengeId:A.id,code:S});if(D)throw D;s({title:"Two-factor authentication enabled",description:"Your account is now protected with 2FA."}),o(!1),l(null),w(null),N(null),_(""),await K()}catch(A){s({title:"Verification failed",description:A.message||"Invalid code. Please try again.",variant:"destructive"})}finally{G(!1)}}},m=async()=>{if(!(d.length===0||M.length!==6)){j(!0);try{const A=d[0],{data:ee,error:D}=await b.auth.mfa.challenge({factorId:A.id});if(D)throw D;const{error:H}=await b.auth.mfa.verify({factorId:A.id,challengeId:ee.id,code:M});if(H)throw H;const{error:Y}=await b.auth.mfa.unenroll({factorId:A.id});if(Y)throw Y;s({title:"Two-factor authentication disabled",description:"2FA has been removed from your account."}),f(!1),W(""),await K()}catch(A){s({title:"Failed to disable 2FA",description:A.message||"Invalid code. Please try again.",variant:"destructive"})}finally{j(!1)}}},k=async()=>{if(v)try{await b.auth.mfa.unenroll({factorId:v})}catch{}o(!1),l(null),w(null),N(null),_("")};if(t)return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Two-Factor Authentication"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add an extra layer of security"})]}),e.jsx(E,{className:"h-4 w-4 animate-spin"})]});const q=d.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[q?e.jsx(un,{className:"h-5 w-5 text-success"}):e.jsx(Ve,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Two-Factor Authentication"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:q?"Your account is protected with 2FA":"Add an extra layer of security"})]})]}),q?e.jsxs(y,{variant:"outline",size:"sm",onClick:()=>f(!0),children:[e.jsx(hn,{className:"h-4 w-4 mr-2"}),"Disable"]}):e.jsxs(y,{variant:"outline",size:"sm",onClick:T,disabled:h,children:[h?e.jsx(E,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(xn,{className:"h-4 w-4 mr-2"}),"Enable"]})]}),e.jsx(_e,{open:i,onOpenChange:A=>!A&&k(),children:e.jsxs(Se,{className:"sm:max-w-md",children:[e.jsxs(ke,{children:[e.jsx(Ae,{children:"Enable Two-Factor Authentication"}),e.jsx(Ee,{children:"Scan the QR code with your authenticator app (like Google Authenticator or Authy)"})]}),e.jsxs("div",{className:"space-y-6 py-4",children:[u&&e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx("div",{className:"bg-white p-4 rounded-lg",children:e.jsx("img",{src:u,alt:"QR Code",className:"w-48 h-48"})}),x&&e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Can't scan? Enter this code manually:"}),e.jsx("code",{className:"text-xs bg-muted px-2 py-1 rounded font-mono break-all",children:x})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(B,{htmlFor:"verify-code",children:"Enter the 6-digit code from your app"}),e.jsx("div",{className:"flex justify-center",children:e.jsx(Et,{maxLength:6,value:S,onChange:_,children:e.jsxs(Lt,{children:[e.jsx(Me,{index:0}),e.jsx(Me,{index:1}),e.jsx(Me,{index:2}),e.jsx(Me,{index:3}),e.jsx(Me,{index:4}),e.jsx(Me,{index:5})]})})})]}),e.jsxs("div",{className:"flex gap-3 justify-end",children:[e.jsx(y,{variant:"outline",onClick:k,children:"Cancel"}),e.jsx(y,{onClick:L,disabled:S.length!==6||P,children:P?e.jsxs(e.Fragment,{children:[e.jsx(E,{className:"h-4 w-4 mr-2 animate-spin"}),"Verifying..."]}):"Verify & Enable"})]})]})]})}),e.jsx(_e,{open:g,onOpenChange:f,children:e.jsxs(Se,{className:"sm:max-w-md",children:[e.jsxs(ke,{children:[e.jsx(Ae,{children:"Disable Two-Factor Authentication"}),e.jsx(Ee,{children:"Enter your authenticator code to confirm disabling 2FA"})]}),e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(B,{children:"Enter the 6-digit code from your authenticator app"}),e.jsx("div",{className:"flex justify-center",children:e.jsx(Et,{maxLength:6,value:M,onChange:W,children:e.jsxs(Lt,{children:[e.jsx(Me,{index:0}),e.jsx(Me,{index:1}),e.jsx(Me,{index:2}),e.jsx(Me,{index:3}),e.jsx(Me,{index:4}),e.jsx(Me,{index:5})]})})})]}),e.jsxs("div",{className:"flex gap-3 justify-end",children:[e.jsx(y,{variant:"outline",onClick:()=>f(!1),children:"Cancel"}),e.jsx(y,{variant:"destructive",onClick:m,disabled:M.length!==6||a,children:a?e.jsxs(e.Fragment,{children:[e.jsx(E,{className:"h-4 w-4 mr-2 animate-spin"}),"Disabling..."]}):"Disable 2FA"})]})]})]})})]})}const Or=Na({newPassword:kt().min(8,"Password must be at least 8 characters"),confirmPassword:kt()}).refine(s=>s.newPassword===s.confirmPassword,{message:"Passwords don't match",path:["confirmPassword"]});function zr(){const{toast:s}=re(),[t,r]=n.useState(!1),[d,c]=n.useState(!1),[i,o]=n.useState(!1),[g,f]=n.useState(!1),{register:h,handleSubmit:p,formState:{errors:u},reset:l}=pn({resolver:gn(Or),defaultValues:{newPassword:"",confirmPassword:""}}),x=async v=>{try{c(!0);const{error:N}=await b.auth.updateUser({password:v.newPassword});if(N)throw N;s({title:"Password Changed",description:"Your password has been updated successfully."}),l(),r(!1)}catch(N){console.error("Error changing password:",N),s({title:"Error",description:N.message||"Failed to change password",variant:"destructive"})}finally{c(!1)}},w=v=>{r(v),v||(l(),o(!1),f(!1))};return e.jsxs(_e,{open:t,onOpenChange:w,children:[e.jsx(ba,{asChild:!0,children:e.jsx(y,{variant:"outline",children:"Change Password"})}),e.jsxs(Se,{className:"sm:max-w-[400px]",children:[e.jsxs(ke,{children:[e.jsxs(Ae,{className:"flex items-center gap-2",children:[e.jsx(Ps,{className:"h-5 w-5"}),"Change Password"]}),e.jsx(Ee,{children:"Enter your new password below. Make sure it's at least 8 characters."})]}),e.jsxs("form",{onSubmit:p(x),className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{htmlFor:"newPassword",children:"New Password *"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ps,{className:"absolute left-3 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(se,{id:"newPassword",type:i?"text":"password",placeholder:"Minimum 8 characters",className:"pl-9 pr-9",...h("newPassword")}),e.jsx(y,{type:"button",variant:"ghost",size:"icon",className:"absolute right-0 top-0 h-full px-3 hover:bg-transparent",onClick:()=>o(!i),"aria-label":i?"Hide password":"Show password",children:i?e.jsx(Qs,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Is,{className:"h-4 w-4 text-muted-foreground"})})]}),u.newPassword&&e.jsx("p",{className:"text-sm text-destructive",children:u.newPassword.message})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{htmlFor:"confirmPassword",children:"Confirm Password *"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ps,{className:"absolute left-3 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(se,{id:"confirmPassword",type:g?"text":"password",placeholder:"Confirm your new password",className:"pl-9 pr-9",...h("confirmPassword")}),e.jsx(y,{type:"button",variant:"ghost",size:"icon",className:"absolute right-0 top-0 h-full px-3 hover:bg-transparent",onClick:()=>f(!g),"aria-label":g?"Hide password":"Show password",children:g?e.jsx(Qs,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Is,{className:"h-4 w-4 text-muted-foreground"})})]}),u.confirmPassword&&e.jsx("p",{className:"text-sm text-destructive",children:u.confirmPassword.message})]}),e.jsxs(Ue,{children:[e.jsx(y,{type:"button",variant:"outline",onClick:()=>r(!1),children:"Cancel"}),e.jsxs(y,{type:"submit",disabled:d,children:[d&&e.jsx(E,{className:"mr-2 h-4 w-4 animate-spin"}),"Change Password"]})]})]})]})]})}const Vt=[{value:"consulting",label:"Consulting / Professional Services",icon:fn,description:"Default terminology (Projects, Proposals)",preview:{project:"Project",proposal:"Proposal"}},{value:"legal",label:"Legal Practice",icon:ra,description:"Law firm terminology (Matters, Engagement Letters)",preview:{project:"Matter",proposal:"Engagement Letter"}},{value:"accounting",label:"Accounting / Finance",icon:yn,description:"Accounting terminology (Engagements, Proposals)",preview:{project:"Engagement",proposal:"Proposal"}},{value:"audit",label:"Audit & Attest Firm",icon:vn,description:"Full audit workflow with phase gating, workpapers, independence certification",preview:{project:"Engagement",proposal:"Engagement Letter"},badge:"SOC 2 Ready"},{value:"general",label:"General Business",icon:We,description:"Standard business terminology",preview:{project:"Project",proposal:"Proposal"}}];function Br(){const{currentTenant:s,refetch:t}=ne(),{hasAuditData:r,isCheckingAuditData:d}=jn(),{toast:c}=re(),[i,o]=n.useState("consulting"),[g,f]=n.useState(!1),[h,p]=n.useState("none"),[u,l]=n.useState(null),x=n.useRef(!1);n.useEffect(()=>{s?.industry_vertical&&o(s.industry_vertical)},[s?.industry_vertical]);const w=j=>{if(s?.industry_vertical==="audit"&&j!=="audit"&&r){l(j),p("blocked");return}j!==s?.industry_vertical?(l(j),p("step1")):o(j)},v=()=>{h==="step1"?p("step2"):h==="step2"?p("step3"):h==="step3"&&u&&(o(u),p("none"),l(null))},N=()=>{p("none"),l(null)},S=async()=>
130{if(s?.id){f(!0);try{const{error:j}=await b.from("tenants").update({industry_vertical:i,terminology_overrides:null}).eq("id",s.id);if(j)throw j;await t(),c({title:"Industry settings updated",description:i==="audit"?"Audit workflow features are now enabled. Navigate to Engagements to get started.":"Terminology will now reflect your industry throughout the app."})}catch(j){console.error("Error saving industry settings:",j),c({title:"Failed to save settings",variant:"destructive"})}finally{f(!1)}}},_=Vt.find(j=>j.value===i),P=s?.industry_vertical!==i,a=(()=>{switch(h){case"step1":return{title:"Change Industry Vertical?",description:"Switching your industry vertical will change terminology throughout the entire application. All labels for Projects, Proposals, Tasks, and more will be updated to match your selected industry.",action:"I Understand, Continue"};case"step2":return{title:"This May Affect Workflows",description:"Changing your industry vertical may affect existing workflows, navigation menus, and how your team interacts with the platform. Some features may become available or unavailable based on your selection.",action:"I Understand, Continue"};case"step3":return{title:"Final Confirmation",description:"Are you absolutely sure you want to proceed? This action will affect all users in your organization immediately. You can always change it back later (unless you create industry-specific data).",action:"Yes, Change Industry"};case"blocked":return{title:"Cannot Switch Industry",description:"Your organization has existing audit data (engagements, workpapers, findings, or independence certifications). You must archive or delete this data before switching away from the Audit vertical. This protects the integrity of your audit documentation.",action:null};default:return null}})();return e.jsxs(e.Fragment,{children:[e.jsxs(R,{children:[e.jsxs(J,{children:[e.jsxs(Z,{className:"flex items-center gap-2",children:[e.jsx(ra,{className:"h-5 w-5"}),"Industry Vertical"]}),e.jsx(ae,{children:"Configure your industry to customize terminology and features throughout the application"})]}),e.jsxs(O,{className:"space-y-6",children:[e.jsx("div",{className:"grid gap-3",role:"radiogroup","aria-label":"Industry vertical selection",children:Vt.map(j=>{const M=j.icon,K=s?.industry_vertical==="audit"&&r&&j.value!=="audit",T=K||d,L=i===j.value;return e.jsxs("div",{role:"radio","aria-checked":L,"aria-disabled":T,tabIndex:T?-1:0,onClick:()=>!T&&w(j.value),onKeyDown:m=>{(m.key==="Enter"||m.key===" ")&&!T&&(m.preventDefault(),w(j.value))}
130,className:`flex items-start gap-4 rounded-lg border-2 p-4 transition-colors ${L?"border-primary bg-primary/5":"border-muted bg-popover hover:bg-accent hover:text-accent-foreground"} ${T?"opacity-50 cursor-not-allowed":"cursor-pointer"}`,children:[e.jsx("div",{className:`mt-0.5 h-4 w-4 rounded-full border-2 flex items-center justify-center ${L?"border-primary":"border-muted-foreground"}`,children:L&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})}),e.jsx(M,{className:"h-5 w-5 mt-0.5 text-muted-foreground"}),e.jsxs("div",{className:"flex-1 space-y-1",children:[e.jsxs("div",{className:"font-medium flex items-center gap-2",children:[j.label,j.badge&&e.jsx(U,{variant:"secondary",className:"text-xs",children:j.badge})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:j.description})]}),K&&e.jsx(U,{variant:"outline",className:"text-xs",children:"Data exists"})]},j.value)})}),_&&e.jsxs("div",{className:"rounded-lg border bg-muted/50 p-4 space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"Terminology Preview"}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(U,{variant:"secondary",children:["Projects â ",_.preview.project,"s"]}),e.jsxs(U,{variant:"secondary",children:["Proposals â ",_.preview.proposal,"s"]})]}),i==="audit"&&e.jsxs("div",{className:"mt-3 pt-3 border-t border-border",children:[e.jsx("p",{className:"text-sm font-medium text-primary",children:"Audit Features Included:"}),e.jsxs("ul",{className:"mt-2 text-sm text-muted-foreground space-y-1",children:[e.jsx("li",{children:"⢠8-phase audit workflow with gate requirements"}),e.jsx("li",{children:"⢠Independence certification (hard gate)"}),e.jsx("li",{children:"⢠Workpaper management with review workflow"}),e.jsx("li",{children:"⢠Evidence library with hash verification"}),e.jsx("li",{children:"⢠Findings tracker with COSO format"}),e.jsx("li",{children:"⢠SOC 2 Type I & II program templates"})]})]})]}),e.jsx(y,{onClick:S,disabled:g||!P||d,children:g?"Saving...":"Save Industry Settings"})]})]}),e.jsx(vs,{open:h!=="none",onOpenChange:j=>{if(!j&&x.current){x.current=!1;return}j||N()},children:e.jsxs(ws,{children:[e.jsxs(Ns,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[h==="blocked"?e.jsx(De,{className:"h-5 w-5 text-destructive"}):e.jsx(De,{className:"h-5 w-5 text-warning"}),a?.title]}),e.jsx(_s,{children:a?.description})]}),e.jsxs(Ss,{children:[e.jsx(Cs,{onClick:N,children:h==="blocked"?"Close":"Cancel"}),a?.action&&e.jsx(st,{onClick:()=>{h!=="step3"&&(x.current=!0),v()},children:a.action})]})]})})]})}const Gr=[{value:"budget_threshold",label:"Budget Threshold",icon:ia,description:"Alert when project budget exceeds threshold %"},{value:"health_score_drop",label:"Health Score Drop",icon:ca,description:"Alert when client health drops below threshold"},{value:"payment_overdue",label:"Payment Overdue",icon:Ge,description:"Alert when invoice payment is overdue by N days"},{value:"utilization_low",label:"Low Utilization",icon:Be,description:"Alert when team member utilization drops below %"},{value:"margin_below",label:"Margin Below Target",icon:De,description:"Alert when project margin falls below threshold %"}],Hr=[{value:"global",label:"All (Global)"},{value:"project",label:"Specific Project"},{value:"client",label:"Specific Client"},{value:"invoice",label:"Invoices"},{value:"team_member",label:"Team Member"}],Ur={budget_threshold:ia,health_score_drop:ca,payment_overdue:Ge,utilization_low:Be,margin_below:De};function Wr(){const{currentTenant:s}=ne(),{user:t}=jt(),r=He(),[d,c]=n.useState(!1),[i,o]=n.useState({name:"",alert_type:"budget_threshold",entity_type:"global",threshold_value:"90",threshold_operator:">="}),{data:g=[],isLoading:f}=Oe({queryKey:["alert-configurations",s?.id],queryFn:async()=>{const{data:l,error:x}=await b.from("alert_configurations").select("*").eq("tenant_id",s.id).order("created_at",{ascending:!1});if(x)throw x;return l||[]},enabled:!!s?.id}),h=we({mutationFn:async()=>{const{error:l}=await b.from("alert_configurations").insert({tenant_id:s.id,created_by:t?.id,name:i.name,alert_type:i.alert_type,entity_type:i.entity_type,threshold_value:parseFloat(i.threshold_value),threshold_operator:i.threshold_operator,notify_via:["in_app"]});if(l)throw l},onSuccess:()=>{r.invalidateQueries({queryKey:["alert-configurations"]}),c(!1),o({name:"",alert_type:"budget_threshold",entity_type:"global",threshold_value:"90",threshold_operator:">="}),de.success("Alert created")},onError:()=>de.error("Failed to create alert")}),p=we({mutationFn:async({id:l,is_active:x})=>{const{error:w}=await b.from("alert_configurations").update({is_active:x}).eq("id",l);if(w)throw w},onSuccess:()=>
130r.invalidateQueries({queryKey:["alert-configurations"]})}),u=we({mutationFn:async l=>{const{error:x}=await b.from("alert_configurations").delete().eq("id",l);if(x)throw x},onSuccess:()=>{r.invalidateQueries({queryKey:["alert-configurations"]}),de.success("Alert deleted")}});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-medium",children:"Alert Configuration"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set up automated alerts for budget, health, and payment thresholds"})]}),e.jsxs(y,{onClick:()=>c(!0),size:"sm",children:[e.jsx(Ts,{className:"h-4 w-4 mr-1"}),"New Alert"]})]}),f?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading alerts..."}):g.length===0?e.jsx(R,{children:e.jsxs(O,{className:"py-8 text-center",children:[e.jsx(Os,{className:"h-8 w-8 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No alerts configured yet"})]})}):e.jsx("div",{className:"space-y-2",children:g.map(l=>{const x=Ur[l.alert_type]||Os;return e.jsx(R,{children:e.jsx(O,{className:"py-3 px-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-muted",children:e.jsx(x,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:l.name}),e.jsx(U,{variant:l.is_active?"default":"secondary",className:"text-caption",children:l.is_active?"Active":"Paused"}),l.trigger_count>0&&e.jsxs(U,{variant:"outline",className:"text-caption",children:["Triggered ",l.trigger_count,"x"]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[l.alert_type.replace(/_/g," ")," · ",l.entity_type," · threshold: ",l.threshold_operator," ",l.threshold_value]})]}),e.jsx(ye,{checked:l.is_active,onCheckedChange:w=>p.mutate({id:l.id,is_active:w})}),e.jsx(y,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",onClick:()=>u.mutate(l.id),"aria-label":"Delete",children:e.jsx(Le,{className:"h-3.5 w-3.5"})})]})})},l.id)})}),e.jsx(_e,{open:d,onOpenChange:c,children:e.jsxs(Se,{children:[e.jsx(ke,{children:e.jsx(Ae,{children:"Create Alert"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(B,{children:"Name"}),e.jsx(se,{value:i.name,onChange:l=>o({...i,name:l.target.value}),placeholder:"e.g., Budget over 90%"})]}),e.jsxs("div",{children:[e.jsx(B,{children:"Alert Type"}),e.jsxs(ie,{value:i.alert_type,onValueChange:l=>o({...i,alert_type:l}),children:[e.jsx(ce,{children:e.jsx(le,{})}),e.jsx(oe,{children:Gr.map(l=>e.jsx(V,{value:l.value,children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(l.icon,{className:"h-3.5 w-3.5"}),l.label]})},l.value))})]})]}),e.jsxs("div",{children:[e.jsx(B,{children:"Scope"}),e.jsxs(ie,{value:i.entity_type,onValueChange:l=>o({...i,entity_type:l}),children:[e.jsx(ce,{children:e.jsx(le,{})}),e.jsx(oe,{children:Hr.map(l=>e.jsx(V,{value:l.value,children:l.label},l.value))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(B,{children:"Operator"}),e.jsxs(ie,{value:i.threshold_operator,onValueChange:l=>o({...i,threshold_operator:l}),children:[e.jsx(ce,{children:e.jsx(le,{})}),e.jsxs(oe,{children:[e.jsx(V,{value:">",children:"Greater than"}),e.jsx(V,{value:">=",children:"Greater than or equal"}),e.jsx(V,{value:"<",children:"Less than"}),e.jsx(V,{value:"<=",children:"Less than or equal"})]})]})]}),e.jsxs("div",{children:[e.jsx(B,{children:"Threshold"}),e.jsx(se,{type:"number",value:i.threshold_value,onChange:l=>o({...i,threshold_value:l.target.value})})]})]})]}),e.jsxs(Ue,{children:[e.jsx(y,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(y,{onClick:()=>h.mutate(),disabled:!i.name||!i.threshold_value||isNaN(parseFloat(i.threshold_value))||h.isPending,children:"Create Alert"})]})]})})]})}function Vr(){const{preferences:s,isLoading:t,isCategoryMuted:r,toggleCategory:d,setEmailEnabled:c,setDigestFrequency:i}=wn();return t?e.jsxs(R,{children:[e.jsx(J,{children:e.jsxs(Z,{className:"flex items-center gap-2",children:[e.jsx(Os,{className:"h-5 w-5"}),"Notifications"]})}),e.jsxs(O,{className:"space-y-3",children:[e.jsx(ct,{className:"h-10"}),e.jsx(ct,{className:"h-10"}),e.jsx(ct,{className:"h-10"})]})]}):e.jsxs(R,{children:[e.jsxs(J,{children:[e.jsxs(Z,{className:"flex items-center gap-2",children:[e.jsx(Os,{className:"h-5 w-5"}),"Notifications"]}),e.jsx(ae,{children:"Choose which notifications you receive and how"})]}),e.jsxs(O,{className:"space-y-4",children:[Nn.map((o,g)=>e.jsxs("div",{children:[g>0&&e.jsx(me,{className:"mb-4"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:o.label}),e.jsx("p",{className:"text-sm text-muted-foreground",children:o.description})]}),e.jsx(ye,{checked:!r(o.id),onCheckedChange:()=>d(o.id),"aria-label":`Toggle ${o.label} notifications`})]})]},o.id)),e.jsx(me,{}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium flex items-center gap-2",children:[e.jsx(Xe,{className:"h-4 w-4"}),"Email Notifications"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Receive email updates about your work"})]}),e.jsx(ye,{checked:s.email_enabled,onCheckedChange:c,"aria-label":"Toggle email notifications"})]}),e.jsx(me,{}),e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Digest Frequency"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"How often to receive summary digests"})]}),e.jsxs(ie,{value:s.digest_frequency,onValueChange:o=>i(o),children:[e.jsx(ce,{className:"w-32",children:e.jsx(le,{})}),e.jsxs(oe,{children:[e.jsx(V,{value:"off",children:"Off"}),e.jsx(V,{value:"daily",children:"Daily"}),e.jsx(V,{value:"weekly",children:"Weekly"})]})]})]})]})]})}const Qt={critical:"bg-destructive/10 text-destructive border-destructive/30",high:"bg-warning/10 text-warning border-warning/30",medium:"bg-warning/10 text-warning border-warning/30",low:"bg-info/10 text-info border-info/30"},Qr={open:"bg-destructive/10 text-destructive",healing:"bg-warning/10 text-warning",healed:"bg-success/10 text-success",escalated:"bg-warning/10 text-warning",dismissed:"bg-neutral-soft text-neutral-soft-foreground"};function Kr(s){const t=s.filter(g=>g.status==="open"||g.status==="escalated"),r=t.filter(g=>g.severity==="critical").length,d=t.filter(g=>g.severity==="high").length,c=t.filter(g=>g.severity==="medium").length,i=r*25+d*10+c*3,o=Math.max(0,100-i);return o>=90?{score:o,label:"Healthy",color:"text-success"}:o>=70?{score:o,label:"Degraded",color:"text-warning"}:o>=40?{score:o,label:"Unhealthy",color:"text-warning"}:{score:o,label:"Critical",color:"text-destructive"}}function ot(s){const t=Date.now()-new Date(s).getTime(),r=Math.floor(t/6e4);if(r<1)return"just now";if(r<60)return`${r}m ago`;const d=Math.floor(r/60);return d<24?`${d}h ago`:`${Math.floor(d/24)}d ago`}function $r(){const{currentTenant:s}=ne(),t=He(),[r,d]=n.useState("overview"),[c,i]=n.useState(""),[o,g]=n.useState(null),{data:f=[],isLoading:h}=Oe({queryKey:["platform-events",s?.id],queryFn:async()=>
130{if(!s?.id)return[];const{data:a,error:j}=await b.from("platform_events").select("*").eq("tenant_id",s.id).order("last_seen_at",{ascending:!1}).limit(200);if(j)throw j;return a||[]},enabled:!!s?.id,refetchInterval:3e4}),{data:p=[],isLoading:u}=Oe({queryKey:["healing-rules"],queryFn:async()=>{const{data:a,error:j}=await b.from("healing_rules").select("*").order("created_at",{ascending:!0});if(j)throw j;return a||[]}}),l=we({mutationFn:async()=>{const{data:a,error:j}=await b.functions.invoke("platform-health-engine",{body:{tenant_id:s?.id}});if(j)throw j;return a},onSuccess:a=>{de.success(`Health engine: ${a.healed} healed, ${a.escalated} escalated`),t.invalidateQueries({queryKey:["platform-events"]})},onError:a=>{de.error("Health engine failed",{description:a.message})}}),x=we({mutationFn:async({ruleId:a,isActive:j})=>{const{error:M}=await b.from("healing_rules").update({is_active:j,updated_at:new Date().toISOString()}).eq("id",a);if(M)throw M},onSuccess:()=>{t.invalidateQueries({queryKey:["healing-rules"]})}}),w=we({mutationFn:async a=>{const{error:j}=await b.from("platform_events").update({status:"dismissed"}).eq("id",a);if(j)throw j},onSuccess:()=>{t.invalidateQueries({queryKey:["platform-events"]})}}),v=Kr(f),N=f.filter(a=>a.status==="open"||a.status==="escalated"),S=f.filter(a=>a.status==="healed"),_=S.filter(a=>a.healed_at&&Date.now()-new Date(a.healed_at).getTime()<864e5),P=f.filter(a=>!c||a.title.toLowerCase().includes(c.toLowerCase())||a.source.toLowerCase().includes(c.toLowerCase())||a.category.toLowerCase().includes(c.toLowerCase())),G=N.reduce((a,j)=>(a[j.category]=(a[j.category]||0)+1,a),{});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(ma,{className:"h-6 w-6"}),"Platform Health"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Self-healing engine monitors and auto-resolves platform errors"})]}),e.jsxs(y,{onClick:()=>l.mutate(),disabled:l.isPending,size:"sm",children:[e.jsx(_t,{className:"h-4 w-4 mr-1"}),l.isPending?"Running...":"Run Health Engine"]})]}),e.jsxs(js,{value:r,onValueChange:a=>d(a),children:[e.jsxs(fs,{children:[e.jsx(ve,{value:"overview",children:"Overview"}),e.jsxs(ve,{value:"events",children:["Events",N.length>0&&e.jsx(U,{variant:"destructive",className:"ml-1.5 h-5 px-1.5 text-xs",children:N.length})]}),e.jsx(ve,{value:"rules",children:"Healing Rules"}),e.jsx(ve,{value:"history",children:"History"})]}),e.jsxs(ue,{value:"overview",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsx(R,{children:e.jsx(O,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Health Score"}),e.jsx(Ie,{size:"lg",className:v.color,children:v.score})]}),e.jsx(U,{variant:"outline",className:v.color,children:v.label})]})})}),e.jsx(R,{children:e.jsx(O,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Open Issues"}),e.jsx(Ie,{size:"lg",children:N.length})]}),e.jsx(De,{className:"h-8 w-8 text-warning"})]})})}),e.jsx(R,{children:e.jsx(O,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Auto-Healed (24h)"}),e.jsx(Ie,{size:"lg",className:"text-success",children:_.length})]}),e.jsx(he,{className:"h-8 w-8 text-success"})]})})}),e.jsx(R,{children:e.jsx(O,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Active Rules"}),e.jsx(Ie,{size:"lg",children:p.filter(a=>a.is_active).length})]}),e.jsx(Ve,{className:"h-8 w-8 text-info"})]})})})]}),Object.keys(G).length>0&&e.jsxs(R,{children:[e.jsx(J,{children:e.jsx(Z,{className:"text-base",children:"Open Issues by Category"})}),e.jsx(O,{children:e.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(G).sort(([,a],[,j])=>j-a).map(([a,j])=>e.jsxs(U,{variant:"outline",className:"text-sm",children:[a,": ",j]},a))})})]}),N.filter(a=>a.severity==="critical"||a.severity==="high").length>0&&e.jsxs(R,{className:"border-warning/30",children:[e.jsx(J,{children:e.jsxs(Z,{className:"text-base flex items-center gap-2 text-warning",children:[e.jsx(De,{className:"h-4 w-4"}),"Attention Required"]})}),e.jsx(O,{className:"space-y-2",children:N.filter(a=>a.severity==="critical"||a.severity==="high").slice(0,5).map(a=>e.jsxs("div",{className:"flex items-center justify-between p-2 rounded border bg-card",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(U,{variant:"outline",className:Qt[a.severity],children:a.severity}),e.jsx("span",{className:"text-sm truncate",children:a.title})]}),e.jsx("span",{className:"text-xs text-muted-foreground whitespace-nowrap ml-2",children:ot(a.last_seen_at)})]},a.id))})]}),N.length===0&&!h&&e.jsx(R,{className:"border-success/30",children:e.jsxs(O,{className:"pt-6 text-center",children:[e.jsx(he,{className:"h-12 w-12 text-success mx-auto mb-2"}),e.jsx("p",{className:"font-medium text-success",children:"All systems healthy"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No open issues detected"})]})})]}
130),e.jsxs(ue,{value:"events",className:"space-y-4 mt-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:"relative flex-1",children:[e.jsx(et,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(se,{placeholder:"Filter events by title, source, or category...",value:c,onChange:a=>i(a.target.value),className:"pl-9"})]})}),h?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading events..."}):P.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No events found"}):e.jsx("div",{className:"space-y-2",children:P.map(a=>e.jsxs(R,{className:"overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3 p-3 cursor-pointer hover:bg-muted/30 transition-colors",onClick:()=>g(o===a.id?null:a.id),children:[e.jsx(U,{variant:"outline",className:Qr[a.status]||"",children:a.status}),e.jsx(U,{variant:"outline",className:Qt[a.severity]||"",children:a.severity}),e.jsx("span",{className:"text-sm font-medium truncate flex-1",children:a.title}),e.jsx("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:a.source}),a.occurrence_count>1&&e.jsxs(U,{variant:"secondary",className:"text-xs",children:["x",a.occurrence_count]}),e.jsx("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:ot(a.last_seen_at)}),o===a.id?e.jsx(ft,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Bs,{className:"h-4 w-4 text-muted-foreground"})]}),o===a.id&&e.jsxs("div",{className:"px-3 pb-3 border-t bg-muted/10",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs mt-2",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Category:"})," ",a.category]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Source:"})," ",a.source]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"First seen:"})," ",new Date(a.first_seen_at).toLocaleString()]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Last seen:"})," ",new Date(a.last_seen_at).toLocaleString()]}),a.healing_action&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Healing action:"})," ",a.healing_action]})]}),a.details&&Object.keys(a.details).length>0&&e.jsx("pre",{className:"text-xs bg-muted p-2 rounded mt-2 overflow-auto max-h-32",children:JSON.stringify(a.details,null,2)}),(a.status==="open"||a.status==="escalated")&&e.jsx("div",{className:"flex gap-2 mt-2",children:e.jsxs(y,{size:"sm",variant:"outline",onClick:j=>{j.stopPropagation(),w.mutate(a.id)},children:[e.jsx(qs,{className:"h-3 w-3 mr-1"}),"Dismiss"]})})]})]},a.id))})]}),e.jsx(ue,{value:"rules",className:"space-y-4 mt-4",children:e.jsxs(R,{children:[e.jsxs(J,{children:[e.jsx(Z,{className:"text-base",children:"Active Healing Rules"}),e.jsx(ae,{children:"Rules are matched against error titles and details. Toggle to enable/disable."})]}),e.jsx(O,{children:u?e.jsx("div",{className:"text-center py-4 text-muted-foreground",children:"Loading rules..."}):p.length===0?e.jsx("div",{className:"text-center py-4 text-muted-foreground",children:"No healing rules configured"}):e.jsx("div",{className:"space-y-3",children:p.map(a=>e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg border bg-card",children:[e.jsx(ye,{checked:a.is_active,onCheckedChange:j=>x.mutate({ruleId:a.id,isActive:j}),className:"mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm font-medium",children:a.description||a.action_type}),e.jsx(U,{variant:"outline",className:"text-xs",children:a.action_type}),a.category&&e.jsx(U,{variant:"secondary",className:"text-xs",children:a.category})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 font-mono truncate",children:["Pattern: ",a.pattern]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(he,{className:"h-3 w-3 text-success"}),a.success_count," successes"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(qs,{className:"h-3 w-3 text-destructive"}),a.failure_count," failures"]})]})]})]},a.id))})})]})}
130),e.jsx(ue,{value:"history",className:"space-y-4 mt-4",children:e.jsxs(R,{children:[e.jsxs(J,{children:[e.jsxs(Z,{className:"text-base flex items-center gap-2",children:[e.jsx(Sn,{className:"h-4 w-4"}),"Healing History"]}),e.jsx(ae,{children:"Timeline of auto-resolved and escalated events"})]}),e.jsx(O,{children:S.length===0&&f.filter(a=>a.status==="escalated").length===0?e.jsx("div",{className:"text-center py-4 text-muted-foreground",children:"No healing history yet"}):e.jsx("div",{className:"space-y-2",children:f.filter(a=>a.status==="healed"||a.status==="escalated").slice(0,50).map(a=>e.jsxs("div",{className:"flex items-center gap-3 p-2 rounded border bg-card text-sm",children:[a.status==="healed"?e.jsx(he,{className:"h-4 w-4 text-success shrink-0"}):e.jsx(De,{className:"h-4 w-4 text-warning shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"truncate block",children:a.title}),a.healing_action&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["via ",a.healing_action]})]}),e.jsx("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:ot(a.healed_at||a.last_seen_at)})]},a.id))})})]})})]})]})}function Yr(){const{t:s,i18n:t}=la("settings"),{setLanguage:r,isLoading:d}=Ua(),{toast:c}=re(),[i,o]=n.useState(t.language);n.useEffect(()=>{const f=h=>{o(h)};return t.on("languageChanged",f),()=>{t.off("languageChanged",f)}},[t]);const g=async f=>{const h=await r(f);c(h?{title:s("language.languageUpdated")}:{title:s("language.languageUpdateFailed"),variant:"destructive"})};return e.jsxs(R,{children:[e.jsxs(J,{children:[e.jsxs(Z,{className:"flex items-center gap-2",children:[e.jsx(hs,{className:"h-5 w-5"}),s("language.title")]}),e.jsx(ae,{children:s("language.description")})]}),e.jsx(O,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{htmlFor:"language-select",children:s("language.selectLanguage")}),e.jsxs(ie,{value:i,onValueChange:g,disabled:d,children:[e.jsx(ce,{id:"language-select",className:"w-full md:w-[300px]",children:e.jsx(le,{})}),e.jsx(oe,{children:_a.map(f=>e.jsx(V,{value:f.code,children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{children:f.nativeName}),e.jsxs("span",{className:"text-muted-foreground text-sm",children:["(",f.name,")"]})]})},f.code))})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s("language.selectLanguageDesc")})]})})]})}const dt={apollo:{name:"Apollo.io",description:"Contact enrichment and prospecting",icon:e.jsx(Be,{className:"h-4 w-4"})},zoominfo:{name:"ZoomInfo",description:"Enterprise B2B contact database",icon:e.jsx(Fs,{className:"h-4 w-4"})},clearbit:{name:"Clearbit",description:"Company and visitor identification",icon:e.jsx(We,{className:"h-4 w-4"})},ipinfo:{name:"IPinfo",description:"IP-to-company resolution",icon:e.jsx(hs,{className:"h-4 w-4"})},hunter:{name:"Hunter.io",description:"Email finding and verification",icon:e.jsx(yt,{className:"h-4 w-4"})}};function Jr(){const{currentTenant:s}=ne(),{toast:t}=re(),{icpConfig:r,isLoading:d}=Cn(),[c,i]=n.useState(!0),[o,g]=n.useState(null),[f,h]=n.useState([]),[p,u]=n.useState([]),[l,x]=n.useState(!1),[w,v]=n.useState(!1),[N,S]=n.useState(""),[_,P]=n.useState(""),[G,a]=n.useState(!1),[j,M]=n.useState(""),[W,K]=n.useState(""),[T,L]=n.useState("directory"),[m,k]=n.useState(!1);n.useEffect(()=>{s&&q()},[s]);const q=async()=>{if(s){i(!0);try{const{data:I}=await b.from("tracking_scripts").select("*").eq("tenant_id",s.id).single();g(I);const{data:C}=await b.from("enrichment_providers").select("id, tenant_id, provider_type, is_active, created_at, updated_at, monthly_credits, credits_used, last_used_at").eq("tenant_id",s.id);h(C||[]);const{data:$}=await b.from("directory_sources").select("*").eq("tenant_id",s.id).order("created_at",{ascending:!1});u($||[])}catch(I){console.error("Failed to fetch lead generation settings:",I)}finally{i(!1)}}},A=async()=>{if(s)try{const{data:I,error:C}=await b.from("tracking_scripts").insert({tenant_id:s.id}).select().single();if(C)throw C;g(I),t({title:"Tracking script generated"})}catch(I){t({title:"Failed to generate script",description:I.message,variant:"destructive"})}},ee=async I=>{if(o)try{const{error:C}=await b.from("tracking_scripts").update({is_active:I}
130).eq("id",o.id);if(C)throw C;g({...o,is_active:I}),t({title:I?"Tracking enabled":"Tracking paused"})}catch(C){t({title:"Failed to update",description:C.message,variant:"destructive"})}},D=()=>{if(!o)return;const I=`<script> 131(function(t){ 132 var s=document.createElement('script'); 133 s.src='https://vgdtukgdfjsvjjcvcuxk.supabase.co/functions/v1/track-visitor/script.js?t='+t; 134 s.async=true; 135 document.head.appendChild(s); 136})('${o.script_id}'); 137<\/script>`;navigator.clipboard.writeText(I),t({title:"Script copied to clipboard"})},H=async()=>{if(!(!s||!N||!_)){a(!0);try{const{data:I,error:C}=await b.functions.invoke("manage-enrichment-keys",{body:{action:"save",tenant_id:s.id,provider_type:N,api_key:_}});if(C)throw C;if(!I?.success)throw new Error(I?.error||"Failed to save provider");t({title:`${dt[N].name} connected`}),x(!1),S(""),P(""),q()}catch(I){t({title:"Failed to save provider",description:I.message,variant:"destructive"})}finally{a(!1)}}},Y=async(I,C)=>{try{const{error:$}=await b.from("enrichment_providers").update({is_active:C}).eq("id",I);if($)throw $;q()}catch($){t({title:"Failed to update",description:$.message,variant:"destructive"})}},xe=async I=>{try{const{data:C,error:$}=await b.functions.invoke("manage-enrichment-keys",{body:{action:"delete",tenant_id:s?.id,provider_id:I}});if($)throw $;t({title:"Provider removed"}),q()}catch(C){t({title:"Failed to delete",description:C.message,variant:"destructive"})}},F=async()=>{if(!(!s||!j||!W)){k(!0);try{const{error:I}=await b.from("directory_sources").insert({tenant_id:s.id,source_name:j,source_url:W,source_type:T});if(I)throw I;
137t({title:"Directory source added"}),v(!1),M(""),K(""),L("directory"),q()}catch(I){t({title:"Failed to add source",description:I.message,variant:"destructive"})}finally{k(!1)}}},X=async I=>{try{const{error:C}=await b.from("directory_sources").delete().eq("id",I);if(C)throw C;t({title:"Source removed"}),q()}catch(C){t({title:"Failed to delete",description:C.message,variant:"destructive"})}};return c?e.jsxs(R,{children:[e.jsx(J,{children:e.jsxs(Z,{className:"flex items-center gap-2",children:[e.jsx(xs,{className:"h-5 w-5"}),"Lead Generation"]})}),e.jsx(O,{className:"flex justify-center py-8",children:e.jsx(E,{className:"h-6 w-6 animate-spin text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(R,{children:[e.jsxs(J,{children:[e.jsxs(Z,{className:"flex items-center gap-2",children:[e.jsx(xs,{className:"h-5 w-5"}),"Lead Generation"]}),e.jsx(ae,{children:"Configure automated lead discovery, visitor tracking, and contact enrichment"})]}),e.jsx(O,{children:e.jsxs(js,{defaultValue:"icp",className:"space-y-4",children:[e.jsxs(fs,{className:"grid w-full grid-cols-4",children:[e.jsx(ve,{value:"icp",children:"ICP Setup"}),e.jsx(ve,{value:"tracking",children:"Visitor Tracking"}),e.jsx(ve,{value:"enrichment",children:"Enrichment"}),e.jsx(ve,{value:"directories",children:"Directories"})]}),e.jsxs(ue,{value:"icp",className:"space-y-4",children:[e.jsx("div",{className:"rounded-lg border p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`p-2 rounded-lg ${r?.is_active?"bg-success/10":"bg-muted"}`,children:e.jsx(yt,{className:`h-5 w-5 ${r?.is_active?"text-success":"text-muted-foreground"}`})}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium",children:"Ideal Customer Profile"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r?.is_active?`${r.target_industries?.length||0} industries, ${r.target_buyer_roles?.length||0} buyer personas`:"Define your target market for automated lead discovery"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r?.is_active&&e.jsxs(U,{className:"bg-success text-white",children:[e.jsx(Ce,{className:"h-3 w-3 mr-1"}),"Active"]}),e.jsx(y,{asChild:!0,variant:r?.is_active?"outline":"default",children:e.jsxs(fa,{to:"/leads/icp-setup",children:[e.jsx(Rs,{className:"h-4 w-4 mr-2"}),r?.is_active?"Edit ICP":"Setup ICP"]})})]})]})}),!r?.is_active&&e.jsx("div",{className:"rounded-lg border border-warning/30 bg-warning/5 p-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(pe,{className:"h-5 w-5 text-warning shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium text-warning",children:"ICP Required"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Set up your Ideal Customer Profile to enable automated lead generation. The system uses your ICP to score and filter leads from all sources."})]})]})})]}),e.jsxs(ue,{value:"tracking",className:"space-y-4",children:[e.jsxs("div",{className:"rounded-lg border p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`p-2 rounded-lg ${o?.is_active?"bg-success/10":"bg-muted"}`,children:e.jsx(Is,{className:`h-5 w-5 ${o?.is_active?"text-success":"text-muted-foreground"}`})}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium",children:"Website Visitor Identification"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Identify companies visiting your website and convert them to leads"})]})]}),o&&e.jsx(ye,{checked:o.is_active,onCheckedChange:ee})]}),o?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-lg bg-muted/50 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(B,{className:"text-xs text-muted-foreground",children:"Installation Script"}),e.jsxs(y,{variant:"ghost",size:"sm",onClick:D,children:[e.jsx(Je,{className:"h-3 w-3 mr-1"}),"Copy"]})]}),e.jsx("code",{className:"text-xs text-muted-foreground block whitespace-pre-wrap",children:`<script src="...track-visitor?t=${o.script_id.slice(0,8)}..."><\/script>`})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("p",{children:"Add this script to your website's <head>
137 section to identify visiting companies."}),o.last_activity_at&&e.jsxs("p",{className:"mt-2",children:["Last activity: ",new Date(o.last_activity_at).toLocaleString()]})]})]}):e.jsxs(y,{onClick:A,children:[e.jsx(Ts,{className:"h-4 w-4 mr-2"}),"Generate Tracking Script"]})]}),e.jsx("div",{className:"rounded-lg border border-info/30 bg-info/5 p-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(hs,{className:"h-5 w-5 text-info shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium text-info",children:"IP Resolution Providers"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"For accurate company identification, configure Clearbit or IPinfo in the Enrichment tab. Without a provider, we'll use basic reverse DNS lookup."})]})]})})]}),e.jsxs(ue,{value:"enrichment",className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Connect enrichment providers to find contact information for discovered leads"}),e.jsxs(y,{onClick:()=>x(!0),children:[e.jsx(Ts,{className:"h-4 w-4 mr-2"}),"Add Provider"]})]}),e.jsx("div",{className:"space-y-3",children:f.length===0?e.jsxs("div",{className:"rounded-lg border border-dashed p-6 text-center",children:[e.jsx(Fs,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No enrichment providers configured. Add Apollo, ZoomInfo, or others to enrich leads."})]}):f.map(I=>{const C=dt[I.provider_type];return e.jsx(qe.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:`rounded-lg border p-4 ${I.is_active?"border-success/30 bg-success/5":"bg-muted/30"}`,children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`p-2 rounded-lg ${I.is_active?"bg-success/10":"bg-muted"}`,children:C?.icon||e.jsx(Fs,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium",children:C?.name||I.provider_type}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[I.credits_used>0?`${I.credits_used} credits used`:"Ready to use",I.last_used_at&&e.jsxs(e.Fragment,{children:[" · Last used ",new Date(I.last_used_at).toLocaleDateString()]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{checked:I.is_active,onCheckedChange:$=>Y(I.id,$)}),e.jsx(y,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",onClick:()=>xe(I.id),"aria-label":"Delete",children:e.jsx(Le,{className:"h-4 w-4"})})]})]})},I.id)})})]}),e.jsxs(ue,{value:"directories",className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add industry directories to scrape for ICP-matched leads"}),e.jsxs(y,{onClick:()=>v(!0),children:[e.jsx(Ts,{className:"h-4 w-4 mr-2"}),"Add Source"]})]}),e.jsx("div",{className:"space-y-3",children:p.length===0?e.jsxs("div",{className:"rounded-lg border border-dashed p-6 text-center",children:[e.jsx(Dn,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No directory sources configured. Add industry association lists, Inc 5000, etc."})]}):p.map(I=>e.jsx(qe.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:`rounded-lg border p-4 ${I.is_active?"border-primary/30":"bg-muted/30"}`,children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-lg bg-muted",children:e.jsx(hs,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium",children:I.source_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[I.source_type," · ",I.leads_generated," leads generated",I.last_scraped_at&&e.jsxs(e.Fragment,{children:[" · Scraped ",new Date(I.last_scraped_at).toLocaleDateString()]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(y,{variant:"ghost",size:"icon",asChild:!0,"aria-label":"Open link",children:e.jsx("a",{href:I.source_url,target:"_blank",rel:"noopener noreferrer",children:e.jsx(ns,{className:"h-4 w-4"})})}),e.jsx(y,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",onClick:()=>X(I.id),"aria-label":"Delete",children:e.jsx(Le,{className:"h-4 w-4"})})]})]})},I.id))})]})]})})]}),e.jsx(_e,{open:l,onOpenChange:x,children:e.jsxs(Se,{children:[e.jsxs(ke,{children:[e.jsx(Ae,{children:"Add Enrichment Provider"}),e.jsx(Ee,{children:"Connect an enrichment provider to find contact information for leads"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{children:"Provider"}),e.jsxs(ie,{value:N,onValueChange:S,children:[e.jsx(ce,{children:e.jsx(le,{placeholder:"Select a provider"})}),e.jsx(oe,{children:Object.entries(dt).map(([I,C])=>
137e.jsx(V,{value:I,children:e.jsxs("div",{className:"flex items-center gap-2",children:[C.icon,C.name]})},I))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{children:"API Key"}),e.jsx(se,{type:"password",placeholder:"Enter your API key",value:_,onChange:I=>P(I.target.value)})]})]}),e.jsxs(Ue,{children:[e.jsx(y,{variant:"outline",onClick:()=>x(!1),children:"Cancel"}),e.jsxs(y,{onClick:H,disabled:!N||!_||G,children:[G&&e.jsx(E,{className:"h-4 w-4 mr-2 animate-spin"}),"Connect"]})]})]})}),e.jsx(_e,{open:w,onOpenChange:v,children:e.jsxs(Se,{children:[e.jsxs(ke,{children:[e.jsx(Ae,{children:"Add Directory Source"}),e.jsx(Ee,{children:"Add an industry directory or list to scrape for leads"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{children:"Source Name"}),e.jsx(se,{placeholder:"e.g., Inc 5000 2024",value:j,onChange:I=>M(I.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{children:"URL"}),e.jsx(se,{type:"url",placeholder:"https://...",value:W,onChange:I=>K(I.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{children:"Type"}),e.jsxs(ie,{value:T,onValueChange:L,children:[e.jsx(ce,{children:e.jsx(le,{})}),e.jsxs(oe,{children:[e.jsx(V,{value:"directory",children:"Directory"}),e.jsx(V,{value:"list",children:"Ranked List"}),e.jsx(V,{value:"association",children:"Association Members"}),e.jsx(V,{value:"crunchbase",children:"Crunchbase"}),e.jsx(V,{value:"linkedin",children:"LinkedIn"})]})]})]})]}),e.jsxs(Ue,{children:[e.jsx(y,{variant:"outline",onClick:()=>v(!1),children:"Cancel"}),e.jsxs(y,{onClick:F,disabled:!j||!W||m,children:[m&&e.jsx(E,{className:"h-4 w-4 mr-2 animate-spin"}),"Add Source"]})]})]})})]})}function Zr(){const{currentTenant:s}=ne(),{toast:t}=re(),[r,d]=n.useState(!1),[c,i]=n.useState(""),[o,g]=n.useState(!1),f=s?.name||"",h=c.toLowerCase()===f.toLowerCase(),p=async()=>{if(!(!s||!h)){g(!0);try{const{data:u,error:l}=await b.functions.invoke("reset-tenant-data",{body:{tenantId:s.id}});if(l)throw l;if(u?.error)throw new Error(u.error);t({title:"Tenant data reset complete",description:`${u.total_deleted} records cleared. Your team and integrations are intact.`}),d(!1),i("")}catch(u){t({title:"Reset failed",description:u.message,variant:"destructive"})}finally{g(!1)}}};return e.jsxs(vs,{open:r,onOpenChange:u=>{d(u),u||i("")},children:[e.jsx(St,{asChild:!0,children:e.jsxs(y,{variant:"destructive",className:"gap-2",children:[e.jsx(Le,{className:"h-4 w-4"}),"Reset All Tenant Data"]})}),e.jsxs(ws,{children:[e.jsxs(Ns,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(De,{className:"h-5 w-5 text-destructive"}),"Reset All Tenant Data"]}),e.jsx(_s,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{children:["This will ",e.jsx("strong",{children:"permanently delete all business data"})," from"," ",e.jsx("strong",{children:f}),", including:"]}),e.jsxs("ul",{className:"list-disc list-inside text-sm space-y-1",children:[e.jsx("li",{children:"All clients, prospects, and leads"}),e.jsx("li",{children:"All projects, proposals, and deliverables"}),e.jsx("li",{children:"All time entries, invoices, and expenses"}),e.jsx("li",{children:"All knowledge documents and service catalog"}),e.jsx("li",{children:"All AI conversations, battlecards, and analytics"}),e.jsx("li",{children:"All brand settings, rate cards, and configurations"})]}),e.jsxs("p",{className:"font-medium",children:["Your team members (",s?.name,") and integrations will be preserved."]}),e.jsxs("div",{className:"pt-2 space-y-2",children:[e.jsxs(B,{htmlFor:"confirm-reset",children:["Type ",e.jsx("strong",{children:f})," to confirm:"]}),e.jsx(se,{id:"confirm-reset",value:c,onChange:u=>i(u.target.value),placeholder:f,autoComplete:"off"})]})]})})]}),e.jsxs(Ss,{children:[e.jsx(Cs,{disabled:o,children:"Cancel"}),e.jsxs(y,{variant:"destructive",onClick:p,disabled:!h||o,children:[o?e.jsx(E,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(Le,{className:"h-4 w-4 mr-2"}),o?"Resetting...":"Reset All Data"]})]})]})]})}function Xr(){const{currentTenant:s}=ne(),{toast:t}=re(),[r,d]=n.useState(!1),[c,i]=n.useState(""),[o,g]=n.useState(!1),f=s?.name||"",h=c.toLowerCase()===f.toLowerCase(),p=async()=>
137{if(!(!s||!h)){g(!0);try{const{data:u,error:l}=await b.functions.invoke("fresh-start-tenant",{body:{tenantId:s.id}});if(l)throw l;if(u?.error)throw new Error(u.error);t({title:"Fresh start complete",description:`${u.total_deleted} records cleared. Your team, integrations, service catalog, brand, and rate table are intact.`}),d(!1),i(""),setTimeout(()=>window.location.reload(),1500)}catch(u){t({title:"Fresh start failed",description:u.message,variant:"destructive"})}finally{g(!1)}}};return e.jsxs(vs,{open:r,onOpenChange:u=>{d(u),u||i("")},children:[e.jsx(St,{asChild:!0,children:e.jsxs(y,{variant:"destructive",className:"gap-2",children:[e.jsx(Ft,{className:"h-4 w-4"}),"Fresh Start"]})}),e.jsxs(ws,{children:[e.jsxs(Ns,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(De,{className:"h-5 w-5 text-destructive"}),"Fresh Start â Go Live"]}),e.jsx(_s,{asChild:!0,children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{children:["This will ",e.jsx("strong",{children:"permanently delete all operational data"})," from"," ",e.jsx("strong",{children:f})," so you can start fresh for production use."]}),e.jsx("p",{className:"font-medium text-foreground",children:"What gets wiped:"}),e.jsxs("ul",{className:"list-disc list-inside text-sm space-y-1",children:[e.jsx("li",{children:"All clients, prospects, and leads"}),e.jsx("li",{children:"All projects, tasks, deliverables, and time entries"}),e.jsx("li",{children:"All proposals, invoices, and billing data"}),e.jsx("li",{children:"All knowledge base articles and embeddings"}),e.jsx("li",{children:"All competitive intelligence and battlecards"}),e.jsx("li",{children:"All AI conversations and briefings"}),e.jsx("li",{children:"All finance analytics and workforce data"}),e.jsx("li",{children:"All document studio content"}),e.jsx("li",{children:"All notifications and approval history"})]}),e.jsx("p",{className:"font-medium text-foreground",children:"What stays:"}),e.jsxs("ul",{className:"list-disc list-inside text-sm space-y-1 text-success",children:[e.jsx("li",{children:"Team members and profiles"}),e.jsx("li",{children:"All integrations (Microsoft, Slack, QBO, etc.)"}),e.jsx("li",{children:"Service catalog"}),e.jsx("li",{children:"Brand identity and settings"}),e.jsx("li",{children:"Rate table and org levels"}),e.jsx("li",{children:"Deliverable templates"}),e.jsx("li",{children:"MSA/signing settings"}),e.jsx("li",{children:"Practices configuration"})]}),e.jsxs("div",{className:"pt-2 space-y-2",children:[e.jsxs(B,{htmlFor:"confirm-fresh-start",children:["Type ",e.jsx("strong",{children:f})," to confirm:"]}),e.jsx(se,{id:"confirm-fresh-start",value:c,onChange:u=>i(u.target.value),placeholder:f,autoComplete:"off"})]})]})})]}),e.jsxs(Ss,{children:[e.jsx(Cs,{disabled:o,children:"Cancel"}),e.jsxs(y,{variant:"destructive",onClick:p,disabled:!h||o,children:[o?e.jsx(E,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(Ft,{className:"h-4 w-4 mr-2"}),o?"Wiping data...":"Go Live â Fresh Start"]})]})]})]})}function ei(){return e.jsxs(R,{children:[e.jsxs(J,{children:[e.jsxs(Z,{className:"flex items-center gap-2",children:[e.jsx(Xe,{className:"h-5 w-5"}),"Personal Email Connections"]}),e.jsx(ae,{children:"Connect your personal account to send emails as yourself"})]}),e.jsxs(O,{className:"space-y-4",children:[e.jsxs(Ne,{className:"border-info/30 bg-info-soft",children:[e.jsx(us,{className:"h-4 w-4 text-info"}),e.jsx(be,{className:"text-info",children:"These connections are personal to you and allow the system to send emails on your behalf. Organization integrations (above) handle background sync only."})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(Bn,{}),e.jsx(Gn,{}),e.jsx(Un,{})]})]})]})}const mt=[{id:"account",label:"Account",icon:e.jsx(oa,{className:"h-4 w-4"})},{id:"notifications",label:"Notifications",icon:e.jsx(Os,{className:"h-4 w-4"})},{id:"appearance",label:"Appearance",icon:e.jsx(da,{className:"h-4 w-4"})},{id:"integrations",label:"Integrations",icon:e.jsx(Vs,{className:"h-4 w-4"})},{id:"organization",label:"Organization",icon:e.jsx(We,{className:"h-4 w-4"}),adminOnly:!0},{id:"billing",label:"Billing & Plans",icon:e.jsx(Ks,{className:"h-4 w-4"}),adminOnly:!0},{id:"security",label:"Security",icon:e.jsx(Ve,{className:"h-4 w-4"})},{id:"advanced",label:"Advanced",icon:e.jsx(Tn,{className:"h-4 w-4"}),adminOnly:!0},{id:"platform-health",label:"Platform Health",icon:e.jsx(ma,{className:"h-4 w-4"}),adminOnly:!0}];function Ll(){const{t:s}=la("settings"),{user:t}=jt(),{toast:r}=re(),[d,c]=n.useState(!1),{isCompact:i,setCompact:o}=Sa(),{isStarter:g}=kn(),{hideProFeatures:f,toggleProFeatures:h}=bn(),{isAdmin:p}=Pa(),{isWidgetHidden:u,hideWidget:l,showWidget:x}=Wa(),[w,v]=n.useState(()=>{const D=window.location.hash.replace("#","");return mt.filter(Y=>!Y.adminOnly).map(Y=>Y.id).includes(D)?D:"account"}),[N,S]=n.useState(""),[_,P]=n.useState("role-default");n.useEffect(()=>{t?.id&&P(Ca(t.id))},[t?.id]);const G=D=>{P(D),t?.id&&Aa(t.id,D)};n.useEffect(()=>{if(!p)return;const D=window.location.hash.replace("#","");mt.map(Y=>Y.id).includes(D)&&D!==w&&v(D)}
137,[p]);const a=D=>{v(D),window.history.replaceState(null,"",`#${D}`)},[j,M]=n.useState(""),[W,K]=n.useState(""),[T,L]=n.useState(!1),[m,k]=n.useState(null),q=n.useMemo(()=>mt.filter(D=>!D.adminOnly||p),[p]);n.useEffect(()=>{(async()=>{if(!t?.id)return;const{data:H}=await b.from("profiles").select("id, full_name, title").eq("user_id",t.id).single();H&&(k(H.id),M(H.full_name||""),K(H.title||""))})()},[t?.id]),n.useEffect(()=>{const D=localStorage.getItem("theme");if(D==="dark")c(!0),document.documentElement.classList.add("dark");else if(D==="light")c(!1),document.documentElement.classList.remove("dark");else{const H=window.matchMedia("(prefers-color-scheme: dark)").matches;c(H),H&&document.documentElement.classList.add("dark")}},[]);const A=D=>{c(D),D?(document.documentElement.classList.add("dark"),localStorage.setItem("theme","dark")):(document.documentElement.classList.remove("dark"),localStorage.setItem("theme","light"))},ee=async()=>{if(!m){r({title:"Profile not found",variant:"destructive"});return}L(!0);try{const{error:D}=await b.from("profiles").update({full_name:j.trim(),title:W.trim()}).eq("id",m);if(D)throw D;r({title:"Profile updated"})}catch(D){console.error("Error saving profile:",D),r({title:"Failed to save profile",variant:"destructive"})}finally{L(!1)}};return n.useEffect(()=>{if(!N||N.length<2)return;const D=N.toLowerCase(),H={account:["profile","name","email","job title","language"],notifications:["notifications","briefing","task","reminder","alerts"],appearance:["dark mode","compact","theme","appearance","pro features","widgets","dashboard"],integrations:["integrations","salesforce","hubspot","teamwork","qbo","quickbooks","calendar","connections"],organization:["organization","margin","msa","signing","performance","industry","knowledge","lead","compliance","dcaa","team","domains","access"],billing:["billing","subscription","plan","payment"],security:["security","password","2fa","two-factor"],advanced:["danger","reset","fresh start","wipe"]};for(const[Y,xe]of Object.entries(H))if(xe.some(F=>F.includes(D))&&q.some(F=>F.id===Y)){a(Y);return}},[N,q]),e.jsxs(qe.div,{initial:{opacity:0}
137,animate:{opacity:1},className:"space-y-6 max-w-4xl",children:[e.jsxs("div",{className:"flex items-center justify-between","data-tour":"settings-header",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold tracking-tight",children:s("title")}),e.jsx("p",{className:"text-muted-foreground",children:s("subtitle")})]}),e.jsxs("div",{className:"relative w-64",children:[e.jsx(et,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(se,{placeholder:"Search settings...",value:N,onChange:D=>S(D.target.value),className:"pl-9 h-9"})]})]}),e.jsxs(js,{value:w,onValueChange:a,className:"w-full",children:[e.jsx(fs,{className:"w-full justify-start flex-wrap h-auto gap-1 p-1.5",children:q.map(D=>e.jsxs(ve,{value:D.id,className:"gap-1.5 text-xs sm:text-sm",children:[D.icon,e.jsx("span",{className:"hidden sm:inline",children:D.label})]},D.id))}),e.jsxs(ue,{value:"account",className:"space-y-6 mt-6",children:[e.jsx(Yr,{}),e.jsxs(R,{children:[e.jsxs(J,{children:[e.jsxs(Z,{className:"flex items-center gap-2",children:[e.jsx(oa,{className:"h-5 w-5"}),"Profile"]}),e.jsx(ae,{children:"Update your personal information"})]}),e.jsxs(O,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{htmlFor:"name",children:"Full Name"}),e.jsx(se,{id:"name",value:j,onChange:D=>M(D.target.value),placeholder:"Your name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{htmlFor:"email",children:"Email"}),e.jsx(se,{id:"email",type:"email",defaultValue:t?.email||"",disabled:!0})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{htmlFor:"title",children:"Job Title"}),e.jsx(se,{id:"title",value:W,onChange:D=>K(D.target.value),placeholder:"e.g., Senior Consultant"})]}),e.jsx(y,{onClick:ee,disabled:T,children:T?"Saving...":"Save Changes"})]})]})]}),e.jsxs(ue,{value:"notifications",className:"space-y-6 mt-6",children:[e.jsx(Vr,{}),e.jsxs(R,{children:[e.jsxs(J,{children:[e.jsx(Z,{className:"text-base",children:"Alert Rules"}),e.jsx(ae,{children:"Set up custom alerts for budget, time, and billing thresholds"})]}),e.jsx(O,{children:e.jsx(Wr,{})})]})]}),e.jsxs(ue,{value:"appearance",className:"space-y-6 mt-6",children:[e.jsxs(R,{children:[e.jsxs(J,{children:[e.jsxs(Z,{className:"flex items-center gap-2",children:[e.jsx(da,{className:"h-5 w-5"}),"Theme & Layout"]}),e.jsx(ae,{children:"Customize the look and feel"})]}),e.jsxs(O,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[d?e.jsx(Ln,{className:"h-5 w-5 text-muted-foreground"}):e.jsx(_n,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Dark Mode"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Use dark theme for the interface"})]})]}),e.jsx(ye,{checked:d,onCheckedChange:A})]}),e.jsx(me,{}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Compact View"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Reduce spacing across the entire interface"})]}),e.jsx(ye,{checked:i,onCheckedChange:o})]}),e.jsx(me,{}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Landing Page"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Where you land after signing in"})]}),e.jsxs(ie,{value:_,onValueChange:G,children:[e.jsx(ce,{className:"w-48","aria-label":"Landing page",children:e.jsx(le,{})}),e.jsx(oe,{children:ka.map(D=>e.jsx(V,{value:D.value,children:D.label},D.value))})]})]}),g&&e.jsxs(e.Fragment,{children:[e.jsx(me,{}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[f?e.jsx(Qs,{className:"h-5 w-5 text-muted-foreground"}):e.jsx(Is,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Hide Pro Features"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Hide locked Pro features from the navigation sidebar"})]})]}),e.jsx(ye,{checked:f,onCheckedChange:h})]})]})]})]}),e.jsxs(R,{children:[e.jsxs(J,{children:[e.jsxs(Z,{className:"flex items-center gap-2",children:[e.jsx(An,{className:"h-5 w-5"}),"Dashboard Widgets"]}),e.jsx(ae,{children:"Choose which widgets appear on your dashboard"})]}),e.jsx(O,{className:"space-y-4",children:[{key:"work_scheduler",label:"Smart Work Scheduler",desc:"AI-
137powered time block suggestions for your day"},{key:"quick_actions",label:"Quick Actions",desc:"Role-based shortcut buttons"},{key:"this_week_stats",label:"This Week Stats",desc:"Weekly hours and billing summary"},{key:"ai_insight",label:"AI Insights",desc:"AI-generated recommendations and alerts"},{key:"learning_insights",label:"Learning Insights",desc:"Patterns and lessons from completed work"}].map(({key:D,label:H,desc:Y},xe)=>e.jsxs("div",{children:[xe>0&&e.jsx(me,{className:"mb-4"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:H}),e.jsx("p",{className:"text-sm text-muted-foreground",children:Y})]}),e.jsx(ye,{checked:!u(D),onCheckedChange:F=>F?x(D):l(D)})]})]},D))})]})]}),e.jsxs(ue,{value:"integrations",className:"space-y-6 mt-6",children:[e.jsxs("div",{"data-tour":"integrations",children:[e.jsx(yr,{}),e.jsx("div",{className:"mt-4",children:e.jsx(Nr,{})})]}),e.jsx(ei,{}),e.jsx(Qn,{}),p&&e.jsx(wr,{})]}),p&&e.jsxs(ue,{value:"organization",className:"space-y-6 mt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(We,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Organization Settings"}),e.jsx(U,{variant:"secondary",className:"text-xs",children:"Admin"})]}),e.jsx(sr,{}),e.jsx(Jr,{}),e.jsx(Jn,{}),e.jsx(Zn,{}),e.jsx(Xn,{}),e.jsx(Mr,{}),e.jsx(Br,{}),e.jsxs(R,{children:[e.jsxs(J,{children:[e.jsxs(Z,{className:"flex items-center gap-2",children:[e.jsx(Pn,{className:"h-5 w-5"}),"Knowledge Hub"]}),e.jsx(ae,{children:"Configure your knowledge management system"})]}),e.jsx(O,{children:e.jsx(qr,{})})]}),e.jsx(_r,{})]}),p&&e.jsxs(ue,{value:"billing",className:"space-y-6 mt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Ks,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Billing & Plans"}),e.jsx(U,{variant:"secondary",className:"text-xs",children:"Admin"})]}),e.jsx(Cr,{}),e.jsx(br,{})]}),e.jsx(ue,{value:"security",className:"space-y-6 mt-6",children:e.jsxs(R,{children:[e.jsxs(J,{children:[e.jsxs(Z,{className:"flex items-center gap-2",children:[e.jsx(Ve,{className:"h-5 w-5"}),"Security"]}),e.jsx(ae,{children:"Manage your account security"})]}),e.jsxs(O,{className:"space-y-4",children:[e.jsx(zr,{}),e.jsx(me,{}),e.jsx(Rr,{})]})]})}),p&&e.jsx(ue,{value:"advanced",className:"space-y-6 mt-6",children:e.jsxs(R,{className:"border-destructive/50",children:[e.jsxs(J,{children:[e.jsxs(Z,{className:"flex items-center gap-2 text-destructive",children:[e.jsx(Ve,{className:"h-5 w-5"}),"Danger Zone"]}),e.jsx(ae,{children:"Destructive actions that cannot be undone. Admin access required."})]}),e.jsxs(O,{children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Fresh Start â Go Live"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Wipe all operational data while keeping team, integrations, service catalog, brand, and rate table."})]}),e.jsx(Xr,{})]}),e.jsx(me,{}),e.jsxs("div",{className:"flex items-center justify-between mt-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Full Reset"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Wipe all business data including configuration. Nuclear option."})]}),e.jsx(Zr,{})]})]})]})}),p&&e.jsx(ue,{value:"platform-health",className:"space-y-6 mt-6",children:e.jsx($r,{})})]})]})}export{Ll as default};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.