@realtimex/email-automator 2.23.2 → 2.23.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -105,7 +105,7 @@ What can I assist you with?`,"agent.composer.placeholder":"Ask a question, or cl
|
|
|
105
105
|
2. Sign in and authorize the app
|
|
106
106
|
3. Copy the authorization code shown
|
|
107
107
|
4. Paste it below`,"config.gmail.authCode":"Authorization Code","config.gmail.clientIdPlaceholder":"xxx.apps.googleusercontent.com","config.gmail.clientSecretPlaceholder":"GOCSPX-...","config.gmail.authCodePlaceholder":"4/0AQlEd8x...","config.rules.actionsHelp":"Select one or more actions to execute when the rule matches","config.rules.instructionsPlaceholder":"e.g. Tell them I'm busy until Friday, but interested in the proposal.","config.rules.attachmentsOptional":"Attachments (Optional)","config.rules.days":"days","config.rules.placeholder.domain":"rta.vn","config.rules.placeholder.email":"john@example.com","config.rules.category.newsletter":"Newsletter","config.rules.category.spam":"Spam","config.rules.category.promotional":"Promotional","config.rules.category.transactional":"Transactional","config.rules.category.social":"Social","config.rules.category.support":"Support","config.rules.category.client":"Client","config.rules.category.internal":"Internal","config.rules.category.personal":"Personal","config.rules.category.other":"Other","config.rules.sentiment.positive":"Positive","config.rules.sentiment.neutral":"Neutral","config.rules.sentiment.negative":"Negative","config.rules.priority.high":"High","config.rules.priority.medium":"Medium","config.rules.priority.low":"Low","config.voice.title":"Voice & Speech","config.voice.desc":"Configure text-to-speech for AI responses","config.voice.autoTitle":"Auto-Speak AI Responses","config.voice.autoHelp":"Automatically read AI responses aloud using text-to-speech","config.voice.provider":"TTS Provider","config.voice.providerHelp":"Select the text-to-speech provider","config.voice.loadingProviders":"Loading providers...","config.voice.voice":"Voice","config.voice.selectVoice":"Select a voice","config.voice.noVoices":"No voices available","config.voice.voiceHelp":"Choose the voice personality for speech synthesis","config.voice.speed":"Speed","config.voice.speedSlow":"0.5x (Slower)","config.voice.speedFast":"2.0x (Faster)","config.voice.quality":"Quality","config.voice.qualityLow":"1 (Lower quality, faster)","config.voice.qualityHigh":"20 (Higher quality, slower)","config.voice.test":"Test","config.voice.save":"Save Settings","config.voice.testText":"Hello! This is a test of the text-to-speech system.","config.voice.piperLocal":"Piper (Local)","config.voice.toast.providersFailed":"Failed to load TTS providers. Ensure RealTimeX Desktop is running.","config.voice.toast.serviceFailed":"Failed to connect to TTS service","config.voice.toast.testFailed":"Failed to test text-to-speech","config.voice.toast.saved":"Voice & Speech settings saved","config.voice.toast.saveFailed":"Failed to save settings","config.voice.toast.autoOn":"Auto-speak AI responses enabled","config.voice.toast.autoOff":"Auto-speak AI responses disabled","config.voice.toast.updateFailed":"Failed to update setting","config.agent.systemInstruction":"You are the Configuration Wizard. Guide the user through setting up their accounts, rules, and system preferences. Explain what each setting does and help them troubleshoot connections.","config.toast.providersFailed":"Failed to load providers","config.toast.providersFailedFallback":"Failed to load providers. Using defaults.","config.toast.embedProvidersFailed":"Failed to load embedding providers","config.toast.embedProvidersFailedFallback":"Failed to load embedding providers. Using defaults.","config.toast.connectionFailed":"Connection failed","config.toast.systemRuleMissing":"System rule not found. Please sync your database.","config.toast.startConnectionFailed":"Failed to start connection. Please ensure you are logged in.","config.toast.startGmailFailed":"Failed to start Gmail connection","config.toast.detectedDesktopCreds":"Detected Desktop app credentials","config.toast.detectedWebCreds":"Detected Web app - make sure redirect URI is configured in Google Cloud Console","config.toast.missingGmailCreds":"Please provide both Client ID and Client Secret","config.toast.authorizeAndPaste":"Please authorize in the opened tab, then paste the code here","config.toast.oauthUrlFailed":"Failed to get OAuth URL","config.toast.saveCredsFailed":"Failed to save credentials","config.toast.missingAuthCode":"Please paste the authorization code","config.toast.gmailConnected":"Gmail account connected successfully!","config.toast.gmailConnectFailed":"Failed to connect Gmail","config.toast.missingOutlookClientId":"Please provide the Client ID","config.toast.deviceFlowFailed":"Failed to start device flow","config.toast.outlookStartFailed":"Failed to start Outlook connection","config.toast.outlookConnected":"Outlook account connected","config.toast.connectionTimedOut":"Connection timed out. Please try again.","config.toast.ruleNameRequired":"Please name your rule","config.toast.ruleActionRequired":"Please select at least one action","config.toast.ruleUpdated":"Rule updated","config.toast.ruleCreated":"Rule created","config.toast.ruleUpdateFailed":"Failed to update rule","config.toast.ruleCreateFailed":"Failed to create rule","config.toast.ruleSaveError":"An error occurred while saving the rule","config.toast.disconnectConfirm":"Are you sure you want to disconnect this account?","config.toast.accountDisconnected":"Account disconnected","config.toast.settingsSaved":"Settings saved","config.toast.fileUploaded":"File uploaded","config.toast.fileUploadFailed":"Failed to upload file","config.rules.edit":"Edit Rule","config.rules.create":"Create Rule","config.rules.createRule":"Create Rule","config.rules.desc":"Define conditions and actions for email automation","config.rules.name":"Rule Name","config.rules.namePlaceholder":"e.g., Archive Newsletters","config.rules.description":"Description","config.rules.descriptionPlaceholder":"What this rule does","config.rules.semanticHelp":"AI will match emails based on this description","config.rules.intent":"Intent","config.rules.intentPlaceholder":"What should happen when this rule triggers","config.rules.intentHelp":"Used to generate appropriate responses","config.rules.conditionField":"Condition Field","config.rules.aiAnalysis":"AI Analysis","config.rules.metadata":"Metadata","config.rules.category":"Category","config.rules.sentiment":"Sentiment","config.rules.priority":"Priority","config.rules.senderEmail":"Sender Email","config.rules.senderDomain":"Sender Domain","config.rules.senderContains":"Sender Contains","config.rules.subjectContains":"Subject Contains","config.rules.bodyContains":"Body Contains","config.rules.equalsValue":"Equals Value","config.rules.keywordsPlaceholder":"Enter keywords...","config.rules.olderThan":"Only if email is older than (days)","config.rules.olderThanHelp":"Leave empty or 0 to apply immediately","config.rules.performActions":"Then Perform Actions","config.rules.draftInstructions":"Draft Instructions","config.rules.contextHelp":"Specific context for AI to use when drafting","config.rules.addAttachment":"Add Attachment","config.rules.attachmentHelp":"Files will be attached to generated drafts","config.rules.uploading":"Uploading...","config.rules.saveChanges":"Save Changes","account.title":"Account Settings","account.subtitle":"Manage your profile and preferences","account.profile":"Profile","account.security":"Security","account.database":"Supabase","account.logout":"Logout","account.logoutSuccess":"Logged out successfully","account.version":"Version","account.profile.title":"Profile Information","account.profile.desc":"Update your personal information","account.profile.firstName":"First Name","account.profile.firstNamePlaceholder":"John","account.profile.lastName":"Last Name","account.profile.lastNamePlaceholder":"Doe","account.profile.email":"Email","account.profile.emailHelp":"This is your login email and cannot be changed","account.profile.sounds":"Sound & Haptic Feedback","account.profile.soundsHelp":"Play sounds for email notifications","account.profile.soundsEnabled":"Sounds enabled","account.profile.soundsDisabled":"Sounds disabled","account.profile.updated":"Profile updated successfully","account.profile.avatarUpdated":"Avatar updated successfully","account.profile.avatarError":"Failed to update avatar","account.security.title":"Security","account.security.desc":"Update your password","account.security.newPassword":"New Password","account.security.confirmPassword":"Confirm Password","account.security.updatePassword":"Update Password","account.security.enterPassword":"Please enter a password","account.security.passwordsMismatch":"Passwords do not match","account.security.passwordTooShort":"Password must be at least 6 characters","account.security.passwordChanged":"Password changed successfully","account.database.title":"Database Connection","account.database.desc":"Manage your Supabase connection","account.database.connected":"Connected","account.database.noConnection":"No Connection","account.database.configureHelp":"Configure your Supabase connection in the Setup Wizard","account.database.anonKey":"Anon Key","account.database.envAlert":"Connection configured via environment variables","account.database.changeConnection":"Change Connection","account.database.clearConfig":"Clear Configuration","account.database.clearConfirm":"Are you sure you want to clear your database configuration?","account.database.setup":"Setup Database","trace.runTrace":"Sync Run Trace","trace.fullLogFor":"Full log for account: {email}","trace.historicalLog":"Historical log for this synchronization run.","trace.loadingTrace":"Loading trace...","trace.noTraceEvents":"No granular trace events found for this run.","analytics.title":"Analytics Dashboard","analytics.totalEmails":"Total Emails","analytics.spamCaught":"Spam Caught","analytics.actionsTaken":"Actions Taken","analytics.accounts":"Accounts","analytics.categories":"Email Categories","analytics.recentActivity":"Recent Sync Activity","analytics.noActivity":"No sync activity yet","analytics.emails":"{count} emails","analytics.deleted":"{count} deleted","analytics.drafted":"{count} drafted","autopilot.title":"Auto-Pilot Rules","autopilot.rulesEnabled":"{enabled} of {total} rules enabled","autopilot.loadingRules":"Loading rules...","autopilot.loadError":"Failed to load rules","autopilot.deleteConfirm":"Are you sure you want to delete this rule?","autopilot.ruleDeleted":"Rule deleted","autopilot.ruleDeleteFailed":"Failed to delete rule","autopilot.ruleDeleteError":"An error occurred while deleting the rule","autopilot.ruleUpdated":"Rule updated","autopilot.ruleCreated":"Rule created","autopilot.ruleUpdateFailed":"Failed to update rule","autopilot.ruleCreateFailed":"Failed to create rule","autopilot.ruleSaveError":"An error occurred while saving the rule","autopilot.fileUploaded":"File uploaded","autopilot.fileUploadFailed":"Failed to upload file","autopilot.noRulesTitle":"No Rules Yet","autopilot.noRulesDesc":"Rules will be automatically created when you sign up or connect your first email account.","autopilot.addCustomRule":"Add Custom Rule","autopilot.refresh":"Refresh","autopilot.infoDesc":"Auto-Pilot rules use AI to automatically organize your inbox. Toggle any rule on or off to customize behavior.","autopilot.customRules":"Custom Rules","autopilot.customRulesDesc":"Rules you've created manually","autopilot.category.email_organization.label":"Email Organization","autopilot.category.email_organization.desc":"Automatically organize common email types","autopilot.category.priority_alerts.label":"Priority & Alerts","autopilot.category.priority_alerts.desc":"Surface urgent and important messages","autopilot.category.development.label":"Development","autopilot.category.development.desc":"GitHub, CI/CD, and dev tool notifications","autopilot.category.sales_business.label":"Sales & Business","autopilot.category.sales_business.desc":"Lead management and business communications","autopilot.category.operations.label":"Operations","autopilot.category.operations.desc":"Support, internal requests, and system alerts","autopilot.enabledCount":"({enabled}/{total} enabled)","autopilot.badge":"Auto-Pilot","autopilot.editRuleTooltip":"Edit Rule","autopilot.deleteRuleTooltip":"Delete Rule","autopilot.triggeredToday":"{count} today","autopilot.editDialog.editTitle":"Edit Rule","autopilot.editDialog.createTitle":"Create Custom Rule","autopilot.editDialog.desc":"Define a condition based on AI analysis to trigger an action.","autopilot.editDialog.ruleName":"Rule Name","autopilot.editDialog.namePlaceholder":"e.g. Archive Newsletters","autopilot.editDialog.description":"Description","autopilot.editDialog.descPlaceholder":"e.g. Handle all marketing newsletters and promotional content from subscription services","autopilot.editDialog.descriptionHelp":"Describe what this rule is for. The AI uses this to semantically match emails.","autopilot.editDialog.intent":"Intent","autopilot.editDialog.intentPlaceholder":"e.g. Politely decline all sales pitches","autopilot.editDialog.intentHelp":"The goal of this rule. Used to generate appropriate draft replies.","autopilot.editDialog.conditionField":"If Condition Field","autopilot.editDialog.aiAnalysisGroup":"AI Analysis","autopilot.editDialog.metadataGroup":"Metadata","autopilot.editDialog.category":"Category","autopilot.editDialog.sentiment":"Sentiment","autopilot.editDialog.priority":"Priority","autopilot.editDialog.senderEmail":"Specific Email (Exact)","autopilot.editDialog.senderDomain":"Email Domain (@...)","autopilot.editDialog.senderContains":"Sender contains...","autopilot.editDialog.subjectContains":"Subject contains...","autopilot.editDialog.bodyContains":"Body contains...","autopilot.editDialog.equalsValue":"Equals Value","autopilot.editDialog.cat.newsletter":"Newsletter","autopilot.editDialog.cat.news":"News","autopilot.editDialog.cat.spam":"Spam","autopilot.editDialog.cat.promotional":"Promotional","autopilot.editDialog.cat.transactional":"Transactional","autopilot.editDialog.cat.social":"Social","autopilot.editDialog.cat.support":"Support","autopilot.editDialog.cat.client":"Client","autopilot.editDialog.cat.internal":"Internal","autopilot.editDialog.cat.personal":"Personal","autopilot.editDialog.cat.other":"Other","autopilot.editDialog.sent.positive":"Positive","autopilot.editDialog.sent.neutral":"Neutral","autopilot.editDialog.sent.negative":"Negative","autopilot.editDialog.prio.high":"High","autopilot.editDialog.prio.medium":"Medium","autopilot.editDialog.prio.low":"Low","autopilot.editDialog.keywordsPlaceholder":"Keywords...","autopilot.editDialog.olderThan":"Only if email is older than... (Optional)","autopilot.editDialog.days":"days","autopilot.editDialog.olderThanHelp":"Leave empty or 0 to apply rule immediately upon receipt.","autopilot.editDialog.performActions":"Then Perform Action(s)","autopilot.editDialog.actionsDesc":"Select one or more actions to execute when the rule matches","autopilot.editDialog.action.archive":"Archive Email","autopilot.editDialog.action.delete":"Delete Email","autopilot.editDialog.action.draft":"Draft Reply","autopilot.editDialog.action.star":"Star / Flag","autopilot.editDialog.draftInstructions":"Draft Instructions (Context)","autopilot.editDialog.draftInstPlaceholder":"e.g. Tell them I'm busy until Friday, but interested in the proposal.","autopilot.editDialog.draftInstHelp":"Specific context for the AI ghostwriter.","autopilot.editDialog.attachments":"Attachments (Optional)","autopilot.editDialog.uploading":"Uploading...","autopilot.editDialog.addAttachment":"Add Attachment","autopilot.editDialog.attachmentsHelp":"Files will be attached to every draft generated by this rule.","autopilot.onboarding.allSet":"All Set!","autopilot.onboarding.enabledDesc":"We've enabled {count} automation rules for you","autopilot.onboarding.rules":"rules","autopilot.onboarding.universalDesc":"Essential rules that help everyone stay organized","autopilot.onboarding.executiveDesc":"Focus on high-priority communications and strategic matters","autopilot.onboarding.developerDesc":"Surface critical alerts and filter tool noise","autopilot.onboarding.salesDesc":"Prioritize leads and customer communications","autopilot.onboarding.operationsDesc":"Organize tickets and internal communications","autopilot.onboarding.tip":"Tip: All rules are enabled by default, but you can customize or disable them anytime in the Auto-Pilot section.","autopilot.onboarding.start":"Start Using Email Automator →","autopilot.role.title":"One Last Step!","autopilot.role.subtitle":"What best describes your role? We'll set up the right automation rules for you.","autopilot.role.executive.label":"Executive / Leadership","autopilot.role.executive.desc":"Focus on VIPs, contracts, and strategic communications","autopilot.role.executive.preview":"VIP Client Prioritizer;Travel Organizer;Legal & Contracts","autopilot.role.sales.label":"Sales / Business Development","autopilot.role.sales.desc":"Prioritize leads and customer communications","autopilot.role.sales.preview":"Customer Questions;CRM Organizer;Proposal Tracker","autopilot.role.developer.label":"Developer / Engineer","autopilot.role.developer.desc":"Surface critical alerts and filter tool noise","autopilot.role.developer.preview":"System Alerts;Code Reviews;Project Management","autopilot.role.operations.label":"Operations / Support","autopilot.role.operations.desc":"Organize tickets and internal communications","autopilot.role.operations.preview":"Support Tickets;System Monitoring;Internal Comms","autopilot.role.marketing.label":"Marketing","autopilot.role.marketing.desc":"Track campaigns and customer engagement","autopilot.role.marketing.preview":"Campaign Tracking;Analytics Reports;Social Media","autopilot.role.other.label":"Other / Manual Setup","autopilot.role.other.desc":"I'll configure my own automation rules","autopilot.role.includes":"Includes:","autopilot.role.skip":"Skip for now","autopilot.role.settingUp":"Setting up...","autopilot.role.continue":"Continue →","terminal.title":"Agent Terminal","terminal.liveActivity":"Live Activity","terminal.syncing":"SYNCING","terminal.live":"LIVE","terminal.stopSync":"STOP SYNC","terminal.clear":"Clear","terminal.waiting":"Waiting for agent activity...","terminal.details":"Details","terminal.useless":"USELESS","terminal.relevant":"RELEVANT","terminal.executionComplete":"Execution Complete","terminal.batchFinished":"Batch Sync Finished","terminal.processed":"Processed","terminal.actions":"Actions","terminal.action.delete":"Moved to Trash","terminal.action.archive":"Archived Email","terminal.action.draft":"Drafted Reply","terminal.action.star":"Starred Email","terminal.tokens":"Tokens: {promptTokens} (in) + {completionTokens} (out)","terminal.itemsFailed":"⚠️ {count} items failed to process.","terminal.detail.systemPrompt":"System Prompt","terminal.detail.inputContent":"Input Content (Cleaned)","terminal.detail.rawLLMOutput":"Raw LLM JSON Output","terminal.detail.rawResponse":"Raw Response (from Error)","terminal.state.running":"Running","terminal.state.finished":"Finished","terminal.state.sync":"Sync","terminal.state.fetching":"Fetching","terminal.state.error":"Error","terminal.state.skipped":"Skipped","terminal.state.ingesting":"Ingesting","terminal.state.storage_error":"Storage Error","terminal.state.database_error":"Database Error","terminal.state.ingested":"Ingested","terminal.state.processing":"Processing","terminal.state.rules_matched":"Rules Matched","terminal.state.actions_resolved":"Actions Resolved","terminal.state.low_confidence":"Low Confidence","terminal.state.no_match":"No Match","terminal.state.processing_failed":"Processing Failed","terminal.state.multi_action":"Multi-Action","terminal.state.skipped_draft":"Skipped Draft","terminal.state.thinking":"Thinking","terminal.state.draft_processing_failed":"Draft Processing Failed","terminal.state.draft_skipped":"Draft Skipped","terminal.state.retention":"Retention","terminal.state.acting":"Acting","terminal.state.drafted":"Drafted","terminal.state.acted":"Acted","terminal.state.action_failed":"Action Failed","terminal.state.stopped":"Stopped","terminal.state.sdk_error":"SDK Error","terminal.state.empty_response":"Empty Response","terminal.state.decided":"Decided","terminal.state.malformed_response":"Malformed Response","terminal.message.background_processing":"Background processing: {subject}","terminal.message.rules_apply":"{count} rule(s) apply: {rules}","terminal.message.conflict_resolution":"After conflict resolution: {actions}","terminal.message.analyzing_email":"Analyzing email: {subject}","terminal.message.context_aware_analysis":"Context-aware analysis: {subject}","terminal.message.generating_draft":"Generating customized draft based on rule","persona.title":"Digital Persona","persona.subtitle":"Manage how your AI assistant represents you.","persona.identity":"Identity","persona.communication":"Communication","persona.automation":"Automation","persona.network":"Network","persona.edit.title":"Edit Persona","persona.edit.desc":"Update your digital assistant preferences.","common.edit":"Edit"},qL=Object.freeze(Object.defineProperty({__proto__:null,default:P_},Symbol.toStringTag,{value:"Module"})),U1={en:{name:"English",flag:"🇺🇸"},fr:{name:"Français",flag:"🇫🇷"},es:{name:"Español",flag:"🇪🇸"},ja:{name:"日本語",flag:"🇯🇵"},ko:{name:"한국어",flag:"🇰🇷"},vi:{name:"Tiếng Việt",flag:"🇻🇳"}},Cu=P_,z_=w.createContext(void 0);function $L({children:e}){const[t,n]=w.useState(()=>localStorage.getItem("app_language")||"en"),[r,i]=w.useState(t==="en"?Cu:{}),[l,u]=w.useState(t!=="en");w.useEffect(()=>{localStorage.setItem("app_language",t),document.documentElement.lang=t,(async()=>{if(t==="en"){i(Cu),u(!1);return}u(!0);try{const p=await FL(Object.assign({"../locales/languages/en.json":()=>Ea(()=>Promise.resolve().then(()=>qL),void 0),"../locales/languages/es.json":()=>Ea(()=>import("./es-C53Z9pEQ.js"),[]),"../locales/languages/fr.json":()=>Ea(()=>import("./fr-CTksqdvo.js"),[]),"../locales/languages/ja.json":()=>Ea(()=>import("./ja-Dvm0bRM4.js"),[]),"../locales/languages/ko.json":()=>Ea(()=>import("./ko-CgJQAwfF.js"),[]),"../locales/languages/vi.json":()=>Ea(()=>import("./vi-mg0Gxysw.js"),[])}),`../locales/languages/${t}.json`,4);i(p.default)}catch(p){console.error(`Failed to load translations for ${t}:`,p),i(Cu)}finally{u(!1)}})()},[t]);const d=m=>{n(m)},h=m=>r[m]||Cu[m]||m;return o.jsx(z_.Provider,{value:{language:t,setLanguage:d,t:h,isLoading:l},children:e})}function tt(){const e=w.useContext(z_);if(e===void 0)throw new Error("useLanguage must be used within a LanguageProvider");return e}function ly({className:e}){const{language:t,setLanguage:n}=tt(),[r,i]=w.useState(!1),l=w.useRef(null);w.useEffect(()=>{function d(h){l.current&&!l.current.contains(h.target)&&i(!1)}return document.addEventListener("mousedown",d),()=>document.removeEventListener("mousedown",d)},[]);const u=U1[t];return o.jsxs("div",{className:me("relative z-50",e),ref:l,children:[o.jsxs("button",{onClick:()=>i(!r),className:me("flex items-center gap-2 px-3 py-2 rounded-lg transition-all duration-200","bg-secondary/50 hover:bg-secondary border border-border/50 hover:border-border shadow-sm",r&&"ring-2 ring-primary/20 border-primary/50"),children:[o.jsx("span",{className:"text-lg leading-none",children:u.flag}),o.jsx("span",{className:"text-xs font-medium uppercase tracking-wider",children:t}),o.jsx(gd,{className:me("w-3 h-3 transition-transform duration-200",r&&"rotate-180")})]}),r&&o.jsxs("div",{className:me("absolute right-0 mt-2 w-48 rounded-xl border border-border bg-card p-1.5 shadow-xl animate-in fade-in zoom-in duration-200","backdrop-blur-xl"),children:[o.jsx("div",{className:"px-2 py-1.5 mb-1 text-[10px] font-bold text-muted-foreground uppercase tracking-widest",children:"Choose Language"}),Object.entries(U1).map(([d,{name:h,flag:m}])=>o.jsxs("button",{onClick:()=>{n(d),i(!1)},className:me("flex items-center justify-between w-full px-3 py-2 rounded-lg text-sm transition-colors",t===d?"bg-primary/10 text-primary font-bold":"hover:bg-secondary text-muted-foreground hover:text-foreground"),children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("span",{className:"text-lg leading-none",children:m}),o.jsx("span",{children:h})]}),t===d&&o.jsx(ar,{className:"w-4 h-4"})]},d))]})]})}const L_=w.createContext(void 0);function HL({children:e}){const[t,n]=w.useState(!1),[r,i]=w.useState(!1),[l,u]=w.useState(null),d=w.useRef(null),h=w.useRef(null),m=w.useRef(null),p=w.useRef(null),g=w.useRef(0),b=w.useCallback(()=>{if(p.current&&(p.current.cancel().catch(()=>{}),p.current=null),m.current){try{m.current.stop(),m.current.disconnect()}catch{}m.current=null}d.current&&(d.current.pause(),d.current.currentTime=0,d.current=null),n(!1),i(!1),u(null),g.current++},[]),v=w.useCallback((j,N)=>new Promise((A,T)=>{j.decodeAudioData(N,O=>{const L=j.createBufferSource();L.buffer=O,L.connect(j.destination),L.onended=()=>A(),L.start(0),m.current=L},O=>T(O))}),[]),S=w.useCallback(async(j,N,A={})=>{b();const T=g.current;i(!0),u(N||null);const O={text:j,...A};console.log("[TTSContext] Sending TTS request:",O);try{const L=await fetch("/api/tts/speak",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(O)});if(!L.ok)throw new Error("TTS generation failed");const M=await L.blob(),B=URL.createObjectURL(M),P=new Audio(B);d.current=P,P.onplay=()=>n(!0),P.onended=()=>{g.current===T&&(n(!1),i(!1),u(null),URL.revokeObjectURL(B))},P.onerror=()=>{g.current===T&&(n(!1),i(!1),u(null),URL.revokeObjectURL(B),console.error("[TTSContext] Audio playback failed"))},await P.play()}catch(L){console.error("[TTSContext] Speak failed:",L),g.current===T&&(i(!1),u(null))}},[b]),_=w.useCallback(async(j,N,A={})=>{b();const T=g.current;i(!0),u(N||null);try{const O=await fetch("/api/tts/stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:j,...A})});if(!O.ok)throw new Error("TTS streaming failed");const L=O.body?.getReader();if(!L)throw new Error("No response body");p.current=L;const M=new TextDecoder;let B="";const P=[];h.current||(h.current=new(window.AudioContext||window.webkitAudioContext));const q=h.current;for(;g.current===T;){const{done:D,value:Q}=await L.read();if(D)break;B+=M.decode(Q,{stream:!0});const G=B.split(`
|
|
108
|
-
`);B=G.pop()||"";for(const fe of G){const se=fe.trim();if(!se||!se.startsWith("data:"))continue;const ae=se.slice(5).trim();if(ae)try{const I=JSON.parse(ae);if(I.audio){const V=atob(I.audio),$=new Uint8Array(V.length);for(let de=0;de<V.length;de++)$[de]=V.charCodeAt(de);P.push($.buffer),P.length===1&&(n(!0),await v(q,$.buffer))}}catch{}}}if(g.current===T)for(let D=1;D<P.length&&g.current===T;D++)await v(q,P[D]);g.current===T&&(n(!1),i(!1),u(null))}catch(O){console.error("[TTSContext] Stream failed:",O),g.current===T&&(n(!1),i(!1),u(null))}},[b,v]);return o.jsx(L_.Provider,{value:{isPlaying:t,isSpeaking:r,speakingId:l,currentAudio:d.current,speak:S,speakStream:_,stop:b},children:e})}function I_(){const e=w.useContext(L_);if(e===void 0)throw new Error("useTTSContext must be used within a TTSProvider");return e}function cy(){const{speak:e,speakStream:t,stop:n,isPlaying:r,isSpeaking:i,speakingId:l}=I_(),u=w.useCallback(async(h,m,p={})=>e(h,m,p),[e]),d=w.useCallback(async(h,m,p={})=>t(h,m,p),[t]);return{speak:u,speakStream:d,stop:n,isPlaying:r,isSpeaking:i,speakingId:l}}const U_=w.createContext(void 0),B1={page_id:"global",system_instruction:"You are a helpful Email Assistant. Use general knowledge to help the user."};function V1(){return jp().autoPlay}function GL({children:e}){const[t,n]=w.useState(B1),[r,i]=w.useState([]),[l,u]=w.useState("idle"),{speak:d}=cy(),h=w.useCallback(g=>{n(b=>b.page_id===g.page_id&&JSON.stringify(b.data)===JSON.stringify(g.data)?b:(console.log(`[AgentContext] Registering new agent context: ${g.page_id}`),g))},[]),m=w.useCallback(()=>{n(B1)},[]),p=w.useCallback(async g=>{u("thinking");const b={role:"user",content:g};i(v=>[...v,b]);try{const v="/api/agent/chat",S=localStorage.getItem("supabase.auth.token"),_=bp(),j={...t,lang:localStorage.getItem("app_language")||"en",tools:t.tools?.map(O=>({name:O.name,description:O.description,parameters:O.parameters}))},N={message:g,context:j,history:r.slice(-10)},A=await fetch(v,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${S||""}`,"X-Supabase-Url":_.edgeFunctionsUrl.replace("/functions/v1",""),"X-Supabase-Anon-Key":_.anonKey},body:JSON.stringify(N)});if(!A.ok)throw new Error(`API request failed: ${A.status} ${A.statusText}`);const T=await A.json();if(T.success&&T.response){const O=T.response.content,L=T.response.action,M={role:"assistant",content:O};if(i(B=>[...B,M]),O&&V1()&&(u("speaking"),await d(O,void 0,jp())),L&&t.tools){console.log(`[AgentContext] Executing tool: ${L.name}`,L.args);const B=t.tools.find(P=>P.name===L.name);if(B)try{if(B.parameters?.required){const D=B.parameters.required.filter(Q=>!(Q in(L.args||{})));if(D.length>0)throw new Error(`Missing required parameters: ${D.join(", ")}`)}const P=await B.callback(L.args),q=P?.message||`✓ Action completed: ${L.name}`;i(D=>[...D,{role:"system",content:q}]),console.log("[AgentContext] Tool executed successfully:",P)}catch(P){console.error("[AgentContext] Tool execution failed:",P);const q=P?.message||"Unknown error occurred";i(D=>[...D,{role:"system",content:`⚠️ Error: ${q}`}]),V1()&&await d(`Error: ${q}`,void 0,jp())}else{const P=`Tool "${L.name}" not found. Available tools: ${t.tools.map(q=>q.name).join(", ")}`;console.warn(`[AgentContext] ${P}`),i(q=>[...q,{role:"system",content:`⚠️ ${P}`}])}}u("idle")}else{const O=T.error||"Sorry, I encountered an error processing your request.";console.error("[AgentContext] API error:",T.error),i(L=>[...L,{role:"assistant",content:`⚠️ ${O}`}]),u("idle")}}catch(v){console.error("[AgentContext] Chat failed:",v);let S="Network error. Please try again.";v.message?.includes("Failed to fetch")?S="Cannot connect to the AI service. Please ensure the API server is running.":v.message&&(S=v.message),i(_=>[..._,{role:"system",content:`⚠️ ${S}`}]),u("idle")}},[t,r,d]);return o.jsx(U_.Provider,{value:{currentConfig:t,registerAgent:h,chatHistory:r,agentState:l,sendMessage:p,resetAgent:m},children:e})}function B_(){const e=w.useContext(U_);if(e===void 0)throw new Error("useAgentContext must be used within an AgentProvider");return e}function uy(e){const{registerAgent:t,resetAgent:n}=B_();w.useRef(e);const r=JSON.stringify(e);w.useEffect(()=>(t(e),()=>{n()}),[r,t,n])}const eo="2.23.
|
|
108
|
+
`);B=G.pop()||"";for(const fe of G){const se=fe.trim();if(!se||!se.startsWith("data:"))continue;const ae=se.slice(5).trim();if(ae)try{const I=JSON.parse(ae);if(I.audio){const V=atob(I.audio),$=new Uint8Array(V.length);for(let de=0;de<V.length;de++)$[de]=V.charCodeAt(de);P.push($.buffer),P.length===1&&(n(!0),await v(q,$.buffer))}}catch{}}}if(g.current===T)for(let D=1;D<P.length&&g.current===T;D++)await v(q,P[D]);g.current===T&&(n(!1),i(!1),u(null))}catch(O){console.error("[TTSContext] Stream failed:",O),g.current===T&&(n(!1),i(!1),u(null))}},[b,v]);return o.jsx(L_.Provider,{value:{isPlaying:t,isSpeaking:r,speakingId:l,currentAudio:d.current,speak:S,speakStream:_,stop:b},children:e})}function I_(){const e=w.useContext(L_);if(e===void 0)throw new Error("useTTSContext must be used within a TTSProvider");return e}function cy(){const{speak:e,speakStream:t,stop:n,isPlaying:r,isSpeaking:i,speakingId:l}=I_(),u=w.useCallback(async(h,m,p={})=>e(h,m,p),[e]),d=w.useCallback(async(h,m,p={})=>t(h,m,p),[t]);return{speak:u,speakStream:d,stop:n,isPlaying:r,isSpeaking:i,speakingId:l}}const U_=w.createContext(void 0),B1={page_id:"global",system_instruction:"You are a helpful Email Assistant. Use general knowledge to help the user."};function V1(){return jp().autoPlay}function GL({children:e}){const[t,n]=w.useState(B1),[r,i]=w.useState([]),[l,u]=w.useState("idle"),{speak:d}=cy(),h=w.useCallback(g=>{n(b=>b.page_id===g.page_id&&JSON.stringify(b.data)===JSON.stringify(g.data)?b:(console.log(`[AgentContext] Registering new agent context: ${g.page_id}`),g))},[]),m=w.useCallback(()=>{n(B1)},[]),p=w.useCallback(async g=>{u("thinking");const b={role:"user",content:g};i(v=>[...v,b]);try{const v="/api/agent/chat",S=localStorage.getItem("supabase.auth.token"),_=bp(),j={...t,lang:localStorage.getItem("app_language")||"en",tools:t.tools?.map(O=>({name:O.name,description:O.description,parameters:O.parameters}))},N={message:g,context:j,history:r.slice(-10)},A=await fetch(v,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${S||""}`,"X-Supabase-Url":_.edgeFunctionsUrl.replace("/functions/v1",""),"X-Supabase-Anon-Key":_.anonKey},body:JSON.stringify(N)});if(!A.ok)throw new Error(`API request failed: ${A.status} ${A.statusText}`);const T=await A.json();if(T.success&&T.response){const O=T.response.content,L=T.response.action,M={role:"assistant",content:O};if(i(B=>[...B,M]),O&&V1()&&(u("speaking"),await d(O,void 0,jp())),L&&t.tools){console.log(`[AgentContext] Executing tool: ${L.name}`,L.args);const B=t.tools.find(P=>P.name===L.name);if(B)try{if(B.parameters?.required){const D=B.parameters.required.filter(Q=>!(Q in(L.args||{})));if(D.length>0)throw new Error(`Missing required parameters: ${D.join(", ")}`)}const P=await B.callback(L.args),q=P?.message||`✓ Action completed: ${L.name}`;i(D=>[...D,{role:"system",content:q}]),console.log("[AgentContext] Tool executed successfully:",P)}catch(P){console.error("[AgentContext] Tool execution failed:",P);const q=P?.message||"Unknown error occurred";i(D=>[...D,{role:"system",content:`⚠️ Error: ${q}`}]),V1()&&await d(`Error: ${q}`,void 0,jp())}else{const P=`Tool "${L.name}" not found. Available tools: ${t.tools.map(q=>q.name).join(", ")}`;console.warn(`[AgentContext] ${P}`),i(q=>[...q,{role:"system",content:`⚠️ ${P}`}])}}u("idle")}else{const O=T.error||"Sorry, I encountered an error processing your request.";console.error("[AgentContext] API error:",T.error),i(L=>[...L,{role:"assistant",content:`⚠️ ${O}`}]),u("idle")}}catch(v){console.error("[AgentContext] Chat failed:",v);let S="Network error. Please try again.";v.message?.includes("Failed to fetch")?S="Cannot connect to the AI service. Please ensure the API server is running.":v.message&&(S=v.message),i(_=>[..._,{role:"system",content:`⚠️ ${S}`}]),u("idle")}},[t,r,d]);return o.jsx(U_.Provider,{value:{currentConfig:t,registerAgent:h,chatHistory:r,agentState:l,sendMessage:p,resetAgent:m},children:e})}function B_(){const e=w.useContext(U_);if(e===void 0)throw new Error("useAgentContext must be used within an AgentProvider");return e}function uy(e){const{registerAgent:t,resetAgent:n}=B_();w.useRef(e);const r=JSON.stringify(e);w.useEffect(()=>(t(e),()=>{n()}),[r,t,n])}const eo="2.23.3",KL="20260205060000";function YL(e,t){const n=e.split(".").map(Number),r=t.split(".").map(Number);for(let i=0;i<Math.max(n.length,r.length);i++){const l=n[i]||0,u=r[i]||0;if(l>u)return 1;if(l<u)return-1}return 0}async function WL(e){try{const{data:t,error:n}=await e.rpc("get_latest_migration_timestamp");return n?n.code==="42883"?(console.info("[Migration Check] RPC function missing - assuming fresh DB."),{version:null,latestMigrationTimestamp:"0"}):(console.warn("Could not get latest migration timestamp:",n.message),{version:null,latestMigrationTimestamp:null}):{version:eo,latestMigrationTimestamp:t||null}}catch(t){return console.error("Error checking database migration info:",t),{version:null,latestMigrationTimestamp:null}}}async function dy(e){const t=eo,n=KL,r=await WL(e);if(console.log("[Migration Check]",{appVersion:t,appMigrationTimestamp:n,dbVersion:r.version,dbMigrationTimestamp:r.latestMigrationTimestamp}),r.latestMigrationTimestamp&&r.latestMigrationTimestamp.trim()!==""){const i=n,l=r.latestMigrationTimestamp;return i>l?{needsMigration:!0,appVersion:t,dbVersion:r.version,latestMigrationTimestamp:l,message:`New migrations available. Database is at ${l}, app has ${i}.`}:i<l?(console.warn("[Migration Check] DB is ahead of app - possible downgrade"),{needsMigration:!1,appVersion:t,dbVersion:r.version,latestMigrationTimestamp:l,message:`Database (${l}) is ahead of app (${i}).`}):(console.log("[Migration Check] Timestamps match - database is up-to-date"),{needsMigration:!1,appVersion:t,dbVersion:r.version,latestMigrationTimestamp:l,message:"Database schema is up-to-date."})}if(r.version){console.log("[Migration Check] Legacy DB detected (no timestamp). Falling back to SemVer.");const i=YL(t,r.version);return i>0?{needsMigration:!0,appVersion:t,dbVersion:r.version,latestMigrationTimestamp:null,message:`Database schema (v${r.version}) is outdated. Migration to v${t} required.`}:i===0?(console.warn("[Migration Check] Legacy DB with matching version - forcing migration to add timestamp tracking"),{needsMigration:!0,appVersion:t,dbVersion:r.version,latestMigrationTimestamp:null,message:`Database lacks timestamp tracking. Please run migration to upgrade to modern schema (v${t}).`}):{needsMigration:!1,appVersion:t,dbVersion:r.version,latestMigrationTimestamp:null,message:`Database version (v${r.version}) is ahead of app (v${t}).`}}return console.log("[Migration Check] No DB info found - assuming migration needed"),{needsMigration:!0,appVersion:t,dbVersion:null,latestMigrationTimestamp:null,message:`Database schema unknown. Migration required to v${t}.`}}const V_="email_automator_migration_reminder_dismissed_at";function XL(e=24){try{const t=localStorage.getItem(V_);if(!t)return!1;const n=new Date(t).getTime();return(Date.now()-n)/(1e3*60*60)<e}catch(t){return console.error("Error checking migration reminder:",t),!1}}function JL(){try{localStorage.setItem(V_,new Date().toISOString())}catch(e){console.error("Error dismissing migration reminder:",e)}}const Kp={step:"welcome",managed:{accessToken:"",organizations:[],selectedOrg:"",projectName:"Email-Automator-AI",region:"us-east-1",isFetchingOrgs:!1},manual:{url:"",anonKey:""},projectId:"",logs:[],error:null,isMigrating:!1,migrationStatus:null};function QL(e,t){switch(t.type){case"SET_STEP":return{...e,step:t.payload,error:null};case"SET_ACCESS_TOKEN":return{...e,managed:{...e.managed,accessToken:t.payload}};case"SET_ORGANIZATIONS":return{...e,managed:{...e.managed,organizations:t.payload,selectedOrg:t.payload.length>0?t.payload[0].id:""}};case"SET_SELECTED_ORG":return{...e,managed:{...e.managed,selectedOrg:t.payload}};case"SET_PROJECT_NAME":return{...e,managed:{...e.managed,projectName:t.payload}};case"SET_REGION":return{...e,managed:{...e.managed,region:t.payload}};case"SET_FETCHING_ORGS":return{...e,managed:{...e.managed,isFetchingOrgs:t.payload}};case"SET_MANUAL_URL":return{...e,manual:{...e.manual,url:t.payload}};case"SET_MANUAL_ANON_KEY":return{...e,manual:{...e.manual,anonKey:t.payload}};case"SET_PROJECT_ID":return{...e,projectId:t.payload};case"ADD_LOG":return{...e,logs:[...e.logs,{...t.payload,timestamp:Date.now()}].slice(-500)};case"CLEAR_LOGS":return{...e,logs:[]};case"SET_ERROR":return{...e,error:t.payload};case"SET_MIGRATING":return{...e,isMigrating:t.payload};case"SET_MIGRATION_STATUS":return{...e,migrationStatus:t.payload};case"RESET_MANAGED_FLOW":return{...e,managed:{...Kp.managed},error:null};case"RESET_MANUAL_FLOW":return{...e,manual:{...Kp.manual},error:null};default:return e}}function Om(e){const t=e.trim();return t?t.startsWith("http://")||t.startsWith("https://")?t:`https://${t}.supabase.co`:""}function F_(e){const t=e.trim();return t?t.startsWith("sbp_")?t.length<20?{valid:!1,message:"Token is too short"}:{valid:!0,message:"Valid access token"}:{valid:!1,message:"Token must start with sbp_"}:{valid:!1,message:"Access token is required"}}function F1(e){const t=e.trim();if(!t)return null;if(!t.includes(".")&&!t.includes("/"))return t;try{return new URL(t.startsWith("http")?t:`https://${t}`).hostname.split(".")[0]||null}catch{return null}}class ZL{buffer="";processChunk(t){const n=[];this.buffer+=t;const r=this.buffer.split(`
|
|
109
109
|
`);this.buffer=r.pop()||"";for(const i of r)if(i.startsWith("data: "))try{const l=i.slice(6),u=JSON.parse(l);n.push(u)}catch(l){console.warn("[SSEParser] Failed to parse event:",i,l)}return n}flush(){if(!this.buffer.trim())return[];const t=[];if(this.buffer.startsWith("data: "))try{const n=this.buffer.slice(6),r=JSON.parse(n);t.push(r)}catch(n){console.warn("[SSEParser] Failed to parse final buffer:",this.buffer,n)}return this.buffer="",t}reset(){this.buffer=""}}async function q_(e,t,n={}){const{timeout:r=3e5,onError:i}=n;if(!e.body)throw new Error("Response body is empty");const l=e.body.getReader(),u=new TextDecoder,d=new ZL,h=setTimeout(()=>{l.cancel("Timeout")},r);try{for(;;){const{value:m,done:p}=await l.read();if(p){d.flush().forEach(t);break}const g=u.decode(m,{stream:!0});d.processChunk(g).forEach(t)}}catch(m){const p=m instanceof Error?m:new Error(String(m));if(i)i(p);else throw p}finally{clearTimeout(h),d.reset()}}class Wr extends Error{constructor(t,n,r){super(t),this.code=n,this.status=r,this.name="SetupApiError"}}async function e6(e){const t=await fetch("/api/setup/organizations",{headers:{Authorization:`Bearer ${e}`}}),n=await t.json();if(!t.ok)throw new Wr(n.error||"Failed to fetch organizations","FETCH_ORGS_FAILED",t.status);return n}async function t6(e,t){const n=await fetch("/api/setup/auto-provision",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`},body:JSON.stringify({orgId:e.orgId,projectName:e.projectName,region:e.region})});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Wr(r.error||"Failed to provision project","PROVISION_FAILED",n.status)}await q_(n,t,{timeout:3e5,onError:r=>{throw new Wr(`Provisioning stream error: ${r.message}`,"STREAM_ERROR")}})}async function n6(e,t){const n=await fetch("/api/migrate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectRef:e.projectRef,dbPassword:e.dbPassword,accessToken:e.accessToken,anonKey:e.anonKey})});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Wr(r.error||"Failed to start migration","MIGRATION_FAILED",n.status)}await q_(n,t,{timeout:6e5,onError:r=>{throw new Wr(`Migration stream error: ${r.message}`,"STREAM_ERROR")}})}function s6({onNext:e}){const{t}=tt();return o.jsxs("div",{className:"flex-1 flex flex-col justify-center space-y-8",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx("h2",{className:"text-4xl font-black italic tracking-tighter uppercase leading-none",children:t("setup.welcomeTitle")}),o.jsx("p",{className:"text-sm text-muted-foreground font-medium max-w-sm",children:t("setup.welcomeSubtitle")})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[o.jsxs("div",{className:"p-4 rounded-2xl bg-muted/40 border border-border/50 flex flex-col gap-2 group hover:bg-primary/5 hover:border-primary/20 transition-all",children:[o.jsx(wg,{className:"w-5 h-5 text-primary","aria-hidden":"true"}),o.jsx("p",{className:"text-[10px] font-bold uppercase tracking-widest",children:t("setup.encryptedTitle")}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:t("setup.encryptedDesc")})]}),o.jsxs("div",{className:"p-4 rounded-2xl bg-muted/40 border border-border/50 flex flex-col gap-2 group hover:bg-primary/5 hover:border-primary/20 transition-all",children:[o.jsx(ao,{className:"w-5 h-5 text-primary","aria-hidden":"true"}),o.jsx("p",{className:"text-[10px] font-bold uppercase tracking-widest",children:t("setup.turboTitle")}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:t("setup.turboDesc")})]})]}),o.jsxs(Z,{onClick:e,size:"lg",className:"h-14 rounded-2xl text-md font-bold uppercase tracking-widest group shadow-xl hover:shadow-primary/20 transition-all active:scale-95 bg-primary text-primary-foreground hover:bg-primary/90",children:[t("setup.getStarted"),o.jsx(pg,{className:"w-5 h-5 ml-4 rotate-180 group-hover:translate-x-1 transition-transform","aria-hidden":"true"})]})]})}function r6({onManaged:e,onManual:t,onBack:n}){const{t:r}=tt();return o.jsxs("div",{className:"flex-1 flex flex-col justify-center space-y-6",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("h3",{className:"text-2xl font-black uppercase italic tracking-tighter",children:r("setup.connectionMode")}),o.jsx("p",{className:"text-xs text-muted-foreground font-bold tracking-widest uppercase",children:r("setup.selectVector")})]}),o.jsxs("div",{className:"grid gap-4",children:[o.jsxs("button",{onClick:e,className:"group relative flex items-center justify-between p-6 rounded-2xl bg-primary/5 border border-primary/20 hover:bg-primary/10 hover:border-primary/40 transition-all text-left","aria-label":"Quick Ignition - Auto-provision via token",children:[o.jsxs("div",{className:"flex items-center gap-4",children:[o.jsx("div",{className:"p-3 bg-primary rounded-xl shadow-lg ring-4 ring-primary/10",children:o.jsx(lR,{className:"w-6 h-6 text-primary-foreground","aria-hidden":"true"})}),o.jsxs("div",{children:[o.jsx("p",{className:"font-black uppercase italic text-sm tracking-tight",children:r("setup.quickIgnition")}),o.jsx("p",{className:"text-[10px] font-bold text-muted-foreground uppercase tracking-widest",children:r("setup.autoProvision")})]})]}),o.jsx(so,{className:"w-5 h-5 text-primary opacity-50 group-hover:opacity-100 transition-all group-hover:translate-x-1"})]}),o.jsxs("button",{onClick:t,className:"group relative flex items-center justify-between p-6 rounded-2xl border border-border hover:bg-muted/50 transition-all text-left","aria-label":"Manual Sync - Use existing credentials",children:[o.jsxs("div",{className:"flex items-center gap-4",children:[o.jsx("div",{className:"p-3 bg-muted rounded-xl",children:o.jsx(yd,{className:"w-6 h-6 text-muted-foreground","aria-hidden":"true"})}),o.jsxs("div",{children:[o.jsx("p",{className:"font-black uppercase italic text-sm tracking-tight text-foreground/80",children:r("setup.manualSync")}),o.jsx("p",{className:"text-[10px] font-bold text-muted-foreground uppercase tracking-widest",children:r("setup.existingCredentials")})]})]}),o.jsx(so,{className:"w-5 h-5 text-muted-foreground opacity-50 group-hover:opacity-100 transition-all group-hover:translate-x-1"})]})]}),o.jsxs("button",{onClick:n,className:"text-[10px] font-bold uppercase tracking-widest text-muted-foreground flex items-center gap-2 hover:text-primary pt-4 transition-colors","aria-label":"Go back to welcome screen",children:[o.jsx(pg,{size:12,"aria-hidden":"true"})," ",r("setup.abortAccess")]})]})}const Ce=w.forwardRef(({className:e,type:t,...n},r)=>o.jsx("input",{type:t,className:me("flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",e),ref:r,...n}));Ce.displayName="Input";var $_=ZS();const a6=Yl($_);var i6=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],o6=i6.reduce((e,t)=>{const n=fj(`Primitive.${t}`),r=w.forwardRef((i,l)=>{const{asChild:u,...d}=i,h=u?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),o.jsx(h,{...d,ref:l})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{}),l6="Label",H_=w.forwardRef((e,t)=>o.jsx(o6.label,{...e,ref:t,onMouseDown:n=>{n.target.closest("button, input, select, textarea")||(e.onMouseDown?.(n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));H_.displayName=l6;var c6=H_;function Ge({className:e,...t}){return o.jsx(c6,{"data-slot":"label",className:me("flex items-center gap-2 text-sm leading-none font-medium select-none text-muted-foreground group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",e),...t})}const u6=jg("relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",{variants:{variant:{default:"bg-card text-card-foreground",destructive:"text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90"}},defaultVariants:{variant:"default"}});function La({className:e,variant:t,...n}){return o.jsx("div",{"data-slot":"alert",role:"alert",className:me(u6({variant:t}),e),...n})}function Ia({className:e,...t}){return o.jsx("div",{"data-slot":"alert-description",className:me("text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",e),...t})}function d6({accessToken:e,error:t,isFetching:n,onTokenChange:r,onFetchOrgs:i,onBack:l}){const d=F_(e).valid;return o.jsxs("div",{className:"flex-1 flex flex-col justify-center space-y-6",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("h3",{className:"text-2xl font-black uppercase italic tracking-tighter",children:"Forge Token"}),o.jsx("p",{className:"text-[10px] text-muted-foreground font-bold tracking-widest uppercase",children:"Supabase API coordinates"})]}),t&&o.jsxs(La,{variant:"destructive",className:"rounded-xl bg-destructive/5 text-destructive border-destructive/20 text-[11px] font-bold",children:[o.jsx(ls,{className:"h-4 w-4"}),o.jsx(Ia,{children:t})]}),o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Ge,{htmlFor:"access-token",className:"text-[10px] font-bold uppercase tracking-widest text-muted-foreground ml-1",children:"Personal Access Token"}),o.jsxs("div",{className:"relative",children:[o.jsx(xg,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground/30",size:14,"aria-hidden":"true"}),o.jsx(Ce,{id:"access-token",type:"password",placeholder:"sbp_xxxxxxxxxxxxxxxx",value:e,onChange:h=>r(h.target.value),className:"pl-10 h-12 bg-muted/20 border-border/50 rounded-xl","aria-describedby":"token-help","aria-invalid":t?"true":"false"})]}),o.jsxs("p",{id:"token-help",className:"text-[9px] text-muted-foreground/60 px-1 italic",children:["Generate at"," ",o.jsx("a",{href:"https://supabase.com/dashboard/account/tokens",target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline",children:"supabase.com/dashboard/tokens"})]})]}),o.jsxs("div",{className:"flex gap-3 pt-4",children:[o.jsx(Z,{variant:"outline",onClick:l,className:"flex-1 h-12 rounded-xl text-[10px] font-bold uppercase tracking-widest",disabled:n,children:"Back"}),o.jsx(Z,{onClick:i,disabled:!d||n,className:"flex-1 h-12 rounded-xl text-[10px] font-bold uppercase tracking-widest group shadow-lg hover:shadow-primary/20",children:n?o.jsx(wt,{className:"w-4 h-4 animate-spin"}):o.jsxs(o.Fragment,{children:["Scan Organizations"," ",o.jsx(so,{size:14,className:"ml-2 group-hover:translate-x-1 transition-transform"})]})})]})]})]})}function f6({organizations:e,selectedOrg:t,projectName:n,region:r,onOrgSelect:i,onProjectNameChange:l,onRegionChange:u,onProvision:d,onBack:h}){return o.jsxs("div",{className:"flex-1 flex flex-col justify-center space-y-6",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("h3",{className:"text-2xl font-black uppercase italic tracking-tighter",children:"Project Config"}),o.jsx("p",{className:"text-[10px] text-muted-foreground font-bold tracking-widest uppercase",children:"Engine parameters"})]}),o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[o.jsxs("div",{className:"space-y-1.5",children:[o.jsx(Ge,{htmlFor:"project-name",className:"text-[10px] font-bold uppercase tracking-widest text-muted-foreground ml-1",children:"Project Name"}),o.jsx(Ce,{id:"project-name",value:n,onChange:m=>l(m.target.value),className:"bg-muted/20 border-border/50 rounded-xl text-[11px]"})]}),o.jsxs("div",{className:"space-y-1.5",children:[o.jsx(Ge,{htmlFor:"region",className:"text-[10px] font-bold uppercase tracking-widest text-muted-foreground ml-1",children:"Hosting Sector"}),o.jsxs("select",{id:"region",value:r,onChange:m=>u(m.target.value),className:"w-full h-10 bg-muted/20 border border-border/50 rounded-xl px-3 text-[11px] font-sans focus:outline-none focus:ring-1 focus:ring-primary/50",children:[o.jsx("option",{value:"us-east-1",children:"US East (N. Virginia)"}),o.jsx("option",{value:"us-west-1",children:"US West (N. California)"}),o.jsx("option",{value:"eu-central-1",children:"Europe (Frankfurt)"}),o.jsx("option",{value:"ap-southeast-1",children:"Asia Pacific (Singapore)"})]})]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Ge,{className:"text-[10px] font-bold uppercase tracking-widest text-muted-foreground ml-1",children:"Vessel (Organization)"}),o.jsx("div",{className:"max-h-[160px] overflow-y-auto space-y-2 pr-1 custom-scrollbar",role:"radiogroup","aria-label":"Select organization",children:e.map(m=>o.jsxs("button",{onClick:()=>i(m.id),role:"radio","aria-checked":t===m.id,className:me("w-full flex items-center justify-between p-3 rounded-xl border text-[11px] font-bold transition-all",t===m.id?"border-primary bg-primary/5 ring-1 ring-primary":"hover:bg-muted/30 border-border/50"),children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx(rj,{className:me("w-3.5 h-3.5",t===m.id?"text-primary":"text-muted-foreground/50"),"aria-hidden":"true"}),o.jsx("span",{children:m.name})]}),t===m.id&&o.jsx("div",{className:"w-2 h-2 rounded-full bg-primary animate-pulse","aria-hidden":"true"})]},m.id))})]}),o.jsxs("div",{className:"flex gap-3 pt-2",children:[o.jsx(Z,{variant:"outline",onClick:h,className:"flex-1 h-12 rounded-xl text-[10px] font-bold uppercase tracking-widest",children:"Back"}),o.jsx(Z,{onClick:d,disabled:!t,className:"flex-1 h-12 rounded-xl text-[10px] font-bold uppercase tracking-widest shadow-md",children:"Initialize System"})]})]})]})}function G_({logs:e,className:t}){const n=w.useRef(null);return w.useEffect(()=>{n.current?.scrollIntoView({behavior:"smooth"})},[e]),o.jsxs("div",{className:me("bg-slate-950 rounded-2xl p-4 font-mono text-[10px] h-[240px] overflow-y-auto border border-white/5 shadow-inner custom-scrollbar relative",t),role:"log","aria-live":"polite","aria-label":"Setup progress logs",children:[o.jsxs("div",{className:"absolute top-2 right-4 flex items-center gap-2 text-[9px] font-bold text-muted-foreground/30 uppercase tracking-widest pointer-events-none",children:[o.jsx(Rl,{size:10,"aria-hidden":"true"}),o.jsx("span",{children:"Live Feed"})]}),e.length===0?o.jsx("div",{className:"text-slate-600 italic animate-pulse",role:"status",children:"Awaiting kernel signals..."}):o.jsxs(o.Fragment,{children:[e.map((r,i)=>o.jsxs("div",{className:me("mb-1 break-all transition-all duration-300",r.type==="error"&&"text-red-400 font-bold",r.type==="success"&&"text-green-400 font-bold",r.type==="info"&&"text-blue-300",r.type==="stdout"&&"text-slate-400",r.type==="stderr"&&"text-yellow-400"),children:[o.jsxs("span",{className:"text-slate-600 mr-2 tabular-nums",children:["[",new Date(r.timestamp).toLocaleTimeString([],{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"}),"]"]}),r.message]},`${r.timestamp}-${i}`)),o.jsx("div",{ref:n})]})]})}function h6({logs:e,error:t,onRetry:n}){return o.jsxs("div",{className:"flex-1 flex flex-col justify-center space-y-6",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx(wt,{className:"w-5 h-5 animate-spin text-primary","aria-hidden":"true"}),o.jsx("h3",{className:"text-2xl font-black uppercase italic tracking-tighter",children:"Provisioning"})]}),o.jsx("p",{className:"text-[10px] text-muted-foreground font-bold tracking-widest uppercase",children:"Assembling infrastructure..."})]}),o.jsx(G_,{logs:e}),t&&o.jsx(Z,{variant:"destructive",onClick:n,className:"w-full h-12 rounded-xl text-[10px] font-bold uppercase tracking-widest",children:"Re-Initialize Engine"})]})}function m6({url:e,anonKey:t,error:n,onUrlChange:r,onAnonKeyChange:i,onSave:l,onBack:u}){const{t:d}=tt(),h=e.trim().length>0&&t.trim().length>0;return o.jsxs("div",{className:"flex-1 flex flex-col justify-center space-y-6",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("h3",{className:"text-2xl font-black uppercase italic tracking-tighter",children:d("setup.manualSync")}),o.jsx("p",{className:"text-[10px] text-muted-foreground font-bold tracking-widest uppercase",children:d("setup.injectCoordinates")})]}),o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"space-y-1.5",children:[o.jsx(Ge,{htmlFor:"platform-url",className:"text-[10px] font-bold uppercase tracking-widest text-muted-foreground ml-1",children:d("setup.platformUrl")}),o.jsx(Ce,{id:"platform-url",placeholder:"https://xyz.supabase.co",value:e,onChange:m=>r(m.target.value),className:"bg-muted/20 border-border/50 rounded-xl h-12","aria-describedby":"url-help","aria-invalid":n?"true":"false"}),o.jsx("p",{id:"url-help",className:"text-[9px] text-muted-foreground/60 px-1 italic",children:d("setup.urlHelp")})]}),o.jsxs("div",{className:"space-y-1.5",children:[o.jsx(Ge,{htmlFor:"anon-key",className:"text-[10px] font-bold uppercase tracking-widest text-muted-foreground ml-1",children:d("setup.anonMatrixKey")}),o.jsx(Ce,{id:"anon-key",type:"password",placeholder:"eyJ...",value:t,onChange:m=>i(m.target.value),className:"bg-muted/20 border-border/50 rounded-xl h-12","aria-describedby":"key-help","aria-invalid":n?"true":"false"}),o.jsx("p",{id:"key-help",className:"text-[9px] text-muted-foreground/60 px-1 italic",children:d("setup.keyHelp")})]})]}),n&&o.jsxs(ir.div,{initial:{y:5,opacity:0},animate:{y:0,opacity:1},className:"p-3 bg-destructive/5 border border-destructive/20 text-destructive text-[11px] font-bold rounded-xl flex items-center gap-2",role:"alert",children:[o.jsx(ls,{size:14,"aria-hidden":"true"}),o.jsx("span",{children:n})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-3 pt-4",children:[o.jsx(Z,{variant:"outline",onClick:u,className:"h-12 rounded-xl text-[10px] font-bold uppercase tracking-widest",children:d("setup.back")}),o.jsx(Z,{onClick:l,disabled:!h,className:"h-12 rounded-xl text-[10px] font-bold uppercase tracking-widest bg-primary shadow-lg hover:shadow-primary/20",children:d("setup.engage")})]})]})}function p6({logs:e,error:t,isMigrating:n,migrationStatus:r,accessToken:i,onTokenChange:l,onRunMigration:u,onBypass:d}){const h=!i,m=r?.dbVersion!==null&&!r?.isUnknown,p=r?.dbVersion===null||r?.isUnknown;return o.jsxs("div",{className:"flex-1 flex flex-col justify-center space-y-6",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[n?o.jsx(wt,{className:"w-5 h-5 animate-spin text-primary","aria-hidden":"true"}):o.jsx(SC,{className:"w-5 h-5 text-primary","aria-hidden":"true"}),o.jsx("h3",{className:"text-2xl font-black uppercase italic tracking-tighter",children:"Installation"})]}),o.jsx("p",{className:"text-[10px] text-muted-foreground font-bold tracking-widest uppercase",children:"Applying schema DNA..."})]}),o.jsx(G_,{logs:e}),!n&&o.jsxs(ir.div,{initial:{y:10,opacity:0},animate:{y:0,opacity:1},className:"p-5 bg-primary/5 rounded-2xl space-y-4 border border-primary/20",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx("p",{className:"text-[11px] text-muted-foreground leading-relaxed font-medium",children:p?"Empty project detected. Initialization is mandatory to install core AI systems.":`Version mismatch detected (v${r?.dbVersion||"?.?"} → v${r?.appVersion||eo}). Normalization is recommended.`}),h&&o.jsxs("div",{className:"space-y-2 pt-2 border-t border-primary/10",children:[o.jsx(Ge,{htmlFor:"migration-token",className:"text-[10px] font-bold uppercase tracking-widest text-primary/60",children:"Management Token Required"}),o.jsxs("div",{className:"relative",children:[o.jsx(xg,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-primary/30",size:12,"aria-hidden":"true"}),o.jsx(Ce,{id:"migration-token",type:"password",placeholder:"sbp_xxxxxxxxxxxxxxxx",value:i,onChange:g=>l(g.target.value),className:"pl-9 h-10 bg-background/50 border-primary/20 rounded-xl text-[11px]","aria-describedby":"migration-token-help"})]}),o.jsxs("p",{id:"migration-token-help",className:"text-[9px] text-muted-foreground/60 italic px-1",children:["Used once to run ",o.jsx("code",{className:"text-primary/70",children:"migrate.sh"})," on your backend."]})]})]}),o.jsxs("div",{className:"flex gap-3",children:[m&&o.jsx(Z,{variant:"ghost",onClick:d,className:"flex-1 h-11 text-[10px] font-bold uppercase tracking-widest opacity-60 hover:opacity-100","aria-label":"Skip migration (risky)",children:"Bypass (Risk)"}),o.jsx(Z,{onClick:u,disabled:h,className:"flex-1 h-11 bg-primary text-[10px] font-bold uppercase tracking-widest shadow-lg hover:shadow-primary/30",children:p?"Install Systems":"Normalize System"})]})]}),t&&o.jsxs("div",{className:"space-y-3",children:[o.jsxs(La,{variant:"destructive",className:"rounded-xl border-destructive/20 bg-destructive/5 text-destructive font-bold text-[11px]",children:[o.jsx(ls,{className:"h-4 w-4"}),o.jsx(Ia,{children:t})]}),o.jsx(Z,{variant:"outline",onClick:u,className:"w-full h-12 rounded-xl text-[10px] font-bold uppercase tracking-widest",children:"Retry Installation"})]})]})}function Au({step:e,currentStep:t,label:n}){const r=Array.isArray(e)?e.includes(t):t===e;return o.jsx("div",{className:me("px-3 py-1.5 rounded-full text-[9px] font-black uppercase tracking-[0.2em] transition-all duration-500",r?"bg-primary text-primary-foreground shadow-sm":"bg-muted text-muted-foreground opacity-40"),role:"status","aria-current":r,children:n})}function fy({className:e}){return o.jsxs("svg",{width:"512",height:"512",viewBox:"0 0 512 512",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:me("w-9 h-9",e),children:[o.jsx("path",{d:"M112 112H400C426.51 112 448 133.49 448 160V352C448 378.51 426.51 400 400 400H112C85.4903 400 64 378.51 64 352V160C64 133.49 85.4903 112 112 112Z",stroke:"currentColor",strokeWidth:"32",strokeLinecap:"round",strokeLinejoin:"round"}),o.jsx("path",{d:"M64 160 L240 290 C250 295 262 295 272 290 L448 160",stroke:"currentColor",strokeWidth:"28",strokeLinecap:"round",strokeLinejoin:"round"}),o.jsx("path",{d:"M256 160 C256 160 270 190 290 195 C270 200 256 230 256 230 C256 230 242 200 222 195 C242 190 256 160 256 160 Z",fill:"currentColor",className:"opacity-50"})]})}function K_({onComplete:e,open:t=!0,canClose:n=!1}){const[r,i]=w.useReducer(QL,Kp),{t:l}=tt();uy({page_id:"setup_wizard",system_instruction:l("setup.agent.systemInstruction"),data:{step:r.step,managedFlow:["managed-token","managed-org","provisioning","validating"].includes(r.step),projectId:r.projectId||null,hasAccessToken:!!r.managed.accessToken}});const u=w.useRef(""),d=w.useRef("");w.useEffect(()=>()=>{u.current="",d.current=""},[]);const h=w.useCallback((S,_)=>{i({type:"ADD_LOG",payload:{type:S,message:_}})},[]),m=w.useCallback(async()=>{i({type:"SET_ERROR",payload:null}),i({type:"SET_FETCHING_ORGS",payload:!0});const S=r.managed.accessToken.trim(),_=F_(S);if(!_.valid){i({type:"SET_ERROR",payload:_.message||"Invalid token"}),i({type:"SET_FETCHING_ORGS",payload:!1});return}try{u.current=S;const j=await e6(S);i({type:"SET_ORGANIZATIONS",payload:j}),i({type:"SET_STEP",payload:"managed-org"})}catch(j){const N=j instanceof Wr?j:new Error(String(j));i({type:"SET_ERROR",payload:N.message})}finally{i({type:"SET_FETCHING_ORGS",payload:!1})}},[r.managed.accessToken]),p=w.useCallback(async()=>{i({type:"SET_ERROR",payload:null}),i({type:"SET_STEP",payload:"provisioning"}),i({type:"CLEAR_LOGS"}),h("info","Connecting to Supabase provisioning engine...");const S=u.current||r.managed.accessToken.trim();let _=null;try{if(await t6({accessToken:S,orgId:r.managed.selectedOrg,projectName:r.managed.projectName,region:r.managed.region},j=>{switch(j.type){case"info":h("info",j.data);break;case"project_id":i({type:"SET_PROJECT_ID",payload:j.data});break;case"success":_=j.data,h("success","✨ Project ready! Initializing database..."),pm({url:Om(_.url),anonKey:_.anonKey.trim()}),d.current=_.dbPass,i({type:"SET_MIGRATION_STATUS",payload:{needsMigration:!0,dbVersion:null,appVersion:eo,isUnknown:!0}});break;case"error":i({type:"SET_ERROR",payload:j.data}),h("error",j.data);break}}),_){const j=_;await g(j.projectId,S,j.url,j.anonKey)}}catch(j){const N=j instanceof Wr?j:new Error(String(j));i({type:"SET_ERROR",payload:N.message}),h("error",`Provisioning failed: ${N.message}`)}},[r.managed.selectedOrg,r.managed.projectName,r.managed.region,r.managed.accessToken,h]),g=w.useCallback(async(S,_,j,N)=>{const A=S||r.projectId||F1(r.manual.url),T=_||u.current||r.managed.accessToken.trim(),O=j||r.manual.url,L=N||r.manual.anonKey;if(!A||!T){i({type:"SET_ERROR",payload:"Project ID and Access Token are required for migration."});return}i({type:"SET_STEP",payload:"migration"}),i({type:"SET_ERROR",payload:null}),i({type:"SET_MIGRATING",payload:!0}),i({type:"CLEAR_LOGS"}),h("info","📦 Preparing database schema initialization...");try{let M=!1;if(await n6({projectRef:A,dbPassword:d.current,accessToken:T,anonKey:L},B=>{switch(B.type){case"stdout":h("stdout",B.data);break;case"stderr":h("stderr",`⚠️ ${B.data}`);break;case"info":h("info",B.data);break;case"error":h("error",B.data);break;case"done":B.data==="success"?(M=!0,h("success","✅ Database setup complete!"),O&&L&&pm({url:Om(O),anonKey:L.trim()}),u.current="",d.current="",setTimeout(()=>{e(),window.location.reload()},2e3)):i({type:"SET_ERROR",payload:"Migration failed. Check terminal logs for details."});break}}),!M)throw new Error("Migration did not complete successfully")}catch(M){const B=M instanceof Wr?M:new Error(String(M));i({type:"SET_ERROR",payload:B.message}),h("error",`Migration failed: ${B.message}`)}finally{i({type:"SET_MIGRATING",payload:!1})}},[r.projectId,r.manual.url,r.manual.anonKey,r.managed.accessToken,h,e]),b=w.useCallback(async()=>{i({type:"SET_ERROR",payload:null}),i({type:"SET_STEP",payload:"validating"});const S=Om(r.manual.url),_=r.manual.anonKey.trim(),j=await I5(S,_);if(j.valid){i({type:"SET_MANUAL_URL",payload:S});const N=F1(S);N&&i({type:"SET_PROJECT_ID",payload:N}),pm({url:S,anonKey:_});try{const A=vp(S,_),T=await dy(A);i({type:"SET_MIGRATION_STATUS",payload:T}),T.needsMigration?i({type:"SET_STEP",payload:"migration"}):(h("success","✨ Database is already up-to-date! Redirecting..."),setTimeout(()=>{e(),window.location.reload()},2e3))}catch(A){console.warn("[SetupWizard] Migration check failed:",A),i({type:"SET_MIGRATION_STATUS",payload:{needsMigration:!0,dbVersion:null,appVersion:eo,isUnknown:!0}}),i({type:"SET_STEP",payload:"migration"})}}else i({type:"SET_ERROR",payload:j.error||"Connection failed"}),i({type:"SET_STEP",payload:"credentials"})},[r.manual.url,r.manual.anonKey,h,e]);if(!t)return null;const v={initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20}};return o.jsx("div",{className:"fixed inset-0 z-50 bg-background flex flex-col items-center justify-center p-0 md:p-8",children:o.jsxs("div",{className:"w-full h-full max-w-6xl mx-auto overflow-hidden bg-background/80 backdrop-blur-xl border border-border/50 shadow-2xl rounded-3xl flex",children:[o.jsxs("div",{className:"w-[280px] bg-muted/30 border-r border-border/10 p-8 flex flex-col justify-between relative overflow-hidden hidden md:flex shrink-0",children:[o.jsxs("div",{className:"space-y-8 relative z-10",children:[o.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[o.jsx("div",{className:"p-2 bg-primary rounded-lg flex-shrink-0",children:o.jsx(fy,{className:"w-5 h-5 text-primary-foreground"})}),o.jsx("span",{className:"font-black italic tracking-tighter uppercase text-xs truncate",children:"Automator Forge"})]}),o.jsxs("div",{className:"space-y-6",children:[o.jsx("p",{className:"text-[9px] font-black uppercase tracking-[0.4em] text-muted-foreground/30 ml-1",children:"Assembly Phase"}),o.jsxs("div",{className:"space-y-4 px-1",children:[o.jsx(Au,{step:"welcome",currentStep:r.step,label:l("setup.initiation")}),o.jsx(Au,{step:["type","managed-token","credentials"],currentStep:r.step,label:l("setup.coordinates")}),o.jsx(Au,{step:["managed-org","provisioning","validating"],currentStep:r.step,label:l("setup.foundation")}),o.jsx(Au,{step:"migration",currentStep:r.step,label:l("setup.ignition")})]})]})]}),o.jsx("div",{className:"relative z-10 space-y-4",children:o.jsxs("p",{className:"text-[9px] font-bold text-muted-foreground/30 uppercase tracking-[0.4em] px-2 text-center",children:["v",eo," // Stable Build"]})})]}),o.jsxs("div",{className:"flex-1 p-8 md:p-12 flex flex-col relative",children:[n&&o.jsx("button",{onClick:e,className:"absolute top-6 right-6 p-2 rounded-full hover:bg-secondary transition-colors z-[60]","aria-label":"Close setup wizard",children:o.jsx(on,{className:"w-5 h-5 text-muted-foreground opacity-40 hover:opacity-100 transition-opacity"})}),o.jsx("div",{className:"absolute top-6 right-6 flex items-center gap-4 z-50",children:o.jsx(ly,{})}),o.jsx(S_,{mode:"wait",children:o.jsxs(ir.div,{initial:"initial",animate:"animate",exit:"exit",variants:v,transition:{type:"spring",damping:25,stiffness:200},className:"flex-1 flex flex-col",children:[r.step==="welcome"&&o.jsx(s6,{onNext:()=>i({type:"SET_STEP",payload:"type"})}),r.step==="type"&&o.jsx(r6,{onManaged:()=>{i({type:"RESET_MANUAL_FLOW"}),i({type:"SET_STEP",payload:"managed-token"})},onManual:()=>{i({type:"RESET_MANAGED_FLOW"}),i({type:"SET_STEP",payload:"credentials"})},onBack:()=>i({type:"SET_STEP",payload:"welcome"})}),r.step==="managed-token"&&o.jsx(d6,{accessToken:r.managed.accessToken,error:r.error,isFetching:r.managed.isFetchingOrgs,onTokenChange:S=>i({type:"SET_ACCESS_TOKEN",payload:S}),onFetchOrgs:m,onBack:()=>i({type:"SET_STEP",payload:"type"})}),r.step==="managed-org"&&o.jsx(f6,{organizations:r.managed.organizations,selectedOrg:r.managed.selectedOrg,projectName:r.managed.projectName,region:r.managed.region,onOrgSelect:S=>i({type:"SET_SELECTED_ORG",payload:S}),onProjectNameChange:S=>i({type:"SET_PROJECT_NAME",payload:S}),onRegionChange:S=>i({type:"SET_REGION",payload:S}),onProvision:p,onBack:()=>i({type:"SET_STEP",payload:"managed-token"})}),r.step==="provisioning"&&o.jsx(h6,{logs:r.logs,error:r.error,onRetry:()=>i({type:"SET_STEP",payload:"managed-token"})}),r.step==="credentials"&&o.jsx(m6,{url:r.manual.url,anonKey:r.manual.anonKey,error:r.error,onUrlChange:S=>i({type:"SET_MANUAL_URL",payload:S}),onAnonKeyChange:S=>i({type:"SET_MANUAL_ANON_KEY",payload:S}),onSave:b,onBack:()=>i({type:"SET_STEP",payload:"type"})}),r.step==="migration"&&o.jsx(p6,{logs:r.logs,error:r.error,isMigrating:r.isMigrating,migrationStatus:r.migrationStatus,accessToken:r.managed.accessToken,onTokenChange:S=>i({type:"SET_ACCESS_TOKEN",payload:S}),onRunMigration:()=>g(),onBypass:()=>{e(),window.location.reload()}})]},r.step)})]})]})})}function Xr(e,t,{checkForDefaultPrevented:n=!0}={}){return function(i){if(e?.(i),n===!1||!i.defaultPrevented)return t?.(i)}}function g6(e,t){const n=w.createContext(t),r=l=>{const{children:u,...d}=l,h=w.useMemo(()=>d,Object.values(d));return o.jsx(n.Provider,{value:h,children:u})};r.displayName=e+"Provider";function i(l){const u=w.useContext(n);if(u)return u;if(t!==void 0)return t;throw new Error(`\`${l}\` must be used within \`${e}\``)}return[r,i]}function y6(e,t=[]){let n=[];function r(l,u){const d=w.createContext(u),h=n.length;n=[...n,u];const m=g=>{const{scope:b,children:v,...S}=g,_=b?.[e]?.[h]||d,j=w.useMemo(()=>S,Object.values(S));return o.jsx(_.Provider,{value:j,children:v})};m.displayName=l+"Provider";function p(g,b){const v=b?.[e]?.[h]||d,S=w.useContext(v);if(S)return S;if(u!==void 0)return u;throw new Error(`\`${g}\` must be used within \`${l}\``)}return[m,p]}const i=()=>{const l=n.map(u=>w.createContext(u));return function(d){const h=d?.[e]||l;return w.useMemo(()=>({[`__scope${e}`]:{...d,[e]:h}}),[d,h])}};return i.scopeName=e,[r,x6(i,...t)]}function x6(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(i=>({useScope:i(),scopeName:i.scopeName}));return function(l){const u=r.reduce((d,{useScope:h,scopeName:m})=>{const g=h(l)[`__scope${m}`];return{...d,...g}},{});return w.useMemo(()=>({[`__scope${t.scopeName}`]:u}),[u])}};return n.scopeName=t.scopeName,n}var $l=globalThis?.document?w.useLayoutEffect:()=>{},v6=mg[" useId ".trim().toString()]||(()=>{}),b6=0;function Dm(e){const[t,n]=w.useState(v6());return $l(()=>{n(r=>r??String(b6++))},[e]),e||(t?`radix-${t}`:"")}var w6=mg[" useInsertionEffect ".trim().toString()]||$l;function S6({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[i,l,u]=j6({defaultProp:t,onChange:n}),d=e!==void 0,h=d?e:i;{const p=w.useRef(e!==void 0);w.useEffect(()=>{const g=p.current;g!==d&&console.warn(`${r} is changing from ${g?"controlled":"uncontrolled"} to ${d?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),p.current=d},[d,r])}const m=w.useCallback(p=>{if(d){const g=k6(p)?p(e):p;g!==e&&u.current?.(g)}else l(p)},[d,e,l,u]);return[h,m]}function j6({defaultProp:e,onChange:t}){const[n,r]=w.useState(e),i=w.useRef(n),l=w.useRef(t);return w6(()=>{l.current=t},[t]),w.useEffect(()=>{i.current!==n&&(l.current?.(n),i.current=n)},[n,i]),[n,r,l]}function k6(e){return typeof e=="function"}function _6(e){const t=N6(e),n=w.forwardRef((r,i)=>{const{children:l,...u}=r,d=w.Children.toArray(l),h=d.find(E6);if(h){const m=h.props.children,p=d.map(g=>g===h?w.Children.count(m)>1?w.Children.only(null):w.isValidElement(m)?m.props.children:null:g);return o.jsx(t,{...u,ref:i,children:w.isValidElement(m)?w.cloneElement(m,void 0,p):null})}return o.jsx(t,{...u,ref:i,children:l})});return n.displayName=`${e}.Slot`,n}function N6(e){const t=w.forwardRef((n,r)=>{const{children:i,...l}=n;if(w.isValidElement(i)){const u=A6(i),d=C6(l,i.props);return i.type!==w.Fragment&&(d.ref=r?Sd(r,u):u),w.cloneElement(i,d)}return w.Children.count(i)>1?w.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var T6=Symbol("radix.slottable");function E6(e){return w.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===T6}function C6(e,t){const n={...t};for(const r in t){const i=e[r],l=t[r];/^on[A-Z]/.test(r)?i&&l?n[r]=(...d)=>{const h=l(...d);return i(...d),h}:i&&(n[r]=i):r==="style"?n[r]={...i,...l}:r==="className"&&(n[r]=[i,l].filter(Boolean).join(" "))}return{...e,...n}}function A6(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var R6=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],mr=R6.reduce((e,t)=>{const n=_6(`Primitive.${t}`),r=w.forwardRef((i,l)=>{const{asChild:u,...d}=i,h=u?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),o.jsx(h,{...d,ref:l})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function O6(e,t){e&&$_.flushSync(()=>e.dispatchEvent(t))}function Hl(e){const t=w.useRef(e);return w.useEffect(()=>{t.current=e}),w.useMemo(()=>(...n)=>t.current?.(...n),[])}function D6(e,t=globalThis?.document){const n=Hl(e);w.useEffect(()=>{const r=i=>{i.key==="Escape"&&n(i)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var M6="DismissableLayer",Yp="dismissableLayer.update",P6="dismissableLayer.pointerDownOutside",z6="dismissableLayer.focusOutside",q1,Y_=w.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),W_=w.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:i,onFocusOutside:l,onInteractOutside:u,onDismiss:d,...h}=e,m=w.useContext(Y_),[p,g]=w.useState(null),b=p?.ownerDocument??globalThis?.document,[,v]=w.useState({}),S=Va(t,B=>g(B)),_=Array.from(m.layers),[j]=[...m.layersWithOutsidePointerEventsDisabled].slice(-1),N=_.indexOf(j),A=p?_.indexOf(p):-1,T=m.layersWithOutsidePointerEventsDisabled.size>0,O=A>=N,L=U6(B=>{const P=B.target,q=[...m.branches].some(D=>D.contains(P));!O||q||(i?.(B),u?.(B),B.defaultPrevented||d?.())},b),M=B6(B=>{const P=B.target;[...m.branches].some(D=>D.contains(P))||(l?.(B),u?.(B),B.defaultPrevented||d?.())},b);return D6(B=>{A===m.layers.size-1&&(r?.(B),!B.defaultPrevented&&d&&(B.preventDefault(),d()))},b),w.useEffect(()=>{if(p)return n&&(m.layersWithOutsidePointerEventsDisabled.size===0&&(q1=b.body.style.pointerEvents,b.body.style.pointerEvents="none"),m.layersWithOutsidePointerEventsDisabled.add(p)),m.layers.add(p),$1(),()=>{n&&m.layersWithOutsidePointerEventsDisabled.size===1&&(b.body.style.pointerEvents=q1)}},[p,b,n,m]),w.useEffect(()=>()=>{p&&(m.layers.delete(p),m.layersWithOutsidePointerEventsDisabled.delete(p),$1())},[p,m]),w.useEffect(()=>{const B=()=>v({});return document.addEventListener(Yp,B),()=>document.removeEventListener(Yp,B)},[]),o.jsx(mr.div,{...h,ref:S,style:{pointerEvents:T?O?"auto":"none":void 0,...e.style},onFocusCapture:Xr(e.onFocusCapture,M.onFocusCapture),onBlurCapture:Xr(e.onBlurCapture,M.onBlurCapture),onPointerDownCapture:Xr(e.onPointerDownCapture,L.onPointerDownCapture)})});W_.displayName=M6;var L6="DismissableLayerBranch",I6=w.forwardRef((e,t)=>{const n=w.useContext(Y_),r=w.useRef(null),i=Va(t,r);return w.useEffect(()=>{const l=r.current;if(l)return n.branches.add(l),()=>{n.branches.delete(l)}},[n.branches]),o.jsx(mr.div,{...e,ref:i})});I6.displayName=L6;function U6(e,t=globalThis?.document){const n=Hl(e),r=w.useRef(!1),i=w.useRef(()=>{});return w.useEffect(()=>{const l=d=>{if(d.target&&!r.current){let h=function(){X_(P6,n,m,{discrete:!0})};const m={originalEvent:d};d.pointerType==="touch"?(t.removeEventListener("click",i.current),i.current=h,t.addEventListener("click",i.current,{once:!0})):h()}else t.removeEventListener("click",i.current);r.current=!1},u=window.setTimeout(()=>{t.addEventListener("pointerdown",l)},0);return()=>{window.clearTimeout(u),t.removeEventListener("pointerdown",l),t.removeEventListener("click",i.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function B6(e,t=globalThis?.document){const n=Hl(e),r=w.useRef(!1);return w.useEffect(()=>{const i=l=>{l.target&&!r.current&&X_(z6,n,{originalEvent:l},{discrete:!1})};return t.addEventListener("focusin",i),()=>t.removeEventListener("focusin",i)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function $1(){const e=new CustomEvent(Yp);document.dispatchEvent(e)}function X_(e,t,n,{discrete:r}){const i=n.originalEvent.target,l=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?O6(i,l):i.dispatchEvent(l)}var Mm="focusScope.autoFocusOnMount",Pm="focusScope.autoFocusOnUnmount",H1={bubbles:!1,cancelable:!0},V6="FocusScope",J_=w.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:i,onUnmountAutoFocus:l,...u}=e,[d,h]=w.useState(null),m=Hl(i),p=Hl(l),g=w.useRef(null),b=Va(t,_=>h(_)),v=w.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;w.useEffect(()=>{if(r){let _=function(T){if(v.paused||!d)return;const O=T.target;d.contains(O)?g.current=O:Hr(g.current,{select:!0})},j=function(T){if(v.paused||!d)return;const O=T.relatedTarget;O!==null&&(d.contains(O)||Hr(g.current,{select:!0}))},N=function(T){if(document.activeElement===document.body)for(const L of T)L.removedNodes.length>0&&Hr(d)};document.addEventListener("focusin",_),document.addEventListener("focusout",j);const A=new MutationObserver(N);return d&&A.observe(d,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",_),document.removeEventListener("focusout",j),A.disconnect()}}},[r,d,v.paused]),w.useEffect(()=>{if(d){K1.add(v);const _=document.activeElement;if(!d.contains(_)){const N=new CustomEvent(Mm,H1);d.addEventListener(Mm,m),d.dispatchEvent(N),N.defaultPrevented||(F6(K6(Q_(d)),{select:!0}),document.activeElement===_&&Hr(d))}return()=>{d.removeEventListener(Mm,m),setTimeout(()=>{const N=new CustomEvent(Pm,H1);d.addEventListener(Pm,p),d.dispatchEvent(N),N.defaultPrevented||Hr(_??document.body,{select:!0}),d.removeEventListener(Pm,p),K1.remove(v)},0)}}},[d,m,p,v]);const S=w.useCallback(_=>{if(!n&&!r||v.paused)return;const j=_.key==="Tab"&&!_.altKey&&!_.ctrlKey&&!_.metaKey,N=document.activeElement;if(j&&N){const A=_.currentTarget,[T,O]=q6(A);T&&O?!_.shiftKey&&N===O?(_.preventDefault(),n&&Hr(T,{select:!0})):_.shiftKey&&N===T&&(_.preventDefault(),n&&Hr(O,{select:!0})):N===A&&_.preventDefault()}},[n,r,v.paused]);return o.jsx(mr.div,{tabIndex:-1,...u,ref:b,onKeyDown:S})});J_.displayName=V6;function F6(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Hr(r,{select:t}),document.activeElement!==n)return}function q6(e){const t=Q_(e),n=G1(t,e),r=G1(t.reverse(),e);return[n,r]}function Q_(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const i=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||i?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function G1(e,t){for(const n of e)if(!$6(n,{upTo:t}))return n}function $6(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function H6(e){return e instanceof HTMLInputElement&&"select"in e}function Hr(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&H6(e)&&t&&e.select()}}var K1=G6();function G6(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=Y1(e,t),e.unshift(t)},remove(t){e=Y1(e,t),e[0]?.resume()}}}function Y1(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function K6(e){return e.filter(t=>t.tagName!=="A")}var Y6="Portal",Z_=w.forwardRef((e,t)=>{const{container:n,...r}=e,[i,l]=w.useState(!1);$l(()=>l(!0),[]);const u=n||i&&globalThis?.document?.body;return u?a6.createPortal(o.jsx(mr.div,{...r,ref:t}),u):null});Z_.displayName=Y6;function W6(e,t){return w.useReducer((n,r)=>t[n][r]??n,e)}var Ad=e=>{const{present:t,children:n}=e,r=X6(t),i=typeof n=="function"?n({present:r.isPresent}):w.Children.only(n),l=Va(r.ref,J6(i));return typeof n=="function"||r.isPresent?w.cloneElement(i,{ref:l}):null};Ad.displayName="Presence";function X6(e){const[t,n]=w.useState(),r=w.useRef(null),i=w.useRef(e),l=w.useRef("none"),u=e?"mounted":"unmounted",[d,h]=W6(u,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return w.useEffect(()=>{const m=Ru(r.current);l.current=d==="mounted"?m:"none"},[d]),$l(()=>{const m=r.current,p=i.current;if(p!==e){const b=l.current,v=Ru(m);e?h("MOUNT"):v==="none"||m?.display==="none"?h("UNMOUNT"):h(p&&b!==v?"ANIMATION_OUT":"UNMOUNT"),i.current=e}},[e,h]),$l(()=>{if(t){let m;const p=t.ownerDocument.defaultView??window,g=v=>{const _=Ru(r.current).includes(CSS.escape(v.animationName));if(v.target===t&&_&&(h("ANIMATION_END"),!i.current)){const j=t.style.animationFillMode;t.style.animationFillMode="forwards",m=p.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=j)})}},b=v=>{v.target===t&&(l.current=Ru(r.current))};return t.addEventListener("animationstart",b),t.addEventListener("animationcancel",g),t.addEventListener("animationend",g),()=>{p.clearTimeout(m),t.removeEventListener("animationstart",b),t.removeEventListener("animationcancel",g),t.removeEventListener("animationend",g)}}else h("ANIMATION_END")},[t,h]),{isPresent:["mounted","unmountSuspended"].includes(d),ref:w.useCallback(m=>{r.current=m?getComputedStyle(m):null,n(m)},[])}}function Ru(e){return e?.animationName||"none"}function J6(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var zm=0;function Q6(){w.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??W1()),document.body.insertAdjacentElement("beforeend",e[1]??W1()),zm++,()=>{zm===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),zm--}},[])}function W1(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var Yu="right-scroll-bar-position",Wu="width-before-scroll-bar",Z6="with-scroll-bars-hidden",eI="--removed-body-scroll-bar-size";function Lm(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function tI(e,t){var n=w.useState(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(r){var i=n.value;i!==r&&(n.value=r,n.callback(r,i))}}}})[0];return n.callback=t,n.facade}var nI=typeof window<"u"?w.useLayoutEffect:w.useEffect,X1=new WeakMap;function sI(e,t){var n=tI(null,function(r){return e.forEach(function(i){return Lm(i,r)})});return nI(function(){var r=X1.get(n);if(r){var i=new Set(r),l=new Set(e),u=n.current;i.forEach(function(d){l.has(d)||Lm(d,null)}),l.forEach(function(d){i.has(d)||Lm(d,u)})}X1.set(n,e)},[e]),n}function rI(e){return e}function aI(e,t){t===void 0&&(t=rI);var n=[],r=!1,i={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(l){var u=t(l,r);return n.push(u),function(){n=n.filter(function(d){return d!==u})}},assignSyncMedium:function(l){for(r=!0;n.length;){var u=n;n=[],u.forEach(l)}n={push:function(d){return l(d)},filter:function(){return n}}},assignMedium:function(l){r=!0;var u=[];if(n.length){var d=n;n=[],d.forEach(l),u=n}var h=function(){var p=u;u=[],p.forEach(l)},m=function(){return Promise.resolve().then(h)};m(),n={push:function(p){u.push(p),m()},filter:function(p){return u=u.filter(p),n}}}};return i}function iI(e){e===void 0&&(e={});var t=aI(null);return t.options=Os({async:!0,ssr:!1},e),t}var eN=function(e){var t=e.sideCar,n=uo(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=t.read();if(!r)throw new Error("Sidecar medium not found");return w.createElement(r,Os({},n))};eN.isSideCarExport=!0;function oI(e,t){return e.useMedium(t),eN}var tN=iI(),Im=function(){},Rd=w.forwardRef(function(e,t){var n=w.useRef(null),r=w.useState({onScrollCapture:Im,onWheelCapture:Im,onTouchMoveCapture:Im}),i=r[0],l=r[1],u=e.forwardProps,d=e.children,h=e.className,m=e.removeScrollBar,p=e.enabled,g=e.shards,b=e.sideCar,v=e.noRelative,S=e.noIsolation,_=e.inert,j=e.allowPinchZoom,N=e.as,A=N===void 0?"div":N,T=e.gapMode,O=uo(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),L=b,M=sI([n,t]),B=Os(Os({},O),i);return w.createElement(w.Fragment,null,p&&w.createElement(L,{sideCar:tN,removeScrollBar:m,shards:g,noRelative:v,noIsolation:S,inert:_,setCallbacks:l,allowPinchZoom:!!j,lockRef:n,gapMode:T}),u?w.cloneElement(w.Children.only(d),Os(Os({},B),{ref:M})):w.createElement(A,Os({},B,{className:h,ref:M}),d))});Rd.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};Rd.classNames={fullWidth:Wu,zeroRight:Yu};var lI=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function cI(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=lI();return t&&e.setAttribute("nonce",t),e}function uI(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function dI(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var fI=function(){var e=0,t=null;return{add:function(n){e==0&&(t=cI())&&(uI(t,n),dI(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},hI=function(){var e=fI();return function(t,n){w.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},nN=function(){var e=hI(),t=function(n){var r=n.styles,i=n.dynamic;return e(r,i),null};return t},mI={left:0,top:0,right:0,gap:0},Um=function(e){return parseInt(e||"",10)||0},pI=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],r=t[e==="padding"?"paddingTop":"marginTop"],i=t[e==="padding"?"paddingRight":"marginRight"];return[Um(n),Um(r),Um(i)]},gI=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return mI;var t=pI(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},yI=nN(),to="data-scroll-locked",xI=function(e,t,n,r){var i=e.left,l=e.top,u=e.right,d=e.gap;return n===void 0&&(n="margin"),`
|
|
110
110
|
.`.concat(Z6,` {
|
|
111
111
|
overflow: hidden `).concat(r,`;
|
|
@@ -213,5 +213,5 @@ Overall it looks solid, though I have a few minor questions about the timeline.
|
|
|
213
213
|
I've analyzed the key points and everything aligns with our objectives. Specifically, the timeline looks realistic and the budget is within scope. I do have a couple of questions regarding the implementation phase, but we can cover those in our next sync.`,p+=`
|
|
214
214
|
|
|
215
215
|
${m}`,p};return o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"space-y-2 text-center md:text-left",children:[o.jsx("h2",{className:"text-xl font-semibold tracking-tight",children:"✍️ How do you communicate?"}),o.jsx("p",{className:"text-muted-foreground",children:"We'll adjust all drafts to match your natural style."})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsx(Ge,{children:"Default Tone"}),o.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:nq.map(d=>o.jsx($e,{className:me("cursor-pointer transition-all hover:bg-accent/50",e.preferred_tone===d.id?"border-primary bg-accent":""),onClick:()=>t({preferred_tone:d.id}),children:o.jsxs(vt,{className:"p-3",children:[o.jsx("p",{className:"font-medium text-sm",children:d.label}),o.jsx("p",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:d.example})]})},d.id))})]}),o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"flex justify-between",children:[o.jsx(Ge,{children:"Response Length"}),o.jsx("span",{className:"text-sm text-muted-foreground capitalize",children:e.preferred_length||"medium"})]}),o.jsx("input",{type:"range",min:"1",max:"3",step:"1",className:"w-full h-2 bg-secondary rounded-lg appearance-none cursor-pointer accent-primary",value:e.preferred_length==="brief"?1:e.preferred_length==="detailed"?3:2,onChange:d=>{const h=parseInt(d.target.value);t({preferred_length:h===1?"brief":h===3?"detailed":"medium"})}}),o.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[o.jsx("span",{children:"Brief"}),o.jsx("span",{children:"Medium"}),o.jsx("span",{children:"Detailed"})]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Ge,{htmlFor:"signature",children:"Signature"}),o.jsx("textarea",{id:"signature",className:"flex min-h-[60px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",rows:2,placeholder:`Best,
|
|
216
|
-
Trung Le`,value:e.signature||"",onChange:d=>t({signature:d.target.value})})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Ge,{children:"Common Phrases"}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Ce,{placeholder:"e.g., Thanks for reaching out",value:n,onChange:d=>r(d.target.value),onKeyDown:d=>d.key==="Enter"&&i()}),o.jsx(Z,{size:"icon",variant:"secondary",onClick:i,children:o.jsx(lr,{className:"h-4 w-4"})})]}),o.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:e.common_phrases?.map((d,h)=>o.jsxs("div",{className:"bg-secondary text-secondary-foreground px-2 py-1 rounded-md text-xs flex items-center gap-1",children:[d,o.jsx(on,{className:"h-3 w-3 cursor-pointer hover:text-destructive",onClick:()=>l(d)})]},h))})]}),o.jsxs("div",{className:"mt-6 pt-4 border-t",children:[o.jsx(Ge,{className:"text-muted-foreground mb-2 block",children:"Preview: How your drafts will look"}),o.jsx("div",{className:"bg-muted/30 border rounded-lg p-4 font-mono text-sm whitespace-pre-wrap",children:u()})]})]})}function rq({data:e,updateData:t}){const[n,r]=w.useState(""),[i,l]=w.useState(""),u=()=>{if(n.trim()){const g=e.vip_senders||[];g.includes(n.trim())||t({vip_senders:[...g,n.trim()]}),r("")}},d=g=>{const b=e.vip_senders||[];t({vip_senders:b.filter(v=>v!==g)})},h=()=>{if(i.trim()){let g=i.trim();g.startsWith("@")&&(g=g.substring(1));const b=e.trusted_domains||[];b.includes(g)||t({trusted_domains:[...b,g]}),l("")}},m=g=>{const b=e.trusted_domains||[];t({trusted_domains:b.filter(v=>v!==g)})},p=[{id:"newsletters",label:"Newsletters"},{id:"social_media",label:"Social media"},{id:"marketing",label:"Marketing emails"}];return o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"space-y-2 text-center md:text-left",children:[o.jsx("h2",{className:"text-xl font-semibold tracking-tight",children:"⭐ Who's important to you?"}),o.jsx("p",{className:"text-muted-foreground",children:"We'll prioritize emails from these people and domains."})]}),o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(ip,{className:"h-4 w-4 text-yellow-500"}),o.jsx(Ge,{children:"VIPs (Always High Priority)"})]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Ce,{placeholder:"investor@vc.com",value:n,onChange:g=>r(g.target.value),onKeyDown:g=>g.key==="Enter"&&u()}),o.jsx(Z,{size:"icon",variant:"secondary",onClick:u,children:o.jsx(lr,{className:"h-4 w-4"})})]}),o.jsxs("div",{className:"space-y-2 max-h-[150px] overflow-y-auto",children:[e.vip_senders?.map((g,b)=>o.jsxs("div",{className:"flex items-center justify-between bg-secondary/50 p-2 rounded-md text-sm",children:[o.jsx("span",{children:g}),o.jsx(Z,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>d(g),children:o.jsx(on,{className:"h-3 w-3"})})]},b)),(!e.vip_senders||e.vip_senders.length===0)&&o.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No VIPs added yet"})]})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(eO,{className:"h-4 w-4 text-blue-500"}),o.jsx(Ge,{children:"Team & Trusted Domains"})]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Ce,{placeholder:"company.com",value:i,onChange:g=>l(g.target.value),onKeyDown:g=>g.key==="Enter"&&h()}),o.jsx(Z,{size:"icon",variant:"secondary",onClick:h,children:o.jsx(lr,{className:"h-4 w-4"})})]}),o.jsxs("div",{className:"space-y-2 max-h-[150px] overflow-y-auto",children:[e.trusted_domains?.map((g,b)=>o.jsxs("div",{className:"flex items-center justify-between bg-secondary/50 p-2 rounded-md text-sm",children:[o.jsxs("span",{children:["@",g]}),o.jsx(Z,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>m(g),children:o.jsx(on,{className:"h-3 w-3"})})]},b)),(!e.trusted_domains||e.trusted_domains.length===0)&&o.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No domains added yet"})]})]})]}),o.jsxs("div",{className:"p-4 bg-muted/30 rounded-lg space-y-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(tj,{className:"h-4 w-4 text-muted-foreground"}),o.jsx(Ge,{children:"Low Priority (Auto-Archive)"})]}),o.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:p.map(g=>o.jsxs("div",{className:"flex items-center space-x-2",children:[o.jsx("input",{type:"checkbox",id:g.id,className:"accent-primary h-4 w-4",defaultChecked:!0}),o.jsx("label",{htmlFor:g.id,className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:g.label})]},g.id))})]}),o.jsxs("div",{className:"bg-blue-500/10 text-blue-500 text-sm p-4 rounded-lg flex items-start gap-2",children:[o.jsx(vg,{className:"h-4 w-4 mt-0.5 shrink-0"}),o.jsx("p",{children:'Tip: Adding your own company domain (@realtimex.ai) to "Team" ensures internal emails are never missed.'})]})]})}const aq=[{id:"inbox_zero",label:"Inbox Zero Daily",icon:wA},{id:"respond_faster",label:"Respond Faster",icon:UR},{id:"focus",label:"Focus on Important",icon:cj},{id:"reduce_time",label:"Reduce Email Time",icon:ea}],iq=[{id:"legal",label:"Legal documents"},{id:"hr",label:"HR & payroll"},{id:"financial",label:"Financial transactions"},{id:"security",label:"Security alerts"}];function oq({data:e,updateData:t}){const n=r=>{const i=e.never_automate_categories||[];i.includes(r)?t({never_automate_categories:i.filter(l=>l!==r)}):t({never_automate_categories:[...i,r]})};return o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"space-y-2 text-center md:text-left",children:[o.jsx("h2",{className:"text-xl font-semibold tracking-tight",children:"🎯 What are your email goals?"}),o.jsx("p",{className:"text-muted-foreground",children:"Let's set up automation that works for your specific targets."})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsx(Ge,{children:"Primary Goal"}),o.jsx("div",{className:"grid grid-cols-2 gap-3",children:aq.map(r=>o.jsx($e,{className:me("cursor-pointer transition-all hover:bg-accent/50",e.primary_goal===r.id?"border-primary bg-accent":""),onClick:()=>t({primary_goal:r.id}),children:o.jsxs(vt,{className:"flex flex-col items-center justify-center p-4 text-center space-y-2",children:[o.jsx(r.icon,{className:me("h-6 w-6",e.primary_goal===r.id?"text-primary":"text-muted-foreground")}),o.jsx("span",{className:"font-medium text-sm",children:r.label})]})},r.id))})]}),o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"flex justify-between",children:[o.jsx(Ge,{children:"Time Budget"}),o.jsxs("span",{className:"text-sm text-muted-foreground",children:[e.time_budget_minutes||30," minutes / day"]})]}),o.jsx("input",{type:"range",min:"15",max:"120",step:"15",className:"w-full h-2 bg-secondary rounded-lg appearance-none cursor-pointer accent-primary",value:e.time_budget_minutes||30,onChange:r=>t({time_budget_minutes:parseInt(r.target.value)})}),o.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[o.jsx("span",{children:"15 min"}),o.jsx("span",{children:"1 hour"}),o.jsx("span",{children:"2 hours"})]})]}),o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"flex justify-between",children:[o.jsx(Ge,{children:"Automation Level"}),o.jsx("span",{className:"text-sm text-muted-foreground",children:!e.automation_level||e.automation_level<=3?"Conservative":e.automation_level<=7?"Balanced":"Aggressive"})]}),o.jsxs("div",{className:"relative pt-6",children:[o.jsxs("div",{className:"absolute top-0 w-full flex justify-between text-xs font-medium text-muted-foreground px-1",children:[o.jsx("span",{children:"Manual"}),o.jsx("span",{children:"Fully Automated"})]}),o.jsx("input",{type:"range",min:"1",max:"10",step:"1",className:"w-full h-2 bg-gradient-to-r from-blue-500/20 to-blue-500 rounded-lg appearance-none cursor-pointer accent-primary",value:e.automation_level||5,onChange:r=>t({automation_level:parseInt(r.target.value)})}),o.jsx("p",{className:"text-xs text-muted-foreground mt-2 text-center",children:e.automation_level&&e.automation_level>7?"AI drafts and organizes aggressively. You review key items.":"AI suggests drafts. You maintain full control."})]})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(wR,{className:"h-4 w-4 text-destructive"}),o.jsx(Ge,{children:"Never Automate (Safety)"})]}),o.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:iq.map(r=>o.jsxs("div",{className:"flex items-center space-x-2 border p-3 rounded-md bg-background",children:[o.jsx(gy,{id:`safety-${r.id}`,checked:e.never_automate_categories?.includes(r.id),onCheckedChange:()=>n(r.id)}),o.jsx(Ge,{htmlFor:`safety-${r.id}`,className:"cursor-pointer",children:r.label})]},r.id))})]}),o.jsxs("div",{className:"bg-emerald-500/10 border border-emerald-500/20 text-emerald-600 dark:text-emerald-400 p-4 rounded-lg",children:[o.jsxs("div",{className:"flex items-center gap-2 mb-2 font-medium",children:[o.jsx(gg,{className:"h-4 w-4"}),"Expected Results"]}),o.jsxs("ul",{className:"text-sm space-y-1 list-disc list-inside opacity-90",children:[o.jsx("li",{children:"Save ~2 hours per week"}),o.jsx("li",{children:"Respond 50% faster to clients"}),o.jsx("li",{children:"Zero missed important emails"})]})]})]})}const Bu=4;function R2({onComplete:e,onClose:t,initialData:n,className:r}){const{t:i}=tt(),{state:l}=Tn(),{user:u}=l,[d,h]=w.useState(1),[m,p]=w.useState(!1),[g,b]=w.useState(n||{work_style:"startup",preferred_tone:"professional",preferred_length:"medium",primary_goal:"inbox_zero",vip_senders:[],trusted_domains:[],blocked_domains:[],never_automate_categories:["legal","hr","financial"],automation_level:5,time_budget_minutes:30}),v=()=>{d<Bu?h(T=>T+1):_()},S=()=>{d>1?h(T=>T-1):t&&t()},_=async()=>{if(u){p(!0);try{const{error:T}=await gt.from("user_settings").update({...g,persona_completed:!0,persona_completed_at:new Date().toISOString()}).eq("user_id",u.id);if(T)throw T;le.success("Persona saved successfully!"),e()}catch(T){console.error("Failed to save persona:",T),le.error("Failed to save persona. Please try again.")}finally{p(!1)}}},j=T=>{b(O=>({...O,...T}))},N=()=>{switch(d){case 1:return o.jsx(tq,{data:g,updateData:j});case 2:return o.jsx(sq,{data:g,updateData:j});case 3:return o.jsx(rq,{data:g,updateData:j});case 4:return o.jsx(oq,{data:g,updateData:j});default:return null}},A=d/Bu*100;return o.jsxs($e,{className:me("w-full max-w-2xl mx-auto border-none shadow-none md:border md:shadow-lg",r),children:[o.jsxs(Ot,{children:[o.jsxs("div",{className:"flex items-center justify-between mb-2",children:[o.jsxs("span",{className:"text-sm text-muted-foreground",children:["Step ",d," of ",Bu]}),t&&o.jsx(Z,{variant:"ghost",size:"sm",onClick:t,children:"Skip"})]}),o.jsx(Py,{value:A,className:"h-2"})]}),o.jsx(vt,{className:"py-4 max-h-[60vh] overflow-y-auto",children:N()}),o.jsxs(Jj,{className:"flex justify-between",children:[o.jsx(Z,{variant:"outline",onClick:S,disabled:m,children:d===1&&t?"Cancel":"Back"}),o.jsxs(Z,{onClick:v,disabled:m,children:[m&&o.jsx(wt,{className:"mr-2 h-4 w-4 animate-spin"}),d===Bu?"Complete Setup":"Next"]})]})]})}function lq(){const{t:e}=tt(),{state:t,actions:n}=Tn(),[r,i]=w.useState(!1),l=t.settings||{persona_completed:!1},u=async()=>{i(!1),await n.fetchSettings()};return r?o.jsx(is,{open:!0,onOpenChange:i,children:o.jsxs(os,{className:"max-w-5xl sm:max-w-5xl h-[80vh] flex flex-col p-0 overflow-hidden",children:[o.jsxs("div",{className:"p-6 pb-0",children:[o.jsx(bs,{children:e("persona.edit.title")||"Edit Persona"}),o.jsx(fr,{children:e("persona.edit.desc")||"Update your digital assistant preferences."})]}),o.jsx("div",{className:"flex-1 overflow-y-auto p-6 pt-2",children:o.jsx(R2,{initialData:l,onComplete:u,onClose:()=>i(!1),className:"max-w-none shadow-none border-0 p-0"})})]})}):o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"text-lg font-medium",children:e("persona.title")||"Digital Persona"}),o.jsx("p",{className:"text-sm text-muted-foreground",children:e("persona.subtitle")||"Manage how your AI assistant represents you."})]}),o.jsxs(Z,{onClick:()=>i(!0),className:"gap-2",children:[o.jsx(oj,{className:"w-4 h-4"}),e("common.edit")||"Edit Persona"]})]}),o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[o.jsxs($e,{children:[o.jsx(Ot,{className:"pb-3",children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(wd,{className:"w-5 h-5 text-primary"}),o.jsx(Bt,{className:"text-base",children:e("persona.identity")||"Identity"})]})}),o.jsx(vt,{className:"space-y-4 text-sm",children:o.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-2",children:[o.jsx("span",{className:"text-muted-foreground",children:"Role:"}),o.jsx("span",{className:"font-medium text-right",children:l.role||"Not set"}),o.jsx("span",{className:"text-muted-foreground",children:"Industry:"}),o.jsx("span",{className:"font-medium text-right",children:l.industry||"Not set"}),o.jsx("span",{className:"text-muted-foreground",children:"Style:"}),o.jsx("span",{className:"font-medium capitalize text-right",children:l.work_style||"Not set"})]})})]}),o.jsxs($e,{children:[o.jsx(Ot,{className:"pb-3",children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(vd,{className:"w-5 h-5 text-indigo-500"}),o.jsx(Bt,{className:"text-base",children:e("persona.communication")||"Communication"})]})}),o.jsx(vt,{className:"space-y-4 text-sm",children:o.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-2",children:[o.jsx("span",{className:"text-muted-foreground",children:"Tone:"}),o.jsx("span",{className:"font-medium capitalize text-right",children:l.preferred_tone||"Professional"}),o.jsx("span",{className:"text-muted-foreground",children:"Length:"}),o.jsx("span",{className:"font-medium capitalize text-right",children:l.preferred_length||"Medium"}),o.jsx("span",{className:"text-muted-foreground",children:"Languages:"}),o.jsx("div",{className:"flex justify-end gap-1 flex-wrap",children:(l.common_phrases?.length||0)>0?o.jsx(El,{variant:"secondary",className:"text-xs",children:"Custom Phrases Active"}):o.jsx("span",{className:"text-muted-foreground italic",children:"None"})})]})})]}),o.jsxs($e,{children:[o.jsx(Ot,{className:"pb-3",children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(cj,{className:"w-5 h-5 text-emerald-500"}),o.jsx(Bt,{className:"text-base",children:e("persona.automation")||"Automation"})]})}),o.jsxs(vt,{className:"space-y-4 text-sm",children:[o.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-2",children:[o.jsx("span",{className:"text-muted-foreground",children:"Primary Goal:"}),o.jsx("span",{className:"font-medium capitalize text-right",children:l.primary_goal?.replace("_"," ")||"Inbox Zero"}),o.jsx("span",{className:"text-muted-foreground",children:"Auto Level:"}),o.jsx("div",{className:"flex items-center justify-end gap-2",children:o.jsxs("span",{className:"font-medium",children:[l.automation_level||5,"/10"]})})]}),(l.never_automate_categories?.length||0)>0&&o.jsxs("div",{className:"pt-2",children:[o.jsx("span",{className:"text-xs text-muted-foreground block mb-1",children:"Never Automate:"}),o.jsx("div",{className:"flex flex-wrap gap-1",children:l.never_automate_categories?.map(d=>o.jsx(El,{variant:"outline",className:"text-xs py-0 h-5 bg-background",children:d},d))})]})]})]}),o.jsxs($e,{children:[o.jsx(Ot,{className:"pb-3",children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(rj,{className:"w-5 h-5 text-sky-500"}),o.jsx(Bt,{className:"text-base",children:e("persona.network")||"Network"})]})}),o.jsxs(vt,{className:"space-y-4 text-sm",children:[o.jsxs("div",{children:[o.jsxs("span",{className:"text-xs text-muted-foreground block mb-2",children:["VIP Senders (",l.vip_senders?.length||0,")"]}),o.jsxs("div",{className:"flex flex-wrap gap-1 max-h-[60px] overflow-hidden",children:[l.vip_senders?.slice(0,3).map(d=>o.jsx(El,{variant:"secondary",className:"text-xs py-0 h-5 truncate max-w-[150px]",children:d},d)),(l.vip_senders?.length||0)>3&&o.jsxs("span",{className:"text-xs text-muted-foreground flex items-center",children:["+",l.vip_senders.length-3," more"]})]})]}),o.jsx("div",{className:"pt-2 border-t mt-2",children:o.jsxs("div",{className:"flex justify-between items-center",children:[o.jsx("span",{className:"text-muted-foreground",children:"Trusted Domains:"}),o.jsx("span",{className:"font-medium",children:l.trusted_domains?.length||0})]})})]})]})]})]})}function cq(){const{t:e}=tt(),[t,n]=w.useState("profile"),{state:r,actions:i}=Tn();w.useEffect(()=>{i.fetchProfile()},[]);const l=[{id:"profile",label:e("account.profile"),icon:wd},{id:"persona",label:e("persona.title")||"Persona",icon:WR},{id:"security",label:e("account.security"),icon:wg},{id:"database",label:e("account.database"),icon:Ra}];return o.jsxs("div",{className:"max-w-4xl mx-auto space-y-6 animate-in fade-in duration-500",children:[o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsx("h1",{className:"text-3xl font-bold tracking-tight",children:e("account.title")}),o.jsx("p",{className:"text-muted-foreground",children:e("account.subtitle")})]}),o.jsxs("div",{className:"flex flex-col md:flex-row gap-8",children:[o.jsxs("aside",{className:"w-full md:w-64 flex flex-col justify-between",children:[o.jsx("nav",{className:"space-y-1",children:l.map(u=>{const d=u.icon,h=t===u.id;return o.jsxs("button",{onClick:()=>n(u.id),className:`w-full flex items-center gap-3 px-4 py-2 text-sm font-medium rounded-lg transition-colors ${h?"bg-primary text-primary-foreground":"hover:bg-secondary text-muted-foreground"}`,children:[o.jsx(d,{className:"w-4 h-4"}),u.label]},u.id)})}),o.jsxs("div",{className:"mt-auto space-y-1",children:[o.jsxs("button",{onClick:async()=>{await gt.auth.signOut(),J5(),le.success(e("account.logoutSuccess")),window.location.reload()},className:"w-full flex items-center gap-3 px-4 py-2 text-sm font-medium rounded-lg transition-colors hover:bg-destructive/10 text-destructive",children:[o.jsx(BA,{className:"w-4 h-4"}),e("account.logout")]}),o.jsxs("div",{className:"px-4 py-4 border-t border-border/40 text-center md:text-left",children:[o.jsx("p",{className:"text-[10px] font-bold text-muted-foreground/50 uppercase tracking-widest mb-1",children:e("account.version")}),o.jsxs("p",{className:"text-xs font-mono text-muted-foreground/70",children:["v","2.23.2"]})]})]})]}),o.jsxs("div",{className:"flex-1 space-y-6",children:[t==="profile"&&o.jsx(uq,{}),t==="persona"&&o.jsx(lq,{}),t==="security"&&o.jsx(dq,{}),t==="database"&&o.jsx(fq,{})]})]})]})}function uq(){const{t:e}=tt(),{state:t,actions:n}=Tn(),[r,i]=w.useState(""),[l,u]=w.useState(""),[d,h]=w.useState(!1),[m,p]=w.useState(!1),[g,b]=w.useState(Ms.isEnabled());w.useEffect(()=>{t.profile&&(i(t.profile.first_name||""),u(t.profile.last_name||""))},[t.profile]);const v=()=>{const j=!g;Ms.setEnabled(j),b(j),j?(Ms.playSuccess(),le.success(e("account.profile.soundsEnabled"))):le.info(e("account.profile.soundsDisabled"))},S=async()=>{h(!0);const j=await n.updateProfile({first_name:r,last_name:l});h(!1),j&&le.success(e("account.profile.updated"))},_=async j=>{const N=j.target.files?.[0];if(!(!N||!t.user)){p(!0);try{const A=N.name.split(".").pop(),T=`${t.user.id}/avatar.${A}`,{data:O,error:L}=await gt.storage.from("avatars").upload(T,N,{upsert:!0});if(L)throw L;const{data:{publicUrl:M}}=gt.storage.from("avatars").getPublicUrl(T);await n.updateProfile({avatar_url:M}),le.success(e("account.profile.avatarUpdated"))}catch(A){console.error("Avatar upload error:",A),le.error(e("account.profile.avatarError"))}finally{p(!1)}}};return o.jsxs($e,{children:[o.jsxs(Ot,{children:[o.jsx(Bt,{children:e("account.profile.title")}),o.jsx(xs,{children:e("account.profile.desc")})]}),o.jsxs(vt,{className:"space-y-6",children:[o.jsxs("div",{className:"flex flex-col items-center sm:flex-row sm:items-start gap-6",children:[o.jsxs("div",{className:"relative group",children:[o.jsx("div",{className:"w-24 h-24 rounded-full bg-secondary overflow-hidden border-2 border-border flex items-center justify-center",children:t.profile?.avatar_url?o.jsx("img",{src:t.profile.avatar_url,alt:"Avatar",className:"w-full h-full object-cover"}):o.jsx(wd,{className:"w-12 h-12 text-muted-foreground"})}),o.jsxs("label",{className:"absolute inset-0 flex items-center justify-center bg-black/40 rounded-full opacity-0 group-hover:opacity-100 cursor-pointer transition-opacity",children:[o.jsx(CC,{className:"w-6 h-6 text-white"}),o.jsx("input",{type:"file",className:"hidden",accept:"image/*",onChange:_,disabled:m})]}),m&&o.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/60 rounded-full",children:o.jsx(pt,{size:"sm"})})]}),o.jsxs("div",{className:"flex-1 space-y-4 w-full",children:[o.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Ge,{htmlFor:"first-name",children:e("account.profile.firstName")}),o.jsx(Ce,{id:"first-name",value:r,onChange:j=>i(j.target.value),placeholder:e("account.profile.firstNamePlaceholder")})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Ge,{htmlFor:"last-name",children:e("account.profile.lastName")}),o.jsx(Ce,{id:"last-name",value:l,onChange:j=>u(j.target.value),placeholder:e("account.profile.lastNamePlaceholder")})]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Ge,{htmlFor:"email",children:e("account.profile.email")}),o.jsx(Ce,{id:"email",value:t.profile?.email||"",disabled:!0,className:"bg-secondary/50"}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:e("account.profile.emailHelp")})]})]})]}),o.jsxs("div",{className:"pt-6 border-t flex items-center justify-between",children:[o.jsxs("div",{className:"space-y-0.5",children:[o.jsx("label",{className:"text-sm font-medium",children:e("account.profile.sounds")}),o.jsx("p",{className:"text-xs text-muted-foreground",children:e("account.profile.soundsHelp")})]}),o.jsxs(Z,{variant:g?"default":"outline",size:"sm",onClick:v,className:"gap-2",children:[g?o.jsx(Ol,{className:"w-4 h-4"}):o.jsx(Sg,{className:"w-4 h-4"}),e(g?"common.enabled":"common.disabled")]})]}),o.jsx("div",{className:"flex justify-end pt-4 border-t",children:o.jsxs(Z,{onClick:S,disabled:d,children:[d?o.jsx(pt,{size:"sm",className:"mr-2"}):o.jsx(dR,{className:"w-4 h-4 mr-2"}),e("common.saveChanges")]})})]})]})}function dq(){const{t:e}=tt(),[t,n]=w.useState(""),[r,i]=w.useState(""),[l,u]=w.useState(!1),d=async()=>{if(!t){le.error(e("account.security.enterPassword"));return}if(t!==r){le.error(e("account.security.passwordsMismatch"));return}if(t.length<6){le.error(e("account.security.passwordTooShort"));return}u(!0);try{const{api:h}=await Ea(async()=>{const{api:p}=await Promise.resolve().then(()=>F5);return{api:p}},void 0),m=await h.changePassword(t);m.success?(le.success(e("account.security.passwordChanged")),n(""),i("")):le.error(m.error?.message||"Failed to change password")}catch{le.error(e("common.errorOccurred"))}finally{u(!1)}};return o.jsxs($e,{children:[o.jsxs(Ot,{children:[o.jsx(Bt,{children:e("account.security.title")}),o.jsx(xs,{children:e("account.security.desc")})]}),o.jsxs(vt,{className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Ge,{htmlFor:"new-password",children:e("account.security.newPassword")}),o.jsx(Ce,{id:"new-password",type:"password",value:t,onChange:h=>n(h.target.value),placeholder:"••••••••"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Ge,{htmlFor:"confirm-password",children:e("account.security.confirmPassword")}),o.jsx(Ce,{id:"confirm-password",type:"password",value:r,onChange:h=>i(h.target.value),placeholder:"••••••••"})]}),o.jsx("div",{className:"flex justify-end pt-4 border-t",children:o.jsxs(Z,{onClick:d,disabled:l,children:[l?o.jsx(pt,{size:"sm",className:"mr-2"}):o.jsx(xg,{className:"w-4 h-4 mr-2"}),e("account.security.updatePassword")]})})]})]})}function fq(){const{t:e}=tt(),[t,n]=w.useState(!1),[r,i]=w.useState(null),l=fo(),u=U5();w.useEffect(()=>{l&&dy(gt).then(i)},[]);const d=()=>{confirm(e("account.database.clearConfirm"))&&(L5(),window.location.reload())};return o.jsxs(o.Fragment,{children:[o.jsxs($e,{children:[o.jsxs(Ot,{children:[o.jsxs(Bt,{className:"flex items-center gap-2",children:[o.jsx(Ra,{className:"w-5 h-5 text-primary"}),e("account.database.title")]}),o.jsx(xs,{children:e("account.database.desc")})]}),o.jsx(vt,{className:"space-y-6",children:l?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex items-start gap-4 p-4 border rounded-xl bg-emerald-500/5 border-emerald-500/20",children:[o.jsx(Ju,{className:"w-6 h-6 text-emerald-500 mt-0.5"}),o.jsxs("div",{className:"flex-1 space-y-1",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("p",{className:"font-semibold text-emerald-700 dark:text-emerald-400",children:e("account.database.connected")}),r?.latestMigrationTimestamp&&o.jsxs("span",{className:"text-[10px] font-mono bg-emerald-500/10 text-emerald-600 px-1.5 py-0.5 rounded border border-emerald-500/20",title:"Database Schema Version",children:["Schema ",r.latestMigrationTimestamp]})]}),o.jsx("p",{className:"text-sm font-mono break-all opacity-80",children:l.url})]})]}),u==="env"&&o.jsxs(La,{className:"bg-amber-500/5 border-amber-500/20",children:[o.jsx(Al,{className:"h-4 w-4 text-amber-500"}),o.jsx(Ia,{className:"text-amber-700 dark:text-amber-400 text-xs",children:e("account.database.envAlert")})]}),o.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[o.jsxs(Z,{variant:"outline",onClick:()=>n(!0),className:"w-full",children:[o.jsx(Al,{className:"w-4 h-4 mr-2"}),e("account.database.changeConnection")]}),u==="ui"&&o.jsxs(Z,{variant:"outline",onClick:d,className:"w-full text-destructive hover:bg-destructive/10",children:[o.jsx(bd,{className:"w-4 h-4 mr-2"}),e("account.database.clearConfig")]})]}),o.jsxs("div",{className:"space-y-2 pt-4 border-t",children:[o.jsx(Ge,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:e("account.database.anonKey")}),o.jsxs("div",{className:"p-2 bg-secondary/50 rounded-lg font-mono text-xs break-all",children:[l.anonKey.substring(0,20),"...",l.anonKey.substring(l.anonKey.length-10)]})]})]}):o.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center space-y-4",children:[o.jsx($C,{className:"w-12 h-12 text-destructive opacity-20"}),o.jsxs("div",{children:[o.jsx("p",{className:"font-medium",children:e("account.database.noConnection")}),o.jsx("p",{className:"text-sm text-muted-foreground",children:e("account.database.configureHelp")})]}),o.jsxs(Z,{onClick:()=>n(!0),children:[o.jsx(Ra,{className:"w-4 h-4 mr-2"}),e("account.database.setup")]})]})})]}),o.jsx(K_,{open:t,onComplete:()=>n(!1),canClose:!0})]})}function hq(){const{t:e}=tt();return o.jsx("span",{className:"inline-flex items-center text-xs px-2 py-0.5 rounded-full bg-blue-50 dark:bg-blue-950/70 text-blue-700 dark:text-blue-200 border border-blue-200 dark:border-blue-700 shrink-0 font-medium",children:e("autopilot.badge")})}function XS({rules:e,onToggleRule:t,onEditRule:n,onDeleteRule:r}){const{t:i}=tt(),l={email_organization:{label:i("autopilot.category.email_organization.label"),icon:as,emoji:"📧",description:i("autopilot.category.email_organization.desc")},priority_alerts:{label:i("autopilot.category.priority_alerts.label"),icon:ls,emoji:"🚨",description:i("autopilot.category.priority_alerts.desc")},development:{label:i("autopilot.category.development.label"),icon:Ds,emoji:"💻",description:i("autopilot.category.development.desc")},sales_business:{label:i("autopilot.category.sales_business.label"),icon:nj,emoji:"💼",description:i("autopilot.category.sales_business.desc")},operations:{label:i("autopilot.category.operations.label"),icon:Al,emoji:"⚙️",description:i("autopilot.category.operations.desc")}},u=e.reduce((m,p)=>{const g=p.category||"email_organization";return m[g]||(m[g]=[]),m[g].push(p),m},{}),d=m=>{const p=m.filter(b=>b.is_enabled).length,g=m.length;return{enabled:p,total:g}},h=m=>!m||m.length===0?"":m.map(p=>p.startsWith("label:")?`label:${p.substring(6)}`:p).join(" + ");return o.jsx("div",{className:"space-y-8",children:Object.entries(l).map(([m,p])=>{const g=u[m]||[];if(g.length===0)return null;const b=d(g);return o.jsxs("div",{className:"space-y-3",children:[o.jsx("div",{className:"flex items-center justify-between",children:o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"w-10 h-10 rounded-lg bg-secondary/50 flex items-center justify-center text-primary",children:o.jsx(p.icon,{className:"w-5 h-5"})}),o.jsxs("div",{children:[o.jsxs("h3",{className:"font-semibold text-base flex items-center gap-2",children:[p.label,o.jsx("span",{className:"text-xs font-normal text-muted-foreground",children:i("autopilot.enabledCount").replace("{enabled}",b.enabled.toString()).replace("{total}",b.total.toString())})]}),o.jsx("p",{className:"text-xs text-muted-foreground",children:p.description})]})]})}),o.jsx("div",{className:"space-y-1",children:g.map(v=>o.jsxs("div",{className:"flex items-center justify-between py-3 px-4 rounded-lg hover:bg-secondary/30 transition-colors",children:[o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("h4",{className:"font-medium text-sm truncate",children:v.name}),v.is_system_managed&&o.jsx(hq,{})]}),o.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[v.intent&&o.jsx("p",{className:"text-xs text-muted-foreground truncate",children:v.intent}),v.actions&&v.actions.length>0&&o.jsxs("span",{className:"text-xs text-muted-foreground shrink-0",children:["→ ",h(v.actions)]})]})]}),o.jsxs("div",{className:"flex items-center gap-2 ml-4 shrink-0",children:[o.jsx(Z,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>n(v.id),title:i("autopilot.editRuleTooltip"),children:o.jsx(oj,{className:"w-4 h-4 text-muted-foreground"})}),o.jsxs(Z,{variant:v.is_enabled?"default":"outline",size:"sm",onClick:()=>t(v.id,!v.is_enabled),className:"h-8 px-3",children:[o.jsx(ap,{className:"w-4 h-4 mr-1"}),v.is_enabled?i("common.on"):i("common.off")]}),!v.is_system_managed&&r&&o.jsx(Z,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-destructive hover:text-destructive",onClick:()=>r(v.id),title:i("autopilot.deleteRuleTooltip"),children:o.jsx(bd,{className:"w-4 h-4"})})]})]},v.id))})]},m)})})}function mq({open:e,rule:t,onClose:n,onSave:r,onFileUpload:i,onRemoveAttachment:l}){const{t:u}=tt(),[d,h]=w.useState(!1),[m,p]=w.useState(!1),[g,b]=w.useState(""),[v,S]=w.useState(""),[_,j]=w.useState(""),[N,A]=w.useState("category"),[T,O]=w.useState("newsletter"),[L,M]=w.useState(""),[B,P]=w.useState(["archive"]),[q,D]=w.useState(""),[Q,G]=w.useState([]);w.useEffect(()=>{if(t){b(t.name||""),S(t.description||""),j(t.intent||""),P(t.actions||["archive"]),D(t.instructions||""),G(t.attachments||[]);const I=t.condition||{},V=Object.keys(I).filter($=>$!=="older_than_days");V.length>0&&(A(V[0]),O(I[V[0]])),I.older_than_days&&M(String(I.older_than_days))}else b(""),S(""),j(""),A("category"),O("newsletter"),M(""),P(["archive"]),D(""),G([])},[t,e]);const fe=async()=>{if(g.trim()&&B.length!==0){h(!0);try{const I={[N]:T};L&&(I.older_than_days=parseInt(L,10));const V=B.includes("draft"),$={name:g.trim(),description:v.trim()||void 0,intent:_.trim()||void 0,condition:I,actions:B,instructions:V?q:void 0,attachments:V?Q:[],is_enabled:!0};await r($)&&n()}finally{h(!1)}}},se=async I=>{if(!i)return;const V=I.target.files;if(!(!V||V.length===0)){p(!0);try{const $=await i(V[0]);$&&G(de=>[...de,$])}finally{p(!1),I.target.value=""}}},ae=I=>{G(V=>V.filter($=>$.path!==I)),l&&l(I)};return o.jsx(is,{open:e,onOpenChange:I=>!I&&n(),children:o.jsxs(os,{className:"sm:max-w-xl max-h-[90vh] flex flex-col p-0",children:[o.jsxs(dr,{className:"p-6 border-b",children:[o.jsx(bs,{children:u(t?"autopilot.editDialog.editTitle":"autopilot.editDialog.createTitle")}),o.jsx(fr,{children:u("autopilot.editDialog.desc")})]}),o.jsxs("div",{className:"flex-1 overflow-y-auto p-6 space-y-6 custom-scrollbar",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:u("autopilot.editDialog.ruleName")}),o.jsx(Ce,{placeholder:u("autopilot.editDialog.namePlaceholder"),value:g,onChange:I=>b(I.target.value)})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:u("autopilot.editDialog.description")}),o.jsx("textarea",{className:"w-full p-2 border rounded-md bg-background min-h-[60px] text-sm",placeholder:u("autopilot.editDialog.descPlaceholder"),value:v,onChange:I=>S(I.target.value)}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:u("autopilot.editDialog.descriptionHelp")})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:u("autopilot.editDialog.intent")}),o.jsx(Ce,{placeholder:u("autopilot.editDialog.intentPlaceholder"),value:_,onChange:I=>j(I.target.value)}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:u("autopilot.editDialog.intentHelp")})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:u("autopilot.editDialog.conditionField")}),o.jsxs("select",{className:"w-full p-2 border rounded-md bg-background text-sm",value:N,onChange:I=>{A(I.target.value),I.target.value==="category"?O("newsletter"):I.target.value==="sentiment"?O("Positive"):I.target.value==="priority"?O("High"):O("")},children:[o.jsxs("optgroup",{label:u("autopilot.editDialog.aiAnalysisGroup"),children:[o.jsx("option",{value:"category",children:u("autopilot.editDialog.category")}),o.jsx("option",{value:"sentiment",children:u("autopilot.editDialog.sentiment")}),o.jsx("option",{value:"priority",children:u("autopilot.editDialog.priority")})]}),o.jsxs("optgroup",{label:u("autopilot.editDialog.metadataGroup"),children:[o.jsx("option",{value:"sender_email",children:u("autopilot.editDialog.senderEmail")}),o.jsx("option",{value:"sender_domain",children:u("autopilot.editDialog.senderDomain")}),o.jsx("option",{value:"sender_contains",children:u("autopilot.editDialog.senderContains")}),o.jsx("option",{value:"subject_contains",children:u("autopilot.editDialog.subjectContains")}),o.jsx("option",{value:"body_contains",children:u("autopilot.editDialog.bodyContains")})]})]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:u("autopilot.editDialog.equalsValue")}),N==="category"?o.jsxs("select",{className:"w-full p-2 border rounded-md bg-background text-sm",value:T,onChange:I=>O(I.target.value),children:[o.jsx("option",{value:"newsletter",children:u("autopilot.editDialog.cat.newsletter")}),o.jsx("option",{value:"news",children:u("autopilot.editDialog.cat.news")}),o.jsx("option",{value:"spam",children:u("autopilot.editDialog.cat.spam")}),o.jsx("option",{value:"promotional",children:u("autopilot.editDialog.cat.promotional")}),o.jsx("option",{value:"transactional",children:u("autopilot.editDialog.cat.transactional")}),o.jsx("option",{value:"social",children:u("autopilot.editDialog.cat.social")}),o.jsx("option",{value:"support",children:u("autopilot.editDialog.cat.support")}),o.jsx("option",{value:"client",children:u("autopilot.editDialog.cat.client")}),o.jsx("option",{value:"internal",children:u("autopilot.editDialog.cat.internal")}),o.jsx("option",{value:"personal",children:u("autopilot.editDialog.cat.personal")}),o.jsx("option",{value:"other",children:u("autopilot.editDialog.cat.other")})]}):N==="sentiment"?o.jsxs("select",{className:"w-full p-2 border rounded-md bg-background text-sm",value:T,onChange:I=>O(I.target.value),children:[o.jsx("option",{value:"Positive",children:u("autopilot.editDialog.sent.positive")}),o.jsx("option",{value:"Neutral",children:u("autopilot.editDialog.sent.neutral")}),o.jsx("option",{value:"Negative",children:u("autopilot.editDialog.sent.negative")})]}):N==="priority"?o.jsxs("select",{className:"w-full p-2 border rounded-md bg-background text-sm",value:T,onChange:I=>O(I.target.value),children:[o.jsx("option",{value:"High",children:u("autopilot.editDialog.prio.high")}),o.jsx("option",{value:"Medium",children:u("autopilot.editDialog.prio.medium")}),o.jsx("option",{value:"Low",children:u("autopilot.editDialog.prio.low")})]}):o.jsx(Ce,{placeholder:N==="sender_domain"?"rta.vn":N==="sender_email"?"john@example.com":u("autopilot.editDialog.keywordsPlaceholder"),value:T,onChange:I=>O(I.target.value)})]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsxs("label",{className:"text-sm font-medium flex items-center gap-2",children:[o.jsx(ea,{className:"w-4 h-4"}),u("autopilot.editDialog.olderThan")]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Ce,{type:"number",min:"0",placeholder:"0",className:"w-24",value:L,onChange:I=>M(I.target.value)}),o.jsx("span",{className:"text-sm text-muted-foreground",children:u("autopilot.editDialog.days")})]}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:u("autopilot.editDialog.olderThanHelp")})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:u("autopilot.editDialog.performActions")}),o.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:u("autopilot.editDialog.actionsDesc")}),o.jsx("div",{className:"grid grid-cols-2 gap-2",children:[{value:"archive",label:u("autopilot.editDialog.action.archive")},{value:"delete",label:u("autopilot.editDialog.action.delete")},{value:"draft",label:u("autopilot.editDialog.action.draft")},{value:"star",label:u("autopilot.editDialog.action.star")}].map(I=>o.jsxs("label",{className:`flex items-center gap-2 p-2 border rounded-md cursor-pointer transition-colors ${B.includes(I.value)?"bg-primary/10 border-primary":"bg-background hover:bg-secondary/50"}`,children:[o.jsx("input",{type:"checkbox",checked:B.includes(I.value),onChange:V=>{V.target.checked?P([...B,I.value]):P(B.filter($=>$!==I.value))},className:"rounded border-gray-300"}),o.jsx("span",{className:"text-sm",children:I.label})]},I.value))})]}),B.includes("draft")&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"space-y-2 animate-in slide-in-from-top-2 duration-200",children:[o.jsx("label",{className:"text-sm font-medium",children:u("autopilot.editDialog.draftInstructions")}),o.jsx("textarea",{className:"w-full p-2 border rounded-md bg-background min-h-[80px] text-sm",placeholder:u("autopilot.editDialog.draftInstPlaceholder"),value:q,onChange:I=>D(I.target.value)}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:u("autopilot.editDialog.draftInstHelp")})]}),i&&o.jsxs("div",{className:"space-y-2 animate-in slide-in-from-top-2 duration-200",children:[o.jsxs("label",{className:"text-sm font-medium flex items-center gap-2",children:[o.jsx(rp,{className:"w-4 h-4"}),u("autopilot.editDialog.attachments")]}),o.jsxs("div",{className:"flex flex-col gap-2",children:[Q.map(I=>o.jsxs("div",{className:"flex items-center justify-between p-2 bg-secondary/50 rounded border text-xs",children:[o.jsx("span",{className:"truncate max-w-[200px]",children:I.name}),o.jsx(Z,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-destructive",onClick:()=>ae(I.path),children:o.jsx(on,{className:"w-3 h-3"})})]},I.path)),o.jsxs("div",{className:"relative",children:[o.jsx("input",{type:"file",className:"absolute inset-0 opacity-0 cursor-pointer",onChange:se,disabled:m}),o.jsxs(Z,{variant:"outline",size:"sm",className:"w-full border-dashed",disabled:m,children:[m?o.jsx(pt,{size:"sm",className:"mr-2"}):o.jsx(lr,{className:"w-3 h-3 mr-2"}),u(m?"autopilot.editDialog.uploading":"autopilot.editDialog.addAttachment")]})]})]}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:u("autopilot.editDialog.attachmentsHelp")})]})]})]}),o.jsxs(or,{className:"p-6 border-t bg-secondary/5",children:[o.jsx(Z,{variant:"outline",onClick:n,children:u("common.cancel")}),o.jsxs(Z,{onClick:fe,disabled:d||!g.trim()||B.length===0,children:[d?o.jsx(pt,{size:"sm",className:"mr-2"}):t?o.jsx(ar,{className:"w-4 h-4 mr-2"}):o.jsx(lr,{className:"w-4 h-4 mr-2"}),u(t?"common.saveChanges":"autopilot.addCustomRule")]})]})]})})}function pq(){const{state:e,actions:t}=Tn(),{t:n}=tt(),[r,i]=w.useState([]),[l,u]=w.useState(!0),[d,h]=w.useState(null),[m,p]=w.useState(!1),[g,b]=w.useState(null),v=async()=>{u(!0),h(null);try{const P=await Oe.getRules();if(P.error)throw new Error(typeof P.error=="string"?P.error:P.error.message);i(P.data?.rules||[])}catch(P){h(P instanceof Error?P.message:n("autopilot.loadError")),console.error("Error fetching rules:",P)}finally{u(!1)}};w.useEffect(()=>{v()},[]);const S=async(P,q)=>{try{const D=await Oe.updateRule(P,{is_enabled:q});if(D.error)throw new Error(typeof D.error=="string"?D.error:D.error.message);i(Q=>Q.map(G=>G.id===P?{...G,is_enabled:q}:G))}catch(D){console.error("Error toggling rule:",D),await v()}},_=P=>{const q=r.find(D=>D.id===P);q&&(b(q),p(!0))},j=async P=>{if(confirm(n("autopilot.deleteConfirm")))try{await t.deleteRule(P)?(le.success(n("autopilot.ruleDeleted")),i(D=>D.filter(Q=>Q.id!==P))):le.error(n("autopilot.ruleDeleteFailed"))}catch(q){console.error("Error deleting rule:",q),le.error(n("autopilot.ruleDeleteError"))}},N=()=>{b(null),p(!0)},A=async P=>{try{let q=!1;return g?q=await t.updateRule(g.id,P):q=await t.createRule(P),q?(le.success(n(g?"autopilot.ruleUpdated":"autopilot.ruleCreated")),await v(),!0):(le.error(n(g?"autopilot.ruleUpdateFailed":"autopilot.ruleCreateFailed")),!1)}catch(q){return console.error("Error saving rule:",q),le.error(n("autopilot.ruleSaveError")),!1}},T=async P=>{try{const q=P.name.split(".").pop(),D=`${Math.random().toString(36).substring(2)}.${q}`,Q=`${e.user.id}/${D}`,{error:G}=await gt.storage.from("rule-attachments").upload(Q,P);if(G)throw G;return le.success(n("autopilot.fileUploaded")),{name:P.name,path:Q,type:P.type,size:P.size}}catch(q){return console.error("Upload error:",q),le.error(n("autopilot.fileUploadFailed")),null}},O=()=>{p(!1),b(null)};if(l)return o.jsx("div",{className:"flex items-center justify-center min-h-[400px]",children:o.jsxs("div",{className:"flex flex-col items-center gap-4",children:[o.jsx(Wt,{className:"w-8 h-8 animate-spin text-gray-400"}),o.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:n("autopilot.loadingRules")})]})});if(d)return o.jsxs(La,{variant:"destructive",children:[o.jsx(ls,{className:"h-4 w-4"}),o.jsxs(Ia,{children:[d,o.jsxs(Z,{variant:"outline",size:"sm",onClick:v,className:"ml-4",children:[o.jsx(Wt,{className:"w-4 h-4 mr-2"}),n("autopilot.refresh")]})]})]});const L=r.filter(P=>P.is_system_managed),M=r.filter(P=>!P.is_system_managed),B=L.filter(P=>P.is_enabled).length;return r.length===0?o.jsxs("div",{className:"flex flex-col items-center justify-center min-h-[400px] p-8",children:[o.jsx(qu,{className:"w-16 h-16 text-gray-300 dark:text-gray-700 mb-4"}),o.jsx("h3",{className:"text-lg font-semibold mb-2",children:n("autopilot.noRulesTitle")}),o.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 text-center max-w-md mb-4",children:n("autopilot.noRulesDesc")})]}):o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"space-y-8",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{children:[o.jsxs("h2",{className:"text-2xl font-bold flex items-center gap-2",children:[o.jsx(qu,{className:"w-6 h-6 text-blue-500"}),n("autopilot.title")]}),o.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:n("autopilot.rulesEnabled").replace("{enabled}",B.toString()).replace("{total}",L.length.toString())})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs(Z,{variant:"default",size:"sm",onClick:N,children:[o.jsx(lr,{className:"w-4 h-4 mr-2"}),n("autopilot.addCustomRule")]}),o.jsxs(Z,{variant:"outline",size:"sm",onClick:v,disabled:l,children:[o.jsx(Wt,{className:`w-4 h-4 mr-2 ${l?"animate-spin":""}`}),n("autopilot.refresh")]})]})]}),L.length>0&&o.jsxs(La,{children:[o.jsx(qu,{className:"h-4 w-4"}),o.jsx(Ia,{children:n("autopilot.infoDesc")})]}),L.length>0&&o.jsx(XS,{rules:L,onToggleRule:S,onEditRule:_,onDeleteRule:j}),M.length>0&&o.jsxs("div",{className:"space-y-4 pt-4 border-t",children:[o.jsxs("div",{children:[o.jsx("h3",{className:"text-lg font-semibold",children:n("autopilot.customRules")}),o.jsx("p",{className:"text-sm text-muted-foreground",children:n("autopilot.customRulesDesc")})]}),o.jsx(XS,{rules:M,onToggleRule:S,onEditRule:_,onDeleteRule:j})]})]}),o.jsx(mq,{open:m,rule:g,onClose:O,onSave:A,onFileUpload:T})]})}function gq({length:e=6,value:t,onChange:n,onComplete:r,disabled:i=!1,error:l=!1}){const u=w.useRef([]),[d,h]=w.useState(null),m=(b,v)=>{const S=v.replace(/[^0-9]/g,"");if(S.length===0){const N=t.split("");N[b]=" ",t.split("");let A=t.split("");b<A.length&&A.splice(b,1);const T=A.join("");n(T),b>0&&u.current[b-1]?.focus();return}t.split("");const _=[...t];_[b]=S[0],n(_.join("")),b<e-1&&u.current[b+1]?.focus();const j=_.join("");j.length===e&&r&&r(j)},p=(b,v)=>{v.key==="Backspace"&&!t[b]&&b>0||v.key==="ArrowLeft"&&b>0?u.current[b-1]?.focus():v.key==="ArrowRight"&&b<e-1&&u.current[b+1]?.focus()},g=b=>{b.preventDefault();const S=b.clipboardData.getData("text/plain").replace(/[^0-9]/g,"").slice(0,e);n(S);const _=Math.min(S.length,e-1);u.current[_]?.focus(),S.length===e&&r&&r(S)};return o.jsx("div",{className:"flex gap-2 justify-center",children:Array.from({length:e}).map((b,v)=>o.jsx(Ce,{ref:S=>{u.current[v]=S},type:"text",inputMode:"numeric",maxLength:1,value:t[v]||"",onChange:S=>m(v,S.target.value),onKeyDown:S=>p(v,S),onPaste:g,onFocus:()=>h(v),onBlur:()=>h(null),disabled:i,className:me("w-10 h-10 sm:w-12 sm:h-12 text-center text-lg font-semibold px-0",l&&"border-destructive focus-visible:ring-destructive",d===v&&"ring-2 ring-ring"),"aria-label":`Digit ${v+1}`},v))})}function yq({onSuccess:e,onConfigure:t,isInitialized:n}){const{t:r}=tt(),[i,l]=w.useState(""),[u,d]=w.useState(""),[h,m]=w.useState(""),[p,g]=w.useState(""),[b,v]=w.useState(!1),[S,_]=w.useState(n===void 0),[j,N]=w.useState(n??!1),[A,T]=w.useState(""),[O,L]=w.useState(!1),[M,B]=w.useState("password"),[P,q]=w.useState("email"),[D,Q]=w.useState(""),[G,fe]=w.useState(!1);w.useEffect(()=>{n===void 0?se():fe(!n)},[n]);const se=async()=>{try{const{data:V,error:$}=await gt.from("init_state").select("is_initialized");if($){if($.code==="42P01"){console.info("[Login] init_state relation missing - fresh database detected."),N(!1),fe(!0);return}console.warn("[Login] Init check error:",$),N(!1),fe(!0),T($.message);return}const de=V&&V.length>0&&V[0].is_initialized>0;N(de),fe(!de)}catch(V){console.warn("[Login] Init check exception:",V),N(!1),fe(!0),T(V.message||"Connection failed")}finally{_(!1)}},ae=async V=>{V.preventDefault(),v(!0),T("");try{if(j){if(M==="password"){const{error:$}=await gt.auth.signInWithPassword({email:i,password:u});if($)throw $;le.success("Logged in successfully"),e?.()}else if(P==="email"){const{error:$}=await gt.auth.signInWithOtp({email:i,options:{shouldCreateUser:!1}});if($)throw $;q("verify"),le.success("Validation code sent to your email")}}else{const{data:$,error:de}=await gt.functions.invoke("setup",{body:{email:i,password:u,first_name:h,last_name:p}});if(de||!$){if(de?.message?.includes("First user already exists")){le.info("System already initialized. Please log in."),N(!0);return}throw new Error(de?.message||"Failed to create admin account")}le.success("Admin account created! Signing you in...");const{error:C}=await gt.auth.signInWithPassword({email:i,password:u});if(C)throw C;N(!0),e?.()}}catch($){T($?.message||"Authentication failed"),console.error("[Login] Error:",$)}finally{v(!1)}},I=async()=>{v(!0),T("");try{const{data:V,error:$}=await gt.auth.verifyOtp({email:i,token:D,type:"magiclink"});if($)throw $;if(!V.session)throw new Error("Failed to create session");le.success("Logged in successfully"),e?.()}catch(V){T(V?.message||"Invalid code")}finally{v(!1)}};return S?o.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center",children:o.jsxs("div",{className:"flex flex-col items-center gap-4",children:[o.jsx(wt,{className:"w-10 h-10 animate-spin text-primary"}),o.jsx("p",{className:"text-xs font-mono uppercase tracking-widest text-muted-foreground",children:"Initializing Engine..."})]})}):o.jsxs("div",{className:"min-h-screen bg-background flex items-center justify-center p-8 relative overflow-hidden",children:[o.jsxs("div",{className:"absolute top-6 right-6 flex items-center gap-4 z-50",children:[t&&o.jsxs(Z,{variant:"ghost",size:"sm",onClick:t,className:"text-xs font-bold uppercase tracking-widest text-muted-foreground hover:text-primary transition-all",children:[o.jsx(Al,{className:"w-3.5 h-3.5 mr-2"}),"Configure"]}),o.jsx(Tj,{}),o.jsx(ly,{})]}),o.jsxs(ir.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"w-full max-w-md relative z-10",children:[o.jsxs("div",{className:"glass p-10 space-y-8 relative overflow-hidden",children:[o.jsxs("div",{className:"text-center space-y-3",children:[o.jsx("div",{className:"mx-auto w-16 h-16 bg-primary rounded-2xl flex items-center justify-center mb-6",children:o.jsx(fy,{className:"w-10 h-10 text-primary-foreground"})}),o.jsx("h2",{className:"text-3xl font-black italic tracking-tighter uppercase text-foreground",children:r(G?"login.initialize":"login.secureLogin")}),o.jsx("p",{className:"text-[10px] text-muted-foreground font-bold tracking-[0.2em] uppercase",children:G?"Create your primary administrator account":M==="otp"?"Magic link authentication":"Personal Access Key Required"})]}),o.jsxs("form",{onSubmit:ae,className:"space-y-4",children:[o.jsxs(S_,{mode:"wait",children:[G&&o.jsxs(ir.div,{initial:{opacity:0,height:0},animate:{opacity:1,height:"auto"},exit:{opacity:0,height:0},className:"grid grid-cols-2 gap-4",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"text-[10px] font-bold uppercase text-muted-foreground ml-1",children:"First Name"}),o.jsx(Ce,{value:h,onChange:V=>m(V.target.value),required:G,placeholder:r("login.firstNamePlaceholder"),className:"bg-background"})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"text-[10px] font-bold uppercase text-muted-foreground ml-1",children:"Last Name"}),o.jsx(Ce,{value:p,onChange:V=>g(V.target.value),required:G,placeholder:r("login.lastNamePlaceholder"),className:"bg-background"})]})]},"signup-fields"),M==="password"||P==="email"?o.jsxs(ir.div,{initial:{opacity:0},animate:{opacity:1},className:"space-y-1",children:[o.jsx("label",{className:"text-[10px] font-bold uppercase text-muted-foreground ml-1",children:"Email Coordinates"}),o.jsxs("div",{className:"relative",children:[o.jsx(as,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground/30",size:16}),o.jsx(Ce,{type:"email",placeholder:r("login.emailPlaceholder"),value:i,onChange:V=>l(V.target.value),required:!0,className:"pl-10 bg-background",autoComplete:"email",disabled:P==="verify"})]})]},"email-field"):null,M==="password"&&o.jsxs(ir.div,{initial:{opacity:0},animate:{opacity:1},className:"space-y-1",children:[o.jsx("label",{className:"text-[10px] font-bold uppercase text-muted-foreground ml-1",children:"Access Password"}),o.jsxs("div",{className:"relative",children:[o.jsx($0,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground/30",size:16}),o.jsx(Ce,{type:O?"text":"password",placeholder:"••••••••",value:u,onChange:V=>d(V.target.value),required:!0,minLength:6,className:"pl-10 pr-10 bg-background",autoComplete:G?"new-password":"current-password"}),o.jsx("button",{type:"button",onClick:()=>L(!O),className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground/30 hover:text-primary transition-colors",children:O?o.jsx(ZC,{size:16}):o.jsx(xd,{size:16})})]})]},"password-field"),M==="otp"&&P==="verify"&&o.jsxs(ir.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},className:"space-y-6 py-4",children:[o.jsx("div",{className:"flex justify-center",children:o.jsx(gq,{value:D,onChange:Q,length:6,onComplete:()=>{}})}),o.jsx(Z,{type:"button",variant:"link",className:"w-full text-[10px] font-bold uppercase tracking-widest text-primary/60",onClick:()=>q("email"),children:"Change Coordinates"}),o.jsxs(Z,{type:"button",onClick:I,disabled:b||D.length!==6,className:"w-full h-12 shadow-md",children:[b?o.jsx(wt,{className:"w-5 h-5 animate-spin mr-2"}):o.jsx(wg,{size:18,className:"mr-2"}),"Verify Access"]})]},"otp-field")]}),A&&o.jsxs(ir.div,{initial:{opacity:0,x:-10},animate:{opacity:1,x:0},className:"bg-destructive/10 text-destructive text-[11px] font-bold p-3 rounded-xl border border-destructive/20 flex items-start gap-2",children:[o.jsx(ls,{size:14,className:"mt-0.5 shrink-0"}),o.jsx("p",{children:A})]}),M!=="otp"||P==="email"?o.jsx(Z,{type:"submit",disabled:b||!i||M==="password"&&!u,className:"w-full h-12 shadow-md mt-4",children:b?o.jsx(wt,{className:"w-5 h-5 animate-spin"}):o.jsxs(o.Fragment,{children:[G?o.jsx(JR,{className:"w-5 h-5 mr-2"}):M==="otp"?o.jsx(as,{className:"w-5 h-5 mr-2"}):o.jsx(IA,{className:"w-5 h-5 mr-2"}),r(G?"login.initializeMaster":M==="otp"?"login.sendMagicLink":"login.openDashboard")]})}):null]}),o.jsxs("div",{className:"space-y-4 pt-4 border-t border-border/10",children:[!G&&o.jsx("div",{className:"flex flex-col gap-2",children:M==="password"?o.jsxs("button",{type:"button",onClick:()=>{B("otp"),q("email"),T("")},className:"w-full flex items-center justify-center gap-2 py-3 glass hover:bg-white/5 text-[10px] font-bold uppercase tracking-widest text-muted-foreground hover:text-primary transition-all rounded-xl",children:[o.jsx($0,{size:14})," Magic Link Login"]}):o.jsxs("button",{type:"button",onClick:()=>{B("password"),T("")},className:"w-full flex items-center justify-center gap-2 py-3 glass hover:bg-white/5 text-[10px] font-bold uppercase tracking-widest text-muted-foreground hover:text-primary transition-all rounded-xl",children:[o.jsx(pg,{size:14})," Password Access"]})}),o.jsxs("p",{className:"text-center text-[10px] text-muted-foreground font-bold uppercase tracking-wider",children:[G?"Already have an account?":"Need a new account?"," "," ",o.jsx("button",{onClick:()=>{fe(!G),B("password"),T("")},className:"text-primary hover:underline ml-1",children:G?"Login Instead":"Create Account"})]})]})]}),o.jsx("div",{className:"mt-8 text-center",children:o.jsx("p",{className:"text-[10px] font-bold text-muted-foreground/30 uppercase tracking-[0.4em]",children:"Powered by RealTimeX Intelligence"})})]})]})}function xq({status:e,onDismiss:t,onLearnMore:n}){const[r,i]=w.useState(!0);if(!r)return null;const l=()=>{JL(),i(!1),t?.()},u=()=>{n?n():(navigator.clipboard.writeText("npx email-automator migrate"),le.success("Command copied to clipboard"))};return o.jsx("div",{className:"fixed right-4 top-16 z-50 max-w-sm animate-in slide-in-from-top-5",children:o.jsx("div",{className:"rounded-lg border border-yellow-500 bg-yellow-50 p-4 shadow-lg dark:bg-yellow-950/90 dark:border-yellow-600",children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx(za,{className:"h-5 w-5 flex-shrink-0 text-yellow-600 dark:text-yellow-500 mt-0.5"}),o.jsxs("div",{className:"flex-1 space-y-2",children:[o.jsxs("div",{className:"flex items-start justify-between gap-2",children:[o.jsx("p",{className:"text-sm font-medium text-yellow-900 dark:text-yellow-100",children:"Database Update Required"}),o.jsxs(Z,{size:"icon",variant:"ghost",className:"h-5 w-5 -mr-1 -mt-1 text-yellow-900 hover:bg-yellow-100 dark:text-yellow-100 dark:hover:bg-yellow-900/30",onClick:l,children:[o.jsx(on,{className:"h-3 w-3"}),o.jsx("span",{className:"sr-only",children:"Dismiss"})]})]}),o.jsxs("p",{className:"text-xs text-yellow-800 dark:text-yellow-200",children:["Your app version (",e.appVersion,") requires a database schema update."]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Z,{size:"sm",variant:"default",className:"h-7 text-xs bg-yellow-600 hover:bg-yellow-700 dark:bg-yellow-500 dark:hover:bg-yellow-600",onClick:u,children:"Update Now"}),o.jsx(Z,{size:"sm",variant:"ghost",className:"h-7 text-xs text-yellow-900 hover:bg-yellow-100 dark:text-yellow-100 dark:hover:bg-yellow-900/30",onClick:l,children:"Remind Later"})]})]})]})})})}function vq({open:e,onOpenChange:t,status:n}){const r=fo(),[i,l]=w.useState(!1),[u,d]=w.useState([]),[h,m]=w.useState(""),p=w.useRef(null),g=w.useMemo(()=>{const v=r?.url;if(!v)return"";try{return new URL(v).hostname.split(".")[0]||""}catch{return""}},[r?.url]);w.useEffect(()=>{p.current&&p.current.scrollIntoView({behavior:"smooth"})},[u]);const b=async()=>{if(!g){le.error("Missing Project ID");return}if(!h){le.error("Provide a Supabase Personal Access Token.");return}l(!0),d(["Initializing migration..."]);try{const v=async N=>{const A=new TextDecoder;let T="",O=null;const L=M=>{const B=M.trim();if(!(!B||!B.startsWith("data: ")))try{const P=B.substring(6),q=JSON.parse(P);q.type==="done"?(q.data==="success"||q.data==="failed")&&(O=q.data==="success"?"success":"failure"):q.data&&d(D=>[...D,q.data])}catch(P){console.error("Failed to parse SSE line:",B,P)}};for(;;){const{done:M,value:B}=await N.read();if(M)break;T+=A.decode(B,{stream:!0});const P=T.split(`
|
|
217
|
-
`);T=P.pop()||"",P.forEach(L)}return T+=A.decode(),T&&L(T),O};d(N=>[...N,"","📦 Database Migration & Edge Functions Deployment"]);const S=await fetch("/api/migrate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectRef:g,accessToken:h})});if(!S.ok)throw new Error(`Migration failed: ${S.status} ${S.statusText}`);const _=S.body?.getReader();if(!_)throw new Error("No migration response stream received.");if(await v(_)!=="success")throw new Error("Migration did not complete successfully");d(N=>[...N,"","═".repeat(60),"✅ Setup Complete!","","✓ Database schema updated","✓ Edge Functions deployed","","🎉 Your Email Automator is ready to use!","📝 The application will reload automatically...","═".repeat(60)]),setTimeout(()=>{window.location.reload()},3e3)}catch(v){console.error(v),d(S=>[...S,"",`❌ Error: ${v instanceof Error?v.message:String(v)}`]),le.error("Setup failed. Check logs for details.")}finally{l(!1)}};return o.jsx(is,{open:e,onOpenChange:v=>!i&&t(v),children:o.jsxs(os,{className:"max-h-[90vh] sm:max-w-5xl overflow-y-auto",children:[o.jsxs(dr,{children:[o.jsxs(bs,{className:"flex items-center gap-2 text-xl",children:[o.jsx(za,{className:"h-6 w-6 text-red-700 dark:text-red-600"}),"Database Setup Required"]}),o.jsxs(fr,{children:["Your application version (",n.appVersion,") requires database migration and Edge Functions deployment to function correctly."]})]}),o.jsxs("div",{className:"space-y-6",children:[o.jsxs(La,{children:[o.jsx(ro,{className:"h-4 w-4"}),o.jsxs(Ia,{children:[o.jsx("strong",{children:"Why is this needed?"}),o.jsxs("ul",{className:"mt-2 list-inside list-disc space-y-1 text-sm",children:[o.jsxs("li",{children:["Updates your database schema to match version ",n.appVersion]}),o.jsx("li",{children:"Deploys Edge Functions (API endpoints) to your Supabase project"}),o.jsx("li",{children:"Enables new features and performance improvements"}),o.jsx("li",{children:"Your existing data will be preserved (safe migration)"})]})]})]}),o.jsxs("div",{className:"space-y-4 py-2",children:[o.jsxs("div",{className:"rounded-lg border bg-card text-card-foreground shadow-sm p-6",children:[o.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Automated Setup"}),o.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Run database migration and deploy Edge Functions directly from your browser. A Supabase Personal Access Token is required to authenticate with your project."}),o.jsxs("div",{className:"grid gap-4",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Ge,{htmlFor:"project-id",children:"Supabase Project ID"}),o.jsx(Ce,{id:"project-id",value:g,disabled:!0,readOnly:!0,className:"bg-muted"})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsxs("div",{className:"flex justify-between items-center",children:[o.jsx(Ge,{htmlFor:"access-token",children:"Access Token"}),o.jsxs("a",{href:"https://supabase.com/dashboard/account/tokens",target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline flex items-center gap-1",children:["Generate Token ",o.jsx(Cl,{className:"h-3 w-3"})]})]}),o.jsx(Ce,{id:"access-token",type:"password",placeholder:"sbp_...",value:h,onChange:v=>m(v.target.value),disabled:i}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"This token is used only for this migration and is not stored."})]}),o.jsx(Z,{onClick:b,disabled:i||!h,className:"w-full",children:i?o.jsxs(o.Fragment,{children:[o.jsx(wt,{className:"mr-2 h-4 w-4 animate-spin"}),"Running Setup..."]}):o.jsxs(o.Fragment,{children:[o.jsx(Rl,{className:"mr-2 h-4 w-4"}),"Start Setup"]})})]})]}),o.jsxs("div",{className:"rounded-lg border bg-black text-white font-mono text-xs p-4 h-64 overflow-y-auto",children:[u.length===0?o.jsx("div",{className:"text-gray-500 italic",children:"Waiting to start..."}):u.map((v,S)=>o.jsx("div",{className:"mb-1 whitespace-pre-wrap",children:v},S)),o.jsx("div",{ref:p})]})]}),o.jsxs(La,{className:"border-red-200 bg-red-50 dark:border-red-900/40 dark:bg-red-950/20",children:[o.jsx(za,{className:"h-4 w-4 text-red-700 dark:text-red-600"}),o.jsxs(Ia,{children:[o.jsx("strong",{children:"Troubleshooting"}),o.jsxs("ul",{className:"mt-2 list-inside list-disc space-y-1 text-sm",children:[o.jsxs("li",{children:["Ensure your Access Token has ",o.jsx("code",{children:"read"})," and ",o.jsx("code",{children:"write"})," permissions."]}),o.jsx("li",{children:"Verify that your Supabase Project ID is correct and active."})]})]})]})]}),o.jsx(or,{children:o.jsx(Z,{type:"button",variant:"outline",onClick:()=>t(!1),disabled:i,children:"Close"})})]})})}const bq="https://registry.npmjs.org/@realtimex/email-automator/latest",wq=300*1e3,O2="email_automator_last_version_check",D2="email_automator_update_dismissed";function Sq(){return"2.23.2"}async function jq(){try{const e=await fetch(bq,{cache:"no-store"});return e.ok?(await e.json()).version||null:(console.warn("[Version Check] Failed to fetch latest version"),null)}catch(e){return console.error("[Version Check] Error fetching latest version:",e),null}}function kq(e,t){if(t==="unknown")return!1;const n=m=>m.replace(/^v/,"").split(".").map(g=>parseInt(g,10)||0),[r,i,l]=n(e),[u,d,h]=n(t);return u>r?!0:u<r?!1:d>i?!0:d<i?!1:h>l}function _q(){try{const e=localStorage.getItem(O2);if(!e)return!0;const t=new Date(e).getTime();return Date.now()-t>wq}catch{return!0}}function Nq(){try{localStorage.setItem(O2,new Date().toISOString())}catch(e){console.error("[Version Check] Error saving check timestamp:",e)}}function Tq(e=24){try{const t=localStorage.getItem(D2);if(!t)return!1;const n=new Date(t).getTime();return(Date.now()-n)/(1e3*60*60)<e}catch{return!1}}function Eq(){try{localStorage.setItem(D2,new Date().toISOString())}catch(e){console.error("[Version Check] Error dismissing update prompt:",e)}}async function Cq(){if(!_q())return console.log("[Version Check] Skipping (throttled)"),null;const e=Sq(),t=await jq();if(Nq(),!t)return console.warn("[Version Check] Could not determine latest version"),null;const n=kq(e,t);return console.log("[Version Check]",{current:e,latest:t,updateAvailable:n}),n?{current:e,latest:t,updateAvailable:!0,updateUrl:"https://github.com/realtimex/email-automator/releases/latest"}:null}function Aq(){typeof window<"u"&&window.location.reload(),window.electron?.ipcRenderer&&window.electron.ipcRenderer.send("restart-app")}function Rq({versionInfo:e,onDismiss:t}){const[n,r]=w.useState(!0),[i,l]=w.useState(!1);if(!n)return null;const u=()=>{Eq(),r(!1),t?.()},d=()=>{l(!0),setTimeout(()=>{Aq()},500)},h=()=>{e.updateUrl&&window.open(e.updateUrl,"_blank")};return o.jsx("div",{className:"fixed right-4 top-16 z-50 max-w-sm animate-in slide-in-from-top-5",children:o.jsx("div",{className:"rounded-lg border border-blue-500 bg-blue-50 p-4 shadow-lg dark:bg-blue-950/90 dark:border-blue-600",children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx(Wt,{className:"h-5 w-5 flex-shrink-0 text-blue-600 dark:text-blue-500 mt-0.5"}),o.jsxs("div",{className:"flex-1 space-y-2",children:[o.jsxs("div",{className:"flex items-start justify-between gap-2",children:[o.jsx("p",{className:"text-sm font-medium text-blue-900 dark:text-blue-100",children:"Update Available"}),o.jsxs(Z,{size:"icon",variant:"ghost",className:"h-5 w-5 -mr-1 -mt-1 text-blue-900 hover:bg-blue-100 dark:text-blue-100 dark:hover:bg-blue-900/30",onClick:u,children:[o.jsx(on,{className:"h-3 w-3"}),o.jsx("span",{className:"sr-only",children:"Dismiss"})]})]}),o.jsxs("p",{className:"text-xs text-blue-800 dark:text-blue-200",children:["Version ",e.latest," is now available (you're on ",e.current,")"]}),o.jsxs("div",{className:"flex gap-2 flex-wrap",children:[o.jsx(Z,{size:"sm",variant:"default",className:"h-7 text-xs bg-blue-600 hover:bg-blue-700 dark:bg-blue-500 dark:hover:bg-blue-600",onClick:d,disabled:i,children:i?o.jsxs(o.Fragment,{children:[o.jsx(Wt,{className:"h-3 w-3 mr-1 animate-spin"}),"Updating..."]}):o.jsxs(o.Fragment,{children:[o.jsx(Wt,{className:"h-3 w-3 mr-1"}),"Update Now"]})}),e.updateUrl&&o.jsxs(Z,{size:"sm",variant:"ghost",className:"h-7 text-xs text-blue-900 hover:bg-blue-100 dark:text-blue-100 dark:hover:bg-blue-900/30",onClick:h,children:[o.jsx(Cl,{className:"h-3 w-3 mr-1"}),"What's New"]}),o.jsx(Z,{size:"sm",variant:"ghost",className:"h-7 text-xs text-blue-900 hover:bg-blue-100 dark:text-blue-100 dark:hover:bg-blue-900/30",onClick:u,children:"Later"})]})]})]})})})}function Oq(){const{t:e}=tt(),[t,n]=w.useState([]),{isExpanded:r,setIsExpanded:i}=Xj(),{state:l,actions:u}=Tn(),{isSyncing:d}=l,[h,m]=w.useState({});w.useEffect(()=>{p();const j=gt.channel("processing_events_feed").on("postgres_changes",{event:"INSERT",schema:"public",table:"processing_events"},N=>{const A=N.new;A.event_type==="error"&&m(T=>({...T,[A.id]:!0})),n(T=>{const O=[A,...T];return A.details?.is_completion&&r&&setTimeout(()=>{i(!1)},3e3),O.length>100?O.slice(0,100):O})}).subscribe();return()=>{gt.removeChannel(j)}},[r,i]);const p=async()=>{const{data:j}=await gt.from("processing_events").select("*").order("created_at",{ascending:!1}).limit(50);j&&n(j)},g=j=>{m(N=>({...N,[j]:!N[j]}))},b=j=>{if(j.details?.is_completion)return o.jsx(Ju,{className:"w-3 h-3 text-emerald-500"});switch(j.event_type){case"analysis":return o.jsx(Jr,{className:"w-3 h-3 text-purple-500"});case"action":return o.jsx(ao,{className:"w-3 h-3 text-emerald-500"});case"error":return o.jsx(za,{className:"w-3 h-3 text-red-500"});default:return o.jsx(ro,{className:"w-3 h-3 text-blue-500"})}},v=j=>new Date(j).toLocaleTimeString([],{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"}),S=j=>{const N=`terminal.state.${j.toLowerCase().replace(/\s+/g,"_")}`,A=e(N);return A.startsWith("terminal.state.")?j:A},_=j=>{if(!j)return"";if(j.startsWith("Background processing: ")){const A=j.replace("Background processing: ","");return e("terminal.message.background_processing").replace("{subject}",A)}const N=j.match(/^(\d+) rule\(s\) apply: (.+)$/);if(N){const[,A,T]=N;return e("terminal.message.rules_apply").replace("{count}",A).replace("{rules}",T)}if(j.startsWith("After conflict resolution: ")){const A=j.replace("After conflict resolution: ","");return e("terminal.message.conflict_resolution").replace("{actions}",A)}if(j.startsWith("Analyzing email: ")){const A=j.replace("Analyzing email: ","");return e("terminal.message.analyzing_email").replace("{subject}",A)}if(j.startsWith("Context-aware analysis: ")){const A=j.replace("Context-aware analysis: ","");return e("terminal.message.context_aware_analysis").replace("{subject}",A)}return j==="Generating customized draft based on rule"?e("terminal.message.generating_draft"):j};return r?o.jsxs($e,{className:"fixed bottom-4 right-4 z-50 w-[550px] h-[650px] flex flex-col shadow-2xl border-border bg-background/95 text-foreground backdrop-blur-md animate-in slide-in-from-bottom-10",children:[o.jsxs(Ot,{className:"py-3 px-4 border-b border-border flex flex-row items-center justify-between sticky top-0 bg-background/95 z-20",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Rl,{className:"w-4 h-4 text-primary"}),o.jsx(Bt,{className:"text-sm font-mono font-bold",children:e("terminal.title")}),o.jsxs("div",{className:me("flex items-center gap-1 text-[10px] px-2 py-0.5 rounded-full border font-bold animate-pulse transition-colors duration-500",d?"text-red-600 dark:text-red-400 bg-red-500/10 border-red-500/20":"text-green-600 dark:text-green-400 bg-green-500/10 border-green-500/20"),children:[o.jsx(fC,{className:"w-3 h-3"}),e(d?"terminal.syncing":"terminal.live")]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[d&&o.jsxs(Z,{variant:"destructive",size:"sm",className:"h-7 text-[10px] font-mono font-bold bg-red-600 hover:bg-red-700 animate-in fade-in zoom-in duration-300",onClick:()=>u.stopSync(),children:[o.jsx(NR,{className:"w-3 h-3 mr-1 fill-current"}),e("terminal.stopSync")]}),o.jsx(Z,{variant:"ghost",size:"sm",className:"h-7 text-[10px] font-mono hover:bg-secondary",onClick:()=>n([]),children:e("terminal.clear")}),o.jsx(Z,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-secondary",onClick:()=>i(!1),children:o.jsx(ij,{className:"w-4 h-4"})})]})]}),o.jsxs(vt,{className:"flex-1 overflow-y-auto p-4 font-mono text-xs space-y-6 custom-scrollbar",children:[t.length===0&&o.jsx("div",{className:"text-center text-muted-foreground py-20 italic",children:e("terminal.waiting")}),t.map((j,N)=>o.jsxs("div",{className:"relative pl-8 animate-in fade-in slide-in-from-top-2 duration-300",children:[N!==t.length-1&&o.jsx("div",{className:"absolute left-[13px] top-7 bottom-[-24px] w-[1px] bg-border"}),o.jsx("div",{className:me("absolute left-0 top-0 w-7 h-7 rounded-full border border-border bg-card flex items-center justify-center z-10 shadow-sm",j.event_type==="error"&&"border-red-500/50 bg-red-500/5",j.event_type==="analysis"&&"border-purple-500/50 bg-purple-500/5",j.event_type==="action"&&"border-emerald-500/50 bg-emerald-500/5",j.details?.is_completion&&"border-emerald-500/50 bg-emerald-500/5"),children:b(j)}),o.jsxs("div",{className:"flex flex-col gap-1.5",children:[o.jsxs("div",{className:"flex items-center justify-between group",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:me("font-bold uppercase tracking-tight text-[10px]",j.event_type==="info"&&"text-muted-foreground",j.event_type==="analysis"&&"text-purple-600 dark:text-purple-400",j.event_type==="action"&&"text-emerald-600 dark:text-emerald-400",j.event_type==="error"&&"text-red-600 dark:text-red-400"),children:S(j.agent_state)}),o.jsx("span",{className:"text-[10px] text-muted-foreground/60",children:v(j.created_at)})]}),(j.details?.system_prompt||j.details?._raw_response||j.details?.raw_response)&&o.jsxs(Z,{variant:"ghost",size:"sm",className:"h-5 px-1.5 text-[9px] text-muted-foreground hover:text-primary opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>g(j.id),children:[h[j.id]?o.jsx(LC,{className:"w-3 h-3 mr-1"}):o.jsx(gd,{className:"w-3 h-3 mr-1"}),e("terminal.details")]})]}),j.event_type==="analysis"&&j.details?o.jsxs("div",{className:"bg-purple-500/5 border border-purple-500/10 rounded-lg p-3 space-y-2",children:[o.jsxs("div",{className:"flex gap-2",children:[o.jsx("span",{className:me("px-1.5 py-0.5 rounded text-[9px] font-bold border",j.details.is_useless?"bg-red-500/10 text-red-600 dark:text-red-400 border-red-500/20":"bg-green-500/10 text-green-600 dark:text-green-400 border-green-500/20"),children:j.details.is_useless?e("terminal.useless"):e("terminal.relevant")}),o.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-bold border bg-blue-500/10 text-blue-600 dark:text-blue-400 border-blue-500/20 uppercase",children:j.details.category})]}),o.jsxs("p",{className:"text-foreground/90 italic leading-relaxed",children:['"',j.details.summary,'"']}),j.details.suggested_actions&&j.details.suggested_actions.length>0&&o.jsx("div",{className:"pt-1 flex items-center gap-2 flex-wrap",children:j.details.suggested_actions.map(A=>o.jsxs("div",{className:"flex items-center gap-1 text-[9px] text-emerald-600 dark:text-emerald-400 font-bold bg-emerald-500/10 px-1.5 py-0.5 rounded border border-emerald-500/20 uppercase",children:[o.jsx(ao,{className:"w-2.5 h-2.5"}),A]},A))}),j.details.usage&&o.jsx("div",{className:"pt-1.5 flex items-center gap-3 text-[9px] text-muted-foreground/70 border-t border-purple-500/10 mt-1",children:o.jsxs("span",{children:[e("terminal.tokens").replace("{promptTokens}",String(j.details.usage.prompt_tokens)).replace("{completionTokens}",String(j.details.usage.completion_tokens))," = ",o.jsx("span",{className:"text-purple-500 font-bold",children:j.details.usage.total_tokens})]})})]}):j.event_type==="action"&&j.details?o.jsxs("div",{className:"bg-emerald-500/5 border border-emerald-500/10 rounded-lg p-3",children:[o.jsx("p",{className:"text-emerald-600 dark:text-emerald-400 font-bold mb-1 uppercase text-[9px] tracking-widest",children:e("terminal.executionComplete")}),o.jsxs("p",{className:"text-foreground font-medium",children:[j.details.action==="delete"&&e("terminal.action.delete"),j.details.action==="archive"&&e("terminal.action.archive"),j.details.action==="draft"&&e("terminal.action.draft"),j.details.action==="star"&&e("terminal.action.star"),!["delete","archive","draft","star"].includes(j.details.action)&&j.details.action]}),j.details.reason&&o.jsxs("p",{className:"text-[10px] text-muted-foreground mt-1.5 flex items-center gap-1",children:[o.jsx(ro,{className:"w-3 h-3"}),j.details.reason]})]}):j.event_type==="error"&&j.details?o.jsx("div",{className:"bg-red-500/5 border border-red-500/10 rounded-lg p-2.5 text-red-600 dark:text-red-400 font-medium",children:typeof j.details.error=="object"?j.details.error.message||JSON.stringify(j.details.error):j.details.error}):j.details?.is_completion?o.jsxs("div",{className:"bg-emerald-500/5 border border-emerald-500/20 rounded-lg p-3 space-y-2",children:[o.jsxs("div",{className:"flex items-center gap-2 text-emerald-600 dark:text-emerald-400 font-bold uppercase text-[9px] tracking-[0.2em]",children:[o.jsx(Ju,{className:"w-3.5 h-3.5"}),e("terminal.batchFinished")]}),o.jsxs("div",{className:"grid grid-cols-2 gap-4 pt-1",children:[o.jsxs("div",{className:"space-y-0.5",children:[o.jsx("p",{className:"text-[10px] text-muted-foreground uppercase",children:e("terminal.processed")}),o.jsx("p",{className:"text-sm font-bold",children:j.details.total_processed||0})]}),o.jsxs("div",{className:"space-y-0.5",children:[o.jsx("p",{className:"text-[10px] text-muted-foreground uppercase",children:e("terminal.actions")}),o.jsx("p",{className:"text-sm font-bold text-emerald-500",children:(j.details.deleted||0)+(j.details.drafted||0)})]})]}),j.details.errors>0&&o.jsx("p",{className:"text-[10px] text-red-500 font-bold pt-1 border-t border-emerald-500/10",children:e("terminal.itemsFailed").replace("{count}",String(j.details.errors))})]}):o.jsx("p",{className:"text-muted-foreground leading-relaxed",children:_(j.details?.message)||JSON.stringify(j.details)}),h[j.id]&&o.jsxs("div",{className:"mt-2 space-y-3 animate-in fade-in zoom-in-95 duration-200",children:[j.details?.system_prompt&&o.jsxs("div",{className:"space-y-1.5",children:[o.jsxs("div",{className:"flex items-center gap-1.5 text-[9px] font-bold text-muted-foreground uppercase tracking-widest px-1",children:[o.jsx(Ds,{className:"w-3 h-3"})," ",e("terminal.detail.systemPrompt")]}),o.jsx("div",{className:"bg-secondary/50 rounded-md p-3 border border-border overflow-x-auto",children:o.jsx("pre",{className:"whitespace-pre-wrap break-words text-[10px] leading-normal text-muted-foreground select-all",children:j.details.system_prompt})})]}),j.details?.content_preview&&o.jsxs("div",{className:"space-y-1.5",children:[o.jsxs("div",{className:"flex items-center gap-1.5 text-[9px] font-bold text-muted-foreground uppercase tracking-widest px-1",children:[o.jsx(Ds,{className:"w-3 h-3"})," ",e("terminal.detail.inputContent")]}),o.jsx("div",{className:"bg-secondary/50 rounded-md p-3 border border-border",children:o.jsx("p",{className:"whitespace-pre-wrap break-words text-[10px] text-muted-foreground",children:j.details.content_preview})})]}),j.details?._raw_response&&o.jsxs("div",{className:"space-y-1.5",children:[o.jsxs("div",{className:"flex items-center gap-1.5 text-[9px] font-bold text-muted-foreground uppercase tracking-widest px-1",children:[o.jsx(Ds,{className:"w-3 h-3"})," ",e("terminal.detail.rawLLMOutput")]}),o.jsx("div",{className:"bg-secondary/50 rounded-md p-3 border border-border overflow-x-auto",children:o.jsx("pre",{className:"text-[10px] text-muted-foreground select-all",children:JSON.stringify(JSON.parse(j.details._raw_response),null,2)})})]}),j.details?.raw_response&&o.jsxs("div",{className:"space-y-1.5",children:[o.jsxs("div",{className:"flex items-center gap-1.5 text-[9px] font-bold text-muted-foreground uppercase tracking-widest px-1",children:[o.jsx(Ds,{className:"w-3 h-3"})," ",e("terminal.detail.rawResponse")]}),o.jsx("div",{className:"bg-secondary/50 rounded-md p-3 border border-border overflow-x-auto",children:o.jsx("pre",{className:"text-[10px] text-muted-foreground select-all whitespace-pre-wrap",children:typeof j.details.raw_response=="object"?JSON.stringify(j.details.raw_response,null,2):j.details.raw_response})})]})]})]})]},j.id))]})]}):o.jsx("div",{className:"fixed bottom-4 right-4 z-50",children:o.jsxs(Z,{onClick:()=>i(!0),className:"shadow-lg bg-primary text-primary-foreground hover:opacity-90 border border-border",children:[o.jsx(Rl,{className:"w-4 h-4 mr-2"}),e("terminal.liveActivity"),(t.length>0||d)&&o.jsxs("span",{className:"ml-2 flex h-2 w-2 relative",children:[o.jsx("span",{className:me("animate-ping absolute inline-flex h-full w-full rounded-full opacity-75",d?"bg-red-400":"bg-green-400")}),o.jsx("span",{className:me("relative inline-flex rounded-full h-2 w-2",d?"bg-red-500":"bg-green-500")})]})]})})}const zy=w.createContext(null),M2=w.forwardRef(({className:e,defaultValue:t,value:n,onValueChange:r,...i},l)=>{const[u,d]=w.useState(t||""),h=n!==void 0?n:u,m=w.useCallback(p=>{r&&r(p),n===void 0&&d(p)},[r,n]);return o.jsx(zy.Provider,{value:{value:h,onValueChange:m},children:o.jsx("div",{ref:l,className:e,...i})})});M2.displayName="Tabs";const P2=w.forwardRef(({className:e,...t},n)=>o.jsx("div",{ref:n,className:me("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",e),...t}));P2.displayName="TabsList";const dg=w.forwardRef(({className:e,value:t,onClick:n,...r},i)=>{const l=w.useContext(zy);if(!l)throw new Error("TabsTrigger must be used within Tabs");const u=l.value===t;return o.jsx("button",{ref:i,type:"button",role:"tab","aria-selected":u,"data-state":u?"active":"inactive",className:me("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",e),onClick:d=>{l.onValueChange(t),n?.(d)},...r})});dg.displayName="TabsTrigger";const fg=w.forwardRef(({className:e,value:t,...n},r)=>{const i=w.useContext(zy);if(!i)throw new Error("TabsContent must be used within Tabs");return i.value!==t?null:o.jsx("div",{ref:r,role:"tabpanel","data-state":"active",className:me("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),...n})});fg.displayName="TabsContent";const Dq=()=>{const[e,t]=w.useState(null),[n,r]=w.useState(!0),i=w.useCallback(async()=>{try{const h=(await Oe.getLearningMetrics()).data;t(h?{total_classifications:h.total_classifications||0,correct_classifications:h.correct_classifications||0,drafts_generated:h.drafts_generated||0,drafts_edited:h.drafts_edited||0,category_patterns:h.category_patterns||{},vip_senders:h.vip_senders||[]}:{total_classifications:0,correct_classifications:0,drafts_generated:0,drafts_edited:0,category_patterns:{},vip_senders:[]})}catch(d){console.error("Failed to load learning metrics",d)}finally{r(!1)}},[]);if(w.useEffect(()=>{i()},[i]),n)return o.jsxs("div",{className:"p-8 text-center text-muted-foreground flex items-center justify-center gap-2",children:[o.jsx(Jr,{className:"w-5 h-5 animate-pulse text-primary"})," Loading AI DNA..."]});if(!e)return null;const l=e.total_classifications>0?Math.round(e.correct_classifications/e.total_classifications*100):100,u=Math.round(e.drafts_generated*5);return e.drafts_generated>0&&Math.round((e.drafts_generated-e.drafts_edited)/e.drafts_generated*100),o.jsxs("div",{className:"space-y-6 animate-in fade-in duration-500",children:[o.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[o.jsxs($e,{children:[o.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[o.jsx(Bt,{className:"text-sm font-medium",children:"AI Accuracy"}),o.jsx(Jr,{className:"h-4 w-4 text-primary"})]}),o.jsxs(vt,{children:[o.jsxs("div",{className:"text-2xl font-bold",children:[l,"%"]}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Classification confidence"}),o.jsx(Py,{value:l,className:"mt-3 h-2"})]})]}),o.jsxs($e,{children:[o.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[o.jsx(Bt,{className:"text-sm font-medium",children:"Time Saved"}),o.jsx(FR,{className:"h-4 w-4 text-green-500"})]}),o.jsxs(vt,{children:[o.jsxs("div",{className:"text-2xl font-bold",children:[u,"m"]}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Est. minutes saved drafting"})]})]}),o.jsxs($e,{children:[o.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[o.jsx(Bt,{className:"text-sm font-medium",children:"Learned Patterns"}),o.jsx(bg,{className:"h-4 w-4 text-blue-500"})]}),o.jsxs(vt,{children:[o.jsx("div",{className:"text-2xl font-bold",children:Object.keys(e.category_patterns).length}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Domain rules learned"})]})]}),o.jsxs($e,{children:[o.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[o.jsx(Bt,{className:"text-sm font-medium",children:"VIP Network"}),o.jsx(ip,{className:"h-4 w-4 text-yellow-500"})]}),o.jsxs(vt,{children:[o.jsx("div",{className:"text-2xl font-bold",children:e.vip_senders.length}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"High-priority contacts"})]})]})]}),o.jsxs(M2,{defaultValue:"patterns",className:"w-full",children:[o.jsxs(P2,{children:[o.jsx(dg,{value:"patterns",children:"Domain Patterns"}),o.jsx(dg,{value:"vips",children:"VIP Senders"})]}),o.jsx(fg,{value:"patterns",className:"space-y-4 pt-4",children:o.jsxs($e,{children:[o.jsxs(Ot,{children:[o.jsx(Bt,{className:"text-lg",children:"Learned Categorization Rules"}),o.jsx(xs,{children:"The AI automatically learns to classify emails from these domains based on your corrections."})]}),o.jsx(vt,{children:o.jsx("div",{className:"space-y-4",children:Object.entries(e.category_patterns).length===0?o.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground border border-dashed rounded-lg bg-secondary/10",children:[o.jsx(ao,{className:"h-10 w-10 mb-4 opacity-50"}),o.jsx("p",{children:"No patterns learned yet."}),o.jsx("p",{className:"text-xs mt-1",children:"Correct some email categories in the Dashboard to teach the AI!"})]}):o.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:Object.entries(e.category_patterns).map(([d,h])=>o.jsxs("div",{className:"flex items-center justify-between p-3 border rounded-lg bg-card hover:bg-accent/50 transition-colors",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"h-2 w-2 rounded-full bg-blue-500"}),o.jsx("span",{className:"font-mono text-sm",children:d})]}),o.jsx(El,{variant:"secondary",className:"capitalize",children:h})]},d))})})})]})}),o.jsx(fg,{value:"vips",className:"pt-4",children:o.jsxs($e,{children:[o.jsxs(Ot,{children:[o.jsx(Bt,{className:"text-lg",children:"Identified VIP Senders"}),o.jsx(xs,{children:"Contacts that are automatically flagged as High Priority."})]}),o.jsx(vt,{children:o.jsx("div",{className:"space-y-4",children:e.vip_senders.length===0?o.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground border border-dashed rounded-lg bg-secondary/10",children:[o.jsx(KR,{className:"h-10 w-10 mb-4 opacity-50"}),o.jsx("p",{children:"No VIPs identified yet."}),o.jsx("p",{className:"text-xs mt-1",children:"Interacting frequently with contacts will elevate them to VIP status."})]}):o.jsx("div",{className:"flex flex-wrap gap-2",children:e.vip_senders.map(d=>o.jsxs(El,{variant:"outline",className:"pl-1 pr-3 py-1.5 text-sm flex items-center gap-2 bg-secondary/20",children:[o.jsx("div",{className:"w-5 h-5 rounded-full bg-yellow-500/10 flex items-center justify-center",children:o.jsx(ip,{className:"w-3 h-3 text-yellow-500 fill-yellow-500"})}),d]},d))})})})]})})]})]})},z2=w.forwardRef(({className:e,...t},n)=>o.jsx("span",{ref:n,className:me("absolute h-px w-px overflow-hidden whitespace-nowrap border-0 p-0","[clip:rect(0,0,0,0)]",e),...t}));z2.displayName="VisuallyHidden";function Mq(e={}){const[t,n]=w.useState(!1),[r,i]=w.useState(""),[l,u]=w.useState(""),[d,h]=w.useState(!1),m=w.useRef(null);w.useEffect(()=>{const v=window.SpeechRecognition||window.webkitSpeechRecognition;return h(!!v),v&&(m.current=new v,m.current.continuous=e.continuous??!1,m.current.interimResults=e.interimResults??!0,m.current.lang=e.lang||"en-US",m.current.onresult=S=>{let _="",j="";for(let N=S.resultIndex;N<S.results.length;N++){const A=S.results[N][0].transcript;S.results[N].isFinal?j+=A:_+=A}j&&i(N=>N+" "+j),u(_)},m.current.onend=()=>{n(!1)},m.current.onerror=S=>{console.error("[SpeechRecognition] Error:",S.error),n(!1)}),()=>{m.current&&m.current.stop()}},[e.continuous,e.interimResults,e.lang]);const p=w.useCallback(()=>{m.current&&!t&&(i(""),u(""),m.current.start(),n(!0))},[t]),g=w.useCallback(()=>{m.current&&t&&(m.current.stop(),n(!1))},[t]),b=w.useCallback(()=>{i(""),u("")},[]);return{isListening:t,transcript:r,interimTranscript:l,isSupported:d,startListening:p,stopListening:g,resetTranscript:b}}const Pq=(e,t)=>{const n={setup_wizard:"agent.title.setup",configuration_wizard:"agent.title.configuration",draft_review:"agent.title.drafts",explainer:"agent.title.explainer",global:"agent.title.global"};return n[e]?t(n[e]):t("agent.title.default").replace("{page}",e.replace(/_/g," "))},JS=(e,t,n)=>{switch(e){case"setup_wizard":return t("agent.intro.setup");case"configuration_wizard":return t("agent.intro.configuration").replace("{accountsCount}",String(n?.accounts_count||0)).replace("{rulesCount}",String(n?.rules_count||0));case"draft_review":{const r=n?.count||0;return t(r===1?"agent.intro.drafts.one":"agent.intro.drafts.other").replace("{count}",String(r))}case"explainer":return t("agent.intro.explainer");case"global":return t("agent.intro.global");default:return t("agent.intro.default").replace("{page}",e.replace(/_/g," "))}};function Vu({className:e}){const{currentConfig:t,chatHistory:n,agentState:r,sendMessage:i}=B_(),{state:l}=Tn(),{speak:u}=cy(),{speakingId:d,stop:h}=I_(),{t:m}=tt(),[p,g]=w.useState(!1),[b,v]=w.useState(""),[S,_]=w.useState(!1),[j,N]=w.useState(!1),A=w.useRef(null),T=w.useRef(t.page_id),{isListening:O,transcript:L,interimTranscript:M,isSupported:B,startListening:P,stopListening:q,resetTranscript:D}=Mq({continuous:!1,interimResults:!0});w.useEffect(()=>{const V=()=>{try{const C=localStorage.getItem("auto_speak_enabled");return C===null?!0:C==="true"}catch{return!0}},$=p&&n.length===0&&!S&&V(),de=t.page_id!==T.current;if($||p&&de&&n.length===0){const C=JS(t.page_id,m,t.data),z={provider:l.settings?.tts_provider||void 0,voice:l.settings?.tts_voice||void 0,speed:l.settings?.tts_speed!==void 0?l.settings.tts_speed:1,quality:l.settings?.tts_quality!==void 0?l.settings.tts_quality:10};console.log("[AgentOverlay] Intro speaking with TTS options:",z),u(C,`intro-${t.page_id}`,z),_(!0),T.current=t.page_id}p||_(!1)},[p,n.length,t.page_id,S,u]),w.useEffect(()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)},[n,p]),w.useEffect(()=>{L&&!O&&(v(L.trim()),D())},[L,O,D]),w.useEffect(()=>{O&&(L||M)&&v((L+" "+M).trim())},[L,M,O]);const Q=async()=>{if(!b.trim())return;const V=b;v(""),D(),await i(V)},G=V=>{V.key==="Enter"&&!V.shiftKey&&(V.preventDefault(),Q())},fe=()=>{O?q():P()},se=async(V,$)=>{const de=`msg-${$}`;if(d===de){h();return}const C={provider:l.settings?.tts_provider||void 0,voice:l.settings?.tts_voice||void 0,speed:l.settings?.tts_speed!==void 0?l.settings.tts_speed:1,quality:l.settings?.tts_quality!==void 0?l.settings.tts_quality:10};console.log("[AgentOverlay] Speaking with TTS options:",C),await u(V,de,C)},ae={p:({children:V})=>o.jsx("p",{className:"text-sm leading-relaxed whitespace-pre-wrap",children:V}),ul:({children:V})=>o.jsx("ul",{className:"list-disc pl-4 space-y-1 text-sm",children:V}),ol:({children:V})=>o.jsx("ol",{className:"list-decimal pl-4 space-y-1 text-sm",children:V}),li:({children:V})=>o.jsx("li",{className:"text-sm",children:V}),a:({href:V,children:$})=>o.jsx("a",{href:V,target:"_blank",rel:"noreferrer",className:"text-primary underline underline-offset-2",children:$}),code:V=>{const{inline:$,children:de}=V;return $?o.jsx("code",{className:"px-1 py-0.5 rounded bg-background/60 text-[12px] font-mono",children:de}):o.jsx("code",{className:"text-[12px] font-mono",children:de})},pre:({children:V})=>o.jsx("pre",{className:"mt-2 overflow-x-auto rounded bg-background/60 p-2 text-[12px] font-mono",children:V}),blockquote:({children:V})=>o.jsx("blockquote",{className:"border-l-2 border-border pl-3 text-sm text-muted-foreground",children:V}),strong:({children:V})=>o.jsx("strong",{className:"font-semibold",children:V}),em:({children:V})=>o.jsx("em",{className:"italic",children:V})},I=me("fixed bottom-6 left-6 z-50",e);return o.jsxs(o.Fragment,{children:[p&&o.jsx("div",{className:I,children:o.jsxs("div",{className:me(j?"w-[calc(100vw-2rem)] sm:w-[33vw] sm:max-w-[560px] h-[90vh] max-h-[calc(100vh-6rem)]":"w-[360px] sm:w-[380px] h-[520px] max-w-[calc(100vw-2rem)] max-h-[calc(100vh-6rem)]","bg-background border border-border/60 rounded-2xl shadow-2xl","flex flex-col overflow-hidden","animate-in slide-in-from-bottom-10 fade-in duration-200","transition-[width,height] duration-200 ease-out","motion-reduce:transition-none motion-reduce:animate-none"),children:[o.jsxs("div",{className:"p-3 border-b bg-muted/40 flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("div",{className:me("w-2.5 h-2.5 rounded-full",O?"bg-red-500 animate-pulse":r==="idle"?"bg-muted-foreground":r==="thinking"?"bg-yellow-500 animate-pulse":r==="speaking"?"bg-emerald-500 animate-pulse":"bg-red-500")}),o.jsxs("div",{className:"flex flex-col",children:[o.jsx("span",{className:"font-semibold text-sm leading-tight",children:O?m("agent.status.listening"):Pq(t.page_id,m)}),o.jsx("span",{className:"text-[10px] text-muted-foreground",children:m(r==="thinking"?"agent.status.analyzing":r==="speaking"?"agent.status.speaking":"agent.status.ready")})]})]}),o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(Z,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>N(V=>!V),"aria-label":j?"Collapse assistant":"Expand assistant",title:j?"Collapse":"Expand",children:j?o.jsx(ij,{className:"w-4 h-4"}):o.jsx(aj,{className:"w-4 h-4"})}),o.jsx(Z,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>g(!1),"aria-label":"Close assistant",children:o.jsx(on,{className:"w-4 h-4"})})]})]}),o.jsxs("div",{ref:A,className:"flex-1 overflow-y-auto p-4 space-y-4 bg-background",children:[n.length===0&&o.jsx("div",{className:"text-center text-muted-foreground text-xs mt-10 whitespace-pre-line",children:JS(t.page_id,m,t.data)}),n.map((V,$)=>{const de=`msg-${$}`,C=d===de,z=V.role!=="user";return o.jsx("div",{className:me("flex flex-col max-w-[85%] rounded-2xl p-3 text-sm relative group",V.role==="user"?"self-end bg-primary/10 text-foreground ml-auto rounded-br-md":"self-start bg-secondary text-secondary-foreground rounded-bl-md"),children:o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx("div",{className:"flex-1",children:V.role==="user"?V.content:o.jsx(i2,{remarkPlugins:[A2],components:ae,children:V.content})}),z&&o.jsx("button",{onClick:()=>se(V.content,$),className:me("shrink-0 p-1.5 rounded-md hover:bg-background/60 transition-colors","opacity-0 group-hover:opacity-100",C&&"opacity-100"),title:C?"Stop speaking":"Speak message",children:C?o.jsx(Sg,{className:"w-3.5 h-3.5 text-muted-foreground animate-pulse"}):o.jsx(Ol,{className:"w-3.5 h-3.5 text-muted-foreground"})})]})},$)}),r==="thinking"&&o.jsxs("div",{className:"self-start bg-secondary/50 rounded-lg p-3 flex gap-1",children:[o.jsx("span",{className:"w-1.5 h-1.5 bg-foreground/40 rounded-full animate-bounce [animation-delay:-0.3s]"}),o.jsx("span",{className:"w-1.5 h-1.5 bg-foreground/40 rounded-full animate-bounce [animation-delay:-0.15s]"}),o.jsx("span",{className:"w-1.5 h-1.5 bg-foreground/40 rounded-full animate-bounce"})]}),O&&o.jsxs("div",{className:"self-start bg-red-500/10 border border-red-500/30 rounded-lg p-4 flex flex-col gap-2 animate-pulse",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(H0,{className:"w-4 h-4 text-red-500 animate-pulse"}),o.jsx("span",{className:"text-xs font-semibold text-red-500",children:m("agent.recording")})]}),o.jsx("div",{className:"flex items-center justify-center gap-1 h-8",children:[...Array(12)].map((V,$)=>o.jsx("div",{className:"w-1 bg-red-500 rounded-full animate-pulse",style:{height:`${20+Math.sin($)*15}px`,animationDelay:`${$*.1}s`,animationDuration:"0.8s"}},$))}),M&&o.jsxs("div",{className:"text-xs text-muted-foreground italic",children:['"',M,'..."']})]})]}),o.jsxs("div",{className:"p-3 border-t bg-background flex gap-2",children:[o.jsx("input",{className:"flex-1 bg-secondary/40 border border-border/50 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-primary/40 outline-none",placeholder:m(O?"agent.composer.listening":"agent.composer.placeholder"),value:b,onChange:V=>v(V.target.value),onKeyDown:G,disabled:r==="thinking"||r==="speaking"||O}),B&&o.jsx(Z,{size:"icon",variant:O?"default":"outline",className:me("h-9 w-9 shrink-0",O&&"bg-red-500 hover:bg-red-600 animate-pulse"),onClick:fe,disabled:r==="thinking"||r==="speaking","aria-label":O?"Stop listening":"Start listening",children:O?o.jsx(HA,{className:"w-4 h-4"}):o.jsx(H0,{className:"w-4 h-4"})}),o.jsx(Z,{size:"icon",className:"h-9 w-9 shrink-0",onClick:Q,disabled:!b.trim()||r==="thinking"||O,"aria-label":"Send message",children:r==="thinking"?o.jsx(wt,{className:"w-4 h-4 animate-spin"}):o.jsx(Wl,{className:"w-4 h-4"})})]})]})}),o.jsx("div",{className:I,children:o.jsx(Z,{size:"icon",className:me("relative rounded-full h-11 w-11 border border-border/60 bg-primary text-primary-foreground shadow-md","transition-all duration-200 ease-out","hover:bg-primary/90 hover:shadow-lg hover:-translate-y-0.5","active:translate-y-0 active:shadow-md active:scale-95","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40 focus-visible:ring-offset-2 focus-visible:ring-offset-background","motion-reduce:transition-none motion-reduce:hover:transform-none",p?"rotate-0 scale-0 opacity-0":"scale-100 opacity-100",r==="speaking"&&"ring-4 ring-emerald-500/30 animate-pulse"),onClick:()=>g(!0),"aria-label":"Open assistant chat",title:"Open assistant chat",children:r==="speaking"?o.jsx(Ol,{className:"w-5 h-5 animate-pulse"}):o.jsx(vd,{className:"w-5 h-5"})})})]})}function zq(){const{state:e,isSubscribed:t,actions:n}=Tn(),{t:r}=tt(),[i,l]=w.useState(null),[u,d]=w.useState(!0),[h,m]=w.useState(!1),[p,g]=w.useState(!0),[b,v]=w.useState("dashboard"),[S,_]=w.useState(!1),[j,N]=w.useState(null),[A,T]=w.useState(!1),[O,L]=w.useState(!1),[M,B]=w.useState(!1),[P,q]=w.useState(null),[D,Q]=w.useState(!1),[G,fe]=w.useState(null),[se,ae]=w.useState(!1),[I,V]=w.useState(!1);if(w.useEffect(()=>{if(e.isInitialized&&e.isAuthenticated&&e.settings&&!e.isLoading&&!e.settings.persona_completed&&!se&&!I){const C=setTimeout(()=>{ae(!0)},2e3);return()=>clearTimeout(C)}},[e.isInitialized,e.isAuthenticated,e.settings,e.isLoading,I]),w.useEffect(()=>{const z=new URLSearchParams(window.location.search).get("code");z&&!S&&(async()=>{_(!0);try{const R=await Oe.connectGmail(z);if(R.data?.success)le.success("Gmail connected successfully!"),window.opener?setTimeout(()=>window.close(),1500):(window.history.replaceState({},"",window.location.pathname),n.fetchAccounts());else{const oe=typeof R.error=="string"?R.error:R.error?.message;le.error(oe||"Failed to connect Gmail")}}catch{le.error("Connection failed")}finally{_(!1)}})()},[]),S)return o.jsx(sd,{text:r("app.connecting")});w.useEffect(()=>{(async()=>{if(!fo()){m(!0),d(!1);return}try{const{data:oe,error:Se}=await gt.from("init_state").select("is_initialized").single();Se?(console.warn("[App] Init check error (might be fresh DB):",Se),Se.code==="42P01"&&g(!1)):g(oe.is_initialized>0);const{data:{session:ge}}=await gt.auth.getSession();if(l(ge?.user??null),ge?.user){const Ke=await dy(gt);N(Ke.needsMigration?Ke:null),Ke.needsMigration&&!XL()&&T(!0)}const pe=await Cq();pe&&!Tq()&&(q(pe),Q(!0))}catch(oe){console.error("[App] Status check failed:",oe),oe instanceof Error&&oe.message.includes("Invalid API key")&&m(!0)}finally{d(!1)}})();const{data:{subscription:z}}=gt.auth.onAuthStateChange((R,oe)=>{l(oe?.user??null),oe||(N(null),T(!1))}),X=()=>{if(Ms.isEnabled()){const R=new(window.AudioContext||window.webkitAudioContext);R.state==="suspended"&&R.resume()}window.removeEventListener("click",X),window.removeEventListener("keydown",X)};return window.addEventListener("click",X),window.addEventListener("keydown",X),()=>{z.unsubscribe(),window.removeEventListener("click",X),window.removeEventListener("keydown",X)}},[]),w.useEffect(()=>{if(i){n.fetchAccounts(),n.fetchRules(),n.fetchSettings(),n.fetchProfile();const C=setTimeout(()=>{console.debug("[App] Retrying fetchAccounts after initialization"),n.fetchAccounts()},1e3);return()=>clearTimeout(C)}},[i]),w.useEffect(()=>{const C=async()=>{try{await Oe.healthCheck()}catch{console.warn("[App] Keep-alive ping failed")}};C();const z=setInterval(C,3e4);return()=>clearInterval(z)},[]);const $=()=>{L(!0),T(!1)},de={migrationStatus:j,showMigrationBanner:A,showMigrationModal:O,openMigrationModal:$,suppressMigrationBanner:M,setSuppressMigrationBanner:B};return u?o.jsxs(o.Fragment,{children:[o.jsx(sd,{text:r("app.loadingWorkspace")}),o.jsx(Vu,{className:"z-[80]"})]}):h?o.jsxs(o.Fragment,{children:[o.jsx(K_,{onComplete:()=>m(!1)}),o.jsx(Vu,{className:"z-[80]"})]}):i?o.jsx(t3,{value:de,children:o.jsxs("div",{className:"min-h-screen bg-background font-sans text-foreground transition-colors duration-300",children:[o.jsx("header",{className:"sticky top-0 z-50 w-full border-b border-border/40 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60",children:o.jsxs("div",{className:"max-w-7xl mx-auto flex h-16 items-center justify-between px-4 sm:px-8",children:[o.jsxs("div",{className:"flex items-center gap-4",children:[o.jsxs("button",{onClick:()=>v("dashboard"),className:"text-xl font-bold flex items-center gap-2 hover:opacity-80 transition-opacity",children:[o.jsx(fy,{className:"w-8 h-8"}),o.jsx("span",{className:"hidden sm:inline",children:r("app.name")}),o.jsx("span",{className:"sm:hidden",children:"Email AI"})]}),o.jsxs("div",{className:me("flex items-center gap-1.5 px-2 h-6 rounded-full text-[10px] font-bold border transition-colors",t?"bg-emerald-500/10 text-emerald-600 border-emerald-500/20 dark:text-emerald-400":"bg-yellow-500/10 text-yellow-600 border-yellow-500/20 dark:text-yellow-400"),children:[o.jsxs("div",{className:"relative flex items-center justify-center",children:[t&&o.jsx("span",{className:"absolute inline-flex h-3 w-3 rounded-full bg-emerald-500/40 animate-ping"}),o.jsx("div",{className:me("relative w-2 h-2 rounded-full",t?"bg-emerald-500":"bg-yellow-500")})]}),o.jsx("span",{className:"hidden xs:inline leading-none",children:r(t?"app.statusLive":"app.statusOffline")})]})]}),o.jsxs("div",{className:"flex gap-4 items-center",children:[o.jsxs("nav",{className:"flex items-center gap-1 bg-secondary/50 p-1 rounded-lg",children:[o.jsxs(Z,{variant:b==="dashboard"?"secondary":"ghost",size:"sm",onClick:()=>v("dashboard"),className:"gap-2",children:[o.jsx(EA,{className:"w-4 h-4"}),o.jsx("span",{className:"hidden sm:inline",children:r("nav.dashboard")})]}),o.jsxs(Z,{variant:b==="drafts"?"secondary":"ghost",size:"sm",onClick:()=>v("drafts"),className:"gap-2",children:[o.jsx(nA,{className:"w-4 h-4"}),o.jsx("span",{className:"hidden sm:inline",children:r("nav.drafts")||"Drafts"})]}),o.jsxs(Z,{variant:b==="autopilot"?"secondary":"ghost",size:"sm",onClick:()=>v("autopilot"),className:"gap-2",children:[o.jsx(qu,{className:"w-4 h-4"}),o.jsx("span",{className:"hidden sm:inline",children:r("nav.autopilot")})]}),o.jsxs(Z,{variant:b==="analytics"?"secondary":"ghost",size:"sm",onClick:()=>v("analytics"),className:"gap-2",children:[o.jsx(gg,{className:"w-4 h-4"}),o.jsx("span",{className:"hidden sm:inline",children:r("nav.analytics")})]}),o.jsxs(Z,{variant:b==="config"?"secondary":"ghost",size:"sm",onClick:()=>v("config"),className:"gap-2",children:[o.jsx(Al,{className:"w-4 h-4"}),o.jsx("span",{className:"hidden sm:inline",children:r("nav.configuration")})]})]}),o.jsx("div",{className:"h-6 w-px bg-border/50 mx-2 hidden sm:block"}),o.jsx(ly,{}),o.jsx(Tj,{}),o.jsx(Z,{variant:b==="account"?"secondary":"ghost",size:"sm",onClick:()=>v("account"),className:"text-muted-foreground hover:text-foreground p-0 w-8 h-8 rounded-full overflow-hidden border",title:r("nav.accountSettings"),children:e.profile?.avatar_url?o.jsx("img",{src:e.profile.avatar_url,alt:"Profile",className:"w-full h-full object-cover"}):o.jsx(FC,{className:"w-5 h-5"})})]})]})}),o.jsxs("main",{className:"max-w-7xl mx-auto p-4 sm:p-8 mt-4 mb-12",children:[b==="dashboard"&&o.jsx(mU,{}),b==="drafts"&&o.jsx(bU,{onPreview:fe}),b==="autopilot"&&o.jsx(pq,{}),b==="config"&&o.jsx(Q7,{}),b==="analytics"&&o.jsx(Iq,{}),b==="account"&&o.jsx(cq,{})]}),o.jsx("footer",{className:"max-w-7xl mx-auto px-4 sm:px-8 pb-8 text-center sm:text-left",children:o.jsxs("p",{className:"text-[10px] font-medium text-muted-foreground/40 uppercase tracking-[0.2em]",children:["Email Automator ",o.jsx("span",{className:"mx-1",children:"•"})," v","2.23.2"]})}),e.error&&o.jsx("div",{className:"fixed bottom-20 left-4 right-4 sm:left-auto sm:right-4 sm:max-w-sm z-50",children:o.jsx("div",{className:"bg-destructive/10 border border-destructive/20 text-destructive p-4 rounded-lg",children:o.jsx("p",{className:"text-sm",children:e.error})})}),j&&A&&!M&&o.jsx(xq,{status:j,onDismiss:()=>T(!1),onLearnMore:$}),P&&D&&o.jsx(Rq,{versionInfo:P,onDismiss:()=>Q(!1)}),j&&o.jsx(vq,{open:O,onOpenChange:L,status:j}),G&&o.jsx(W7,{email:G,onClose:()=>fe(null),onSend:async C=>{fe(null)},onDismiss:async C=>{(await Oe.dismissDraft(C)).data?.success?(le.success(r("drafts.dismissSuccess")||"Draft dismissed"),fe(null)):le.error(r("drafts.dismissError")||"Failed to dismiss draft")}}),o.jsx(Oq,{}),o.jsx(Vu,{}),o.jsx(is,{open:se,onOpenChange:C=>{C||V(!0),ae(C)},children:o.jsxs(os,{className:"max-w-3xl border-none bg-transparent shadow-none p-0 sm:max-w-3xl",children:[o.jsx(z2,{children:o.jsx(bs,{children:"Persona Setup Wizard"})}),o.jsx(R2,{onComplete:()=>{ae(!1),n.fetchSettings()},onClose:()=>{ae(!1),V(!0)}})]})})]})}):o.jsxs(o.Fragment,{children:[o.jsx(yq,{onSuccess:()=>n.fetchProfile(),onConfigure:()=>m(!0),isInitialized:p}),o.jsx(Vu,{className:"z-[80]"})]})}function Lq({runId:e,accountEmail:t,isOpen:n,onOpenChange:r}){const{t:i}=tt(),[l,u]=w.useState([]),[d,h]=w.useState(!1);w.useEffect(()=>{n&&e&&m()},[n,e]);const m=async()=>{if(e){h(!0);try{const g=await Oe.getRunEvents(e);g.data&&u(g.data.events)}catch(g){console.error("Failed to fetch run trace:",g)}finally{h(!1)}}},p=g=>{switch(g){case"analysis":return o.jsx(Jr,{className:"w-4 h-4 text-purple-500"});case"action":return o.jsx(ao,{className:"w-4 h-4 text-emerald-500"});case"error":return o.jsx(ls,{className:"w-4 h-4 text-red-500"});default:return o.jsx(ro,{className:"w-4 h-4 text-blue-500"})}};return o.jsx(is,{open:n,onOpenChange:r,children:o.jsxs(os,{className:"sm:max-w-2xl max-h-[85vh] flex flex-col p-0 overflow-hidden",children:[o.jsxs(dr,{className:"p-6 border-b",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(yd,{className:"w-5 h-5 text-primary"}),o.jsx(bs,{children:i("trace.runTrace")})]}),o.jsx(fr,{children:t?i("trace.fullLogFor").replace("{email}",t):i("trace.historicalLog")})]}),o.jsx("div",{className:"flex-1 overflow-y-auto p-6 space-y-6 custom-scrollbar bg-secondary/5",children:d?o.jsx("div",{className:"py-20 flex justify-center",children:o.jsx(sd,{text:i("trace.loadingTrace")})}):l.length===0?o.jsx("div",{className:"py-20 text-center text-muted-foreground italic font-mono text-sm",children:i("trace.noTraceEvents")}):l.map((g,b)=>o.jsxs("div",{className:"relative pl-8",children:[b!==l.length-1&&o.jsx("div",{className:"absolute left-[15px] top-8 bottom-[-24px] w-px bg-border"}),o.jsx("div",{className:"absolute left-0 top-0 w-8 h-8 rounded-full border bg-background flex items-center justify-center z-10 shadow-sm",children:p(g.event_type)}),o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"flex flex-col",children:[o.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider text-foreground/70",children:g.agent_state}),g.emails?.subject&&o.jsxs("span",{className:"text-[10px] text-primary font-medium truncate max-w-[300px]",children:["Re: ",g.emails.subject]})]}),o.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:[o.jsx(ea,{className:"w-3 h-3"}),new Date(g.created_at).toLocaleTimeString()]})]}),o.jsxs("div",{className:"bg-card border rounded-lg p-4 shadow-sm",children:[g.event_type==="info"&&o.jsx("p",{className:"text-sm text-foreground/90",children:g.details?.message}),g.event_type==="analysis"&&o.jsxs("div",{className:"space-y-2",children:[o.jsxs("p",{className:"text-xs text-foreground italic leading-relaxed",children:['"',g.details?.summary,'"']}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx("span",{className:"text-[9px] bg-secondary px-1.5 py-0.5 rounded font-bold uppercase",children:g.details?.category}),g.details?.suggested_actions?.map(v=>o.jsx("span",{className:"text-[9px] bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 px-1.5 py-0.5 rounded border border-emerald-500/20 font-bold uppercase",children:v},v))]}),g.details?.usage&&o.jsxs("div",{className:"flex gap-3 pt-1.5 mt-1 border-t border-border/50 text-[9px] text-muted-foreground",children:[o.jsxs("span",{children:["In: ",o.jsx("b",{children:g.details.usage.prompt_tokens})]}),o.jsxs("span",{children:["Out: ",o.jsx("b",{children:g.details.usage.completion_tokens})]}),o.jsxs("span",{children:["Total: ",o.jsx("span",{className:"text-primary font-bold",children:g.details.usage.total_tokens})]})]})]}),g.event_type==="action"&&o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("p",{className:"text-sm font-bold text-emerald-600 dark:text-emerald-400 capitalize",children:[i("dashboard.done")," ",g.details?.action]}),o.jsx(yg,{className:"w-4 h-4 text-emerald-500"})]}),g.event_type==="error"&&o.jsx("p",{className:"text-sm text-red-600 dark:text-red-400 font-bold",children:g.details?.error})]})]})]},g.id))})]})})}function Iq(){const{state:e,actions:t}=Tn(),{t:n}=tt(),[r,i]=w.useState(null),[l,u]=w.useState(void 0),[d,h]=w.useState(!1),[m,p]=w.useState("overview");if(w.useEffect(()=>{t.fetchStats()},[]),!e.stats)return o.jsx(sd,{text:n("common.loading")});const g=(v,S)=>{i(v),u(S),h(!0)},{stats:b}=e;return o.jsxs("div",{className:"space-y-8 animate-in fade-in duration-500",children:[o.jsxs("div",{className:"flex flex-col md:flex-row md:items-center justify-between gap-4",children:[o.jsxs("h2",{className:"text-2xl font-bold flex items-center gap-2",children:[o.jsx(gg,{className:"w-6 h-6 text-primary"}),n("analytics.title")]}),o.jsxs("div",{className:"flex p-1 bg-muted rounded-lg w-full md:w-auto",children:[o.jsx("button",{onClick:()=>p("overview"),className:`flex-1 md:w-32 px-3 py-1.5 text-sm font-medium rounded-md transition-all ${m==="overview"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:bg-background/50"}`,children:"Overview"}),o.jsxs("button",{onClick:()=>p("learning"),className:`flex-1 md:w-32 px-3 py-1.5 text-sm font-medium rounded-md transition-all flex items-center justify-center gap-2 ${m==="learning"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:bg-background/50"}`,children:[o.jsx(Jr,{className:"w-3.5 h-3.5"}),"Learning"]})]})]}),m==="learning"?o.jsx(Dq,{}):o.jsxs("div",{className:"space-y-8",children:[o.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[o.jsx(Fu,{title:n("analytics.totalEmails"),value:b.totalEmails,color:"primary"}),o.jsx(Fu,{title:n("analytics.spamCaught"),value:b.categoryCounts.spam||0,color:"destructive"}),o.jsx(Fu,{title:n("analytics.actionsTaken"),value:Object.values(b.actionCounts).reduce((v,S)=>v+S,0)-(b.actionCounts.none||0),color:"emerald"}),o.jsx(Fu,{title:n("analytics.accounts"),value:b.accountCount,color:"blue"})]}),o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-8",children:[o.jsxs("div",{className:"bg-card border rounded-xl p-6",children:[o.jsx("h3",{className:"font-semibold mb-4",children:n("analytics.categories")}),o.jsx("div",{className:"space-y-3",children:Object.entries(b.categoryCounts).map(([v,S])=>o.jsx("div",{className:"flex items-center gap-3",children:o.jsxs("div",{className:"flex-1",children:[o.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[o.jsx("span",{className:"capitalize",children:v}),o.jsx("span",{className:"text-muted-foreground",children:S})]}),o.jsx("div",{className:"h-2 bg-secondary rounded-full overflow-hidden",children:o.jsx("div",{className:"h-full bg-primary rounded-full transition-all",style:{width:`${S/b.totalEmails*100}%`}})})]})},v))})]}),o.jsxs("div",{className:"bg-card border rounded-xl p-6",children:[o.jsx("h3",{className:"font-semibold mb-4",children:n("analytics.actionsTaken")}),o.jsx("div",{className:"space-y-3",children:Object.entries(b.actionCounts).map(([v,S])=>o.jsxs("div",{className:"flex items-center justify-between py-2 border-b last:border-0",children:[o.jsx("span",{className:"capitalize",children:v}),o.jsx("span",{className:"font-medium",children:S})]},v))})]})]}),o.jsxs("div",{className:"bg-card border rounded-xl p-6",children:[o.jsx("h3",{className:"font-semibold mb-4",children:n("analytics.recentActivity")}),b.recentSyncs.length===0?o.jsx("p",{className:"text-muted-foreground text-sm",children:n("analytics.noActivity")}):o.jsx("div",{className:"space-y-3",children:b.recentSyncs.map(v=>{const S=v.completed_at?Math.round((new Date(v.completed_at).getTime()-new Date(v.started_at).getTime())/1e3):null;return o.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between p-3 border rounded-lg hover:bg-secondary/30 transition-colors gap-3 cursor-pointer group",onClick:()=>g(v.id,v.email_accounts?.email_address),children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:me("w-2.5 h-2.5 rounded-full",v.status==="success"?"bg-emerald-500":v.status==="failed"?"bg-destructive":"bg-yellow-500 shadow-[0_0_8px_rgba(234,179,8,0.5)] animate-pulse")}),o.jsxs("div",{className:"flex flex-col",children:[o.jsx("span",{className:"text-sm font-medium group-hover:text-primary transition-colors",children:v.email_accounts?.email_address||n("common.systemSync")}),o.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:[o.jsx(ea,{className:"w-3 h-3"}),new Date(v.started_at).toLocaleString(),S!==null&&o.jsxs("span",{className:"ml-2 px-1.5 py-0.5 bg-secondary rounded-full",children:[S,"s"]})]})]})]}),o.jsx("div",{className:"flex items-center gap-4 text-xs",children:o.jsxs("div",{className:"flex flex-col items-end",children:[o.jsx("span",{className:"font-bold text-primary",children:n("analytics.emails").replace("{count}",v.emails_processed.toString())}),o.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[n("analytics.deleted").replace("{count}",v.emails_deleted.toString()),", ",n("analytics.drafted").replace("{count}",v.emails_drafted.toString())]})]})})]},v.id)})})]})]}),o.jsx(Lq,{runId:r,accountEmail:l,isOpen:d,onOpenChange:h})]})}function Fu({title:e,value:t,color:n}){const r={primary:"bg-primary/10 text-primary",destructive:"bg-destructive/10 text-destructive",emerald:"bg-emerald-500/10 text-emerald-600 dark:text-emerald-400",blue:"bg-blue-500/10 text-blue-600 dark:text-blue-400"};return o.jsxs("div",{className:"bg-card border rounded-xl p-6",children:[o.jsx("p",{className:"text-sm text-muted-foreground mb-1",children:e}),o.jsx("p",{className:`text-3xl font-bold ${r[n]||""}`,children:t})]})}function Uq(){return o.jsx($L,{children:o.jsx(iO,{defaultTheme:"system",storageKey:"email-automator-theme",children:o.jsx(s3,{children:o.jsx(n3,{children:o.jsx(HL,{children:o.jsx(GL,{children:o.jsxs(Z5,{children:[o.jsx(zq,{}),o.jsx(W5,{})]})})})})})})})}aC.createRoot(document.getElementById("root")).render(o.jsx(QS.StrictMode,{children:o.jsx(Uq,{})}));
|
|
216
|
+
Trung Le`,value:e.signature||"",onChange:d=>t({signature:d.target.value})})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Ge,{children:"Common Phrases"}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Ce,{placeholder:"e.g., Thanks for reaching out",value:n,onChange:d=>r(d.target.value),onKeyDown:d=>d.key==="Enter"&&i()}),o.jsx(Z,{size:"icon",variant:"secondary",onClick:i,children:o.jsx(lr,{className:"h-4 w-4"})})]}),o.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:e.common_phrases?.map((d,h)=>o.jsxs("div",{className:"bg-secondary text-secondary-foreground px-2 py-1 rounded-md text-xs flex items-center gap-1",children:[d,o.jsx(on,{className:"h-3 w-3 cursor-pointer hover:text-destructive",onClick:()=>l(d)})]},h))})]}),o.jsxs("div",{className:"mt-6 pt-4 border-t",children:[o.jsx(Ge,{className:"text-muted-foreground mb-2 block",children:"Preview: How your drafts will look"}),o.jsx("div",{className:"bg-muted/30 border rounded-lg p-4 font-mono text-sm whitespace-pre-wrap",children:u()})]})]})}function rq({data:e,updateData:t}){const[n,r]=w.useState(""),[i,l]=w.useState(""),u=()=>{if(n.trim()){const g=e.vip_senders||[];g.includes(n.trim())||t({vip_senders:[...g,n.trim()]}),r("")}},d=g=>{const b=e.vip_senders||[];t({vip_senders:b.filter(v=>v!==g)})},h=()=>{if(i.trim()){let g=i.trim();g.startsWith("@")&&(g=g.substring(1));const b=e.trusted_domains||[];b.includes(g)||t({trusted_domains:[...b,g]}),l("")}},m=g=>{const b=e.trusted_domains||[];t({trusted_domains:b.filter(v=>v!==g)})},p=[{id:"newsletters",label:"Newsletters"},{id:"social_media",label:"Social media"},{id:"marketing",label:"Marketing emails"}];return o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"space-y-2 text-center md:text-left",children:[o.jsx("h2",{className:"text-xl font-semibold tracking-tight",children:"⭐ Who's important to you?"}),o.jsx("p",{className:"text-muted-foreground",children:"We'll prioritize emails from these people and domains."})]}),o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(ip,{className:"h-4 w-4 text-yellow-500"}),o.jsx(Ge,{children:"VIPs (Always High Priority)"})]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Ce,{placeholder:"investor@vc.com",value:n,onChange:g=>r(g.target.value),onKeyDown:g=>g.key==="Enter"&&u()}),o.jsx(Z,{size:"icon",variant:"secondary",onClick:u,children:o.jsx(lr,{className:"h-4 w-4"})})]}),o.jsxs("div",{className:"space-y-2 max-h-[150px] overflow-y-auto",children:[e.vip_senders?.map((g,b)=>o.jsxs("div",{className:"flex items-center justify-between bg-secondary/50 p-2 rounded-md text-sm",children:[o.jsx("span",{children:g}),o.jsx(Z,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>d(g),children:o.jsx(on,{className:"h-3 w-3"})})]},b)),(!e.vip_senders||e.vip_senders.length===0)&&o.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No VIPs added yet"})]})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(eO,{className:"h-4 w-4 text-blue-500"}),o.jsx(Ge,{children:"Team & Trusted Domains"})]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Ce,{placeholder:"company.com",value:i,onChange:g=>l(g.target.value),onKeyDown:g=>g.key==="Enter"&&h()}),o.jsx(Z,{size:"icon",variant:"secondary",onClick:h,children:o.jsx(lr,{className:"h-4 w-4"})})]}),o.jsxs("div",{className:"space-y-2 max-h-[150px] overflow-y-auto",children:[e.trusted_domains?.map((g,b)=>o.jsxs("div",{className:"flex items-center justify-between bg-secondary/50 p-2 rounded-md text-sm",children:[o.jsxs("span",{children:["@",g]}),o.jsx(Z,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>m(g),children:o.jsx(on,{className:"h-3 w-3"})})]},b)),(!e.trusted_domains||e.trusted_domains.length===0)&&o.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No domains added yet"})]})]})]}),o.jsxs("div",{className:"p-4 bg-muted/30 rounded-lg space-y-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(tj,{className:"h-4 w-4 text-muted-foreground"}),o.jsx(Ge,{children:"Low Priority (Auto-Archive)"})]}),o.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:p.map(g=>o.jsxs("div",{className:"flex items-center space-x-2",children:[o.jsx("input",{type:"checkbox",id:g.id,className:"accent-primary h-4 w-4",defaultChecked:!0}),o.jsx("label",{htmlFor:g.id,className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:g.label})]},g.id))})]}),o.jsxs("div",{className:"bg-blue-500/10 text-blue-500 text-sm p-4 rounded-lg flex items-start gap-2",children:[o.jsx(vg,{className:"h-4 w-4 mt-0.5 shrink-0"}),o.jsx("p",{children:'Tip: Adding your own company domain (@realtimex.ai) to "Team" ensures internal emails are never missed.'})]})]})}const aq=[{id:"inbox_zero",label:"Inbox Zero Daily",icon:wA},{id:"respond_faster",label:"Respond Faster",icon:UR},{id:"focus",label:"Focus on Important",icon:cj},{id:"reduce_time",label:"Reduce Email Time",icon:ea}],iq=[{id:"legal",label:"Legal documents"},{id:"hr",label:"HR & payroll"},{id:"financial",label:"Financial transactions"},{id:"security",label:"Security alerts"}];function oq({data:e,updateData:t}){const n=r=>{const i=e.never_automate_categories||[];i.includes(r)?t({never_automate_categories:i.filter(l=>l!==r)}):t({never_automate_categories:[...i,r]})};return o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"space-y-2 text-center md:text-left",children:[o.jsx("h2",{className:"text-xl font-semibold tracking-tight",children:"🎯 What are your email goals?"}),o.jsx("p",{className:"text-muted-foreground",children:"Let's set up automation that works for your specific targets."})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsx(Ge,{children:"Primary Goal"}),o.jsx("div",{className:"grid grid-cols-2 gap-3",children:aq.map(r=>o.jsx($e,{className:me("cursor-pointer transition-all hover:bg-accent/50",e.primary_goal===r.id?"border-primary bg-accent":""),onClick:()=>t({primary_goal:r.id}),children:o.jsxs(vt,{className:"flex flex-col items-center justify-center p-4 text-center space-y-2",children:[o.jsx(r.icon,{className:me("h-6 w-6",e.primary_goal===r.id?"text-primary":"text-muted-foreground")}),o.jsx("span",{className:"font-medium text-sm",children:r.label})]})},r.id))})]}),o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"flex justify-between",children:[o.jsx(Ge,{children:"Time Budget"}),o.jsxs("span",{className:"text-sm text-muted-foreground",children:[e.time_budget_minutes||30," minutes / day"]})]}),o.jsx("input",{type:"range",min:"15",max:"120",step:"15",className:"w-full h-2 bg-secondary rounded-lg appearance-none cursor-pointer accent-primary",value:e.time_budget_minutes||30,onChange:r=>t({time_budget_minutes:parseInt(r.target.value)})}),o.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[o.jsx("span",{children:"15 min"}),o.jsx("span",{children:"1 hour"}),o.jsx("span",{children:"2 hours"})]})]}),o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"flex justify-between",children:[o.jsx(Ge,{children:"Automation Level"}),o.jsx("span",{className:"text-sm text-muted-foreground",children:!e.automation_level||e.automation_level<=3?"Conservative":e.automation_level<=7?"Balanced":"Aggressive"})]}),o.jsxs("div",{className:"relative pt-6",children:[o.jsxs("div",{className:"absolute top-0 w-full flex justify-between text-xs font-medium text-muted-foreground px-1",children:[o.jsx("span",{children:"Manual"}),o.jsx("span",{children:"Fully Automated"})]}),o.jsx("input",{type:"range",min:"1",max:"10",step:"1",className:"w-full h-2 bg-gradient-to-r from-blue-500/20 to-blue-500 rounded-lg appearance-none cursor-pointer accent-primary",value:e.automation_level||5,onChange:r=>t({automation_level:parseInt(r.target.value)})}),o.jsx("p",{className:"text-xs text-muted-foreground mt-2 text-center",children:e.automation_level&&e.automation_level>7?"AI drafts and organizes aggressively. You review key items.":"AI suggests drafts. You maintain full control."})]})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(wR,{className:"h-4 w-4 text-destructive"}),o.jsx(Ge,{children:"Never Automate (Safety)"})]}),o.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:iq.map(r=>o.jsxs("div",{className:"flex items-center space-x-2 border p-3 rounded-md bg-background",children:[o.jsx(gy,{id:`safety-${r.id}`,checked:e.never_automate_categories?.includes(r.id),onCheckedChange:()=>n(r.id)}),o.jsx(Ge,{htmlFor:`safety-${r.id}`,className:"cursor-pointer",children:r.label})]},r.id))})]}),o.jsxs("div",{className:"bg-emerald-500/10 border border-emerald-500/20 text-emerald-600 dark:text-emerald-400 p-4 rounded-lg",children:[o.jsxs("div",{className:"flex items-center gap-2 mb-2 font-medium",children:[o.jsx(gg,{className:"h-4 w-4"}),"Expected Results"]}),o.jsxs("ul",{className:"text-sm space-y-1 list-disc list-inside opacity-90",children:[o.jsx("li",{children:"Save ~2 hours per week"}),o.jsx("li",{children:"Respond 50% faster to clients"}),o.jsx("li",{children:"Zero missed important emails"})]})]})]})}const Bu=4;function R2({onComplete:e,onClose:t,initialData:n,className:r}){const{t:i}=tt(),{state:l}=Tn(),{user:u}=l,[d,h]=w.useState(1),[m,p]=w.useState(!1),[g,b]=w.useState(n||{work_style:"startup",preferred_tone:"professional",preferred_length:"medium",primary_goal:"inbox_zero",vip_senders:[],trusted_domains:[],blocked_domains:[],never_automate_categories:["legal","hr","financial"],automation_level:5,time_budget_minutes:30}),v=()=>{d<Bu?h(T=>T+1):_()},S=()=>{d>1?h(T=>T-1):t&&t()},_=async()=>{if(u){p(!0);try{const{error:T}=await gt.from("user_settings").update({...g,persona_completed:!0,persona_completed_at:new Date().toISOString()}).eq("user_id",u.id);if(T)throw T;le.success("Persona saved successfully!"),e()}catch(T){console.error("Failed to save persona:",T),le.error("Failed to save persona. Please try again.")}finally{p(!1)}}},j=T=>{b(O=>({...O,...T}))},N=()=>{switch(d){case 1:return o.jsx(tq,{data:g,updateData:j});case 2:return o.jsx(sq,{data:g,updateData:j});case 3:return o.jsx(rq,{data:g,updateData:j});case 4:return o.jsx(oq,{data:g,updateData:j});default:return null}},A=d/Bu*100;return o.jsxs($e,{className:me("w-full max-w-2xl mx-auto border-none shadow-none md:border md:shadow-lg",r),children:[o.jsxs(Ot,{children:[o.jsxs("div",{className:"flex items-center justify-between mb-2",children:[o.jsxs("span",{className:"text-sm text-muted-foreground",children:["Step ",d," of ",Bu]}),t&&o.jsx(Z,{variant:"ghost",size:"sm",onClick:t,children:"Skip"})]}),o.jsx(Py,{value:A,className:"h-2"})]}),o.jsx(vt,{className:"py-4 max-h-[60vh] overflow-y-auto",children:N()}),o.jsxs(Jj,{className:"flex justify-between",children:[o.jsx(Z,{variant:"outline",onClick:S,disabled:m,children:d===1&&t?"Cancel":"Back"}),o.jsxs(Z,{onClick:v,disabled:m,children:[m&&o.jsx(wt,{className:"mr-2 h-4 w-4 animate-spin"}),d===Bu?"Complete Setup":"Next"]})]})]})}function lq(){const{t:e}=tt(),{state:t,actions:n}=Tn(),[r,i]=w.useState(!1),l=t.settings||{persona_completed:!1},u=async()=>{i(!1),await n.fetchSettings()};return r?o.jsx(is,{open:!0,onOpenChange:i,children:o.jsxs(os,{className:"max-w-5xl sm:max-w-5xl h-[80vh] flex flex-col p-0 overflow-hidden",children:[o.jsxs("div",{className:"p-6 pb-0",children:[o.jsx(bs,{children:e("persona.edit.title")||"Edit Persona"}),o.jsx(fr,{children:e("persona.edit.desc")||"Update your digital assistant preferences."})]}),o.jsx("div",{className:"flex-1 overflow-y-auto p-6 pt-2",children:o.jsx(R2,{initialData:l,onComplete:u,onClose:()=>i(!1),className:"max-w-none shadow-none border-0 p-0"})})]})}):o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"text-lg font-medium",children:e("persona.title")||"Digital Persona"}),o.jsx("p",{className:"text-sm text-muted-foreground",children:e("persona.subtitle")||"Manage how your AI assistant represents you."})]}),o.jsxs(Z,{onClick:()=>i(!0),className:"gap-2",children:[o.jsx(oj,{className:"w-4 h-4"}),e("common.edit")||"Edit Persona"]})]}),o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[o.jsxs($e,{children:[o.jsx(Ot,{className:"pb-3",children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(wd,{className:"w-5 h-5 text-primary"}),o.jsx(Bt,{className:"text-base",children:e("persona.identity")||"Identity"})]})}),o.jsx(vt,{className:"space-y-4 text-sm",children:o.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-2",children:[o.jsx("span",{className:"text-muted-foreground",children:"Role:"}),o.jsx("span",{className:"font-medium text-right",children:l.role||"Not set"}),o.jsx("span",{className:"text-muted-foreground",children:"Industry:"}),o.jsx("span",{className:"font-medium text-right",children:l.industry||"Not set"}),o.jsx("span",{className:"text-muted-foreground",children:"Style:"}),o.jsx("span",{className:"font-medium capitalize text-right",children:l.work_style||"Not set"})]})})]}),o.jsxs($e,{children:[o.jsx(Ot,{className:"pb-3",children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(vd,{className:"w-5 h-5 text-indigo-500"}),o.jsx(Bt,{className:"text-base",children:e("persona.communication")||"Communication"})]})}),o.jsx(vt,{className:"space-y-4 text-sm",children:o.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-2",children:[o.jsx("span",{className:"text-muted-foreground",children:"Tone:"}),o.jsx("span",{className:"font-medium capitalize text-right",children:l.preferred_tone||"Professional"}),o.jsx("span",{className:"text-muted-foreground",children:"Length:"}),o.jsx("span",{className:"font-medium capitalize text-right",children:l.preferred_length||"Medium"}),o.jsx("span",{className:"text-muted-foreground",children:"Languages:"}),o.jsx("div",{className:"flex justify-end gap-1 flex-wrap",children:(l.common_phrases?.length||0)>0?o.jsx(El,{variant:"secondary",className:"text-xs",children:"Custom Phrases Active"}):o.jsx("span",{className:"text-muted-foreground italic",children:"None"})})]})})]}),o.jsxs($e,{children:[o.jsx(Ot,{className:"pb-3",children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(cj,{className:"w-5 h-5 text-emerald-500"}),o.jsx(Bt,{className:"text-base",children:e("persona.automation")||"Automation"})]})}),o.jsxs(vt,{className:"space-y-4 text-sm",children:[o.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-2",children:[o.jsx("span",{className:"text-muted-foreground",children:"Primary Goal:"}),o.jsx("span",{className:"font-medium capitalize text-right",children:l.primary_goal?.replace("_"," ")||"Inbox Zero"}),o.jsx("span",{className:"text-muted-foreground",children:"Auto Level:"}),o.jsx("div",{className:"flex items-center justify-end gap-2",children:o.jsxs("span",{className:"font-medium",children:[l.automation_level||5,"/10"]})})]}),(l.never_automate_categories?.length||0)>0&&o.jsxs("div",{className:"pt-2",children:[o.jsx("span",{className:"text-xs text-muted-foreground block mb-1",children:"Never Automate:"}),o.jsx("div",{className:"flex flex-wrap gap-1",children:l.never_automate_categories?.map(d=>o.jsx(El,{variant:"outline",className:"text-xs py-0 h-5 bg-background",children:d},d))})]})]})]}),o.jsxs($e,{children:[o.jsx(Ot,{className:"pb-3",children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(rj,{className:"w-5 h-5 text-sky-500"}),o.jsx(Bt,{className:"text-base",children:e("persona.network")||"Network"})]})}),o.jsxs(vt,{className:"space-y-4 text-sm",children:[o.jsxs("div",{children:[o.jsxs("span",{className:"text-xs text-muted-foreground block mb-2",children:["VIP Senders (",l.vip_senders?.length||0,")"]}),o.jsxs("div",{className:"flex flex-wrap gap-1 max-h-[60px] overflow-hidden",children:[l.vip_senders?.slice(0,3).map(d=>o.jsx(El,{variant:"secondary",className:"text-xs py-0 h-5 truncate max-w-[150px]",children:d},d)),(l.vip_senders?.length||0)>3&&o.jsxs("span",{className:"text-xs text-muted-foreground flex items-center",children:["+",l.vip_senders.length-3," more"]})]})]}),o.jsx("div",{className:"pt-2 border-t mt-2",children:o.jsxs("div",{className:"flex justify-between items-center",children:[o.jsx("span",{className:"text-muted-foreground",children:"Trusted Domains:"}),o.jsx("span",{className:"font-medium",children:l.trusted_domains?.length||0})]})})]})]})]})]})}function cq(){const{t:e}=tt(),[t,n]=w.useState("profile"),{state:r,actions:i}=Tn();w.useEffect(()=>{i.fetchProfile()},[]);const l=[{id:"profile",label:e("account.profile"),icon:wd},{id:"persona",label:e("persona.title")||"Persona",icon:WR},{id:"security",label:e("account.security"),icon:wg},{id:"database",label:e("account.database"),icon:Ra}];return o.jsxs("div",{className:"max-w-4xl mx-auto space-y-6 animate-in fade-in duration-500",children:[o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsx("h1",{className:"text-3xl font-bold tracking-tight",children:e("account.title")}),o.jsx("p",{className:"text-muted-foreground",children:e("account.subtitle")})]}),o.jsxs("div",{className:"flex flex-col md:flex-row gap-8",children:[o.jsxs("aside",{className:"w-full md:w-64 flex flex-col justify-between",children:[o.jsx("nav",{className:"space-y-1",children:l.map(u=>{const d=u.icon,h=t===u.id;return o.jsxs("button",{onClick:()=>n(u.id),className:`w-full flex items-center gap-3 px-4 py-2 text-sm font-medium rounded-lg transition-colors ${h?"bg-primary text-primary-foreground":"hover:bg-secondary text-muted-foreground"}`,children:[o.jsx(d,{className:"w-4 h-4"}),u.label]},u.id)})}),o.jsxs("div",{className:"mt-auto space-y-1",children:[o.jsxs("button",{onClick:async()=>{await gt.auth.signOut(),J5(),le.success(e("account.logoutSuccess")),window.location.reload()},className:"w-full flex items-center gap-3 px-4 py-2 text-sm font-medium rounded-lg transition-colors hover:bg-destructive/10 text-destructive",children:[o.jsx(BA,{className:"w-4 h-4"}),e("account.logout")]}),o.jsxs("div",{className:"px-4 py-4 border-t border-border/40 text-center md:text-left",children:[o.jsx("p",{className:"text-[10px] font-bold text-muted-foreground/50 uppercase tracking-widest mb-1",children:e("account.version")}),o.jsxs("p",{className:"text-xs font-mono text-muted-foreground/70",children:["v","2.23.3"]})]})]})]}),o.jsxs("div",{className:"flex-1 space-y-6",children:[t==="profile"&&o.jsx(uq,{}),t==="persona"&&o.jsx(lq,{}),t==="security"&&o.jsx(dq,{}),t==="database"&&o.jsx(fq,{})]})]})]})}function uq(){const{t:e}=tt(),{state:t,actions:n}=Tn(),[r,i]=w.useState(""),[l,u]=w.useState(""),[d,h]=w.useState(!1),[m,p]=w.useState(!1),[g,b]=w.useState(Ms.isEnabled());w.useEffect(()=>{t.profile&&(i(t.profile.first_name||""),u(t.profile.last_name||""))},[t.profile]);const v=()=>{const j=!g;Ms.setEnabled(j),b(j),j?(Ms.playSuccess(),le.success(e("account.profile.soundsEnabled"))):le.info(e("account.profile.soundsDisabled"))},S=async()=>{h(!0);const j=await n.updateProfile({first_name:r,last_name:l});h(!1),j&&le.success(e("account.profile.updated"))},_=async j=>{const N=j.target.files?.[0];if(!(!N||!t.user)){p(!0);try{const A=N.name.split(".").pop(),T=`${t.user.id}/avatar.${A}`,{data:O,error:L}=await gt.storage.from("avatars").upload(T,N,{upsert:!0});if(L)throw L;const{data:{publicUrl:M}}=gt.storage.from("avatars").getPublicUrl(T);await n.updateProfile({avatar_url:M}),le.success(e("account.profile.avatarUpdated"))}catch(A){console.error("Avatar upload error:",A),le.error(e("account.profile.avatarError"))}finally{p(!1)}}};return o.jsxs($e,{children:[o.jsxs(Ot,{children:[o.jsx(Bt,{children:e("account.profile.title")}),o.jsx(xs,{children:e("account.profile.desc")})]}),o.jsxs(vt,{className:"space-y-6",children:[o.jsxs("div",{className:"flex flex-col items-center sm:flex-row sm:items-start gap-6",children:[o.jsxs("div",{className:"relative group",children:[o.jsx("div",{className:"w-24 h-24 rounded-full bg-secondary overflow-hidden border-2 border-border flex items-center justify-center",children:t.profile?.avatar_url?o.jsx("img",{src:t.profile.avatar_url,alt:"Avatar",className:"w-full h-full object-cover"}):o.jsx(wd,{className:"w-12 h-12 text-muted-foreground"})}),o.jsxs("label",{className:"absolute inset-0 flex items-center justify-center bg-black/40 rounded-full opacity-0 group-hover:opacity-100 cursor-pointer transition-opacity",children:[o.jsx(CC,{className:"w-6 h-6 text-white"}),o.jsx("input",{type:"file",className:"hidden",accept:"image/*",onChange:_,disabled:m})]}),m&&o.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/60 rounded-full",children:o.jsx(pt,{size:"sm"})})]}),o.jsxs("div",{className:"flex-1 space-y-4 w-full",children:[o.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Ge,{htmlFor:"first-name",children:e("account.profile.firstName")}),o.jsx(Ce,{id:"first-name",value:r,onChange:j=>i(j.target.value),placeholder:e("account.profile.firstNamePlaceholder")})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Ge,{htmlFor:"last-name",children:e("account.profile.lastName")}),o.jsx(Ce,{id:"last-name",value:l,onChange:j=>u(j.target.value),placeholder:e("account.profile.lastNamePlaceholder")})]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Ge,{htmlFor:"email",children:e("account.profile.email")}),o.jsx(Ce,{id:"email",value:t.profile?.email||"",disabled:!0,className:"bg-secondary/50"}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:e("account.profile.emailHelp")})]})]})]}),o.jsxs("div",{className:"pt-6 border-t flex items-center justify-between",children:[o.jsxs("div",{className:"space-y-0.5",children:[o.jsx("label",{className:"text-sm font-medium",children:e("account.profile.sounds")}),o.jsx("p",{className:"text-xs text-muted-foreground",children:e("account.profile.soundsHelp")})]}),o.jsxs(Z,{variant:g?"default":"outline",size:"sm",onClick:v,className:"gap-2",children:[g?o.jsx(Ol,{className:"w-4 h-4"}):o.jsx(Sg,{className:"w-4 h-4"}),e(g?"common.enabled":"common.disabled")]})]}),o.jsx("div",{className:"flex justify-end pt-4 border-t",children:o.jsxs(Z,{onClick:S,disabled:d,children:[d?o.jsx(pt,{size:"sm",className:"mr-2"}):o.jsx(dR,{className:"w-4 h-4 mr-2"}),e("common.saveChanges")]})})]})]})}function dq(){const{t:e}=tt(),[t,n]=w.useState(""),[r,i]=w.useState(""),[l,u]=w.useState(!1),d=async()=>{if(!t){le.error(e("account.security.enterPassword"));return}if(t!==r){le.error(e("account.security.passwordsMismatch"));return}if(t.length<6){le.error(e("account.security.passwordTooShort"));return}u(!0);try{const{api:h}=await Ea(async()=>{const{api:p}=await Promise.resolve().then(()=>F5);return{api:p}},void 0),m=await h.changePassword(t);m.success?(le.success(e("account.security.passwordChanged")),n(""),i("")):le.error(m.error?.message||"Failed to change password")}catch{le.error(e("common.errorOccurred"))}finally{u(!1)}};return o.jsxs($e,{children:[o.jsxs(Ot,{children:[o.jsx(Bt,{children:e("account.security.title")}),o.jsx(xs,{children:e("account.security.desc")})]}),o.jsxs(vt,{className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Ge,{htmlFor:"new-password",children:e("account.security.newPassword")}),o.jsx(Ce,{id:"new-password",type:"password",value:t,onChange:h=>n(h.target.value),placeholder:"••••••••"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Ge,{htmlFor:"confirm-password",children:e("account.security.confirmPassword")}),o.jsx(Ce,{id:"confirm-password",type:"password",value:r,onChange:h=>i(h.target.value),placeholder:"••••••••"})]}),o.jsx("div",{className:"flex justify-end pt-4 border-t",children:o.jsxs(Z,{onClick:d,disabled:l,children:[l?o.jsx(pt,{size:"sm",className:"mr-2"}):o.jsx(xg,{className:"w-4 h-4 mr-2"}),e("account.security.updatePassword")]})})]})]})}function fq(){const{t:e}=tt(),[t,n]=w.useState(!1),[r,i]=w.useState(null),l=fo(),u=U5();w.useEffect(()=>{l&&dy(gt).then(i)},[]);const d=()=>{confirm(e("account.database.clearConfirm"))&&(L5(),window.location.reload())};return o.jsxs(o.Fragment,{children:[o.jsxs($e,{children:[o.jsxs(Ot,{children:[o.jsxs(Bt,{className:"flex items-center gap-2",children:[o.jsx(Ra,{className:"w-5 h-5 text-primary"}),e("account.database.title")]}),o.jsx(xs,{children:e("account.database.desc")})]}),o.jsx(vt,{className:"space-y-6",children:l?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex items-start gap-4 p-4 border rounded-xl bg-emerald-500/5 border-emerald-500/20",children:[o.jsx(Ju,{className:"w-6 h-6 text-emerald-500 mt-0.5"}),o.jsxs("div",{className:"flex-1 space-y-1",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("p",{className:"font-semibold text-emerald-700 dark:text-emerald-400",children:e("account.database.connected")}),r?.latestMigrationTimestamp&&o.jsxs("span",{className:"text-[10px] font-mono bg-emerald-500/10 text-emerald-600 px-1.5 py-0.5 rounded border border-emerald-500/20",title:"Database Schema Version",children:["Schema ",r.latestMigrationTimestamp]})]}),o.jsx("p",{className:"text-sm font-mono break-all opacity-80",children:l.url})]})]}),u==="env"&&o.jsxs(La,{className:"bg-amber-500/5 border-amber-500/20",children:[o.jsx(Al,{className:"h-4 w-4 text-amber-500"}),o.jsx(Ia,{className:"text-amber-700 dark:text-amber-400 text-xs",children:e("account.database.envAlert")})]}),o.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[o.jsxs(Z,{variant:"outline",onClick:()=>n(!0),className:"w-full",children:[o.jsx(Al,{className:"w-4 h-4 mr-2"}),e("account.database.changeConnection")]}),u==="ui"&&o.jsxs(Z,{variant:"outline",onClick:d,className:"w-full text-destructive hover:bg-destructive/10",children:[o.jsx(bd,{className:"w-4 h-4 mr-2"}),e("account.database.clearConfig")]})]}),o.jsxs("div",{className:"space-y-2 pt-4 border-t",children:[o.jsx(Ge,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:e("account.database.anonKey")}),o.jsxs("div",{className:"p-2 bg-secondary/50 rounded-lg font-mono text-xs break-all",children:[l.anonKey.substring(0,20),"...",l.anonKey.substring(l.anonKey.length-10)]})]})]}):o.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center space-y-4",children:[o.jsx($C,{className:"w-12 h-12 text-destructive opacity-20"}),o.jsxs("div",{children:[o.jsx("p",{className:"font-medium",children:e("account.database.noConnection")}),o.jsx("p",{className:"text-sm text-muted-foreground",children:e("account.database.configureHelp")})]}),o.jsxs(Z,{onClick:()=>n(!0),children:[o.jsx(Ra,{className:"w-4 h-4 mr-2"}),e("account.database.setup")]})]})})]}),o.jsx(K_,{open:t,onComplete:()=>n(!1),canClose:!0})]})}function hq(){const{t:e}=tt();return o.jsx("span",{className:"inline-flex items-center text-xs px-2 py-0.5 rounded-full bg-blue-50 dark:bg-blue-950/70 text-blue-700 dark:text-blue-200 border border-blue-200 dark:border-blue-700 shrink-0 font-medium",children:e("autopilot.badge")})}function XS({rules:e,onToggleRule:t,onEditRule:n,onDeleteRule:r}){const{t:i}=tt(),l={email_organization:{label:i("autopilot.category.email_organization.label"),icon:as,emoji:"📧",description:i("autopilot.category.email_organization.desc")},priority_alerts:{label:i("autopilot.category.priority_alerts.label"),icon:ls,emoji:"🚨",description:i("autopilot.category.priority_alerts.desc")},development:{label:i("autopilot.category.development.label"),icon:Ds,emoji:"💻",description:i("autopilot.category.development.desc")},sales_business:{label:i("autopilot.category.sales_business.label"),icon:nj,emoji:"💼",description:i("autopilot.category.sales_business.desc")},operations:{label:i("autopilot.category.operations.label"),icon:Al,emoji:"⚙️",description:i("autopilot.category.operations.desc")}},u=e.reduce((m,p)=>{const g=p.category||"email_organization";return m[g]||(m[g]=[]),m[g].push(p),m},{}),d=m=>{const p=m.filter(b=>b.is_enabled).length,g=m.length;return{enabled:p,total:g}},h=m=>!m||m.length===0?"":m.map(p=>p.startsWith("label:")?`label:${p.substring(6)}`:p).join(" + ");return o.jsx("div",{className:"space-y-8",children:Object.entries(l).map(([m,p])=>{const g=u[m]||[];if(g.length===0)return null;const b=d(g);return o.jsxs("div",{className:"space-y-3",children:[o.jsx("div",{className:"flex items-center justify-between",children:o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"w-10 h-10 rounded-lg bg-secondary/50 flex items-center justify-center text-primary",children:o.jsx(p.icon,{className:"w-5 h-5"})}),o.jsxs("div",{children:[o.jsxs("h3",{className:"font-semibold text-base flex items-center gap-2",children:[p.label,o.jsx("span",{className:"text-xs font-normal text-muted-foreground",children:i("autopilot.enabledCount").replace("{enabled}",b.enabled.toString()).replace("{total}",b.total.toString())})]}),o.jsx("p",{className:"text-xs text-muted-foreground",children:p.description})]})]})}),o.jsx("div",{className:"space-y-1",children:g.map(v=>o.jsxs("div",{className:"flex items-center justify-between py-3 px-4 rounded-lg hover:bg-secondary/30 transition-colors",children:[o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("h4",{className:"font-medium text-sm truncate",children:v.name}),v.is_system_managed&&o.jsx(hq,{})]}),o.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[v.intent&&o.jsx("p",{className:"text-xs text-muted-foreground truncate",children:v.intent}),v.actions&&v.actions.length>0&&o.jsxs("span",{className:"text-xs text-muted-foreground shrink-0",children:["→ ",h(v.actions)]})]})]}),o.jsxs("div",{className:"flex items-center gap-2 ml-4 shrink-0",children:[o.jsx(Z,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>n(v.id),title:i("autopilot.editRuleTooltip"),children:o.jsx(oj,{className:"w-4 h-4 text-muted-foreground"})}),o.jsxs(Z,{variant:v.is_enabled?"default":"outline",size:"sm",onClick:()=>t(v.id,!v.is_enabled),className:"h-8 px-3",children:[o.jsx(ap,{className:"w-4 h-4 mr-1"}),v.is_enabled?i("common.on"):i("common.off")]}),!v.is_system_managed&&r&&o.jsx(Z,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-destructive hover:text-destructive",onClick:()=>r(v.id),title:i("autopilot.deleteRuleTooltip"),children:o.jsx(bd,{className:"w-4 h-4"})})]})]},v.id))})]},m)})})}function mq({open:e,rule:t,onClose:n,onSave:r,onFileUpload:i,onRemoveAttachment:l}){const{t:u}=tt(),[d,h]=w.useState(!1),[m,p]=w.useState(!1),[g,b]=w.useState(""),[v,S]=w.useState(""),[_,j]=w.useState(""),[N,A]=w.useState("category"),[T,O]=w.useState("newsletter"),[L,M]=w.useState(""),[B,P]=w.useState(["archive"]),[q,D]=w.useState(""),[Q,G]=w.useState([]);w.useEffect(()=>{if(t){b(t.name||""),S(t.description||""),j(t.intent||""),P(t.actions||["archive"]),D(t.instructions||""),G(t.attachments||[]);const I=t.condition||{},V=Object.keys(I).filter($=>$!=="older_than_days");V.length>0&&(A(V[0]),O(I[V[0]])),I.older_than_days&&M(String(I.older_than_days))}else b(""),S(""),j(""),A("category"),O("newsletter"),M(""),P(["archive"]),D(""),G([])},[t,e]);const fe=async()=>{if(g.trim()&&B.length!==0){h(!0);try{const I={[N]:T};L&&(I.older_than_days=parseInt(L,10));const V=B.includes("draft"),$={name:g.trim(),description:v.trim()||void 0,intent:_.trim()||void 0,condition:I,actions:B,instructions:V?q:void 0,attachments:V?Q:[],is_enabled:!0};await r($)&&n()}finally{h(!1)}}},se=async I=>{if(!i)return;const V=I.target.files;if(!(!V||V.length===0)){p(!0);try{const $=await i(V[0]);$&&G(de=>[...de,$])}finally{p(!1),I.target.value=""}}},ae=I=>{G(V=>V.filter($=>$.path!==I)),l&&l(I)};return o.jsx(is,{open:e,onOpenChange:I=>!I&&n(),children:o.jsxs(os,{className:"sm:max-w-xl max-h-[90vh] flex flex-col p-0",children:[o.jsxs(dr,{className:"p-6 border-b",children:[o.jsx(bs,{children:u(t?"autopilot.editDialog.editTitle":"autopilot.editDialog.createTitle")}),o.jsx(fr,{children:u("autopilot.editDialog.desc")})]}),o.jsxs("div",{className:"flex-1 overflow-y-auto p-6 space-y-6 custom-scrollbar",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:u("autopilot.editDialog.ruleName")}),o.jsx(Ce,{placeholder:u("autopilot.editDialog.namePlaceholder"),value:g,onChange:I=>b(I.target.value)})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:u("autopilot.editDialog.description")}),o.jsx("textarea",{className:"w-full p-2 border rounded-md bg-background min-h-[60px] text-sm",placeholder:u("autopilot.editDialog.descPlaceholder"),value:v,onChange:I=>S(I.target.value)}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:u("autopilot.editDialog.descriptionHelp")})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:u("autopilot.editDialog.intent")}),o.jsx(Ce,{placeholder:u("autopilot.editDialog.intentPlaceholder"),value:_,onChange:I=>j(I.target.value)}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:u("autopilot.editDialog.intentHelp")})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:u("autopilot.editDialog.conditionField")}),o.jsxs("select",{className:"w-full p-2 border rounded-md bg-background text-sm",value:N,onChange:I=>{A(I.target.value),I.target.value==="category"?O("newsletter"):I.target.value==="sentiment"?O("Positive"):I.target.value==="priority"?O("High"):O("")},children:[o.jsxs("optgroup",{label:u("autopilot.editDialog.aiAnalysisGroup"),children:[o.jsx("option",{value:"category",children:u("autopilot.editDialog.category")}),o.jsx("option",{value:"sentiment",children:u("autopilot.editDialog.sentiment")}),o.jsx("option",{value:"priority",children:u("autopilot.editDialog.priority")})]}),o.jsxs("optgroup",{label:u("autopilot.editDialog.metadataGroup"),children:[o.jsx("option",{value:"sender_email",children:u("autopilot.editDialog.senderEmail")}),o.jsx("option",{value:"sender_domain",children:u("autopilot.editDialog.senderDomain")}),o.jsx("option",{value:"sender_contains",children:u("autopilot.editDialog.senderContains")}),o.jsx("option",{value:"subject_contains",children:u("autopilot.editDialog.subjectContains")}),o.jsx("option",{value:"body_contains",children:u("autopilot.editDialog.bodyContains")})]})]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:u("autopilot.editDialog.equalsValue")}),N==="category"?o.jsxs("select",{className:"w-full p-2 border rounded-md bg-background text-sm",value:T,onChange:I=>O(I.target.value),children:[o.jsx("option",{value:"newsletter",children:u("autopilot.editDialog.cat.newsletter")}),o.jsx("option",{value:"news",children:u("autopilot.editDialog.cat.news")}),o.jsx("option",{value:"spam",children:u("autopilot.editDialog.cat.spam")}),o.jsx("option",{value:"promotional",children:u("autopilot.editDialog.cat.promotional")}),o.jsx("option",{value:"transactional",children:u("autopilot.editDialog.cat.transactional")}),o.jsx("option",{value:"social",children:u("autopilot.editDialog.cat.social")}),o.jsx("option",{value:"support",children:u("autopilot.editDialog.cat.support")}),o.jsx("option",{value:"client",children:u("autopilot.editDialog.cat.client")}),o.jsx("option",{value:"internal",children:u("autopilot.editDialog.cat.internal")}),o.jsx("option",{value:"personal",children:u("autopilot.editDialog.cat.personal")}),o.jsx("option",{value:"other",children:u("autopilot.editDialog.cat.other")})]}):N==="sentiment"?o.jsxs("select",{className:"w-full p-2 border rounded-md bg-background text-sm",value:T,onChange:I=>O(I.target.value),children:[o.jsx("option",{value:"Positive",children:u("autopilot.editDialog.sent.positive")}),o.jsx("option",{value:"Neutral",children:u("autopilot.editDialog.sent.neutral")}),o.jsx("option",{value:"Negative",children:u("autopilot.editDialog.sent.negative")})]}):N==="priority"?o.jsxs("select",{className:"w-full p-2 border rounded-md bg-background text-sm",value:T,onChange:I=>O(I.target.value),children:[o.jsx("option",{value:"High",children:u("autopilot.editDialog.prio.high")}),o.jsx("option",{value:"Medium",children:u("autopilot.editDialog.prio.medium")}),o.jsx("option",{value:"Low",children:u("autopilot.editDialog.prio.low")})]}):o.jsx(Ce,{placeholder:N==="sender_domain"?"rta.vn":N==="sender_email"?"john@example.com":u("autopilot.editDialog.keywordsPlaceholder"),value:T,onChange:I=>O(I.target.value)})]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsxs("label",{className:"text-sm font-medium flex items-center gap-2",children:[o.jsx(ea,{className:"w-4 h-4"}),u("autopilot.editDialog.olderThan")]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Ce,{type:"number",min:"0",placeholder:"0",className:"w-24",value:L,onChange:I=>M(I.target.value)}),o.jsx("span",{className:"text-sm text-muted-foreground",children:u("autopilot.editDialog.days")})]}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:u("autopilot.editDialog.olderThanHelp")})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-sm font-medium",children:u("autopilot.editDialog.performActions")}),o.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:u("autopilot.editDialog.actionsDesc")}),o.jsx("div",{className:"grid grid-cols-2 gap-2",children:[{value:"archive",label:u("autopilot.editDialog.action.archive")},{value:"delete",label:u("autopilot.editDialog.action.delete")},{value:"draft",label:u("autopilot.editDialog.action.draft")},{value:"star",label:u("autopilot.editDialog.action.star")}].map(I=>o.jsxs("label",{className:`flex items-center gap-2 p-2 border rounded-md cursor-pointer transition-colors ${B.includes(I.value)?"bg-primary/10 border-primary":"bg-background hover:bg-secondary/50"}`,children:[o.jsx("input",{type:"checkbox",checked:B.includes(I.value),onChange:V=>{V.target.checked?P([...B,I.value]):P(B.filter($=>$!==I.value))},className:"rounded border-gray-300"}),o.jsx("span",{className:"text-sm",children:I.label})]},I.value))})]}),B.includes("draft")&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"space-y-2 animate-in slide-in-from-top-2 duration-200",children:[o.jsx("label",{className:"text-sm font-medium",children:u("autopilot.editDialog.draftInstructions")}),o.jsx("textarea",{className:"w-full p-2 border rounded-md bg-background min-h-[80px] text-sm",placeholder:u("autopilot.editDialog.draftInstPlaceholder"),value:q,onChange:I=>D(I.target.value)}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:u("autopilot.editDialog.draftInstHelp")})]}),i&&o.jsxs("div",{className:"space-y-2 animate-in slide-in-from-top-2 duration-200",children:[o.jsxs("label",{className:"text-sm font-medium flex items-center gap-2",children:[o.jsx(rp,{className:"w-4 h-4"}),u("autopilot.editDialog.attachments")]}),o.jsxs("div",{className:"flex flex-col gap-2",children:[Q.map(I=>o.jsxs("div",{className:"flex items-center justify-between p-2 bg-secondary/50 rounded border text-xs",children:[o.jsx("span",{className:"truncate max-w-[200px]",children:I.name}),o.jsx(Z,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-destructive",onClick:()=>ae(I.path),children:o.jsx(on,{className:"w-3 h-3"})})]},I.path)),o.jsxs("div",{className:"relative",children:[o.jsx("input",{type:"file",className:"absolute inset-0 opacity-0 cursor-pointer",onChange:se,disabled:m}),o.jsxs(Z,{variant:"outline",size:"sm",className:"w-full border-dashed",disabled:m,children:[m?o.jsx(pt,{size:"sm",className:"mr-2"}):o.jsx(lr,{className:"w-3 h-3 mr-2"}),u(m?"autopilot.editDialog.uploading":"autopilot.editDialog.addAttachment")]})]})]}),o.jsx("p",{className:"text-[10px] text-muted-foreground",children:u("autopilot.editDialog.attachmentsHelp")})]})]})]}),o.jsxs(or,{className:"p-6 border-t bg-secondary/5",children:[o.jsx(Z,{variant:"outline",onClick:n,children:u("common.cancel")}),o.jsxs(Z,{onClick:fe,disabled:d||!g.trim()||B.length===0,children:[d?o.jsx(pt,{size:"sm",className:"mr-2"}):t?o.jsx(ar,{className:"w-4 h-4 mr-2"}):o.jsx(lr,{className:"w-4 h-4 mr-2"}),u(t?"common.saveChanges":"autopilot.addCustomRule")]})]})]})})}function pq(){const{state:e,actions:t}=Tn(),{t:n}=tt(),[r,i]=w.useState([]),[l,u]=w.useState(!0),[d,h]=w.useState(null),[m,p]=w.useState(!1),[g,b]=w.useState(null),v=async()=>{u(!0),h(null);try{const P=await Oe.getRules();if(P.error)throw new Error(typeof P.error=="string"?P.error:P.error.message);i(P.data?.rules||[])}catch(P){h(P instanceof Error?P.message:n("autopilot.loadError")),console.error("Error fetching rules:",P)}finally{u(!1)}};w.useEffect(()=>{v()},[]);const S=async(P,q)=>{try{const D=await Oe.updateRule(P,{is_enabled:q});if(D.error)throw new Error(typeof D.error=="string"?D.error:D.error.message);i(Q=>Q.map(G=>G.id===P?{...G,is_enabled:q}:G))}catch(D){console.error("Error toggling rule:",D),await v()}},_=P=>{const q=r.find(D=>D.id===P);q&&(b(q),p(!0))},j=async P=>{if(confirm(n("autopilot.deleteConfirm")))try{await t.deleteRule(P)?(le.success(n("autopilot.ruleDeleted")),i(D=>D.filter(Q=>Q.id!==P))):le.error(n("autopilot.ruleDeleteFailed"))}catch(q){console.error("Error deleting rule:",q),le.error(n("autopilot.ruleDeleteError"))}},N=()=>{b(null),p(!0)},A=async P=>{try{let q=!1;return g?q=await t.updateRule(g.id,P):q=await t.createRule(P),q?(le.success(n(g?"autopilot.ruleUpdated":"autopilot.ruleCreated")),await v(),!0):(le.error(n(g?"autopilot.ruleUpdateFailed":"autopilot.ruleCreateFailed")),!1)}catch(q){return console.error("Error saving rule:",q),le.error(n("autopilot.ruleSaveError")),!1}},T=async P=>{try{const q=P.name.split(".").pop(),D=`${Math.random().toString(36).substring(2)}.${q}`,Q=`${e.user.id}/${D}`,{error:G}=await gt.storage.from("rule-attachments").upload(Q,P);if(G)throw G;return le.success(n("autopilot.fileUploaded")),{name:P.name,path:Q,type:P.type,size:P.size}}catch(q){return console.error("Upload error:",q),le.error(n("autopilot.fileUploadFailed")),null}},O=()=>{p(!1),b(null)};if(l)return o.jsx("div",{className:"flex items-center justify-center min-h-[400px]",children:o.jsxs("div",{className:"flex flex-col items-center gap-4",children:[o.jsx(Wt,{className:"w-8 h-8 animate-spin text-gray-400"}),o.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:n("autopilot.loadingRules")})]})});if(d)return o.jsxs(La,{variant:"destructive",children:[o.jsx(ls,{className:"h-4 w-4"}),o.jsxs(Ia,{children:[d,o.jsxs(Z,{variant:"outline",size:"sm",onClick:v,className:"ml-4",children:[o.jsx(Wt,{className:"w-4 h-4 mr-2"}),n("autopilot.refresh")]})]})]});const L=r.filter(P=>P.is_system_managed),M=r.filter(P=>!P.is_system_managed),B=L.filter(P=>P.is_enabled).length;return r.length===0?o.jsxs("div",{className:"flex flex-col items-center justify-center min-h-[400px] p-8",children:[o.jsx(qu,{className:"w-16 h-16 text-gray-300 dark:text-gray-700 mb-4"}),o.jsx("h3",{className:"text-lg font-semibold mb-2",children:n("autopilot.noRulesTitle")}),o.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 text-center max-w-md mb-4",children:n("autopilot.noRulesDesc")})]}):o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"space-y-8",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{children:[o.jsxs("h2",{className:"text-2xl font-bold flex items-center gap-2",children:[o.jsx(qu,{className:"w-6 h-6 text-blue-500"}),n("autopilot.title")]}),o.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:n("autopilot.rulesEnabled").replace("{enabled}",B.toString()).replace("{total}",L.length.toString())})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs(Z,{variant:"default",size:"sm",onClick:N,children:[o.jsx(lr,{className:"w-4 h-4 mr-2"}),n("autopilot.addCustomRule")]}),o.jsxs(Z,{variant:"outline",size:"sm",onClick:v,disabled:l,children:[o.jsx(Wt,{className:`w-4 h-4 mr-2 ${l?"animate-spin":""}`}),n("autopilot.refresh")]})]})]}),L.length>0&&o.jsxs(La,{children:[o.jsx(qu,{className:"h-4 w-4"}),o.jsx(Ia,{children:n("autopilot.infoDesc")})]}),L.length>0&&o.jsx(XS,{rules:L,onToggleRule:S,onEditRule:_,onDeleteRule:j}),M.length>0&&o.jsxs("div",{className:"space-y-4 pt-4 border-t",children:[o.jsxs("div",{children:[o.jsx("h3",{className:"text-lg font-semibold",children:n("autopilot.customRules")}),o.jsx("p",{className:"text-sm text-muted-foreground",children:n("autopilot.customRulesDesc")})]}),o.jsx(XS,{rules:M,onToggleRule:S,onEditRule:_,onDeleteRule:j})]})]}),o.jsx(mq,{open:m,rule:g,onClose:O,onSave:A,onFileUpload:T})]})}function gq({length:e=6,value:t,onChange:n,onComplete:r,disabled:i=!1,error:l=!1}){const u=w.useRef([]),[d,h]=w.useState(null),m=(b,v)=>{const S=v.replace(/[^0-9]/g,"");if(S.length===0){const N=t.split("");N[b]=" ",t.split("");let A=t.split("");b<A.length&&A.splice(b,1);const T=A.join("");n(T),b>0&&u.current[b-1]?.focus();return}t.split("");const _=[...t];_[b]=S[0],n(_.join("")),b<e-1&&u.current[b+1]?.focus();const j=_.join("");j.length===e&&r&&r(j)},p=(b,v)=>{v.key==="Backspace"&&!t[b]&&b>0||v.key==="ArrowLeft"&&b>0?u.current[b-1]?.focus():v.key==="ArrowRight"&&b<e-1&&u.current[b+1]?.focus()},g=b=>{b.preventDefault();const S=b.clipboardData.getData("text/plain").replace(/[^0-9]/g,"").slice(0,e);n(S);const _=Math.min(S.length,e-1);u.current[_]?.focus(),S.length===e&&r&&r(S)};return o.jsx("div",{className:"flex gap-2 justify-center",children:Array.from({length:e}).map((b,v)=>o.jsx(Ce,{ref:S=>{u.current[v]=S},type:"text",inputMode:"numeric",maxLength:1,value:t[v]||"",onChange:S=>m(v,S.target.value),onKeyDown:S=>p(v,S),onPaste:g,onFocus:()=>h(v),onBlur:()=>h(null),disabled:i,className:me("w-10 h-10 sm:w-12 sm:h-12 text-center text-lg font-semibold px-0",l&&"border-destructive focus-visible:ring-destructive",d===v&&"ring-2 ring-ring"),"aria-label":`Digit ${v+1}`},v))})}function yq({onSuccess:e,onConfigure:t,isInitialized:n}){const{t:r}=tt(),[i,l]=w.useState(""),[u,d]=w.useState(""),[h,m]=w.useState(""),[p,g]=w.useState(""),[b,v]=w.useState(!1),[S,_]=w.useState(n===void 0),[j,N]=w.useState(n??!1),[A,T]=w.useState(""),[O,L]=w.useState(!1),[M,B]=w.useState("password"),[P,q]=w.useState("email"),[D,Q]=w.useState(""),[G,fe]=w.useState(!1);w.useEffect(()=>{n===void 0?se():fe(!n)},[n]);const se=async()=>{try{const{data:V,error:$}=await gt.from("init_state").select("is_initialized");if($){if($.code==="42P01"){console.info("[Login] init_state relation missing - fresh database detected."),N(!1),fe(!0);return}console.warn("[Login] Init check error:",$),N(!1),fe(!0),T($.message);return}const de=V&&V.length>0&&V[0].is_initialized>0;N(de),fe(!de)}catch(V){console.warn("[Login] Init check exception:",V),N(!1),fe(!0),T(V.message||"Connection failed")}finally{_(!1)}},ae=async V=>{V.preventDefault(),v(!0),T("");try{if(j){if(M==="password"){const{error:$}=await gt.auth.signInWithPassword({email:i,password:u});if($)throw $;le.success("Logged in successfully"),e?.()}else if(P==="email"){const{error:$}=await gt.auth.signInWithOtp({email:i,options:{shouldCreateUser:!1}});if($)throw $;q("verify"),le.success("Validation code sent to your email")}}else{const{data:$,error:de}=await gt.functions.invoke("setup",{body:{email:i,password:u,first_name:h,last_name:p}});if(de||!$){if(de?.message?.includes("First user already exists")){le.info("System already initialized. Please log in."),N(!0);return}throw new Error(de?.message||"Failed to create admin account")}le.success("Admin account created! Signing you in...");const{error:C}=await gt.auth.signInWithPassword({email:i,password:u});if(C)throw C;N(!0),e?.()}}catch($){T($?.message||"Authentication failed"),console.error("[Login] Error:",$)}finally{v(!1)}},I=async()=>{v(!0),T("");try{const{data:V,error:$}=await gt.auth.verifyOtp({email:i,token:D,type:"magiclink"});if($)throw $;if(!V.session)throw new Error("Failed to create session");le.success("Logged in successfully"),e?.()}catch(V){T(V?.message||"Invalid code")}finally{v(!1)}};return S?o.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center",children:o.jsxs("div",{className:"flex flex-col items-center gap-4",children:[o.jsx(wt,{className:"w-10 h-10 animate-spin text-primary"}),o.jsx("p",{className:"text-xs font-mono uppercase tracking-widest text-muted-foreground",children:"Initializing Engine..."})]})}):o.jsxs("div",{className:"min-h-screen bg-background flex items-center justify-center p-8 relative overflow-hidden",children:[o.jsxs("div",{className:"absolute top-6 right-6 flex items-center gap-4 z-50",children:[t&&o.jsxs(Z,{variant:"ghost",size:"sm",onClick:t,className:"text-xs font-bold uppercase tracking-widest text-muted-foreground hover:text-primary transition-all",children:[o.jsx(Al,{className:"w-3.5 h-3.5 mr-2"}),"Configure"]}),o.jsx(Tj,{}),o.jsx(ly,{})]}),o.jsxs(ir.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"w-full max-w-md relative z-10",children:[o.jsxs("div",{className:"glass p-10 space-y-8 relative overflow-hidden",children:[o.jsxs("div",{className:"text-center space-y-3",children:[o.jsx("div",{className:"mx-auto w-16 h-16 bg-primary rounded-2xl flex items-center justify-center mb-6",children:o.jsx(fy,{className:"w-10 h-10 text-primary-foreground"})}),o.jsx("h2",{className:"text-3xl font-black italic tracking-tighter uppercase text-foreground",children:r(G?"login.initialize":"login.secureLogin")}),o.jsx("p",{className:"text-[10px] text-muted-foreground font-bold tracking-[0.2em] uppercase",children:G?"Create your primary administrator account":M==="otp"?"Magic link authentication":"Personal Access Key Required"})]}),o.jsxs("form",{onSubmit:ae,className:"space-y-4",children:[o.jsxs(S_,{mode:"wait",children:[G&&o.jsxs(ir.div,{initial:{opacity:0,height:0},animate:{opacity:1,height:"auto"},exit:{opacity:0,height:0},className:"grid grid-cols-2 gap-4",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"text-[10px] font-bold uppercase text-muted-foreground ml-1",children:"First Name"}),o.jsx(Ce,{value:h,onChange:V=>m(V.target.value),required:G,placeholder:r("login.firstNamePlaceholder"),className:"bg-background"})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"text-[10px] font-bold uppercase text-muted-foreground ml-1",children:"Last Name"}),o.jsx(Ce,{value:p,onChange:V=>g(V.target.value),required:G,placeholder:r("login.lastNamePlaceholder"),className:"bg-background"})]})]},"signup-fields"),M==="password"||P==="email"?o.jsxs(ir.div,{initial:{opacity:0},animate:{opacity:1},className:"space-y-1",children:[o.jsx("label",{className:"text-[10px] font-bold uppercase text-muted-foreground ml-1",children:"Email Coordinates"}),o.jsxs("div",{className:"relative",children:[o.jsx(as,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground/30",size:16}),o.jsx(Ce,{type:"email",placeholder:r("login.emailPlaceholder"),value:i,onChange:V=>l(V.target.value),required:!0,className:"pl-10 bg-background",autoComplete:"email",disabled:P==="verify"})]})]},"email-field"):null,M==="password"&&o.jsxs(ir.div,{initial:{opacity:0},animate:{opacity:1},className:"space-y-1",children:[o.jsx("label",{className:"text-[10px] font-bold uppercase text-muted-foreground ml-1",children:"Access Password"}),o.jsxs("div",{className:"relative",children:[o.jsx($0,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground/30",size:16}),o.jsx(Ce,{type:O?"text":"password",placeholder:"••••••••",value:u,onChange:V=>d(V.target.value),required:!0,minLength:6,className:"pl-10 pr-10 bg-background",autoComplete:G?"new-password":"current-password"}),o.jsx("button",{type:"button",onClick:()=>L(!O),className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground/30 hover:text-primary transition-colors",children:O?o.jsx(ZC,{size:16}):o.jsx(xd,{size:16})})]})]},"password-field"),M==="otp"&&P==="verify"&&o.jsxs(ir.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},className:"space-y-6 py-4",children:[o.jsx("div",{className:"flex justify-center",children:o.jsx(gq,{value:D,onChange:Q,length:6,onComplete:()=>{}})}),o.jsx(Z,{type:"button",variant:"link",className:"w-full text-[10px] font-bold uppercase tracking-widest text-primary/60",onClick:()=>q("email"),children:"Change Coordinates"}),o.jsxs(Z,{type:"button",onClick:I,disabled:b||D.length!==6,className:"w-full h-12 shadow-md",children:[b?o.jsx(wt,{className:"w-5 h-5 animate-spin mr-2"}):o.jsx(wg,{size:18,className:"mr-2"}),"Verify Access"]})]},"otp-field")]}),A&&o.jsxs(ir.div,{initial:{opacity:0,x:-10},animate:{opacity:1,x:0},className:"bg-destructive/10 text-destructive text-[11px] font-bold p-3 rounded-xl border border-destructive/20 flex items-start gap-2",children:[o.jsx(ls,{size:14,className:"mt-0.5 shrink-0"}),o.jsx("p",{children:A})]}),M!=="otp"||P==="email"?o.jsx(Z,{type:"submit",disabled:b||!i||M==="password"&&!u,className:"w-full h-12 shadow-md mt-4",children:b?o.jsx(wt,{className:"w-5 h-5 animate-spin"}):o.jsxs(o.Fragment,{children:[G?o.jsx(JR,{className:"w-5 h-5 mr-2"}):M==="otp"?o.jsx(as,{className:"w-5 h-5 mr-2"}):o.jsx(IA,{className:"w-5 h-5 mr-2"}),r(G?"login.initializeMaster":M==="otp"?"login.sendMagicLink":"login.openDashboard")]})}):null]}),o.jsxs("div",{className:"space-y-4 pt-4 border-t border-border/10",children:[!G&&o.jsx("div",{className:"flex flex-col gap-2",children:M==="password"?o.jsxs("button",{type:"button",onClick:()=>{B("otp"),q("email"),T("")},className:"w-full flex items-center justify-center gap-2 py-3 glass hover:bg-white/5 text-[10px] font-bold uppercase tracking-widest text-muted-foreground hover:text-primary transition-all rounded-xl",children:[o.jsx($0,{size:14})," Magic Link Login"]}):o.jsxs("button",{type:"button",onClick:()=>{B("password"),T("")},className:"w-full flex items-center justify-center gap-2 py-3 glass hover:bg-white/5 text-[10px] font-bold uppercase tracking-widest text-muted-foreground hover:text-primary transition-all rounded-xl",children:[o.jsx(pg,{size:14})," Password Access"]})}),o.jsxs("p",{className:"text-center text-[10px] text-muted-foreground font-bold uppercase tracking-wider",children:[G?"Already have an account?":"Need a new account?"," "," ",o.jsx("button",{onClick:()=>{fe(!G),B("password"),T("")},className:"text-primary hover:underline ml-1",children:G?"Login Instead":"Create Account"})]})]})]}),o.jsx("div",{className:"mt-8 text-center",children:o.jsx("p",{className:"text-[10px] font-bold text-muted-foreground/30 uppercase tracking-[0.4em]",children:"Powered by RealTimeX Intelligence"})})]})]})}function xq({status:e,onDismiss:t,onLearnMore:n}){const[r,i]=w.useState(!0);if(!r)return null;const l=()=>{JL(),i(!1),t?.()},u=()=>{n?n():(navigator.clipboard.writeText("npx email-automator migrate"),le.success("Command copied to clipboard"))};return o.jsx("div",{className:"fixed right-4 top-16 z-50 max-w-sm animate-in slide-in-from-top-5",children:o.jsx("div",{className:"rounded-lg border border-yellow-500 bg-yellow-50 p-4 shadow-lg dark:bg-yellow-950/90 dark:border-yellow-600",children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx(za,{className:"h-5 w-5 flex-shrink-0 text-yellow-600 dark:text-yellow-500 mt-0.5"}),o.jsxs("div",{className:"flex-1 space-y-2",children:[o.jsxs("div",{className:"flex items-start justify-between gap-2",children:[o.jsx("p",{className:"text-sm font-medium text-yellow-900 dark:text-yellow-100",children:"Database Update Required"}),o.jsxs(Z,{size:"icon",variant:"ghost",className:"h-5 w-5 -mr-1 -mt-1 text-yellow-900 hover:bg-yellow-100 dark:text-yellow-100 dark:hover:bg-yellow-900/30",onClick:l,children:[o.jsx(on,{className:"h-3 w-3"}),o.jsx("span",{className:"sr-only",children:"Dismiss"})]})]}),o.jsxs("p",{className:"text-xs text-yellow-800 dark:text-yellow-200",children:["Your app version (",e.appVersion,") requires a database schema update."]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Z,{size:"sm",variant:"default",className:"h-7 text-xs bg-yellow-600 hover:bg-yellow-700 dark:bg-yellow-500 dark:hover:bg-yellow-600",onClick:u,children:"Update Now"}),o.jsx(Z,{size:"sm",variant:"ghost",className:"h-7 text-xs text-yellow-900 hover:bg-yellow-100 dark:text-yellow-100 dark:hover:bg-yellow-900/30",onClick:l,children:"Remind Later"})]})]})]})})})}function vq({open:e,onOpenChange:t,status:n}){const r=fo(),[i,l]=w.useState(!1),[u,d]=w.useState([]),[h,m]=w.useState(""),p=w.useRef(null),g=w.useMemo(()=>{const v=r?.url;if(!v)return"";try{return new URL(v).hostname.split(".")[0]||""}catch{return""}},[r?.url]);w.useEffect(()=>{p.current&&p.current.scrollIntoView({behavior:"smooth"})},[u]);const b=async()=>{if(!g){le.error("Missing Project ID");return}if(!h){le.error("Provide a Supabase Personal Access Token.");return}l(!0),d(["Initializing migration..."]);try{const v=async N=>{const A=new TextDecoder;let T="",O=null;const L=M=>{const B=M.trim();if(!(!B||!B.startsWith("data: ")))try{const P=B.substring(6),q=JSON.parse(P);q.type==="done"?(q.data==="success"||q.data==="failed")&&(O=q.data==="success"?"success":"failure"):q.data&&d(D=>[...D,q.data])}catch(P){console.error("Failed to parse SSE line:",B,P)}};for(;;){const{done:M,value:B}=await N.read();if(M)break;T+=A.decode(B,{stream:!0});const P=T.split(`
|
|
217
|
+
`);T=P.pop()||"",P.forEach(L)}return T+=A.decode(),T&&L(T),O};d(N=>[...N,"","📦 Database Migration & Edge Functions Deployment"]);const S=await fetch("/api/migrate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectRef:g,accessToken:h})});if(!S.ok)throw new Error(`Migration failed: ${S.status} ${S.statusText}`);const _=S.body?.getReader();if(!_)throw new Error("No migration response stream received.");if(await v(_)!=="success")throw new Error("Migration did not complete successfully");d(N=>[...N,"","═".repeat(60),"✅ Setup Complete!","","✓ Database schema updated","✓ Edge Functions deployed","","🎉 Your Email Automator is ready to use!","📝 The application will reload automatically...","═".repeat(60)]),setTimeout(()=>{window.location.reload()},3e3)}catch(v){console.error(v),d(S=>[...S,"",`❌ Error: ${v instanceof Error?v.message:String(v)}`]),le.error("Setup failed. Check logs for details.")}finally{l(!1)}};return o.jsx(is,{open:e,onOpenChange:v=>!i&&t(v),children:o.jsxs(os,{className:"max-h-[90vh] sm:max-w-5xl overflow-y-auto",children:[o.jsxs(dr,{children:[o.jsxs(bs,{className:"flex items-center gap-2 text-xl",children:[o.jsx(za,{className:"h-6 w-6 text-red-700 dark:text-red-600"}),"Database Setup Required"]}),o.jsxs(fr,{children:["Your application version (",n.appVersion,") requires database migration and Edge Functions deployment to function correctly."]})]}),o.jsxs("div",{className:"space-y-6",children:[o.jsxs(La,{children:[o.jsx(ro,{className:"h-4 w-4"}),o.jsxs(Ia,{children:[o.jsx("strong",{children:"Why is this needed?"}),o.jsxs("ul",{className:"mt-2 list-inside list-disc space-y-1 text-sm",children:[o.jsxs("li",{children:["Updates your database schema to match version ",n.appVersion]}),o.jsx("li",{children:"Deploys Edge Functions (API endpoints) to your Supabase project"}),o.jsx("li",{children:"Enables new features and performance improvements"}),o.jsx("li",{children:"Your existing data will be preserved (safe migration)"})]})]})]}),o.jsxs("div",{className:"space-y-4 py-2",children:[o.jsxs("div",{className:"rounded-lg border bg-card text-card-foreground shadow-sm p-6",children:[o.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Automated Setup"}),o.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Run database migration and deploy Edge Functions directly from your browser. A Supabase Personal Access Token is required to authenticate with your project."}),o.jsxs("div",{className:"grid gap-4",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Ge,{htmlFor:"project-id",children:"Supabase Project ID"}),o.jsx(Ce,{id:"project-id",value:g,disabled:!0,readOnly:!0,className:"bg-muted"})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsxs("div",{className:"flex justify-between items-center",children:[o.jsx(Ge,{htmlFor:"access-token",children:"Access Token"}),o.jsxs("a",{href:"https://supabase.com/dashboard/account/tokens",target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline flex items-center gap-1",children:["Generate Token ",o.jsx(Cl,{className:"h-3 w-3"})]})]}),o.jsx(Ce,{id:"access-token",type:"password",placeholder:"sbp_...",value:h,onChange:v=>m(v.target.value),disabled:i}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"This token is used only for this migration and is not stored."})]}),o.jsx(Z,{onClick:b,disabled:i||!h,className:"w-full",children:i?o.jsxs(o.Fragment,{children:[o.jsx(wt,{className:"mr-2 h-4 w-4 animate-spin"}),"Running Setup..."]}):o.jsxs(o.Fragment,{children:[o.jsx(Rl,{className:"mr-2 h-4 w-4"}),"Start Setup"]})})]})]}),o.jsxs("div",{className:"rounded-lg border bg-black text-white font-mono text-xs p-4 h-64 overflow-y-auto",children:[u.length===0?o.jsx("div",{className:"text-gray-500 italic",children:"Waiting to start..."}):u.map((v,S)=>o.jsx("div",{className:"mb-1 whitespace-pre-wrap",children:v},S)),o.jsx("div",{ref:p})]})]}),o.jsxs(La,{className:"border-red-200 bg-red-50 dark:border-red-900/40 dark:bg-red-950/20",children:[o.jsx(za,{className:"h-4 w-4 text-red-700 dark:text-red-600"}),o.jsxs(Ia,{children:[o.jsx("strong",{children:"Troubleshooting"}),o.jsxs("ul",{className:"mt-2 list-inside list-disc space-y-1 text-sm",children:[o.jsxs("li",{children:["Ensure your Access Token has ",o.jsx("code",{children:"read"})," and ",o.jsx("code",{children:"write"})," permissions."]}),o.jsx("li",{children:"Verify that your Supabase Project ID is correct and active."})]})]})]})]}),o.jsx(or,{children:o.jsx(Z,{type:"button",variant:"outline",onClick:()=>t(!1),disabled:i,children:"Close"})})]})})}const bq="https://registry.npmjs.org/@realtimex/email-automator/latest",wq=300*1e3,O2="email_automator_last_version_check",D2="email_automator_update_dismissed";function Sq(){return"2.23.3"}async function jq(){try{const e=await fetch(bq,{cache:"no-store"});return e.ok?(await e.json()).version||null:(console.warn("[Version Check] Failed to fetch latest version"),null)}catch(e){return console.error("[Version Check] Error fetching latest version:",e),null}}function kq(e,t){if(t==="unknown")return!1;const n=m=>m.replace(/^v/,"").split(".").map(g=>parseInt(g,10)||0),[r,i,l]=n(e),[u,d,h]=n(t);return u>r?!0:u<r?!1:d>i?!0:d<i?!1:h>l}function _q(){try{const e=localStorage.getItem(O2);if(!e)return!0;const t=new Date(e).getTime();return Date.now()-t>wq}catch{return!0}}function Nq(){try{localStorage.setItem(O2,new Date().toISOString())}catch(e){console.error("[Version Check] Error saving check timestamp:",e)}}function Tq(e=24){try{const t=localStorage.getItem(D2);if(!t)return!1;const n=new Date(t).getTime();return(Date.now()-n)/(1e3*60*60)<e}catch{return!1}}function Eq(){try{localStorage.setItem(D2,new Date().toISOString())}catch(e){console.error("[Version Check] Error dismissing update prompt:",e)}}async function Cq(){if(!_q())return console.log("[Version Check] Skipping (throttled)"),null;const e=Sq(),t=await jq();if(Nq(),!t)return console.warn("[Version Check] Could not determine latest version"),null;const n=kq(e,t);return console.log("[Version Check]",{current:e,latest:t,updateAvailable:n}),n?{current:e,latest:t,updateAvailable:!0,updateUrl:"https://github.com/realtimex/email-automator/releases/latest"}:null}function Aq(){typeof window<"u"&&window.location.reload(),window.electron?.ipcRenderer&&window.electron.ipcRenderer.send("restart-app")}function Rq({versionInfo:e,onDismiss:t}){const[n,r]=w.useState(!0),[i,l]=w.useState(!1);if(!n)return null;const u=()=>{Eq(),r(!1),t?.()},d=()=>{l(!0),setTimeout(()=>{Aq()},500)},h=()=>{e.updateUrl&&window.open(e.updateUrl,"_blank")};return o.jsx("div",{className:"fixed right-4 top-16 z-50 max-w-sm animate-in slide-in-from-top-5",children:o.jsx("div",{className:"rounded-lg border border-blue-500 bg-blue-50 p-4 shadow-lg dark:bg-blue-950/90 dark:border-blue-600",children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx(Wt,{className:"h-5 w-5 flex-shrink-0 text-blue-600 dark:text-blue-500 mt-0.5"}),o.jsxs("div",{className:"flex-1 space-y-2",children:[o.jsxs("div",{className:"flex items-start justify-between gap-2",children:[o.jsx("p",{className:"text-sm font-medium text-blue-900 dark:text-blue-100",children:"Update Available"}),o.jsxs(Z,{size:"icon",variant:"ghost",className:"h-5 w-5 -mr-1 -mt-1 text-blue-900 hover:bg-blue-100 dark:text-blue-100 dark:hover:bg-blue-900/30",onClick:u,children:[o.jsx(on,{className:"h-3 w-3"}),o.jsx("span",{className:"sr-only",children:"Dismiss"})]})]}),o.jsxs("p",{className:"text-xs text-blue-800 dark:text-blue-200",children:["Version ",e.latest," is now available (you're on ",e.current,")"]}),o.jsxs("div",{className:"flex gap-2 flex-wrap",children:[o.jsx(Z,{size:"sm",variant:"default",className:"h-7 text-xs bg-blue-600 hover:bg-blue-700 dark:bg-blue-500 dark:hover:bg-blue-600",onClick:d,disabled:i,children:i?o.jsxs(o.Fragment,{children:[o.jsx(Wt,{className:"h-3 w-3 mr-1 animate-spin"}),"Updating..."]}):o.jsxs(o.Fragment,{children:[o.jsx(Wt,{className:"h-3 w-3 mr-1"}),"Update Now"]})}),e.updateUrl&&o.jsxs(Z,{size:"sm",variant:"ghost",className:"h-7 text-xs text-blue-900 hover:bg-blue-100 dark:text-blue-100 dark:hover:bg-blue-900/30",onClick:h,children:[o.jsx(Cl,{className:"h-3 w-3 mr-1"}),"What's New"]}),o.jsx(Z,{size:"sm",variant:"ghost",className:"h-7 text-xs text-blue-900 hover:bg-blue-100 dark:text-blue-100 dark:hover:bg-blue-900/30",onClick:u,children:"Later"})]})]})]})})})}function Oq(){const{t:e}=tt(),[t,n]=w.useState([]),{isExpanded:r,setIsExpanded:i}=Xj(),{state:l,actions:u}=Tn(),{isSyncing:d}=l,[h,m]=w.useState({});w.useEffect(()=>{p();const j=gt.channel("processing_events_feed").on("postgres_changes",{event:"INSERT",schema:"public",table:"processing_events"},N=>{const A=N.new;A.event_type==="error"&&m(T=>({...T,[A.id]:!0})),n(T=>{const O=[A,...T];return A.details?.is_completion&&r&&setTimeout(()=>{i(!1)},3e3),O.length>100?O.slice(0,100):O})}).subscribe();return()=>{gt.removeChannel(j)}},[r,i]);const p=async()=>{const{data:j}=await gt.from("processing_events").select("*").order("created_at",{ascending:!1}).limit(50);j&&n(j)},g=j=>{m(N=>({...N,[j]:!N[j]}))},b=j=>{if(j.details?.is_completion)return o.jsx(Ju,{className:"w-3 h-3 text-emerald-500"});switch(j.event_type){case"analysis":return o.jsx(Jr,{className:"w-3 h-3 text-purple-500"});case"action":return o.jsx(ao,{className:"w-3 h-3 text-emerald-500"});case"error":return o.jsx(za,{className:"w-3 h-3 text-red-500"});default:return o.jsx(ro,{className:"w-3 h-3 text-blue-500"})}},v=j=>new Date(j).toLocaleTimeString([],{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"}),S=j=>{const N=`terminal.state.${j.toLowerCase().replace(/\s+/g,"_")}`,A=e(N);return A.startsWith("terminal.state.")?j:A},_=j=>{if(!j)return"";if(j.startsWith("Background processing: ")){const A=j.replace("Background processing: ","");return e("terminal.message.background_processing").replace("{subject}",A)}const N=j.match(/^(\d+) rule\(s\) apply: (.+)$/);if(N){const[,A,T]=N;return e("terminal.message.rules_apply").replace("{count}",A).replace("{rules}",T)}if(j.startsWith("After conflict resolution: ")){const A=j.replace("After conflict resolution: ","");return e("terminal.message.conflict_resolution").replace("{actions}",A)}if(j.startsWith("Analyzing email: ")){const A=j.replace("Analyzing email: ","");return e("terminal.message.analyzing_email").replace("{subject}",A)}if(j.startsWith("Context-aware analysis: ")){const A=j.replace("Context-aware analysis: ","");return e("terminal.message.context_aware_analysis").replace("{subject}",A)}return j==="Generating customized draft based on rule"?e("terminal.message.generating_draft"):j};return r?o.jsxs($e,{className:"fixed bottom-4 right-4 z-50 w-[550px] h-[650px] flex flex-col shadow-2xl border-border bg-background/95 text-foreground backdrop-blur-md animate-in slide-in-from-bottom-10",children:[o.jsxs(Ot,{className:"py-3 px-4 border-b border-border flex flex-row items-center justify-between sticky top-0 bg-background/95 z-20",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Rl,{className:"w-4 h-4 text-primary"}),o.jsx(Bt,{className:"text-sm font-mono font-bold",children:e("terminal.title")}),o.jsxs("div",{className:me("flex items-center gap-1 text-[10px] px-2 py-0.5 rounded-full border font-bold animate-pulse transition-colors duration-500",d?"text-red-600 dark:text-red-400 bg-red-500/10 border-red-500/20":"text-green-600 dark:text-green-400 bg-green-500/10 border-green-500/20"),children:[o.jsx(fC,{className:"w-3 h-3"}),e(d?"terminal.syncing":"terminal.live")]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[d&&o.jsxs(Z,{variant:"destructive",size:"sm",className:"h-7 text-[10px] font-mono font-bold bg-red-600 hover:bg-red-700 animate-in fade-in zoom-in duration-300",onClick:()=>u.stopSync(),children:[o.jsx(NR,{className:"w-3 h-3 mr-1 fill-current"}),e("terminal.stopSync")]}),o.jsx(Z,{variant:"ghost",size:"sm",className:"h-7 text-[10px] font-mono hover:bg-secondary",onClick:()=>n([]),children:e("terminal.clear")}),o.jsx(Z,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 hover:bg-secondary",onClick:()=>i(!1),children:o.jsx(ij,{className:"w-4 h-4"})})]})]}),o.jsxs(vt,{className:"flex-1 overflow-y-auto p-4 font-mono text-xs space-y-6 custom-scrollbar",children:[t.length===0&&o.jsx("div",{className:"text-center text-muted-foreground py-20 italic",children:e("terminal.waiting")}),t.map((j,N)=>o.jsxs("div",{className:"relative pl-8 animate-in fade-in slide-in-from-top-2 duration-300",children:[N!==t.length-1&&o.jsx("div",{className:"absolute left-[13px] top-7 bottom-[-24px] w-[1px] bg-border"}),o.jsx("div",{className:me("absolute left-0 top-0 w-7 h-7 rounded-full border border-border bg-card flex items-center justify-center z-10 shadow-sm",j.event_type==="error"&&"border-red-500/50 bg-red-500/5",j.event_type==="analysis"&&"border-purple-500/50 bg-purple-500/5",j.event_type==="action"&&"border-emerald-500/50 bg-emerald-500/5",j.details?.is_completion&&"border-emerald-500/50 bg-emerald-500/5"),children:b(j)}),o.jsxs("div",{className:"flex flex-col gap-1.5",children:[o.jsxs("div",{className:"flex items-center justify-between group",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:me("font-bold uppercase tracking-tight text-[10px]",j.event_type==="info"&&"text-muted-foreground",j.event_type==="analysis"&&"text-purple-600 dark:text-purple-400",j.event_type==="action"&&"text-emerald-600 dark:text-emerald-400",j.event_type==="error"&&"text-red-600 dark:text-red-400"),children:S(j.agent_state)}),o.jsx("span",{className:"text-[10px] text-muted-foreground/60",children:v(j.created_at)})]}),(j.details?.system_prompt||j.details?._raw_response||j.details?.raw_response)&&o.jsxs(Z,{variant:"ghost",size:"sm",className:"h-5 px-1.5 text-[9px] text-muted-foreground hover:text-primary opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>g(j.id),children:[h[j.id]?o.jsx(LC,{className:"w-3 h-3 mr-1"}):o.jsx(gd,{className:"w-3 h-3 mr-1"}),e("terminal.details")]})]}),j.event_type==="analysis"&&j.details?o.jsxs("div",{className:"bg-purple-500/5 border border-purple-500/10 rounded-lg p-3 space-y-2",children:[o.jsxs("div",{className:"flex gap-2",children:[o.jsx("span",{className:me("px-1.5 py-0.5 rounded text-[9px] font-bold border",j.details.is_useless?"bg-red-500/10 text-red-600 dark:text-red-400 border-red-500/20":"bg-green-500/10 text-green-600 dark:text-green-400 border-green-500/20"),children:j.details.is_useless?e("terminal.useless"):e("terminal.relevant")}),o.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-bold border bg-blue-500/10 text-blue-600 dark:text-blue-400 border-blue-500/20 uppercase",children:j.details.category})]}),o.jsxs("p",{className:"text-foreground/90 italic leading-relaxed",children:['"',j.details.summary,'"']}),j.details.suggested_actions&&j.details.suggested_actions.length>0&&o.jsx("div",{className:"pt-1 flex items-center gap-2 flex-wrap",children:j.details.suggested_actions.map(A=>o.jsxs("div",{className:"flex items-center gap-1 text-[9px] text-emerald-600 dark:text-emerald-400 font-bold bg-emerald-500/10 px-1.5 py-0.5 rounded border border-emerald-500/20 uppercase",children:[o.jsx(ao,{className:"w-2.5 h-2.5"}),A]},A))}),j.details.usage&&o.jsx("div",{className:"pt-1.5 flex items-center gap-3 text-[9px] text-muted-foreground/70 border-t border-purple-500/10 mt-1",children:o.jsxs("span",{children:[e("terminal.tokens").replace("{promptTokens}",String(j.details.usage.prompt_tokens)).replace("{completionTokens}",String(j.details.usage.completion_tokens))," = ",o.jsx("span",{className:"text-purple-500 font-bold",children:j.details.usage.total_tokens})]})})]}):j.event_type==="action"&&j.details?o.jsxs("div",{className:"bg-emerald-500/5 border border-emerald-500/10 rounded-lg p-3",children:[o.jsx("p",{className:"text-emerald-600 dark:text-emerald-400 font-bold mb-1 uppercase text-[9px] tracking-widest",children:e("terminal.executionComplete")}),o.jsxs("p",{className:"text-foreground font-medium",children:[j.details.action==="delete"&&e("terminal.action.delete"),j.details.action==="archive"&&e("terminal.action.archive"),j.details.action==="draft"&&e("terminal.action.draft"),j.details.action==="star"&&e("terminal.action.star"),!["delete","archive","draft","star"].includes(j.details.action)&&j.details.action]}),j.details.reason&&o.jsxs("p",{className:"text-[10px] text-muted-foreground mt-1.5 flex items-center gap-1",children:[o.jsx(ro,{className:"w-3 h-3"}),j.details.reason]})]}):j.event_type==="error"&&j.details?o.jsx("div",{className:"bg-red-500/5 border border-red-500/10 rounded-lg p-2.5 text-red-600 dark:text-red-400 font-medium",children:typeof j.details.error=="object"?j.details.error.message||JSON.stringify(j.details.error):j.details.error}):j.details?.is_completion?o.jsxs("div",{className:"bg-emerald-500/5 border border-emerald-500/20 rounded-lg p-3 space-y-2",children:[o.jsxs("div",{className:"flex items-center gap-2 text-emerald-600 dark:text-emerald-400 font-bold uppercase text-[9px] tracking-[0.2em]",children:[o.jsx(Ju,{className:"w-3.5 h-3.5"}),e("terminal.batchFinished")]}),o.jsxs("div",{className:"grid grid-cols-2 gap-4 pt-1",children:[o.jsxs("div",{className:"space-y-0.5",children:[o.jsx("p",{className:"text-[10px] text-muted-foreground uppercase",children:e("terminal.processed")}),o.jsx("p",{className:"text-sm font-bold",children:j.details.total_processed||0})]}),o.jsxs("div",{className:"space-y-0.5",children:[o.jsx("p",{className:"text-[10px] text-muted-foreground uppercase",children:e("terminal.actions")}),o.jsx("p",{className:"text-sm font-bold text-emerald-500",children:(j.details.deleted||0)+(j.details.drafted||0)})]})]}),j.details.errors>0&&o.jsx("p",{className:"text-[10px] text-red-500 font-bold pt-1 border-t border-emerald-500/10",children:e("terminal.itemsFailed").replace("{count}",String(j.details.errors))})]}):o.jsx("p",{className:"text-muted-foreground leading-relaxed",children:_(j.details?.message)||JSON.stringify(j.details)}),h[j.id]&&o.jsxs("div",{className:"mt-2 space-y-3 animate-in fade-in zoom-in-95 duration-200",children:[j.details?.system_prompt&&o.jsxs("div",{className:"space-y-1.5",children:[o.jsxs("div",{className:"flex items-center gap-1.5 text-[9px] font-bold text-muted-foreground uppercase tracking-widest px-1",children:[o.jsx(Ds,{className:"w-3 h-3"})," ",e("terminal.detail.systemPrompt")]}),o.jsx("div",{className:"bg-secondary/50 rounded-md p-3 border border-border overflow-x-auto",children:o.jsx("pre",{className:"whitespace-pre-wrap break-words text-[10px] leading-normal text-muted-foreground select-all",children:j.details.system_prompt})})]}),j.details?.content_preview&&o.jsxs("div",{className:"space-y-1.5",children:[o.jsxs("div",{className:"flex items-center gap-1.5 text-[9px] font-bold text-muted-foreground uppercase tracking-widest px-1",children:[o.jsx(Ds,{className:"w-3 h-3"})," ",e("terminal.detail.inputContent")]}),o.jsx("div",{className:"bg-secondary/50 rounded-md p-3 border border-border",children:o.jsx("p",{className:"whitespace-pre-wrap break-words text-[10px] text-muted-foreground",children:j.details.content_preview})})]}),j.details?._raw_response&&o.jsxs("div",{className:"space-y-1.5",children:[o.jsxs("div",{className:"flex items-center gap-1.5 text-[9px] font-bold text-muted-foreground uppercase tracking-widest px-1",children:[o.jsx(Ds,{className:"w-3 h-3"})," ",e("terminal.detail.rawLLMOutput")]}),o.jsx("div",{className:"bg-secondary/50 rounded-md p-3 border border-border overflow-x-auto",children:o.jsx("pre",{className:"text-[10px] text-muted-foreground select-all",children:JSON.stringify(JSON.parse(j.details._raw_response),null,2)})})]}),j.details?.raw_response&&o.jsxs("div",{className:"space-y-1.5",children:[o.jsxs("div",{className:"flex items-center gap-1.5 text-[9px] font-bold text-muted-foreground uppercase tracking-widest px-1",children:[o.jsx(Ds,{className:"w-3 h-3"})," ",e("terminal.detail.rawResponse")]}),o.jsx("div",{className:"bg-secondary/50 rounded-md p-3 border border-border overflow-x-auto",children:o.jsx("pre",{className:"text-[10px] text-muted-foreground select-all whitespace-pre-wrap",children:typeof j.details.raw_response=="object"?JSON.stringify(j.details.raw_response,null,2):j.details.raw_response})})]})]})]})]},j.id))]})]}):o.jsx("div",{className:"fixed bottom-4 right-4 z-50",children:o.jsxs(Z,{onClick:()=>i(!0),className:"shadow-lg bg-primary text-primary-foreground hover:opacity-90 border border-border",children:[o.jsx(Rl,{className:"w-4 h-4 mr-2"}),e("terminal.liveActivity"),(t.length>0||d)&&o.jsxs("span",{className:"ml-2 flex h-2 w-2 relative",children:[o.jsx("span",{className:me("animate-ping absolute inline-flex h-full w-full rounded-full opacity-75",d?"bg-red-400":"bg-green-400")}),o.jsx("span",{className:me("relative inline-flex rounded-full h-2 w-2",d?"bg-red-500":"bg-green-500")})]})]})})}const zy=w.createContext(null),M2=w.forwardRef(({className:e,defaultValue:t,value:n,onValueChange:r,...i},l)=>{const[u,d]=w.useState(t||""),h=n!==void 0?n:u,m=w.useCallback(p=>{r&&r(p),n===void 0&&d(p)},[r,n]);return o.jsx(zy.Provider,{value:{value:h,onValueChange:m},children:o.jsx("div",{ref:l,className:e,...i})})});M2.displayName="Tabs";const P2=w.forwardRef(({className:e,...t},n)=>o.jsx("div",{ref:n,className:me("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",e),...t}));P2.displayName="TabsList";const dg=w.forwardRef(({className:e,value:t,onClick:n,...r},i)=>{const l=w.useContext(zy);if(!l)throw new Error("TabsTrigger must be used within Tabs");const u=l.value===t;return o.jsx("button",{ref:i,type:"button",role:"tab","aria-selected":u,"data-state":u?"active":"inactive",className:me("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",e),onClick:d=>{l.onValueChange(t),n?.(d)},...r})});dg.displayName="TabsTrigger";const fg=w.forwardRef(({className:e,value:t,...n},r)=>{const i=w.useContext(zy);if(!i)throw new Error("TabsContent must be used within Tabs");return i.value!==t?null:o.jsx("div",{ref:r,role:"tabpanel","data-state":"active",className:me("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),...n})});fg.displayName="TabsContent";const Dq=()=>{const[e,t]=w.useState(null),[n,r]=w.useState(!0),i=w.useCallback(async()=>{try{const h=(await Oe.getLearningMetrics()).data;t(h?{total_classifications:h.total_classifications||0,correct_classifications:h.correct_classifications||0,drafts_generated:h.drafts_generated||0,drafts_edited:h.drafts_edited||0,category_patterns:h.category_patterns||{},vip_senders:h.vip_senders||[]}:{total_classifications:0,correct_classifications:0,drafts_generated:0,drafts_edited:0,category_patterns:{},vip_senders:[]})}catch(d){console.error("Failed to load learning metrics",d)}finally{r(!1)}},[]);if(w.useEffect(()=>{i()},[i]),n)return o.jsxs("div",{className:"p-8 text-center text-muted-foreground flex items-center justify-center gap-2",children:[o.jsx(Jr,{className:"w-5 h-5 animate-pulse text-primary"})," Loading AI DNA..."]});if(!e)return null;const l=e.total_classifications>0?Math.round(e.correct_classifications/e.total_classifications*100):100,u=Math.round(e.drafts_generated*5);return e.drafts_generated>0&&Math.round((e.drafts_generated-e.drafts_edited)/e.drafts_generated*100),o.jsxs("div",{className:"space-y-6 animate-in fade-in duration-500",children:[o.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[o.jsxs($e,{children:[o.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[o.jsx(Bt,{className:"text-sm font-medium",children:"AI Accuracy"}),o.jsx(Jr,{className:"h-4 w-4 text-primary"})]}),o.jsxs(vt,{children:[o.jsxs("div",{className:"text-2xl font-bold",children:[l,"%"]}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Classification confidence"}),o.jsx(Py,{value:l,className:"mt-3 h-2"})]})]}),o.jsxs($e,{children:[o.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[o.jsx(Bt,{className:"text-sm font-medium",children:"Time Saved"}),o.jsx(FR,{className:"h-4 w-4 text-green-500"})]}),o.jsxs(vt,{children:[o.jsxs("div",{className:"text-2xl font-bold",children:[u,"m"]}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Est. minutes saved drafting"})]})]}),o.jsxs($e,{children:[o.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[o.jsx(Bt,{className:"text-sm font-medium",children:"Learned Patterns"}),o.jsx(bg,{className:"h-4 w-4 text-blue-500"})]}),o.jsxs(vt,{children:[o.jsx("div",{className:"text-2xl font-bold",children:Object.keys(e.category_patterns).length}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"Domain rules learned"})]})]}),o.jsxs($e,{children:[o.jsxs(Ot,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[o.jsx(Bt,{className:"text-sm font-medium",children:"VIP Network"}),o.jsx(ip,{className:"h-4 w-4 text-yellow-500"})]}),o.jsxs(vt,{children:[o.jsx("div",{className:"text-2xl font-bold",children:e.vip_senders.length}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"High-priority contacts"})]})]})]}),o.jsxs(M2,{defaultValue:"patterns",className:"w-full",children:[o.jsxs(P2,{children:[o.jsx(dg,{value:"patterns",children:"Domain Patterns"}),o.jsx(dg,{value:"vips",children:"VIP Senders"})]}),o.jsx(fg,{value:"patterns",className:"space-y-4 pt-4",children:o.jsxs($e,{children:[o.jsxs(Ot,{children:[o.jsx(Bt,{className:"text-lg",children:"Learned Categorization Rules"}),o.jsx(xs,{children:"The AI automatically learns to classify emails from these domains based on your corrections."})]}),o.jsx(vt,{children:o.jsx("div",{className:"space-y-4",children:Object.entries(e.category_patterns).length===0?o.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground border border-dashed rounded-lg bg-secondary/10",children:[o.jsx(ao,{className:"h-10 w-10 mb-4 opacity-50"}),o.jsx("p",{children:"No patterns learned yet."}),o.jsx("p",{className:"text-xs mt-1",children:"Correct some email categories in the Dashboard to teach the AI!"})]}):o.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:Object.entries(e.category_patterns).map(([d,h])=>o.jsxs("div",{className:"flex items-center justify-between p-3 border rounded-lg bg-card hover:bg-accent/50 transition-colors",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"h-2 w-2 rounded-full bg-blue-500"}),o.jsx("span",{className:"font-mono text-sm",children:d})]}),o.jsx(El,{variant:"secondary",className:"capitalize",children:h})]},d))})})})]})}),o.jsx(fg,{value:"vips",className:"pt-4",children:o.jsxs($e,{children:[o.jsxs(Ot,{children:[o.jsx(Bt,{className:"text-lg",children:"Identified VIP Senders"}),o.jsx(xs,{children:"Contacts that are automatically flagged as High Priority."})]}),o.jsx(vt,{children:o.jsx("div",{className:"space-y-4",children:e.vip_senders.length===0?o.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground border border-dashed rounded-lg bg-secondary/10",children:[o.jsx(KR,{className:"h-10 w-10 mb-4 opacity-50"}),o.jsx("p",{children:"No VIPs identified yet."}),o.jsx("p",{className:"text-xs mt-1",children:"Interacting frequently with contacts will elevate them to VIP status."})]}):o.jsx("div",{className:"flex flex-wrap gap-2",children:e.vip_senders.map(d=>o.jsxs(El,{variant:"outline",className:"pl-1 pr-3 py-1.5 text-sm flex items-center gap-2 bg-secondary/20",children:[o.jsx("div",{className:"w-5 h-5 rounded-full bg-yellow-500/10 flex items-center justify-center",children:o.jsx(ip,{className:"w-3 h-3 text-yellow-500 fill-yellow-500"})}),d]},d))})})})]})})]})]})},z2=w.forwardRef(({className:e,...t},n)=>o.jsx("span",{ref:n,className:me("absolute h-px w-px overflow-hidden whitespace-nowrap border-0 p-0","[clip:rect(0,0,0,0)]",e),...t}));z2.displayName="VisuallyHidden";function Mq(e={}){const[t,n]=w.useState(!1),[r,i]=w.useState(""),[l,u]=w.useState(""),[d,h]=w.useState(!1),m=w.useRef(null);w.useEffect(()=>{const v=window.SpeechRecognition||window.webkitSpeechRecognition;return h(!!v),v&&(m.current=new v,m.current.continuous=e.continuous??!1,m.current.interimResults=e.interimResults??!0,m.current.lang=e.lang||"en-US",m.current.onresult=S=>{let _="",j="";for(let N=S.resultIndex;N<S.results.length;N++){const A=S.results[N][0].transcript;S.results[N].isFinal?j+=A:_+=A}j&&i(N=>N+" "+j),u(_)},m.current.onend=()=>{n(!1)},m.current.onerror=S=>{console.error("[SpeechRecognition] Error:",S.error),n(!1)}),()=>{m.current&&m.current.stop()}},[e.continuous,e.interimResults,e.lang]);const p=w.useCallback(()=>{m.current&&!t&&(i(""),u(""),m.current.start(),n(!0))},[t]),g=w.useCallback(()=>{m.current&&t&&(m.current.stop(),n(!1))},[t]),b=w.useCallback(()=>{i(""),u("")},[]);return{isListening:t,transcript:r,interimTranscript:l,isSupported:d,startListening:p,stopListening:g,resetTranscript:b}}const Pq=(e,t)=>{const n={setup_wizard:"agent.title.setup",configuration_wizard:"agent.title.configuration",draft_review:"agent.title.drafts",explainer:"agent.title.explainer",global:"agent.title.global"};return n[e]?t(n[e]):t("agent.title.default").replace("{page}",e.replace(/_/g," "))},JS=(e,t,n)=>{switch(e){case"setup_wizard":return t("agent.intro.setup");case"configuration_wizard":return t("agent.intro.configuration").replace("{accountsCount}",String(n?.accounts_count||0)).replace("{rulesCount}",String(n?.rules_count||0));case"draft_review":{const r=n?.count||0;return t(r===1?"agent.intro.drafts.one":"agent.intro.drafts.other").replace("{count}",String(r))}case"explainer":return t("agent.intro.explainer");case"global":return t("agent.intro.global");default:return t("agent.intro.default").replace("{page}",e.replace(/_/g," "))}};function Vu({className:e}){const{currentConfig:t,chatHistory:n,agentState:r,sendMessage:i}=B_(),{state:l}=Tn(),{speak:u}=cy(),{speakingId:d,stop:h}=I_(),{t:m}=tt(),[p,g]=w.useState(!1),[b,v]=w.useState(""),[S,_]=w.useState(!1),[j,N]=w.useState(!1),A=w.useRef(null),T=w.useRef(t.page_id),{isListening:O,transcript:L,interimTranscript:M,isSupported:B,startListening:P,stopListening:q,resetTranscript:D}=Mq({continuous:!1,interimResults:!0});w.useEffect(()=>{const V=()=>{try{const C=localStorage.getItem("auto_speak_enabled");return C===null?!0:C==="true"}catch{return!0}},$=p&&n.length===0&&!S&&V(),de=t.page_id!==T.current;if($||p&&de&&n.length===0){const C=JS(t.page_id,m,t.data),z={provider:l.settings?.tts_provider||void 0,voice:l.settings?.tts_voice||void 0,speed:l.settings?.tts_speed!==void 0?l.settings.tts_speed:1,quality:l.settings?.tts_quality!==void 0?l.settings.tts_quality:10};console.log("[AgentOverlay] Intro speaking with TTS options:",z),u(C,`intro-${t.page_id}`,z),_(!0),T.current=t.page_id}p||_(!1)},[p,n.length,t.page_id,S,u]),w.useEffect(()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)},[n,p]),w.useEffect(()=>{L&&!O&&(v(L.trim()),D())},[L,O,D]),w.useEffect(()=>{O&&(L||M)&&v((L+" "+M).trim())},[L,M,O]);const Q=async()=>{if(!b.trim())return;const V=b;v(""),D(),await i(V)},G=V=>{V.key==="Enter"&&!V.shiftKey&&(V.preventDefault(),Q())},fe=()=>{O?q():P()},se=async(V,$)=>{const de=`msg-${$}`;if(d===de){h();return}const C={provider:l.settings?.tts_provider||void 0,voice:l.settings?.tts_voice||void 0,speed:l.settings?.tts_speed!==void 0?l.settings.tts_speed:1,quality:l.settings?.tts_quality!==void 0?l.settings.tts_quality:10};console.log("[AgentOverlay] Speaking with TTS options:",C),await u(V,de,C)},ae={p:({children:V})=>o.jsx("p",{className:"text-sm leading-relaxed whitespace-pre-wrap",children:V}),ul:({children:V})=>o.jsx("ul",{className:"list-disc pl-4 space-y-1 text-sm",children:V}),ol:({children:V})=>o.jsx("ol",{className:"list-decimal pl-4 space-y-1 text-sm",children:V}),li:({children:V})=>o.jsx("li",{className:"text-sm",children:V}),a:({href:V,children:$})=>o.jsx("a",{href:V,target:"_blank",rel:"noreferrer",className:"text-primary underline underline-offset-2",children:$}),code:V=>{const{inline:$,children:de}=V;return $?o.jsx("code",{className:"px-1 py-0.5 rounded bg-background/60 text-[12px] font-mono",children:de}):o.jsx("code",{className:"text-[12px] font-mono",children:de})},pre:({children:V})=>o.jsx("pre",{className:"mt-2 overflow-x-auto rounded bg-background/60 p-2 text-[12px] font-mono",children:V}),blockquote:({children:V})=>o.jsx("blockquote",{className:"border-l-2 border-border pl-3 text-sm text-muted-foreground",children:V}),strong:({children:V})=>o.jsx("strong",{className:"font-semibold",children:V}),em:({children:V})=>o.jsx("em",{className:"italic",children:V})},I=me("fixed bottom-6 left-6 z-50",e);return o.jsxs(o.Fragment,{children:[p&&o.jsx("div",{className:I,children:o.jsxs("div",{className:me(j?"w-[calc(100vw-2rem)] sm:w-[33vw] sm:max-w-[560px] h-[90vh] max-h-[calc(100vh-6rem)]":"w-[360px] sm:w-[380px] h-[520px] max-w-[calc(100vw-2rem)] max-h-[calc(100vh-6rem)]","bg-background border border-border/60 rounded-2xl shadow-2xl","flex flex-col overflow-hidden","animate-in slide-in-from-bottom-10 fade-in duration-200","transition-[width,height] duration-200 ease-out","motion-reduce:transition-none motion-reduce:animate-none"),children:[o.jsxs("div",{className:"p-3 border-b bg-muted/40 flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("div",{className:me("w-2.5 h-2.5 rounded-full",O?"bg-red-500 animate-pulse":r==="idle"?"bg-muted-foreground":r==="thinking"?"bg-yellow-500 animate-pulse":r==="speaking"?"bg-emerald-500 animate-pulse":"bg-red-500")}),o.jsxs("div",{className:"flex flex-col",children:[o.jsx("span",{className:"font-semibold text-sm leading-tight",children:O?m("agent.status.listening"):Pq(t.page_id,m)}),o.jsx("span",{className:"text-[10px] text-muted-foreground",children:m(r==="thinking"?"agent.status.analyzing":r==="speaking"?"agent.status.speaking":"agent.status.ready")})]})]}),o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(Z,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>N(V=>!V),"aria-label":j?"Collapse assistant":"Expand assistant",title:j?"Collapse":"Expand",children:j?o.jsx(ij,{className:"w-4 h-4"}):o.jsx(aj,{className:"w-4 h-4"})}),o.jsx(Z,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>g(!1),"aria-label":"Close assistant",children:o.jsx(on,{className:"w-4 h-4"})})]})]}),o.jsxs("div",{ref:A,className:"flex-1 overflow-y-auto p-4 space-y-4 bg-background",children:[n.length===0&&o.jsx("div",{className:"text-center text-muted-foreground text-xs mt-10 whitespace-pre-line",children:JS(t.page_id,m,t.data)}),n.map((V,$)=>{const de=`msg-${$}`,C=d===de,z=V.role!=="user";return o.jsx("div",{className:me("flex flex-col max-w-[85%] rounded-2xl p-3 text-sm relative group",V.role==="user"?"self-end bg-primary/10 text-foreground ml-auto rounded-br-md":"self-start bg-secondary text-secondary-foreground rounded-bl-md"),children:o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx("div",{className:"flex-1",children:V.role==="user"?V.content:o.jsx(i2,{remarkPlugins:[A2],components:ae,children:V.content})}),z&&o.jsx("button",{onClick:()=>se(V.content,$),className:me("shrink-0 p-1.5 rounded-md hover:bg-background/60 transition-colors","opacity-0 group-hover:opacity-100",C&&"opacity-100"),title:C?"Stop speaking":"Speak message",children:C?o.jsx(Sg,{className:"w-3.5 h-3.5 text-muted-foreground animate-pulse"}):o.jsx(Ol,{className:"w-3.5 h-3.5 text-muted-foreground"})})]})},$)}),r==="thinking"&&o.jsxs("div",{className:"self-start bg-secondary/50 rounded-lg p-3 flex gap-1",children:[o.jsx("span",{className:"w-1.5 h-1.5 bg-foreground/40 rounded-full animate-bounce [animation-delay:-0.3s]"}),o.jsx("span",{className:"w-1.5 h-1.5 bg-foreground/40 rounded-full animate-bounce [animation-delay:-0.15s]"}),o.jsx("span",{className:"w-1.5 h-1.5 bg-foreground/40 rounded-full animate-bounce"})]}),O&&o.jsxs("div",{className:"self-start bg-red-500/10 border border-red-500/30 rounded-lg p-4 flex flex-col gap-2 animate-pulse",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(H0,{className:"w-4 h-4 text-red-500 animate-pulse"}),o.jsx("span",{className:"text-xs font-semibold text-red-500",children:m("agent.recording")})]}),o.jsx("div",{className:"flex items-center justify-center gap-1 h-8",children:[...Array(12)].map((V,$)=>o.jsx("div",{className:"w-1 bg-red-500 rounded-full animate-pulse",style:{height:`${20+Math.sin($)*15}px`,animationDelay:`${$*.1}s`,animationDuration:"0.8s"}},$))}),M&&o.jsxs("div",{className:"text-xs text-muted-foreground italic",children:['"',M,'..."']})]})]}),o.jsxs("div",{className:"p-3 border-t bg-background flex gap-2",children:[o.jsx("input",{className:"flex-1 bg-secondary/40 border border-border/50 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-primary/40 outline-none",placeholder:m(O?"agent.composer.listening":"agent.composer.placeholder"),value:b,onChange:V=>v(V.target.value),onKeyDown:G,disabled:r==="thinking"||r==="speaking"||O}),B&&o.jsx(Z,{size:"icon",variant:O?"default":"outline",className:me("h-9 w-9 shrink-0",O&&"bg-red-500 hover:bg-red-600 animate-pulse"),onClick:fe,disabled:r==="thinking"||r==="speaking","aria-label":O?"Stop listening":"Start listening",children:O?o.jsx(HA,{className:"w-4 h-4"}):o.jsx(H0,{className:"w-4 h-4"})}),o.jsx(Z,{size:"icon",className:"h-9 w-9 shrink-0",onClick:Q,disabled:!b.trim()||r==="thinking"||O,"aria-label":"Send message",children:r==="thinking"?o.jsx(wt,{className:"w-4 h-4 animate-spin"}):o.jsx(Wl,{className:"w-4 h-4"})})]})]})}),o.jsx("div",{className:I,children:o.jsx(Z,{size:"icon",className:me("relative rounded-full h-11 w-11 border border-border/60 bg-primary text-primary-foreground shadow-md","transition-all duration-200 ease-out","hover:bg-primary/90 hover:shadow-lg hover:-translate-y-0.5","active:translate-y-0 active:shadow-md active:scale-95","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40 focus-visible:ring-offset-2 focus-visible:ring-offset-background","motion-reduce:transition-none motion-reduce:hover:transform-none",p?"rotate-0 scale-0 opacity-0":"scale-100 opacity-100",r==="speaking"&&"ring-4 ring-emerald-500/30 animate-pulse"),onClick:()=>g(!0),"aria-label":"Open assistant chat",title:"Open assistant chat",children:r==="speaking"?o.jsx(Ol,{className:"w-5 h-5 animate-pulse"}):o.jsx(vd,{className:"w-5 h-5"})})})]})}function zq(){const{state:e,isSubscribed:t,actions:n}=Tn(),{t:r}=tt(),[i,l]=w.useState(null),[u,d]=w.useState(!0),[h,m]=w.useState(!1),[p,g]=w.useState(!0),[b,v]=w.useState("dashboard"),[S,_]=w.useState(!1),[j,N]=w.useState(null),[A,T]=w.useState(!1),[O,L]=w.useState(!1),[M,B]=w.useState(!1),[P,q]=w.useState(null),[D,Q]=w.useState(!1),[G,fe]=w.useState(null),[se,ae]=w.useState(!1),[I,V]=w.useState(!1);if(w.useEffect(()=>{if(e.isInitialized&&e.isAuthenticated&&e.settings&&!e.isLoading&&!e.settings.persona_completed&&!se&&!I){const C=setTimeout(()=>{ae(!0)},2e3);return()=>clearTimeout(C)}},[e.isInitialized,e.isAuthenticated,e.settings,e.isLoading,I]),w.useEffect(()=>{const z=new URLSearchParams(window.location.search).get("code");z&&!S&&(async()=>{_(!0);try{const R=await Oe.connectGmail(z);if(R.data?.success)le.success("Gmail connected successfully!"),window.opener?setTimeout(()=>window.close(),1500):(window.history.replaceState({},"",window.location.pathname),n.fetchAccounts());else{const oe=typeof R.error=="string"?R.error:R.error?.message;le.error(oe||"Failed to connect Gmail")}}catch{le.error("Connection failed")}finally{_(!1)}})()},[]),S)return o.jsx(sd,{text:r("app.connecting")});w.useEffect(()=>{(async()=>{if(!fo()){m(!0),d(!1);return}try{const{data:oe,error:Se}=await gt.from("init_state").select("is_initialized").single();Se?(console.warn("[App] Init check error (might be fresh DB):",Se),Se.code==="42P01"&&g(!1)):g(oe.is_initialized>0);const{data:{session:ge}}=await gt.auth.getSession();if(l(ge?.user??null),ge?.user){const Ke=await dy(gt);N(Ke.needsMigration?Ke:null),Ke.needsMigration&&!XL()&&T(!0)}const pe=await Cq();pe&&!Tq()&&(q(pe),Q(!0))}catch(oe){console.error("[App] Status check failed:",oe),oe instanceof Error&&oe.message.includes("Invalid API key")&&m(!0)}finally{d(!1)}})();const{data:{subscription:z}}=gt.auth.onAuthStateChange((R,oe)=>{l(oe?.user??null),oe||(N(null),T(!1))}),X=()=>{if(Ms.isEnabled()){const R=new(window.AudioContext||window.webkitAudioContext);R.state==="suspended"&&R.resume()}window.removeEventListener("click",X),window.removeEventListener("keydown",X)};return window.addEventListener("click",X),window.addEventListener("keydown",X),()=>{z.unsubscribe(),window.removeEventListener("click",X),window.removeEventListener("keydown",X)}},[]),w.useEffect(()=>{if(i){n.fetchAccounts(),n.fetchRules(),n.fetchSettings(),n.fetchProfile();const C=setTimeout(()=>{console.debug("[App] Retrying fetchAccounts after initialization"),n.fetchAccounts()},1e3);return()=>clearTimeout(C)}},[i]),w.useEffect(()=>{const C=async()=>{try{await Oe.healthCheck()}catch{console.warn("[App] Keep-alive ping failed")}};C();const z=setInterval(C,3e4);return()=>clearInterval(z)},[]);const $=()=>{L(!0),T(!1)},de={migrationStatus:j,showMigrationBanner:A,showMigrationModal:O,openMigrationModal:$,suppressMigrationBanner:M,setSuppressMigrationBanner:B};return u?o.jsxs(o.Fragment,{children:[o.jsx(sd,{text:r("app.loadingWorkspace")}),o.jsx(Vu,{className:"z-[80]"})]}):h?o.jsxs(o.Fragment,{children:[o.jsx(K_,{onComplete:()=>m(!1)}),o.jsx(Vu,{className:"z-[80]"})]}):i?o.jsx(t3,{value:de,children:o.jsxs("div",{className:"min-h-screen bg-background font-sans text-foreground transition-colors duration-300",children:[o.jsx("header",{className:"sticky top-0 z-50 w-full border-b border-border/40 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60",children:o.jsxs("div",{className:"max-w-7xl mx-auto flex h-16 items-center justify-between px-4 sm:px-8",children:[o.jsxs("div",{className:"flex items-center gap-4",children:[o.jsxs("button",{onClick:()=>v("dashboard"),className:"text-xl font-bold flex items-center gap-2 hover:opacity-80 transition-opacity",children:[o.jsx(fy,{className:"w-8 h-8"}),o.jsx("span",{className:"hidden sm:inline",children:r("app.name")}),o.jsx("span",{className:"sm:hidden",children:"Email AI"})]}),o.jsxs("div",{className:me("flex items-center gap-1.5 px-2 h-6 rounded-full text-[10px] font-bold border transition-colors",t?"bg-emerald-500/10 text-emerald-600 border-emerald-500/20 dark:text-emerald-400":"bg-yellow-500/10 text-yellow-600 border-yellow-500/20 dark:text-yellow-400"),children:[o.jsxs("div",{className:"relative flex items-center justify-center",children:[t&&o.jsx("span",{className:"absolute inline-flex h-3 w-3 rounded-full bg-emerald-500/40 animate-ping"}),o.jsx("div",{className:me("relative w-2 h-2 rounded-full",t?"bg-emerald-500":"bg-yellow-500")})]}),o.jsx("span",{className:"hidden xs:inline leading-none",children:r(t?"app.statusLive":"app.statusOffline")})]})]}),o.jsxs("div",{className:"flex gap-4 items-center",children:[o.jsxs("nav",{className:"flex items-center gap-1 bg-secondary/50 p-1 rounded-lg",children:[o.jsxs(Z,{variant:b==="dashboard"?"secondary":"ghost",size:"sm",onClick:()=>v("dashboard"),className:"gap-2",children:[o.jsx(EA,{className:"w-4 h-4"}),o.jsx("span",{className:"hidden sm:inline",children:r("nav.dashboard")})]}),o.jsxs(Z,{variant:b==="drafts"?"secondary":"ghost",size:"sm",onClick:()=>v("drafts"),className:"gap-2",children:[o.jsx(nA,{className:"w-4 h-4"}),o.jsx("span",{className:"hidden sm:inline",children:r("nav.drafts")||"Drafts"})]}),o.jsxs(Z,{variant:b==="autopilot"?"secondary":"ghost",size:"sm",onClick:()=>v("autopilot"),className:"gap-2",children:[o.jsx(qu,{className:"w-4 h-4"}),o.jsx("span",{className:"hidden sm:inline",children:r("nav.autopilot")})]}),o.jsxs(Z,{variant:b==="analytics"?"secondary":"ghost",size:"sm",onClick:()=>v("analytics"),className:"gap-2",children:[o.jsx(gg,{className:"w-4 h-4"}),o.jsx("span",{className:"hidden sm:inline",children:r("nav.analytics")})]}),o.jsxs(Z,{variant:b==="config"?"secondary":"ghost",size:"sm",onClick:()=>v("config"),className:"gap-2",children:[o.jsx(Al,{className:"w-4 h-4"}),o.jsx("span",{className:"hidden sm:inline",children:r("nav.configuration")})]})]}),o.jsx("div",{className:"h-6 w-px bg-border/50 mx-2 hidden sm:block"}),o.jsx(ly,{}),o.jsx(Tj,{}),o.jsx(Z,{variant:b==="account"?"secondary":"ghost",size:"sm",onClick:()=>v("account"),className:"text-muted-foreground hover:text-foreground p-0 w-8 h-8 rounded-full overflow-hidden border",title:r("nav.accountSettings"),children:e.profile?.avatar_url?o.jsx("img",{src:e.profile.avatar_url,alt:"Profile",className:"w-full h-full object-cover"}):o.jsx(FC,{className:"w-5 h-5"})})]})]})}),o.jsxs("main",{className:"max-w-7xl mx-auto p-4 sm:p-8 mt-4 mb-12",children:[b==="dashboard"&&o.jsx(mU,{}),b==="drafts"&&o.jsx(bU,{onPreview:fe}),b==="autopilot"&&o.jsx(pq,{}),b==="config"&&o.jsx(Q7,{}),b==="analytics"&&o.jsx(Iq,{}),b==="account"&&o.jsx(cq,{})]}),o.jsx("footer",{className:"max-w-7xl mx-auto px-4 sm:px-8 pb-8 text-center sm:text-left",children:o.jsxs("p",{className:"text-[10px] font-medium text-muted-foreground/40 uppercase tracking-[0.2em]",children:["Email Automator ",o.jsx("span",{className:"mx-1",children:"•"})," v","2.23.3"]})}),e.error&&o.jsx("div",{className:"fixed bottom-20 left-4 right-4 sm:left-auto sm:right-4 sm:max-w-sm z-50",children:o.jsx("div",{className:"bg-destructive/10 border border-destructive/20 text-destructive p-4 rounded-lg",children:o.jsx("p",{className:"text-sm",children:e.error})})}),j&&A&&!M&&o.jsx(xq,{status:j,onDismiss:()=>T(!1),onLearnMore:$}),P&&D&&o.jsx(Rq,{versionInfo:P,onDismiss:()=>Q(!1)}),j&&o.jsx(vq,{open:O,onOpenChange:L,status:j}),G&&o.jsx(W7,{email:G,onClose:()=>fe(null),onSend:async C=>{fe(null)},onDismiss:async C=>{(await Oe.dismissDraft(C)).data?.success?(le.success(r("drafts.dismissSuccess")||"Draft dismissed"),fe(null)):le.error(r("drafts.dismissError")||"Failed to dismiss draft")}}),o.jsx(Oq,{}),o.jsx(Vu,{}),o.jsx(is,{open:se,onOpenChange:C=>{C||V(!0),ae(C)},children:o.jsxs(os,{className:"max-w-3xl border-none bg-transparent shadow-none p-0 sm:max-w-3xl",children:[o.jsx(z2,{children:o.jsx(bs,{children:"Persona Setup Wizard"})}),o.jsx(R2,{onComplete:()=>{ae(!1),n.fetchSettings()},onClose:()=>{ae(!1),V(!0)}})]})})]})}):o.jsxs(o.Fragment,{children:[o.jsx(yq,{onSuccess:()=>n.fetchProfile(),onConfigure:()=>m(!0),isInitialized:p}),o.jsx(Vu,{className:"z-[80]"})]})}function Lq({runId:e,accountEmail:t,isOpen:n,onOpenChange:r}){const{t:i}=tt(),[l,u]=w.useState([]),[d,h]=w.useState(!1);w.useEffect(()=>{n&&e&&m()},[n,e]);const m=async()=>{if(e){h(!0);try{const g=await Oe.getRunEvents(e);g.data&&u(g.data.events)}catch(g){console.error("Failed to fetch run trace:",g)}finally{h(!1)}}},p=g=>{switch(g){case"analysis":return o.jsx(Jr,{className:"w-4 h-4 text-purple-500"});case"action":return o.jsx(ao,{className:"w-4 h-4 text-emerald-500"});case"error":return o.jsx(ls,{className:"w-4 h-4 text-red-500"});default:return o.jsx(ro,{className:"w-4 h-4 text-blue-500"})}};return o.jsx(is,{open:n,onOpenChange:r,children:o.jsxs(os,{className:"sm:max-w-2xl max-h-[85vh] flex flex-col p-0 overflow-hidden",children:[o.jsxs(dr,{className:"p-6 border-b",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(yd,{className:"w-5 h-5 text-primary"}),o.jsx(bs,{children:i("trace.runTrace")})]}),o.jsx(fr,{children:t?i("trace.fullLogFor").replace("{email}",t):i("trace.historicalLog")})]}),o.jsx("div",{className:"flex-1 overflow-y-auto p-6 space-y-6 custom-scrollbar bg-secondary/5",children:d?o.jsx("div",{className:"py-20 flex justify-center",children:o.jsx(sd,{text:i("trace.loadingTrace")})}):l.length===0?o.jsx("div",{className:"py-20 text-center text-muted-foreground italic font-mono text-sm",children:i("trace.noTraceEvents")}):l.map((g,b)=>o.jsxs("div",{className:"relative pl-8",children:[b!==l.length-1&&o.jsx("div",{className:"absolute left-[15px] top-8 bottom-[-24px] w-px bg-border"}),o.jsx("div",{className:"absolute left-0 top-0 w-8 h-8 rounded-full border bg-background flex items-center justify-center z-10 shadow-sm",children:p(g.event_type)}),o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"flex flex-col",children:[o.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider text-foreground/70",children:g.agent_state}),g.emails?.subject&&o.jsxs("span",{className:"text-[10px] text-primary font-medium truncate max-w-[300px]",children:["Re: ",g.emails.subject]})]}),o.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:[o.jsx(ea,{className:"w-3 h-3"}),new Date(g.created_at).toLocaleTimeString()]})]}),o.jsxs("div",{className:"bg-card border rounded-lg p-4 shadow-sm",children:[g.event_type==="info"&&o.jsx("p",{className:"text-sm text-foreground/90",children:g.details?.message}),g.event_type==="analysis"&&o.jsxs("div",{className:"space-y-2",children:[o.jsxs("p",{className:"text-xs text-foreground italic leading-relaxed",children:['"',g.details?.summary,'"']}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx("span",{className:"text-[9px] bg-secondary px-1.5 py-0.5 rounded font-bold uppercase",children:g.details?.category}),g.details?.suggested_actions?.map(v=>o.jsx("span",{className:"text-[9px] bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 px-1.5 py-0.5 rounded border border-emerald-500/20 font-bold uppercase",children:v},v))]}),g.details?.usage&&o.jsxs("div",{className:"flex gap-3 pt-1.5 mt-1 border-t border-border/50 text-[9px] text-muted-foreground",children:[o.jsxs("span",{children:["In: ",o.jsx("b",{children:g.details.usage.prompt_tokens})]}),o.jsxs("span",{children:["Out: ",o.jsx("b",{children:g.details.usage.completion_tokens})]}),o.jsxs("span",{children:["Total: ",o.jsx("span",{className:"text-primary font-bold",children:g.details.usage.total_tokens})]})]})]}),g.event_type==="action"&&o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("p",{className:"text-sm font-bold text-emerald-600 dark:text-emerald-400 capitalize",children:[i("dashboard.done")," ",g.details?.action]}),o.jsx(yg,{className:"w-4 h-4 text-emerald-500"})]}),g.event_type==="error"&&o.jsx("p",{className:"text-sm text-red-600 dark:text-red-400 font-bold",children:g.details?.error})]})]})]},g.id))})]})})}function Iq(){const{state:e,actions:t}=Tn(),{t:n}=tt(),[r,i]=w.useState(null),[l,u]=w.useState(void 0),[d,h]=w.useState(!1),[m,p]=w.useState("overview");if(w.useEffect(()=>{t.fetchStats()},[]),!e.stats)return o.jsx(sd,{text:n("common.loading")});const g=(v,S)=>{i(v),u(S),h(!0)},{stats:b}=e;return o.jsxs("div",{className:"space-y-8 animate-in fade-in duration-500",children:[o.jsxs("div",{className:"flex flex-col md:flex-row md:items-center justify-between gap-4",children:[o.jsxs("h2",{className:"text-2xl font-bold flex items-center gap-2",children:[o.jsx(gg,{className:"w-6 h-6 text-primary"}),n("analytics.title")]}),o.jsxs("div",{className:"flex p-1 bg-muted rounded-lg w-full md:w-auto",children:[o.jsx("button",{onClick:()=>p("overview"),className:`flex-1 md:w-32 px-3 py-1.5 text-sm font-medium rounded-md transition-all ${m==="overview"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:bg-background/50"}`,children:"Overview"}),o.jsxs("button",{onClick:()=>p("learning"),className:`flex-1 md:w-32 px-3 py-1.5 text-sm font-medium rounded-md transition-all flex items-center justify-center gap-2 ${m==="learning"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:bg-background/50"}`,children:[o.jsx(Jr,{className:"w-3.5 h-3.5"}),"Learning"]})]})]}),m==="learning"?o.jsx(Dq,{}):o.jsxs("div",{className:"space-y-8",children:[o.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[o.jsx(Fu,{title:n("analytics.totalEmails"),value:b.totalEmails,color:"primary"}),o.jsx(Fu,{title:n("analytics.spamCaught"),value:b.categoryCounts.spam||0,color:"destructive"}),o.jsx(Fu,{title:n("analytics.actionsTaken"),value:Object.values(b.actionCounts).reduce((v,S)=>v+S,0)-(b.actionCounts.none||0),color:"emerald"}),o.jsx(Fu,{title:n("analytics.accounts"),value:b.accountCount,color:"blue"})]}),o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-8",children:[o.jsxs("div",{className:"bg-card border rounded-xl p-6",children:[o.jsx("h3",{className:"font-semibold mb-4",children:n("analytics.categories")}),o.jsx("div",{className:"space-y-3",children:Object.entries(b.categoryCounts).map(([v,S])=>o.jsx("div",{className:"flex items-center gap-3",children:o.jsxs("div",{className:"flex-1",children:[o.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[o.jsx("span",{className:"capitalize",children:v}),o.jsx("span",{className:"text-muted-foreground",children:S})]}),o.jsx("div",{className:"h-2 bg-secondary rounded-full overflow-hidden",children:o.jsx("div",{className:"h-full bg-primary rounded-full transition-all",style:{width:`${S/b.totalEmails*100}%`}})})]})},v))})]}),o.jsxs("div",{className:"bg-card border rounded-xl p-6",children:[o.jsx("h3",{className:"font-semibold mb-4",children:n("analytics.actionsTaken")}),o.jsx("div",{className:"space-y-3",children:Object.entries(b.actionCounts).map(([v,S])=>o.jsxs("div",{className:"flex items-center justify-between py-2 border-b last:border-0",children:[o.jsx("span",{className:"capitalize",children:v}),o.jsx("span",{className:"font-medium",children:S})]},v))})]})]}),o.jsxs("div",{className:"bg-card border rounded-xl p-6",children:[o.jsx("h3",{className:"font-semibold mb-4",children:n("analytics.recentActivity")}),b.recentSyncs.length===0?o.jsx("p",{className:"text-muted-foreground text-sm",children:n("analytics.noActivity")}):o.jsx("div",{className:"space-y-3",children:b.recentSyncs.map(v=>{const S=v.completed_at?Math.round((new Date(v.completed_at).getTime()-new Date(v.started_at).getTime())/1e3):null;return o.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between p-3 border rounded-lg hover:bg-secondary/30 transition-colors gap-3 cursor-pointer group",onClick:()=>g(v.id,v.email_accounts?.email_address),children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:me("w-2.5 h-2.5 rounded-full",v.status==="success"?"bg-emerald-500":v.status==="failed"?"bg-destructive":"bg-yellow-500 shadow-[0_0_8px_rgba(234,179,8,0.5)] animate-pulse")}),o.jsxs("div",{className:"flex flex-col",children:[o.jsx("span",{className:"text-sm font-medium group-hover:text-primary transition-colors",children:v.email_accounts?.email_address||n("common.systemSync")}),o.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:[o.jsx(ea,{className:"w-3 h-3"}),new Date(v.started_at).toLocaleString(),S!==null&&o.jsxs("span",{className:"ml-2 px-1.5 py-0.5 bg-secondary rounded-full",children:[S,"s"]})]})]})]}),o.jsx("div",{className:"flex items-center gap-4 text-xs",children:o.jsxs("div",{className:"flex flex-col items-end",children:[o.jsx("span",{className:"font-bold text-primary",children:n("analytics.emails").replace("{count}",v.emails_processed.toString())}),o.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[n("analytics.deleted").replace("{count}",v.emails_deleted.toString()),", ",n("analytics.drafted").replace("{count}",v.emails_drafted.toString())]})]})})]},v.id)})})]})]}),o.jsx(Lq,{runId:r,accountEmail:l,isOpen:d,onOpenChange:h})]})}function Fu({title:e,value:t,color:n}){const r={primary:"bg-primary/10 text-primary",destructive:"bg-destructive/10 text-destructive",emerald:"bg-emerald-500/10 text-emerald-600 dark:text-emerald-400",blue:"bg-blue-500/10 text-blue-600 dark:text-blue-400"};return o.jsxs("div",{className:"bg-card border rounded-xl p-6",children:[o.jsx("p",{className:"text-sm text-muted-foreground mb-1",children:e}),o.jsx("p",{className:`text-3xl font-bold ${r[n]||""}`,children:t})]})}function Uq(){return o.jsx($L,{children:o.jsx(iO,{defaultTheme:"system",storageKey:"email-automator-theme",children:o.jsx(s3,{children:o.jsx(n3,{children:o.jsx(HL,{children:o.jsx(GL,{children:o.jsxs(Z5,{children:[o.jsx(zq,{}),o.jsx(W5,{})]})})})})})})})}aC.createRoot(document.getElementById("root")).render(o.jsx(QS.StrictMode,{children:o.jsx(Uq,{})}));
|
package/dist/index.html
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
|
6
6
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
7
7
|
<title>Email Automator</title>
|
|
8
|
-
<script type="module" crossorigin src="/assets/index-
|
|
8
|
+
<script type="module" crossorigin src="/assets/index-_VUAvNIp.js"></script>
|
|
9
9
|
<link rel="stylesheet" crossorigin href="/assets/index-D4JdJS8Y.css">
|
|
10
10
|
</head>
|
|
11
11
|
<body>
|
package/package.json
CHANGED